UNPKG

@fastly/js-compute

Version:

JavaScript SDK and CLI for building JavaScript applications on [Fastly Compute](https://www.fastly.com/products/edge-compute/serverless).

73 lines (72 loc) 2.96 kB
import { copyFile, readFile, writeFile } from 'node:fs/promises'; import { basename, resolve } from 'node:path'; import MagicString from 'magic-string'; import { pipeline } from './pipeline.js'; export class CompilerContext { inFilepath; outFilepath; tmpDir; debugIntermediateFilesDir; sourceMaps; moduleMode; enableStackTraces; excludeSources; compilerPipelineSteps; constructor(input, tmpDir, debugIntermediateFilesDir, moduleMode, enableStackTraces, excludeSources) { this.inFilepath = input; this.outFilepath = ''; // This is filled in by the eventual steps of the compiler this.tmpDir = tmpDir; this.debugIntermediateFilesDir = debugIntermediateFilesDir; this.sourceMaps = []; this.moduleMode = moduleMode; this.enableStackTraces = enableStackTraces; this.excludeSources = excludeSources; this.compilerPipelineSteps = []; } addCompilerPipelineStep(step) { this.compilerPipelineSteps.push(step); } async applyCompilerPipeline() { await pipeline(this.compilerPipelineSteps.map((step) => async (args, index) => { await step.fn.call(step, args, index); return args; }), this, { beforeStep: (args, index) => { const step = this.compilerPipelineSteps[index]; args.outFilepath = resolve(this.tmpDir, step.outFilename); }, afterStep: (args) => { args.inFilepath = args.outFilepath; }, }); } async magicStringWriter(filename, fn) { const source = await readFile(this.inFilepath, { encoding: 'utf8' }); const magicString = new MagicString(source); await fn(magicString, source); await writeFile(this.outFilepath, magicString.toString()); if (this.enableStackTraces != null) { const map = magicString.generateMap({ source: basename(this.inFilepath), hires: true, includeContent: true, }); await writeFile(this.outFilepath + '.map', map.toString()); this.sourceMaps.push({ f: filename, s: this.outFilepath + '.map' }); } } async maybeWriteDebugIntermediateFile(outFilename) { if (this.debugIntermediateFilesDir != null) { await copyFile(this.outFilepath, resolve(this.debugIntermediateFilesDir, outFilename)); } } async maybeWriteDebugIntermediateSourceMapFile(outFilename) { if (this.enableStackTraces && this.debugIntermediateFilesDir != null) { await copyFile(this.outFilepath + '.map', resolve(this.debugIntermediateFilesDir, outFilename)); } } async maybeWriteDebugIntermediateFiles(outFilename) { await this.maybeWriteDebugIntermediateFile(outFilename); await this.maybeWriteDebugIntermediateSourceMapFile(outFilename + '.map'); } }