@format.dev/compile 0.1.0 → 0.1.2
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 +3 -2
- 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/make-config.mjs +8 -2
- package/dist/server/compile/make-config.mjs.map +1 -1
- package/dist/server/compile/producer-release.mjs +1 -1
- package/dist/server/integrations/nextjs/generate-entry.mjs +1 -1
- package/dist/server/integrations/nextjs/generate-entry.mjs.map +1 -1
- package/dist/server/integrations/unplugin/index.d.mts +2 -2
- package/dist/server/render-worker/host.mjs +1 -1
- package/dist/server/render-worker/host.mjs.map +1 -1
- package/dist/server/vite/create-config.d.mts +7 -7
- 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 +11 -11
|
@@ -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);
|
|
@@ -680,7 +681,7 @@ async function runCompile(runArgs) {
|
|
|
680
681
|
const suppressBuildLogs = (_level, ...args) => {
|
|
681
682
|
const msg = args.join(" ");
|
|
682
683
|
if (msg.includes("building SSR bundle for production")) return false;
|
|
683
|
-
if (msg.includes("
|
|
684
|
+
if (msg.includes("vite v") && msg.includes("building")) return false;
|
|
684
685
|
if (msg.includes("built in")) return false;
|
|
685
686
|
return true;
|
|
686
687
|
};
|
|
@@ -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('rolldown-vite') && 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,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AAG,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,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;CAC9D,MAAM,WAAW,MAAM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a,gBAAgB,CAChC;CAG1C,MAAM,EAAE,aAAa;CACrB,MAAM,cAAc,SAAS;AAE7B,KAAI,SAAS,cAAc,KAAK,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"}
|
|
@@ -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,eA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GAAM,OAAO;GAAM,aAAa;GAAM,CAAC;AAElG,OAAK,MAAM,OAAO,MAAM,UAAU,gBAAgB,CACjD,QAAO,OAAO,MAAM,WAAW,GAAG;;AAIpC,QAAO;;;;;;;;AASR,eAAsB,2BAA2B,MAIhB;CAChC,MAAM,EAAE,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
|
+
{"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;CACx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BAAqB;CAC1E,MAAM,aAAa,UAAU,cAAc,qBAAqB;CAEhE,MAAMA,SAAiC,EAAE;CAIzC,MAAM,cAAc,aAAa,MAAM,UAAU,WAAW,GAAG,EAAE;AAEjE,MAAK,MAAM,OAAO,YACjB,QAAO,GAAG,WAAW,GAAG,SAAS,MAAM,WAAW,GAAG;AAGtD,KAAI,iBAAiB;AACpB,QAAM,MAAM,oBAAoB,EAAE,WAAW,MAAM,CAAC;AACpD,QAAM,GAAG,iBAAiB,oBAAoB;GAAE,WAAW;GAAM,OAAO;GAAM,aAAa;GAAM,CAAC;AAElG,OAAK,MAAM,OAAO,MAAM,UAAU,gBAAgB,CACjD,QAAO,OAAO,MAAM,WAAW,GAAG;;AAIpC,QAAO;;;;;;;;AASR,eAAsB,2BAA2B,MAIhB;CAChC,MAAM,EAAE,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"}
|
|
@@ -159,12 +159,18 @@ function makeViteBuildConfig(i) {
|
|
|
159
159
|
input: Object.fromEntries(documents.map((document) => [document.name, `${VIRTUAL_ENTRY_PREFIX}${document.name}`])),
|
|
160
160
|
preserveEntrySignatures: "strict",
|
|
161
161
|
treeshake: false,
|
|
162
|
+
experimental: { attachDebugInfo: "none" },
|
|
162
163
|
output: {
|
|
163
164
|
format,
|
|
164
165
|
entryFileNames: (chunkInfo) => `${chunkInfo.name}/${compiledFileName}`,
|
|
165
166
|
chunkFileNames: (chunkInfo) => chunkInfo.name === "styles" || chunkInfo.name === "rolldown-runtime" ? `chunks/${chunkInfo.name}.js` : "chunks/[name]-[hash].js",
|
|
166
|
-
|
|
167
|
-
|
|
167
|
+
codeSplitting: { groups: [{
|
|
168
|
+
name: "styles",
|
|
169
|
+
test: (id) => id === VIRTUAL_STYLES_MODULE_ID
|
|
170
|
+
}] },
|
|
171
|
+
comments: {
|
|
172
|
+
legal: false,
|
|
173
|
+
jsdoc: false
|
|
168
174
|
},
|
|
169
175
|
exports: "named",
|
|
170
176
|
assetFileNames: (assetInfo) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make-config.mjs","names":["adaptorHtml","adaptorReactBrowser","adaptorReactNode","adaptorVueBrowser","adaptorVueNode","rendererVirtualPlugin: PluginOption","validate","virtualStyles","decodeStyleEntitiesModule","sanitizeHtml","createRenderer","webpackNodeCompatRuntimePlugin: PluginOption","common: UserConfig","workerNoExternal: NoExternal | undefined","workerTarget: SSRTarget"],"sources":["../../../src/server/compile/make-config.ts"],"sourcesContent":["import type { FormatConfig } from '../../shared/types/public/config'\nimport type { UserConfig, PluginOption, SSRTarget } from 'vite'\nimport type { PreRenderedAsset, PreRenderedChunk, LogLevel as RollupLogLevel, RollupLog } from 'rolldown'\nimport type { AssetMode, NormalizedCompileOptions, Format } from '../../shared/types/public/compile'\nimport type { BuildDocument } from './build-entry-module'\n\nimport { buildDocumentEntryModule } from './build-entry-module'\n\nimport { extname } from 'node:path'\nimport { createRequire } from 'node:module'\nimport { shouldDecodeStyleEntities } from '../utils/dependencies'\nimport { producerDefines } from './producer-release'\nimport { expandTransitiveDependencyClosure } from './dependency-closure'\n\nimport adaptorReactNode from './generated/adaptorReactNode.mjs?raw'\nimport adaptorReactBrowser from './generated/adaptorReactBrowser.mjs?raw'\nimport adaptorVueNode from './generated/adaptorVueNode.mjs?raw'\nimport adaptorVueBrowser from './generated/adaptorVueBrowser.mjs?raw'\nimport adaptorHtml from './generated/adaptorHtml.mjs?raw'\nimport createRenderer from './generated/createRenderer.mjs?raw'\nimport decodeStyleEntitiesModule from './generated/decodeStyleEntities.mjs?raw'\nimport sanitizeHtml from './generated/sanitizeHtml.mjs?raw'\nimport virtualStyles from './generated/virtualStyles.mjs?raw'\nimport validate from './generated/validate.mjs?raw'\n\nconst VIRTUAL_STYLES_MODULE_ID = 'virtual:styles'\nconst VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID = 'virtual:decode-style-entities'\nconst VIRTUAL_SANITIZE_HTML_MODULE_ID = 'virtual:sanitize-html'\nconst VIRTUAL_ENTRY_PREFIX = 'virtual:entry:'\nconst VIRTUAL_ADAPTOR_MODULE_ID = 'virtual:adaptor'\nconst VIRTUAL_VALIDATE_MODULE_ID = 'virtual:validate'\nconst VIRTUAL_CREATE_RENDERER_PREFIX = 'virtual:create-renderer:'\nconst ROLLDOWN_RUNTIME_CHUNK_RE = /^chunks\\/rolldown-runtime-.*\\.js$/\nconst ROLLDOWN_REQUIRE_LINE_RE = /var __require = \\/\\* @__PURE__ \\*\\/ createRequire\\(import\\.meta\\.url\\);/g\nconst WEBPACK_COMPAT_REQUIRE_LINE =\n\t'var __require = typeof process !== \"undefined\" && typeof process.getBuiltinModule === \"function\" ? process.getBuiltinModule(\"module\").createRequire(import.meta.url) : /* @__PURE__ */ createRequire(import.meta.url);'\n\nfunction makeExternalPredicate(\n\texternalArr: string[]\n): (id: string, parentId?: string, isResolved?: boolean) => boolean {\n\tif (externalArr.length === 0) {\n\t\treturn () => false\n\t}\n\n\treturn (id: string) => {\n\t\treturn externalArr.some(external => {\n\t\t\tif (id === external) return true\n\t\t\t// Match subpaths: e.g 'react-dom' matches 'react-dom/client'\n\t\t\tif (id.startsWith(external + '/')) return true\n\t\t\treturn false\n\t\t})\n\t}\n}\n\nfunction getAdaptor(framework: string, frameworkIsBundled: boolean): string {\n\tif (framework === 'html') return adaptorHtml\n\n\tif (framework === 'react') {\n\t\treturn frameworkIsBundled ? adaptorReactBrowser : adaptorReactNode\n\t}\n\n\treturn frameworkIsBundled ? adaptorVueBrowser : adaptorVueNode\n}\n\ntype Target = 'node' | 'browser' | 'worker'\n\ntype BuildConfigInput = {\n\tdocuments: BuildDocument[]\n\toutDir: string\n\tcompiledFileName: string\n\ttarget: Target\n\tsource: 'cli' | 'unplugin'\n\tplugins: PluginOption[]\n\tshouldMinify: boolean\n\tformat: Format\n\tlogger: { [K in RollupLogLevel]: (log: RollupLog) => void }\n\temittedAssetsDir: string\n\tassetMode: AssetMode\n\toptions: NormalizedCompileOptions\n\tconfig: FormatConfig\n\tforceExternalFramework?: boolean\n}\n\n/**\n * Resolved absolute path to the zip module the compiled wrapper imports its\n * helpers from, for every target and source: the full `@format.dev/zip/web` entry\n * for dynamic mode (it carries node-html-parser for runtime zipping) or the\n * slim `@format.dev/zip/scan` entry for static mode (regex scanner only). Both are\n * fully self-contained ESM (no bare imports to resolve, no node coupling), so\n * our own builds and consumer bundlers (vite, webpack, rollup, esbuild) inline\n * the file as-is — and static bundles never pull the parser.\n */\nexport function resolveZipModulePath(assetMode: AssetMode): string {\n\t// `none` wrappers do no asset work, so they import nothing from @format.dev/zip.\n\tif (assetMode === 'none') {\n\t\treturn ''\n\t}\n\n\t// Dynamic wrappers call zip() at render time and need the full web entry\n\t// (it carries node-html-parser). Static wrappers only run the regex\n\t// known-asset check, so they import the slim scan entry, which has no\n\t// path to the parser — that keeps node-html-parser in dynamic bundles only.\n\tconst subpath = assetMode === 'dynamic' ? '@format.dev/zip/web' : '@format.dev/zip/scan'\n\n\t// require.resolve honours the \"require\" condition (.cjs); the wrapper is\n\t// emitted as ESM, so swap to the sibling ESM build we own the layout of.\n\treturn createRequire(import.meta.url)\n\t\t.resolve(subpath)\n\t\t.replace(/\\.cjs$/, '.mjs')\n}\n\nexport const frameworkPkgs = ['react', 'react-dom', 'vue', 'vue/server-renderer']\n\ntype NoExternal = NonNullable<NonNullable<UserConfig['ssr']>['noExternal']>\n\nexport function makeViteBuildConfig(i: BuildConfigInput): UserConfig {\n\tconst {\n\t\ttarget,\n\t\tsource,\n\t\tplugins,\n\t\tdocuments,\n\t\tcompiledFileName,\n\t\toutDir,\n\t\tshouldMinify,\n\t\tformat,\n\t\tconfig,\n\t\tlogger,\n\t\temittedAssetsDir,\n\t\toptions\n\t} = i\n\n\t// When forceExternalFramework is set (SSR temp builds for asset pre-rendering),\n\t// framework packages are always kept external regardless of the user's bundle config.\n\t// Otherwise, the user's config determines whether framework is bundled or external.\n\tconst effectiveBundle = i.forceExternalFramework\n\t\t? options.bundle.filter(pkg => !frameworkPkgs.includes(pkg))\n\t\t: options.bundle\n\n\tconst frameworkIsBundled = (() => {\n\t\tif (config.framework === 'html') return false\n\n\t\tconst primaryPkg = config.framework // 'react' or 'vue'\n\n\t\tif (target === 'node') {\n\t\t\treturn effectiveBundle.includes(primaryPkg)\n\t\t}\n\n\t\t// Browser and worker bundle framework by default\n\t\treturn !options.external.includes(primaryPkg)\n\t})()\n\n\tconst adaptor = getAdaptor(config.framework, frameworkIsBundled)\n\n\tconst documentMap = new Map(documents.map(document => [document.name, document]))\n\n\tconst rendererVirtualPlugin: PluginOption = {\n\t\tname: 'plugin:virtual-modules',\n\t\tenforce: 'pre',\n\t\tresolveId(id) {\n\t\t\tif (id.startsWith(VIRTUAL_ENTRY_PREFIX)) {\n\t\t\t\treturn id\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_ADAPTOR_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_ADAPTOR_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_VALIDATE_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_VALIDATE_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_STYLES_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_STYLES_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_SANITIZE_HTML_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_SANITIZE_HTML_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id.startsWith(VIRTUAL_CREATE_RENDERER_PREFIX)) {\n\t\t\t\treturn id\n\t\t\t}\n\n\t\t\treturn null\n\t\t},\n\t\tasync load(id) {\n\t\t\tif (id.startsWith(VIRTUAL_ENTRY_PREFIX)) {\n\t\t\t\tconst documentName = id.slice(VIRTUAL_ENTRY_PREFIX.length)\n\t\t\t\tconst document = documentMap.get(documentName)\n\n\t\t\t\tif (!document) {\n\t\t\t\t\tthrow new Error(`Unknown document entry \"${documentName}\"`)\n\t\t\t\t}\n\n\t\t\t\tconst createRendererId = `${VIRTUAL_CREATE_RENDERER_PREFIX}${documentName}`\n\t\t\t\tconst entryModule = buildDocumentEntryModule(document, createRendererId, {\n\t\t\t\t\ttarget,\n\t\t\t\t\tsource,\n\t\t\t\t\tassetMode: i.assetMode,\n\t\t\t\t\tzipModulePath: resolveZipModulePath(i.assetMode)\n\t\t\t\t})\n\t\t\t\treturn { code: entryModule }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_ADAPTOR_MODULE_ID) {\n\t\t\t\treturn { code: adaptor }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_VALIDATE_MODULE_ID) {\n\t\t\t\treturn { code: validate }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_STYLES_MODULE_ID) {\n\t\t\t\treturn { code: virtualStyles }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID) {\n\t\t\t\tif (shouldDecodeStyleEntities({ framework: config.framework })) {\n\t\t\t\t\treturn { code: decodeStyleEntitiesModule }\n\t\t\t\t}\n\n\t\t\t\t// Stub: always safe to call, doesn't import any deps.\n\t\t\t\treturn {\n\t\t\t\t\tcode: [\n\t\t\t\t\t\t`export function decodeStyleEntities(html) { return html; }`,\n\t\t\t\t\t\t`export default decodeStyleEntities;`\n\t\t\t\t\t].join('\\n')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_SANITIZE_HTML_MODULE_ID) {\n\t\t\t\treturn { code: sanitizeHtml }\n\t\t\t}\n\n\t\t\tif (id.startsWith(VIRTUAL_CREATE_RENDERER_PREFIX)) {\n\t\t\t\treturn { code: createRenderer }\n\t\t\t}\n\n\t\t\treturn null\n\t\t}\n\t}\n\n\tconst webpackNodeCompatRuntimePlugin: PluginOption =\n\t\ttarget !== 'node' || source !== 'unplugin' || options.userBundler !== 'webpack'\n\t\t\t? null\n\t\t\t: {\n\t\t\t\t\tname: 'plugin:webpack-node-compat-runtime',\n\t\t\t\t\trenderChunk(code, chunk) {\n\t\t\t\t\t\tif (!ROLLDOWN_RUNTIME_CHUNK_RE.test(chunk.fileName)) {\n\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Webpack-node re-bundles can fail on the rolldown runtime's ESM helper:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// var __require = /* @__PURE__ */ createRequire(import.meta.url);\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// We rewrite it to a guarded variant:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// var __require = typeof process !== \"undefined\" && typeof process.getBuiltinModule === \"function\"\n\t\t\t\t\t\t// ? process.getBuiltinModule(\"module\").createRequire(import.meta.url)\n\t\t\t\t\t\t// : /* @__PURE__ */ createRequire(import.meta.url);\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// Also rewrite:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// import { createRequire } from \"node:module\"\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// to:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// import { createRequire } from \"module\"\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\tlet patched = code.replace(/from\\s+[\"']node:module[\"']/g, 'from \"module\"')\n\t\t\t\t\t\tpatched = patched.replace(ROLLDOWN_REQUIRE_LINE_RE, WEBPACK_COMPAT_REQUIRE_LINE)\n\n\t\t\t\t\t\tif (patched === code) {\n\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn { code: patched, map: null }\n\t\t\t\t\t}\n\t\t\t\t}\n\n\tconst cwd = config.cwd ? JSON.stringify(config.cwd) : JSON.stringify(process.cwd())\n\n\tconst conditions = options.conditions.length ? options.conditions : undefined\n\tconst externalConditions = options.externalConditions.length ? options.externalConditions : undefined\n\n\tconst common: UserConfig = {\n\t\tmode: 'production' as const,\n\t\tpublicDir: false,\n\t\tplugins: [\n\t\t\trendererVirtualPlugin,\n\t\t\t...(webpackNodeCompatRuntimePlugin ? [webpackNodeCompatRuntimePlugin] : []),\n\t\t\t...plugins\n\t\t],\n\t\tresolve: {\n\t\t\tpreserveSymlinks: false,\n\t\t\tconditions\n\t\t},\n\t\tdefine: {\n\t\t\t_FMT_VALIDATE_SCHEMA_: JSON.stringify(options.validateSchema),\n\t\t\t_FMT_CWD_: cwd,\n\t\t\t...producerDefines()\n\t\t},\n\t\tesbuild: {\n\t\t\tjsx: 'automatic',\n\t\t\tjsxDev: false,\n\t\t\tjsxImportSource: 'react'\n\t\t}\n\t}\n\n\tconst buildCommon = {\n\t\toutDir,\n\t\temptyOutDir: false, // very important*\n\t\tminify: shouldMinify,\n\t\tcssMinify: shouldMinify,\n\t\tcssCodeSplit: true\n\t}\n\n\tconst rollupInput = Object.fromEntries(\n\t\tdocuments.map(document => [document.name, `${VIRTUAL_ENTRY_PREFIX}${document.name}`])\n\t)\n\n\tconst rollupOptions = {\n\t\tinput: rollupInput,\n\t\tpreserveEntrySignatures: 'strict' as const,\n\t\ttreeshake: false, // I'm slightly nervous about treeshaking, so I've gone with false for now.\n\t\toutput: {\n\t\t\tformat,\n\t\t\tentryFileNames: (chunkInfo: PreRenderedChunk) => `${chunkInfo.name}/${compiledFileName}`,\n\t\t\t// styles and rolldown's runtime helpers are one-per-build infrastructure\n\t\t\t// chunks — hashing them would churn consumer output (and goldens) on\n\t\t\t// every toolchain bump for no caching benefit. User-code chunks keep the\n\t\t\t// hashed fallback so same-named dynamic chunks can't collide.\n\t\t\tchunkFileNames: (chunkInfo: PreRenderedChunk) =>\n\t\t\t\tchunkInfo.name === 'styles' || chunkInfo.name === 'rolldown-runtime'\n\t\t\t\t\t? `chunks/${chunkInfo.name}.js`\n\t\t\t\t\t: 'chunks/[name]-[hash].js',\n\t\t\tmanualChunks: (id: string) => {\n\t\t\t\t// Force virtual:styles into a shared chunk.\n\t\t\t\tif (id === VIRTUAL_STYLES_MODULE_ID) {\n\t\t\t\t\treturn 'styles'\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t},\n\t\t\t// Each entry deliberately ships a named export (the document's export\n\t\t\t// name) alongside a default. 'auto' can't pick a CJS shape when both are\n\t\t\t// present and warns (MIXED_EXPORT); 'named' makes the choice explicit and\n\t\t\t// keeps both reachable. Ignored for ES output, so the default ESM build is\n\t\t\t// unaffected.\n\t\t\texports: 'named' as const,\n\t\t\tassetFileNames: (assetInfo: PreRenderedAsset) => {\n\t\t\t\tconst name = assetInfo.names?.[0] ?? ''\n\t\t\t\tconst ext = extname(name).toLowerCase()\n\t\t\t\tconst imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.avif']\n\t\t\t\tconst fontExtensions = ['.woff', '.woff2', '.ttf', '.otf', '.eot']\n\n\t\t\t\t// Images and fonts — the assets a document author references — land in\n\t\t\t\t// the shared `assets/` dir so they sit in one place rather than split\n\t\t\t\t// across the outDir root. Images are content-hashed; fonts keep their\n\t\t\t\t// stable name (their @font-face src references them by it). Everything\n\t\t\t\t// else (e.g. emitted CSS the styles pipeline keys by its root path)\n\t\t\t\t// stays at the root, where the rest of the build expects it.\n\t\t\t\tif (imageExtensions.includes(ext)) {\n\t\t\t\t\treturn `${emittedAssetsDir}/[name]-[hash][extname]`\n\t\t\t\t}\n\n\t\t\t\tif (fontExtensions.includes(ext)) {\n\t\t\t\t\treturn `${emittedAssetsDir}/[name][extname]`\n\t\t\t\t}\n\n\t\t\t\treturn '[name][extname]'\n\t\t\t}\n\t\t},\n\t\tonLog: (level: RollupLogLevel, log: RollupLog) => {\n\t\t\tlogger[level](log)\n\t\t}\n\t}\n\n\t// Framework packages not in the effective bundle list are excluded from\n\t// the transitive closure so they don't get pulled in as indirect deps.\n\tconst frameworkExclude = frameworkPkgs.filter(pkg => !effectiveBundle.includes(pkg))\n\tconst nodeNoExternal = expandTransitiveDependencyClosure({\n\t\tseedPackages: effectiveBundle,\n\t\texcludedPackages: frameworkExclude\n\t})\n\n\t// Method: We use a Vite build + SSR configs to bundle for Node.\n\t// Externals: When bundling for Node, Vite's \"SSR\" mode defaults\n\t// to all deps being externalized. The \"bundle\" option includes\n\t// deps (including framework packages) in the bundle.\n\tconst node = {\n\t\t...common,\n\t\tssr: {\n\t\t\tnoExternal: nodeNoExternal,\n\t\t\tresolve: {\n\t\t\t\tconditions,\n\t\t\t\texternalConditions\n\t\t\t}\n\t\t},\n\t\tbuild: {\n\t\t\t...buildCommon,\n\t\t\tssr: true,\n\t\t\tssrEmitAssets: true,\n\t\t\ttarget: 'esnext' as const,\n\t\t\trollupOptions\n\t\t}\n\t} satisfies UserConfig\n\n\tconst workerNoExternal: NoExternal | undefined = options.bundleAll\n\t\t? (true as const)\n\t\t: options.bundle.length\n\t\t\t? options.bundle\n\t\t\t: undefined\n\n\tconst workerTarget: SSRTarget = 'webworker'\n\n\t// Method: We use a Vite build + SSR configs to bundle for a Worker-like runtime.\n\t// Externals: Worker builds can bundle all deps by default via presets, but users can still override.\n\tconst worker = {\n\t\t...common,\n\t\tdefine: {\n\t\t\t...common.define!,\n\t\t\t'process.env.NODE_ENV': JSON.stringify('production'),\n\t\t\t'process.env': JSON.stringify({}),\n\t\t\tglobal: 'globalThis'\n\t\t},\n\t\tssr: {\n\t\t\ttarget: workerTarget,\n\t\t\tnoExternal:\n\t\t\t\tworkerNoExternal === true\n\t\t\t\t\t? true\n\t\t\t\t\t: Array.isArray(workerNoExternal)\n\t\t\t\t\t\t? expandTransitiveDependencyClosure({\n\t\t\t\t\t\t\t\tseedPackages: workerNoExternal as string[],\n\t\t\t\t\t\t\t\texcludedPackages: frameworkPkgs\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: workerNoExternal,\n\t\t\texternal: options.external.length ? options.external : undefined,\n\t\t\tresolve: {\n\t\t\t\tconditions,\n\t\t\t\texternalConditions\n\t\t\t}\n\t\t},\n\t\tbuild: {\n\t\t\t...buildCommon,\n\t\t\tssr: true,\n\t\t\tssrEmitAssets: true,\n\t\t\ttarget: 'esnext' as const,\n\t\t\trollupOptions\n\t\t}\n\t} satisfies UserConfig\n\n\t// Method: We use standard Vite mode to bundle for the browser.\n\t// Externals: When bundling for the browser, Vite + Rollup default\n\t// to all deps being bundled. We provide the \"external\" option\n\t// to exclude deps from the bundle in this case.\n\tconst browser = {\n\t\t...common,\n\t\tdefine: {\n\t\t\t...common.define!,\n\t\t\t'process.env.NODE_ENV': JSON.stringify('production'),\n\t\t\t'process.env': JSON.stringify({}),\n\t\t\tglobal: 'globalThis'\n\t\t},\n\t\tbuild: {\n\t\t\t...buildCommon,\n\t\t\ttarget: 'baseline-widely-available',\n\t\t\trollupOptions: {\n\t\t\t\t...rollupOptions,\n\t\t\t\texternal: makeExternalPredicate(options.external)\n\t\t\t}\n\t\t}\n\t} satisfies UserConfig\n\n\t// *emptyOutDir is true by default in vite. For browser bundles, we build\n\t// an SSR bundle to render HTML for zip and this goes in the same ourDir.\n\t// So we don't want any automatic outDir emptying/cleansing.\n\n\tif (target === 'node') return node\n\tif (target === 'worker') return worker\n\treturn browser\n}\n"],"mappings":";;;;;;;;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GACA;EACD;CAMD,MAAM,UAAU;EACf,GAAG;EACH,QAAQ;GACP,GAAG,OAAO;GACV,wBAAwB,KAAK,UAAU,aAAa;GACpD,eAAe,KAAK,UAAU,EAAE,CAAC;GACjC,QAAQ;GACR;EACD,OAAO;GACN,GAAG;GACH,QAAQ;GACR,eAAe;IACd,GAAG;IACH,UAAU,sBAAsB,QAAQ,SAAS;IACjD;GACD;EACD;AAMD,KAAI,WAAW,OAAQ,QAAO;AAC9B,KAAI,WAAW,SAAU,QAAO;AAChC,QAAO"}
|
|
1
|
+
{"version":3,"file":"make-config.mjs","names":["adaptorHtml","adaptorReactBrowser","adaptorReactNode","adaptorVueBrowser","adaptorVueNode","rendererVirtualPlugin: PluginOption","validate","virtualStyles","decodeStyleEntitiesModule","sanitizeHtml","createRenderer","webpackNodeCompatRuntimePlugin: PluginOption","common: UserConfig","workerNoExternal: NoExternal | undefined","workerTarget: SSRTarget"],"sources":["../../../src/server/compile/make-config.ts"],"sourcesContent":["import type { FormatConfig } from '../../shared/types/public/config'\nimport type { UserConfig, PluginOption, SSRTarget } from 'vite'\nimport type { PreRenderedAsset, PreRenderedChunk, LogLevel as RollupLogLevel, RollupLog } from 'rolldown'\nimport type { AssetMode, NormalizedCompileOptions, Format } from '../../shared/types/public/compile'\nimport type { BuildDocument } from './build-entry-module'\n\nimport { buildDocumentEntryModule } from './build-entry-module'\n\nimport { extname } from 'node:path'\nimport { createRequire } from 'node:module'\nimport { shouldDecodeStyleEntities } from '../utils/dependencies'\nimport { producerDefines } from './producer-release'\nimport { expandTransitiveDependencyClosure } from './dependency-closure'\n\nimport adaptorReactNode from './generated/adaptorReactNode.mjs?raw'\nimport adaptorReactBrowser from './generated/adaptorReactBrowser.mjs?raw'\nimport adaptorVueNode from './generated/adaptorVueNode.mjs?raw'\nimport adaptorVueBrowser from './generated/adaptorVueBrowser.mjs?raw'\nimport adaptorHtml from './generated/adaptorHtml.mjs?raw'\nimport createRenderer from './generated/createRenderer.mjs?raw'\nimport decodeStyleEntitiesModule from './generated/decodeStyleEntities.mjs?raw'\nimport sanitizeHtml from './generated/sanitizeHtml.mjs?raw'\nimport virtualStyles from './generated/virtualStyles.mjs?raw'\nimport validate from './generated/validate.mjs?raw'\n\nconst VIRTUAL_STYLES_MODULE_ID = 'virtual:styles'\nconst VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID = 'virtual:decode-style-entities'\nconst VIRTUAL_SANITIZE_HTML_MODULE_ID = 'virtual:sanitize-html'\nconst VIRTUAL_ENTRY_PREFIX = 'virtual:entry:'\nconst VIRTUAL_ADAPTOR_MODULE_ID = 'virtual:adaptor'\nconst VIRTUAL_VALIDATE_MODULE_ID = 'virtual:validate'\nconst VIRTUAL_CREATE_RENDERER_PREFIX = 'virtual:create-renderer:'\nconst ROLLDOWN_RUNTIME_CHUNK_RE = /^chunks\\/rolldown-runtime-.*\\.js$/\nconst ROLLDOWN_REQUIRE_LINE_RE = /var __require = \\/\\* @__PURE__ \\*\\/ createRequire\\(import\\.meta\\.url\\);/g\nconst WEBPACK_COMPAT_REQUIRE_LINE =\n\t'var __require = typeof process !== \"undefined\" && typeof process.getBuiltinModule === \"function\" ? process.getBuiltinModule(\"module\").createRequire(import.meta.url) : /* @__PURE__ */ createRequire(import.meta.url);'\n\nfunction makeExternalPredicate(\n\texternalArr: string[]\n): (id: string, parentId?: string, isResolved?: boolean) => boolean {\n\tif (externalArr.length === 0) {\n\t\treturn () => false\n\t}\n\n\treturn (id: string) => {\n\t\treturn externalArr.some(external => {\n\t\t\tif (id === external) return true\n\t\t\t// Match subpaths: e.g 'react-dom' matches 'react-dom/client'\n\t\t\tif (id.startsWith(external + '/')) return true\n\t\t\treturn false\n\t\t})\n\t}\n}\n\nfunction getAdaptor(framework: string, frameworkIsBundled: boolean): string {\n\tif (framework === 'html') return adaptorHtml\n\n\tif (framework === 'react') {\n\t\treturn frameworkIsBundled ? adaptorReactBrowser : adaptorReactNode\n\t}\n\n\treturn frameworkIsBundled ? adaptorVueBrowser : adaptorVueNode\n}\n\ntype Target = 'node' | 'browser' | 'worker'\n\ntype BuildConfigInput = {\n\tdocuments: BuildDocument[]\n\toutDir: string\n\tcompiledFileName: string\n\ttarget: Target\n\tsource: 'cli' | 'unplugin'\n\tplugins: PluginOption[]\n\tshouldMinify: boolean\n\tformat: Format\n\tlogger: { [K in RollupLogLevel]: (log: RollupLog) => void }\n\temittedAssetsDir: string\n\tassetMode: AssetMode\n\toptions: NormalizedCompileOptions\n\tconfig: FormatConfig\n\tforceExternalFramework?: boolean\n}\n\n/**\n * Resolved absolute path to the zip module the compiled wrapper imports its\n * helpers from, for every target and source: the full `@format.dev/zip/web` entry\n * for dynamic mode (it carries node-html-parser for runtime zipping) or the\n * slim `@format.dev/zip/scan` entry for static mode (regex scanner only). Both are\n * fully self-contained ESM (no bare imports to resolve, no node coupling), so\n * our own builds and consumer bundlers (vite, webpack, rollup, esbuild) inline\n * the file as-is — and static bundles never pull the parser.\n */\nexport function resolveZipModulePath(assetMode: AssetMode): string {\n\t// `none` wrappers do no asset work, so they import nothing from @format.dev/zip.\n\tif (assetMode === 'none') {\n\t\treturn ''\n\t}\n\n\t// Dynamic wrappers call zip() at render time and need the full web entry\n\t// (it carries node-html-parser). Static wrappers only run the regex\n\t// known-asset check, so they import the slim scan entry, which has no\n\t// path to the parser — that keeps node-html-parser in dynamic bundles only.\n\tconst subpath = assetMode === 'dynamic' ? '@format.dev/zip/web' : '@format.dev/zip/scan'\n\n\t// require.resolve honours the \"require\" condition (.cjs); the wrapper is\n\t// emitted as ESM, so swap to the sibling ESM build we own the layout of.\n\treturn createRequire(import.meta.url)\n\t\t.resolve(subpath)\n\t\t.replace(/\\.cjs$/, '.mjs')\n}\n\nexport const frameworkPkgs = ['react', 'react-dom', 'vue', 'vue/server-renderer']\n\ntype NoExternal = NonNullable<NonNullable<UserConfig['ssr']>['noExternal']>\n\nexport function makeViteBuildConfig(i: BuildConfigInput): UserConfig {\n\tconst {\n\t\ttarget,\n\t\tsource,\n\t\tplugins,\n\t\tdocuments,\n\t\tcompiledFileName,\n\t\toutDir,\n\t\tshouldMinify,\n\t\tformat,\n\t\tconfig,\n\t\tlogger,\n\t\temittedAssetsDir,\n\t\toptions\n\t} = i\n\n\t// When forceExternalFramework is set (SSR temp builds for asset pre-rendering),\n\t// framework packages are always kept external regardless of the user's bundle config.\n\t// Otherwise, the user's config determines whether framework is bundled or external.\n\tconst effectiveBundle = i.forceExternalFramework\n\t\t? options.bundle.filter(pkg => !frameworkPkgs.includes(pkg))\n\t\t: options.bundle\n\n\tconst frameworkIsBundled = (() => {\n\t\tif (config.framework === 'html') return false\n\n\t\tconst primaryPkg = config.framework // 'react' or 'vue'\n\n\t\tif (target === 'node') {\n\t\t\treturn effectiveBundle.includes(primaryPkg)\n\t\t}\n\n\t\t// Browser and worker bundle framework by default\n\t\treturn !options.external.includes(primaryPkg)\n\t})()\n\n\tconst adaptor = getAdaptor(config.framework, frameworkIsBundled)\n\n\tconst documentMap = new Map(documents.map(document => [document.name, document]))\n\n\tconst rendererVirtualPlugin: PluginOption = {\n\t\tname: 'plugin:virtual-modules',\n\t\tenforce: 'pre',\n\t\tresolveId(id) {\n\t\t\tif (id.startsWith(VIRTUAL_ENTRY_PREFIX)) {\n\t\t\t\treturn id\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_ADAPTOR_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_ADAPTOR_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_VALIDATE_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_VALIDATE_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_STYLES_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_STYLES_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_SANITIZE_HTML_MODULE_ID) {\n\t\t\t\treturn VIRTUAL_SANITIZE_HTML_MODULE_ID\n\t\t\t}\n\n\t\t\tif (id.startsWith(VIRTUAL_CREATE_RENDERER_PREFIX)) {\n\t\t\t\treturn id\n\t\t\t}\n\n\t\t\treturn null\n\t\t},\n\t\tasync load(id) {\n\t\t\tif (id.startsWith(VIRTUAL_ENTRY_PREFIX)) {\n\t\t\t\tconst documentName = id.slice(VIRTUAL_ENTRY_PREFIX.length)\n\t\t\t\tconst document = documentMap.get(documentName)\n\n\t\t\t\tif (!document) {\n\t\t\t\t\tthrow new Error(`Unknown document entry \"${documentName}\"`)\n\t\t\t\t}\n\n\t\t\t\tconst createRendererId = `${VIRTUAL_CREATE_RENDERER_PREFIX}${documentName}`\n\t\t\t\tconst entryModule = buildDocumentEntryModule(document, createRendererId, {\n\t\t\t\t\ttarget,\n\t\t\t\t\tsource,\n\t\t\t\t\tassetMode: i.assetMode,\n\t\t\t\t\tzipModulePath: resolveZipModulePath(i.assetMode)\n\t\t\t\t})\n\t\t\t\treturn { code: entryModule }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_ADAPTOR_MODULE_ID) {\n\t\t\t\treturn { code: adaptor }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_VALIDATE_MODULE_ID) {\n\t\t\t\treturn { code: validate }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_STYLES_MODULE_ID) {\n\t\t\t\treturn { code: virtualStyles }\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_DECODE_STYLE_ENTITIES_MODULE_ID) {\n\t\t\t\tif (shouldDecodeStyleEntities({ framework: config.framework })) {\n\t\t\t\t\treturn { code: decodeStyleEntitiesModule }\n\t\t\t\t}\n\n\t\t\t\t// Stub: always safe to call, doesn't import any deps.\n\t\t\t\treturn {\n\t\t\t\t\tcode: [\n\t\t\t\t\t\t`export function decodeStyleEntities(html) { return html; }`,\n\t\t\t\t\t\t`export default decodeStyleEntities;`\n\t\t\t\t\t].join('\\n')\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (id === VIRTUAL_SANITIZE_HTML_MODULE_ID) {\n\t\t\t\treturn { code: sanitizeHtml }\n\t\t\t}\n\n\t\t\tif (id.startsWith(VIRTUAL_CREATE_RENDERER_PREFIX)) {\n\t\t\t\treturn { code: createRenderer }\n\t\t\t}\n\n\t\t\treturn null\n\t\t}\n\t}\n\n\tconst webpackNodeCompatRuntimePlugin: PluginOption =\n\t\ttarget !== 'node' || source !== 'unplugin' || options.userBundler !== 'webpack'\n\t\t\t? null\n\t\t\t: {\n\t\t\t\t\tname: 'plugin:webpack-node-compat-runtime',\n\t\t\t\t\trenderChunk(code, chunk) {\n\t\t\t\t\t\tif (!ROLLDOWN_RUNTIME_CHUNK_RE.test(chunk.fileName)) {\n\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Webpack-node re-bundles can fail on the rolldown runtime's ESM helper:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// var __require = /* @__PURE__ */ createRequire(import.meta.url);\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// We rewrite it to a guarded variant:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// var __require = typeof process !== \"undefined\" && typeof process.getBuiltinModule === \"function\"\n\t\t\t\t\t\t// ? process.getBuiltinModule(\"module\").createRequire(import.meta.url)\n\t\t\t\t\t\t// : /* @__PURE__ */ createRequire(import.meta.url);\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t//\n\t\t\t\t\t\t// Also rewrite:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// import { createRequire } from \"node:module\"\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// to:\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\t// import { createRequire } from \"module\"\n\t\t\t\t\t\t// ```\n\t\t\t\t\t\tlet patched = code.replace(/from\\s+[\"']node:module[\"']/g, 'from \"module\"')\n\t\t\t\t\t\tpatched = patched.replace(ROLLDOWN_REQUIRE_LINE_RE, WEBPACK_COMPAT_REQUIRE_LINE)\n\n\t\t\t\t\t\tif (patched === code) {\n\t\t\t\t\t\t\treturn null\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\treturn { code: patched, map: null }\n\t\t\t\t\t}\n\t\t\t\t}\n\n\tconst cwd = config.cwd ? JSON.stringify(config.cwd) : JSON.stringify(process.cwd())\n\n\tconst conditions = options.conditions.length ? options.conditions : undefined\n\tconst externalConditions = options.externalConditions.length ? options.externalConditions : undefined\n\n\tconst common: UserConfig = {\n\t\tmode: 'production' as const,\n\t\tpublicDir: false,\n\t\tplugins: [\n\t\t\trendererVirtualPlugin,\n\t\t\t...(webpackNodeCompatRuntimePlugin ? [webpackNodeCompatRuntimePlugin] : []),\n\t\t\t...plugins\n\t\t],\n\t\tresolve: {\n\t\t\tpreserveSymlinks: false,\n\t\t\tconditions\n\t\t},\n\t\tdefine: {\n\t\t\t_FMT_VALIDATE_SCHEMA_: JSON.stringify(options.validateSchema),\n\t\t\t_FMT_CWD_: cwd,\n\t\t\t...producerDefines()\n\t\t},\n\t\tesbuild: {\n\t\t\tjsx: 'automatic',\n\t\t\tjsxDev: false,\n\t\t\tjsxImportSource: 'react'\n\t\t}\n\t}\n\n\tconst buildCommon = {\n\t\toutDir,\n\t\temptyOutDir: false, // very important*\n\t\tminify: shouldMinify,\n\t\tcssMinify: shouldMinify,\n\t\tcssCodeSplit: true\n\t}\n\n\tconst rollupInput = Object.fromEntries(\n\t\tdocuments.map(document => [document.name, `${VIRTUAL_ENTRY_PREFIX}${document.name}`])\n\t)\n\n\tconst rollupOptions = {\n\t\tinput: rollupInput,\n\t\tpreserveEntrySignatures: 'strict' as const,\n\t\ttreeshake: false, // I'm slightly nervous about treeshaking, so I've gone with false for now.\n\t\t// Rolldown otherwise heads each module in the output with a comment naming its\n\t\t// source path, which spells out the project's directory layout.\n\t\texperimental: { attachDebugInfo: 'none' as const },\n\t\toutput: {\n\t\t\tformat,\n\t\t\tentryFileNames: (chunkInfo: PreRenderedChunk) => `${chunkInfo.name}/${compiledFileName}`,\n\t\t\t// styles and rolldown's runtime helpers are one-per-build infrastructure\n\t\t\t// chunks — hashing them would churn consumer output (and goldens) on\n\t\t\t// every toolchain bump for no caching benefit. User-code chunks keep the\n\t\t\t// hashed fallback so same-named dynamic chunks can't collide.\n\t\t\tchunkFileNames: (chunkInfo: PreRenderedChunk) =>\n\t\t\t\tchunkInfo.name === 'styles' || chunkInfo.name === 'rolldown-runtime'\n\t\t\t\t\t? `chunks/${chunkInfo.name}.js`\n\t\t\t\t\t: 'chunks/[name]-[hash].js',\n\t\t\t// Force virtual:styles into a shared chunk. Vite turns code splitting off\n\t\t\t// for a single-document worker build unless this option is set, and the\n\t\t\t// styles chunk would then fold into the entry.\n\t\t\tcodeSplitting: {\n\t\t\t\tgroups: [{ name: 'styles', test: (id: string) => id === VIRTUAL_STYLES_MODULE_ID }]\n\t\t\t},\n\t\t\t// Compiled documents carry no legal or JSDoc comments. Vite keeps both in\n\t\t\t// an unminified build, and the JSDoc from bundled dependencies made test\n\t\t\t// documents 12–18% larger, which counts against a worker's size limit.\n\t\t\tcomments: { legal: false, jsdoc: false },\n\t\t\t// Each entry deliberately ships a named export (the document's export\n\t\t\t// name) alongside a default. 'auto' can't pick a CJS shape when both are\n\t\t\t// present and warns (MIXED_EXPORT); 'named' makes the choice explicit and\n\t\t\t// keeps both reachable. Ignored for ES output, so the default ESM build is\n\t\t\t// unaffected.\n\t\t\texports: 'named' as const,\n\t\t\tassetFileNames: (assetInfo: PreRenderedAsset) => {\n\t\t\t\tconst name = assetInfo.names?.[0] ?? ''\n\t\t\t\tconst ext = extname(name).toLowerCase()\n\t\t\t\tconst imageExtensions = ['.png', '.jpg', '.jpeg', '.gif', '.svg', '.webp', '.avif']\n\t\t\t\tconst fontExtensions = ['.woff', '.woff2', '.ttf', '.otf', '.eot']\n\n\t\t\t\t// Images and fonts — the assets a document author references — land in\n\t\t\t\t// the shared `assets/` dir so they sit in one place rather than split\n\t\t\t\t// across the outDir root. Images are content-hashed; fonts keep their\n\t\t\t\t// stable name (their @font-face src references them by it). Everything\n\t\t\t\t// else (e.g. emitted CSS the styles pipeline keys by its root path)\n\t\t\t\t// stays at the root, where the rest of the build expects it.\n\t\t\t\tif (imageExtensions.includes(ext)) {\n\t\t\t\t\treturn `${emittedAssetsDir}/[name]-[hash][extname]`\n\t\t\t\t}\n\n\t\t\t\tif (fontExtensions.includes(ext)) {\n\t\t\t\t\treturn `${emittedAssetsDir}/[name][extname]`\n\t\t\t\t}\n\n\t\t\t\treturn '[name][extname]'\n\t\t\t}\n\t\t},\n\t\tonLog: (level: RollupLogLevel, log: RollupLog) => {\n\t\t\tlogger[level](log)\n\t\t}\n\t}\n\n\t// Framework packages not in the effective bundle list are excluded from\n\t// the transitive closure so they don't get pulled in as indirect deps.\n\tconst frameworkExclude = frameworkPkgs.filter(pkg => !effectiveBundle.includes(pkg))\n\tconst nodeNoExternal = expandTransitiveDependencyClosure({\n\t\tseedPackages: effectiveBundle,\n\t\texcludedPackages: frameworkExclude\n\t})\n\n\t// Method: We use a Vite build + SSR configs to bundle for Node.\n\t// Externals: When bundling for Node, Vite's \"SSR\" mode defaults\n\t// to all deps being externalized. The \"bundle\" option includes\n\t// deps (including framework packages) in the bundle.\n\tconst node = {\n\t\t...common,\n\t\tssr: {\n\t\t\tnoExternal: nodeNoExternal,\n\t\t\tresolve: {\n\t\t\t\tconditions,\n\t\t\t\texternalConditions\n\t\t\t}\n\t\t},\n\t\tbuild: {\n\t\t\t...buildCommon,\n\t\t\tssr: true,\n\t\t\tssrEmitAssets: true,\n\t\t\ttarget: 'esnext' as const,\n\t\t\trollupOptions\n\t\t}\n\t} satisfies UserConfig\n\n\tconst workerNoExternal: NoExternal | undefined = options.bundleAll\n\t\t? (true as const)\n\t\t: options.bundle.length\n\t\t\t? options.bundle\n\t\t\t: undefined\n\n\tconst workerTarget: SSRTarget = 'webworker'\n\n\t// Method: We use a Vite build + SSR configs to bundle for a Worker-like runtime.\n\t// Externals: Worker builds can bundle all deps by default via presets, but users can still override.\n\tconst worker = {\n\t\t...common,\n\t\tdefine: {\n\t\t\t...common.define!,\n\t\t\t'process.env.NODE_ENV': JSON.stringify('production'),\n\t\t\t'process.env': JSON.stringify({}),\n\t\t\tglobal: 'globalThis'\n\t\t},\n\t\tssr: {\n\t\t\ttarget: workerTarget,\n\t\t\tnoExternal:\n\t\t\t\tworkerNoExternal === true\n\t\t\t\t\t? true\n\t\t\t\t\t: Array.isArray(workerNoExternal)\n\t\t\t\t\t\t? expandTransitiveDependencyClosure({\n\t\t\t\t\t\t\t\tseedPackages: workerNoExternal as string[],\n\t\t\t\t\t\t\t\texcludedPackages: frameworkPkgs\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t: workerNoExternal,\n\t\t\texternal: options.external.length ? options.external : undefined,\n\t\t\tresolve: {\n\t\t\t\tconditions,\n\t\t\t\texternalConditions\n\t\t\t}\n\t\t},\n\t\tbuild: {\n\t\t\t...buildCommon,\n\t\t\tssr: true,\n\t\t\tssrEmitAssets: true,\n\t\t\ttarget: 'esnext' as const,\n\t\t\trollupOptions\n\t\t}\n\t} satisfies UserConfig\n\n\t// Method: We use standard Vite mode to bundle for the browser.\n\t// Externals: When bundling for the browser, Vite + Rollup default\n\t// to all deps being bundled. We provide the \"external\" option\n\t// to exclude deps from the bundle in this case.\n\tconst browser = {\n\t\t...common,\n\t\tdefine: {\n\t\t\t...common.define!,\n\t\t\t'process.env.NODE_ENV': JSON.stringify('production'),\n\t\t\t'process.env': JSON.stringify({}),\n\t\t\tglobal: 'globalThis'\n\t\t},\n\t\tbuild: {\n\t\t\t...buildCommon,\n\t\t\ttarget: 'baseline-widely-available',\n\t\t\trollupOptions: {\n\t\t\t\t...rollupOptions,\n\t\t\t\texternal: makeExternalPredicate(options.external)\n\t\t\t}\n\t\t}\n\t} satisfies UserConfig\n\n\t// *emptyOutDir is true by default in vite. For browser bundles, we build\n\t// an SSR bundle to render HTML for zip and this goes in the same ourDir.\n\t// So we don't want any automatic outDir emptying/cleansing.\n\n\tif (target === 'node') return node\n\tif (target === 'worker') return worker\n\treturn browser\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,MAAM,2BAA2B;AACjC,MAAM,0CAA0C;AAChD,MAAM,kCAAkC;AACxC,MAAM,uBAAuB;AAC7B,MAAM,4BAA4B;AAClC,MAAM,6BAA6B;AACnC,MAAM,iCAAiC;AACvC,MAAM,4BAA4B;AAClC,MAAM,2BAA2B;AACjC,MAAM,8BACL;AAED,SAAS,sBACR,aACmE;AACnE,KAAI,YAAY,WAAW,EAC1B,cAAa;AAGd,SAAQ,OAAe;AACtB,SAAO,YAAY,MAAK,aAAY;AACnC,OAAI,OAAO,SAAU,QAAO;AAE5B,OAAI,GAAG,WAAW,WAAW,IAAI,CAAE,QAAO;AAC1C,UAAO;IACN;;;AAIJ,SAAS,WAAW,WAAmB,oBAAqC;AAC3E,KAAI,cAAc,OAAQ,QAAOA;AAEjC,KAAI,cAAc,QACjB,QAAO,qBAAqBC,8BAAsBC;AAGnD,QAAO,qBAAqBC,4BAAoBC;;;;;;;;;;;AA+BjD,SAAgB,qBAAqB,WAA8B;AAElE,KAAI,cAAc,OACjB,QAAO;CAOR,MAAM,UAAU,cAAc,YAAY,wBAAwB;AAIlE,QAAO,cAAc,OAAO,KAAK,IAAI,CACnC,QAAQ,QAAQ,CAChB,QAAQ,UAAU,OAAO;;AAG5B,MAAa,gBAAgB;CAAC;CAAS;CAAa;CAAO;CAAsB;AAIjF,SAAgB,oBAAoB,GAAiC;CACpE,MAAM,EACL,QACA,QACA,SACA,WACA,kBACA,QACA,cACA,QACA,QACA,QACA,kBACA,YACG;CAKJ,MAAM,kBAAkB,EAAE,yBACvB,QAAQ,OAAO,QAAO,QAAO,CAAC,cAAc,SAAS,IAAI,CAAC,GAC1D,QAAQ;CAEX,MAAM,4BAA4B;AACjC,MAAI,OAAO,cAAc,OAAQ,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GACJ,QAAQ;GACR,YACC,qBAAqB,OAClB,OACA,MAAM,QAAQ,iBAAiB,GAC9B,kCAAkC;IAClC,cAAc;IACd,kBAAkB;IAClB,CAAC,GACD;GACL,UAAU,QAAQ,SAAS,SAAS,QAAQ,WAAW;GACvD,SAAS;IACR;IACA;IACA;GACD;EACD,OAAO;GACN,GAAG;GACH,KAAK;GACL,eAAe;GACf,QAAQ;GACR;GACA;EACD;CAMD,MAAM,UAAU;EACf,GAAG;EACH,QAAQ;GACP,GAAG,OAAO;GACV,wBAAwB,KAAK,UAAU,aAAa;GACpD,eAAe,KAAK,UAAU,EAAE,CAAC;GACjC,QAAQ;GACR;EACD,OAAO;GACN,GAAG;GACH,QAAQ;GACR,eAAe;IACd,GAAG;IACH,UAAU,sBAAsB,QAAQ,SAAS;IACjD;GACD;EACD;AAMD,KAAI,WAAW,OAAQ,QAAO;AAC9B,KAAI,WAAW,SAAU,QAAO;AAChC,QAAO"}
|
|
@@ -218,7 +218,7 @@ async function generateEntry(config, options) {
|
|
|
218
218
|
await mkdir(outDir, { recursive: true });
|
|
219
219
|
const suppressRolldownLogs = (_level, ...args) => {
|
|
220
220
|
const msg = args.join(" ");
|
|
221
|
-
if (msg.includes("
|
|
221
|
+
if (msg.includes("vite v") && msg.includes("building")) return false;
|
|
222
222
|
if (msg.includes("built in")) return false;
|
|
223
223
|
return true;
|
|
224
224
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-entry.mjs","names":["TARGET_SUFFIXES: Record<Target, string>","assetMode: AssetMode","compiledDocuments: EntryDocument[]","init: EntryDocument['init']","urlMap: Record<string, string>","rm"],"sources":["../../../../src/server/integrations/nextjs/generate-entry.ts"],"sourcesContent":["import type { FormatConfig } from '../../../shared/types'\nimport type { AssetMode, Target } from '../../../shared/types/public/compile'\nimport type { FormatNextPluginOptions, FormatTargetOptions } from '../../../shared/types/public/nextjs'\nimport type { DocumentAssetState } from '../../compile/compile'\n\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'\nimport { listZipEntries } from '@format.dev/zip'\nimport { compileForUnplugin } from '../../compile/compile'\nimport { getBundleOutDir } from '../../compile/compile'\nimport { getDocuments } from '../../project/documents'\nimport { getDocumentsDir } from '../../project/paths'\nimport { buildDocumentExportMap } from '@format.dev/cli/scaffold'\nimport { resolveBundleName } from '../../compile/bundle-name'\nimport { BUNDLE_ENTRY_POINT_FILE_NAME } from '../../compile/constants'\nimport { computeCacheHash, readCachedHash, writeCacheHash } from '../../compile/compile-cache'\nimport { dynamicAssetEmitEntries } from '../../compile/document-assets'\nimport { buildWrapperFactorySource } from '../../compile/wrapper-source'\nimport { resolveZipModulePath } from '../../compile/make-config'\nimport { writeFormatEnvTypes } from '../../project/format-env-types'\nimport { logger, withPrefixedConsole } from '../../utils/log'\n\nconst TARGET_SUFFIXES: Record<Target, string> = {\n\tnode: '/node',\n\tbrowser: '/browser',\n\tworker: '/edge'\n}\n\ninterface ResolvedTargetOptions {\n\ttarget: Target\n\tassets: AssetMode | null\n\tinlineRemoteCss: boolean\n\tvalidateSchema: boolean\n\tbundle: string[]\n\texternal: string[]\n}\n\ninterface TargetEntry {\n\ttarget: Target\n\tsuffix: string\n\taliasKeys: string[]\n\tentryPath: string\n}\n\nexport interface GenerateEntryResult {\n\tentries: TargetEntry[]\n\toutDir: string\n}\n\nfunction resolveTargetOptions(shared: FormatNextPluginOptions, target: FormatTargetOptions): ResolvedTargetOptions {\n\treturn {\n\t\ttarget: target.target,\n\t\tassets: target.assets ?? shared.assets ?? null,\n\t\tinlineRemoteCss: target.inlineRemoteCss ?? shared.inlineRemoteCss ?? false,\n\t\tvalidateSchema: target.validateSchema ?? shared.validateSchema ?? true,\n\t\tbundle: target.bundle ?? [],\n\t\texternal: target.external ?? []\n\t}\n}\n\nfunction getEntryFileName(target: Target): string {\n\treturn `_next-entry-${target}.js`\n}\n\ninterface EntryDocument {\n\tdocumentName: string\n\texportName: string\n\tinit: {\n\t\tknownAssets: string[]\n\t\tassetUrls: Record<string, string> | null\n\t\tassetsPath: string | null\n\t\tassetsUrl: string | null\n\t}\n}\n\nfunction buildEntrySource(\n\ttarget: Target,\n\tassetMode: AssetMode,\n\trendererRelativePath: string,\n\tdocuments: EntryDocument[]\n): string {\n\tconst exportList = documents.map(doc => doc.exportName).join(', ')\n\n\tconst factory = buildWrapperFactorySource({\n\t\tmode: assetMode,\n\t\ttarget,\n\t\tzipModulePath: resolveZipModulePath(assetMode)\n\t})\n\n\tconst wrapperLines = documents.map(\n\t\tdoc =>\n\t\t\t`const ${doc.exportName} = createRendererWrapper(${JSON.stringify(doc.documentName)}, resolveRenderer(${JSON.stringify(doc.exportName)}), ${JSON.stringify(doc.init)});`\n\t)\n\n\treturn [\n\t\t`import * as rendererModule from ${JSON.stringify(rendererRelativePath)};`,\n\t\tfactory,\n\t\t[\n\t\t\t`function resolveRenderer(name) {`,\n\t\t\t`\tconst renderer = rendererModule?.[name] ?? rendererModule?.default?.[name] ?? rendererModule?.default?.default?.[name];`,\n\t\t\t`\tif (!renderer) {`,\n\t\t\t`\t\tthrow new Error('Renderer export \"' + name + '\" not found');`,\n\t\t\t`\t}`,\n\t\t\t`\treturn renderer;`,\n\t\t\t`}`\n\t\t].join('\\n'),\n\t\twrapperLines.join('\\n'),\n\t\t`export { ${exportList} };`,\n\t\t`export default { ${exportList} };`,\n\t\t''\n\t].join('\\n\\n')\n}\n\nfunction buildTypesSourceForModule(moduleAlias: string, documents: Array<{ exportName: string }>): string {\n\tconst exportNames = documents.map(doc => doc.exportName)\n\n\tconst namedExports = exportNames.map(name => `\\texport const ${name}: FormatRenderer`).join('\\n')\n\n\tconst defaultShape = exportNames.map(name => `${name}: FormatRenderer`).join('; ')\n\n\treturn [\n\t\t`declare module '${moduleAlias}' {`,\n\t\t'\\tinterface FormatAssetConfig {',\n\t\t'\\t\\tgetAssetsUrl(): string | undefined',\n\t\t'\\t\\tsetAssetsUrl(url: string): void',\n\t\t'\\t}',\n\t\t'',\n\t\t'\\tinterface FormatDocument {',\n\t\t'\\t\\thtml: string',\n\t\t'\\t\\tgetAssetsWebStream(): Promise<ReadableStream<Uint8Array> | undefined>',\n\t\t'\\t}',\n\t\t'',\n\t\t'\\tinterface FormatRenderer extends FormatAssetConfig {',\n\t\t'\\t\\trender(data?: Record<string, unknown>): Promise<FormatDocument>',\n\t\t'\\t\\tgetAssetsWebStream(): Promise<ReadableStream<Uint8Array> | undefined>',\n\t\t'\\t}',\n\t\t'',\n\t\tnamedExports,\n\t\t'',\n\t\t`\\tconst renderers: { ${defaultShape}; [key: string]: FormatRenderer }`,\n\t\t'\\texport default renderers',\n\t\t'}'\n\t].join('\\n')\n}\n\nfunction buildTypesSource(aliases: string[], documents: Array<{ exportName: string }>): string {\n\tconst modules = aliases.map(alias => buildTypesSourceForModule(alias, documents)).join('\\n\\n')\n\n\treturn `// Auto-generated by Format Studio — do not edit\\n${modules}\\n`\n}\n\nfunction patchReactDomServerImports(source: string): string {\n\tlet patched = source\n\n\tpatched = patched.replace(\n\t\t/import\\s*\\{([^}]+)\\}\\s*from\\s*[\"']react-dom\\/server[\"']\\s*;?/g,\n\t\t'const {$1} = await import(\"react-dom/server\");'\n\t)\n\n\tpatched = patched.replace(\n\t\t/import\\s*\\*\\s*as\\s+(\\w+)\\s+from\\s*[\"']react-dom\\/server[\"']\\s*;?/g,\n\t\t'const $1 = await import(\"react-dom/server\");'\n\t)\n\n\tpatched = patched.replace(\n\t\t/import\\s+(\\w+)\\s+from\\s*[\"']react-dom\\/server[\"']\\s*;?/g,\n\t\t'const { default: $1 } = await import(\"react-dom/server\");'\n\t)\n\n\treturn patched\n}\n\nasync function patchFile(filePath: string): Promise<void> {\n\tconst content = await readFile(filePath, 'utf-8')\n\tconst patched = patchReactDomServerImports(content)\n\n\tif (patched !== content) {\n\t\tawait writeFile(filePath, patched, 'utf-8')\n\t\tlogger.debug(`Patched react-dom/server imports in ${filePath}`)\n\t}\n}\n\nasync function patchCompiledBundles(outDir: string, documentNames: string[]): Promise<void> {\n\tfor (const documentName of documentNames) {\n\t\tawait patchFile(resolve(outDir, documentName, BUNDLE_ENTRY_POINT_FILE_NAME))\n\t}\n\n\t// Shared chunks can also contain react-dom/server imports (e.g. the engine chunk)\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 patchFile(resolve(chunksDir, file))\n\t\t}\n\t}\n}\n\nasync function compileTarget(\n\ttargetConfig: FormatTargetOptions,\n\toptions: FormatNextPluginOptions,\n\tconfig: FormatConfig,\n\toutDir: string,\n\tbundleName: string,\n\tdocumentNames: string[],\n\texportNames: Map<string, string>\n): Promise<TargetEntry> {\n\tconst resolved = resolveTargetOptions(options, targetConfig)\n\tconst suffix = TARGET_SUFFIXES[resolved.target]\n\tconst suffixedAlias = `@format:${bundleName}${suffix}`\n\tconst targetOutDir = resolve(outDir, resolved.target)\n\tconst assetMode: AssetMode = resolved.assets ?? 'static'\n\n\tlogger.info(`Compiling ${resolved.target} bundle. Documents: ${documentNames.join(', ')}`)\n\n\tconst assetState = new Map<string, DocumentAssetState>()\n\tawait compileForUnplugin(\n\t\t{\n\t\t\tdocuments: documentNames,\n\t\t\tassets: resolved.assets,\n\t\t\tvalidateSchema: resolved.validateSchema,\n\t\t\tinlineRemoteCss: resolved.inlineRemoteCss,\n\t\t\tbundle: resolved.bundle,\n\t\t\texternal: resolved.external,\n\t\t\ttarget: resolved.target,\n\t\t\tconfigPath: options.configPath,\n\t\t\toutDir: targetOutDir,\n\t\t\tbundleName,\n\t\t\tclean: false,\n\t\t\tuserBundler: 'webpack'\n\t\t},\n\t\t{ capturedAssetState: assetState }\n\t)\n\n\tawait patchCompiledBundles(targetOutDir, documentNames)\n\n\t// The generated entry lives outside the compiled outDir and is re-bundled\n\t// by Next.js, so all asset locations are baked as absolute file:// URLs.\n\t// Browser/edge consumers point at hosted assets with setAssetsUrl().\n\tconst compiledDocuments: EntryDocument[] = []\n\n\tfor (const name of documentNames) {\n\t\tconst init: EntryDocument['init'] = { knownAssets: [], assetUrls: null, assetsPath: null, assetsUrl: null }\n\n\t\tif (assetMode === 'static') {\n\t\t\tconst zipPath = resolve(targetOutDir, name, 'assets.zip')\n\t\t\tconst zipBuffer = await readFile(zipPath).catch(() => null)\n\n\t\t\tif (zipBuffer) {\n\t\t\t\tinit.knownAssets = listZipEntries(new Uint8Array(zipBuffer))\n\t\t\t\tinit.assetsUrl = pathToFileURL(zipPath).href\n\t\t\t}\n\t\t} else if (assetMode === 'dynamic') {\n\t\t\tconst compiledUrlMap = assetState.get(name)?.urlMap ?? {}\n\t\t\tconst entries = dynamicAssetEmitEntries({\n\t\t\t\toutDir: targetOutDir,\n\t\t\t\tdocumentName: name,\n\t\t\t\turlMap: compiledUrlMap\n\t\t\t})\n\n\t\t\tconst urlMap: Record<string, string> = {}\n\t\t\tfor (const entry of entries) {\n\t\t\t\turlMap[entry.knownPath] = pathToFileURL(entry.sourcePath).href\n\t\t\t}\n\n\t\t\tinit.assetUrls = urlMap\n\t\t\tinit.knownAssets = Object.keys(urlMap).sort()\n\t\t}\n\n\t\tcompiledDocuments.push({ documentName: name, exportName: exportNames.get(name)!, init })\n\t}\n\n\tconst entryFileName = getEntryFileName(resolved.target)\n\tconst rendererRelativePath = `./${resolved.target}/${BUNDLE_ENTRY_POINT_FILE_NAME}`\n\tconst entrySource = buildEntrySource(resolved.target, assetMode, rendererRelativePath, compiledDocuments)\n\tconst entryPath = resolve(outDir, entryFileName)\n\tawait writeFile(entryPath, entrySource, 'utf-8')\n\n\tlogger.debug(`Generated Next.js entry module for ${resolved.target} at ${entryPath}`)\n\n\treturn { target: resolved.target, suffix, aliasKeys: [suffixedAlias], entryPath }\n}\n\nexport async function generateEntry(\n\tconfig: FormatConfig,\n\toptions: FormatNextPluginOptions\n): Promise<GenerateEntryResult> {\n\tconst bundleName = resolveBundleName(options.bundleName)\n\tconst outDir = getBundleOutDir(config, options.outDir)\n\tconst targets = options.targets ?? [{ target: 'node' }]\n\n\tconst documents = await getDocuments(config)\n\tconst documentNames = documents.map(doc => doc.name).sort((a, b) => a.localeCompare(b))\n\n\tif (documentNames.length === 0) {\n\t\tthrow new Error('No documents found to compile.')\n\t}\n\n\tconst exportNames = buildDocumentExportMap(documentNames)\n\n\t// Check cache — skip compilation if documents + options haven't changed\n\tconst documentsDir = getDocumentsDir(config)\n\tconst currentHash = await computeCacheHash(documentsDir, options)\n\tconst cachedHash = await readCachedHash(outDir)\n\n\tif (cachedHash === currentHash) {\n\t\tlogger.info('Cache hit. Skipping compile.')\n\n\t\tconst entries: TargetEntry[] = targets.map((targetConfig, index) => {\n\t\t\tconst resolved = resolveTargetOptions(options, targetConfig)\n\t\t\tconst suffix = TARGET_SUFFIXES[resolved.target]\n\t\t\tconst suffixedAlias = `@format:${bundleName}${suffix}`\n\t\t\tconst entryFileName = getEntryFileName(resolved.target)\n\t\t\tconst entryPath = resolve(outDir, entryFileName)\n\n\t\t\tconst aliasKeys = index === 0 ? [`@format:${bundleName}`, suffixedAlias] : [suffixedAlias]\n\n\t\t\treturn { target: resolved.target, suffix, aliasKeys, entryPath }\n\t\t})\n\n\t\treturn { entries, outDir }\n\t}\n\n\tlogger.debug(`Cache miss. Compiling ${targets.length} target(s)`)\n\n\tif (options.clean !== false) {\n\t\tconst { rm } = await import('node:fs/promises')\n\t\tawait rm(outDir, { recursive: true, force: true }).catch(() => {})\n\t}\n\n\tawait mkdir(outDir, { recursive: true })\n\n\tconst suppressRolldownLogs = (_level: string, ...args: unknown[]) => {\n\t\tconst msg = args.join(' ')\n\n\t\tif (msg.includes('rolldown-vite') && msg.includes('building')) return false\n\t\tif (msg.includes('built in')) return false\n\n\t\treturn true\n\t}\n\n\t// Compile all targets in parallel, suppressing rolldown's stdout noise\n\tconst entries = (await withPrefixedConsole(\n\t\t() =>\n\t\t\tPromise.all(\n\t\t\t\ttargets.map(targetConfig =>\n\t\t\t\t\tcompileTarget(targetConfig, options, config, outDir, bundleName, documentNames, exportNames)\n\t\t\t\t)\n\t\t\t),\n\t\tsuppressRolldownLogs\n\t)) as TargetEntry[]\n\n\t// First target also gets the base alias (format:<bundleName>)\n\tconst baseAlias = `@format:${bundleName}`\n\tentries[0].aliasKeys = [baseAlias, ...entries[0].aliasKeys]\n\n\tconst allAliases = entries.flatMap(e => e.aliasKeys)\n\tconst documentsForTypes = documentNames.map(name => ({\n\t\texportName: exportNames.get(name)!\n\t}))\n\n\tconst typesSource = buildTypesSource(allAliases, documentsForTypes)\n\tconst typesPath = resolve(outDir, 'types.d.ts')\n\tawait writeFile(typesPath, typesSource, 'utf-8')\n\n\t// Write the project's format-env.d.ts — the same file init seeds and every\n\t// bundler plugin regenerates, so document imports are strongly typed.\n\tawait writeFormatEnvTypes({\n\t\tprojectRoot: process.cwd(),\n\t\taliases: allAliases,\n\t\tdocuments: documentsForTypes\n\t})\n\n\tawait writeCacheHash(outDir, currentHash)\n\n\treturn { entries, outDir }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,MAAMA,kBAA0C;CAC/C,MAAM;CACN,SAAS;CACT,QAAQ;CACR;AAuBD,SAAS,qBAAqB,QAAiC,QAAoD;AAClH,QAAO;EACN,QAAQ,OAAO;EACf,QAAQ,OAAO,UAAU,OAAO,UAAU;EAC1C,iBAAiB,OAAO,mBAAmB,OAAO,mBAAmB;EACrE,gBAAgB,OAAO,kBAAkB,OAAO,kBAAkB;EAClE,QAAQ,OAAO,UAAU,EAAE;EAC3B,UAAU,OAAO,YAAY,EAAE;EAC/B;;AAGF,SAAS,iBAAiB,QAAwB;AACjD,QAAO,eAAe,OAAO;;AAc9B,SAAS,iBACR,QACA,WACA,sBACA,WACS;CACT,MAAM,aAAa,UAAU,KAAI,QAAO,IAAI,WAAW,CAAC,KAAK,KAAK;CAElE,MAAM,UAAU,0BAA0B;EACzC,MAAM;EACN;EAC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AG,UAAU;CAE3D,MAAM,aAAa,QAAQ,SAAQ,MAAK,EAAE,UAAU;CACpD,MAAM,oBAAoB,cAAc,KAAI,UAAS,EACpD,YAAY,YAAY,IAAI,KAAK,EACjC,EAAE;CAEH,MAAM,cAAc,iBAAiB,YAAY,kBAAkB;AAEnE,OAAM,UADY,QAAQ,QAAQ,aAAa,EACpB,aAAa,QAAQ;AAIhD,OAAM,oBAAoB;EACzB,aAAa,QAAQ,KAAK;EAC1B,SAAS;EACT,WAAW;EACX,CAAC;AAEF,OAAM,eAAe,QAAQ,YAAY;AAEzC,QAAO;EAAE;EAAS;EAAQ"}
|
|
1
|
+
{"version":3,"file":"generate-entry.mjs","names":["TARGET_SUFFIXES: Record<Target, string>","assetMode: AssetMode","compiledDocuments: EntryDocument[]","init: EntryDocument['init']","urlMap: Record<string, string>","rm"],"sources":["../../../../src/server/integrations/nextjs/generate-entry.ts"],"sourcesContent":["import type { FormatConfig } from '../../../shared/types'\nimport type { AssetMode, Target } from '../../../shared/types/public/compile'\nimport type { FormatNextPluginOptions, FormatTargetOptions } from '../../../shared/types/public/nextjs'\nimport type { DocumentAssetState } from '../../compile/compile'\n\nimport { resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { mkdir, readdir, readFile, writeFile } from 'node:fs/promises'\nimport { listZipEntries } from '@format.dev/zip'\nimport { compileForUnplugin } from '../../compile/compile'\nimport { getBundleOutDir } from '../../compile/compile'\nimport { getDocuments } from '../../project/documents'\nimport { getDocumentsDir } from '../../project/paths'\nimport { buildDocumentExportMap } from '@format.dev/cli/scaffold'\nimport { resolveBundleName } from '../../compile/bundle-name'\nimport { BUNDLE_ENTRY_POINT_FILE_NAME } from '../../compile/constants'\nimport { computeCacheHash, readCachedHash, writeCacheHash } from '../../compile/compile-cache'\nimport { dynamicAssetEmitEntries } from '../../compile/document-assets'\nimport { buildWrapperFactorySource } from '../../compile/wrapper-source'\nimport { resolveZipModulePath } from '../../compile/make-config'\nimport { writeFormatEnvTypes } from '../../project/format-env-types'\nimport { logger, withPrefixedConsole } from '../../utils/log'\n\nconst TARGET_SUFFIXES: Record<Target, string> = {\n\tnode: '/node',\n\tbrowser: '/browser',\n\tworker: '/edge'\n}\n\ninterface ResolvedTargetOptions {\n\ttarget: Target\n\tassets: AssetMode | null\n\tinlineRemoteCss: boolean\n\tvalidateSchema: boolean\n\tbundle: string[]\n\texternal: string[]\n}\n\ninterface TargetEntry {\n\ttarget: Target\n\tsuffix: string\n\taliasKeys: string[]\n\tentryPath: string\n}\n\nexport interface GenerateEntryResult {\n\tentries: TargetEntry[]\n\toutDir: string\n}\n\nfunction resolveTargetOptions(shared: FormatNextPluginOptions, target: FormatTargetOptions): ResolvedTargetOptions {\n\treturn {\n\t\ttarget: target.target,\n\t\tassets: target.assets ?? shared.assets ?? null,\n\t\tinlineRemoteCss: target.inlineRemoteCss ?? shared.inlineRemoteCss ?? false,\n\t\tvalidateSchema: target.validateSchema ?? shared.validateSchema ?? true,\n\t\tbundle: target.bundle ?? [],\n\t\texternal: target.external ?? []\n\t}\n}\n\nfunction getEntryFileName(target: Target): string {\n\treturn `_next-entry-${target}.js`\n}\n\ninterface EntryDocument {\n\tdocumentName: string\n\texportName: string\n\tinit: {\n\t\tknownAssets: string[]\n\t\tassetUrls: Record<string, string> | null\n\t\tassetsPath: string | null\n\t\tassetsUrl: string | null\n\t}\n}\n\nfunction buildEntrySource(\n\ttarget: Target,\n\tassetMode: AssetMode,\n\trendererRelativePath: string,\n\tdocuments: EntryDocument[]\n): string {\n\tconst exportList = documents.map(doc => doc.exportName).join(', ')\n\n\tconst factory = buildWrapperFactorySource({\n\t\tmode: assetMode,\n\t\ttarget,\n\t\tzipModulePath: resolveZipModulePath(assetMode)\n\t})\n\n\tconst wrapperLines = documents.map(\n\t\tdoc =>\n\t\t\t`const ${doc.exportName} = createRendererWrapper(${JSON.stringify(doc.documentName)}, resolveRenderer(${JSON.stringify(doc.exportName)}), ${JSON.stringify(doc.init)});`\n\t)\n\n\treturn [\n\t\t`import * as rendererModule from ${JSON.stringify(rendererRelativePath)};`,\n\t\tfactory,\n\t\t[\n\t\t\t`function resolveRenderer(name) {`,\n\t\t\t`\tconst renderer = rendererModule?.[name] ?? rendererModule?.default?.[name] ?? rendererModule?.default?.default?.[name];`,\n\t\t\t`\tif (!renderer) {`,\n\t\t\t`\t\tthrow new Error('Renderer export \"' + name + '\" not found');`,\n\t\t\t`\t}`,\n\t\t\t`\treturn renderer;`,\n\t\t\t`}`\n\t\t].join('\\n'),\n\t\twrapperLines.join('\\n'),\n\t\t`export { ${exportList} };`,\n\t\t`export default { ${exportList} };`,\n\t\t''\n\t].join('\\n\\n')\n}\n\nfunction buildTypesSourceForModule(moduleAlias: string, documents: Array<{ exportName: string }>): string {\n\tconst exportNames = documents.map(doc => doc.exportName)\n\n\tconst namedExports = exportNames.map(name => `\\texport const ${name}: FormatRenderer`).join('\\n')\n\n\tconst defaultShape = exportNames.map(name => `${name}: FormatRenderer`).join('; ')\n\n\treturn [\n\t\t`declare module '${moduleAlias}' {`,\n\t\t'\\tinterface FormatAssetConfig {',\n\t\t'\\t\\tgetAssetsUrl(): string | undefined',\n\t\t'\\t\\tsetAssetsUrl(url: string): void',\n\t\t'\\t}',\n\t\t'',\n\t\t'\\tinterface FormatDocument {',\n\t\t'\\t\\thtml: string',\n\t\t'\\t\\tgetAssetsWebStream(): Promise<ReadableStream<Uint8Array> | undefined>',\n\t\t'\\t}',\n\t\t'',\n\t\t'\\tinterface FormatRenderer extends FormatAssetConfig {',\n\t\t'\\t\\trender(data?: Record<string, unknown>): Promise<FormatDocument>',\n\t\t'\\t\\tgetAssetsWebStream(): Promise<ReadableStream<Uint8Array> | undefined>',\n\t\t'\\t}',\n\t\t'',\n\t\tnamedExports,\n\t\t'',\n\t\t`\\tconst renderers: { ${defaultShape}; [key: string]: FormatRenderer }`,\n\t\t'\\texport default renderers',\n\t\t'}'\n\t].join('\\n')\n}\n\nfunction buildTypesSource(aliases: string[], documents: Array<{ exportName: string }>): string {\n\tconst modules = aliases.map(alias => buildTypesSourceForModule(alias, documents)).join('\\n\\n')\n\n\treturn `// Auto-generated by Format Studio — do not edit\\n${modules}\\n`\n}\n\nfunction patchReactDomServerImports(source: string): string {\n\tlet patched = source\n\n\tpatched = patched.replace(\n\t\t/import\\s*\\{([^}]+)\\}\\s*from\\s*[\"']react-dom\\/server[\"']\\s*;?/g,\n\t\t'const {$1} = await import(\"react-dom/server\");'\n\t)\n\n\tpatched = patched.replace(\n\t\t/import\\s*\\*\\s*as\\s+(\\w+)\\s+from\\s*[\"']react-dom\\/server[\"']\\s*;?/g,\n\t\t'const $1 = await import(\"react-dom/server\");'\n\t)\n\n\tpatched = patched.replace(\n\t\t/import\\s+(\\w+)\\s+from\\s*[\"']react-dom\\/server[\"']\\s*;?/g,\n\t\t'const { default: $1 } = await import(\"react-dom/server\");'\n\t)\n\n\treturn patched\n}\n\nasync function patchFile(filePath: string): Promise<void> {\n\tconst content = await readFile(filePath, 'utf-8')\n\tconst patched = patchReactDomServerImports(content)\n\n\tif (patched !== content) {\n\t\tawait writeFile(filePath, patched, 'utf-8')\n\t\tlogger.debug(`Patched react-dom/server imports in ${filePath}`)\n\t}\n}\n\nasync function patchCompiledBundles(outDir: string, documentNames: string[]): Promise<void> {\n\tfor (const documentName of documentNames) {\n\t\tawait patchFile(resolve(outDir, documentName, BUNDLE_ENTRY_POINT_FILE_NAME))\n\t}\n\n\t// Shared chunks can also contain react-dom/server imports (e.g. the engine chunk)\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 patchFile(resolve(chunksDir, file))\n\t\t}\n\t}\n}\n\nasync function compileTarget(\n\ttargetConfig: FormatTargetOptions,\n\toptions: FormatNextPluginOptions,\n\tconfig: FormatConfig,\n\toutDir: string,\n\tbundleName: string,\n\tdocumentNames: string[],\n\texportNames: Map<string, string>\n): Promise<TargetEntry> {\n\tconst resolved = resolveTargetOptions(options, targetConfig)\n\tconst suffix = TARGET_SUFFIXES[resolved.target]\n\tconst suffixedAlias = `@format:${bundleName}${suffix}`\n\tconst targetOutDir = resolve(outDir, resolved.target)\n\tconst assetMode: AssetMode = resolved.assets ?? 'static'\n\n\tlogger.info(`Compiling ${resolved.target} bundle. Documents: ${documentNames.join(', ')}`)\n\n\tconst assetState = new Map<string, DocumentAssetState>()\n\tawait compileForUnplugin(\n\t\t{\n\t\t\tdocuments: documentNames,\n\t\t\tassets: resolved.assets,\n\t\t\tvalidateSchema: resolved.validateSchema,\n\t\t\tinlineRemoteCss: resolved.inlineRemoteCss,\n\t\t\tbundle: resolved.bundle,\n\t\t\texternal: resolved.external,\n\t\t\ttarget: resolved.target,\n\t\t\tconfigPath: options.configPath,\n\t\t\toutDir: targetOutDir,\n\t\t\tbundleName,\n\t\t\tclean: false,\n\t\t\tuserBundler: 'webpack'\n\t\t},\n\t\t{ capturedAssetState: assetState }\n\t)\n\n\tawait patchCompiledBundles(targetOutDir, documentNames)\n\n\t// The generated entry lives outside the compiled outDir and is re-bundled\n\t// by Next.js, so all asset locations are baked as absolute file:// URLs.\n\t// Browser/edge consumers point at hosted assets with setAssetsUrl().\n\tconst compiledDocuments: EntryDocument[] = []\n\n\tfor (const name of documentNames) {\n\t\tconst init: EntryDocument['init'] = { knownAssets: [], assetUrls: null, assetsPath: null, assetsUrl: null }\n\n\t\tif (assetMode === 'static') {\n\t\t\tconst zipPath = resolve(targetOutDir, name, 'assets.zip')\n\t\t\tconst zipBuffer = await readFile(zipPath).catch(() => null)\n\n\t\t\tif (zipBuffer) {\n\t\t\t\tinit.knownAssets = listZipEntries(new Uint8Array(zipBuffer))\n\t\t\t\tinit.assetsUrl = pathToFileURL(zipPath).href\n\t\t\t}\n\t\t} else if (assetMode === 'dynamic') {\n\t\t\tconst compiledUrlMap = assetState.get(name)?.urlMap ?? {}\n\t\t\tconst entries = dynamicAssetEmitEntries({\n\t\t\t\toutDir: targetOutDir,\n\t\t\t\tdocumentName: name,\n\t\t\t\turlMap: compiledUrlMap\n\t\t\t})\n\n\t\t\tconst urlMap: Record<string, string> = {}\n\t\t\tfor (const entry of entries) {\n\t\t\t\turlMap[entry.knownPath] = pathToFileURL(entry.sourcePath).href\n\t\t\t}\n\n\t\t\tinit.assetUrls = urlMap\n\t\t\tinit.knownAssets = Object.keys(urlMap).sort()\n\t\t}\n\n\t\tcompiledDocuments.push({ documentName: name, exportName: exportNames.get(name)!, init })\n\t}\n\n\tconst entryFileName = getEntryFileName(resolved.target)\n\tconst rendererRelativePath = `./${resolved.target}/${BUNDLE_ENTRY_POINT_FILE_NAME}`\n\tconst entrySource = buildEntrySource(resolved.target, assetMode, rendererRelativePath, compiledDocuments)\n\tconst entryPath = resolve(outDir, entryFileName)\n\tawait writeFile(entryPath, entrySource, 'utf-8')\n\n\tlogger.debug(`Generated Next.js entry module for ${resolved.target} at ${entryPath}`)\n\n\treturn { target: resolved.target, suffix, aliasKeys: [suffixedAlias], entryPath }\n}\n\nexport async function generateEntry(\n\tconfig: FormatConfig,\n\toptions: FormatNextPluginOptions\n): Promise<GenerateEntryResult> {\n\tconst bundleName = resolveBundleName(options.bundleName)\n\tconst outDir = getBundleOutDir(config, options.outDir)\n\tconst targets = options.targets ?? [{ target: 'node' }]\n\n\tconst documents = await getDocuments(config)\n\tconst documentNames = documents.map(doc => doc.name).sort((a, b) => a.localeCompare(b))\n\n\tif (documentNames.length === 0) {\n\t\tthrow new Error('No documents found to compile.')\n\t}\n\n\tconst exportNames = buildDocumentExportMap(documentNames)\n\n\t// Check cache — skip compilation if documents + options haven't changed\n\tconst documentsDir = getDocumentsDir(config)\n\tconst currentHash = await computeCacheHash(documentsDir, options)\n\tconst cachedHash = await readCachedHash(outDir)\n\n\tif (cachedHash === currentHash) {\n\t\tlogger.info('Cache hit. Skipping compile.')\n\n\t\tconst entries: TargetEntry[] = targets.map((targetConfig, index) => {\n\t\t\tconst resolved = resolveTargetOptions(options, targetConfig)\n\t\t\tconst suffix = TARGET_SUFFIXES[resolved.target]\n\t\t\tconst suffixedAlias = `@format:${bundleName}${suffix}`\n\t\t\tconst entryFileName = getEntryFileName(resolved.target)\n\t\t\tconst entryPath = resolve(outDir, entryFileName)\n\n\t\t\tconst aliasKeys = index === 0 ? [`@format:${bundleName}`, suffixedAlias] : [suffixedAlias]\n\n\t\t\treturn { target: resolved.target, suffix, aliasKeys, entryPath }\n\t\t})\n\n\t\treturn { entries, outDir }\n\t}\n\n\tlogger.debug(`Cache miss. Compiling ${targets.length} target(s)`)\n\n\tif (options.clean !== false) {\n\t\tconst { rm } = await import('node:fs/promises')\n\t\tawait rm(outDir, { recursive: true, force: true }).catch(() => {})\n\t}\n\n\tawait mkdir(outDir, { recursive: true })\n\n\tconst suppressRolldownLogs = (_level: string, ...args: unknown[]) => {\n\t\tconst msg = args.join(' ')\n\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\t// Compile all targets in parallel, suppressing rolldown's stdout noise\n\tconst entries = (await withPrefixedConsole(\n\t\t() =>\n\t\t\tPromise.all(\n\t\t\t\ttargets.map(targetConfig =>\n\t\t\t\t\tcompileTarget(targetConfig, options, config, outDir, bundleName, documentNames, exportNames)\n\t\t\t\t)\n\t\t\t),\n\t\tsuppressRolldownLogs\n\t)) as TargetEntry[]\n\n\t// First target also gets the base alias (format:<bundleName>)\n\tconst baseAlias = `@format:${bundleName}`\n\tentries[0].aliasKeys = [baseAlias, ...entries[0].aliasKeys]\n\n\tconst allAliases = entries.flatMap(e => e.aliasKeys)\n\tconst documentsForTypes = documentNames.map(name => ({\n\t\texportName: exportNames.get(name)!\n\t}))\n\n\tconst typesSource = buildTypesSource(allAliases, documentsForTypes)\n\tconst typesPath = resolve(outDir, 'types.d.ts')\n\tawait writeFile(typesPath, typesSource, 'utf-8')\n\n\t// Write the project's format-env.d.ts — the same file init seeds and every\n\t// bundler plugin regenerates, so document imports are strongly typed.\n\tawait writeFormatEnvTypes({\n\t\tprojectRoot: process.cwd(),\n\t\taliases: allAliases,\n\t\tdocuments: documentsForTypes\n\t})\n\n\tawait writeCacheHash(outDir, currentHash)\n\n\treturn { entries, outDir }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,MAAMA,kBAA0C;CAC/C,MAAM;CACN,SAAS;CACT,QAAQ;CACR;AAuBD,SAAS,qBAAqB,QAAiC,QAAoD;AAClH,QAAO;EACN,QAAQ,OAAO;EACf,QAAQ,OAAO,UAAU,OAAO,UAAU;EAC1C,iBAAiB,OAAO,mBAAmB,OAAO,mBAAmB;EACrE,gBAAgB,OAAO,kBAAkB,OAAO,kBAAkB;EAClE,QAAQ,OAAO,UAAU,EAAE;EAC3B,UAAU,OAAO,YAAY,EAAE;EAC/B;;AAGF,SAAS,iBAAiB,QAAwB;AACjD,QAAO,eAAe,OAAO;;AAc9B,SAAS,iBACR,QACA,WACA,sBACA,WACS;CACT,MAAM,aAAa,UAAU,KAAI,QAAO,IAAI,WAAW,CAAC,KAAK,KAAK;CAElE,MAAM,UAAU,0BAA0B;EACzC,MAAM;EACN;EACA,eAAe,qBAAqB,UAAU;EAC9C,CAAC;CAEF,MAAM,eAAe,UAAU,KAC9B,QACC,SAAS,IAAI,WAAW,2BAA2B,KAAK,UAAU,IAAI,aAAa,CAAC,oBAAoB,KAAK,UAAU,IAAI,WAAW,CAAC,KAAK,KAAK,UAAU,IAAI,KAAK,CAAC,IACtK;AAED,QAAO;EACN,mCAAmC,KAAK,UAAU,qBAAqB,CAAC;EACxE;EACA;GACC;GACA;GACA;GACA;GACA;GACA;GACA;GACA,CAAC,KAAK,KAAK;EACZ,aAAa,KAAK,KAAK;EACvB,YAAY,WAAW;EACvB,oBAAoB,WAAW;EAC/B;EACA,CAAC,KAAK,OAAO;;AAGf,SAAS,0BAA0B,aAAqB,WAAkD;CACzG,MAAM,cAAc,UAAU,KAAI,QAAO,IAAI,W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|
import { FormatUnpluginOptions } from "../../../shared/types/public/unplugin.mjs";
|
|
4
4
|
import { DocumentAssetState } from "../../compile/compile.mjs";
|
|
5
|
-
import * as
|
|
5
|
+
import * as vite5 from "vite";
|
|
6
6
|
import * as unplugin0 from "unplugin";
|
|
7
7
|
|
|
8
8
|
//#region src/server/integrations/unplugin/index.d.ts
|
|
@@ -59,7 +59,7 @@ interface BuildVirtualModuleArgs {
|
|
|
59
59
|
}
|
|
60
60
|
declare function buildVirtualModuleCode(args: BuildVirtualModuleArgs): Promise<string | null>;
|
|
61
61
|
declare const universalBundlerPlugin: unplugin0.UnpluginInstance<FormatUnpluginOptions, boolean>;
|
|
62
|
-
declare const formatVitePlugin: (options: FormatUnpluginOptions) =>
|
|
62
|
+
declare const formatVitePlugin: (options: FormatUnpluginOptions) => vite5.Plugin<any> | vite5.Plugin<any>[];
|
|
63
63
|
declare const formatRollupPlugin: (options: FormatUnpluginOptions) => any;
|
|
64
64
|
declare const formatRolldownPlugin: (options: FormatUnpluginOptions) => any;
|
|
65
65
|
declare const formatWebpackPlugin: (options: FormatUnpluginOptions) => WebpackPluginInstance;
|
|
@@ -39,7 +39,7 @@ async function handleDevInit(request) {
|
|
|
39
39
|
devServer = await createServer(mergeConfig(baseViteConfig, {
|
|
40
40
|
configFile: false,
|
|
41
41
|
clearScreen: false,
|
|
42
|
-
|
|
42
|
+
envDir: false,
|
|
43
43
|
cacheDir: join(tmpdir(), "format-vite-cache"),
|
|
44
44
|
logLevel: "info",
|
|
45
45
|
customLogger: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.mjs","names":["devServer: ViteDevServer | null","frameworkAdaptors: Record<string, () => Promise<any>>","userModule: any"],"sources":["../../../src/server/render-worker/host.ts"],"sourcesContent":["/**\n * Render worker host — runs in a forked child process.\n *\n * Handles two execution paths:\n * 1. compile-render: imports a pre-built bundle, calls its render()\n * 2. dev-render: runs a headless Vite dev server with ssrLoadModule()\n * so all plugins (Vue SFC, Linaria, Vanilla Extract, etc.) work\n * with transforms and evaluation in the same process\n *\n * This process runs with a scrubbed environment (see env.ts), so user\n * code cannot access the parent process's secrets.\n */\n\nimport type { WorkerRequest, WorkerResponse, CompileRenderRequest, DevRenderRequest, DevInitRequest } from './types'\nimport type { ViteDevServer } from 'vite'\n\nimport { serializeError } from './error'\nimport { pathToFileURL } from 'node:url'\nimport { getDocumentExportName } from '@format.dev/cli/scaffold'\nimport { formatForLog } from '../utils/format-for-log'\nimport { finalizeDocumentHtml, restampDocumentEngine } from '../compile/finalize-document-html'\nimport { engineTarget, sdkVersion } from '../compile/producer-release'\nimport { applySandboxPatches } from './sandbox'\nimport { collectDocumentCss, invalidateModuleTree } from './document-css'\n\n// Apply JS-level API patches (network, child_process) before any user code\n// runs. In 'strict' mode, Node's --experimental-permission handles this\n// at the runtime level instead.\nif (process.env.FMT_SANDBOX_MODE === 'standard') {\n\tapplySandboxPatches()\n}\n\nasync function handleCompileRender(request: CompileRenderRequest): Promise<string> {\n\tconst { bundlePath, documentName, data, cwd } = request\n\n\t// Dynamic import with cache buster — same strategy as get-renderer.ts\n\tconst url = new URL(pathToFileURL(bundlePath).href)\n\turl.search = `?t=${Date.now()}-${Math.random().toString(36).slice(2)}`\n\n\tconst bundle = await import(url.href)\n\n\t// Resolve the named export (same logic as resolveRenderer in get-renderer.ts)\n\tconst exportName = getDocumentExportName(documentName)\n\n\tconst renderer = bundle?.[exportName] ?? bundle?.default?.[exportName] ?? bundle?.default?.default?.[exportName]\n\n\tif (!renderer) {\n\t\tthrow new Error(`Renderer export \"${exportName}\" not found for document \"${documentName}\"`)\n\t}\n\n\tconst result = await renderer.render(data || {}, cwd)\n\n\t// The CLI-compiled wrapper returns a FormatDocument object while the inner renderer\n\t// returns a plain string. Extract FormatDocument.html for IPC serialization.\n\treturn typeof result === 'object' && result !== null && 'html' in result ? result.html : result\n}\n\nlet devServer: ViteDevServer | null = null\nlet devDecodeStyleEntities = false\n\nasync function handleDevInit(request: DevInitRequest): Promise<void> {\n\tconst { root, configJson, decodeStyleEntities: decode } = request\n\n\tdevDecodeStyleEntities = decode === true\n\n\t// Hydrate runtime state so createConfig() and adaptors work\n\tconst { setUserProjectDir } = await import('../project/user-project-dir')\n\tsetUserProjectDir(root)\n\n\tconst { compileState } = await import('../runtime-state')\n\tcompileState.setConfig(JSON.parse(configJson))\n\n\t// Build Vite config using the same factory as the main server\n\tconst { createConfig } = await import('../vite/create-config')\n\tconst { collectCssPlugin } = await import('../vite/plugins/collect-css')\n\tconst { stylesPreProcessor } = await import('../vite/plugins/styles-pre-processor')\n\n\tconst { baseViteConfig, frameworkPlugins, stylePlugins } = createConfig()\n\n\tconst { createServer, mergeConfig } = await import('vite')\n\n\tconst { join } = await import('node:path')\n\tconst { tmpdir } = await import('node:os')\n\n\tconst workerLogger = {\n\t\tinfo: (msg: string) => console.log(msg),\n\t\twarn: (msg: string) => console.warn(msg),\n\t\terror: () => {},\n\t\twarnOnce: (msg: string) => console.warn(msg),\n\t\thasWarned: false,\n\t\tclearScreen: () => {},\n\t\thasErrorLogged: () => false\n\t}\n\n\tconst serverConfig = mergeConfig(baseViteConfig, {\n\t\tconfigFile: false,\n\t\tclearScreen: false,\n\t\tenvFile: false, // Block .env file loading — primary .env protection\n\t\tcacheDir: join(tmpdir(), 'format-vite-cache'),\n\t\tlogLevel: 'info',\n\t\tcustomLogger: workerLogger,\n\t\tserver: {\n\t\t\tmiddlewareMode: true,\n\t\t\twatch: null // No file watching — main server handles HMR\n\t\t},\n\t\tplugins: [await stylesPreProcessor(false), ...frameworkPlugins, ...stylePlugins, collectCssPlugin()],\n\t\tresolve: {\n\t\t\t// Force framework packages to resolve from the user's project\n\t\t\t// (Vite root) rather than from workspace packages like\n\t\t\t// @format.dev/react or @format.dev/vue, which may resolve to a different\n\t\t\t// version at the workspace root.\n\t\t\tdedupe: ['react', 'react-dom', 'vue', 'vue/server-renderer']\n\t\t},\n\t\tssr: {\n\t\t\t// We externalize third-party node_modules to Node's own loader,\n\t\t\t// which is the only path that handles CommonJS packages. Inlining\n\t\t\t// CJS into Vite's ESM module runner throws \"module is not defined\"\n\t\t\t// (its entry has no `module` global), so a document importing any\n\t\t\t// CJS-only library — highlight.js, and thousands like it — would\n\t\t\t// otherwise crash the render.\n\t\t\t//\n\t\t\t// noExternal as an array keeps Vite's default of auto-bundling\n\t\t\t// linked workspace packages and adds @format.dev/* on top, so our SDK\n\t\t\t// is always bundled (even when installed from npm, not symlinked).\n\t\t\t// Bundling routes its react/vue imports through resolve.dedupe\n\t\t\t// below, giving the user's single framework instance and avoiding\n\t\t\t// the dual-instance crashes that a blanket noExternal was added for.\n\t\t\t//\n\t\t\t// react/react-dom and vue/vue-server-renderer stay external\n\t\t\t// because their entry files are CJS (module.exports) which fails\n\t\t\t// in Vite's ESM evaluator. The adaptors manually load them from\n\t\t\t// the user's project via createRequire.\n\t\t\tnoExternal: [/@format(?:\\.dev)?\\//],\n\t\t\texternal: ['react', 'react-dom', 'vue', 'vue/server-renderer']\n\t\t},\n\t\toptimizeDeps: {\n\t\t\tnoDiscovery: true,\n\t\t\tentries: false\n\t\t}\n\t})\n\n\tdevServer = await createServer(serverConfig)\n}\n\nconst frameworkAdaptors: Record<string, () => Promise<any>> = {\n\treact: () => import('../compile/adaptors/react-node'),\n\tvue: () => import('../compile/adaptors/vue-node'),\n\thtml: () => import('../compile/adaptors/html')\n}\n\nasync function handleDevRender(request: DevRenderRequest): Promise<{ html: string }> {\n\tif (!devServer) {\n\t\tthrow new Error('Dev server not initialized. Send a dev-init message first.')\n\t}\n\n\tconst { entryFilePath, data, framework, engineVersion } = request\n\tconst { compileState } = await import('../runtime-state')\n\tconst { decodeStyleEntities } = await import('../compile/decode-style-entities')\n\n\tconsole.log(`Render started (framework=${framework}, engine=${engineVersion})`)\n\n\t// Look the entry up by URL, the same way ssrLoadModule resolves it, so\n\t// invalidation and CSS collection find the module that was loaded.\n\tconst { moduleGraph } = devServer.environments.ssr\n\n\tinvalidateModuleTree({\n\t\tentry: await moduleGraph.getModuleByUrl(entryFilePath),\n\t\tinvalidate: module => moduleGraph.invalidateModule(module)\n\t})\n\n\tconst userModule: any = await devServer.ssrLoadModule(entryFilePath)\n\n\tif (!userModule?.default) {\n\t\tthrow new Error(`Entry module does not export a default export: ${entryFilePath}`)\n\t}\n\n\tconst Component = userModule.default\n\tconst mod = await frameworkAdaptors[framework]()\n\tconst adaptor = mod.default\n\tconst { create, render } = adaptor\n\n\t// Resolve react/react-dom (and vue) from the user's project — the same\n\t// root Vite uses to resolve the document's jsx-runtime. Without this the\n\t// adaptor falls back to process.cwd(), which can resolve a different\n\t// framework copy: the document's elements would be created by one React\n\t// and rendered by another (\"Objects are not valid as a React child\").\n\tconst { getUserProjectDir } = await import('../project/user-project-dir')\n\tconst cwd = getUserProjectDir()\n\n\tconst element = await create({ Component, data, cwd })\n\tconst rawHtml = await render({ element: element as any, engine: engineVersion, cwd })\n\n\t// Stamp the producing release and inject the collected CSS as a document-level\n\t// <style>, in one parse. Empty payloads emit no tag (see finalize-document-html).\n\tconst combinedStyles = collectDocumentCss({\n\t\tentry: await moduleGraph.getModuleByUrl(entryFilePath),\n\t\tcss: compileState.getCss()\n\t})\n\n\t// This build's own two numbers, so an SDK rendering from a different release\n\t// fails here rather than having its output relabelled.\n\tlet finalHtml = finalizeDocumentHtml({\n\t\thtml: rawHtml,\n\t\tsdk: sdkVersion,\n\t\tengine: engineTarget,\n\t\tcss: combinedStyles\n\t})\n\n\t// Then the engine Studio actually resolved, which is the released target\n\t// unless FMT_ENGINE_VERSION pinned a local build. Written separately because\n\t// a locally pinned engine is not a different producing release: it changes\n\t// which engine lays the preview out and nothing about what produced it.\n\tfinalHtml = restampDocumentEngine(finalHtml, engineVersion)\n\n\tif (devDecodeStyleEntities) {\n\t\tfinalHtml = decodeStyleEntities(finalHtml)\n\t}\n\n\tconst isDebug = process.env.FORMAT_DEBUG === '1' || process.env.FORMAT_DEBUG === 'true'\n\n\tif (isDebug) {\n\t\tconst stylesLog = await formatForLog(combinedStyles, 'css')\n\t\tconst htmlLog = await formatForLog(finalHtml, 'html')\n\n\t\tconsole.log('Final styles\\n', `<style>\\n${stylesLog}</style>`)\n\t\t// This is the raw render output; the dev-server middleware sanitizes it afterwards\n\t\t// and logs the post-sanitize result as \"Final HTML (post-sanitize)\".\n\t\tconsole.log('Rendered HTML (pre-sanitize)\\n', htmlLog)\n\t}\n\n\treturn { html: finalHtml }\n}\n\nfunction reply(msg: WorkerResponse) {\n\tprocess.send!(msg)\n}\n\nprocess.on('message', async (msg: any) => {\n\tconst request = msg as WorkerRequest\n\ttry {\n\t\tswitch (request.type) {\n\t\t\tcase 'compile-render': {\n\t\t\t\tconst html = await handleCompileRender(request)\n\t\t\t\treply({ id: request.id, type: 'render-result', html })\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'dev-init': {\n\t\t\t\tawait handleDevInit(request)\n\t\t\t\treply({ id: request.id, type: 'dev-init-result' })\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'dev-render': {\n\t\t\t\tconst result = await handleDevRender(request)\n\t\t\t\treply({ id: request.id, type: 'render-result', html: result.html })\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\treply({\n\t\t\tid: request.id,\n\t\t\ttype: 'render-error',\n\t\t\terror: serializeError(error)\n\t\t})\n\t}\n})\n\n// Signal readiness to the parent process\nreply({ type: 'ready' } as WorkerResponse)\n"],"mappings":";;;;;;;;;;AA4BA,IAAI,QAAQ,IAAI,qBAAqB,WACpC,sBAAqB;AAGtB,eAAe,oBAAoB,SAAgD;CAClF,MAAM,EAAE,YAAY,cAAc,MAAM,QAAQ;CAGhD,MAAM,MAAM,IAAI,IAAI,cAAc,WAAW,CAAC,KAAK;AACnD,KAAI,SAAS,MAAM,KAAK,KAAK,CAAC,GAAG,KAAK,QAAQ,CAAC,SAAS,GAAG,CAAC,MAAM,EAAE;CAEpE,MAAM,SAAS,MAAM,OAAO,IAAI;CAGhC,MAAM,a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Q;EAC1B,CAAC;CAIF,IAAI,YAAY,qBAAqB;EACpC,MAAM;EACN,KAAK;EACL,QAAQ;EACR,KAAK;EACL,CAAC;AAMF,aAAY,sBAAsB,WAAW,cAAc;AAE3D,KAAI,uBACH,aAAY,oBAAoB,UAAU;AAK3C,KAFgB,QAAQ,IAAI,iBAAiB,OAAO,QAAQ,IAAI,iBAAiB,QAEpE;EACZ,MAAM,YAAY,MAAM,aAAa,gBAAgB,MAAM;EAC3D,MAAM,UAAU,MAAM,aAAa,WAAW,OAAO;AAErD,UAAQ,IAAI,kBAAkB,YAAY,UAAU,UAAU;AAG9D,UAAQ,IAAI,kCAAkC,QAAQ;;AAGvD,QAAO,EAAE,MAAM,WAAW;;AAG3B,SAAS,MAAM,KAAqB;AACnC,SAAQ,KAAM,IAAI;;AAGnB,QAAQ,GAAG,WAAW,OAAO,QAAa;CACzC,MAAM,UAAU;AAChB,KAAI;AACH,UAAQ,QAAQ,MAAhB;GACC,KAAK,kBAAkB;IACtB,MAAM,OAAO,MAAM,oBAAoB,QAAQ;AAC/C,UAAM;KAAE,IAAI,QAAQ;KAAI,MAAM;KAAiB;KAAM,CAAC;AACtD;;GAGD,KAAK;AACJ,UAAM,cAAc,QAAQ;AAC5B,UAAM;KAAE,IAAI,QAAQ;KAAI,MAAM;KAAmB,CAAC;AAClD;GAGD,KAAK,cAAc;IAClB,MAAM,SAAS,MAAM,gBAAgB,QAAQ;AAC7C,UAAM;KAAE,IAAI,QAAQ;KAAI,MAAM;KAAiB,MAAM,OAAO;KAAM,CAAC;AACnE;;;UAGM,OAAO;AACf,QAAM;GACL,IAAI,QAAQ;GACZ,MAAM;GACN,OAAO,eAAe,MAAM;GAC5B,CAAC;;EAEF;AAGF,MAAM,EAAE,MAAM,SAAS,CAAmB"}
|
|
1
|
+
{"version":3,"file":"host.mjs","names":["devServer: ViteDevServer | null","frameworkAdaptors: Record<string, () => Promise<any>>","userModule: any"],"sources":["../../../src/server/render-worker/host.ts"],"sourcesContent":["/**\n * Render worker host — runs in a forked child process.\n *\n * Handles two execution paths:\n * 1. compile-render: imports a pre-built bundle, calls its render()\n * 2. dev-render: runs a headless Vite dev server with ssrLoadModule()\n * so all plugins (Vue SFC, Linaria, Vanilla Extract, etc.) work\n * with transforms and evaluation in the same process\n *\n * This process runs with a scrubbed environment (see env.ts), so user\n * code cannot access the parent process's secrets.\n */\n\nimport type { WorkerRequest, WorkerResponse, CompileRenderRequest, DevRenderRequest, DevInitRequest } from './types'\nimport type { ViteDevServer } from 'vite'\n\nimport { serializeError } from './error'\nimport { pathToFileURL } from 'node:url'\nimport { getDocumentExportName } from '@format.dev/cli/scaffold'\nimport { formatForLog } from '../utils/format-for-log'\nimport { finalizeDocumentHtml, restampDocumentEngine } from '../compile/finalize-document-html'\nimport { engineTarget, sdkVersion } from '../compile/producer-release'\nimport { applySandboxPatches } from './sandbox'\nimport { collectDocumentCss, invalidateModuleTree } from './document-css'\n\n// Apply JS-level API patches (network, child_process) before any user code\n// runs. In 'strict' mode, Node's --experimental-permission handles this\n// at the runtime level instead.\nif (process.env.FMT_SANDBOX_MODE === 'standard') {\n\tapplySandboxPatches()\n}\n\nasync function handleCompileRender(request: CompileRenderRequest): Promise<string> {\n\tconst { bundlePath, documentName, data, cwd } = request\n\n\t// Dynamic import with cache buster — same strategy as get-renderer.ts\n\tconst url = new URL(pathToFileURL(bundlePath).href)\n\turl.search = `?t=${Date.now()}-${Math.random().toString(36).slice(2)}`\n\n\tconst bundle = await import(url.href)\n\n\t// Resolve the named export (same logic as resolveRenderer in get-renderer.ts)\n\tconst exportName = getDocumentExportName(documentName)\n\n\tconst renderer = bundle?.[exportName] ?? bundle?.default?.[exportName] ?? bundle?.default?.default?.[exportName]\n\n\tif (!renderer) {\n\t\tthrow new Error(`Renderer export \"${exportName}\" not found for document \"${documentName}\"`)\n\t}\n\n\tconst result = await renderer.render(data || {}, cwd)\n\n\t// The CLI-compiled wrapper returns a FormatDocument object while the inner renderer\n\t// returns a plain string. Extract FormatDocument.html for IPC serialization.\n\treturn typeof result === 'object' && result !== null && 'html' in result ? result.html : result\n}\n\nlet devServer: ViteDevServer | null = null\nlet devDecodeStyleEntities = false\n\nasync function handleDevInit(request: DevInitRequest): Promise<void> {\n\tconst { root, configJson, decodeStyleEntities: decode } = request\n\n\tdevDecodeStyleEntities = decode === true\n\n\t// Hydrate runtime state so createConfig() and adaptors work\n\tconst { setUserProjectDir } = await import('../project/user-project-dir')\n\tsetUserProjectDir(root)\n\n\tconst { compileState } = await import('../runtime-state')\n\tcompileState.setConfig(JSON.parse(configJson))\n\n\t// Build Vite config using the same factory as the main server\n\tconst { createConfig } = await import('../vite/create-config')\n\tconst { collectCssPlugin } = await import('../vite/plugins/collect-css')\n\tconst { stylesPreProcessor } = await import('../vite/plugins/styles-pre-processor')\n\n\tconst { baseViteConfig, frameworkPlugins, stylePlugins } = createConfig()\n\n\tconst { createServer, mergeConfig } = await import('vite')\n\n\tconst { join } = await import('node:path')\n\tconst { tmpdir } = await import('node:os')\n\n\tconst workerLogger = {\n\t\tinfo: (msg: string) => console.log(msg),\n\t\twarn: (msg: string) => console.warn(msg),\n\t\terror: () => {},\n\t\twarnOnce: (msg: string) => console.warn(msg),\n\t\thasWarned: false,\n\t\tclearScreen: () => {},\n\t\thasErrorLogged: () => false\n\t}\n\n\tconst serverConfig = mergeConfig(baseViteConfig, {\n\t\tconfigFile: false,\n\t\tclearScreen: false,\n\t\tenvDir: false, // Block .env file loading — primary .env protection\n\t\tcacheDir: join(tmpdir(), 'format-vite-cache'),\n\t\tlogLevel: 'info',\n\t\tcustomLogger: workerLogger,\n\t\tserver: {\n\t\t\tmiddlewareMode: true,\n\t\t\twatch: null // No file watching — main server handles HMR\n\t\t},\n\t\tplugins: [await stylesPreProcessor(false), ...frameworkPlugins, ...stylePlugins, collectCssPlugin()],\n\t\tresolve: {\n\t\t\t// Force framework packages to resolve from the user's project\n\t\t\t// (Vite root) rather than from workspace packages like\n\t\t\t// @format.dev/react or @format.dev/vue, which may resolve to a different\n\t\t\t// version at the workspace root.\n\t\t\tdedupe: ['react', 'react-dom', 'vue', 'vue/server-renderer']\n\t\t},\n\t\tssr: {\n\t\t\t// We externalize third-party node_modules to Node's own loader,\n\t\t\t// which is the only path that handles CommonJS packages. Inlining\n\t\t\t// CJS into Vite's ESM module runner throws \"module is not defined\"\n\t\t\t// (its entry has no `module` global), so a document importing any\n\t\t\t// CJS-only library — highlight.js, and thousands like it — would\n\t\t\t// otherwise crash the render.\n\t\t\t//\n\t\t\t// noExternal as an array keeps Vite's default of auto-bundling\n\t\t\t// linked workspace packages and adds @format.dev/* on top, so our SDK\n\t\t\t// is always bundled (even when installed from npm, not symlinked).\n\t\t\t// Bundling routes its react/vue imports through resolve.dedupe\n\t\t\t// below, giving the user's single framework instance and avoiding\n\t\t\t// the dual-instance crashes that a blanket noExternal was added for.\n\t\t\t//\n\t\t\t// react/react-dom and vue/vue-server-renderer stay external\n\t\t\t// because their entry files are CJS (module.exports) which fails\n\t\t\t// in Vite's ESM evaluator. The adaptors manually load them from\n\t\t\t// the user's project via createRequire.\n\t\t\tnoExternal: [/@format(?:\\.dev)?\\//],\n\t\t\texternal: ['react', 'react-dom', 'vue', 'vue/server-renderer']\n\t\t},\n\t\toptimizeDeps: {\n\t\t\tnoDiscovery: true,\n\t\t\tentries: false\n\t\t}\n\t})\n\n\tdevServer = await createServer(serverConfig)\n}\n\nconst frameworkAdaptors: Record<string, () => Promise<any>> = {\n\treact: () => import('../compile/adaptors/react-node'),\n\tvue: () => import('../compile/adaptors/vue-node'),\n\thtml: () => import('../compile/adaptors/html')\n}\n\nasync function handleDevRender(request: DevRenderRequest): Promise<{ html: string }> {\n\tif (!devServer) {\n\t\tthrow new Error('Dev server not initialized. Send a dev-init message first.')\n\t}\n\n\tconst { entryFilePath, data, framework, engineVersion } = request\n\tconst { compileState } = await import('../runtime-state')\n\tconst { decodeStyleEntities } = await import('../compile/decode-style-entities')\n\n\tconsole.log(`Render started (framework=${framework}, engine=${engineVersion})`)\n\n\t// Look the entry up by URL, the same way ssrLoadModule resolves it, so\n\t// invalidation and CSS collection find the module that was loaded.\n\tconst { moduleGraph } = devServer.environments.ssr\n\n\tinvalidateModuleTree({\n\t\tentry: await moduleGraph.getModuleByUrl(entryFilePath),\n\t\tinvalidate: module => moduleGraph.invalidateModule(module)\n\t})\n\n\tconst userModule: any = await devServer.ssrLoadModule(entryFilePath)\n\n\tif (!userModule?.default) {\n\t\tthrow new Error(`Entry module does not export a default export: ${entryFilePath}`)\n\t}\n\n\tconst Component = userModule.default\n\tconst mod = await frameworkAdaptors[framework]()\n\tconst adaptor = mod.default\n\tconst { create, render } = adaptor\n\n\t// Resolve react/react-dom (and vue) from the user's project — the same\n\t// root Vite uses to resolve the document's jsx-runtime. Without this the\n\t// adaptor falls back to process.cwd(), which can resolve a different\n\t// framework copy: the document's elements would be created by one React\n\t// and rendered by another (\"Objects are not valid as a React child\").\n\tconst { getUserProjectDir } = await import('../project/user-project-dir')\n\tconst cwd = getUserProjectDir()\n\n\tconst element = await create({ Component, data, cwd })\n\tconst rawHtml = await render({ element: element as any, engine: engineVersion, cwd })\n\n\t// Stamp the producing release and inject the collected CSS as a document-level\n\t// <style>, in one parse. Empty payloads emit no tag (see finalize-document-html).\n\tconst combinedStyles = collectDocumentCss({\n\t\tentry: await moduleGraph.getModuleByUrl(entryFilePath),\n\t\tcss: compileState.getCss()\n\t})\n\n\t// This build's own two numbers, so an SDK rendering from a different release\n\t// fails here rather than having its output relabelled.\n\tlet finalHtml = finalizeDocumentHtml({\n\t\thtml: rawHtml,\n\t\tsdk: sdkVersion,\n\t\tengine: engineTarget,\n\t\tcss: combinedStyles\n\t})\n\n\t// Then the engine Studio actually resolved, which is the released target\n\t// unless FMT_ENGINE_VERSION pinned a local build. Written separately because\n\t// a locally pinned engine is not a different producing release: it changes\n\t// which engine lays the preview out and nothing about what produced it.\n\tfinalHtml = restampDocumentEngine(finalHtml, engineVersion)\n\n\tif (devDecodeStyleEntities) {\n\t\tfinalHtml = decodeStyleEntities(finalHtml)\n\t}\n\n\tconst isDebug = process.env.FORMAT_DEBUG === '1' || process.env.FORMAT_DEBUG === 'true'\n\n\tif (isDebug) {\n\t\tconst stylesLog = await formatForLog(combinedStyles, 'css')\n\t\tconst htmlLog = await formatForLog(finalHtml, 'html')\n\n\t\tconsole.log('Final styles\\n', `<style>\\n${stylesLog}</style>`)\n\t\t// This is the raw render output; the dev-server middleware sanitizes it afterwards\n\t\t// and logs the post-sanitize result as \"Final HTML (post-sanitize)\".\n\t\tconsole.log('Rendered HTML (pre-sanitize)\\n', htmlLog)\n\t}\n\n\treturn { html: finalHtml }\n}\n\nfunction reply(msg: WorkerResponse) {\n\tprocess.send!(msg)\n}\n\nprocess.on('message', async (msg: any) => {\n\tconst request = msg as WorkerRequest\n\ttry {\n\t\tswitch (request.type) {\n\t\t\tcase 'compile-render': {\n\t\t\t\tconst html = await handleCompileRender(request)\n\t\t\t\treply({ id: request.id, type: 'render-result', html })\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'dev-init': {\n\t\t\t\tawait handleDevInit(request)\n\t\t\t\treply({ id: request.id, type: 'dev-init-result' })\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'dev-render': {\n\t\t\t\tconst result = await handleDevRender(request)\n\t\t\t\treply({ id: request.id, type: 'render-result', html: result.html })\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} catch (error) {\n\t\treply({\n\t\t\tid: request.id,\n\t\t\ttype: 'render-error',\n\t\t\terror: serializeError(error)\n\t\t})\n\t}\n})\n\n// Signal readiness to the parent process\nreply({ type: 'ready' } as WorkerResponse)\n"],"mappings":";;;;;;;;;;AA4BA,IAAI,QAAQ,IAAI,qBAAqB,WACpC,sBAAqB;AAGtB,eAAe,oBAAoB,SAAgD;CAClF,MAAM,EAAE,YAAY,cAAc,MAAM,QAAQ;CAGhD,MAAM,MAAM,IAAI,IAAI,cAAc,WAAW,CAAC,KAAK;AACnD,KAAI,SA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AmB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as vite0 from "vite";
|
|
2
2
|
import { LogLevel } from "vite";
|
|
3
3
|
import * as postcss0 from "postcss";
|
|
4
4
|
import autoprefixer from "autoprefixer";
|
|
@@ -19,16 +19,16 @@ declare function createConfig(): {
|
|
|
19
19
|
logLevel: LogLevel;
|
|
20
20
|
customLogger: {
|
|
21
21
|
warn: (msg: string, options?: any) => void;
|
|
22
|
-
info(msg: string, options?:
|
|
23
|
-
warnOnce(msg: string, options?:
|
|
24
|
-
error(msg: string, options?:
|
|
25
|
-
clearScreen(type:
|
|
26
|
-
hasErrorLogged(error: Error | rolldown0.
|
|
22
|
+
info(msg: string, options?: vite0.LogOptions): void;
|
|
23
|
+
warnOnce(msg: string, options?: vite0.LogOptions): void;
|
|
24
|
+
error(msg: string, options?: vite0.LogErrorOptions): void;
|
|
25
|
+
clearScreen(type: vite0.LogType): void;
|
|
26
|
+
hasErrorLogged(error: Error | rolldown0.RolldownError): boolean;
|
|
27
27
|
hasWarned: boolean;
|
|
28
28
|
};
|
|
29
29
|
};
|
|
30
30
|
frameworkPlugins: any[];
|
|
31
|
-
stylePlugins: (
|
|
31
|
+
stylePlugins: (vite0.Plugin<any> | vite0.Plugin<any>[])[];
|
|
32
32
|
};
|
|
33
33
|
//#endregion
|
|
34
34
|
export { createConfig };
|
|
@@ -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;CACpC,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vB,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.2",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Compile Format documents into renderers, without the Studio UI",
|
|
6
6
|
"author": "the format.dev developers",
|
|
@@ -62,8 +62,8 @@
|
|
|
62
62
|
"@babel/preset-react": "^7.28.5",
|
|
63
63
|
"@babel/preset-typescript": "^7.28.5",
|
|
64
64
|
"@standard-schema/spec": "^1.1.0",
|
|
65
|
-
"@tailwindcss/vite": "^4.
|
|
66
|
-
"@vanilla-extract/vite-plugin": "^5.
|
|
65
|
+
"@tailwindcss/vite": "^4.3.3",
|
|
66
|
+
"@vanilla-extract/vite-plugin": "^5.2.6",
|
|
67
67
|
"@vitejs/plugin-vue": "^6.0.3",
|
|
68
68
|
"@vitejs/plugin-vue-jsx": "^5.1.3",
|
|
69
69
|
"@wyw-in-js/vite": "^2.1.0",
|
|
@@ -81,18 +81,18 @@
|
|
|
81
81
|
"rehype-parse": "^9.0.1",
|
|
82
82
|
"rehype-sanitize": "^6.0.0",
|
|
83
83
|
"rehype-stringify": "^10.0.1",
|
|
84
|
-
"rolldown": "1.
|
|
84
|
+
"rolldown": "~1.2.11",
|
|
85
85
|
"sass-embedded": "^1.97.2",
|
|
86
86
|
"semver": "^7.7.3",
|
|
87
87
|
"unified": "^11.0.5",
|
|
88
88
|
"unplugin": "^2.3.11",
|
|
89
|
-
"vite": "
|
|
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/types": "0.1.
|
|
94
|
-
"@format.dev/
|
|
95
|
-
"@format.dev/
|
|
92
|
+
"@format.dev/cli": "0.1.2",
|
|
93
|
+
"@format.dev/types": "0.1.2",
|
|
94
|
+
"@format.dev/utils": "0.1.2",
|
|
95
|
+
"@format.dev/zip": "0.1.2"
|
|
96
96
|
},
|
|
97
97
|
"devDependencies": {
|
|
98
98
|
"@pandacss/dev": "^1.8.0",
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
"@types/react": "^19.2.7",
|
|
105
105
|
"@types/react-dom": "^19.2.3",
|
|
106
106
|
"@types/semver": "^7.7.1",
|
|
107
|
-
"@vitest/browser-playwright": "^4.
|
|
107
|
+
"@vitest/browser-playwright": "^4.1.11",
|
|
108
108
|
"concurrently": "^9.2.1",
|
|
109
109
|
"execa": "^9.6.1",
|
|
110
110
|
"express": "^5.2.1",
|
|
@@ -121,7 +121,7 @@
|
|
|
121
121
|
"tsx": "^4.21.0",
|
|
122
122
|
"typescript": "^5.9.3",
|
|
123
123
|
"unplugin-raw": "^0.6.4",
|
|
124
|
-
"vitest": "^4.
|
|
124
|
+
"vitest": "^4.1.11",
|
|
125
125
|
"vue": "^3.5.25"
|
|
126
126
|
},
|
|
127
127
|
"peerDependencies": {
|