diff --git a/lib/build-esbuild/errors.js b/lib/build-esbuild/errors.js new file mode 100644 index 00000000..e748d568 --- /dev/null +++ b/lib/build-esbuild/errors.js @@ -0,0 +1,48 @@ +/** + * @import esbuild from 'esbuild' + */ + +/** + * Convert an esbuild diagnostic into plain data that survives error inspection, + * structured logging, and serialization across process boundaries. + * + * @param {esbuild.Message} message + */ +export function serializeEsbuildMessage (message) { + return { + id: message.id, + pluginName: message.pluginName, + text: message.text, + location: message.location ? { ...message.location } : null, + notes: message.notes.map(note => ({ + text: note.text, + location: note.location ? { ...note.location } : null, + })), + detail: message.detail instanceof Error + ? { name: message.detail.name, message: message.detail.message, stack: message.detail.stack } + : message.detail == null ? message.detail : String(message.detail), + } +} + +/** + * Materialize esbuild's accessor-backed errors and warnings as enumerable arrays. + * Non-esbuild errors are returned unchanged. + * + * @param {unknown} value + * @returns {Error} + */ +export function serializeEsbuildError (value) { + if (!(value instanceof Error)) return new Error(String(value)) + + const failure = /** @type {Error & { errors?: esbuild.Message[], warnings?: esbuild.Message[] }} */ (value) + if (!Array.isArray(failure.errors) && !Array.isArray(failure.warnings)) return value + + const serialized = new Error(value.message) + serialized.name = value.name + if (value.stack) serialized.stack = value.stack + Object.assign(serialized, { + errors: (failure.errors ?? []).map(serializeEsbuildMessage), + warnings: (failure.warnings ?? []).map(serializeEsbuildMessage), + }) + return serialized +} diff --git a/lib/build-esbuild/index.js b/lib/build-esbuild/index.js index 9803fe8c..5edaea72 100644 --- a/lib/build-esbuild/index.js +++ b/lib/build-esbuild/index.js @@ -1,632 +1,54 @@ /** - * @import { BuildStep, SiteData, DomStackOpts } from '../builder.js' - * @import { DomstackManifestKind, DomstackManifestRecord } from '../domstack-manifest/index.js' - * @import { Logger as PinoLogger } from 'pino' + * @import { BuildStep, SiteData } from '../builder.js' + * @import { + * BundleAsset as MetafileBundleAsset, + * BundleAssetAs as MetafileBundleAssetAs, + * BundleAssetsMap as MetafileBundleAssetsMap, + * OutputMap as MetafileOutputMap, + * } from './metafile.js' + * @import { + * EsbuildBuildOptions as OptionsEsbuildBuildOptions, + * EsbuildFormat as OptionsEsbuildFormat, + * EsbuildLogLevel as OptionsEsbuildLogLevel, + * ServiceWorkerBuildDefines as OptionsServiceWorkerBuildDefines, + * } from './options.js' + * @import { DisposableBuildContext as WatchDisposableBuildContext } from './watch.js' */ -import { writeFile } from 'fs/promises' -import { Worker } from 'node:worker_threads' -import { join, relative, basename, resolve, extname } from 'path' import esbuild from 'esbuild' -import mime from 'mime-types' -import { globalBundleAssets, pageBundleAssets, layoutBundleAssets } from '../file-conventions.js' -import { resolveVars } from '../build-pages/vars/resolve-vars.js' -import { - createDomstackManifestRecord, - DEFAULT_DOMSTACK_MANIFEST_FILENAME, - isDomstackManifestEnabled, -} from '../domstack-manifest/index.js' -import { importFile } from '#helpers/import-file.js' -import { toPosix } from '../helpers/path.js' -import { createDomStackLogger } from '../logger.js' - -const __dirname = import.meta.dirname -const DOM_STACK_DEFAULTS_PREFIX = 'domstack-defaults' -const DEFAULT_STYLE_INPUT = resolve(__dirname, '../defaults/default.style.css') -const DEFAULT_CLIENT_INPUT = resolve(__dirname, '../defaults/default.client.js') -const SERVICE_WORKER_OUTPUT_RELNAME = 'service-worker.js' - -/** - * Preload destination derived from an emitted asset's MIME type. - * @typedef {'font' | 'image' | 'audio' | 'video'} BundleAssetAs - */ - -/** - * Metadata for a non-entry asset emitted by esbuild (such as a hashed font or - * file-loader asset referenced from a CSS or JS bundle). - * @typedef {object} BundleAsset - * @property {string} url - Public root-relative URL of the emitted asset (e.g. `"/inter-latin-400-XYZ.woff2"`). - * @property {string | null} source - Original unhashed input path (POSIX) reported by esbuild, or `null` if unavailable. - * @property {string} ext - Lowercase file extension including the leading dot (e.g. `".woff2"`). - * @property {string | null} type - MIME type derived from `ext` (e.g. `"font/woff2"`), or `null` if unknown. - * @property {BundleAssetAs | null} as - HTML `` destination when applicable, or `null`. - * @property {string} bundle - Public root-relative URL of the entry bundle that referenced this asset. - */ - -/** - * @typedef {esbuild.Format} EsbuildFormat - * @typedef {esbuild.LogLevel} EsbuildLogLevel - * @typedef {{[relpath: string]: string}} OutputMap - * @typedef {{ byEntry: Record, defaultAssets: BundleAsset[] }} BundleAssetsMap - * @typedef {esbuild.BuildOptions} EsbuildBuildOptions - * @typedef {{ dispose: () => Promise }} DisposableBuildContext - * @typedef {{ define?: Record, manifestVersion?: string }} ServiceWorkerBuildDefines +import { serializeEsbuildError } from './errors.js' +import { applyBuildOutputMap, writeMetafile } from './metafile.js' +import { createBrowserBuildOpts, createServiceWorkerBuildOpts } from './options.js' +import { createEsbuildOutputRecords } from './outputs.js' + +export { serializeEsbuildError } from './errors.js' +export { extractBundleAssets, extractOutputMap, syncSiteDataBundleAssets } from './metafile.js' +export { createEsbuildOutputRecords } from './outputs.js' +export { buildEsbuildWatch } from './watch.js' + +/** + * @typedef {MetafileBundleAssetAs} BundleAssetAs + * @typedef {MetafileBundleAsset} BundleAsset + * @typedef {MetafileOutputMap} OutputMap + * @typedef {MetafileBundleAssetsMap} BundleAssetsMap + * @typedef {OptionsEsbuildFormat} EsbuildFormat + * @typedef {OptionsEsbuildLogLevel} EsbuildLogLevel + * @typedef {OptionsEsbuildBuildOptions} EsbuildBuildOptions + * @typedef {WatchDisposableBuildContext} DisposableBuildContext + * @typedef {OptionsServiceWorkerBuildDefines} ServiceWorkerBuildDefines * @typedef {{ * buildResults?: esbuild.BuildResult, * buildOpts?: EsbuildBuildOptions, * outputMap?: OutputMap * }} EsbuildReport - + * * @typedef {BuildStep< - * 'esbuild', - * EsbuildReport + * 'esbuild', + * EsbuildReport * >} EsBuildStep - */ - -/** - * @typedef {Awaited>} EsBuildStepResults - */ - -/** - * Convert an esbuild diagnostic into plain data that survives error inspection, - * structured logging, and serialization across process boundaries. - * - * @param {esbuild.Message} message - */ -function serializeEsbuildMessage (message) { - return { - id: message.id, - pluginName: message.pluginName, - text: message.text, - location: message.location ? { ...message.location } : null, - notes: message.notes.map(note => ({ - text: note.text, - location: note.location ? { ...note.location } : null, - })), - detail: message.detail instanceof Error - ? { name: message.detail.name, message: message.detail.message, stack: message.detail.stack } - : message.detail == null ? message.detail : String(message.detail), - } -} - -/** - * Materialize esbuild's accessor-backed errors and warnings as enumerable arrays. - * Non-esbuild errors are returned unchanged. - * - * @param {unknown} value - * @returns {Error} - */ -export function serializeEsbuildError (value) { - if (!(value instanceof Error)) return new Error(String(value)) - - const failure = /** @type {Error & { errors?: esbuild.Message[], warnings?: esbuild.Message[] }} */ (value) - if (!Array.isArray(failure.errors) && !Array.isArray(failure.warnings)) return value - - const serialized = new Error(value.message) - serialized.name = value.name - if (value.stack) serialized.stack = value.stack - Object.assign(serialized, { - errors: (failure.errors ?? []).map(serializeEsbuildMessage), - warnings: (failure.warnings ?? []).map(serializeEsbuildMessage), - }) - return serialized -} - -/** - * Extract entry output paths, default bundle paths, and per-entry non-entry - * emitted assets from an esbuild metafile in a single pass. - * - * @param {esbuild.Metafile} metafile - * @param {string} src - * @param {string} dest - * @returns {{ - * outputMap: OutputMap, - * byEntry: Record, - * defaultClient: string | null, - * defaultStyle: string | null, - * defaultAssets: BundleAsset[], - * }} - */ -function extractBuildOutputs (metafile, src, dest) { - /** @type {OutputMap} */ - const outputMap = {} - /** @type {Record} */ - const byEntry = {} - /** @type {string | null} */ - let defaultClient = null - /** @type {string | null} */ - let defaultStyle = null - /** @type {BundleAsset[]} */ - const defaultAssets = [] - const seenDefaultUrls = new Set() - /** @type {Map>} */ - const assetMetaCache = new Map() - - /** - * Resolve and memoize bundle-independent metadata for a non-entry emitted asset. - * @param {string} assetPath - * @param {esbuild.Metafile['outputs'][string]} target - * @returns {Omit} - */ - const getAssetMeta = (assetPath, target) => { - const cached = assetMetaCache.get(assetPath) - if (cached) return cached - const assetRelname = toPosix(relative(dest, assetPath)) - let source = null - if (target.inputs) { - for (const inputKey in target.inputs) { - if (Object.hasOwn(target.inputs, inputKey)) { - source = toPosix(inputKey) - break - } - } - } - const ext = extname(assetRelname).toLowerCase() - const lookedUp = mime.lookup(ext) - const type = typeof lookedUp === 'string' ? lookedUp : null - const meta = { - url: `/${assetRelname}`, - source, - ext, - type, - as: preloadAsForMime(type), - } - assetMetaCache.set(assetPath, meta) - return meta - } - - for (const outputFile in metafile.outputs) { - if (!Object.hasOwn(metafile.outputs, outputFile)) continue - const outputInfo = metafile.outputs[outputFile] - const entryPoint = outputInfo?.entryPoint - if (!entryPoint) continue - - // Esbuild metafiles can use platform separators, while siteData keys are POSIX relnames. - const entryRelname = toPosix(relative(src, entryPoint)) - const entryOutputRelname = toPosix(relative(dest, outputFile)) - outputMap[entryRelname] = entryOutputRelname - - const resolvedEntryPoint = resolve(entryPoint) - const isDefaultStyle = resolvedEntryPoint === DEFAULT_STYLE_INPUT - const isDefaultClient = resolvedEntryPoint === DEFAULT_CLIENT_INPUT - const isDefaultBundle = isDefaultStyle || isDefaultClient - if (isDefaultClient && defaultClient === null) defaultClient = entryOutputRelname - else if (isDefaultStyle && defaultStyle === null) defaultStyle = entryOutputRelname - - const bundleUrl = `/${entryOutputRelname}` - /** @type {BundleAsset[]} */ - const assets = [] - const seenUrls = new Set() - const visitedOutputs = new Set([outputFile]) - - /** @param {string} currentFile */ - const walk = (currentFile) => { - const currentOutput = metafile.outputs[currentFile] - if (!currentOutput) return - - if (currentOutput.cssBundle && !visitedOutputs.has(currentOutput.cssBundle)) { - visitedOutputs.add(currentOutput.cssBundle) - walk(currentOutput.cssBundle) - } - - for (const imp of currentOutput.imports ?? []) { - if (imp.external || !Object.hasOwn(metafile.outputs, imp.path)) continue - const target = metafile.outputs[imp.path] - if (!target) continue - - if (!target.entryPoint && (imp.kind === 'url-token' || imp.kind === 'file-loader')) { - if (imp.path.endsWith('.map')) continue - const meta = getAssetMeta(imp.path, target) - if (seenUrls.has(meta.url)) continue - seenUrls.add(meta.url) - assets.push({ ...meta, bundle: bundleUrl }) - continue - } - - if ( - (imp.kind === 'import-statement' || imp.kind === 'dynamic-import' || imp.kind === 'import-rule') && - !visitedOutputs.has(imp.path) - ) { - visitedOutputs.add(imp.path) - walk(imp.path) - } - } - } - - walk(outputFile) - - if (isDefaultBundle) { - for (const asset of assets) { - if (seenDefaultUrls.has(asset.url)) continue - seenDefaultUrls.add(asset.url) - defaultAssets.push(asset) - } - } else if (assets.length > 0) { - byEntry[entryRelname] = assets - } - } - - return { outputMap, byEntry, defaultClient, defaultStyle, defaultAssets } -} - -/** - * Extract a relpath→relpath output map from esbuild metafile outputs. - * - * @param {esbuild.Metafile} metafile - * @param {string} src - * @param {string} dest - * @returns {OutputMap} - */ -export function extractOutputMap (metafile, src, dest) { - /** @type {OutputMap} */ - const outputMap = {} - for (const file in metafile.outputs) { - if (!Object.hasOwn(metafile.outputs, file)) continue - const entryPoint = metafile.outputs[file]?.entryPoint - if (entryPoint) { - // Esbuild metafiles can use platform separators, while siteData keys are POSIX relnames. - outputMap[toPosix(relative(src, entryPoint))] = toPosix(relative(dest, file)) - } - } - return outputMap -} - -/** - * Derive the HTML `` destination for a MIME type. - * @param {string | null} mimeType - * @returns {BundleAssetAs | null} - */ -function preloadAsForMime (mimeType) { - if (!mimeType) return null - if (mimeType.startsWith('font/')) return 'font' - if (mimeType.startsWith('image/')) return 'image' - if (mimeType.startsWith('audio/')) return 'audio' - if (mimeType.startsWith('video/')) return 'video' - return null -} - -/** - * Extract non-entry emitted assets (such as hashed `.woff2` fonts or `file`-loader - * imports) for each entry point in an esbuild metafile, walking transitive - * shared chunks and companion CSS bundles. - * - * @param {esbuild.Metafile} metafile - * @param {string} src - * @param {string} dest - * @returns {BundleAssetsMap} - */ -export function extractBundleAssets (metafile, src, dest) { - const { byEntry, defaultAssets } = extractBuildOutputs(metafile, src, dest) - return { byEntry, defaultAssets } -} - -/** - * Compare two `BundleAsset` lists for value equality. - * @param {BundleAsset[] | undefined} a - * @param {BundleAsset[] | undefined} b - * @returns {boolean} - */ -function sameBundleAssets (a, b) { - const listA = a ?? [] - const listB = b ?? [] - if (listA.length !== listB.length) return false - for (let i = 0; i < listA.length; i++) { - const itemA = listA[i] - const itemB = listB[i] - if (!itemA || !itemB) return false - if ( - itemA.url !== itemB.url || - itemA.source !== itemB.source || - itemA.ext !== itemB.ext || - itemA.type !== itemB.type || - itemA.as !== itemB.as || - itemA.bundle !== itemB.bundle - ) { - return false - } - } - return true -} - -/** - * Update `siteData` bundle-emitted assets from a watch esbuild rebuild and - * report which scopes changed so watch mode only rebuilds affected pages. - * - * @param {esbuild.Metafile} metafile - * @param {string} src - * @param {string} dest - * @param {SiteData} siteData - * @returns {{ globalChanged: boolean, changedLayouts: string[], changedPagePaths: string[] }} - */ -export function syncSiteDataBundleAssets (metafile, src, dest, siteData) { - const { byEntry, defaultAssets } = extractBundleAssets(metafile, src, dest) - let globalChanged = false - /** @type {string[]} */ - const changedLayouts = [] - /** @type {string[]} */ - const changedPagePaths = [] - - /** @param {{ relname: string, emittedAssets?: BundleAsset[] } | null | undefined} fileInfo */ - const syncFile = (fileInfo) => { - if (!fileInfo) return false - const next = byEntry[fileInfo.relname] ?? [] - if (sameBundleAssets(fileInfo.emittedAssets, next)) return false - fileInfo.emittedAssets = next - return true - } - - if (syncFile(siteData.globalStyle)) globalChanged = true - if (syncFile(siteData.globalClient)) globalChanged = true - if (siteData.defaultLayout && !sameBundleAssets(siteData.defaultAssets, defaultAssets)) { - siteData.defaultAssets = defaultAssets - globalChanged = true - } - - for (const layout of Object.values(siteData.layouts)) { - const styleChanged = syncFile(layout.layoutStyle) - const clientChanged = syncFile(layout.layoutClient) - if (styleChanged || clientChanged) changedLayouts.push(layout.layoutName) - } - - for (const page of siteData.pages) { - const styleChanged = syncFile(page.pageStyle) - const clientChanged = syncFile(page.clientBundle) - if (styleChanged || clientChanged) changedPagePaths.push(page.pageFile.filepath) - } - - return { globalChanged, changedLayouts, changedPagePaths } -} - -/** - * Stamp output relpaths and emitted non-entry assets from esbuild back onto siteData in place. - * - * @param {ReturnType} extracted - * @param {SiteData} siteData - */ -function updateSiteDataOutputPaths (extracted, siteData) { - const { outputMap, byEntry, defaultClient, defaultStyle, defaultAssets } = extracted - for (const page of siteData.pages) { - updateOutputFileInfo(outputMap, byEntry, page.pageStyle) - updateOutputFileInfo(outputMap, byEntry, page.clientBundle) - - if (page.workers) { - for (const workerFile of Object.values(page.workers)) { - updateOutputFileInfo(outputMap, byEntry, workerFile) - } - } - } - - updateOutputFileInfo(outputMap, byEntry, siteData.globalClient) - updateOutputFileInfo(outputMap, byEntry, siteData.globalStyle) - updateOutputFileInfo(outputMap, byEntry, siteData.serviceWorker) - - for (const layout of Object.values(siteData.layouts)) { - updateOutputFileInfo(outputMap, byEntry, layout.layoutStyle) - updateOutputFileInfo(outputMap, byEntry, layout.layoutClient) - } - - if (siteData.defaultLayout && (defaultClient !== null || defaultStyle !== null)) { - siteData.defaultClient = defaultClient - siteData.defaultStyle = defaultStyle - siteData.defaultAssets = defaultAssets - } -} - -/** - * @param {OutputMap} outputMap - * @param {Record} assetsByEntry - * @param {{ relname: string, outputRelname?: string, outputName?: string, emittedAssets?: BundleAsset[] } | null | undefined} fileInfo - */ -function updateOutputFileInfo (outputMap, assetsByEntry, fileInfo) { - if (!fileInfo) return - - const outputRelname = outputMap[fileInfo.relname] - if (!outputRelname) return - - fileInfo.outputRelname = outputRelname - fileInfo.outputName = basename(outputRelname) - fileInfo.emittedAssets = assetsByEntry[fileInfo.relname] ?? [] -} - -/** - * Resolve `global.vars.*`'s `browser` export in a fresh worker thread so watch - * mode reloads changes without caching `global.vars.*` on the main thread. - * - * @param {string | undefined} varsPath - * @returns {Promise>} - */ -function resolveBrowserVarsInWorker (varsPath) { - if (!varsPath) return Promise.resolve({}) - - return new Promise((resolve, reject) => { - const worker = new Worker(join(__dirname, 'browser-vars-worker.js'), { - workerData: { varsPath }, - }) - - let settled = false - /** @param {Record} value */ - const settleResolve = (value) => { - if (settled) return - settled = true - resolve(value) - } - /** @param {unknown} err */ - const settleReject = (err) => { - if (settled) return - settled = true - reject(err) - } - - worker.once('message', settleResolve) - worker.once('error', settleReject) - worker.once('exit', (code) => { - if (settled) return - settleReject(new Error( - code !== 0 - ? `Browser vars worker stopped with exit code ${code}` - : 'Browser vars worker exited with code 0 without posting a result' - )) - }) - }) -} - -/** - * Create browser-side esbuild options from siteData + opts. - * The root service worker intentionally uses a separate build derived from these base options. - * - * @param {string} src - * @param {string} dest - * @param {SiteData} siteData - * @param {DomStackOpts | null} opts - * @param {{ watch?: boolean }} [modeOpts] - * @returns {Promise} - */ -async function createBrowserBuildOpts (src, dest, siteData, opts, modeOpts = {}) { - const entryPoints = /** @type {(string | { in: string, out: string })[]} */ (globalBundleAssets(siteData).map(asset => join(src, asset.relname))) - - if (siteData.defaultLayout) { - entryPoints.push( - { in: join(__dirname, '../defaults/default.style.css'), out: join(DOM_STACK_DEFAULTS_PREFIX, 'default.style.css') }, - { in: join(__dirname, '../defaults/default.client.js'), out: join(DOM_STACK_DEFAULTS_PREFIX, 'default.client.js') } - ) - } - - for (const page of siteData.pages) { - for (const asset of pageBundleAssets(page)) entryPoints.push(join(src, asset.relname)) - } - - for (const layout of Object.values(siteData.layouts)) { - for (const asset of layoutBundleAssets(layout)) entryPoints.push(join(src, asset.relname)) - } - - const target = Array.isArray(opts?.target) ? opts.target : [] - - const watch = modeOpts.watch ?? false - const browserDefines = watch - ? await resolveBrowserVarsInWorker(siteData?.globalVars?.filepath) - : Object.fromEntries( - Object.entries(await resolveVars({ - varsPath: siteData?.globalVars?.filepath, - key: 'browser', - })).map(([k, v]) => [k, JSON.stringify(v)]) - ) - - /** @type {{ [varName: string]: string }} */ - const domstackDefines = createDomstackDefines({ opts, siteData, watch }) - /** @type {{ [varName: string]: string }} */ - const define = { ...domstackDefines } - for (const [k, v] of Object.entries(browserDefines)) { - if (Object.hasOwn(define, k)) { - throw new Error(`Conflict: "${k}" is reserved by domstack.`) - } - define[k] = v - } - - /** @type {esbuild.BuildOptions} */ - const buildOpts = { - entryPoints, - /** @type {EsbuildLogLevel} */ - logLevel: 'silent', - bundle: true, - write: true, - /** @type {EsbuildFormat} */ - format: 'esm', - splitting: true, - sourcemap: true, - outdir: dest, - outbase: src, - target, - define, - metafile: true, - // In watch mode use stable unhashed entry filenames so page HTML references remain stable. - // Shared chunks still use content hashes so watch stays close to production behavior. - entryNames: watch ? '[dir]/[name]' : '[dir]/[name]-[hash]', - chunkNames: 'chunks/[ext]/[name]-[hash]', - loader: { - '.png': 'dataurl', - '.jpg': 'dataurl', - '.jpeg': 'dataurl', - '.gif': 'dataurl', - '.svg': 'dataurl', - '.webp': 'dataurl', - '.avif': 'dataurl', - '.ico': 'file', - '.woff': 'file', - '.woff2': 'file', - '.ttf': 'file', - '.eot': 'file', - '.otf': 'file', - } - } - - const esbuildSettingsExtends = siteData.esbuildSettings - ? (await importFile(siteData.esbuildSettings.filepath)).default - : (/** @type {typeof buildOpts} */ esbuildOpts) => esbuildOpts - - const extendedBuildOpts = await esbuildSettingsExtends(buildOpts) - - if (Object.keys(browserDefines).length > 0 && extendedBuildOpts.define !== buildOpts.define) { - throw new Error( - 'Conflict: both the "browser" export in global.vars and "define" in esbuild.settings are set. ' + - 'Use one or the other to define browser constants.' - ) - } - - return { - ...extendedBuildOpts, - define: preserveDomstackDefines(extendedBuildOpts.define, domstackDefines), - } -} - -/** - * Keep domstack-owned browser build facts available even when esbuild.settings - * replaces the define object. User settings may add custom defines, but they may - * not override domstack's reserved DOMSTACK_* values. * - * @param {esbuild.BuildOptions['define']} define - * @param {{ [varName: string]: string }} domstackDefines - * @returns {{ [varName: string]: string }} - */ -function preserveDomstackDefines (define, domstackDefines) { - const mergedDefine = { ...(define ?? {}) } - - for (const [key, value] of Object.entries(domstackDefines)) { - if (Object.hasOwn(mergedDefine, key) && mergedDefine[key] !== value) { - throw new Error(`Conflict: "${key}" is reserved by domstack.`) - } - mergedDefine[key] = value - } - - return mergedDefine -} - -/** - * @param {object} params - * @param {string} params.dest - * @param {esbuild.BuildResult} params.result - * @param {boolean} params.shouldWrite - */ -async function writeMetafile ({ dest, result, shouldWrite }) { - if (!result.metafile || !shouldWrite) return - - await writeFile(join(dest, 'domstack-esbuild-meta.json'), JSON.stringify(result.metafile, null, ' ')) -} - -/** - * @param {object} params - * @param {string} params.dest - * @param {esbuild.BuildResult} params.result - * @param {SiteData} params.siteData - * @param {string} params.src - * @returns {OutputMap} + * @typedef {Awaited>} EsBuildStepResults */ -function applyBuildOutputMap ({ dest, result, siteData, src }) { - const extracted = result.metafile - ? extractBuildOutputs(result.metafile, src, dest) - : { outputMap: {}, byEntry: {}, defaultClient: null, defaultStyle: null, defaultAssets: [] } - updateSiteDataOutputPaths(extracted, siteData) - return extracted.outputMap -} /** * @returns {EsbuildReport} @@ -740,301 +162,3 @@ export async function buildServiceWorkerEsbuild (src, dest, siteData, browserBui } } } - -/** - * Production entry filenames are content-hashed globally. Service workers need - * a stable root URL, so they get a tiny second build with a fixed entry name. - * Emitting at /service-worker.js also gives the worker root scope by default. - * - * @param {object} params - * @param {esbuild.BuildOptions} params.buildOpts - * @param {ServiceWorkerBuildDefines} params.defines - * @param {NonNullable} params.serviceWorker - * @param {string} params.src - * @returns {esbuild.BuildOptions} - */ -function createServiceWorkerBuildOpts ({ buildOpts, defines, serviceWorker, src }) { - return { - ...buildOpts, - define: createServiceWorkerDefineMap(buildOpts.define, defines), - entryPoints: [ - { - in: join(src, serviceWorker.relname), - out: 'service-worker', - }, - ], - entryNames: '[name]', - splitting: false, - } -} - -/** - * @param {esbuild.BuildOptions['define']} baseDefine - * @param {ServiceWorkerBuildDefines} defines - * @returns {{ [varName: string]: string }} - */ -function createServiceWorkerDefineMap (baseDefine, defines) { - const define = { ...(baseDefine ?? {}) } - const serviceWorkerDefine = defines.define ?? {} - - for (const [key, value] of Object.entries(serviceWorkerDefine)) { - if (Object.hasOwn(define, key) && define[key] !== value) { - throw new Error(`Conflict: "${key}" is already defined for the service-worker build.`) - } - define[key] = value - } - - define['process.env.DOMSTACK_MANIFEST_VERSION'] = JSON.stringify(defines.manifestVersion ?? '') - return define -} - -/** - * Provide domstack-owned build facts to all browser-side bundles. - * - * @param {object} params - * @param {DomStackOpts | null} params.opts - * @param {SiteData} params.siteData - * @param {boolean} params.watch - */ -function createDomstackDefines ({ opts, siteData, watch }) { - const hasServiceWorker = Boolean(siteData.serviceWorker) - const domstackManifestSettingsPath = siteData?.domstackManifestSettings?.filepath - - return { - 'process.env.DOMSTACK_MANIFEST_URL': JSON.stringify(`/${DEFAULT_DOMSTACK_MANIFEST_FILENAME}`), - 'process.env.DOMSTACK_MANIFEST_VERSION': JSON.stringify(''), - 'process.env.DOMSTACK_MANIFEST_ENABLED': JSON.stringify(String(!watch && isDomstackManifestEnabled({ domstackManifestSettingsPath, opts: opts ?? undefined }))), - 'process.env.DOMSTACK_SERVICE_WORKER_URL': JSON.stringify(hasServiceWorker ? `/${SERVICE_WORKER_OUTPUT_RELNAME}` : ''), - 'process.env.DOMSTACK_SERVICE_WORKER_SCOPE': JSON.stringify(hasServiceWorker ? '/' : ''), - } -} - -/** - * Create esbuild watch contexts with stable unhashed entry filenames. - * The browser context keeps production-like code splitting. - * The service-worker context is separate and self-contained so watch-mode cleanup can run reliably. - * - * @param {string} src - * @param {string} dest - * @param {SiteData} siteData - * @param {DomStackOpts} opts - * @param {{ onEnd?: (result: esbuild.BuildResult) => void, logger?: PinoLogger }} [watchOpts] - * @returns {Promise<{ context: DisposableBuildContext, outputMap: OutputMap, buildResults: esbuild.BuildResult, buildOpts: EsbuildBuildOptions }>} - */ -export async function buildEsbuildWatch (src, dest, siteData, opts, watchOpts = {}) { - const logger = watchOpts.logger ?? opts.logger ?? createDomStackLogger() - const extendedBuildOpts = await createBrowserBuildOpts(src, dest, siteData, opts, { watch: true }) - const browserWatch = await createWatchBuild({ - buildOpts: extendedBuildOpts, - dest, - label: 'JS/CSS', - logger, - onEnd: watchOpts.onEnd, - shouldWriteMetafile: opts?.metafile !== false, - }) - - const initialResult = browserWatch.initialResult - - /** @type {esbuild.BuildContext[]} */ - const contexts = [browserWatch.context] - try { - const outputMap = applyBuildOutputMap({ dest, result: initialResult, siteData, src }) - - if (siteData.serviceWorker) { - // Keep service-worker-only defines and no-policy watch cleanup behavior out of browser bundles. - const serviceWorkerBuildOpts = createServiceWorkerBuildOpts({ - buildOpts: extendedBuildOpts, - defines: {}, - serviceWorker: siteData.serviceWorker, - src, - }) - const serviceWorkerWatch = await createWatchBuild({ - buildOpts: serviceWorkerBuildOpts, - dest, - label: 'Service worker', - logger, - shouldWriteMetafile: false, - }) - contexts.push(serviceWorkerWatch.context) - applyBuildOutputMap({ - dest, - result: serviceWorkerWatch.initialResult, - siteData, - src, - }) - } - - return { - context: createDisposableBuildContext(contexts), - outputMap, - buildResults: initialResult, - buildOpts: extendedBuildOpts, - } - } catch (error) { - const cleanup = await Promise.allSettled(contexts.map(context => context.dispose())) - const failures = cleanup.filter(result => result.status === 'rejected').map(result => result.reason) - if (failures.length) throw new AggregateError([error, ...failures], 'Esbuild watch startup and cleanup failed') - throw error - } -} - -/** - * @param {object} params - * @param {esbuild.BuildOptions} params.buildOpts - * @param {string} params.dest - * @param {string} params.label - * @param {PinoLogger} params.logger - * @param {((result: esbuild.BuildResult) => void | Promise) | undefined} [params.onEnd] - * @param {boolean} params.shouldWriteMetafile - * @returns {Promise<{ context: esbuild.BuildContext, initialResult: esbuild.BuildResult }>} - */ -async function createWatchBuild ({ buildOpts, dest, label, logger, onEnd, shouldWriteMetafile }) { - const initial = Promise.withResolvers() - // Attach a rejection handler before watch() can deliver a failing initial build. - initial.promise.catch(() => {}) - let isInitialBuild = true - const plugins = buildOpts.plugins ?? [] - - /** @type {esbuild.Plugin} */ - const onEndPlugin = { - name: `domstack-${label.toLowerCase().replaceAll(/[^a-z0-9]+/g, '-')}-on-end`, - setup (build) { - build.onEnd(async result => { - const first = isInitialBuild - isInitialBuild = false - try { - if (result.errors.length > 0) { - const failure = Object.assign(new Error(`${label} build failed`), { - errors: result.errors.map(serializeEsbuildMessage), - warnings: result.warnings.map(serializeEsbuildMessage), - }) - if (first) { - initial.reject(failure) - return - } - logger.error({ errors: failure.errors, warnings: failure.warnings }, `${label} rebuild failed`) - } else { - if (result.warnings.length) { - logger.warn({ warnings: result.warnings.map(serializeEsbuildMessage) }, `${label} build warnings`) - } - await writeMetafile({ dest, result, shouldWrite: shouldWriteMetafile }) - if (first) logger.debug(`${label} initial build complete`) - else logger.info(`${label} rebuild complete`) - } - if (first) initial.resolve(result) - else if (onEnd) await onEnd(result) - } catch (error) { - if (first) initial.reject(error) - else logger.error({ err: error }, `${label} rebuild processing failed`) - } - }) - } - } - - const contextOpts = { ...buildOpts, plugins: [...plugins, onEndPlugin] } - - /** @type {esbuild.BuildContext | undefined} */ - let context - try { - context = await esbuild.context(contextOpts) - await context.watch() - const initialResult = await initial.promise - - return { context, initialResult } - } catch (err) { - await context?.dispose() - throw serializeEsbuildError(err) - } -} - -/** - * @param {esbuild.BuildContext[]} contexts - * @returns {DisposableBuildContext} - */ -function createDisposableBuildContext (contexts) { - return { - async dispose () { - const results = await Promise.allSettled(contexts.map(context => context.dispose())) - const errors = results.filter(result => result.status === 'rejected').map(result => result.reason) - if (errors.length) throw new AggregateError(errors, 'Esbuild watch cleanup failed') - }, - } -} - -/** - * @param {object} params - * @param {string} params.src - * @param {string} params.dest - * @param {SiteData} params.siteData - * @param {esbuild.BuildResult} params.buildResults - * @param {boolean} params.includeMetafileRecord - * @returns {DomstackManifestRecord[]} - */ -export function createEsbuildOutputRecords ({ src, dest, siteData, buildResults, includeMetafileRecord }) { - /** @type {DomstackManifestRecord[]} */ - const outputs = [] - const metafile = buildResults.metafile - if (!metafile) return outputs - - const workerOutputRelnames = new Set() - for (const page of siteData.pages) { - if (!page.workers) continue - for (const worker of Object.values(page.workers)) { - if (worker.outputRelname) workerOutputRelnames.add(toPosix(worker.outputRelname)) - } - } - const serviceWorkerOutputRelname = siteData.serviceWorker?.outputRelname - ? toPosix(siteData.serviceWorker.outputRelname) - : undefined - - for (const [outputPath, outputMeta] of Object.entries(metafile.outputs)) { - const filepath = resolve(outputPath) - const outputRelname = toPosix(relative(dest, filepath)) - const kind = classifyEsbuildOutput({ - outputRelname, - entryPoint: outputMeta.entryPoint, - workerOutputRelnames, - serviceWorkerOutputRelname, - }) - - outputs.push(createDomstackManifestRecord({ - dest, - filepath, - outputRelname, - kind, - entryPoint: outputMeta.entryPoint, - sourceRelname: outputMeta.entryPoint ? toPosix(relative(src, resolve(outputMeta.entryPoint))) : undefined, - })) - } - - if (includeMetafileRecord) { - outputs.push(createDomstackManifestRecord({ - dest, - outputRelname: 'domstack-esbuild-meta.json', - kind: 'metadata', - })) - } - - return outputs -} - -/** - * Classify a dest-relative esbuild output. - * - * @param {object} params - * @param {string} params.outputRelname - * @param {string | undefined} params.entryPoint - * @param {Set} params.workerOutputRelnames - * @param {string | undefined} [params.serviceWorkerOutputRelname] - * @returns {DomstackManifestKind} - */ -function classifyEsbuildOutput ({ outputRelname, entryPoint, workerOutputRelnames, serviceWorkerOutputRelname }) { - const ext = extname(outputRelname) - - if (ext === '.map') return 'sourcemap' - if (serviceWorkerOutputRelname && outputRelname === serviceWorkerOutputRelname) return 'service-worker' - if (workerOutputRelnames.has(outputRelname)) return 'worker' - if (ext === '.css') return 'style' - if (ext === '.js' && entryPoint) return 'script' - return 'chunk' -} diff --git a/lib/build-esbuild/metafile.js b/lib/build-esbuild/metafile.js new file mode 100644 index 00000000..7da779cf --- /dev/null +++ b/lib/build-esbuild/metafile.js @@ -0,0 +1,379 @@ +/** + * @import esbuild from 'esbuild' + * @import { SiteData } from '../builder.js' + */ + +import { writeFile } from 'node:fs/promises' +import { basename, extname, join, relative, resolve } from 'node:path' +import mime from 'mime-types' +import { toPosix } from '#helpers/path.js' + +const __dirname = import.meta.dirname +const DEFAULT_STYLE_INPUT = resolve(__dirname, '../defaults/default.style.css') +const DEFAULT_CLIENT_INPUT = resolve(__dirname, '../defaults/default.client.js') + +/** + * Preload destination derived from an emitted asset's MIME type. + * @typedef {'font' | 'image' | 'audio' | 'video'} BundleAssetAs + */ + +/** + * Metadata for a non-entry asset emitted by esbuild (such as a hashed font or + * file-loader asset referenced from a CSS or JS bundle). + * @typedef {object} BundleAsset + * @property {string} url - Public root-relative URL of the emitted asset (e.g. `"/inter-latin-400-XYZ.woff2"`). + * @property {string | null} source - Original unhashed input path (POSIX) reported by esbuild, or `null` if unavailable. + * @property {string} ext - Lowercase file extension including the leading dot (e.g. `".woff2"`). + * @property {string | null} type - MIME type derived from `ext` (e.g. `"font/woff2"`), or `null` if unknown. + * @property {BundleAssetAs | null} as - HTML `` destination when applicable, or `null`. + * @property {string} bundle - Public root-relative URL of the entry bundle that referenced this asset. + */ + +/** + * @typedef {{[relpath: string]: string}} OutputMap + * @typedef {{ byEntry: Record, defaultAssets: BundleAsset[] }} BundleAssetsMap + */ + +/** + * Extract entry output paths, default bundle paths, and per-entry non-entry + * emitted assets from an esbuild metafile in a single pass. + * + * @param {esbuild.Metafile} metafile + * @param {string} src + * @param {string} dest + * @returns {{ + * outputMap: OutputMap, + * byEntry: Record, + * defaultClient: string | null, + * defaultStyle: string | null, + * defaultAssets: BundleAsset[], + * }} + */ +function extractBuildOutputs (metafile, src, dest) { + /** @type {OutputMap} */ + const outputMap = {} + /** @type {Record} */ + const byEntry = {} + /** @type {string | null} */ + let defaultClient = null + /** @type {string | null} */ + let defaultStyle = null + /** @type {BundleAsset[]} */ + const defaultAssets = [] + const seenDefaultUrls = new Set() + /** @type {Map>} */ + const assetMetaCache = new Map() + + /** + * Resolve and memoize bundle-independent metadata for a non-entry emitted asset. + * @param {string} assetPath + * @param {esbuild.Metafile['outputs'][string]} target + * @returns {Omit} + */ + const getAssetMeta = (assetPath, target) => { + const cached = assetMetaCache.get(assetPath) + if (cached) return cached + const assetRelname = toPosix(relative(dest, assetPath)) + let source = null + if (target.inputs) { + for (const inputKey in target.inputs) { + if (Object.hasOwn(target.inputs, inputKey)) { + source = toPosix(inputKey) + break + } + } + } + const ext = extname(assetRelname).toLowerCase() + const lookedUp = mime.lookup(ext) + const type = typeof lookedUp === 'string' ? lookedUp : null + const meta = { + url: `/${assetRelname}`, + source, + ext, + type, + as: preloadAsForMime(type), + } + assetMetaCache.set(assetPath, meta) + return meta + } + + for (const outputFile in metafile.outputs) { + if (!Object.hasOwn(metafile.outputs, outputFile)) continue + const outputInfo = metafile.outputs[outputFile] + const entryPoint = outputInfo?.entryPoint + if (!entryPoint) continue + + // Esbuild metafiles can use platform separators, while siteData keys are POSIX relnames. + const entryRelname = toPosix(relative(src, entryPoint)) + const entryOutputRelname = toPosix(relative(dest, outputFile)) + outputMap[entryRelname] = entryOutputRelname + + const resolvedEntryPoint = resolve(entryPoint) + const isDefaultStyle = resolvedEntryPoint === DEFAULT_STYLE_INPUT + const isDefaultClient = resolvedEntryPoint === DEFAULT_CLIENT_INPUT + const isDefaultBundle = isDefaultStyle || isDefaultClient + if (isDefaultClient && defaultClient === null) defaultClient = entryOutputRelname + else if (isDefaultStyle && defaultStyle === null) defaultStyle = entryOutputRelname + + const bundleUrl = `/${entryOutputRelname}` + /** @type {BundleAsset[]} */ + const assets = [] + const seenUrls = new Set() + const visitedOutputs = new Set([outputFile]) + + /** @param {string} currentFile */ + const walk = (currentFile) => { + const currentOutput = metafile.outputs[currentFile] + if (!currentOutput) return + + if (currentOutput.cssBundle && !visitedOutputs.has(currentOutput.cssBundle)) { + visitedOutputs.add(currentOutput.cssBundle) + walk(currentOutput.cssBundle) + } + + for (const imp of currentOutput.imports ?? []) { + if (imp.external || !Object.hasOwn(metafile.outputs, imp.path)) continue + const target = metafile.outputs[imp.path] + if (!target) continue + + if (!target.entryPoint && (imp.kind === 'url-token' || imp.kind === 'file-loader')) { + if (imp.path.endsWith('.map')) continue + const meta = getAssetMeta(imp.path, target) + if (seenUrls.has(meta.url)) continue + seenUrls.add(meta.url) + assets.push({ ...meta, bundle: bundleUrl }) + continue + } + + if ( + (imp.kind === 'import-statement' || imp.kind === 'dynamic-import' || imp.kind === 'import-rule') && + !visitedOutputs.has(imp.path) + ) { + visitedOutputs.add(imp.path) + walk(imp.path) + } + } + } + + walk(outputFile) + + if (isDefaultBundle) { + for (const asset of assets) { + if (seenDefaultUrls.has(asset.url)) continue + seenDefaultUrls.add(asset.url) + defaultAssets.push(asset) + } + } else if (assets.length > 0) { + byEntry[entryRelname] = assets + } + } + + return { outputMap, byEntry, defaultClient, defaultStyle, defaultAssets } +} + +/** + * Extract a relpath→relpath output map from esbuild metafile outputs. + * + * @param {esbuild.Metafile} metafile + * @param {string} src + * @param {string} dest + * @returns {OutputMap} + */ +export function extractOutputMap (metafile, src, dest) { + /** @type {OutputMap} */ + const outputMap = {} + for (const file in metafile.outputs) { + if (!Object.hasOwn(metafile.outputs, file)) continue + const entryPoint = metafile.outputs[file]?.entryPoint + if (entryPoint) { + // Esbuild metafiles can use platform separators, while siteData keys are POSIX relnames. + outputMap[toPosix(relative(src, entryPoint))] = toPosix(relative(dest, file)) + } + } + return outputMap +} + +/** + * Derive the HTML `` destination for a MIME type. + * @param {string | null} mimeType + * @returns {BundleAssetAs | null} + */ +function preloadAsForMime (mimeType) { + if (!mimeType) return null + if (mimeType.startsWith('font/')) return 'font' + if (mimeType.startsWith('image/')) return 'image' + if (mimeType.startsWith('audio/')) return 'audio' + if (mimeType.startsWith('video/')) return 'video' + return null +} + +/** + * Extract non-entry emitted assets (such as hashed `.woff2` fonts or `file`-loader + * imports) for each entry point in an esbuild metafile, walking transitive + * shared chunks and companion CSS bundles. + * + * @param {esbuild.Metafile} metafile + * @param {string} src + * @param {string} dest + * @returns {BundleAssetsMap} + */ +export function extractBundleAssets (metafile, src, dest) { + const { byEntry, defaultAssets } = extractBuildOutputs(metafile, src, dest) + return { byEntry, defaultAssets } +} + +/** + * Compare two `BundleAsset` lists for value equality. + * @param {BundleAsset[] | undefined} a + * @param {BundleAsset[] | undefined} b + * @returns {boolean} + */ +function sameBundleAssets (a, b) { + const listA = a ?? [] + const listB = b ?? [] + if (listA.length !== listB.length) return false + for (let i = 0; i < listA.length; i++) { + const itemA = listA[i] + const itemB = listB[i] + if (!itemA || !itemB) return false + if ( + itemA.url !== itemB.url || + itemA.source !== itemB.source || + itemA.ext !== itemB.ext || + itemA.type !== itemB.type || + itemA.as !== itemB.as || + itemA.bundle !== itemB.bundle + ) { + return false + } + } + return true +} + +/** + * Update `siteData` bundle-emitted assets from a watch esbuild rebuild and + * report which scopes changed so watch mode only rebuilds affected pages. + * + * @param {esbuild.Metafile} metafile + * @param {string} src + * @param {string} dest + * @param {SiteData} siteData + * @returns {{ globalChanged: boolean, changedLayouts: string[], changedPagePaths: string[] }} + */ +export function syncSiteDataBundleAssets (metafile, src, dest, siteData) { + const { byEntry, defaultAssets } = extractBundleAssets(metafile, src, dest) + let globalChanged = false + /** @type {string[]} */ + const changedLayouts = [] + /** @type {string[]} */ + const changedPagePaths = [] + + /** @param {{ relname: string, emittedAssets?: BundleAsset[] } | null | undefined} fileInfo */ + const syncFile = (fileInfo) => { + if (!fileInfo) return false + const next = byEntry[fileInfo.relname] ?? [] + if (sameBundleAssets(fileInfo.emittedAssets, next)) return false + fileInfo.emittedAssets = next + return true + } + + if (syncFile(siteData.globalStyle)) globalChanged = true + if (syncFile(siteData.globalClient)) globalChanged = true + if (siteData.defaultLayout && !sameBundleAssets(siteData.defaultAssets, defaultAssets)) { + siteData.defaultAssets = defaultAssets + globalChanged = true + } + + for (const layout of Object.values(siteData.layouts)) { + const styleChanged = syncFile(layout.layoutStyle) + const clientChanged = syncFile(layout.layoutClient) + if (styleChanged || clientChanged) changedLayouts.push(layout.layoutName) + } + + for (const page of siteData.pages) { + const styleChanged = syncFile(page.pageStyle) + const clientChanged = syncFile(page.clientBundle) + if (styleChanged || clientChanged) changedPagePaths.push(page.pageFile.filepath) + } + + return { globalChanged, changedLayouts, changedPagePaths } +} + +/** + * Stamp output relpaths and emitted non-entry assets from esbuild back onto siteData in place. + * + * @param {ReturnType} extracted + * @param {SiteData} siteData + */ +function updateSiteDataOutputPaths (extracted, siteData) { + const { outputMap, byEntry, defaultClient, defaultStyle, defaultAssets } = extracted + for (const page of siteData.pages) { + updateOutputFileInfo(outputMap, byEntry, page.pageStyle) + updateOutputFileInfo(outputMap, byEntry, page.clientBundle) + + if (page.workers) { + for (const workerFile of Object.values(page.workers)) { + updateOutputFileInfo(outputMap, byEntry, workerFile) + } + } + } + + updateOutputFileInfo(outputMap, byEntry, siteData.globalClient) + updateOutputFileInfo(outputMap, byEntry, siteData.globalStyle) + updateOutputFileInfo(outputMap, byEntry, siteData.serviceWorker) + + for (const layout of Object.values(siteData.layouts)) { + updateOutputFileInfo(outputMap, byEntry, layout.layoutStyle) + updateOutputFileInfo(outputMap, byEntry, layout.layoutClient) + } + + if (siteData.defaultLayout && (defaultClient !== null || defaultStyle !== null)) { + siteData.defaultClient = defaultClient + siteData.defaultStyle = defaultStyle + siteData.defaultAssets = defaultAssets + } +} + +/** + * @param {OutputMap} outputMap + * @param {Record} assetsByEntry + * @param {{ relname: string, outputRelname?: string, outputName?: string, emittedAssets?: BundleAsset[] } | null | undefined} fileInfo + */ +function updateOutputFileInfo (outputMap, assetsByEntry, fileInfo) { + if (!fileInfo) return + + const outputRelname = outputMap[fileInfo.relname] + if (!outputRelname) return + + fileInfo.outputRelname = outputRelname + fileInfo.outputName = basename(outputRelname) + fileInfo.emittedAssets = assetsByEntry[fileInfo.relname] ?? [] +} + +/** + * @param {object} params + * @param {string} params.dest + * @param {esbuild.BuildResult} params.result + * @param {boolean} params.shouldWrite + */ +export async function writeMetafile ({ dest, result, shouldWrite }) { + if (!result.metafile || !shouldWrite) return + + await writeFile(join(dest, 'domstack-esbuild-meta.json'), JSON.stringify(result.metafile, null, ' ')) +} + +/** + * @param {object} params + * @param {string} params.dest + * @param {esbuild.BuildResult} params.result + * @param {SiteData} params.siteData + * @param {string} params.src + * @returns {OutputMap} + */ +export function applyBuildOutputMap ({ dest, result, siteData, src }) { + const extracted = result.metafile + ? extractBuildOutputs(result.metafile, src, dest) + : { outputMap: {}, byEntry: {}, defaultClient: null, defaultStyle: null, defaultAssets: [] } + updateSiteDataOutputPaths(extracted, siteData) + return extracted.outputMap +} diff --git a/lib/build-esbuild/options.js b/lib/build-esbuild/options.js new file mode 100644 index 00000000..3d98542e --- /dev/null +++ b/lib/build-esbuild/options.js @@ -0,0 +1,265 @@ +/** + * @import esbuild from 'esbuild' + * @import { DomStackOpts, SiteData } from '../builder.js' + */ + +import { Worker } from 'node:worker_threads' +import { join } from 'node:path' +import { globalBundleAssets, pageBundleAssets, layoutBundleAssets } from '../file-conventions.js' +import { resolveVars } from '../build-pages/vars/resolve-vars.js' +import { + DEFAULT_DOMSTACK_MANIFEST_FILENAME, + isDomstackManifestEnabled, +} from '../domstack-manifest/index.js' +import { importFile } from '#helpers/import-file.js' + +const __dirname = import.meta.dirname +const DOM_STACK_DEFAULTS_PREFIX = 'domstack-defaults' +const SERVICE_WORKER_OUTPUT_RELNAME = 'service-worker.js' + +/** + * @typedef {esbuild.Format} EsbuildFormat + * @typedef {esbuild.LogLevel} EsbuildLogLevel + * @typedef {esbuild.BuildOptions} EsbuildBuildOptions + * @typedef {{ define?: Record, manifestVersion?: string }} ServiceWorkerBuildDefines + */ + +/** + * Resolve `global.vars.*`'s `browser` export in a fresh worker thread so watch + * mode reloads changes without caching `global.vars.*` on the main thread. + * + * @param {string | undefined} varsPath + * @returns {Promise>} + */ +function resolveBrowserVarsInWorker (varsPath) { + if (!varsPath) return Promise.resolve({}) + + return new Promise((resolve, reject) => { + const worker = new Worker(join(__dirname, 'browser-vars-worker.js'), { + workerData: { varsPath }, + }) + + let settled = false + /** @param {Record} value */ + const settleResolve = (value) => { + if (settled) return + settled = true + resolve(value) + } + /** @param {unknown} err */ + const settleReject = (err) => { + if (settled) return + settled = true + reject(err) + } + + worker.once('message', settleResolve) + worker.once('error', settleReject) + worker.once('exit', (code) => { + if (settled) return + settleReject(new Error( + code !== 0 + ? `Browser vars worker stopped with exit code ${code}` + : 'Browser vars worker exited with code 0 without posting a result' + )) + }) + }) +} + +/** + * Create browser-side esbuild options from siteData + opts. + * The root service worker intentionally uses a separate build derived from these base options. + * + * @param {string} src + * @param {string} dest + * @param {SiteData} siteData + * @param {DomStackOpts | null} opts + * @param {{ watch?: boolean }} [modeOpts] + * @returns {Promise} + */ +export async function createBrowserBuildOpts (src, dest, siteData, opts, modeOpts = {}) { + const entryPoints = /** @type {(string | { in: string, out: string })[]} */ (globalBundleAssets(siteData).map(asset => join(src, asset.relname))) + + if (siteData.defaultLayout) { + entryPoints.push( + { in: join(__dirname, '../defaults/default.style.css'), out: join(DOM_STACK_DEFAULTS_PREFIX, 'default.style.css') }, + { in: join(__dirname, '../defaults/default.client.js'), out: join(DOM_STACK_DEFAULTS_PREFIX, 'default.client.js') } + ) + } + + for (const page of siteData.pages) { + for (const asset of pageBundleAssets(page)) entryPoints.push(join(src, asset.relname)) + } + + for (const layout of Object.values(siteData.layouts)) { + for (const asset of layoutBundleAssets(layout)) entryPoints.push(join(src, asset.relname)) + } + + const target = Array.isArray(opts?.target) ? opts.target : [] + + const watch = modeOpts.watch ?? false + const browserDefines = watch + ? await resolveBrowserVarsInWorker(siteData?.globalVars?.filepath) + : Object.fromEntries( + Object.entries(await resolveVars({ + varsPath: siteData?.globalVars?.filepath, + key: 'browser', + })).map(([k, v]) => [k, JSON.stringify(v)]) + ) + + /** @type {{ [varName: string]: string }} */ + const domstackDefines = createDomstackDefines({ opts, siteData, watch }) + /** @type {{ [varName: string]: string }} */ + const define = { ...domstackDefines } + for (const [k, v] of Object.entries(browserDefines)) { + if (Object.hasOwn(define, k)) { + throw new Error(`Conflict: "${k}" is reserved by domstack.`) + } + define[k] = v + } + + /** @type {esbuild.BuildOptions} */ + const buildOpts = { + entryPoints, + /** @type {EsbuildLogLevel} */ + logLevel: 'silent', + bundle: true, + write: true, + /** @type {EsbuildFormat} */ + format: 'esm', + splitting: true, + sourcemap: true, + outdir: dest, + outbase: src, + target, + define, + metafile: true, + // In watch mode use stable unhashed entry filenames so page HTML references remain stable. + // Shared chunks still use content hashes so watch stays close to production behavior. + entryNames: watch ? '[dir]/[name]' : '[dir]/[name]-[hash]', + chunkNames: 'chunks/[ext]/[name]-[hash]', + loader: { + '.png': 'dataurl', + '.jpg': 'dataurl', + '.jpeg': 'dataurl', + '.gif': 'dataurl', + '.svg': 'dataurl', + '.webp': 'dataurl', + '.avif': 'dataurl', + '.ico': 'file', + '.woff': 'file', + '.woff2': 'file', + '.ttf': 'file', + '.eot': 'file', + '.otf': 'file', + } + } + + const esbuildSettingsExtends = siteData.esbuildSettings + ? (await importFile(siteData.esbuildSettings.filepath)).default + : (/** @type {typeof buildOpts} */ esbuildOpts) => esbuildOpts + + const extendedBuildOpts = await esbuildSettingsExtends(buildOpts) + + if (Object.keys(browserDefines).length > 0 && extendedBuildOpts.define !== buildOpts.define) { + throw new Error( + 'Conflict: both the "browser" export in global.vars and "define" in esbuild.settings are set. ' + + 'Use one or the other to define browser constants.' + ) + } + + return { + ...extendedBuildOpts, + define: preserveDomstackDefines(extendedBuildOpts.define, domstackDefines), + } +} + +/** + * Keep domstack-owned browser build facts available even when esbuild.settings + * replaces the define object. User settings may add custom defines, but they may + * not override domstack's reserved DOMSTACK_* values. + * + * @param {esbuild.BuildOptions['define']} define + * @param {{ [varName: string]: string }} domstackDefines + * @returns {{ [varName: string]: string }} + */ +function preserveDomstackDefines (define, domstackDefines) { + const mergedDefine = { ...(define ?? {}) } + + for (const [key, value] of Object.entries(domstackDefines)) { + if (Object.hasOwn(mergedDefine, key) && mergedDefine[key] !== value) { + throw new Error(`Conflict: "${key}" is reserved by domstack.`) + } + mergedDefine[key] = value + } + + return mergedDefine +} + +/** + * Production entry filenames are content-hashed globally. Service workers need + * a stable root URL, so they get a tiny second build with a fixed entry name. + * Emitting at /service-worker.js also gives the worker root scope by default. + * + * @param {object} params + * @param {esbuild.BuildOptions} params.buildOpts + * @param {ServiceWorkerBuildDefines} params.defines + * @param {NonNullable} params.serviceWorker + * @param {string} params.src + * @returns {esbuild.BuildOptions} + */ +export function createServiceWorkerBuildOpts ({ buildOpts, defines, serviceWorker, src }) { + return { + ...buildOpts, + define: createServiceWorkerDefineMap(buildOpts.define, defines), + entryPoints: [ + { + in: join(src, serviceWorker.relname), + out: 'service-worker', + }, + ], + entryNames: '[name]', + splitting: false, + } +} + +/** + * @param {esbuild.BuildOptions['define']} baseDefine + * @param {ServiceWorkerBuildDefines} defines + * @returns {{ [varName: string]: string }} + */ +function createServiceWorkerDefineMap (baseDefine, defines) { + const define = { ...(baseDefine ?? {}) } + const serviceWorkerDefine = defines.define ?? {} + + for (const [key, value] of Object.entries(serviceWorkerDefine)) { + if (Object.hasOwn(define, key) && define[key] !== value) { + throw new Error(`Conflict: "${key}" is already defined for the service-worker build.`) + } + define[key] = value + } + + define['process.env.DOMSTACK_MANIFEST_VERSION'] = JSON.stringify(defines.manifestVersion ?? '') + return define +} + +/** + * Provide domstack-owned build facts to all browser-side bundles. + * + * @param {object} params + * @param {DomStackOpts | null} params.opts + * @param {SiteData} params.siteData + * @param {boolean} params.watch + */ +function createDomstackDefines ({ opts, siteData, watch }) { + const hasServiceWorker = Boolean(siteData.serviceWorker) + const domstackManifestSettingsPath = siteData?.domstackManifestSettings?.filepath + + return { + 'process.env.DOMSTACK_MANIFEST_URL': JSON.stringify(`/${DEFAULT_DOMSTACK_MANIFEST_FILENAME}`), + 'process.env.DOMSTACK_MANIFEST_VERSION': JSON.stringify(''), + 'process.env.DOMSTACK_MANIFEST_ENABLED': JSON.stringify(String(!watch && isDomstackManifestEnabled({ domstackManifestSettingsPath, opts: opts ?? undefined }))), + 'process.env.DOMSTACK_SERVICE_WORKER_URL': JSON.stringify(hasServiceWorker ? `/${SERVICE_WORKER_OUTPUT_RELNAME}` : ''), + 'process.env.DOMSTACK_SERVICE_WORKER_SCOPE': JSON.stringify(hasServiceWorker ? '/' : ''), + } +} diff --git a/lib/build-esbuild/outputs.js b/lib/build-esbuild/outputs.js new file mode 100644 index 00000000..528fe779 --- /dev/null +++ b/lib/build-esbuild/outputs.js @@ -0,0 +1,87 @@ +/** + * @import esbuild from 'esbuild' + * @import { SiteData } from '../builder.js' + * @import { DomstackManifestKind, DomstackManifestRecord } from '../domstack-manifest/index.js' + */ + +import { extname, relative, resolve } from 'node:path' +import { createDomstackManifestRecord } from '../domstack-manifest/index.js' +import { toPosix } from '#helpers/path.js' + +/** + * @param {object} params + * @param {string} params.src + * @param {string} params.dest + * @param {SiteData} params.siteData + * @param {esbuild.BuildResult} params.buildResults + * @param {boolean} params.includeMetafileRecord + * @returns {DomstackManifestRecord[]} + */ +export function createEsbuildOutputRecords ({ src, dest, siteData, buildResults, includeMetafileRecord }) { + /** @type {DomstackManifestRecord[]} */ + const outputs = [] + const metafile = buildResults.metafile + if (!metafile) return outputs + + const workerOutputRelnames = new Set() + for (const page of siteData.pages) { + if (!page.workers) continue + for (const worker of Object.values(page.workers)) { + if (worker.outputRelname) workerOutputRelnames.add(toPosix(worker.outputRelname)) + } + } + const serviceWorkerOutputRelname = siteData.serviceWorker?.outputRelname + ? toPosix(siteData.serviceWorker.outputRelname) + : undefined + + for (const [outputPath, outputMeta] of Object.entries(metafile.outputs)) { + const filepath = resolve(outputPath) + const outputRelname = toPosix(relative(dest, filepath)) + const kind = classifyEsbuildOutput({ + outputRelname, + entryPoint: outputMeta.entryPoint, + workerOutputRelnames, + serviceWorkerOutputRelname, + }) + + outputs.push(createDomstackManifestRecord({ + dest, + filepath, + outputRelname, + kind, + entryPoint: outputMeta.entryPoint, + sourceRelname: outputMeta.entryPoint ? toPosix(relative(src, resolve(outputMeta.entryPoint))) : undefined, + })) + } + + if (includeMetafileRecord) { + outputs.push(createDomstackManifestRecord({ + dest, + outputRelname: 'domstack-esbuild-meta.json', + kind: 'metadata', + })) + } + + return outputs +} + +/** + * Classify a dest-relative esbuild output. + * + * @param {object} params + * @param {string} params.outputRelname + * @param {string | undefined} params.entryPoint + * @param {Set} params.workerOutputRelnames + * @param {string | undefined} [params.serviceWorkerOutputRelname] + * @returns {DomstackManifestKind} + */ +function classifyEsbuildOutput ({ outputRelname, entryPoint, workerOutputRelnames, serviceWorkerOutputRelname }) { + const ext = extname(outputRelname) + + if (ext === '.map') return 'sourcemap' + if (serviceWorkerOutputRelname && outputRelname === serviceWorkerOutputRelname) return 'service-worker' + if (workerOutputRelnames.has(outputRelname)) return 'worker' + if (ext === '.css') return 'style' + if (ext === '.js' && entryPoint) return 'script' + return 'chunk' +} diff --git a/lib/build-esbuild/watch.js b/lib/build-esbuild/watch.js new file mode 100644 index 00000000..aaa34d8f --- /dev/null +++ b/lib/build-esbuild/watch.js @@ -0,0 +1,168 @@ +/** + * @import { Logger as PinoLogger } from 'pino' + * @import { DomStackOpts, SiteData } from '../builder.js' + * @import { OutputMap } from './metafile.js' + * @import { EsbuildBuildOptions } from './options.js' + */ + +import esbuild from 'esbuild' +import { createDomStackLogger } from '../logger.js' +import { serializeEsbuildError, serializeEsbuildMessage } from './errors.js' +import { applyBuildOutputMap, writeMetafile } from './metafile.js' +import { createBrowserBuildOpts, createServiceWorkerBuildOpts } from './options.js' + +/** + * @typedef {{ dispose: () => Promise }} DisposableBuildContext + */ + +/** + * Create esbuild watch contexts with stable unhashed entry filenames. + * The browser context keeps production-like code splitting. + * The service-worker context is separate and self-contained so watch-mode cleanup can run reliably. + * + * @param {string} src + * @param {string} dest + * @param {SiteData} siteData + * @param {DomStackOpts} opts + * @param {{ onEnd?: (result: esbuild.BuildResult) => void, logger?: PinoLogger }} [watchOpts] + * @returns {Promise<{ context: DisposableBuildContext, outputMap: OutputMap, buildResults: esbuild.BuildResult, buildOpts: EsbuildBuildOptions }>} + */ +export async function buildEsbuildWatch (src, dest, siteData, opts, watchOpts = {}) { + const logger = watchOpts.logger ?? opts.logger ?? createDomStackLogger() + const extendedBuildOpts = await createBrowserBuildOpts(src, dest, siteData, opts, { watch: true }) + const browserWatch = await createWatchBuild({ + buildOpts: extendedBuildOpts, + dest, + label: 'JS/CSS', + logger, + onEnd: watchOpts.onEnd, + shouldWriteMetafile: opts?.metafile !== false, + }) + + const initialResult = browserWatch.initialResult + + /** @type {esbuild.BuildContext[]} */ + const contexts = [browserWatch.context] + try { + const outputMap = applyBuildOutputMap({ dest, result: initialResult, siteData, src }) + + if (siteData.serviceWorker) { + // Keep service-worker-only defines and no-policy watch cleanup behavior out of browser bundles. + const serviceWorkerBuildOpts = createServiceWorkerBuildOpts({ + buildOpts: extendedBuildOpts, + defines: {}, + serviceWorker: siteData.serviceWorker, + src, + }) + const serviceWorkerWatch = await createWatchBuild({ + buildOpts: serviceWorkerBuildOpts, + dest, + label: 'Service worker', + logger, + shouldWriteMetafile: false, + }) + contexts.push(serviceWorkerWatch.context) + applyBuildOutputMap({ + dest, + result: serviceWorkerWatch.initialResult, + siteData, + src, + }) + } + + return { + context: createDisposableBuildContext(contexts), + outputMap, + buildResults: initialResult, + buildOpts: extendedBuildOpts, + } + } catch (error) { + const cleanup = await Promise.allSettled(contexts.map(context => context.dispose())) + const failures = cleanup.filter(result => result.status === 'rejected').map(result => result.reason) + if (failures.length) throw new AggregateError([error, ...failures], 'Esbuild watch startup and cleanup failed') + throw error + } +} + +/** + * @param {object} params + * @param {esbuild.BuildOptions} params.buildOpts + * @param {string} params.dest + * @param {string} params.label + * @param {PinoLogger} params.logger + * @param {((result: esbuild.BuildResult) => void | Promise) | undefined} [params.onEnd] + * @param {boolean} params.shouldWriteMetafile + * @returns {Promise<{ context: esbuild.BuildContext, initialResult: esbuild.BuildResult }>} + */ +async function createWatchBuild ({ buildOpts, dest, label, logger, onEnd, shouldWriteMetafile }) { + const initial = Promise.withResolvers() + // Attach a rejection handler before watch() can deliver a failing initial build. + initial.promise.catch(() => {}) + let isInitialBuild = true + const plugins = buildOpts.plugins ?? [] + + /** @type {esbuild.Plugin} */ + const onEndPlugin = { + name: `domstack-${label.toLowerCase().replaceAll(/[^a-z0-9]+/g, '-')}-on-end`, + setup (build) { + build.onEnd(async result => { + const first = isInitialBuild + isInitialBuild = false + try { + if (result.errors.length > 0) { + const failure = Object.assign(new Error(`${label} build failed`), { + errors: result.errors.map(serializeEsbuildMessage), + warnings: result.warnings.map(serializeEsbuildMessage), + }) + if (first) { + initial.reject(failure) + return + } + logger.error({ errors: failure.errors, warnings: failure.warnings }, `${label} rebuild failed`) + } else { + if (result.warnings.length) { + logger.warn({ warnings: result.warnings.map(serializeEsbuildMessage) }, `${label} build warnings`) + } + await writeMetafile({ dest, result, shouldWrite: shouldWriteMetafile }) + if (first) logger.debug(`${label} initial build complete`) + else logger.info(`${label} rebuild complete`) + } + if (first) initial.resolve(result) + else if (onEnd) await onEnd(result) + } catch (error) { + if (first) initial.reject(error) + else logger.error({ err: error }, `${label} rebuild processing failed`) + } + }) + } + } + + const contextOpts = { ...buildOpts, plugins: [...plugins, onEndPlugin] } + + /** @type {esbuild.BuildContext | undefined} */ + let context + try { + context = await esbuild.context(contextOpts) + await context.watch() + const initialResult = await initial.promise + + return { context, initialResult } + } catch (err) { + await context?.dispose() + throw serializeEsbuildError(err) + } +} + +/** + * @param {esbuild.BuildContext[]} contexts + * @returns {DisposableBuildContext} + */ +function createDisposableBuildContext (contexts) { + return { + async dispose () { + const results = await Promise.allSettled(contexts.map(context => context.dispose())) + const errors = results.filter(result => result.status === 'rejected').map(result => result.reason) + if (errors.length) throw new AggregateError(errors, 'Esbuild watch cleanup failed') + }, + } +}