@format.dev/compile 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/cli/cli-spec.mjs +2 -2
- package/dist/server/compile/compile.d.mts.map +1 -1
- package/dist/server/compile/compile.mjs +2 -1
- package/dist/server/compile/compile.mjs.map +1 -1
- package/dist/server/compile/document-assets.d.mts +2 -0
- package/dist/server/compile/document-assets.d.mts.map +1 -1
- package/dist/server/compile/document-assets.mjs +12 -3
- package/dist/server/compile/document-assets.mjs.map +1 -1
- package/dist/server/compile/producer-release.mjs +1 -1
- package/dist/server/utils/suggest-similar.d.mts.map +1 -1
- package/dist/server/vite/plugins/get-styles.d.mts.map +1 -1
- package/dist/server/vite/plugins/get-styles.mjs +1 -1
- package/dist/server/vite/plugins/get-styles.mjs.map +1 -1
- package/dist/shared/types/public/compile.d.mts.map +1 -1
- package/package.json +5 -5
|
@@ -124,7 +124,7 @@ var cli_spec_default = { commands: [{
|
|
|
124
124
|
"field": "validateSchema",
|
|
125
125
|
"flags": "--no-validate-schema",
|
|
126
126
|
"summary": "Disables data validation against your schema when calling render",
|
|
127
|
-
"description": "Disables data validation against your schema when calling render. Switch this off if you plan to validate yourself or are prone to taking risks. [Read more about data and schema](/docs/studio/data-and-variants#schemas).",
|
|
127
|
+
"description": "Disables data validation against your schema when calling render. Switch this off if you plan to validate yourself or are prone to taking risks. Documents without a schema are never validated. [Read more about data and schema](/docs/studio/data-and-variants#schemas).",
|
|
128
128
|
"type": "boolean",
|
|
129
129
|
"defaultValue": true
|
|
130
130
|
},
|
|
@@ -138,7 +138,7 @@ var cli_spec_default = { commands: [{
|
|
|
138
138
|
{
|
|
139
139
|
"field": "clean",
|
|
140
140
|
"flags": "--no-clean",
|
|
141
|
-
"description": "
|
|
141
|
+
"description": "Leaves files already in the output directory in place instead of deleting them. Files from an earlier compile stay on disk, but the new bundle only includes the documents you compile now.",
|
|
142
142
|
"type": "boolean",
|
|
143
143
|
"defaultValue": true
|
|
144
144
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.d.mts","names":[],"sources":["../../../src/server/compile/compile.ts"],"sourcesContent":[],"mappings":";;;;;;;iBAkEgB,gBAAA,SAAyB;iBAIzB,eAAA,SAAwB;iBAMxB,iBAAA;AAVA,iBAcA,oBAAA,CAdyB,MAAY,EAAA,MAAA,EAAA,YAAA,EAAA,MAAA,CAAA,EAAA,MAAA;AAIrC,iBAcA,qBAAA,CAdwB,MAAY,EAAA,MAAA,EAAA,YAAA,EAAA,MAAA,CAAA,EAAA,MAAA;AAMpC,iBAeA,kBAAA,CAfiB,MAAA,EAAA,MAAA,EAAA,YAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA;AAIjB,UAiNC,0BAAA,CAjNmB;EAIpB;EAOA,MAAA,EAAA,MAAA;EAsMC,YAAA,EAAA,MAAA;EAqBK,OAAA,EAAA,MAAA;EAkEL,MAAA,EAlFR,YAkFQ;
|
|
1
|
+
{"version":3,"file":"compile.d.mts","names":[],"sources":["../../../src/server/compile/compile.ts"],"sourcesContent":[],"mappings":";;;;;;;iBAkEgB,gBAAA,SAAyB;iBAIzB,eAAA,SAAwB;iBAMxB,iBAAA;AAVA,iBAcA,oBAAA,CAdyB,MAAY,EAAA,MAAA,EAAA,YAAA,EAAA,MAAA,CAAA,EAAA,MAAA;AAIrC,iBAcA,qBAAA,CAdwB,MAAY,EAAA,MAAA,EAAA,YAAA,EAAA,MAAA,CAAA,EAAA,MAAA;AAMpC,iBAeA,kBAAA,CAfiB,MAAA,EAAA,MAAA,EAAA,YAAA,EAAA,MAAA,EAAA,OAAA,EAAA,MAAA,CAAA,EAAA,MAAA;AAIjB,UAiNC,0BAAA,CAjNmB;EAIpB;EAOA,MAAA,EAAA,MAAA;EAsMC,YAAA,EAAA,MAAA;EAqBK,OAAA,EAAA,MAAA;EAkEL,MAAA,EAlFR,YAkFQ;EA4jBD;EAuDA,YAAA,CAAA,EAAA,OAAA;EAmPM;EAAiB,WAAA,CAAA,EAp7BxB,kBAo7BwB;;;;AAWvC;AA4BA;AAYA;;;;;AAGU,iBA99BY,sBAAA,CA89BZ,IAAA,EA99ByC,0BA89BzC,CAAA,EA99BsE,OA89BtE,CAAA,MAAA,CAAA;AAkBY,UA96BL,kBAAA,CA86BuB;EAC9B,KAAA,EAAA,MAAA,EAAA;EACkC,MAAA,EA96BnC,MA86BmC,CAAA,MAAA,EAAA,MAAA,CAAA,GAAA,IAAA;;;;;AAK5C;;;AAA+D,iBAzX/C,wBAAA,CAyX+C,SAAA,EAzXX,QAyXW,EAAA,EAAA,iBAAA,EAAA,MAAA,EAAA,CAAA,EAzX+B,GAyX/B,CAAA,MAAA,EAAA,MAAA,EAAA,CAAA;;;;;;;;iBAlU/C,2BAAA,UAAqC;iBAmP/B,OAAA,UAAiB,iBAAiB,QAAQ;UAW/C,oBAAA;;;;;;;;;;;;;;;;;;gBAkBF;;;;;;;;;UAUE,mBAAA;WACP;;QAEH;;;;;;;;iBASe,gBAAA,UACZ,gCACM,uBACb,QAAQ;iBAkBW,kBAAA,UACZ;uBACsB,YAAY;IACzC,QAAQ;iBAIW,cAAA,UAAwB,iBAAiB,QAAQ"}
|
|
@@ -326,7 +326,6 @@ async function compileBundle(args) {
|
|
|
326
326
|
throw new Error(`Entry file not found at ${entryFilePath}`);
|
|
327
327
|
}
|
|
328
328
|
const schemaPath = await getSchemaPath(getDocumentDataDir(documentName$1, config));
|
|
329
|
-
if (options.validateSchema && !schemaPath) throw new Error(`Schema file not found. Either use --no-validate-schema to disable schema validation or ensure you are using a valid schema file.`);
|
|
330
329
|
buildDocuments.push({
|
|
331
330
|
name: documentName$1,
|
|
332
331
|
entryFilePath,
|
|
@@ -430,6 +429,8 @@ async function compileBundle(args) {
|
|
|
430
429
|
});
|
|
431
430
|
if (assetMode === "static") {
|
|
432
431
|
const staticAssets = await buildDocumentStaticAssets(sources, resolve(stagingRoot, document.name));
|
|
432
|
+
const unsupportedCount = staticAssets.unsupported.length;
|
|
433
|
+
if (unsupportedCount > 0) logger.warn(`⚠ Skipped ${unsupportedCount} ${pluralize("file", unsupportedCount)} in the assets for ${document.name} that renders can't use: ${staticAssets.unsupported.join(", ")}. Renders accept fonts, images, CSS, and JSON.`);
|
|
433
434
|
if (staticAssets.zip) {
|
|
434
435
|
await mkdir(getDocumentOutDir(outDir, document.name), { recursive: true });
|
|
435
436
|
await writeFile(getDocumentAssetsPath(outDir, document.name), staticAssets.zip);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compile.mjs","names":["error: unknown","documents: HtmlManifestDocument[]","manifest: HtmlManifest","cssInJsVmPrewarm: Promise<void> | null","assetMode: AssetMode","LogLevel","buildDocuments: BuildDocument[]","documentName","format: Format","exportNames","output","gradient","options: NormalizedCompileOptions"],"sources":["../../../src/server/compile/compile.ts"],"sourcesContent":["import { LogLevel, type FormatConfig, type Document } from '../../shared/types'\nimport type { AssetMode, CompileOptions, NormalizedCompileOptions, Format } from '../../shared/types/public'\nimport type { RemoteAssetFetcher } from '@format.dev/zip'\n\nimport { resolve, dirname } from 'node:path'\nimport { mkdir, access, rm, readFile, writeFile, readdir } from 'node:fs/promises'\nimport { builtinModules, createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\nimport { build, mergeConfig } from 'vite'\nimport { scanRemoteRefs, mergeRemoteAssets, findBrokenRemoteAssets, AssetMismatchError } from '@format.dev/zip'\nimport pluralize from 'pluralize'\nimport grad, { atlas as gradient } from 'gradient-string'\n\nimport { getStyles } from '../vite/plugins/get-styles'\nimport { stylesPreProcessor } from '../vite/plugins/styles-pre-processor'\nimport { htmlLoader } from '../vite/plugins/html-loader'\nimport { getSharedAssetsDir, getDocumentsDir, getRootDir, DEFAULT_OUT_DIR_NAME } from '../project/paths'\nimport { createConfig } from '../vite/create-config'\nimport { emitPackageJson } from './package-json'\nimport { getSchemaPath } from '../utils/schema'\nimport { NO_DOCUMENTS_MESSAGE, DEFAULT_VARIANT } from '../../shared/constants'\nimport { RenderWorker } from '../render-worker'\nimport { NO_CONFIG_FILE_MESSAGE } from '../constants'\nimport { normalizeCompileOptions } from './defaults'\nimport {\n\tbuildCacheKeyOptions,\n\tcomputeCacheHash,\n\treadCachedHash,\n\twriteCacheHash,\n\tcachedOutputsExist\n} from './compile-cache'\nimport { DocumentRenderError } from './render-error'\nimport { BUNDLE_ENTRY_POINT_FILE_NAME, SHARED_ASSETS_OUT_DIR_NAME, CHUNKS_DIR_NAME } from './constants'\nimport { createStructuredOutput, type StructuredOutput } from './structured-log'\nimport { makeViteBuildConfig } from './make-config'\nimport { basePackageName } from './dependency-closure'\nimport { compileState } from '../runtime-state'\nimport { engineTarget } from './producer-release'\nimport { warnOnLockstepDrift } from '../utils/warn-lockstep'\nimport { assertProducersAgree } from './producer-agreement'\nimport { getUserProjectDir } from '../project/user-project-dir'\nimport { CompileError } from '../errors'\nimport { bakeWrapperAssetConstants } from './wrapper-source'\n\nimport {\n\tresolveDocumentAssetSources,\n\tbuildDocumentStaticAssets,\n\tbuildDocumentDynamicAssets,\n\tmaterialiseSharedDynamicAssets\n} from './document-assets'\n\nimport { getDocumentDataDir, getDocumentDataFile, getDocuments, getUserDocumentIndex } from '../project/documents'\n\nimport {\n\tlogger,\n\twithPrefixedConsole,\n\tloadConfig,\n\tsetLogLevel,\n\tparseLogLevelFromEnv,\n\tgetLogLevel,\n\tcheckDir\n} from '../utils'\nimport { buildDocumentExportMap } from '@format.dev/cli/scaffold'\n\ntype CompileSource = 'cli' | 'unplugin'\n\nexport function getDefaultOutDir(config: FormatConfig) {\n\treturn resolve(getRootDir(config), DEFAULT_OUT_DIR_NAME)\n}\n\nexport function getBundleOutDir(config: FormatConfig, outDirOverride?: string | null) {\n\treturn outDirOverride != null ? resolve(outDirOverride) : getDefaultOutDir(config)\n}\n\nconst assetsFileName = 'assets.zip'\n\nexport function getDocumentOutDir(outDir: string, documentName: string) {\n\treturn resolve(outDir, documentName)\n}\n\nexport function getDocumentEntryPath(outDir: string, documentName: string) {\n\treturn resolve(getDocumentOutDir(outDir, documentName), BUNDLE_ENTRY_POINT_FILE_NAME)\n}\n\nexport function getDocumentAssetsPath(outDir: string, documentName: string) {\n\treturn resolve(getDocumentOutDir(outDir, documentName), assetsFileName)\n}\n\nconst INDEX_HTML_FILE_NAME = 'index.html'\nconst MANIFEST_FILE_NAME = 'manifest.json'\n\nexport function getHtmlVariantPath(outDir: string, documentName: string, variant: string) {\n\treturn resolve(getDocumentOutDir(outDir, documentName), variant, INDEX_HTML_FILE_NAME)\n}\n\ninterface HtmlManifestVariant {\n\tvariant: string\n\thtml: string\n}\n\ninterface HtmlManifestDocument {\n\tdocument: string\n\tassets?: string\n\tvariants: HtmlManifestVariant[]\n}\n\ninterface HtmlManifest {\n\toutput: 'html'\n\tengine: string\n\tdocuments: HtmlManifestDocument[]\n}\n\nconst REMOTE_ASSETS_DOCS_URL = 'https://format.dev/docs/authoring/assets#remote-assets'\n\n/**\n * Post-render remote-reference pass (static mode). PDF generation never\n * fetches remote references at render time, so anything the rendered HTML\n * points at over http(s) must either be fetched into the document's zip now\n * (`remoteAssets` on) or flagged — without it, the reference is missing from\n * every generated PDF.\n */\nasync function processRemoteAssetRefs(args: {\n\thtml: string\n\tdocumentName: string\n\toutDir: string\n\tremoteAssets: boolean\n\t/** Replaces the network fetch for each remote reference. Studio passes a session cache. */\n\tremoteFetch?: RemoteAssetFetcher\n\t/** Report progress at debug level only. Set for builds the user didn't ask for. */\n\tquiet?: boolean\n}) {\n\tconst { html, documentName, outDir, remoteAssets, remoteFetch, quiet } = args\n\n\tconst remoteRefs = scanRemoteRefs(html)\n\n\tif (remoteRefs.length === 0) {\n\t\treturn\n\t}\n\n\tif (!remoteAssets) {\n\t\tconst list = remoteRefs.map(url => ` • ${url}`).join('\\n')\n\n\t\tlogger.warn(\n\t\t\t`Document \"${documentName}\" references remote assets that will be missing from generated PDFs — remote references are never fetched at render time:\\n${list}\\n` +\n\t\t\t\t`Compile with --remote-assets to fetch and bundle them, or reference local files instead. ${REMOTE_ASSETS_DOCS_URL}`\n\t\t)\n\t\treturn\n\t}\n\n\tconst assetsPath = getDocumentAssetsPath(outDir, documentName)\n\tconst existing = await readFile(assetsPath).catch(() => undefined)\n\n\tconst merged = await mergeRemoteAssets({\n\t\thtml,\n\t\tzip: existing,\n\t\toptions: remoteFetch ? { remoteAssets: { fetch: remoteFetch } } : undefined\n\t})\n\n\tif (merged && merged !== existing) {\n\t\tawait mkdir(getDocumentOutDir(outDir, documentName), { recursive: true })\n\t\tawait writeFile(assetsPath, merged)\n\n\t\tconst message = `Bundled remote assets referenced by \"${documentName}\" into its assets.zip`\n\n\t\tif (quiet) {\n\t\t\tlogger.debug(message)\n\t\t} else {\n\t\t\tlogger.info(message)\n\t\t}\n\t}\n}\n\n/**\n * Every real source file the bundler read, taken from the build's own module\n * graph. Virtual ids and dependencies are dropped: a `virtual:` id is not a\n * file to stat, and `node_modules` changes only on an install, which the\n * bundler's own cache invalidation already covers.\n */\nfunction collectModuleIds(buildOutput: unknown): string[] {\n\tconst outputs = Array.isArray(buildOutput) ? buildOutput : [buildOutput]\n\tconst ids = new Set<string>()\n\n\tfor (const result of outputs) {\n\t\tconst chunks = (result as { output?: Array<{ moduleIds?: string[] }> } | null)?.output ?? []\n\n\t\tfor (const chunk of chunks) {\n\t\t\tfor (const id of chunk.moduleIds ?? []) {\n\t\t\t\tif (isRealSourceFile(id)) {\n\t\t\t\t\tids.add(id)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...ids]\n}\n\nfunction isRealSourceFile(id: string): boolean {\n\tif (!id.startsWith('/') && !/^[A-Za-z]:[\\\\/]/.test(id)) {\n\t\treturn false\n\t}\n\n\tif (id.includes('\\u0000') || id.includes('node_modules')) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\ninterface RenderVariantWithWorkerArgs {\n\trenderWorker: RenderWorker\n\toutDir: string\n\tdocumentName: string\n\tvariant: string\n\tconfig: FormatConfig\n\tassetMode: AssetMode\n\t/**\n\t * Probe the remote URLs a local-asset mismatch carries, so one error reports\n\t * every unresolvable asset rather than only the local ones. Only meaningful\n\t * where remote references are being fetched at all.\n\t */\n\tprobeRemoteOnMismatch: boolean\n\t/** Replaces the network fetch used by that probe. */\n\tremoteFetch?: RemoteAssetFetcher\n}\n\n/**\n * Render one compiled document variant on an already-running strict worker.\n * Shared by the build-time smoke render and {@link renderCompiledDocument},\n * so both report a failure the same way.\n */\nasync function renderVariantWithWorker(args: RenderVariantWithWorkerArgs): Promise<string> {\n\tconst { renderWorker, outDir, documentName, variant, config, assetMode, probeRemoteOnMismatch, remoteFetch } = args\n\n\tconst data = await getDocumentDataFile(documentName, variant, config)\n\n\ttry {\n\t\treturn await renderWorker.compileRender({\n\t\t\tbundlePath: getDocumentEntryPath(outDir, documentName),\n\t\t\tdocumentName,\n\t\t\tdata: data || {},\n\t\t\tcwd: getDocumentOutDir(outDir, documentName)\n\t\t})\n\t} catch (error: unknown) {\n\t\tlogger.error(`Compiled bundle failed to render document \"${documentName}\" (variant \"${variant}\")`, error)\n\n\t\tconst errData =\n\t\t\terror && typeof error === 'object' && 'data' in error ? (error as { data?: unknown }).data : undefined\n\n\t\tif (errData !== undefined) {\n\t\t\tlogger.error('Error data', errData)\n\t\t}\n\n\t\tconst mismatch = error as { missing?: unknown; known?: unknown; remoteRefs?: unknown }\n\t\tconst isLocalMismatch = Array.isArray(mismatch.missing) && Array.isArray(mismatch.remoteRefs)\n\n\t\tconst renderFailure =\n\t\t\tisLocalMismatch && probeRemoteOnMismatch\n\t\t\t\t? await enrichWithBrokenRemotes({ documentName, assetMode, mismatch, error, remoteFetch })\n\t\t\t\t: error\n\n\t\tthrow new DocumentRenderError({ documentName, variant, cause: renderFailure })\n\t}\n}\n\nasync function enrichWithBrokenRemotes(args: {\n\tdocumentName: string\n\tassetMode: AssetMode\n\tmismatch: { missing?: unknown; known?: unknown; remoteRefs?: unknown }\n\terror: unknown\n\tremoteFetch?: RemoteAssetFetcher\n}): Promise<unknown> {\n\tconst { documentName, assetMode, mismatch, error, remoteFetch } = args\n\n\tconst brokenRemote = await findBrokenRemoteAssets({ urls: mismatch.remoteRefs as string[], fetch: remoteFetch })\n\n\tif (brokenRemote.length === 0) {\n\t\treturn error\n\t}\n\n\treturn new AssetMismatchError({\n\t\tdocumentName,\n\t\tmode: assetMode as 'static' | 'dynamic',\n\t\tmissing: mismatch.missing as string[],\n\t\tknown: Array.isArray(mismatch.known) ? (mismatch.known as string[]) : [],\n\t\tbrokenRemote\n\t})\n}\n\nexport interface RenderCompiledDocumentArgs {\n\t/** The bundle output directory a previous compile wrote. */\n\toutDir: string\n\tdocumentName: string\n\tvariant: string\n\tconfig: FormatConfig\n\t/** Fetch the rendered HTML's remote references into the document's `assets.zip`. */\n\tremoteAssets?: boolean\n\t/** Replaces the network fetch for those references. Studio passes a session cache. */\n\tremoteFetch?: RemoteAssetFetcher\n}\n\n/**\n * Render one variant of an already-compiled document and bundle the remote\n * references its HTML carries, without rebuilding the bundle.\n *\n * `compileBundle` runs this same render inline against its own long-lived\n * worker, one per build. This entry point owns a worker of its own, for callers\n * holding a bundle from an earlier compile — Studio renders each variant this\n * way rather than recompiling per download.\n */\nexport async function renderCompiledDocument(args: RenderCompiledDocumentArgs): Promise<string> {\n\tconst { outDir, documentName, variant, config, remoteAssets = false, remoteFetch } = args\n\n\tconst renderWorker = new RenderWorker({\n\t\tlog: msg => logger.debug(msg),\n\t\twarn: msg => logger.warn(msg),\n\t\tallowedReadPaths: [outDir],\n\t\tsandbox: 'strict'\n\t})\n\n\ttry {\n\t\tconst html = await renderVariantWithWorker({\n\t\t\trenderWorker,\n\t\t\toutDir,\n\t\t\tdocumentName,\n\t\t\tvariant,\n\t\t\tconfig,\n\t\t\tassetMode: 'static',\n\t\t\tprobeRemoteOnMismatch: remoteAssets,\n\t\t\tremoteFetch\n\t\t})\n\n\t\tawait processRemoteAssetRefs({ html, documentName, outDir, remoteAssets, remoteFetch })\n\n\t\treturn html\n\t} finally {\n\t\tawait renderWorker.dispose()\n\t}\n}\n\ntype BuildDocument = {\n\tname: string\n\tentryFilePath: string\n\tschemaPath?: string\n\texportName: string\n}\n\ninterface CompileBundleArgs {\n\tdocumentNames: string[]\n\tconfig: FormatConfig\n\toptions: NormalizedCompileOptions\n\tlogLevel: LogLevel\n\tsource: CompileSource\n\t/** Variant rendered by the node-target smoke test. Defaults to the default variant. */\n\tsmokeVariant?: string\n\t/** When provided, the smoke render writes each document's rendered HTML here, keyed by name. */\n\tcapturedHtml?: Map<string, string>\n\t/**\n\t * When provided, each document's computed asset state (known set + dynamic URL\n\t * map) is written here, keyed by name. The unplugin/Next.js paths read it back\n\t * to re-host assets, instead of re-deriving the map from the output on disk.\n\t */\n\tcapturedAssetState?: Map<string, DocumentAssetState>\n\t/** Per-document variant lists to render and write under output: 'html'. */\n\thtmlVariantMatrix?: Map<string, string[]>\n\t/** When provided, every source file the bundler read is added here (Studio, to invalidate its cache). */\n\tcapturedInputs?: Set<string>\n\t/** Replaces the network fetch for remote references (Studio's session cache). */\n\tremoteFetch?: RemoteAssetFetcher\n\t/**\n\t * Drop the progress and success reporting this compile would otherwise print.\n\t * Warnings and errors still go out, and `FORMAT_DEBUG` still shows everything.\n\t */\n\tquiet?: boolean\n}\n\nexport interface DocumentAssetState {\n\tknown: string[]\n\turlMap: Record<string, string> | null\n}\n\nasync function collectExternals(outDir: string, documentNames: string[]): Promise<string[]> {\n\tconst externals = new Set<string>()\n\tconst importRe = /(?:import|from)\\s+[\"']([^./][^\"']*)[\"']/g\n\n\tconst isNodeBuiltin = (specifier: string) => specifier.startsWith('node:') || builtinModules.includes(specifier)\n\n\tconst scanFile = async (filePath: string) => {\n\t\ttry {\n\t\t\tconst content = await readFile(filePath, 'utf-8')\n\t\t\tlet match\n\n\t\t\twhile ((match = importRe.exec(content)) !== null) {\n\t\t\t\tconst pkg = basePackageName(match[1]!)\n\n\t\t\t\tif (!isNodeBuiltin(pkg)) {\n\t\t\t\t\texternals.add(pkg)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// file may not exist\n\t\t}\n\t}\n\n\tfor (const name of documentNames) {\n\t\tawait scanFile(resolve(outDir, name, BUNDLE_ENTRY_POINT_FILE_NAME))\n\t}\n\n\tconst chunksDir = resolve(outDir, 'chunks')\n\tconst chunkFiles = await readdir(chunksDir).catch(() => [] as string[])\n\n\tfor (const file of chunkFiles) {\n\t\tif (file.endsWith('.js')) {\n\t\t\tawait scanFile(resolve(chunksDir, file))\n\t\t}\n\t}\n\n\treturn [...externals].sort()\n}\n\n/**\n * HTML output ships only HTML, each document's `assets.zip`, and the manifest.\n * Remove the JS renderer artefacts left by the node build we rendered from: the\n * per-document wrappers, the bundle index, `package.json`, `externals.json`, the\n * shared chunks, and the root stylesheets (their CSS is already inlined into the\n * rendered HTML).\n */\nasync function stripJsArtefacts(outDir: string, documents: BuildDocument[]) {\n\tconst removals = documents.map(document => rm(getDocumentEntryPath(outDir, document.name), { force: true }))\n\n\tremovals.push(\n\t\trm(resolve(outDir, BUNDLE_ENTRY_POINT_FILE_NAME), { force: true }),\n\t\trm(resolve(outDir, 'package.json'), { force: true }),\n\t\trm(resolve(outDir, 'externals.json'), { force: true }),\n\t\trm(resolve(outDir, CHUNKS_DIR_NAME), { recursive: true, force: true })\n\t)\n\n\tconst rootEntries = await readdir(outDir, { withFileTypes: true }).catch(() => [])\n\n\tfor (const entry of rootEntries) {\n\t\tconst isRootStylesheet = entry.isFile() && entry.name.endsWith('.css')\n\n\t\tif (isRootStylesheet) {\n\t\t\tremovals.push(rm(resolve(outDir, entry.name), { force: true }))\n\t\t}\n\t}\n\n\tawait Promise.all(removals)\n}\n\n/**\n * Finalise HTML output: drop the JS artefacts and write the manifest grouping\n * each document's variants with the single shared zip they render from.\n */\nasync function writeHtmlOutput(args: {\n\toutDir: string\n\tbuildDocuments: BuildDocument[]\n\thtmlVariantEntries: Map<string, HtmlManifestVariant[]>\n}) {\n\tconst { outDir, buildDocuments, htmlVariantEntries } = args\n\n\tawait stripJsArtefacts(outDir, buildDocuments)\n\n\tconst documents: HtmlManifestDocument[] = []\n\n\tfor (const document of buildDocuments) {\n\t\tconst variants = htmlVariantEntries.get(document.name) ?? []\n\n\t\t// Checked on disk so a document whose zip came only from remote-asset\n\t\t// fetching (no local assets) is still listed correctly.\n\t\tconst assetsPath = getDocumentAssetsPath(outDir, document.name)\n\t\tconst hasAssets = await access(assetsPath).then(\n\t\t\t() => true,\n\t\t\t() => false\n\t\t)\n\n\t\tdocuments.push({\n\t\t\tdocument: document.name,\n\t\t\t...(hasAssets ? { assets: `${document.name}/${assetsFileName}` } : {}),\n\t\t\tvariants\n\t\t})\n\t}\n\n\tconst manifest: HtmlManifest = {\n\t\toutput: 'html',\n\t\tengine: engineTarget,\n\t\tdocuments\n\t}\n\n\tawait writeFile(resolve(outDir, MANIFEST_FILE_NAME), JSON.stringify(manifest, null, '\\t'), 'utf-8')\n}\n\nlet cssInJsVmPrewarm: Promise<void> | null = null\n\n/**\n * Pre-warm the module wyw-in-js loads when it evaluates CSS-in-JS.\n *\n * wyw-in-js extracts styles by running each component in a happy-dom VM, and\n * happy-dom loads Node's built-in `node:vm` the first time it builds a window.\n * Rolldown transforms modules in parallel, so two CSS-in-JS files can trigger\n * that load at the same instant — one `require()` then catches `node:vm`\n * mid-`import()` and Node throws \"Cannot require() ES Module node:vm because it\n * is not yet fully loaded\". Loading the graph once here, sequentially, fills the\n * module cache so the concurrent loads read from it instead of racing the\n * loader. `node:vm` is the module that actually races and is always resolvable;\n * happy-dom is what drags it in, so we warm that too when it resolves through\n * wyw-in-js. Cached so repeat builds in one process pay the cost only once.\n */\nfunction prewarmCssInJsVm(): Promise<void> {\n\tif (!cssInJsVmPrewarm) {\n\t\tcssInJsVmPrewarm = warmCssInJsVm()\n\t}\n\n\treturn cssInJsVmPrewarm\n}\n\nasync function warmCssInJsVm(): Promise<void> {\n\tawait import('node:vm')\n\n\ttry {\n\t\tconst requireFromStudio = createRequire(import.meta.url)\n\t\tconst requireFromVite = createRequire(requireFromStudio.resolve('@wyw-in-js/vite'))\n\t\tconst requireFromTransform = createRequire(requireFromVite.resolve('@wyw-in-js/transform'))\n\t\tconst happyDomEntry = requireFromTransform.resolve('happy-dom')\n\n\t\tawait import(pathToFileURL(happyDomEntry).href)\n\t} catch {\n\t\t// happy-dom may not resolve (e.g. a wyw-in-js version that no longer bundles\n\t\t// it). Warming node:vm above already covers the documented race.\n\t}\n}\n\nasync function compileBundle(args: CompileBundleArgs): Promise<StructuredOutput[]> {\n\tconst { documentNames, config, options, logLevel, source } = args\n\tconst { outDir: outDirOverride } = options\n\n\tconst isBrowserTarget = options.target === 'browser'\n\tconst isWorkerTarget = options.target === 'worker'\n\n\tconst assetMode: AssetMode = options.assets\n\tconst isHtmlOutput = options.output === 'html'\n\n\tconst isCli = source === 'cli'\n\tconst isUnplugin = source === 'unplugin'\n\n\tlogger.debug('Compile bundle context', {\n\t\tsource,\n\t\ttarget: options.target,\n\t\tuserBundler: options.userBundler\n\t})\n\n\tconst outDir = getBundleOutDir(config, outDirOverride)\n\tconst rootDir = getRootDir(config)\n\n\tif (resolve(outDir) === resolve(rootDir)) {\n\t\tthrow new CompileError(\n\t\t\t'outDir cannot be the same directory as rootDir. Please choose a different output directory before bundling.'\n\t\t)\n\t}\n\n\tif (options.clean) {\n\t\tawait rm(outDir, { recursive: true, force: true })\n\t}\n\n\tawait mkdir(outDir, { recursive: true })\n\n\tconst startTime = performance.now()\n\n\t// Never minify bundles for unplugin builds (user's bundler can choose to minify)\n\tconst shouldMinify = isUnplugin ? false : logLevel !== LogLevel.DEBUG\n\n\tconst exportNames = buildDocumentExportMap(documentNames)\n\tconst buildDocuments: BuildDocument[] = []\n\n\tfor (const documentName of documentNames) {\n\t\tconst entryFilePath = await getUserDocumentIndex({ documentName, config })\n\n\t\ttry {\n\t\t\tawait access(entryFilePath)\n\t\t} catch {\n\t\t\tthrow new Error(`Entry file not found at ${entryFilePath}`)\n\t\t}\n\n\t\tconst dataDir = getDocumentDataDir(documentName, config)\n\t\tconst schemaPath = await getSchemaPath(dataDir)\n\n\t\tif (options.validateSchema && !schemaPath) {\n\t\t\tthrow new Error(\n\t\t\t\t`Schema file not found. Either use --no-validate-schema to disable schema validation or ensure you are using a valid schema file.`\n\t\t\t)\n\t\t}\n\n\t\tbuildDocuments.push({\n\t\t\tname: documentName,\n\t\t\tentryFilePath,\n\t\t\tschemaPath: schemaPath ?? undefined,\n\t\t\texportName: exportNames.get(documentName)!\n\t\t})\n\t}\n\n\tconst { baseViteConfig, frameworkPlugins, stylePlugins } = createConfig()\n\n\t// Need fresh plugin instances per build, so state is _not_ cached between builds.\n\tconst makePlugins = () => [\n\t\thtmlLoader(),\n\t\tstylesPreProcessor(options.inlineRemoteCss),\n\t\t...frameworkPlugins,\n\t\t...stylePlugins,\n\t\tgetStyles()\n\t]\n\n\tconst format: Format = options.cjs ? 'cjs' : 'es'\n\n\tconst commonConfig = {\n\t\tdocuments: buildDocuments,\n\t\tcompiledFileName: BUNDLE_ENTRY_POINT_FILE_NAME,\n\t\tshouldMinify,\n\t\tformat,\n\t\tlogger,\n\t\temittedAssetsDir: SHARED_ASSETS_OUT_DIR_NAME,\n\t\tassetMode,\n\t\tconfig,\n\t\toptions,\n\t\tsource\n\t}\n\n\tconst buildTarget = isBrowserTarget ? 'browser' : isWorkerTarget ? 'worker' : 'node'\n\n\tconst buildConfig = makeViteBuildConfig({\n\t\t...commonConfig,\n\t\tplugins: makePlugins(),\n\t\ttarget: buildTarget,\n\t\toutDir\n\t})\n\n\tawait prewarmCssInJsVm()\n\n\t// All documents build in one Vite pass, so a build error doesn't say which\n\t// document broke. Best effort: match the failing module's path (or the error\n\t// message) against each document's directory.\n\tconst findDocumentForBuildError = (error: unknown): string | undefined => {\n\t\tconst errorShape = error as { id?: unknown; loc?: { file?: unknown }; message?: unknown } | null\n\t\tconst candidates = [errorShape?.id, errorShape?.loc?.file, errorShape?.message].filter(\n\t\t\t(value): value is string => typeof value === 'string'\n\t\t)\n\n\t\tconst failing = buildDocuments.find(document =>\n\t\t\tcandidates.some(candidate => candidate.includes(dirname(document.entryFilePath)))\n\t\t)\n\n\t\treturn failing?.name\n\t}\n\n\ttry {\n\t\tconst buildOutput = await build(mergeConfig(baseViteConfig, buildConfig))\n\n\t\tfor (const id of collectModuleIds(buildOutput)) {\n\t\t\targs.capturedInputs?.add(id)\n\t\t}\n\t} catch (error) {\n\t\tconst failingDocument = findDocumentForBuildError(error)\n\t\tconst documentLabel = failingDocument ? ` while building document \"${failingDocument}\"` : ''\n\n\t\tlogger.error(`Vite/Rollup Build Error${documentLabel}:`, error)\n\t\tthrow error\n\t}\n\n\tawait emitPackageJson(outDir, options.bundleName, format, options.version)\n\n\tconst writeBundleIndex = async (targetOutDir: string, bundleFormat: Format) => {\n\t\tconst exportNames = buildDocuments.map(doc => doc.exportName)\n\n\t\tif (bundleFormat === 'cjs') {\n\t\t\tconst requireLines = buildDocuments.map(doc => {\n\t\t\t\tconst relPath = `./${doc.name}/${BUNDLE_ENTRY_POINT_FILE_NAME}`.replace(/\\\\/g, '/')\n\t\t\t\treturn `const { ${doc.exportName} } = require(${JSON.stringify(relPath)});`\n\t\t\t})\n\n\t\t\tconst output = [...requireLines, '', `module.exports = { ${exportNames.join(', ')} };`, ''].join('\\n')\n\n\t\t\tawait writeFile(resolve(targetOutDir, BUNDLE_ENTRY_POINT_FILE_NAME), output, 'utf8')\n\t\t\treturn\n\t\t}\n\n\t\tconst importLines = buildDocuments.map(doc => {\n\t\t\tconst relPath = `./${doc.name}/${BUNDLE_ENTRY_POINT_FILE_NAME}`.replace(/\\\\/g, '/')\n\t\t\treturn `import { ${doc.exportName} } from ${JSON.stringify(relPath)};`\n\t\t})\n\t\tconst output = [\n\t\t\t...importLines,\n\t\t\t'',\n\t\t\t`export { ${exportNames.join(', ')} };`,\n\t\t\t`export default { ${exportNames.join(', ')} };`,\n\t\t\t''\n\t\t].join('\\n')\n\n\t\tawait writeFile(resolve(targetOutDir, BUNDLE_ENTRY_POINT_FILE_NAME), output, 'utf8')\n\t}\n\n\tawait writeBundleIndex(outDir, format)\n\n\t// Per-document asset bundling. Static mode zips each document's full merged\n\t// set (shared assets dir + per-doc ./assets/ + Vite-emitted) — no filtering by\n\t// rendered HTML, so any variant renders from a single zip. Dynamic mode\n\t// materialises the files next to the bundle and embeds a URL map instead.\n\tconst stagingRoot = resolve(outDir, '__assets_staging')\n\tconst documentAssetState = new Map<string, DocumentAssetState>()\n\n\t// Dynamic mode shares one `shared-assets/` dir across documents (the\n\t// sharedAssetsDir contents + Vite-emitted images and fonts). Materialise it\n\t// once and reuse its URL map for every document, so nothing is duplicated.\n\tconst sharedDynamicUrlMap =\n\t\tassetMode === 'dynamic'\n\t\t\t? await materialiseSharedDynamicAssets({ config, outDir, sharedAssetsOutDirName: SHARED_ASSETS_OUT_DIR_NAME })\n\t\t\t: {}\n\n\t// Each document's staging dir and output dir are its own, so documents\n\t// materialise in parallel.\n\tconst materialiseDocumentAssets = async (document: BuildDocument): Promise<DocumentAssetState> => {\n\t\tif (assetMode === 'none') {\n\t\t\treturn { known: [], urlMap: null }\n\t\t}\n\n\t\tconst sources = await resolveDocumentAssetSources({\n\t\t\tentryFilePath: document.entryFilePath,\n\t\t\tconfig,\n\t\t\toutDir,\n\t\t\tsharedAssetsOutDirName: SHARED_ASSETS_OUT_DIR_NAME\n\t\t})\n\n\t\tif (assetMode === 'static') {\n\t\t\tconst staticAssets = await buildDocumentStaticAssets(sources, resolve(stagingRoot, document.name))\n\n\t\t\tif (staticAssets.zip) {\n\t\t\t\tawait mkdir(getDocumentOutDir(outDir, document.name), { recursive: true })\n\t\t\t\tawait writeFile(getDocumentAssetsPath(outDir, document.name), staticAssets.zip)\n\t\t\t}\n\n\t\t\treturn { known: staticAssets.known, urlMap: null }\n\t\t}\n\n\t\tconst dynamicAssets = await buildDocumentDynamicAssets({\n\t\t\tdocumentAssetsDir: sources.documentAssetsDir,\n\t\t\tdocumentOutDir: getDocumentOutDir(outDir, document.name),\n\t\t\tsharedUrlMap: sharedDynamicUrlMap\n\t\t})\n\n\t\treturn { known: dynamicAssets.known, urlMap: dynamicAssets.urlMap }\n\t}\n\n\ttry {\n\t\tawait Promise.all(\n\t\t\tbuildDocuments.map(async document => {\n\t\t\t\tdocumentAssetState.set(document.name, await materialiseDocumentAssets(document))\n\t\t\t})\n\t\t)\n\t} finally {\n\t\tawait rm(stagingRoot, { recursive: true, force: true }).catch(() => {})\n\t}\n\n\t// Bake each document's known-asset set (and dynamic URL map) into its\n\t// emitted wrapper. No-op for unplugin builds — their wrapper is generated\n\t// after compile, reading the captured asset state below with the values\n\t// inlined directly.\n\tawait Promise.all(\n\t\tbuildDocuments.map(async document => {\n\t\t\tconst assetState = documentAssetState.get(document.name)\n\n\t\t\tif (!assetState) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\targs.capturedAssetState?.set(document.name, assetState)\n\n\t\t\tawait bakeWrapperAssetConstants({\n\t\t\t\tentryPath: getDocumentEntryPath(outDir, document.name),\n\t\t\t\tknown: assetState.known,\n\t\t\t\turlMap: assetState.urlMap\n\t\t\t})\n\t\t})\n\t)\n\n\t// `none` ships no asset bundle, but the bundler still content-hashes and\n\t// emits anything imported as a module. Those imports can't be resolved by\n\t// name and won't ship in this mode, so warn rather than let them vanish\n\t// silently. Path references (e.g. `<img src=\"logo.png\">`) are unaffected —\n\t// the consumer supplies those bytes themselves.\n\tif (assetMode === 'none') {\n\t\tconst emittedDir = resolve(outDir, SHARED_ASSETS_OUT_DIR_NAME)\n\t\tconst emittedEntries = await readdir(emittedDir, { recursive: true, withFileTypes: true }).catch(() => [])\n\t\tconst emittedCount = emittedEntries.filter(entry => entry.isFile()).length\n\n\t\tif (emittedCount > 0) {\n\t\t\tlogger.warn(\n\t\t\t\t`⚠ --assets none, but the bundle imported ${emittedCount} ${pluralize('asset', emittedCount)} ` +\n\t\t\t\t\t`(e.g. \\`import logo from './logo.png'\\`). Imported assets are content-hashed and managed by the build, ` +\n\t\t\t\t\t`so they can't be resolved by name and won't ship in this mode. Reference assets by path ` +\n\t\t\t\t\t`(e.g. \\`<img src=\"logo.png\">\\`) to supply them yourself, or use --assets static or dynamic to bundle them.`\n\t\t\t)\n\t\t}\n\t}\n\n\t// Static and none modes don't ship the loose Vite-emitted assets: static\n\t// folds them into each document's zip, none emits nothing. Either way the\n\t// shared `shared-assets/` dir is build state, so drop it.\n\tif (assetMode === 'static' || assetMode === 'none') {\n\t\tawait rm(resolve(outDir, SHARED_ASSETS_OUT_DIR_NAME), { recursive: true, force: true }).catch(() => {})\n\t}\n\n\t// The remote-reference pass needs rendered HTML, which node-target builds\n\t// produce at build time: CLI dynamic compiles smoke-render the default\n\t// variant, and HTML output renders every variant. Both qualify.\n\tconst canProcessRemoteRefs = assetMode === 'static' && options.target === 'node' && (isCli || isHtmlOutput)\n\n\t// The mode/target legs of this incompatibility are warned upfront at options\n\t// normalisation. The one left to surface here is source-dependent, which\n\t// normalisation can't see: a bundler-driven (unplugin) build never renders at\n\t// build time, so there is no HTML to fetch remote references from.\n\tconst remoteAssetsBlockedBySource =\n\t\toptions.remoteAssets && !canProcessRemoteRefs && assetMode === 'static' && options.target === 'node'\n\n\tif (remoteAssetsBlockedBySource) {\n\t\tlogger.warn(\n\t\t\t'remoteAssets was set but cannot be honoured here: fetching remote assets requires a CLI compile, where the document renders at build time. Skipping remote asset fetching.'\n\t\t)\n\t}\n\n\t// Node bundles are runnable as-is, so render the real artifact: import each\n\t// document's emitted wrapper and run it. Dynamic output smoke-renders the\n\t// default variant (CLI only) to catch broken externals, module-load failures,\n\t// and default-variant asset mismatches at build time. HTML output renders\n\t// every selected variant and writes each result to disk — that is its whole\n\t// artefact, so it runs regardless of source. Browser/worker artifacts can't\n\t// run here — their failures surface in Studio dev or at the first render.\n\tconst htmlVariantEntries = new Map<string, HtmlManifestVariant[]>()\n\n\tif (options.target === 'node' && (isCli || isHtmlOutput)) {\n\t\tconst renderWorker = new RenderWorker({\n\t\t\tlog: msg => logger.debug(msg),\n\t\t\twarn: msg => logger.warn(msg),\n\t\t\tallowedReadPaths: [outDir],\n\t\t\tsandbox: 'strict'\n\t\t})\n\n\t\tconst smokeVariant = args.smokeVariant ?? DEFAULT_VARIANT\n\n\t\ttry {\n\t\t\tfor (const document of buildDocuments) {\n\t\t\t\tconst variants = isHtmlOutput ? (args.htmlVariantMatrix?.get(document.name) ?? []) : [smokeVariant]\n\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst html = await renderVariantWithWorker({\n\t\t\t\t\t\trenderWorker,\n\t\t\t\t\t\toutDir,\n\t\t\t\t\t\tdocumentName: document.name,\n\t\t\t\t\t\tvariant,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tassetMode,\n\t\t\t\t\t\tprobeRemoteOnMismatch: canProcessRemoteRefs && options.remoteAssets,\n\t\t\t\t\t\tremoteFetch: args.remoteFetch\n\t\t\t\t\t})\n\n\t\t\t\t\t// Per variant so the document's shared zip accumulates the union of\n\t\t\t\t\t// every variant's remote references — any variant then resolves from it.\n\t\t\t\t\tif (canProcessRemoteRefs) {\n\t\t\t\t\t\tawait processRemoteAssetRefs({\n\t\t\t\t\t\t\thtml,\n\t\t\t\t\t\t\tdocumentName: document.name,\n\t\t\t\t\t\t\toutDir,\n\t\t\t\t\t\t\tremoteAssets: options.remoteAssets,\n\t\t\t\t\t\t\tremoteFetch: args.remoteFetch,\n\t\t\t\t\t\t\tquiet: args.quiet\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isHtmlOutput) {\n\t\t\t\t\t\targs.capturedHtml?.set(document.name, html)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst htmlPath = getHtmlVariantPath(outDir, document.name, variant)\n\t\t\t\t\tawait mkdir(dirname(htmlPath), { recursive: true })\n\t\t\t\t\tawait writeFile(htmlPath, html, 'utf-8')\n\n\t\t\t\t\tconst entries = htmlVariantEntries.get(document.name) ?? []\n\t\t\t\t\tentries.push({ variant, html: `${document.name}/${variant}/${INDEX_HTML_FILE_NAME}` })\n\t\t\t\t\thtmlVariantEntries.set(document.name, entries)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tawait renderWorker.dispose()\n\t\t}\n\t}\n\n\t// HTML output ships rendered HTML, not a runnable bundle, so it writes the\n\t// manifest and strips the JS artefacts instead of recording externals.\n\tif (isHtmlOutput) {\n\t\tawait writeHtmlOutput({ outDir, buildDocuments, htmlVariantEntries })\n\t}\n\n\tif (!isHtmlOutput) {\n\t\tconst externals = await collectExternals(outDir, documentNames)\n\t\tconst externalsPayload = { target: options.target, externals }\n\n\t\tawait writeFile(resolve(outDir, 'externals.json'), JSON.stringify(externalsPayload, null, '\\t'), 'utf-8')\n\n\t\tlogger.debug(`Externals for ${options.target}:`, externals.length ? externals.join(', ') : '(none)')\n\t}\n\n\tconst endTime = performance.now()\n\tconst compiledIn = `${(endTime - startTime).toFixed(2)}ms`\n\n\tconst documentName = buildDocuments.length === 1 ? buildDocuments[0]!.name : `${buildDocuments.length} documents`\n\n\tconst structuredOutput = createStructuredOutput({\n\t\tdocumentName,\n\t\toutDir,\n\t\tcompiledIn\n\t})\n\n\tconst isDebug = getLogLevel() === LogLevel.DEBUG\n\n\t// A quiet compile is work the user didn't ask for — a background build after\n\t// a preview render — so it says nothing on success. FORMAT_DEBUG still shows it.\n\tif ((isCli && !args.quiet) || isDebug) {\n\t\tlogger.info(\n\t\t\tgradient(`✓ Successfully compiled ${documentName}`),\n\t\t\t'\\n',\n\t\t\tJSON.stringify(structuredOutput, null, 2),\n\t\t\t'\\n'\n\t\t)\n\t}\n\n\treturn [structuredOutput]\n}\n\nfunction warnIgnoredOption(message: string) {\n\tlogger.warn(`ℹ ${message}`)\n}\n\n/**\n * Map each document to the data variants HTML output should render. Throws on\n * the two unrecoverable cases — a selected document with no data at all, and a\n * requested variant that exists for no document — and warns per document for a\n * requested variant that only some documents have.\n */\nexport function resolveHtmlVariantMatrix(documents: Document[], requestedVariants: string[]): Map<string, string[]> {\n\tconst documentsWithoutData = documents.filter(document => document.variants.length === 0)\n\n\tif (documentsWithoutData.length > 0) {\n\t\tconst names = documentsWithoutData.map(document => `\"${document.name}\"`).join(', ')\n\n\t\tthrow new CompileError(\n\t\t\t`Can't use --output html for ${names}: no data files found. Add at least a \\`data/${DEFAULT_VARIANT}.json\\`.`\n\t\t)\n\t}\n\n\tconst matrix = new Map<string, string[]>()\n\n\tif (requestedVariants.length === 0) {\n\t\tfor (const document of documents) {\n\t\t\tmatrix.set(document.name, document.variants)\n\t\t}\n\n\t\treturn matrix\n\t}\n\n\tconst orphanVariants = requestedVariants.filter(\n\t\tvariant => !documents.some(document => document.variants.includes(variant))\n\t)\n\n\tif (orphanVariants.length > 0) {\n\t\tconst names = orphanVariants.map(variant => `\"${variant}\"`).join(', ')\n\n\t\tthrow new CompileError(\n\t\t\t`No document has the variant(s) ${names}. Check the names against your \\`data/*.json\\` files.`\n\t\t)\n\t}\n\n\tfor (const document of documents) {\n\t\tconst selected = requestedVariants.filter(variant => document.variants.includes(variant))\n\t\tconst missing = requestedVariants.filter(variant => !document.variants.includes(variant))\n\n\t\tif (missing.length > 0) {\n\t\t\tconst names = missing.map(variant => `\"${variant}\"`).join(', ')\n\t\t\tlogger.warn(`Document \"${document.name}\" has no variant(s) ${names}; skipping for this document.`)\n\t\t}\n\n\t\tmatrix.set(document.name, selected)\n\t}\n\n\treturn matrix\n}\n\n/**\n * HTML output renders from a forced node build with assets bundled at build\n * time, so the JS-bundle and asset-mode flags have nothing to act on. None of\n * them is build-breaking — we override and warn per flag. The genuinely\n * unrecoverable cases (a document with no data, an unknown variant) are errors,\n * raised later in resolveHtmlVariantMatrix.\n */\nexport function warnIncompatibleHtmlOptions(options: NormalizedCompileOptions) {\n\tconst warnIgnored = (flag: string) =>\n\t\twarnIgnoredOption(`The ${flag} flag is not compatible with html output, ignoring.`)\n\n\tif (options.target !== 'node') {\n\t\twarnIgnored('--target')\n\t}\n\n\tif (options.preset !== 'node') {\n\t\twarnIgnored('--preset')\n\t}\n\n\tif (options.assets !== 'static') {\n\t\twarnIgnored('--assets')\n\t}\n\n\tif (options.external.length > 0) {\n\t\twarnIgnored('--external')\n\t}\n\n\tif (options.bundle.length > 0) {\n\t\twarnIgnored('--bundle')\n\t}\n\n\tif (options.conditions.length > 0) {\n\t\twarnIgnored('--conditions')\n\t}\n\n\tif (options.externalConditions.length > 0) {\n\t\twarnIgnored('--external-conditions')\n\t}\n\n\tif (options.cjs) {\n\t\twarnIgnored('--cjs')\n\t}\n\n\tif (options.version) {\n\t\twarnIgnored('--version')\n\t}\n}\n\ninterface RunCompileArgs {\n\t/** Raw consumer options; normalised here so every entry point shares one path. */\n\toptions: CompileOptions\n\tsource: CompileSource\n\t/** Variant the node-target smoke render uses (Studio only). Defaults to the default variant. */\n\tsmokeVariant?: string\n\t/** Collector the smoke render fills with each document's rendered HTML (Studio only). */\n\tcapturedHtml?: Map<string, string>\n\t/** Collector filled with each document's asset state (unplugin/Next.js, to re-host assets). */\n\tcapturedAssetState?: Map<string, DocumentAssetState>\n\t/** Collector filled with every source file the bundler read (Studio only). */\n\tcapturedInputs?: Set<string>\n\t/** Replaces the network fetch for remote references (Studio only). */\n\tremoteFetch?: RemoteAssetFetcher\n\t/** Suppress success and progress reporting (Studio background builds). */\n\tquiet?: boolean\n\t/**\n\t * Read and write the `.cache` hash in `outDir`. Studio owns its own bundle\n\t * directory and invalidates on a finer input set, so it turns this off — and\n\t * a hit here would skip the smoke render Studio needs the HTML from.\n\t */\n\tuseDiskCache?: boolean\n}\n\nasync function runCompile(runArgs: RunCompileArgs): Promise<StructuredOutput[]> {\n\tconst { options: inputOptions, source, smokeVariant, capturedHtml, capturedAssetState, capturedInputs } = runArgs\n\n\tsetLogLevel(parseLogLevelFromEnv())\n\tconst logLevel = getLogLevel()\n\n\tconst isCli = source === 'cli'\n\n\t// Unplugin builds default to clean: false — the consumer bundler owns the\n\t// output directory's lifecycle.\n\tconst rawOptions = normalizeCompileOptions(\n\t\tsource === 'unplugin' ? { ...inputOptions, clean: inputOptions.clean ?? false } : inputOptions\n\t)\n\n\tconst isHtmlOutput = rawOptions.output === 'html'\n\n\tif (isHtmlOutput) {\n\t\twarnIncompatibleHtmlOptions(rawOptions)\n\t}\n\n\t// HTML output has no JS runtime, so the bundle-shaping options are\n\t// meaningless. Force a node render build with bundled assets; the warning\n\t// above tells the user which of their flags were dropped.\n\tconst options: NormalizedCompileOptions = isHtmlOutput\n\t\t? {\n\t\t\t\t...rawOptions,\n\t\t\t\ttarget: 'node',\n\t\t\t\tpreset: 'node',\n\t\t\t\tassets: 'static',\n\t\t\t\tcjs: false,\n\t\t\t\texternal: [],\n\t\t\t\tbundle: [],\n\t\t\t\tconditions: [],\n\t\t\t\texternalConditions: [],\n\t\t\t\tbundleAll: false\n\t\t\t}\n\t\t: rawOptions\n\n\tlogger.debug('Compile options', options)\n\n\tconst { documents: documentNames } = options\n\n\tconst { config } = await loadConfig(options.configPath)\n\n\tif (!config) {\n\t\tthrow new Error(NO_CONFIG_FILE_MESSAGE)\n\t}\n\n\t// after loadConfig, which is what sets the project dir — before it, this reads\n\t// whatever directory the command was launched from\n\tassertProducersAgree(getUserProjectDir())\n\n\tcompileState.setConfig(config)\n\n\tconst allDocuments = await getDocuments(config)\n\n\tconst documents = allDocuments\n\t\t.filter(({ name }) => documentNames.length === 0 || documentNames.includes(name))\n\t\t.sort((a, b) => a.name.localeCompare(b.name))\n\n\tconst missingDocuments = documentNames.filter(\n\t\tname => !allDocuments.some(({ name: documentName }) => documentName === name)\n\t)\n\n\tif (missingDocuments.length > 0) {\n\t\tlogger.warn(`Couldn't find the following documents: \"${missingDocuments.join(', ')}\"`)\n\t}\n\n\tif (documents.length === 0) {\n\t\tthrow new Error(NO_DOCUMENTS_MESSAGE)\n\t}\n\n\t// Fail on export-name collisions before any build work starts — compileBundle\n\t// would otherwise only hit this after cleaning the output directory.\n\tbuildDocumentExportMap(documents.map(({ name }) => name))\n\n\t// The default `assets/` dir is optional, but an explicitly configured one\n\t// that's missing is a mistake worth failing on.\n\tif (config.sharedAssetsDir) {\n\t\tconst sharedAssetsDir = getSharedAssetsDir(config)\n\t\tconst { isDirectory } = await checkDir(sharedAssetsDir)\n\t\tif (!isDirectory) {\n\t\t\tthrow new Error(`Your configured \\`sharedAssetsDir\\` not found or is not a directory: ${sharedAssetsDir}`)\n\t\t}\n\t}\n\n\tconst htmlVariantMatrix = isHtmlOutput ? resolveHtmlVariantMatrix(documents, options.variants) : undefined\n\n\tconst outDir = getBundleOutDir(config, options.outDir)\n\n\t// CLI and unplugin builds use disk-persisted caching to skip recompilation\n\t// when nothing changed. HTML output isn't cached: it renders the whole\n\t// variant matrix and always writes fresh HTML. Dynamic-mode unplugin builds\n\t// aren't cached either — the plugin needs the per-document asset state a\n\t// compile captures, and a cache hit would skip capturing it.\n\tconst isCacheableRun =\n\t\t(runArgs.useDiskCache ?? true) &&\n\t\t(isCli || (source === 'unplugin' && options.assets !== 'dynamic')) &&\n\t\t!isHtmlOutput\n\n\t// The consumer bundler only changes compile output through the webpack-node\n\t// compat rewrite (see make-config), so key on that fact rather than the raw\n\t// bundler name — vite/rollup/esbuild consumers then share one cached compile.\n\tconst cacheKeyOptions = buildCacheKeyOptions({\n\t\toptions,\n\t\twebpackNodeCompat: options.target === 'node' && source === 'unplugin' && options.userBundler === 'webpack'\n\t})\n\n\tif (isCacheableRun) {\n\t\tconst documentsDir = getDocumentsDir(config)\n\t\tconst currentHash = await computeCacheHash(documentsDir, cacheKeyOptions)\n\t\tconst cachedHash = await readCachedHash(outDir)\n\n\t\tif (cachedHash === currentHash) {\n\t\t\tconst expectedEntryPaths = documents.map(({ name }) => getDocumentEntryPath(outDir, name))\n\t\t\tconst outputsPresent = await cachedOutputsExist(expectedEntryPaths)\n\n\t\t\tif (outputsPresent) {\n\t\t\t\tlogger.info('Cache hit — documents unchanged, skipping compile.')\n\t\t\t\treturn []\n\t\t\t}\n\n\t\t\tlogger.debug('Cache hash matched but compiled outputs are missing — recompiling.')\n\t\t}\n\t}\n\n\tconst runAll = () =>\n\t\tcompileBundle({\n\t\t\tdocumentNames: documents.map(({ name }) => name),\n\t\t\tconfig,\n\t\t\toptions,\n\t\t\tlogLevel,\n\t\t\tsource,\n\t\t\tsmokeVariant,\n\t\t\tcapturedHtml,\n\t\t\tcapturedAssetState,\n\t\t\tcapturedInputs,\n\t\t\tremoteFetch: runArgs.remoteFetch,\n\t\t\tquiet: runArgs.quiet,\n\t\t\thtmlVariantMatrix\n\t\t})\n\n\tconst suppressBuildLogs = (_level: string, ...args: unknown[]) => {\n\t\tconst msg = args.join(' ')\n\n\t\tif (msg.includes('building SSR bundle for production')) return false\n\t\tif (msg.includes('vite v') && msg.includes('building')) return false\n\t\tif (msg.includes('built in')) return false\n\n\t\treturn true\n\t}\n\n\tconst results = isCli\n\t\t? ((await withPrefixedConsole(() => runAll(), suppressBuildLogs)) as StructuredOutput[])\n\t\t: await runAll()\n\n\t// Write cache hash after successful compilation\n\tif (isCacheableRun) {\n\t\tconst documentsDir = getDocumentsDir(config)\n\t\tconst currentHash = await computeCacheHash(documentsDir, cacheKeyOptions)\n\t\tawait writeCacheHash(outDir, currentHash)\n\t}\n\n\tconst { external } = options\n\tconst externalLen = external.length\n\n\tif (isCli && externalLen > 0 && !runArgs.quiet) {\n\t\tlogger.info(\n\t\t\t`ℹ External packages: ${external.join(', ')}. Make sure ${pluralize('this', externalLen)} ${pluralize(\n\t\t\t\t'is',\n\t\t\t\texternalLen\n\t\t\t)} installed where you call render.`\n\t\t)\n\t}\n\n\treturn results\n}\n\nexport async function compile(options: CompileOptions): Promise<StructuredOutput[]> {\n\tawait warnOnLockstepDrift(options.configPath ? dirname(options.configPath) : process.cwd())\n\n\treturn runCompile({ options, source: 'cli' })\n\t\t.then(() => process.exit(0))\n\t\t.catch(error => {\n\t\t\tlogger.error('Compile error', error)\n\t\t\tprocess.exit(1)\n\t\t})\n}\n\nexport interface StudioCompileOptions {\n\t/**\n\t * Variant the node-target smoke render uses. The download route passes the\n\t * variant being downloaded so its remote assets land in the zip and its\n\t * rendered HTML comes back ready to send. Defaults to the default variant.\n\t */\n\tvariant?: string\n\t/**\n\t * Use the compile package's own `.cache` hash in `outDir`. Off for callers\n\t * that keep the output directory and track its inputs themselves — a hit\n\t * skips the smoke render, so the HTML would come back empty.\n\t */\n\tuseDiskCache?: boolean\n\t/**\n\t * Replaces the network fetch for remote references. Studio passes a\n\t * session-wide cache so a rebuilt bundle doesn't download every remote asset\n\t * again.\n\t */\n\tremoteFetch?: RemoteAssetFetcher\n\t/**\n\t * Compile without the usual success and progress reporting. Studio sets this\n\t * for background builds, which the user never asked for and shouldn't have to\n\t * read about on every save. Warnings and errors are unaffected, and\n\t * `FORMAT_DEBUG=true` restores the full output.\n\t */\n\tquiet?: boolean\n}\n\nexport interface StudioCompileResult {\n\toutputs: StructuredOutput[]\n\t/** Each document's smoke-rendered HTML, keyed by document name. */\n\thtml: Map<string, string>\n\t/**\n\t * Absolute paths of every source file the bundler read. Studio stats these to\n\t * decide whether a kept bundle is still current. Empty when the compile was\n\t * served from the disk cache.\n\t */\n\tinputs: string[]\n}\n\nexport async function compileForStudio(\n\toptions: CompileOptions,\n\tstudioOptions: StudioCompileOptions = {}\n): Promise<StudioCompileResult> {\n\tconst capturedHtml = new Map<string, string>()\n\tconst capturedInputs = new Set<string>()\n\n\tconst outputs = await runCompile({\n\t\toptions,\n\t\tsource: 'cli',\n\t\tsmokeVariant: studioOptions.variant,\n\t\tcapturedHtml,\n\t\tcapturedInputs,\n\t\tuseDiskCache: studioOptions.useDiskCache,\n\t\tremoteFetch: studioOptions.remoteFetch,\n\t\tquiet: studioOptions.quiet\n\t})\n\n\treturn { outputs, html: capturedHtml, inputs: [...capturedInputs] }\n}\n\nexport async function compileForUnplugin(\n\toptions: CompileOptions,\n\textras: { capturedAssetState?: Map<string, DocumentAssetState> } = {}\n): Promise<StructuredOutput[]> {\n\treturn runCompile({ options, source: 'unplugin', capturedAssetState: extras.capturedAssetState })\n}\n\nexport async function compileForTest(options: CompileOptions): Promise<StructuredOutput[]> {\n\t// Using the Unplugin entrypoint for compile tests, as it's the same as the unplugin process and tests\n\treturn compileForUnplugin(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAAgB,iBAAiB,QAAsB;AACtD,QAAO,QAAQ,WAAW,OAAO,EAAE,qBAAqB;;AAGzD,SAAgB,gBAAgB,QAAsB,gBAAgC;AACrF,QAAO,kBAAkB,OAAO,QAAQ,eAAe,GAAG,iBAAiB,OAAO;;AAGnF,MAAM,iBAAiB;AAEvB,SAAgB,kBAAkB,QAAgB,cAAsB;AACvE,QAAO,QAAQ,QAAQ,aAAa;;AAGrC,SAAgB,qBAAqB,QAAgB,cAAsB;AAC1E,QAAO,QAAQ,kBAAkB,QAAQ,aAAa,EAAE,6BAA6B;;AAGtF,SAAgB,sBAAsB,QAAgB,cAAsB;AAC3E,QAAO,QAAQ,kBAAkB,QAAQ,aAAa,EAAE,eAAe;;AAGxE,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAE3B,SAAgB,mBAAmB,QAAgB,cAAsB,SAAiB;AACzF,QAAO,QAAQ,kBAAkB,QAAQ,aAAa,EAAE,SAAS,qBAAqB;;AAoBvF,MAAM,yBAAyB;;;;;;;;AAS/B,eAAe,uBAAuB,MASnC;CACF,MAAM,EAAE,MAAM,cAAc,QAAQ,cAAc,aAAa,UAAU;CAEzE,MAAM,aAAa,eAAe,KAAK;AAEvC,KAAI,WAAW,WAAW,EACzB;AAGD,KAAI,CAAC,cAAc;EAClB,MAAM,OAAO,WAAW,KAAI,QAAO,OAAO,MAAM,CAAC,KAAK,KAAK;AAE3D,SAAO,KACN,aAAa,aAAa,6HAA6H,KAAK,6FAC/D,yBAC7F;AACD;;CAGD,MAAM,aAAa,sBAAsB,QAAQ,aAAa;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,CAAC,QAAQ,MACxC,QAAO,KACN,wBAAwB,SAAS,KAAK,KAAK,CAAC,cAAc,UAAU,QAAQ,YAAY,CAAC,GAAG,UAC3F,MACA,YACA,CAAC,mCACF;AAGF,QAAO;;AAGR,eAAsB,QAAQ,SAAsD;AACnF,OAAM,oBAAoB,QAAQ,aAAa,QAAQ,QAAQ,WAAW,GAAG,QAAQ,KAAK,CAAC;AAE3F,QAAO,WAAW;EAAE;EAAS,QAAQ;EAAO,CAAC,CAC3C,WAAW,QAAQ,KAAK,EAAE,CAAC,CAC3B,OAAM,UAAS;AACf,SAAO,MAAM,iBAAiB,MAAM;AACpC,UAAQ,KAAK,EAAE;GACd;;AA2CJ,eAAsB,iBACrB,SACA,gBAAsC,EAAE,EACT;CAC/B,MAAM,+BAAe,IAAI,KAAqB;CAC9C,MAAM,iCAAiB,IAAI,KAAa;AAaxC,QAAO;EAAE,SAXO,MAAM,WAAW;GAChC;GACA,QAAQ;GACR,cAAc,cAAc;GAC5B;GACA;GACA,cAAc,cAAc;GAC5B,aAAa,cAAc;GAC3B,OAAO,cAAc;GACrB,CAAC;EAEgB,MAAM;EAAc,QAAQ,CAAC,GAAG,eAAe;EAAE;;AAGpE,eAAsB,mBACrB,SACA,SAAmE,EAAE,EACvC;AAC9B,QAAO,WAAW;EAAE;EAAS,QAAQ;EAAY,oBAAoB,OAAO;EAAoB,CAAC;;AAGlG,eAAsB,eAAe,SAAsD;AAE1F,QAAO,mBAAmB,QAAQ"}
|
|
1
|
+
{"version":3,"file":"compile.mjs","names":["error: unknown","documents: HtmlManifestDocument[]","manifest: HtmlManifest","cssInJsVmPrewarm: Promise<void> | null","assetMode: AssetMode","LogLevel","buildDocuments: BuildDocument[]","documentName","format: Format","exportNames","output","gradient","options: NormalizedCompileOptions"],"sources":["../../../src/server/compile/compile.ts"],"sourcesContent":["import { LogLevel, type FormatConfig, type Document } from '../../shared/types'\nimport type { AssetMode, CompileOptions, NormalizedCompileOptions, Format } from '../../shared/types/public'\nimport type { RemoteAssetFetcher } from '@format.dev/zip'\n\nimport { resolve, dirname } from 'node:path'\nimport { mkdir, access, rm, readFile, writeFile, readdir } from 'node:fs/promises'\nimport { builtinModules, createRequire } from 'node:module'\nimport { pathToFileURL } from 'node:url'\nimport { build, mergeConfig } from 'vite'\nimport { scanRemoteRefs, mergeRemoteAssets, findBrokenRemoteAssets, AssetMismatchError } from '@format.dev/zip'\nimport pluralize from 'pluralize'\nimport grad, { atlas as gradient } from 'gradient-string'\n\nimport { getStyles } from '../vite/plugins/get-styles'\nimport { stylesPreProcessor } from '../vite/plugins/styles-pre-processor'\nimport { htmlLoader } from '../vite/plugins/html-loader'\nimport { getSharedAssetsDir, getDocumentsDir, getRootDir, DEFAULT_OUT_DIR_NAME } from '../project/paths'\nimport { createConfig } from '../vite/create-config'\nimport { emitPackageJson } from './package-json'\nimport { getSchemaPath } from '../utils/schema'\nimport { NO_DOCUMENTS_MESSAGE, DEFAULT_VARIANT } from '../../shared/constants'\nimport { RenderWorker } from '../render-worker'\nimport { NO_CONFIG_FILE_MESSAGE } from '../constants'\nimport { normalizeCompileOptions } from './defaults'\nimport {\n\tbuildCacheKeyOptions,\n\tcomputeCacheHash,\n\treadCachedHash,\n\twriteCacheHash,\n\tcachedOutputsExist\n} from './compile-cache'\nimport { DocumentRenderError } from './render-error'\nimport { BUNDLE_ENTRY_POINT_FILE_NAME, SHARED_ASSETS_OUT_DIR_NAME, CHUNKS_DIR_NAME } from './constants'\nimport { createStructuredOutput, type StructuredOutput } from './structured-log'\nimport { makeViteBuildConfig } from './make-config'\nimport { basePackageName } from './dependency-closure'\nimport { compileState } from '../runtime-state'\nimport { engineTarget } from './producer-release'\nimport { warnOnLockstepDrift } from '../utils/warn-lockstep'\nimport { assertProducersAgree } from './producer-agreement'\nimport { getUserProjectDir } from '../project/user-project-dir'\nimport { CompileError } from '../errors'\nimport { bakeWrapperAssetConstants } from './wrapper-source'\n\nimport {\n\tresolveDocumentAssetSources,\n\tbuildDocumentStaticAssets,\n\tbuildDocumentDynamicAssets,\n\tmaterialiseSharedDynamicAssets\n} from './document-assets'\n\nimport { getDocumentDataDir, getDocumentDataFile, getDocuments, getUserDocumentIndex } from '../project/documents'\n\nimport {\n\tlogger,\n\twithPrefixedConsole,\n\tloadConfig,\n\tsetLogLevel,\n\tparseLogLevelFromEnv,\n\tgetLogLevel,\n\tcheckDir\n} from '../utils'\nimport { buildDocumentExportMap } from '@format.dev/cli/scaffold'\n\ntype CompileSource = 'cli' | 'unplugin'\n\nexport function getDefaultOutDir(config: FormatConfig) {\n\treturn resolve(getRootDir(config), DEFAULT_OUT_DIR_NAME)\n}\n\nexport function getBundleOutDir(config: FormatConfig, outDirOverride?: string | null) {\n\treturn outDirOverride != null ? resolve(outDirOverride) : getDefaultOutDir(config)\n}\n\nconst assetsFileName = 'assets.zip'\n\nexport function getDocumentOutDir(outDir: string, documentName: string) {\n\treturn resolve(outDir, documentName)\n}\n\nexport function getDocumentEntryPath(outDir: string, documentName: string) {\n\treturn resolve(getDocumentOutDir(outDir, documentName), BUNDLE_ENTRY_POINT_FILE_NAME)\n}\n\nexport function getDocumentAssetsPath(outDir: string, documentName: string) {\n\treturn resolve(getDocumentOutDir(outDir, documentName), assetsFileName)\n}\n\nconst INDEX_HTML_FILE_NAME = 'index.html'\nconst MANIFEST_FILE_NAME = 'manifest.json'\n\nexport function getHtmlVariantPath(outDir: string, documentName: string, variant: string) {\n\treturn resolve(getDocumentOutDir(outDir, documentName), variant, INDEX_HTML_FILE_NAME)\n}\n\ninterface HtmlManifestVariant {\n\tvariant: string\n\thtml: string\n}\n\ninterface HtmlManifestDocument {\n\tdocument: string\n\tassets?: string\n\tvariants: HtmlManifestVariant[]\n}\n\ninterface HtmlManifest {\n\toutput: 'html'\n\tengine: string\n\tdocuments: HtmlManifestDocument[]\n}\n\nconst REMOTE_ASSETS_DOCS_URL = 'https://format.dev/docs/authoring/assets#remote-assets'\n\n/**\n * Post-render remote-reference pass (static mode). PDF generation never\n * fetches remote references at render time, so anything the rendered HTML\n * points at over http(s) must either be fetched into the document's zip now\n * (`remoteAssets` on) or flagged — without it, the reference is missing from\n * every generated PDF.\n */\nasync function processRemoteAssetRefs(args: {\n\thtml: string\n\tdocumentName: string\n\toutDir: string\n\tremoteAssets: boolean\n\t/** Replaces the network fetch for each remote reference. Studio passes a session cache. */\n\tremoteFetch?: RemoteAssetFetcher\n\t/** Report progress at debug level only. Set for builds the user didn't ask for. */\n\tquiet?: boolean\n}) {\n\tconst { html, documentName, outDir, remoteAssets, remoteFetch, quiet } = args\n\n\tconst remoteRefs = scanRemoteRefs(html)\n\n\tif (remoteRefs.length === 0) {\n\t\treturn\n\t}\n\n\tif (!remoteAssets) {\n\t\tconst list = remoteRefs.map(url => ` • ${url}`).join('\\n')\n\n\t\tlogger.warn(\n\t\t\t`Document \"${documentName}\" references remote assets that will be missing from generated PDFs — remote references are never fetched at render time:\\n${list}\\n` +\n\t\t\t\t`Compile with --remote-assets to fetch and bundle them, or reference local files instead. ${REMOTE_ASSETS_DOCS_URL}`\n\t\t)\n\t\treturn\n\t}\n\n\tconst assetsPath = getDocumentAssetsPath(outDir, documentName)\n\tconst existing = await readFile(assetsPath).catch(() => undefined)\n\n\tconst merged = await mergeRemoteAssets({\n\t\thtml,\n\t\tzip: existing,\n\t\toptions: remoteFetch ? { remoteAssets: { fetch: remoteFetch } } : undefined\n\t})\n\n\tif (merged && merged !== existing) {\n\t\tawait mkdir(getDocumentOutDir(outDir, documentName), { recursive: true })\n\t\tawait writeFile(assetsPath, merged)\n\n\t\tconst message = `Bundled remote assets referenced by \"${documentName}\" into its assets.zip`\n\n\t\tif (quiet) {\n\t\t\tlogger.debug(message)\n\t\t} else {\n\t\t\tlogger.info(message)\n\t\t}\n\t}\n}\n\n/**\n * Every real source file the bundler read, taken from the build's own module\n * graph. Virtual ids and dependencies are dropped: a `virtual:` id is not a\n * file to stat, and `node_modules` changes only on an install, which the\n * bundler's own cache invalidation already covers.\n */\nfunction collectModuleIds(buildOutput: unknown): string[] {\n\tconst outputs = Array.isArray(buildOutput) ? buildOutput : [buildOutput]\n\tconst ids = new Set<string>()\n\n\tfor (const result of outputs) {\n\t\tconst chunks = (result as { output?: Array<{ moduleIds?: string[] }> } | null)?.output ?? []\n\n\t\tfor (const chunk of chunks) {\n\t\t\tfor (const id of chunk.moduleIds ?? []) {\n\t\t\t\tif (isRealSourceFile(id)) {\n\t\t\t\t\tids.add(id)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn [...ids]\n}\n\nfunction isRealSourceFile(id: string): boolean {\n\tif (!id.startsWith('/') && !/^[A-Za-z]:[\\\\/]/.test(id)) {\n\t\treturn false\n\t}\n\n\tif (id.includes('\\u0000') || id.includes('node_modules')) {\n\t\treturn false\n\t}\n\n\treturn true\n}\n\ninterface RenderVariantWithWorkerArgs {\n\trenderWorker: RenderWorker\n\toutDir: string\n\tdocumentName: string\n\tvariant: string\n\tconfig: FormatConfig\n\tassetMode: AssetMode\n\t/**\n\t * Probe the remote URLs a local-asset mismatch carries, so one error reports\n\t * every unresolvable asset rather than only the local ones. Only meaningful\n\t * where remote references are being fetched at all.\n\t */\n\tprobeRemoteOnMismatch: boolean\n\t/** Replaces the network fetch used by that probe. */\n\tremoteFetch?: RemoteAssetFetcher\n}\n\n/**\n * Render one compiled document variant on an already-running strict worker.\n * Shared by the build-time smoke render and {@link renderCompiledDocument},\n * so both report a failure the same way.\n */\nasync function renderVariantWithWorker(args: RenderVariantWithWorkerArgs): Promise<string> {\n\tconst { renderWorker, outDir, documentName, variant, config, assetMode, probeRemoteOnMismatch, remoteFetch } = args\n\n\tconst data = await getDocumentDataFile(documentName, variant, config)\n\n\ttry {\n\t\treturn await renderWorker.compileRender({\n\t\t\tbundlePath: getDocumentEntryPath(outDir, documentName),\n\t\t\tdocumentName,\n\t\t\tdata: data || {},\n\t\t\tcwd: getDocumentOutDir(outDir, documentName)\n\t\t})\n\t} catch (error: unknown) {\n\t\tlogger.error(`Compiled bundle failed to render document \"${documentName}\" (variant \"${variant}\")`, error)\n\n\t\tconst errData =\n\t\t\terror && typeof error === 'object' && 'data' in error ? (error as { data?: unknown }).data : undefined\n\n\t\tif (errData !== undefined) {\n\t\t\tlogger.error('Error data', errData)\n\t\t}\n\n\t\tconst mismatch = error as { missing?: unknown; known?: unknown; remoteRefs?: unknown }\n\t\tconst isLocalMismatch = Array.isArray(mismatch.missing) && Array.isArray(mismatch.remoteRefs)\n\n\t\tconst renderFailure =\n\t\t\tisLocalMismatch && probeRemoteOnMismatch\n\t\t\t\t? await enrichWithBrokenRemotes({ documentName, assetMode, mismatch, error, remoteFetch })\n\t\t\t\t: error\n\n\t\tthrow new DocumentRenderError({ documentName, variant, cause: renderFailure })\n\t}\n}\n\nasync function enrichWithBrokenRemotes(args: {\n\tdocumentName: string\n\tassetMode: AssetMode\n\tmismatch: { missing?: unknown; known?: unknown; remoteRefs?: unknown }\n\terror: unknown\n\tremoteFetch?: RemoteAssetFetcher\n}): Promise<unknown> {\n\tconst { documentName, assetMode, mismatch, error, remoteFetch } = args\n\n\tconst brokenRemote = await findBrokenRemoteAssets({ urls: mismatch.remoteRefs as string[], fetch: remoteFetch })\n\n\tif (brokenRemote.length === 0) {\n\t\treturn error\n\t}\n\n\treturn new AssetMismatchError({\n\t\tdocumentName,\n\t\tmode: assetMode as 'static' | 'dynamic',\n\t\tmissing: mismatch.missing as string[],\n\t\tknown: Array.isArray(mismatch.known) ? (mismatch.known as string[]) : [],\n\t\tbrokenRemote\n\t})\n}\n\nexport interface RenderCompiledDocumentArgs {\n\t/** The bundle output directory a previous compile wrote. */\n\toutDir: string\n\tdocumentName: string\n\tvariant: string\n\tconfig: FormatConfig\n\t/** Fetch the rendered HTML's remote references into the document's `assets.zip`. */\n\tremoteAssets?: boolean\n\t/** Replaces the network fetch for those references. Studio passes a session cache. */\n\tremoteFetch?: RemoteAssetFetcher\n}\n\n/**\n * Render one variant of an already-compiled document and bundle the remote\n * references its HTML carries, without rebuilding the bundle.\n *\n * `compileBundle` runs this same render inline against its own long-lived\n * worker, one per build. This entry point owns a worker of its own, for callers\n * holding a bundle from an earlier compile — Studio renders each variant this\n * way rather than recompiling per download.\n */\nexport async function renderCompiledDocument(args: RenderCompiledDocumentArgs): Promise<string> {\n\tconst { outDir, documentName, variant, config, remoteAssets = false, remoteFetch } = args\n\n\tconst renderWorker = new RenderWorker({\n\t\tlog: msg => logger.debug(msg),\n\t\twarn: msg => logger.warn(msg),\n\t\tallowedReadPaths: [outDir],\n\t\tsandbox: 'strict'\n\t})\n\n\ttry {\n\t\tconst html = await renderVariantWithWorker({\n\t\t\trenderWorker,\n\t\t\toutDir,\n\t\t\tdocumentName,\n\t\t\tvariant,\n\t\t\tconfig,\n\t\t\tassetMode: 'static',\n\t\t\tprobeRemoteOnMismatch: remoteAssets,\n\t\t\tremoteFetch\n\t\t})\n\n\t\tawait processRemoteAssetRefs({ html, documentName, outDir, remoteAssets, remoteFetch })\n\n\t\treturn html\n\t} finally {\n\t\tawait renderWorker.dispose()\n\t}\n}\n\ntype BuildDocument = {\n\tname: string\n\tentryFilePath: string\n\tschemaPath?: string\n\texportName: string\n}\n\ninterface CompileBundleArgs {\n\tdocumentNames: string[]\n\tconfig: FormatConfig\n\toptions: NormalizedCompileOptions\n\tlogLevel: LogLevel\n\tsource: CompileSource\n\t/** Variant rendered by the node-target smoke test. Defaults to the default variant. */\n\tsmokeVariant?: string\n\t/** When provided, the smoke render writes each document's rendered HTML here, keyed by name. */\n\tcapturedHtml?: Map<string, string>\n\t/**\n\t * When provided, each document's computed asset state (known set + dynamic URL\n\t * map) is written here, keyed by name. The unplugin/Next.js paths read it back\n\t * to re-host assets, instead of re-deriving the map from the output on disk.\n\t */\n\tcapturedAssetState?: Map<string, DocumentAssetState>\n\t/** Per-document variant lists to render and write under output: 'html'. */\n\thtmlVariantMatrix?: Map<string, string[]>\n\t/** When provided, every source file the bundler read is added here (Studio, to invalidate its cache). */\n\tcapturedInputs?: Set<string>\n\t/** Replaces the network fetch for remote references (Studio's session cache). */\n\tremoteFetch?: RemoteAssetFetcher\n\t/**\n\t * Drop the progress and success reporting this compile would otherwise print.\n\t * Warnings and errors still go out, and `FORMAT_DEBUG` still shows everything.\n\t */\n\tquiet?: boolean\n}\n\nexport interface DocumentAssetState {\n\tknown: string[]\n\turlMap: Record<string, string> | null\n}\n\nasync function collectExternals(outDir: string, documentNames: string[]): Promise<string[]> {\n\tconst externals = new Set<string>()\n\tconst importRe = /(?:import|from)\\s+[\"']([^./][^\"']*)[\"']/g\n\n\tconst isNodeBuiltin = (specifier: string) => specifier.startsWith('node:') || builtinModules.includes(specifier)\n\n\tconst scanFile = async (filePath: string) => {\n\t\ttry {\n\t\t\tconst content = await readFile(filePath, 'utf-8')\n\t\t\tlet match\n\n\t\t\twhile ((match = importRe.exec(content)) !== null) {\n\t\t\t\tconst pkg = basePackageName(match[1]!)\n\n\t\t\t\tif (!isNodeBuiltin(pkg)) {\n\t\t\t\t\texternals.add(pkg)\n\t\t\t\t}\n\t\t\t}\n\t\t} catch {\n\t\t\t// file may not exist\n\t\t}\n\t}\n\n\tfor (const name of documentNames) {\n\t\tawait scanFile(resolve(outDir, name, BUNDLE_ENTRY_POINT_FILE_NAME))\n\t}\n\n\tconst chunksDir = resolve(outDir, 'chunks')\n\tconst chunkFiles = await readdir(chunksDir).catch(() => [] as string[])\n\n\tfor (const file of chunkFiles) {\n\t\tif (file.endsWith('.js')) {\n\t\t\tawait scanFile(resolve(chunksDir, file))\n\t\t}\n\t}\n\n\treturn [...externals].sort()\n}\n\n/**\n * HTML output ships only HTML, each document's `assets.zip`, and the manifest.\n * Remove the JS renderer artefacts left by the node build we rendered from: the\n * per-document wrappers, the bundle index, `package.json`, `externals.json`, the\n * shared chunks, and the root stylesheets (their CSS is already inlined into the\n * rendered HTML).\n */\nasync function stripJsArtefacts(outDir: string, documents: BuildDocument[]) {\n\tconst removals = documents.map(document => rm(getDocumentEntryPath(outDir, document.name), { force: true }))\n\n\tremovals.push(\n\t\trm(resolve(outDir, BUNDLE_ENTRY_POINT_FILE_NAME), { force: true }),\n\t\trm(resolve(outDir, 'package.json'), { force: true }),\n\t\trm(resolve(outDir, 'externals.json'), { force: true }),\n\t\trm(resolve(outDir, CHUNKS_DIR_NAME), { recursive: true, force: true })\n\t)\n\n\tconst rootEntries = await readdir(outDir, { withFileTypes: true }).catch(() => [])\n\n\tfor (const entry of rootEntries) {\n\t\tconst isRootStylesheet = entry.isFile() && entry.name.endsWith('.css')\n\n\t\tif (isRootStylesheet) {\n\t\t\tremovals.push(rm(resolve(outDir, entry.name), { force: true }))\n\t\t}\n\t}\n\n\tawait Promise.all(removals)\n}\n\n/**\n * Finalise HTML output: drop the JS artefacts and write the manifest grouping\n * each document's variants with the single shared zip they render from.\n */\nasync function writeHtmlOutput(args: {\n\toutDir: string\n\tbuildDocuments: BuildDocument[]\n\thtmlVariantEntries: Map<string, HtmlManifestVariant[]>\n}) {\n\tconst { outDir, buildDocuments, htmlVariantEntries } = args\n\n\tawait stripJsArtefacts(outDir, buildDocuments)\n\n\tconst documents: HtmlManifestDocument[] = []\n\n\tfor (const document of buildDocuments) {\n\t\tconst variants = htmlVariantEntries.get(document.name) ?? []\n\n\t\t// Checked on disk so a document whose zip came only from remote-asset\n\t\t// fetching (no local assets) is still listed correctly.\n\t\tconst assetsPath = getDocumentAssetsPath(outDir, document.name)\n\t\tconst hasAssets = await access(assetsPath).then(\n\t\t\t() => true,\n\t\t\t() => false\n\t\t)\n\n\t\tdocuments.push({\n\t\t\tdocument: document.name,\n\t\t\t...(hasAssets ? { assets: `${document.name}/${assetsFileName}` } : {}),\n\t\t\tvariants\n\t\t})\n\t}\n\n\tconst manifest: HtmlManifest = {\n\t\toutput: 'html',\n\t\tengine: engineTarget,\n\t\tdocuments\n\t}\n\n\tawait writeFile(resolve(outDir, MANIFEST_FILE_NAME), JSON.stringify(manifest, null, '\\t'), 'utf-8')\n}\n\nlet cssInJsVmPrewarm: Promise<void> | null = null\n\n/**\n * Pre-warm the module wyw-in-js loads when it evaluates CSS-in-JS.\n *\n * wyw-in-js extracts styles by running each component in a happy-dom VM, and\n * happy-dom loads Node's built-in `node:vm` the first time it builds a window.\n * Rolldown transforms modules in parallel, so two CSS-in-JS files can trigger\n * that load at the same instant — one `require()` then catches `node:vm`\n * mid-`import()` and Node throws \"Cannot require() ES Module node:vm because it\n * is not yet fully loaded\". Loading the graph once here, sequentially, fills the\n * module cache so the concurrent loads read from it instead of racing the\n * loader. `node:vm` is the module that actually races and is always resolvable;\n * happy-dom is what drags it in, so we warm that too when it resolves through\n * wyw-in-js. Cached so repeat builds in one process pay the cost only once.\n */\nfunction prewarmCssInJsVm(): Promise<void> {\n\tif (!cssInJsVmPrewarm) {\n\t\tcssInJsVmPrewarm = warmCssInJsVm()\n\t}\n\n\treturn cssInJsVmPrewarm\n}\n\nasync function warmCssInJsVm(): Promise<void> {\n\tawait import('node:vm')\n\n\ttry {\n\t\tconst requireFromStudio = createRequire(import.meta.url)\n\t\tconst requireFromVite = createRequire(requireFromStudio.resolve('@wyw-in-js/vite'))\n\t\tconst requireFromTransform = createRequire(requireFromVite.resolve('@wyw-in-js/transform'))\n\t\tconst happyDomEntry = requireFromTransform.resolve('happy-dom')\n\n\t\tawait import(pathToFileURL(happyDomEntry).href)\n\t} catch {\n\t\t// happy-dom may not resolve (e.g. a wyw-in-js version that no longer bundles\n\t\t// it). Warming node:vm above already covers the documented race.\n\t}\n}\n\nasync function compileBundle(args: CompileBundleArgs): Promise<StructuredOutput[]> {\n\tconst { documentNames, config, options, logLevel, source } = args\n\tconst { outDir: outDirOverride } = options\n\n\tconst isBrowserTarget = options.target === 'browser'\n\tconst isWorkerTarget = options.target === 'worker'\n\n\tconst assetMode: AssetMode = options.assets\n\tconst isHtmlOutput = options.output === 'html'\n\n\tconst isCli = source === 'cli'\n\tconst isUnplugin = source === 'unplugin'\n\n\tlogger.debug('Compile bundle context', {\n\t\tsource,\n\t\ttarget: options.target,\n\t\tuserBundler: options.userBundler\n\t})\n\n\tconst outDir = getBundleOutDir(config, outDirOverride)\n\tconst rootDir = getRootDir(config)\n\n\tif (resolve(outDir) === resolve(rootDir)) {\n\t\tthrow new CompileError(\n\t\t\t'outDir cannot be the same directory as rootDir. Please choose a different output directory before bundling.'\n\t\t)\n\t}\n\n\tif (options.clean) {\n\t\tawait rm(outDir, { recursive: true, force: true })\n\t}\n\n\tawait mkdir(outDir, { recursive: true })\n\n\tconst startTime = performance.now()\n\n\t// Never minify bundles for unplugin builds (user's bundler can choose to minify)\n\tconst shouldMinify = isUnplugin ? false : logLevel !== LogLevel.DEBUG\n\n\tconst exportNames = buildDocumentExportMap(documentNames)\n\tconst buildDocuments: BuildDocument[] = []\n\n\tfor (const documentName of documentNames) {\n\t\tconst entryFilePath = await getUserDocumentIndex({ documentName, config })\n\n\t\ttry {\n\t\t\tawait access(entryFilePath)\n\t\t} catch {\n\t\t\tthrow new Error(`Entry file not found at ${entryFilePath}`)\n\t\t}\n\n\t\tconst dataDir = getDocumentDataDir(documentName, config)\n\t\tconst schemaPath = await getSchemaPath(dataDir)\n\n\t\tbuildDocuments.push({\n\t\t\tname: documentName,\n\t\t\tentryFilePath,\n\t\t\tschemaPath: schemaPath ?? undefined,\n\t\t\texportName: exportNames.get(documentName)!\n\t\t})\n\t}\n\n\tconst { baseViteConfig, frameworkPlugins, stylePlugins } = createConfig()\n\n\t// Need fresh plugin instances per build, so state is _not_ cached between builds.\n\tconst makePlugins = () => [\n\t\thtmlLoader(),\n\t\tstylesPreProcessor(options.inlineRemoteCss),\n\t\t...frameworkPlugins,\n\t\t...stylePlugins,\n\t\tgetStyles()\n\t]\n\n\tconst format: Format = options.cjs ? 'cjs' : 'es'\n\n\tconst commonConfig = {\n\t\tdocuments: buildDocuments,\n\t\tcompiledFileName: BUNDLE_ENTRY_POINT_FILE_NAME,\n\t\tshouldMinify,\n\t\tformat,\n\t\tlogger,\n\t\temittedAssetsDir: SHARED_ASSETS_OUT_DIR_NAME,\n\t\tassetMode,\n\t\tconfig,\n\t\toptions,\n\t\tsource\n\t}\n\n\tconst buildTarget = isBrowserTarget ? 'browser' : isWorkerTarget ? 'worker' : 'node'\n\n\tconst buildConfig = makeViteBuildConfig({\n\t\t...commonConfig,\n\t\tplugins: makePlugins(),\n\t\ttarget: buildTarget,\n\t\toutDir\n\t})\n\n\tawait prewarmCssInJsVm()\n\n\t// All documents build in one Vite pass, so a build error doesn't say which\n\t// document broke. Best effort: match the failing module's path (or the error\n\t// message) against each document's directory.\n\tconst findDocumentForBuildError = (error: unknown): string | undefined => {\n\t\tconst errorShape = error as { id?: unknown; loc?: { file?: unknown }; message?: unknown } | null\n\t\tconst candidates = [errorShape?.id, errorShape?.loc?.file, errorShape?.message].filter(\n\t\t\t(value): value is string => typeof value === 'string'\n\t\t)\n\n\t\tconst failing = buildDocuments.find(document =>\n\t\t\tcandidates.some(candidate => candidate.includes(dirname(document.entryFilePath)))\n\t\t)\n\n\t\treturn failing?.name\n\t}\n\n\ttry {\n\t\tconst buildOutput = await build(mergeConfig(baseViteConfig, buildConfig))\n\n\t\tfor (const id of collectModuleIds(buildOutput)) {\n\t\t\targs.capturedInputs?.add(id)\n\t\t}\n\t} catch (error) {\n\t\tconst failingDocument = findDocumentForBuildError(error)\n\t\tconst documentLabel = failingDocument ? ` while building document \"${failingDocument}\"` : ''\n\n\t\tlogger.error(`Vite/Rollup Build Error${documentLabel}:`, error)\n\t\tthrow error\n\t}\n\n\tawait emitPackageJson(outDir, options.bundleName, format, options.version)\n\n\tconst writeBundleIndex = async (targetOutDir: string, bundleFormat: Format) => {\n\t\tconst exportNames = buildDocuments.map(doc => doc.exportName)\n\n\t\tif (bundleFormat === 'cjs') {\n\t\t\tconst requireLines = buildDocuments.map(doc => {\n\t\t\t\tconst relPath = `./${doc.name}/${BUNDLE_ENTRY_POINT_FILE_NAME}`.replace(/\\\\/g, '/')\n\t\t\t\treturn `const { ${doc.exportName} } = require(${JSON.stringify(relPath)});`\n\t\t\t})\n\n\t\t\tconst output = [...requireLines, '', `module.exports = { ${exportNames.join(', ')} };`, ''].join('\\n')\n\n\t\t\tawait writeFile(resolve(targetOutDir, BUNDLE_ENTRY_POINT_FILE_NAME), output, 'utf8')\n\t\t\treturn\n\t\t}\n\n\t\tconst importLines = buildDocuments.map(doc => {\n\t\t\tconst relPath = `./${doc.name}/${BUNDLE_ENTRY_POINT_FILE_NAME}`.replace(/\\\\/g, '/')\n\t\t\treturn `import { ${doc.exportName} } from ${JSON.stringify(relPath)};`\n\t\t})\n\t\tconst output = [\n\t\t\t...importLines,\n\t\t\t'',\n\t\t\t`export { ${exportNames.join(', ')} };`,\n\t\t\t`export default { ${exportNames.join(', ')} };`,\n\t\t\t''\n\t\t].join('\\n')\n\n\t\tawait writeFile(resolve(targetOutDir, BUNDLE_ENTRY_POINT_FILE_NAME), output, 'utf8')\n\t}\n\n\tawait writeBundleIndex(outDir, format)\n\n\t// Per-document asset bundling. Static mode zips each document's full merged\n\t// set (shared assets dir + per-doc ./assets/ + Vite-emitted) — no filtering by\n\t// rendered HTML, so any variant renders from a single zip. Dynamic mode\n\t// materialises the files next to the bundle and embeds a URL map instead.\n\tconst stagingRoot = resolve(outDir, '__assets_staging')\n\tconst documentAssetState = new Map<string, DocumentAssetState>()\n\n\t// Dynamic mode shares one `shared-assets/` dir across documents (the\n\t// sharedAssetsDir contents + Vite-emitted images and fonts). Materialise it\n\t// once and reuse its URL map for every document, so nothing is duplicated.\n\tconst sharedDynamicUrlMap =\n\t\tassetMode === 'dynamic'\n\t\t\t? await materialiseSharedDynamicAssets({ config, outDir, sharedAssetsOutDirName: SHARED_ASSETS_OUT_DIR_NAME })\n\t\t\t: {}\n\n\t// Each document's staging dir and output dir are its own, so documents\n\t// materialise in parallel.\n\tconst materialiseDocumentAssets = async (document: BuildDocument): Promise<DocumentAssetState> => {\n\t\tif (assetMode === 'none') {\n\t\t\treturn { known: [], urlMap: null }\n\t\t}\n\n\t\tconst sources = await resolveDocumentAssetSources({\n\t\t\tentryFilePath: document.entryFilePath,\n\t\t\tconfig,\n\t\t\toutDir,\n\t\t\tsharedAssetsOutDirName: SHARED_ASSETS_OUT_DIR_NAME\n\t\t})\n\n\t\tif (assetMode === 'static') {\n\t\t\tconst staticAssets = await buildDocumentStaticAssets(sources, resolve(stagingRoot, document.name))\n\t\t\tconst unsupportedCount = staticAssets.unsupported.length\n\n\t\t\tif (unsupportedCount > 0) {\n\t\t\t\tlogger.warn(\n\t\t\t\t\t`⚠ Skipped ${unsupportedCount} ${pluralize('file', unsupportedCount)} in the assets for ${document.name} ` +\n\t\t\t\t\t\t`that renders can't use: ${staticAssets.unsupported.join(', ')}. Renders accept fonts, images, CSS, and JSON.`\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tif (staticAssets.zip) {\n\t\t\t\tawait mkdir(getDocumentOutDir(outDir, document.name), { recursive: true })\n\t\t\t\tawait writeFile(getDocumentAssetsPath(outDir, document.name), staticAssets.zip)\n\t\t\t}\n\n\t\t\treturn { known: staticAssets.known, urlMap: null }\n\t\t}\n\n\t\tconst dynamicAssets = await buildDocumentDynamicAssets({\n\t\t\tdocumentAssetsDir: sources.documentAssetsDir,\n\t\t\tdocumentOutDir: getDocumentOutDir(outDir, document.name),\n\t\t\tsharedUrlMap: sharedDynamicUrlMap\n\t\t})\n\n\t\treturn { known: dynamicAssets.known, urlMap: dynamicAssets.urlMap }\n\t}\n\n\ttry {\n\t\tawait Promise.all(\n\t\t\tbuildDocuments.map(async document => {\n\t\t\t\tdocumentAssetState.set(document.name, await materialiseDocumentAssets(document))\n\t\t\t})\n\t\t)\n\t} finally {\n\t\tawait rm(stagingRoot, { recursive: true, force: true }).catch(() => {})\n\t}\n\n\t// Bake each document's known-asset set (and dynamic URL map) into its\n\t// emitted wrapper. No-op for unplugin builds — their wrapper is generated\n\t// after compile, reading the captured asset state below with the values\n\t// inlined directly.\n\tawait Promise.all(\n\t\tbuildDocuments.map(async document => {\n\t\t\tconst assetState = documentAssetState.get(document.name)\n\n\t\t\tif (!assetState) {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\targs.capturedAssetState?.set(document.name, assetState)\n\n\t\t\tawait bakeWrapperAssetConstants({\n\t\t\t\tentryPath: getDocumentEntryPath(outDir, document.name),\n\t\t\t\tknown: assetState.known,\n\t\t\t\turlMap: assetState.urlMap\n\t\t\t})\n\t\t})\n\t)\n\n\t// `none` ships no asset bundle, but the bundler still content-hashes and\n\t// emits anything imported as a module. Those imports can't be resolved by\n\t// name and won't ship in this mode, so warn rather than let them vanish\n\t// silently. Path references (e.g. `<img src=\"logo.png\">`) are unaffected —\n\t// the consumer supplies those bytes themselves.\n\tif (assetMode === 'none') {\n\t\tconst emittedDir = resolve(outDir, SHARED_ASSETS_OUT_DIR_NAME)\n\t\tconst emittedEntries = await readdir(emittedDir, { recursive: true, withFileTypes: true }).catch(() => [])\n\t\tconst emittedCount = emittedEntries.filter(entry => entry.isFile()).length\n\n\t\tif (emittedCount > 0) {\n\t\t\tlogger.warn(\n\t\t\t\t`⚠ --assets none, but the bundle imported ${emittedCount} ${pluralize('asset', emittedCount)} ` +\n\t\t\t\t\t`(e.g. \\`import logo from './logo.png'\\`). Imported assets are content-hashed and managed by the build, ` +\n\t\t\t\t\t`so they can't be resolved by name and won't ship in this mode. Reference assets by path ` +\n\t\t\t\t\t`(e.g. \\`<img src=\"logo.png\">\\`) to supply them yourself, or use --assets static or dynamic to bundle them.`\n\t\t\t)\n\t\t}\n\t}\n\n\t// Static and none modes don't ship the loose Vite-emitted assets: static\n\t// folds them into each document's zip, none emits nothing. Either way the\n\t// shared `shared-assets/` dir is build state, so drop it.\n\tif (assetMode === 'static' || assetMode === 'none') {\n\t\tawait rm(resolve(outDir, SHARED_ASSETS_OUT_DIR_NAME), { recursive: true, force: true }).catch(() => {})\n\t}\n\n\t// The remote-reference pass needs rendered HTML, which node-target builds\n\t// produce at build time: CLI dynamic compiles smoke-render the default\n\t// variant, and HTML output renders every variant. Both qualify.\n\tconst canProcessRemoteRefs = assetMode === 'static' && options.target === 'node' && (isCli || isHtmlOutput)\n\n\t// The mode/target legs of this incompatibility are warned upfront at options\n\t// normalisation. The one left to surface here is source-dependent, which\n\t// normalisation can't see: a bundler-driven (unplugin) build never renders at\n\t// build time, so there is no HTML to fetch remote references from.\n\tconst remoteAssetsBlockedBySource =\n\t\toptions.remoteAssets && !canProcessRemoteRefs && assetMode === 'static' && options.target === 'node'\n\n\tif (remoteAssetsBlockedBySource) {\n\t\tlogger.warn(\n\t\t\t'remoteAssets was set but cannot be honoured here: fetching remote assets requires a CLI compile, where the document renders at build time. Skipping remote asset fetching.'\n\t\t)\n\t}\n\n\t// Node bundles are runnable as-is, so render the real artifact: import each\n\t// document's emitted wrapper and run it. Dynamic output smoke-renders the\n\t// default variant (CLI only) to catch broken externals, module-load failures,\n\t// and default-variant asset mismatches at build time. HTML output renders\n\t// every selected variant and writes each result to disk — that is its whole\n\t// artefact, so it runs regardless of source. Browser/worker artifacts can't\n\t// run here — their failures surface in Studio dev or at the first render.\n\tconst htmlVariantEntries = new Map<string, HtmlManifestVariant[]>()\n\n\tif (options.target === 'node' && (isCli || isHtmlOutput)) {\n\t\tconst renderWorker = new RenderWorker({\n\t\t\tlog: msg => logger.debug(msg),\n\t\t\twarn: msg => logger.warn(msg),\n\t\t\tallowedReadPaths: [outDir],\n\t\t\tsandbox: 'strict'\n\t\t})\n\n\t\tconst smokeVariant = args.smokeVariant ?? DEFAULT_VARIANT\n\n\t\ttry {\n\t\t\tfor (const document of buildDocuments) {\n\t\t\t\tconst variants = isHtmlOutput ? (args.htmlVariantMatrix?.get(document.name) ?? []) : [smokeVariant]\n\n\t\t\t\tfor (const variant of variants) {\n\t\t\t\t\tconst html = await renderVariantWithWorker({\n\t\t\t\t\t\trenderWorker,\n\t\t\t\t\t\toutDir,\n\t\t\t\t\t\tdocumentName: document.name,\n\t\t\t\t\t\tvariant,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tassetMode,\n\t\t\t\t\t\tprobeRemoteOnMismatch: canProcessRemoteRefs && options.remoteAssets,\n\t\t\t\t\t\tremoteFetch: args.remoteFetch\n\t\t\t\t\t})\n\n\t\t\t\t\t// Per variant so the document's shared zip accumulates the union of\n\t\t\t\t\t// every variant's remote references — any variant then resolves from it.\n\t\t\t\t\tif (canProcessRemoteRefs) {\n\t\t\t\t\t\tawait processRemoteAssetRefs({\n\t\t\t\t\t\t\thtml,\n\t\t\t\t\t\t\tdocumentName: document.name,\n\t\t\t\t\t\t\toutDir,\n\t\t\t\t\t\t\tremoteAssets: options.remoteAssets,\n\t\t\t\t\t\t\tremoteFetch: args.remoteFetch,\n\t\t\t\t\t\t\tquiet: args.quiet\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isHtmlOutput) {\n\t\t\t\t\t\targs.capturedHtml?.set(document.name, html)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\n\t\t\t\t\tconst htmlPath = getHtmlVariantPath(outDir, document.name, variant)\n\t\t\t\t\tawait mkdir(dirname(htmlPath), { recursive: true })\n\t\t\t\t\tawait writeFile(htmlPath, html, 'utf-8')\n\n\t\t\t\t\tconst entries = htmlVariantEntries.get(document.name) ?? []\n\t\t\t\t\tentries.push({ variant, html: `${document.name}/${variant}/${INDEX_HTML_FILE_NAME}` })\n\t\t\t\t\thtmlVariantEntries.set(document.name, entries)\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tawait renderWorker.dispose()\n\t\t}\n\t}\n\n\t// HTML output ships rendered HTML, not a runnable bundle, so it writes the\n\t// manifest and strips the JS artefacts instead of recording externals.\n\tif (isHtmlOutput) {\n\t\tawait writeHtmlOutput({ outDir, buildDocuments, htmlVariantEntries })\n\t}\n\n\tif (!isHtmlOutput) {\n\t\tconst externals = await collectExternals(outDir, documentNames)\n\t\tconst externalsPayload = { target: options.target, externals }\n\n\t\tawait writeFile(resolve(outDir, 'externals.json'), JSON.stringify(externalsPayload, null, '\\t'), 'utf-8')\n\n\t\tlogger.debug(`Externals for ${options.target}:`, externals.length ? externals.join(', ') : '(none)')\n\t}\n\n\tconst endTime = performance.now()\n\tconst compiledIn = `${(endTime - startTime).toFixed(2)}ms`\n\n\tconst documentName = buildDocuments.length === 1 ? buildDocuments[0]!.name : `${buildDocuments.length} documents`\n\n\tconst structuredOutput = createStructuredOutput({\n\t\tdocumentName,\n\t\toutDir,\n\t\tcompiledIn\n\t})\n\n\tconst isDebug = getLogLevel() === LogLevel.DEBUG\n\n\t// A quiet compile is work the user didn't ask for — a background build after\n\t// a preview render — so it says nothing on success. FORMAT_DEBUG still shows it.\n\tif ((isCli && !args.quiet) || isDebug) {\n\t\tlogger.info(\n\t\t\tgradient(`✓ Successfully compiled ${documentName}`),\n\t\t\t'\\n',\n\t\t\tJSON.stringify(structuredOutput, null, 2),\n\t\t\t'\\n'\n\t\t)\n\t}\n\n\treturn [structuredOutput]\n}\n\nfunction warnIgnoredOption(message: string) {\n\tlogger.warn(`ℹ ${message}`)\n}\n\n/**\n * Map each document to the data variants HTML output should render. Throws on\n * the two unrecoverable cases — a selected document with no data at all, and a\n * requested variant that exists for no document — and warns per document for a\n * requested variant that only some documents have.\n */\nexport function resolveHtmlVariantMatrix(documents: Document[], requestedVariants: string[]): Map<string, string[]> {\n\tconst documentsWithoutData = documents.filter(document => document.variants.length === 0)\n\n\tif (documentsWithoutData.length > 0) {\n\t\tconst names = documentsWithoutData.map(document => `\"${document.name}\"`).join(', ')\n\n\t\tthrow new CompileError(\n\t\t\t`Can't use --output html for ${names}: no data files found. Add at least a \\`data/${DEFAULT_VARIANT}.json\\`.`\n\t\t)\n\t}\n\n\tconst matrix = new Map<string, string[]>()\n\n\tif (requestedVariants.length === 0) {\n\t\tfor (const document of documents) {\n\t\t\tmatrix.set(document.name, document.variants)\n\t\t}\n\n\t\treturn matrix\n\t}\n\n\tconst orphanVariants = requestedVariants.filter(\n\t\tvariant => !documents.some(document => document.variants.includes(variant))\n\t)\n\n\tif (orphanVariants.length > 0) {\n\t\tconst names = orphanVariants.map(variant => `\"${variant}\"`).join(', ')\n\n\t\tthrow new CompileError(\n\t\t\t`No document has the variant(s) ${names}. Check the names against your \\`data/*.json\\` files.`\n\t\t)\n\t}\n\n\tfor (const document of documents) {\n\t\tconst selected = requestedVariants.filter(variant => document.variants.includes(variant))\n\t\tconst missing = requestedVariants.filter(variant => !document.variants.includes(variant))\n\n\t\tif (missing.length > 0) {\n\t\t\tconst names = missing.map(variant => `\"${variant}\"`).join(', ')\n\t\t\tlogger.warn(`Document \"${document.name}\" has no variant(s) ${names}; skipping for this document.`)\n\t\t}\n\n\t\tmatrix.set(document.name, selected)\n\t}\n\n\treturn matrix\n}\n\n/**\n * HTML output renders from a forced node build with assets bundled at build\n * time, so the JS-bundle and asset-mode flags have nothing to act on. None of\n * them is build-breaking — we override and warn per flag. The genuinely\n * unrecoverable cases (a document with no data, an unknown variant) are errors,\n * raised later in resolveHtmlVariantMatrix.\n */\nexport function warnIncompatibleHtmlOptions(options: NormalizedCompileOptions) {\n\tconst warnIgnored = (flag: string) =>\n\t\twarnIgnoredOption(`The ${flag} flag is not compatible with html output, ignoring.`)\n\n\tif (options.target !== 'node') {\n\t\twarnIgnored('--target')\n\t}\n\n\tif (options.preset !== 'node') {\n\t\twarnIgnored('--preset')\n\t}\n\n\tif (options.assets !== 'static') {\n\t\twarnIgnored('--assets')\n\t}\n\n\tif (options.external.length > 0) {\n\t\twarnIgnored('--external')\n\t}\n\n\tif (options.bundle.length > 0) {\n\t\twarnIgnored('--bundle')\n\t}\n\n\tif (options.conditions.length > 0) {\n\t\twarnIgnored('--conditions')\n\t}\n\n\tif (options.externalConditions.length > 0) {\n\t\twarnIgnored('--external-conditions')\n\t}\n\n\tif (options.cjs) {\n\t\twarnIgnored('--cjs')\n\t}\n\n\tif (options.version) {\n\t\twarnIgnored('--version')\n\t}\n}\n\ninterface RunCompileArgs {\n\t/** Raw consumer options; normalised here so every entry point shares one path. */\n\toptions: CompileOptions\n\tsource: CompileSource\n\t/** Variant the node-target smoke render uses (Studio only). Defaults to the default variant. */\n\tsmokeVariant?: string\n\t/** Collector the smoke render fills with each document's rendered HTML (Studio only). */\n\tcapturedHtml?: Map<string, string>\n\t/** Collector filled with each document's asset state (unplugin/Next.js, to re-host assets). */\n\tcapturedAssetState?: Map<string, DocumentAssetState>\n\t/** Collector filled with every source file the bundler read (Studio only). */\n\tcapturedInputs?: Set<string>\n\t/** Replaces the network fetch for remote references (Studio only). */\n\tremoteFetch?: RemoteAssetFetcher\n\t/** Suppress success and progress reporting (Studio background builds). */\n\tquiet?: boolean\n\t/**\n\t * Read and write the `.cache` hash in `outDir`. Studio owns its own bundle\n\t * directory and invalidates on a finer input set, so it turns this off — and\n\t * a hit here would skip the smoke render Studio needs the HTML from.\n\t */\n\tuseDiskCache?: boolean\n}\n\nasync function runCompile(runArgs: RunCompileArgs): Promise<StructuredOutput[]> {\n\tconst { options: inputOptions, source, smokeVariant, capturedHtml, capturedAssetState, capturedInputs } = runArgs\n\n\tsetLogLevel(parseLogLevelFromEnv())\n\tconst logLevel = getLogLevel()\n\n\tconst isCli = source === 'cli'\n\n\t// Unplugin builds default to clean: false — the consumer bundler owns the\n\t// output directory's lifecycle.\n\tconst rawOptions = normalizeCompileOptions(\n\t\tsource === 'unplugin' ? { ...inputOptions, clean: inputOptions.clean ?? false } : inputOptions\n\t)\n\n\tconst isHtmlOutput = rawOptions.output === 'html'\n\n\tif (isHtmlOutput) {\n\t\twarnIncompatibleHtmlOptions(rawOptions)\n\t}\n\n\t// HTML output has no JS runtime, so the bundle-shaping options are\n\t// meaningless. Force a node render build with bundled assets; the warning\n\t// above tells the user which of their flags were dropped.\n\tconst options: NormalizedCompileOptions = isHtmlOutput\n\t\t? {\n\t\t\t\t...rawOptions,\n\t\t\t\ttarget: 'node',\n\t\t\t\tpreset: 'node',\n\t\t\t\tassets: 'static',\n\t\t\t\tcjs: false,\n\t\t\t\texternal: [],\n\t\t\t\tbundle: [],\n\t\t\t\tconditions: [],\n\t\t\t\texternalConditions: [],\n\t\t\t\tbundleAll: false\n\t\t\t}\n\t\t: rawOptions\n\n\tlogger.debug('Compile options', options)\n\n\tconst { documents: documentNames } = options\n\n\tconst { config } = await loadConfig(options.configPath)\n\n\tif (!config) {\n\t\tthrow new Error(NO_CONFIG_FILE_MESSAGE)\n\t}\n\n\t// after loadConfig, which is what sets the project dir — before it, this reads\n\t// whatever directory the command was launched from\n\tassertProducersAgree(getUserProjectDir())\n\n\tcompileState.setConfig(config)\n\n\tconst allDocuments = await getDocuments(config)\n\n\tconst documents = allDocuments\n\t\t.filter(({ name }) => documentNames.length === 0 || documentNames.includes(name))\n\t\t.sort((a, b) => a.name.localeCompare(b.name))\n\n\tconst missingDocuments = documentNames.filter(\n\t\tname => !allDocuments.some(({ name: documentName }) => documentName === name)\n\t)\n\n\tif (missingDocuments.length > 0) {\n\t\tlogger.warn(`Couldn't find the following documents: \"${missingDocuments.join(', ')}\"`)\n\t}\n\n\tif (documents.length === 0) {\n\t\tthrow new Error(NO_DOCUMENTS_MESSAGE)\n\t}\n\n\t// Fail on export-name collisions before any build work starts — compileBundle\n\t// would otherwise only hit this after cleaning the output directory.\n\tbuildDocumentExportMap(documents.map(({ name }) => name))\n\n\t// The default `assets/` dir is optional, but an explicitly configured one\n\t// that's missing is a mistake worth failing on.\n\tif (config.sharedAssetsDir) {\n\t\tconst sharedAssetsDir = getSharedAssetsDir(config)\n\t\tconst { isDirectory } = await checkDir(sharedAssetsDir)\n\t\tif (!isDirectory) {\n\t\t\tthrow new Error(`Your configured \\`sharedAssetsDir\\` not found or is not a directory: ${sharedAssetsDir}`)\n\t\t}\n\t}\n\n\tconst htmlVariantMatrix = isHtmlOutput ? resolveHtmlVariantMatrix(documents, options.variants) : undefined\n\n\tconst outDir = getBundleOutDir(config, options.outDir)\n\n\t// CLI and unplugin builds use disk-persisted caching to skip recompilation\n\t// when nothing changed. HTML output isn't cached: it renders the whole\n\t// variant matrix and always writes fresh HTML. Dynamic-mode unplugin builds\n\t// aren't cached either — the plugin needs the per-document asset state a\n\t// compile captures, and a cache hit would skip capturing it.\n\tconst isCacheableRun =\n\t\t(runArgs.useDiskCache ?? true) &&\n\t\t(isCli || (source === 'unplugin' && options.assets !== 'dynamic')) &&\n\t\t!isHtmlOutput\n\n\t// The consumer bundler only changes compile output through the webpack-node\n\t// compat rewrite (see make-config), so key on that fact rather than the raw\n\t// bundler name — vite/rollup/esbuild consumers then share one cached compile.\n\tconst cacheKeyOptions = buildCacheKeyOptions({\n\t\toptions,\n\t\twebpackNodeCompat: options.target === 'node' && source === 'unplugin' && options.userBundler === 'webpack'\n\t})\n\n\tif (isCacheableRun) {\n\t\tconst documentsDir = getDocumentsDir(config)\n\t\tconst currentHash = await computeCacheHash(documentsDir, cacheKeyOptions)\n\t\tconst cachedHash = await readCachedHash(outDir)\n\n\t\tif (cachedHash === currentHash) {\n\t\t\tconst expectedEntryPaths = documents.map(({ name }) => getDocumentEntryPath(outDir, name))\n\t\t\tconst outputsPresent = await cachedOutputsExist(expectedEntryPaths)\n\n\t\t\tif (outputsPresent) {\n\t\t\t\tlogger.info('Cache hit — documents unchanged, skipping compile.')\n\t\t\t\treturn []\n\t\t\t}\n\n\t\t\tlogger.debug('Cache hash matched but compiled outputs are missing — recompiling.')\n\t\t}\n\t}\n\n\tconst runAll = () =>\n\t\tcompileBundle({\n\t\t\tdocumentNames: documents.map(({ name }) => name),\n\t\t\tconfig,\n\t\t\toptions,\n\t\t\tlogLevel,\n\t\t\tsource,\n\t\t\tsmokeVariant,\n\t\t\tcapturedHtml,\n\t\t\tcapturedAssetState,\n\t\t\tcapturedInputs,\n\t\t\tremoteFetch: runArgs.remoteFetch,\n\t\t\tquiet: runArgs.quiet,\n\t\t\thtmlVariantMatrix\n\t\t})\n\n\tconst suppressBuildLogs = (_level: string, ...args: unknown[]) => {\n\t\tconst msg = args.join(' ')\n\n\t\tif (msg.includes('building SSR bundle for production')) return false\n\t\tif (msg.includes('vite v') && msg.includes('building')) return false\n\t\tif (msg.includes('built in')) return false\n\n\t\treturn true\n\t}\n\n\tconst results = isCli\n\t\t? ((await withPrefixedConsole(() => runAll(), suppressBuildLogs)) as StructuredOutput[])\n\t\t: await runAll()\n\n\t// Write cache hash after successful compilation\n\tif (isCacheableRun) {\n\t\tconst documentsDir = getDocumentsDir(config)\n\t\tconst currentHash = await computeCacheHash(documentsDir, cacheKeyOptions)\n\t\tawait writeCacheHash(outDir, currentHash)\n\t}\n\n\tconst { external } = options\n\tconst externalLen = external.length\n\n\tif (isCli && externalLen > 0 && !runArgs.quiet) {\n\t\tlogger.info(\n\t\t\t`ℹ External packages: ${external.join(', ')}. Make sure ${pluralize('this', externalLen)} ${pluralize(\n\t\t\t\t'is',\n\t\t\t\texternalLen\n\t\t\t)} installed where you call render.`\n\t\t)\n\t}\n\n\treturn results\n}\n\nexport async function compile(options: CompileOptions): Promise<StructuredOutput[]> {\n\tawait warnOnLockstepDrift(options.configPath ? dirname(options.configPath) : process.cwd())\n\n\treturn runCompile({ options, source: 'cli' })\n\t\t.then(() => process.exit(0))\n\t\t.catch(error => {\n\t\t\tlogger.error('Compile error', error)\n\t\t\tprocess.exit(1)\n\t\t})\n}\n\nexport interface StudioCompileOptions {\n\t/**\n\t * Variant the node-target smoke render uses. The download route passes the\n\t * variant being downloaded so its remote assets land in the zip and its\n\t * rendered HTML comes back ready to send. Defaults to the default variant.\n\t */\n\tvariant?: string\n\t/**\n\t * Use the compile package's own `.cache` hash in `outDir`. Off for callers\n\t * that keep the output directory and track its inputs themselves — a hit\n\t * skips the smoke render, so the HTML would come back empty.\n\t */\n\tuseDiskCache?: boolean\n\t/**\n\t * Replaces the network fetch for remote references. Studio passes a\n\t * session-wide cache so a rebuilt bundle doesn't download every remote asset\n\t * again.\n\t */\n\tremoteFetch?: RemoteAssetFetcher\n\t/**\n\t * Compile without the usual success and progress reporting. Studio sets this\n\t * for background builds, which the user never asked for and shouldn't have to\n\t * read about on every save. Warnings and errors are unaffected, and\n\t * `FORMAT_DEBUG=true` restores the full output.\n\t */\n\tquiet?: boolean\n}\n\nexport interface StudioCompileResult {\n\toutputs: StructuredOutput[]\n\t/** Each document's smoke-rendered HTML, keyed by document name. */\n\thtml: Map<string, string>\n\t/**\n\t * Absolute paths of every source file the bundler read. Studio stats these to\n\t * decide whether a kept bundle is still current. Empty when the compile was\n\t * served from the disk cache.\n\t */\n\tinputs: string[]\n}\n\nexport async function compileForStudio(\n\toptions: CompileOptions,\n\tstudioOptions: StudioCompileOptions = {}\n): Promise<StudioCompileResult> {\n\tconst capturedHtml = new Map<string, string>()\n\tconst capturedInputs = new Set<string>()\n\n\tconst outputs = await runCompile({\n\t\toptions,\n\t\tsource: 'cli',\n\t\tsmokeVariant: studioOptions.variant,\n\t\tcapturedHtml,\n\t\tcapturedInputs,\n\t\tuseDiskCache: studioOptions.useDiskCache,\n\t\tremoteFetch: studioOptions.remoteFetch,\n\t\tquiet: studioOptions.quiet\n\t})\n\n\treturn { outputs, html: capturedHtml, inputs: [...capturedInputs] }\n}\n\nexport async function compileForUnplugin(\n\toptions: CompileOptions,\n\textras: { capturedAssetState?: Map<string, DocumentAssetState> } = {}\n): Promise<StructuredOutput[]> {\n\treturn runCompile({ options, source: 'unplugin', capturedAssetState: extras.capturedAssetState })\n}\n\nexport async function compileForTest(options: CompileOptions): Promise<StructuredOutput[]> {\n\t// Using the Unplugin entrypoint for compile tests, as it's the same as the unplugin process and tests\n\treturn compileForUnplugin(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkEA,SAAgB,iBAAiB,QAAsB;AACtD,QAAO,QAAQ,WAAW,OAAO,EAAE,qBAAqB;;AAGzD,SAAgB,gBAAgB,QAAsB,gBAAgC;AACrF,QAAO,kBAAkB,OAAO,QAAQ,eAAe,GAAG,iBAAiB,OAAO;;AAGnF,MAAM,iBAAiB;AAEvB,SAAgB,kBAAkB,QAAgB,cAAsB;AACvE,QAAO,QAAQ,QAAQ,aAAa;;AAGrC,SAAgB,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GACd;;AA2CJ,eAAsB,iBACrB,SACA,gBAAsC,EAAE,EACT;CAC/B,MAAM,+BAAe,IAAI,KAAqB;CAC9C,MAAM,iCAAiB,IAAI,KAAa;AAaxC,QAAO;EAAE,SAXO,MAAM,WAAW;GAChC;GACA,QAAQ;GACR,cAAc,cAAc;GAC5B;GACA;GACA,cAAc,cAAc;GAC5B,aAAa,cAAc;GAC3B,OAAO,cAAc;GACrB,CAAC;EAEgB,MAAM;EAAc,QAAQ,CAAC,GAAG,eAAe;EAAE;;AAGpE,eAAsB,mBACrB,SACA,SAAmE,EAAE,EACvC;AAC9B,QAAO,WAAW;EAAE;EAAS,QAAQ;EAAY,oBAAoB,OAAO;EAAoB,CAAC;;AAGlG,eAAsB,eAAe,SAAsD;AAE1F,QAAO,mBAAmB,QAAQ"}
|
|
@@ -30,6 +30,8 @@ interface StaticAssetsResult {
|
|
|
30
30
|
known: string[];
|
|
31
31
|
/** The merged archive, or undefined when the document has no assets. */
|
|
32
32
|
zip: Uint8Array | undefined;
|
|
33
|
+
/** Files left out because renders can't use their type, such as a font licence `.txt`. */
|
|
34
|
+
unsupported: string[];
|
|
33
35
|
}
|
|
34
36
|
/**
|
|
35
37
|
* Build one document's merged `assets.zip` (static mode): the full merged set,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-assets.d.mts","names":[],"sources":["../../../src/server/compile/document-assets.ts"],"sourcesContent":[],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"document-assets.d.mts","names":[],"sources":["../../../src/server/compile/document-assets.ts"],"sourcesContent":[],"mappings":";;;;cAUa,wBAAA;AAAb;AAUA;AAKC;AAUD;;;;;AA2EiB,UA1FA,oBAAA,CA8FX;EAkBgB,eAAA,EAAA,MAAA,GAAA,IAAyB;EACrC,iBAAA,EAAA,MAAA,GAAA,IAAA;EAEC;EAAR,UAAA,EAAA,MAAA,GAAA,IAAA;;AAwBH,UApIU,kBAAA,CAoIO;EAiBD;EAiBC,aAAA,EAAA,MAAA;EAuBK,MAAA,EA1Lb,YA0La;EACb,MAAA,EAAA,MAAA;EAGG,sBAAA,EAAA,MAAA;;AAAD,iBAzLW,2BAAA,CAyLX,IAAA,EAzL6C,kBAyL7C,CAAA,EAzLkE,OAyLlE,CAzL0E,oBAyL1E,CAAA;AAwCW,UAtJL,kBAAA,CAsJ+B;EAGjC;EACH,KAAA,EAAA,MAAA,EAAA;EAAR;EAAO,GAAA,EAtJL,UAsJK,GAAA,SAAA;;;;;;;;;;;iBApIW,yBAAA,UACZ,2CAEP,QAAQ;UAwBM,yBAAA;;;;;;;;;;;;;;;;iBAiBD,uBAAA;;;UAGP;IACL;UAaa,mBAAA;;;;;;;UAOR;;;;;;;;;;;;;;;iBAgBa,8BAAA;UACb;;;IAGL,QAAQ;;;;;;;iBAwCU,0BAAA;;;gBAGP;IACX,QAAQ"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { getSharedAssetsDir } from "../project/paths.mjs";
|
|
2
2
|
import { checkDir } from "../utils/check-dir.mjs";
|
|
3
3
|
import "../utils/index.mjs";
|
|
4
|
-
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
5
5
|
import { cp, mkdir, readdir, rm, stat } from "node:fs/promises";
|
|
6
6
|
import { isSystemJunkFile, zipDir } from "@format.dev/zip";
|
|
7
|
+
import { isUserAssetExtension } from "@format.dev/utils";
|
|
7
8
|
|
|
8
9
|
//#region src/server/compile/document-assets.ts
|
|
9
10
|
/** Reserved co-location folder: `documents/<name>/assets/` travels with the document. */
|
|
@@ -62,6 +63,9 @@ async function overlayDocumentSources(sources, destDir) {
|
|
|
62
63
|
dereference: true
|
|
63
64
|
});
|
|
64
65
|
}
|
|
66
|
+
function isRenderableAsset(file) {
|
|
67
|
+
return isUserAssetExtension(extname(file).slice(1).toLowerCase());
|
|
68
|
+
}
|
|
65
69
|
/**
|
|
66
70
|
* Build one document's merged `assets.zip` (static mode): the full merged set,
|
|
67
71
|
* with no filtering by rendered HTML — any variant renders from the same zip.
|
|
@@ -84,9 +88,14 @@ async function buildDocumentStaticAssets(sources, stagingDir) {
|
|
|
84
88
|
});
|
|
85
89
|
}
|
|
86
90
|
try {
|
|
91
|
+
const files = await listFiles(stagingDir);
|
|
92
|
+
const known = files.filter((file) => isRenderableAsset(file));
|
|
93
|
+
const unsupported = files.filter((file) => !isRenderableAsset(file));
|
|
94
|
+
await Promise.all(unsupported.map((file) => rm(join(stagingDir, file), { force: true })));
|
|
87
95
|
return {
|
|
88
|
-
known
|
|
89
|
-
zip: await zipDir(stagingDir)
|
|
96
|
+
known,
|
|
97
|
+
zip: await zipDir(stagingDir),
|
|
98
|
+
unsupported
|
|
90
99
|
};
|
|
91
100
|
} finally {
|
|
92
101
|
await rm(stagingDir, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-assets.mjs","names":["urlMap: Record<string, string>"],"sources":["../../../src/server/compile/document-assets.ts"],"sourcesContent":["import type { FormatConfig } from '../../shared/types'\n\nimport { basename, dirname, join, relative, resolve } from 'node:path'\nimport { cp, mkdir, readdir, rm, stat } from 'node:fs/promises'\nimport { zipDir, isSystemJunkFile } from '@format.dev/zip'\nimport { getSharedAssetsDir } from '../project/paths'\nimport { checkDir } from '../utils'\n\n/** Reserved co-location folder: `documents/<name>/assets/` travels with the document. */\nexport const DOCUMENT_ASSETS_DIR_NAME = 'assets'\n\n/**\n * Everything that can contribute files to one document's asset set:\n * the shared assets dir, the document's own `./assets/` folder, and the\n * Vite-emitted output (hashed images and fonts). The shared assets dir and the\n * Vite-emitted output both live in the bundle's shared `shared-assets/` dir;\n * the document's `./assets/` lands under `<doc>/assets/`. On filename clash the\n * per-document folder wins.\n */\nexport interface DocumentAssetSources {\n\tsharedAssetsDir: string | null\n\tdocumentAssetsDir: string | null\n\t/** The shared Vite-emitted dir (hashed images + fonts), or null when absent. */\n\temittedDir: string | null\n}\n\ninterface ResolveSourcesArgs {\n\t/** The document's entry file path — its `assets/` sibling is the per-doc folder. */\n\tentryFilePath: string\n\tconfig: FormatConfig\n\toutDir: string\n\tsharedAssetsOutDirName: string\n}\n\nexport async function resolveDocumentAssetSources(args: ResolveSourcesArgs): Promise<DocumentAssetSources> {\n\tconst { entryFilePath, config, outDir, sharedAssetsOutDirName } = args\n\n\tconst sharedAssetsDir = getSharedAssetsDir(config)\n\tconst documentAssetsDir = join(dirname(entryFilePath), DOCUMENT_ASSETS_DIR_NAME)\n\tconst emittedDir = resolve(outDir, sharedAssetsOutDirName)\n\n\tconst [sharedOk, perDocOk, emittedOk] = await Promise.all([\n\t\tcheckDir(sharedAssetsDir),\n\t\tcheckDir(documentAssetsDir),\n\t\tcheckDir(emittedDir)\n\t])\n\n\treturn {\n\t\tsharedAssetsDir: sharedOk.isDirectory ? sharedAssetsDir : null,\n\t\tdocumentAssetsDir: perDocOk.isDirectory ? documentAssetsDir : null,\n\t\temittedDir: emittedOk.isDirectory ? emittedDir : null\n\t}\n}\n\n/**\n * Recursively list a directory's files as '/'-separated paths relative to it.\n *\n * Walks by hand with `stat` (not `readdir({ recursive: true })`) so it descends\n * through symlinked directories. Asset roots are often wired up with symlinks —\n * a shared `assets/` dir linked into a project, for example — and those files\n * must still be discovered and shipped.\n */\nasync function listFiles(dir: string): Promise<string[]> {\n\tconst walk = async (current: string): Promise<string[]> => {\n\t\tconst entries = await readdir(current, { withFileTypes: true }).catch(() => [])\n\n\t\tconst nested = await Promise.all(\n\t\t\tentries.map(async entry => {\n\t\t\t\tconst entryPath = join(current, entry.name)\n\t\t\t\tconst stats = await stat(entryPath).catch(() => null)\n\n\t\t\t\tif (!stats) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\n\t\t\t\tif (stats.isDirectory()) {\n\t\t\t\t\treturn walk(entryPath)\n\t\t\t\t}\n\n\t\t\t\tconst isShippableFile = stats.isFile() && !isSystemJunkFile(entry.name)\n\n\t\t\t\treturn isShippableFile ? [entryPath] : []\n\t\t\t})\n\t\t)\n\n\t\treturn nested.flat()\n\t}\n\n\tconst files = await walk(dir)\n\n\treturn files.map(file => relative(dir, file).split('\\\\').join('/')).sort()\n}\n\n/**\n * Copy the document-scoped sources (shared assets dir, then the per-document\n * `./assets/` folder on top — last write wins) into `destDir`.\n */\nasync function overlayDocumentSources(sources: DocumentAssetSources, destDir: string) {\n\tawait mkdir(destDir, { recursive: true })\n\n\tif (sources.sharedAssetsDir) {\n\t\tawait cp(sources.sharedAssetsDir, destDir, { recursive: true, force: true, dereference: true })\n\t}\n\n\tif (sources.documentAssetsDir) {\n\t\tawait cp(sources.documentAssetsDir, destDir, { recursive: true, force: true, dereference: true })\n\t}\n}\n\nexport interface StaticAssetsResult {\n\t/** Zip entry names — the document's known-asset set. Empty when no assets. */\n\tknown: string[]\n\t/** The merged archive, or undefined when the document has no assets. */\n\tzip: Uint8Array | undefined\n}\n\n/**\n * Build one document's merged `assets.zip` (static mode): the full merged set,\n * with no filtering by rendered HTML — any variant renders from the same zip.\n *\n * Standalone by design: callable without emitting any JS wrapper, so HTML\n * output (`format compile --output=html`) can reuse the same artefact.\n */\nexport async function buildDocumentStaticAssets(\n\tsources: DocumentAssetSources,\n\tstagingDir: string\n): Promise<StaticAssetsResult> {\n\tawait rm(stagingDir, { recursive: true, force: true })\n\tawait overlayDocumentSources(sources, stagingDir)\n\n\tif (sources.emittedDir) {\n\t\tconst emittedName = sources.emittedDir.split('\\\\').join('/').split('/').pop()!\n\t\tawait cp(sources.emittedDir, join(stagingDir, emittedName), { recursive: true, force: true, dereference: true })\n\t}\n\n\ttry {\n\t\tconst known = await listFiles(stagingDir)\n\t\tconst zip = await zipDir(stagingDir)\n\n\t\treturn { known, zip }\n\t} finally {\n\t\tawait rm(stagingDir, { recursive: true, force: true }).catch(() => {})\n\t}\n}\n\nexport interface CompiledDynamicAssetEntry {\n\t/** The known-asset path (URL map key) this file backs. */\n\tknownPath: string\n\t/** Absolute path of the file in the compiled outDir. */\n\tsourcePath: string\n\t/** '/'-separated path for emission into a consumer bundle, mirroring the outDir layout. */\n\temitPath: string\n}\n\n/**\n * Turn a compiled document's dynamic-mode URL map into per-file emit entries,\n * for consumers that re-host the assets (the unplugin, Next.js). The map value\n * is each file's location relative to the document's `index.js`, so it already\n * encodes the on-disk path — no need to re-scan the output or re-infer which\n * dir a file came from. `<doc>/assets/x` → emitted under the document; a\n * `../shared-assets/x` value → emitted under the shared dir, shared across docs.\n */\nexport function dynamicAssetEmitEntries(args: {\n\toutDir: string\n\tdocumentName: string\n\turlMap: Record<string, string>\n}): CompiledDynamicAssetEntry[] {\n\tconst { outDir, documentName, urlMap } = args\n\n\tconst documentOutDir = join(outDir, documentName)\n\n\treturn Object.entries(urlMap).map(([knownPath, url]) => {\n\t\tconst sourcePath = resolve(documentOutDir, url)\n\t\tconst emitPath = relative(outDir, sourcePath).split('\\\\').join('/')\n\n\t\treturn { knownPath, sourcePath, emitPath }\n\t})\n}\n\nexport interface DynamicAssetsResult {\n\t/** The document's known-asset set (map keys). Empty when no assets. */\n\tknown: string[]\n\t/**\n\t * Known-asset path → URL relative to the document's `index.js`. The wrapper\n\t * resolves each against `import.meta.url` at render time.\n\t */\n\turlMap: Record<string, string>\n}\n\n/**\n * Materialise the dynamic-mode shared asset layout once per build and return the\n * shared portion of every document's URL map (relative to a document dir). Both\n * the `sharedAssetsDir` contents and the Vite-emitted output (hashed images +\n * fonts) live in the bundle's `shared-assets/` dir, so they are shared across\n * documents and never duplicated.\n *\n * Their map keys differ by how the rendered HTML references them: author files\n * from `sharedAssetsDir` are referenced by their bare path (e.g. `cube.svg`),\n * while Vite rewrites its emitted references to include the dir (e.g.\n * `shared-assets/chart-abc.png`). We snapshot the Vite-emitted files *before*\n * copying `sharedAssetsDir` in, so the two are never confused.\n */\nexport async function materialiseSharedDynamicAssets(args: {\n\tconfig: FormatConfig\n\toutDir: string\n\tsharedAssetsOutDirName: string\n}): Promise<Record<string, string>> {\n\tconst { config, outDir, sharedAssetsOutDirName } = args\n\n\tconst sharedAssetsOutDir = resolve(outDir, sharedAssetsOutDirName)\n\tconst sharedName = basename(sharedAssetsOutDir)\n\n\tconst sharedAssetsSource = getSharedAssetsDir(config)\n\tconst [sharedSourceOk, emittedOk] = await Promise.all([checkDir(sharedAssetsSource), checkDir(sharedAssetsOutDir)])\n\n\tconst sharedAssetsDir = sharedSourceOk.isDirectory ? sharedAssetsSource : null\n\tconst emittedDir = emittedOk.isDirectory ? sharedAssetsOutDir : null\n\n\tconst urlMap: Record<string, string> = {}\n\n\t// Vite emits straight into the shared dir, so its current contents are the\n\t// emitted files — snapshot them before the sharedAssetsDir copy lands on top.\n\tconst emittedRels = emittedDir ? await listFiles(emittedDir) : []\n\n\tfor (const rel of emittedRels) {\n\t\turlMap[`${sharedName}/${rel}`] = `../${sharedName}/${rel}`\n\t}\n\n\tif (sharedAssetsDir) {\n\t\tawait mkdir(sharedAssetsOutDir, { recursive: true })\n\t\tawait cp(sharedAssetsDir, sharedAssetsOutDir, { recursive: true, force: true, dereference: true })\n\n\t\tfor (const rel of await listFiles(sharedAssetsDir)) {\n\t\t\turlMap[rel] = `../${sharedName}/${rel}`\n\t\t}\n\t}\n\n\treturn urlMap\n}\n\n/**\n * Materialise one document's own runtime asset layout (dynamic mode) and return\n * its full URL map. The document's `./assets/` folder is copied to\n * `<documentOutDir>/assets/**` (bare keys, document-local urls); the shared\n * entries are merged in on top with the per-document folder winning on clash.\n */\nexport async function buildDocumentDynamicAssets(args: {\n\tdocumentAssetsDir: string | null\n\tdocumentOutDir: string\n\tsharedUrlMap: Record<string, string>\n}): Promise<DynamicAssetsResult> {\n\tconst { documentAssetsDir, documentOutDir, sharedUrlMap } = args\n\n\tconst runtimeAssetsDir = join(documentOutDir, DOCUMENT_ASSETS_DIR_NAME)\n\n\tawait rm(runtimeAssetsDir, { recursive: true, force: true })\n\n\tconst urlMap: Record<string, string> = { ...sharedUrlMap }\n\n\tif (documentAssetsDir) {\n\t\tawait mkdir(runtimeAssetsDir, { recursive: true })\n\t\tawait cp(documentAssetsDir, runtimeAssetsDir, { recursive: true, force: true, dereference: true })\n\n\t\tfor (const rel of await listFiles(runtimeAssetsDir)) {\n\t\t\turlMap[rel] = `./${DOCUMENT_ASSETS_DIR_NAME}/${rel}`\n\t\t}\n\t}\n\n\treturn { known: Object.keys(urlMap).sort(), urlMap }\n}\n"],"mappings":";;;;;;;;;AASA,MAAa,2BAA2B;AAyBxC,eAAsB,4BAA4B,MAAyD;CAC1G,MAAM,EAAE,eAAe,QAAQ,QAAQ,2BAA2B;CAElE,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,MAAM,oBAAoB,KAAK,QAAQ,cAAc,EAAE,yBAAyB;CAChF,MAAM,aAAa,QAAQ,QAAQ,uBAAuB;CAE1D,MAAM,CAAC,UAAU,UAAU,aAAa,MAAM,QAAQ,IAAI;EACzD,SAAS,gBAAgB;EACzB,SAAS,kBAAkB;EAC3B,SAAS,WAAW;EACpB,CAAC;AAEF,QAAO;EACN,iBAAiB,SAAS,cAAc,kBAAkB;EAC1D,mBAAmB,SAAS,cAAc,oBAAoB;EAC9D,YAAY,UAAU,cAAc,aAAa;EACjD;;;;;;;;;;AAWF,eAAe,UAAU,KAAgC;CACxD,MAAM,OAAO,OAAO,YAAuC;EAC1D,MAAM,UAAU,MAAM,QAAQ,SAAS,EAAE,eAAe,MAAM,CAAC,CAAC,YAAY,EAAE,CAAC;AAqB/E,UAnBe,MAAM,QAAQ,IAC5B,QAAQ,IAAI,OAAM,UAAS;GAC1B,MAAM,YAAY,KAAK,SAAS,MAAM,KAAK;GAC3C,MAAM,QAAQ,MAAM,KAAK,UAAU,CAAC,YAAY,KAAK;AAErD,OAAI,CAAC,MACJ,QAAO,EAAE;AAGV,OAAI,MAAM,aAAa,CACtB,QAAO,KAAK,UAAU;AAKvB,UAFwB,MAAM,QAAQ,IAAI,CAAC,iBAAiB,MAAM,KAAK,GAE9C,CAAC,UAAU,GAAG,EAAE;IACxC,CACF,EAEa,MAAM;;AAKrB,SAFc,MA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C;AAElG,OAAK,MAAM,OAAO,MAAM,UAAU,iBAAiB,CAClD,QAAO,OAAO,KAAK,yBAAyB,GAAG;;AAIjD,QAAO;EAAE,OAAO,OAAO,KAAK,OAAO,CAAC,MAAM;EAAE;EAAQ"}
|
|
1
|
+
{"version":3,"file":"document-assets.mjs","names":["urlMap: Record<string, string>"],"sources":["../../../src/server/compile/document-assets.ts"],"sourcesContent":["import type { FormatConfig } from '../../shared/types'\n\nimport { basename, dirname, extname, join, relative, resolve } from 'node:path'\nimport { cp, mkdir, readdir, rm, stat } from 'node:fs/promises'\nimport { isUserAssetExtension } from '@format.dev/utils'\nimport { zipDir, isSystemJunkFile } from '@format.dev/zip'\nimport { getSharedAssetsDir } from '../project/paths'\nimport { checkDir } from '../utils'\n\n/** Reserved co-location folder: `documents/<name>/assets/` travels with the document. */\nexport const DOCUMENT_ASSETS_DIR_NAME = 'assets'\n\n/**\n * Everything that can contribute files to one document's asset set:\n * the shared assets dir, the document's own `./assets/` folder, and the\n * Vite-emitted output (hashed images and fonts). The shared assets dir and the\n * Vite-emitted output both live in the bundle's shared `shared-assets/` dir;\n * the document's `./assets/` lands under `<doc>/assets/`. On filename clash the\n * per-document folder wins.\n */\nexport interface DocumentAssetSources {\n\tsharedAssetsDir: string | null\n\tdocumentAssetsDir: string | null\n\t/** The shared Vite-emitted dir (hashed images + fonts), or null when absent. */\n\temittedDir: string | null\n}\n\ninterface ResolveSourcesArgs {\n\t/** The document's entry file path — its `assets/` sibling is the per-doc folder. */\n\tentryFilePath: string\n\tconfig: FormatConfig\n\toutDir: string\n\tsharedAssetsOutDirName: string\n}\n\nexport async function resolveDocumentAssetSources(args: ResolveSourcesArgs): Promise<DocumentAssetSources> {\n\tconst { entryFilePath, config, outDir, sharedAssetsOutDirName } = args\n\n\tconst sharedAssetsDir = getSharedAssetsDir(config)\n\tconst documentAssetsDir = join(dirname(entryFilePath), DOCUMENT_ASSETS_DIR_NAME)\n\tconst emittedDir = resolve(outDir, sharedAssetsOutDirName)\n\n\tconst [sharedOk, perDocOk, emittedOk] = await Promise.all([\n\t\tcheckDir(sharedAssetsDir),\n\t\tcheckDir(documentAssetsDir),\n\t\tcheckDir(emittedDir)\n\t])\n\n\treturn {\n\t\tsharedAssetsDir: sharedOk.isDirectory ? sharedAssetsDir : null,\n\t\tdocumentAssetsDir: perDocOk.isDirectory ? documentAssetsDir : null,\n\t\temittedDir: emittedOk.isDirectory ? emittedDir : null\n\t}\n}\n\n/**\n * Recursively list a directory's files as '/'-separated paths relative to it.\n *\n * Walks by hand with `stat` (not `readdir({ recursive: true })`) so it descends\n * through symlinked directories. Asset roots are often wired up with symlinks —\n * a shared `assets/` dir linked into a project, for example — and those files\n * must still be discovered and shipped.\n */\nasync function listFiles(dir: string): Promise<string[]> {\n\tconst walk = async (current: string): Promise<string[]> => {\n\t\tconst entries = await readdir(current, { withFileTypes: true }).catch(() => [])\n\n\t\tconst nested = await Promise.all(\n\t\t\tentries.map(async entry => {\n\t\t\t\tconst entryPath = join(current, entry.name)\n\t\t\t\tconst stats = await stat(entryPath).catch(() => null)\n\n\t\t\t\tif (!stats) {\n\t\t\t\t\treturn []\n\t\t\t\t}\n\n\t\t\t\tif (stats.isDirectory()) {\n\t\t\t\t\treturn walk(entryPath)\n\t\t\t\t}\n\n\t\t\t\tconst isShippableFile = stats.isFile() && !isSystemJunkFile(entry.name)\n\n\t\t\t\treturn isShippableFile ? [entryPath] : []\n\t\t\t})\n\t\t)\n\n\t\treturn nested.flat()\n\t}\n\n\tconst files = await walk(dir)\n\n\treturn files.map(file => relative(dir, file).split('\\\\').join('/')).sort()\n}\n\n/**\n * Copy the document-scoped sources (shared assets dir, then the per-document\n * `./assets/` folder on top — last write wins) into `destDir`.\n */\nasync function overlayDocumentSources(sources: DocumentAssetSources, destDir: string) {\n\tawait mkdir(destDir, { recursive: true })\n\n\tif (sources.sharedAssetsDir) {\n\t\tawait cp(sources.sharedAssetsDir, destDir, { recursive: true, force: true, dereference: true })\n\t}\n\n\tif (sources.documentAssetsDir) {\n\t\tawait cp(sources.documentAssetsDir, destDir, { recursive: true, force: true, dereference: true })\n\t}\n}\n\nexport interface StaticAssetsResult {\n\t/** Zip entry names — the document's known-asset set. Empty when no assets. */\n\tknown: string[]\n\t/** The merged archive, or undefined when the document has no assets. */\n\tzip: Uint8Array | undefined\n\t/** Files left out because renders can't use their type, such as a font licence `.txt`. */\n\tunsupported: string[]\n}\n\n// The same check the render API applies when it unpacks the zip. It refuses the\n// whole archive over one unknown type, so these files must never reach it.\nfunction isRenderableAsset(file: string) {\n\treturn isUserAssetExtension(extname(file).slice(1).toLowerCase())\n}\n\n/**\n * Build one document's merged `assets.zip` (static mode): the full merged set,\n * with no filtering by rendered HTML — any variant renders from the same zip.\n *\n * Standalone by design: callable without emitting any JS wrapper, so HTML\n * output (`format compile --output=html`) can reuse the same artefact.\n */\nexport async function buildDocumentStaticAssets(\n\tsources: DocumentAssetSources,\n\tstagingDir: string\n): Promise<StaticAssetsResult> {\n\tawait rm(stagingDir, { recursive: true, force: true })\n\tawait overlayDocumentSources(sources, stagingDir)\n\n\tif (sources.emittedDir) {\n\t\tconst emittedName = sources.emittedDir.split('\\\\').join('/').split('/').pop()!\n\t\tawait cp(sources.emittedDir, join(stagingDir, emittedName), { recursive: true, force: true, dereference: true })\n\t}\n\n\ttry {\n\t\tconst files = await listFiles(stagingDir)\n\t\tconst known = files.filter(file => isRenderableAsset(file))\n\t\tconst unsupported = files.filter(file => !isRenderableAsset(file))\n\n\t\tawait Promise.all(unsupported.map(file => rm(join(stagingDir, file), { force: true })))\n\n\t\tconst zip = await zipDir(stagingDir)\n\n\t\treturn { known, zip, unsupported }\n\t} finally {\n\t\tawait rm(stagingDir, { recursive: true, force: true }).catch(() => {})\n\t}\n}\n\nexport interface CompiledDynamicAssetEntry {\n\t/** The known-asset path (URL map key) this file backs. */\n\tknownPath: string\n\t/** Absolute path of the file in the compiled outDir. */\n\tsourcePath: string\n\t/** '/'-separated path for emission into a consumer bundle, mirroring the outDir layout. */\n\temitPath: string\n}\n\n/**\n * Turn a compiled document's dynamic-mode URL map into per-file emit entries,\n * for consumers that re-host the assets (the unplugin, Next.js). The map value\n * is each file's location relative to the document's `index.js`, so it already\n * encodes the on-disk path — no need to re-scan the output or re-infer which\n * dir a file came from. `<doc>/assets/x` → emitted under the document; a\n * `../shared-assets/x` value → emitted under the shared dir, shared across docs.\n */\nexport function dynamicAssetEmitEntries(args: {\n\toutDir: string\n\tdocumentName: string\n\turlMap: Record<string, string>\n}): CompiledDynamicAssetEntry[] {\n\tconst { outDir, documentName, urlMap } = args\n\n\tconst documentOutDir = join(outDir, documentName)\n\n\treturn Object.entries(urlMap).map(([knownPath, url]) => {\n\t\tconst sourcePath = resolve(documentOutDir, url)\n\t\tconst emitPath = relative(outDir, sourcePath).split('\\\\').join('/')\n\n\t\treturn { knownPath, sourcePath, emitPath }\n\t})\n}\n\nexport interface DynamicAssetsResult {\n\t/** The document's known-asset set (map keys). Empty when no assets. */\n\tknown: string[]\n\t/**\n\t * Known-asset path → URL relative to the document's `index.js`. The wrapper\n\t * resolves each against `import.meta.url` at render time.\n\t */\n\turlMap: Record<string, string>\n}\n\n/**\n * Materialise the dynamic-mode shared asset layout once per build and return the\n * shared portion of every document's URL map (relative to a document dir). Both\n * the `sharedAssetsDir` contents and the Vite-emitted output (hashed images +\n * fonts) live in the bundle's `shared-assets/` dir, so they are shared across\n * documents and never duplicated.\n *\n * Their map keys differ by how the rendered HTML references them: author files\n * from `sharedAssetsDir` are referenced by their bare path (e.g. `cube.svg`),\n * while Vite rewrites its emitted references to include the dir (e.g.\n * `shared-assets/chart-abc.png`). We snapshot the Vite-emitted files *before*\n * copying `sharedAssetsDir` in, so the two are never confused.\n */\nexport async function materialiseSharedDynamicAssets(args: {\n\tconfig: FormatConfig\n\toutDir: string\n\tsharedAssetsOutDirName: string\n}): Promise<Record<string, string>> {\n\tconst { config, outDir, sharedAssetsOutDirName } = args\n\n\tconst sharedAssetsOutDir = resolve(outDir, sharedAssetsOutDirName)\n\tconst sharedName = basename(sharedAssetsOutDir)\n\n\tconst sharedAssetsSource = getSharedAssetsDir(config)\n\tconst [sharedSourceOk, emittedOk] = await Promise.all([checkDir(sharedAssetsSource), checkDir(sharedAssetsOutDir)])\n\n\tconst sharedAssetsDir = sharedSourceOk.isDirectory ? sharedAssetsSource : null\n\tconst emittedDir = emittedOk.isDirectory ? sharedAssetsOutDir : null\n\n\tconst urlMap: Record<string, string> = {}\n\n\t// Vite emits straight into the shared dir, so its current contents are the\n\t// emitted files — snapshot them before the sharedAssetsDir copy lands on top.\n\tconst emittedRels = emittedDir ? await listFiles(emittedDir) : []\n\n\tfor (const rel of emittedRels) {\n\t\turlMap[`${sharedName}/${rel}`] = `../${sharedName}/${rel}`\n\t}\n\n\tif (sharedAssetsDir) {\n\t\tawait mkdir(sharedAssetsOutDir, { recursive: true })\n\t\tawait cp(sharedAssetsDir, sharedAssetsOutDir, { recursive: true, force: true, dereference: true })\n\n\t\tfor (const rel of await listFiles(sharedAssetsDir)) {\n\t\t\turlMap[rel] = `../${sharedName}/${rel}`\n\t\t}\n\t}\n\n\treturn urlMap\n}\n\n/**\n * Materialise one document's own runtime asset layout (dynamic mode) and return\n * its full URL map. The document's `./assets/` folder is copied to\n * `<documentOutDir>/assets/**` (bare keys, document-local urls); the shared\n * entries are merged in on top with the per-document folder winning on clash.\n */\nexport async function buildDocumentDynamicAssets(args: {\n\tdocumentAssetsDir: string | null\n\tdocumentOutDir: string\n\tsharedUrlMap: Record<string, string>\n}): Promise<DynamicAssetsResult> {\n\tconst { documentAssetsDir, documentOutDir, sharedUrlMap } = args\n\n\tconst runtimeAssetsDir = join(documentOutDir, DOCUMENT_ASSETS_DIR_NAME)\n\n\tawait rm(runtimeAssetsDir, { recursive: true, force: true })\n\n\tconst urlMap: Record<string, string> = { ...sharedUrlMap }\n\n\tif (documentAssetsDir) {\n\t\tawait mkdir(runtimeAssetsDir, { recursive: true })\n\t\tawait cp(documentAssetsDir, runtimeAssetsDir, { recursive: true, force: true, dereference: true })\n\n\t\tfor (const rel of await listFiles(runtimeAssetsDir)) {\n\t\t\turlMap[rel] = `./${DOCUMENT_ASSETS_DIR_NAME}/${rel}`\n\t\t}\n\t}\n\n\treturn { known: Object.keys(urlMap).sort(), urlMap }\n}\n"],"mappings":";;;;;;;;;;AAUA,MAAa,2BAA2B;AAyBxC,eAAsB,4BAA4B,MAAyD;CAC1G,MAAM,EAAE,eAAe,QAAQ,QAAQ,2BAA2B;CAElE,MAAM,kBAAkB,mBAAmB,OAAO;CAClD,MAAM,oBAAoB,KAAK,QAAQ,cAAc,EAAE,yBAAyB;CAChF,MAAM,aAAa,QAAQ,QAAQ,uBAAuB;CAE1D,MAAM,CAAC,UAAU,UAAU,aAAa,MAAM,QAAQ,IAAI;EACzD,SAAS,gBAAgB;EACzB,SAAS,kBAAkB;EAC3B,SAAS,WAAW;EACpB,CAAC;AAEF,QAAO;EACN,iBAAiB,SAAS,cAAc,kBAAkB;EAC1D,mBAAmB,SAAS,cAAc,oBAAoB;EAC9D,YAAY,UAAU,cAAc,aAAa;EACjD;;;;;;;;;;AAWF,eAAe,UAAU,KAAgC;CACxD,MAAM,OAAO,OAAO,YAAuC;EAC1D,MAAM,UAAU,MAAM,QAAQ,SAAS,EAAE,eAAe,MAAM,CAAC,CAAC,YAAY,EAAE,CAAC;AAqB/E,UAnBe,MAAM,QAAQ,IAC5B,QAAQ,IAAI,OAAM,UAAS;GAC1B,MAAM,YAAY,KAAK,SAAS,MAAM,KAAK;GAC3C,MAAM,QAAQ,MAAM,KAAK,UAAU,CAAC,YAAY,KAAK;AAErD,OAAI,CAAC,MACJ,QAAO,EAAE;AAGV,OAAI,MAAM,aAAa,CACtB,QAAO,KAAK,UAAU;AAKvB,UAFwB,MAAM,QAAQ,IAAI,CAAC,iBAAiB,MAAM,KAAK,GAE9C,CAAC,UAAU,GAAG,EAAE;IACxC,CACF,EAEa,MAAM;;AAKrB,SAFc,MAAM,KAAK,IAAI,EAEh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E,mBAAmB,gBAAgB,iBAAiB;CAE5D,MAAM,mBAAmB,KAAK,gBAAgB,yBAAyB;AAEvE,OAAM,GAAG,kBAAkB;EAAE,WAAW;EAAM,OAAO;EAAM,CAAC;CAE5D,MAAMA,SAAiC,EAAE,GAAG,cAAc;AAE1D,KAAI,mBAAmB;AACtB,QAAM,MAAM,kBAAkB,EAAE,WAAW,MAAM,CAAC;AAClD,QAAM,GAAG,mBAAmB,kBAAkB;GAAE,WAAW;GAAM,OAAO;GAAM,aAAa;GAAM,CAAC;AAElG,OAAK,MAAM,OAAO,MAAM,UAAU,iBAAiB,CAClD,QAAO,OAAO,KAAK,yBAAyB,GAAG;;AAIjD,QAAO;EAAE,OAAO,OAAO,KAAK,OAAO,CAAC,MAAM;EAAE;EAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"suggest-similar.d.mts","names":[],"sources":["../../../src/server/utils/suggest-similar.ts"],"sourcesContent":[],"mappings":";UAiDU,kBAAA;EAAA,IAAA,EAAA,MAAA;EAOM,UAAA,EAAA,SAAc,MAAA,
|
|
1
|
+
{"version":3,"file":"suggest-similar.d.mts","names":[],"sources":["../../../src/server/utils/suggest-similar.ts"],"sourcesContent":[],"mappings":";UAiDU,kBAAA;EAAA,IAAA,EAAA,MAAA;EAOM,UAAA,EAAA,SAAc,MAAA,EAAO;;iBAArB,cAAA,OAAqB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-styles.d.mts","names":[],"sources":["../../../../src/server/vite/plugins/get-styles.ts"],"sourcesContent":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"get-styles.d.mts","names":[],"sources":["../../../../src/server/vite/plugins/get-styles.ts"],"sourcesContent":[],"mappings":";;;iBAyEgB,SAAA,CAAA;;EAAA,KAAA,EAAA,MAAS;;;;aAQqC"}
|
|
@@ -37,7 +37,6 @@ function collectCssForEntry(args) {
|
|
|
37
37
|
}
|
|
38
38
|
for (const next of [...chunk.imports, ...chunk.dynamicImports]) stack.push(next);
|
|
39
39
|
}
|
|
40
|
-
if (orderedCss.length === 0) return [...stylesByFile.keys()];
|
|
41
40
|
return orderedCss;
|
|
42
41
|
}
|
|
43
42
|
function getStyles() {
|
|
@@ -55,6 +54,7 @@ function getStyles() {
|
|
|
55
54
|
}
|
|
56
55
|
const chunksByFileName = /* @__PURE__ */ new Map();
|
|
57
56
|
for (const [fileName, item] of Object.entries(bundle)) if (isChunk(item)) chunksByFileName.set(fileName, item);
|
|
57
|
+
if (![...chunksByFileName.values()].some((chunk) => chunk.viteMetadata)) throw new Error("get-styles: no chunk has viteMetadata, so CSS cannot be matched to documents. Vite sets it on every chunk, so a Vite upgrade has likely renamed or removed it.");
|
|
58
58
|
for (const item of Object.values(bundle)) if (isChunk(item) && item.isEntry) {
|
|
59
59
|
const cssFiles = collectCssForEntry({
|
|
60
60
|
entry: item,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"get-styles.mjs","names":["orderedCss: string[]","stylesByFileObj: Record<string, string>","entryCssFilesObj: Record<string, string[]>"],"sources":["../../../../src/server/vite/plugins/get-styles.ts"],"sourcesContent":["import type { OutputBundle, OutputChunk, OutputAsset } from 'rolldown'\nimport { ENTRY_CSS_FILES_REPLACEMENT, STYLES_BY_FILE_REPLACEMENT } from '../../compile/constants'\nimport { logger } from '../../utils'\n\nfunction escapeRegExp(value: string) {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction replacePlaceholder(code: string, placeholder: string, replacement: string) {\n\tconst literalRe = new RegExp('([\\'\"`])' + escapeRegExp(placeholder) + '\\\\1', 'g')\n\treturn code.replace(literalRe, replacement)\n}\n\nfunction isAsset(item: any): item is OutputAsset {\n\treturn item.type === 'asset'\n}\n\nfunction isChunk(item: any): item is OutputChunk {\n\treturn item.type === 'chunk'\n}\n\nfunction collectCssForEntry(args: {\n\tentry: OutputChunk\n\tchunksByFileName: Map<string, OutputChunk>\n\tstylesByFile: Map<string, string>\n}): string[] {\n\t// Walk the entry's chunk graph to include shared CSS from imported chunks.\n\tconst { entry, chunksByFileName, stylesByFile } = args\n\tconst orderedCss: string[] = []\n\tconst seenCss = new Set<string>()\n\tconst seenChunks = new Set<string>()\n\tconst stack = [entry.fileName]\n\n\twhile (stack.length) {\n\t\tconst fileName = stack.pop()!\n\t\tif (seenChunks.has(fileName)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tseenChunks.add(fileName)\n\n\t\tconst chunk = chunksByFileName.get(fileName)\n\t\tif (!chunk) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst importedCss = (chunk as any)?.viteMetadata?.importedCss as Set<string> | undefined\n\t\tif (importedCss) {\n\t\t\tfor (const cssFile of importedCss) {\n\t\t\t\t// Only include CSS we captured from the bundle output.\n\t\t\t\tif (!stylesByFile.has(cssFile)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (seenCss.has(cssFile)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tseenCss.add(cssFile)\n\t\t\t\torderedCss.push(cssFile)\n\t\t\t}\n\t\t}\n\n\t\tfor (const next of [...chunk.imports, ...chunk.dynamicImports]) {\n\t\t\tstack.push(next)\n\t\t}\n\t}\n\n\
|
|
1
|
+
{"version":3,"file":"get-styles.mjs","names":["orderedCss: string[]","stylesByFileObj: Record<string, string>","entryCssFilesObj: Record<string, string[]>"],"sources":["../../../../src/server/vite/plugins/get-styles.ts"],"sourcesContent":["import type { OutputBundle, OutputChunk, OutputAsset } from 'rolldown'\nimport { ENTRY_CSS_FILES_REPLACEMENT, STYLES_BY_FILE_REPLACEMENT } from '../../compile/constants'\nimport { logger } from '../../utils'\n\nfunction escapeRegExp(value: string) {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction replacePlaceholder(code: string, placeholder: string, replacement: string) {\n\tconst literalRe = new RegExp('([\\'\"`])' + escapeRegExp(placeholder) + '\\\\1', 'g')\n\treturn code.replace(literalRe, replacement)\n}\n\nfunction isAsset(item: any): item is OutputAsset {\n\treturn item.type === 'asset'\n}\n\nfunction isChunk(item: any): item is OutputChunk {\n\treturn item.type === 'chunk'\n}\n\nfunction collectCssForEntry(args: {\n\tentry: OutputChunk\n\tchunksByFileName: Map<string, OutputChunk>\n\tstylesByFile: Map<string, string>\n}): string[] {\n\t// Walk the entry's chunk graph to include shared CSS from imported chunks.\n\tconst { entry, chunksByFileName, stylesByFile } = args\n\tconst orderedCss: string[] = []\n\tconst seenCss = new Set<string>()\n\tconst seenChunks = new Set<string>()\n\tconst stack = [entry.fileName]\n\n\twhile (stack.length) {\n\t\tconst fileName = stack.pop()!\n\t\tif (seenChunks.has(fileName)) {\n\t\t\tcontinue\n\t\t}\n\n\t\tseenChunks.add(fileName)\n\n\t\tconst chunk = chunksByFileName.get(fileName)\n\t\tif (!chunk) {\n\t\t\tcontinue\n\t\t}\n\n\t\tconst importedCss = (chunk as any)?.viteMetadata?.importedCss as Set<string> | undefined\n\t\tif (importedCss) {\n\t\t\tfor (const cssFile of importedCss) {\n\t\t\t\t// Only include CSS we captured from the bundle output.\n\t\t\t\tif (!stylesByFile.has(cssFile)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif (seenCss.has(cssFile)) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tseenCss.add(cssFile)\n\t\t\t\torderedCss.push(cssFile)\n\t\t\t}\n\t\t}\n\n\t\tfor (const next of [...chunk.imports, ...chunk.dynamicImports]) {\n\t\t\tstack.push(next)\n\t\t}\n\t}\n\n\treturn orderedCss\n}\n\n/*\nPost-build, gather CSS assets and fill virtual styles placeholders.\n*/\n\nexport function getStyles() {\n\tconst stylesByFile = new Map<string, string>()\n\n\treturn {\n\t\tname: 'get-styles',\n\t\tapply: 'build',\n\t\tenforce: 'post',\n\n\t\tgenerateBundle(_outputOptions: { format?: string }, bundle: OutputBundle) {\n\t\t\tstylesByFile.clear()\n\t\t\tconst entryCssFiles = new Map<string, string[]>()\n\n\t\t\tfor (const [fileName, item] of Object.entries(bundle)) {\n\t\t\t\t// Should just be the generated style.css file from rollup\n\t\t\t\tconst isCssFile = isAsset(item) && fileName.endsWith('.css')\n\n\t\t\t\tif (isCssFile) {\n\t\t\t\t\tconst cleanedSource = String(item.source ?? '').replace(\n\t\t\t\t\t\t/\\/\\*\\$vite\\$\\:\\d+\\*\\/\\s*$/, // Targets the vite comment marker at the end of the file\n\t\t\t\t\t\t''\n\t\t\t\t\t)\n\n\t\t\t\t\tstylesByFile.set(fileName, cleanedSource)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst chunksByFileName = new Map<string, OutputChunk>()\n\n\t\t\tfor (const [fileName, item] of Object.entries(bundle)) {\n\t\t\t\tif (isChunk(item)) {\n\t\t\t\t\t// Map for fast graph traversal.\n\t\t\t\t\tchunksByFileName.set(fileName, item)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst hasViteMetadata = [...chunksByFileName.values()].some(chunk => (chunk as any).viteMetadata)\n\n\t\t\tif (!hasViteMetadata) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t'get-styles: no chunk has viteMetadata, so CSS cannot be matched to documents. Vite sets it on every chunk, so a Vite upgrade has likely renamed or removed it.'\n\t\t\t\t)\n\t\t\t}\n\n\t\t\tfor (const item of Object.values(bundle)) {\n\t\t\t\tif (isChunk(item) && item.isEntry) {\n\t\t\t\t\tconst cssFiles = collectCssForEntry({ entry: item, chunksByFileName, stylesByFile })\n\t\t\t\t\tentryCssFiles.set(item.name, cssFiles)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst stylesByFileObj: Record<string, string> = {}\n\t\t\tconst entryCssFilesObj: Record<string, string[]> = {}\n\n\t\t\tfor (const [fileName, styles] of stylesByFile) {\n\t\t\t\tstylesByFileObj[fileName] = styles\n\t\t\t}\n\n\t\t\tfor (const [entryName, files] of entryCssFiles) {\n\t\t\t\tentryCssFilesObj[entryName] = files\n\t\t\t}\n\n\t\t\tconst stylesByFileReplacement = JSON.stringify(stylesByFileObj)\n\t\t\tconst entryCssFilesReplacement = JSON.stringify(entryCssFilesObj)\n\n\t\t\tfor (const item of Object.values(bundle)) {\n\t\t\t\tif (!isChunk(item) || typeof item.code !== 'string') {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Replace placeholders in the virtual:styles module chunk.\n\n\t\t\t\tif (item.code.includes(STYLES_BY_FILE_REPLACEMENT)) {\n\t\t\t\t\titem.code = replacePlaceholder(item.code, STYLES_BY_FILE_REPLACEMENT, stylesByFileReplacement)\n\t\t\t\t}\n\n\t\t\t\tif (item.code.includes(ENTRY_CSS_FILES_REPLACEMENT)) {\n\t\t\t\t\titem.code = replacePlaceholder(item.code, ENTRY_CSS_FILES_REPLACEMENT, entryCssFilesReplacement)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogger.debug('Collected CSS assets', {\n\t\t\t\tcssFiles: stylesByFile.size,\n\t\t\t\tentries: entryCssFiles.size\n\t\t\t})\n\n\t\t\tfor (const fileName of stylesByFile.keys()) {\n\t\t\t\tdelete bundle[fileName]\n\t\t\t}\n\t\t}\n\t}\n}\n"],"mappings":";;;;;AAIA,SAAS,aAAa,OAAe;AACpC,QAAO,MAAM,QAAQ,uBAAuB,OAAO;;AAGpD,SAAS,mBAAmB,MAAc,aAAqB,aAAqB;CACnF,MAAM,YAAY,IAAI,OAAO,aAAa,aAAa,YAAY,GAAG,OAAO,IAAI;AACjF,QAAO,KAAK,QAAQ,WAAW,YAAY;;AAG5C,SAAS,QAAQ,MAAgC;AAChD,QAAO,KAAK,SAAS;;AAGtB,SAAS,QAAQ,MAAgC;AAChD,QAAO,KAAK,SAAS;;AAGtB,SAAS,mBAAmB,MAIf;CAEZ,MAAM,EAAE,OAAO,kBAAkB,iBAAiB;CAClD,MAAMA,aAAuB,EAAE;CAC/B,MAAM,0BAAU,IAAI,KAAa;CACjC,MAAM,6BAAa,IAAI,KAAa;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A;AAEvB,KACD,MAAA,GADiC,CAAA,OAChB,OADgB,CAAA,CAAA,MAAA,CAAA;AACjC,cAEC,
|
|
1
|
+
{"version":3,"file":"compile.d.mts","names":[],"sources":["../../../../src/shared/types/public/compile.ts"],"sourcesContent":[],"mappings":";cAAa;AAAA,KACD,MAAA,GADiD,CAAA,OAChC,OADgC,CAAA,CAAA,MAAA,CAAA;AACjD,cAEC,OAFgB,EAAA,SAAO,CAAA,MAAA,EAAA,SAAA,EAAA,MAAA,CAAA;AAEvB,KACD,MAAA,GAD+C,CAAA,OAC9B,OAD8B,CAAA,CAAA,MAAA,CAAA;AAC/C,cAEC,OAFgB,EAAA,SAAO,CAAA,KAAA,EAAA,IAAA,CAAA;AAEvB,KACD,MAAA,GADiC,CAAA,OAChB,OADgB,CAAA,CAAA,MAAA,CAAA;AACjC,cAEC,YAFuB,EAAA,SAAA,CAAA,MAAA,EAAA,QAAA,EAAA,SAAA,EAAA,SAAA,EAAA,QAAA,CAAA;AAEvB,KACD,WAAA,GAD2E,CAAA,OACrD,YADqD,CAAA,CAAA,MAAA,CAAA;AAC3E,cAEC,UAFqB,EAAA,SAAA,CAAY,QAAA,EAAA,SAAA,EAAA,MAAA,CAAA;AAEjC,KACD,SAAA,GADoD,CAAA,OAChC,UADgC,CAAA,CAAA,MAAA,CAAA;AACpD,cAEC,OAFmB,EAAA,SAAU,CAAA,UAAA,EAAA,MAAA,CAAA;AAE7B,KACD,MAAA,GADwC,CAAA,OACvB,OADuB,CAAA,CAAA,MAAA,CAAA;AACxC,UAEK,cAAA,CAFY;EAEZ,MAAA,CAAA,EACP,MADO;EACP,MAAA,CAAA,EACA,MADA;EACA,MAAA,CAAA,EAAA,MAAA,EAAA;EAMA,QAAA,CAAA,EAAA,MAAA,EAAA;EACA,UAAA,CAAA,EAAA,MAAA,EAAA;EAYK,kBAAA,CAAA,EAAA,MAAA,EAAA;EAAW,SAAA,CAAA,EAAA,MAAA,EAAA;EAIrB,MAAA,CAAA,EAjBK,SAiBL,GAAgB,IAAA;EAMT,MAAA,CAAA,EAtBF,MAsBE,GAAA,IAAA;EACC,QAAA,CAAA,EAAA,MAAA,EAAA;EAAmB,YAAA,CAAA,EAAA,OAAA;EAAe,eAAA,CAAA,EAAA,OAAA;EAC3C,cAAA,CAAA,EAAA,OAAA;EAAgB,GAAA,CAAA,EAAA,OAAA;;;;;;;gBAZL;;KAIV,gBAAA;;UAEI;UACA;;KAGG,wBAAA,iBACC,mBAAmB,eAAe,OAC3C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@format.dev/compile",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.3",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Compile Format documents into renderers, without the Studio UI",
|
|
6
6
|
"author": "the format.dev developers",
|
|
@@ -89,10 +89,10 @@
|
|
|
89
89
|
"vite": "8.3.2",
|
|
90
90
|
"vite-plugin-svgr": "^4.5.0",
|
|
91
91
|
"vite-svg-loader": "^5.1.0",
|
|
92
|
-
"@format.dev/cli": "0.1.
|
|
93
|
-
"@format.dev/utils": "0.1.
|
|
94
|
-
"@format.dev/
|
|
95
|
-
"@format.dev/
|
|
92
|
+
"@format.dev/cli": "0.1.3",
|
|
93
|
+
"@format.dev/utils": "0.1.3",
|
|
94
|
+
"@format.dev/types": "0.1.3",
|
|
95
|
+
"@format.dev/zip": "0.1.3"
|
|
96
96
|
},
|
|
97
97
|
"devDependencies": {
|
|
98
98
|
"@pandacss/dev": "^1.8.0",
|