import child_process from "child_process"; import config from "config"; import crypto from "crypto"; import fs from "fs"; import {nanoid} from "nanoid"; import path from "path"; import requireFromString from "require-from-string"; import {compile, preprocess} from "svelte/compiler"; import {CssResult} from "svelte/types/compiler/interfaces"; import {sveltePreprocess} from "svelte-preprocess/dist/autoProcess.js"; import {logger} from "../Logger.js"; import {afs} from "../Utils.js"; import FileCache from "../utils/FileCache.js"; import ViewEngine from "./ViewEngine.js"; const BACKEND_CODE_PREFIX = 'locals.'; const BACKEND_CODE_PREFIX_TEMPORARY_HOLDER = '$$locals$$'; const COMPILED_SVELTE_EXTENSION = '.precompiled'; export default class SvelteViewEngine extends ViewEngine { public static getPreCompileSeparator(canonicalViewName: string): string { return '\n---' + crypto.createHash('sha1') .update(path.basename(path.resolve(canonicalViewName))) .digest('base64') + '---\n'; } private readonly fileCache: FileCache = new FileCache(); private readonly dependencyCache: Record> = {}; private readonly backendCallsCache: Record = {}; private rollup?: child_process.ChildProcess; /** * @param buildDir A temporary directory that will contain any non-final or final non-public asset. * @param publicDir The output directory that should contain all final and public assets. * @param devWatchedViewDir see {@link ViewEngine}. * @param additionalViewPaths see {@link ViewEngine}. */ public constructor( private readonly buildDir: string, private readonly publicDir: string, devWatchedViewDir: string, ...additionalViewPaths: string[] ) { super(devWatchedViewDir, ...additionalViewPaths); if (!fs.existsSync(this.buildDir)) { fs.mkdirSync(this.buildDir, {recursive: true}); } } public getExtension(): string { return 'svelte'; } public async render( file: string, locals: Record, ): Promise { const canonicalViewName = this.toCanonicalName(file); // View const actualFile = path.join(this.buildDir, canonicalViewName + COMPILED_SVELTE_EXTENSION); const view = await this.fileCache.get(actualFile, !config.get('view.cache')); // Root template const templateFile = await this.resolveFileFromCanonicalName('layouts/svelte_layout.html'); const rawOutput = await this.fileCache.get(templateFile, !config.get('view.cache')); // Pre-compiled parts const [ backendCalls, head, html, css, ] = view.split(SvelteViewEngine.getPreCompileSeparator(canonicalViewName)); const localMap: Record = {}; backendCalls.split('\n').forEach(code => { const key = code.substring(1, code.indexOf(',') >= 0 ? code.indexOf(',') - 1 : code.length - 1); if (code.indexOf('`[') >= 0) { const args = code.substring(code.indexOf('`[') + 2, code.length - 2) .split(/, *?/) .map(arg => { if (arg.startsWith("'")) return '"' + arg.substring(1, arg.length - 1) + '"'; return arg; }) .map(arg => Function(`"use strict";const locals = arguments[0];return (${arg});`)(locals)); // Uses named parameter locals const f = locals[key]; if (typeof f !== 'function') throw new Error(key + ' is not a function.'); localMap[`'${key}', \`[${code.substring(code.indexOf('`[') + 2, code.length - 2)}]\``] = f.call(locals, ...args); } else { localMap[`'${key}'`] = locals[key]; } }); const actualLocals = JSON.stringify(localMap, (key, value) => { return typeof value === 'function' ? value.toString() : value; }); // Replaces const replaceMap: Record = { canonicalViewName: canonicalViewName, locals: actualLocals, head: head, html: html, css: css, }; return rawOutput.replace( new RegExp(Object.keys(replaceMap).map(str => `%${str}%`).join('|'), 'g'), (substring) => replaceMap[substring.slice(1, substring.length - 1)], ); } public async stop(): Promise { await super.stop(); await this.stopRollup(); } public async preCompile(canonicalName: string, alsoCompileDependents: boolean): Promise { const file = await this.resolveFileFromCanonicalName(canonicalName); const intermediateFile = path.join(this.buildDir, canonicalName); logger.info(canonicalName + ' > ', 'Pre-compiling', file, '->', intermediateFile); const source = await this.fileCache.get(file, !config.get('view.cache')); const allBackendCalls: string[] = []; for (const dependency of this.resolveDependencies(source, canonicalName)) { allBackendCalls.push(...(await this.replaceBackendCalls(dependency)).backendCalls); } const {replacedBackendCall, backendCalls} = await this.replaceBackendCalls(canonicalName, source); allBackendCalls.push(...backendCalls); // Server Side Render (initial HTML and CSS, no-js) const ssr = await this.compileSsr(canonicalName, intermediateFile, replacedBackendCall); const separator = SvelteViewEngine.getPreCompileSeparator(canonicalName); const finalCode = [ [...new Set(allBackendCalls).values()].join('\n'), ssr.head, ssr.html, ssr.css.code, ].join(separator); const swafViewFile = path.join(this.buildDir, canonicalName + COMPILED_SVELTE_EXTENSION); await afs.mkdir(path.dirname(swafViewFile), {recursive: true}); await afs.writeFile(swafViewFile, finalCode); if (alsoCompileDependents && Object.keys(this.dependencyCache).indexOf(canonicalName) >= 0) { logger.info(canonicalName + ' > ', 'Compiling dependents...'); for (const dependent of [...this.dependencyCache[canonicalName]]) { await this.preCompile(dependent, true); } } } private resolveDependencies(source: string, canonicalViewName: string): string[] { const dependencies: string[] = []; for (const match of source.matchAll(/import .+ from ['"](.+?\.svelte)['"];/gm)) { dependencies.push(path.join(path.dirname(canonicalViewName), match[1])); } // Clear existing links from cache for (const dependency of Object.keys(this.dependencyCache)) { this.dependencyCache[dependency].delete(canonicalViewName); } // Add new links to cache for (const dependency of dependencies) { if (Object.keys(this.dependencyCache).indexOf(dependency) < 0) { this.dependencyCache[dependency] = new Set(); } this.dependencyCache[dependency].add(canonicalViewName); } return dependencies; } private async replaceBackendCalls(canonicalViewName: string, code?: string): Promise<{ replacedBackendCall: string, backendCalls: string[], }> { // Cache if (Object.keys(this.backendCallsCache).indexOf(canonicalViewName) >= 0) { return this.backendCallsCache[canonicalViewName]; } // mkdir output file dir const outputFile = path.join(this.buildDir, canonicalViewName); await afs.mkdir(path.dirname(outputFile), {recursive: true}); // Read source file if code was not already provided if (!code) { const file = await this.resolveFileFromCanonicalName(canonicalViewName); code = await this.fileCache.get(file, !config.get('view.cache')); } // Skip replace if there is no swaf export if (!code.match(/export[ \n]+let[ \n]+locals[ \n]*=[ \n]*{[ \n]*}/)) { const generated = { replacedBackendCall: code, backendCalls: [], }; await afs.writeFile(outputFile, generated.replacedBackendCall); this.backendCallsCache[canonicalViewName] = generated; return generated; } let output = code; const backendCalls = new Set(); let index = 0; while ((index = output.indexOf(BACKEND_CODE_PREFIX, index + 1)) >= 0) { // Escaping if (index > 0 && output[index - 1] === '\\') { const isEscapingEscaped: boolean = index > 1 && output[index - 2] === '\\'; output = output.substring(0, index - 1 - (isEscapingEscaped ? 1 : 0)) + output.substring(index, output.length); continue; } const startIndex = index + BACKEND_CODE_PREFIX.length; let endIndex = startIndex; let struct = 0; while (endIndex < output.length) { if (['(', '[', '{'].indexOf(output[endIndex]) >= 0) struct++; if ([')', ']', '}'].indexOf(output[endIndex]) >= 0) { struct--; if (struct <= 0) { if (struct === 0) endIndex++; break; } } if ([' ', '\n', '<'].indexOf(output[endIndex]) >= 0 && struct === 0) break; endIndex++; } let backendCall = output.substring(startIndex, endIndex); if (backendCall.match(/([^()]+)\((.+?)\)/)) { backendCall = backendCall.replace(/([^()]+)\((.+?)\)/, "'$1', `[$2]`"); } else { backendCall = backendCall.replace(/([^()]+)/, "'$1'"); } backendCalls.add(backendCall); output = output.substring(0, index) + 'locals(' + backendCall.split(BACKEND_CODE_PREFIX).join(BACKEND_CODE_PREFIX_TEMPORARY_HOLDER) + ')' + output.substring(endIndex, output.length); } output = output.split(BACKEND_CODE_PREFIX_TEMPORARY_HOLDER).join(BACKEND_CODE_PREFIX); const generated = { replacedBackendCall: output, backendCalls: [...backendCalls], }; await afs.writeFile(outputFile, generated.replacedBackendCall); this.backendCallsCache[canonicalViewName] = generated; return generated; } public async afterPreCompile(watch: boolean): Promise { await this.bundle(watch, ...Object.keys(this.backendCallsCache)); } public async onNewFile(): Promise { await this.stopRollup(); } public async onFileChange(file: string): Promise { delete this.backendCallsCache[this.toCanonicalName(file)]; } public async onFileRemove(file: string): Promise { const canonicalName = this.toCanonicalName(file); delete this.backendCallsCache[canonicalName]; delete this.dependencyCache[canonicalName]; Object.values(this.dependencyCache).forEach(set => set.delete(canonicalName)); await this.stopRollup(); await this.afterPreCompile(true); } private async compileSsr(canonicalName: string, file: string, code: string): Promise<{ head: string, css: CssResult, html: string, }> { // Svelte preprocess logger.info(canonicalName + ' > ', 'Preprocessing svelte', file); const preprocessed = await preprocess( code, sveltePreprocess({ typescript: { tsconfigFile: 'tsconfig.views.json', }, }), { filename: file, }, ); // Svelte compile logger.info(canonicalName + ' > ', 'Compiling svelte ssr', file); const svelteSsr = compile(preprocessed.code, { dev: config.get('view.dev'), generate: 'ssr', format: 'cjs', cssOutputFilename: file + '.css', }); const globals = ViewEngine.getGlobals(); const localsFunction = (key: string, rawArgs?: string) => { if (!rawArgs) return globals[key]; const args = Function(`"use strict";const locals = Object.assign(arguments[0], arguments[1]);return (${rawArgs});`)(localsFunction, globals) as string[]; const f = globals[key]; if (typeof f !== 'function') throw new Error(key + ' is not a function.'); return f.call(globals, ...args); }; return requireFromString(svelteSsr.js.code, file + nanoid()).default.render({ locals: localsFunction, }); } private async bundle(watch: boolean, ...canonicalViewNames: string[]): Promise { logger.info('Bundling...'); // Prepare output dir for (const name of canonicalViewNames) { await afs.mkdir(path.dirname(path.join(this.publicDir, 'js', name)), {recursive: true}); } const production = !config.get('view.dev'); const input = canonicalViewNames.map(name => path.join(this.buildDir, name)); if (!this.rollup) { const args = [ 'rollup', '-c', 'rollup.config.js', '--environment', `ENV:${production ? 'production' : 'dev'},BUILD_DIR:${this.buildDir},PUBLIC_DIR:${this.publicDir},INPUT:${input.join(':')}`, ]; if (watch) args.push('--watch'); this.rollup = child_process.spawn('yarn', args, {stdio: [process.stdin, process.stdout, process.stderr]}); logger.info('Rollup started'); this.rollup.once('exit', () => { logger.info('Rollup stopped'); this.rollup = undefined; }); } } private async stopRollup(): Promise { if (this.rollup) { logger.info(`Stopping rollup (${this.rollup.pid})...`); await new Promise((resolve, reject) => { if (!this.rollup) return resolve(); this.rollup.once('exit', () => { resolve(); }); if (!this.rollup.kill("SIGTERM")) reject('Could not stop rollup.'); }); } } }