import * as fs from 'fs'; import * as path from 'path'; import glob from 'tiny-glob/sync.js'; import { posixify, stringify, write_if_changed } from './utils'; import { dev, locations } from '../config'; import { Page, PageComponent, ServerRoute, ManifestData } from '../interfaces'; export function create_main_manifests({ bundler, manifest_data, dev_port }: { bundler: string, manifest_data: ManifestData; dev_port?: number; }) { const manifest_dir = '__sapper__'; if (!fs.existsSync(manifest_dir)) fs.mkdirSync(manifest_dir); const path_to_routes = path.relative(manifest_dir, locations.routes()); const client_manifest = generate_client(manifest_data, path_to_routes, bundler, dev_port); const server_manifest = generate_server(manifest_data, path_to_routes); write_if_changed( `${manifest_dir}/default-layout.html`, `` ); write_if_changed(`${manifest_dir}/client.js`, client_manifest); write_if_changed(`${manifest_dir}/server.js`, server_manifest); } export function create_serviceworker_manifest({ manifest_data, client_files }: { manifest_data: ManifestData; client_files: string[]; }) { let files; // TODO remove in a future version if (fs.existsSync(locations.static())) { files = glob('**', { cwd: locations.static(), filesOnly: true }); } else { if (fs.existsSync('assets')) { throw new Error(`As of Sapper 0.21, the assets/ directory should become static/`); } files = []; } let code = ` // This file is generated by Sapper — do not edit it! export const timestamp = ${Date.now()}; export const files = [\n\t${files.map((x: string) => stringify(x)).join(',\n\t')}\n]; export { files as assets }; // legacy export const shell = [\n\t${client_files.map((x: string) => stringify(x)).join(',\n\t')}\n]; export const routes = [\n\t${manifest_data.pages.map((r: Page) => `{ pattern: ${r.pattern} }`).join(',\n\t')}\n]; `.replace(/^\t\t/gm, '').trim(); write_if_changed(`__sapper__/service-worker.js`, code); } function generate_client( manifest_data: ManifestData, path_to_routes: string, bundler: string, dev_port?: number ) { const template_file = path.resolve(__dirname, '../templates/dist/client.js'); const template = fs.readFileSync(template_file, 'utf-8'); const page_ids = new Set(manifest_data.pages.map(page => page.pattern.toString())); const server_routes_to_ignore = manifest_data.server_routes.filter(route => !page_ids.has(route.pattern.toString())); const component_indexes: Record = {}; const components = `[ ${manifest_data.components.map((component, i) => { const annotation = bundler === 'webpack' ? `/* webpackChunkName: "${component.name}" */ ` : ''; const source = get_file(path_to_routes, component); component_indexes[component.name] = i; return `{ js: () => import(${annotation}${stringify(source)}), css: "__SAPPER_CSS_PLACEHOLDER:${stringify(component.file, false)}__" }`; }).join(',\n\t\t')} ]`.replace(/^\t/gm, '').trim(); let needs_decode = false; let pages = `[ ${manifest_data.pages.map(page => `{ // ${page.parts[page.parts.length - 1].component.file} pattern: ${page.pattern}, parts: [ ${page.parts.map(part => { if (part === null) return 'null'; if (part.params.length > 0) { needs_decode = true; const props = part.params.map((param, i) => `${param}: d(match[${i + 1}])`); return `{ i: ${component_indexes[part.component.name]}, params: match => ({ ${props.join(', ')} }) }`; } return `{ i: ${component_indexes[part.component.name]} }`; }).join(',\n\t\t\t\t')} ] }`).join(',\n\n\t\t')} ]`.replace(/^\t/gm, '').trim(); if (needs_decode) { pages = `(d => ${pages})(decodeURIComponent)` } let footer = ''; if (dev()) { const sapper_dev_client = posixify( path.resolve(__dirname, '../sapper-dev-client.js') ); footer = ` import(${stringify(sapper_dev_client)}).then(client => { client.connect(${dev_port}); });`.replace(/^\t{3}/gm, ''); } return `// This file is generated by Sapper — do not edit it!\n` + template .replace('__ROOT__', stringify(get_file(path_to_routes, manifest_data.root), false)) .replace('__ERROR__', stringify(posixify(`${path_to_routes}/_error.html`), false)) .replace('__IGNORE__', `[${server_routes_to_ignore.map(route => route.pattern).join(', ')}]`) .replace('__COMPONENTS__', components) .replace('__PAGES__', pages) + footer; } function generate_server( manifest_data: ManifestData, path_to_routes: string ) { const template_file = path.resolve(__dirname, '../templates/dist/server.js'); const template = fs.readFileSync(template_file, 'utf-8'); const imports = [].concat( manifest_data.server_routes.map(route => `import * as __${route.name} from ${stringify(posixify(`${path_to_routes}/${route.file}`))};`), manifest_data.components.map(component => `import __${component.name} from ${stringify(get_file(path_to_routes, component))};`), `import root from ${stringify(get_file(path_to_routes, manifest_data.root))};`, `import error from ${stringify(posixify(`${path_to_routes}/_error.html`))};` ); let code = ` ${imports.join('\n')} const d = decodeURIComponent; export const manifest = { server_routes: [ ${manifest_data.server_routes.map(route => `{ // ${route.file} pattern: ${route.pattern}, handlers: __${route.name}, params: ${route.params.length > 0 ? `match => ({ ${route.params.map((param, i) => `${param}: d(match[${i + 1}])`).join(', ')} })` : `() => ({})`} }`).join(',\n\n\t\t\t\t')} ], pages: [ ${manifest_data.pages.map(page => `{ // ${page.parts[page.parts.length - 1].component.file} pattern: ${page.pattern}, parts: [ ${page.parts.map(part => { if (part === null) return 'null'; const props = [ `name: "${part.component.name}"`, `file: ${stringify(part.component.file)}`, `component: __${part.component.name}` ]; if (part.params.length > 0) { const params = part.params.map((param, i) => `${param}: d(match[${i + 1}])`); props.push(`params: match => ({ ${params.join(', ')} })`); } return `{ ${props.join(', ')} }`; }).join(',\n\t\t\t\t\t\t')} ] }`).join(',\n\n\t\t\t\t')} ], root, error };`.replace(/^\t\t/gm, '').trim(); return `// This file is generated by Sapper — do not edit it!\n` + template .replace('__BUILD__DIR__', JSON.stringify(locations.dest())) .replace('__SRC__DIR__', JSON.stringify(locations.src())) .replace('__DEV__', dev() ? 'true' : 'false') .replace(/const manifest = __MANIFEST__;/, code); } function get_file(path_to_routes: string, component: PageComponent) { if (component.default) { return `./default-layout.html`; } return posixify(`${path_to_routes}/${component.file}`); }