@markless/bundler 0.2.1 → 0.3.0

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.
@@ -1,2554 +0,0 @@
1
- import { MarklessCompileError, createCompileErrorPayload } from "./dev-error.js";
2
- import { C as planModulePreloads, _ as normalizeExecutionLogMode, a as payloadModule, b as MARKLESS_BUNDLE_GRAPH, c as scopedSymbolExportName, d as MARKLESS_EXECUTION_LOG_MODULE_ID, f as MARKLESS_EXECUTION_SIZES, g as injectExecutionLogModuleHook, h as executionLogVirtualModuleSource, i as encodedSymbolSource, l as symbolVirtualModuleId, m as executionLogActivationInjection, n as emitResumeModule, o as resumeVirtualModuleId, p as createExecutionSizesAsset, r as emitSourceModule, s as rewriteSymbolModuleExport, t as MARKLESS_VIRTUAL_PREFIX, u as symbolVirtualModuleSourceFile, v as requalifyExecutionLogModuleHook, x as outputDefaults, y as MARKLESS_BUILD_PREFIX } from "./source-module-C8W2THUI.js";
3
- import { joinURL, parsePath, withLeadingSlash, withQuery, withoutLeadingSlash } from "ufo";
4
- import { dirname, isAbsolute, join, normalize, relative, resolve } from "pathe";
5
- import { defDGraph } from "@thi.ng/dgraph";
6
- import { collectTsrxModuleDiagnostics, compileTsrxModule, emitSymbolResolverModule, parseJavaScriptModule } from "@markless/compiler";
7
- import { createStorageSeedMetadataFromGraphNodeId } from "@markless/serializer";
8
- import { createInlineResumerDebugRegistrationSource, createInlineResumerSource } from "@markless/web/inline/resumer";
9
- //#region src/build/bundle-graph.ts
10
- const SLOW_BUNDLE_TOTAL = 300 * 1024 / 8 * .5;
11
- const SMALL_BUNDLE_TOTAL = 1e3;
12
- function convertManifestToBundleGraph(manifest, bundleGraphAdders) {
13
- const graph = bundleGraphRecords(manifest, bundleGraphAdders);
14
- const dag = defDGraph(bundleGraphEdges(graph));
15
- const reduced = dag.copy();
16
- for (const name of dag.nodes()) for (const dep of dag.immediateDependencies(name)) for (const transitive of dag.transitiveDependencies(dep)) reduced.removeEdge(name, transitive);
17
- const nodes = Object.keys(graph).sort().map((name) => {
18
- const bundle = graph[name];
19
- const dynamicImports = (bundle?.dynamicImports ?? []).map((dep) => [dep, dynamicImportMarker(bundle, graph[dep])]).sort((a, b) => a[1] - b[1] || a[0].localeCompare(b[0]));
20
- const deps = [...reduced.immediateDependencies(name)].sort();
21
- let lastMarker;
22
- for (const [dep, marker] of dynamicImports) {
23
- if (marker !== lastMarker) {
24
- deps.push(marker);
25
- lastMarker = marker;
26
- }
27
- deps.push(dep);
28
- }
29
- return [name, deps];
30
- });
31
- const indexes = /* @__PURE__ */ new Map();
32
- let index = 0;
33
- for (const [name, deps] of nodes) {
34
- indexes.set(name, index);
35
- index += 1 + deps.length;
36
- }
37
- return nodes.flatMap(([name, deps]) => [name, ...deps.map((dep) => {
38
- if (typeof dep === "number") return dep;
39
- return indexes.get(dep);
40
- })]);
41
- }
42
- function createPreloadGraphAdder(addEntries) {
43
- return (manifest) => addEntries({
44
- manifest,
45
- hasBundle: (bundleName) => !!manifest.bundles[bundleName],
46
- bundlesForOrigins: (origins) => bundlesForOrigins(manifest, origins)
47
- });
48
- }
49
- function bundlesForOrigins(manifest, origins) {
50
- const normalizedOrigins = new Set(origins.map(normalizeManifestOrigin));
51
- const bundles = [];
52
- for (const [bundleName, bundle] of Object.entries(manifest.bundles)) if (bundle.origins?.some((origin) => normalizedOrigins.has(normalizeManifestOrigin(origin)))) bundles.push(bundleName);
53
- return bundles.sort();
54
- }
55
- function bundleGraphRecords(manifest, bundleGraphAdders) {
56
- const graph = { ...manifest.bundles };
57
- const runtimeBundles = runtimeBundleNamesByModuleId(manifest);
58
- for (const module of manifest.modules) {
59
- const runtimeModuleIdsBySymbolId = new Map((module.runtimeDemandMap?.symbols ?? []).map((symbol) => [symbol.symbolId, symbol.runtimeModuleIds]));
60
- for (const symbol of module.symbols) {
61
- if (!symbol.fileName) continue;
62
- const imports = [...manifest.bundles[symbol.fileName]?.imports ?? [], ...module.resolver.fileName ? [module.resolver.fileName] : []];
63
- const runtimeDemandBundles = (runtimeModuleIdsBySymbolId.get(symbol.symbolId) ?? []).flatMap((id) => runtimeBundles.get(id) ?? []);
64
- const symbolBundle = {
65
- size: 0,
66
- total: 0,
67
- dynamicImports: [...new Set([symbol.fileName, ...runtimeDemandBundles])]
68
- };
69
- if (imports.length > 0) symbolBundle.imports = imports;
70
- graph[symbol.symbolId] = symbolBundle;
71
- }
72
- }
73
- for (const [bundleName, bundle] of Object.entries(graph)) for (const symbolId of bundle.symbols ?? []) {
74
- if (symbolId === bundleName) continue;
75
- graph[symbolId] = appendDynamicImport(graph[symbolId] ?? {
76
- size: 0,
77
- total: 0
78
- }, bundleName);
79
- }
80
- if (bundleGraphAdders) {
81
- const combined = {
82
- ...manifest,
83
- bundles: graph
84
- };
85
- for (const add of bundleGraphAdders) Object.assign(graph, add(combined));
86
- }
87
- for (const bundleName of Object.keys(graph)) {
88
- const bundle = graph[bundleName];
89
- if (!bundle) continue;
90
- graph[bundleName] = {
91
- ...bundle,
92
- imports: bundle.imports?.filter((dep) => graph[dep]) ?? [],
93
- dynamicImports: bundle.dynamicImports?.filter((dep) => graph[dep]) ?? []
94
- };
95
- }
96
- const used = /* @__PURE__ */ new Set();
97
- for (const bundle of Object.values(graph)) {
98
- for (const dep of bundle.imports ?? []) used.add(dep);
99
- for (const dep of bundle.dynamicImports ?? []) used.add(dep);
100
- }
101
- for (const [bundleName, bundle] of Object.entries(graph)) if (!used.has(bundleName) && !bundle.imports?.length && !bundle.dynamicImports?.length) delete graph[bundleName];
102
- return graph;
103
- }
104
- function appendDynamicImport(bundle, dependency) {
105
- if (bundle.dynamicImports?.includes(dependency)) return bundle;
106
- return {
107
- ...bundle,
108
- dynamicImports: [...bundle.dynamicImports ?? [], dependency]
109
- };
110
- }
111
- function runtimeBundleNamesByModuleId(manifest) {
112
- const entries = /* @__PURE__ */ new Map();
113
- for (const [bundleName, bundle] of Object.entries(manifest.bundles)) for (const origin of bundle.origins ?? []) {
114
- const runtimeModuleId = runtimeModuleIdFromOrigin(origin);
115
- if (!runtimeModuleId) continue;
116
- entries.set(runtimeModuleId, [...entries.get(runtimeModuleId) ?? [], bundleName]);
117
- }
118
- for (const [id, names] of entries) entries.set(id, names.sort());
119
- return entries;
120
- }
121
- function runtimeModuleIdFromOrigin(origin) {
122
- const normalized = normalizeManifestOrigin(origin);
123
- for (const [prefix, marker] of [["web", "packages/web/src/"], ["core", "packages/core/src/"]]) {
124
- const index = normalized.lastIndexOf(marker);
125
- if (index === -1 || !normalized.endsWith(".ts")) continue;
126
- return `${prefix}/${normalized.slice(index + marker.length, -3)}`;
127
- }
128
- }
129
- function dynamicImportMarker(bundle, dependency) {
130
- let probability = .5;
131
- if (hasRelatedOrigin(bundle, dependency)) probability += .25;
132
- if ((dependency?.total ?? 0) > SLOW_BUNDLE_TOTAL) if (probability > .5) probability += .02;
133
- else probability -= .02;
134
- if ((dependency?.total ?? 0) < SMALL_BUNDLE_TOTAL) probability += .15;
135
- probability = Math.min(probability, .99);
136
- return -Math.round(probability * 10);
137
- }
138
- function hasRelatedOrigin(bundle, dependency) {
139
- return !!bundle?.origins?.some((origin) => dependency?.origins?.some((depOrigin) => depOrigin.startsWith(origin)));
140
- }
141
- function* bundleGraphEdges(graph) {
142
- for (const [bundleName, bundle] of Object.entries(graph)) {
143
- yield [bundleName, null];
144
- for (const dep of bundle.imports ?? []) yield [bundleName, dep];
145
- }
146
- }
147
- function normalizeManifestOrigin(origin) {
148
- return withoutLeadingSlash(normalize(origin));
149
- }
150
- //#endregion
151
- //#region src/build/dynamic-import-scan.ts
152
- function scanEmittedDynamicImports(code, chunkFileName) {
153
- if (!code.includes("import(")) return [];
154
- let ast;
155
- try {
156
- ast = parseJavaScriptModule(code);
157
- } catch {
158
- return [];
159
- }
160
- const specifiers = /* @__PURE__ */ new Set();
161
- const visit = (node) => {
162
- if (!node || typeof node !== "object") return;
163
- if (node.type === "ImportExpression") {
164
- const specifier = staticSpecifier(node.source ?? node.arguments);
165
- if (specifier?.startsWith(".")) specifiers.add(join(dirname(chunkFileName), specifier));
166
- }
167
- for (const child of childNodes$1(node)) visit(child);
168
- };
169
- visit(ast);
170
- return [...specifiers];
171
- }
172
- function staticSpecifier(source) {
173
- const node = Array.isArray(source) ? source[0] : source;
174
- if (!node || typeof node !== "object") return void 0;
175
- const astNode = node;
176
- if (astNode.type === "Literal" || astNode.type === "StringLiteral") return typeof astNode.value === "string" ? astNode.value : void 0;
177
- if (astNode.type === "TemplateLiteral" && (astNode.expressions ?? []).length === 0) {
178
- const quasi = astNode.quasis?.[0];
179
- return quasi?.value?.cooked ?? quasi?.cooked;
180
- }
181
- }
182
- function childNodes$1(node) {
183
- const children = [];
184
- for (const [key, value] of Object.entries(node)) {
185
- if (key === "loc" || key === "span" || key === "range") continue;
186
- if (Array.isArray(value)) {
187
- for (const item of value) if (isAstNode$1(item)) children.push(item);
188
- continue;
189
- }
190
- if (isAstNode$1(value)) children.push(value);
191
- }
192
- return children;
193
- }
194
- function isAstNode$1(value) {
195
- return !!value && typeof value === "object" && "type" in value;
196
- }
197
- //#endregion
198
- //#region src/build/head-links.ts
199
- const STYLESHEET_ASSET_RE = /\.css$/;
200
- function collectHeadLinkInjections(bundle, options = {}) {
201
- const publicPath = options.publicPath ?? ((fileName) => fileName);
202
- const stylesheetFiles = stylesheetFilesFromViteMetadata(bundle);
203
- if (stylesheetFiles.size === 0) {
204
- for (const item of Object.values(bundle)) if (item.type === "asset" && STYLESHEET_ASSET_RE.test(item.fileName)) stylesheetFiles.add(item.fileName);
205
- }
206
- return [...stylesheetFiles].sort().map((fileName) => stylesheetInjection(publicPath(fileName)));
207
- }
208
- function stylesheetFilesFromViteMetadata(bundle) {
209
- const stylesheetFiles = /* @__PURE__ */ new Set();
210
- for (const item of Object.values(bundle)) {
211
- if (item.type !== "chunk") continue;
212
- for (const fileName of item.viteMetadata?.importedCss ?? []) stylesheetFiles.add(fileName);
213
- }
214
- return stylesheetFiles;
215
- }
216
- function collectModulePreloadInjections(preloadSource, options = {}) {
217
- const buildMetadata = isBuildMetadata(preloadSource) ? preloadSource : void 0;
218
- const bundleGraph = buildMetadata ? buildMetadata.bundleGraph : preloadSource;
219
- const roots = [...buildMetadata ? symbolRootsFromBuildMetadata(buildMetadata) : (bundleGraph ?? []).filter((name) => typeof name === "string" && name.startsWith("symbol:")).map((name) => ({
220
- name,
221
- priority: "high"
222
- })), ...(options.entryChunks ?? []).map((name) => ({
223
- name,
224
- priority: "auto",
225
- edges: "dynamic-only"
226
- }))];
227
- return planModulePreloads({
228
- base: options.publicPath ? options.publicPath(MARKLESS_BUILD_PREFIX) : joinURL("/", MARKLESS_BUILD_PREFIX),
229
- bundleGraph,
230
- roots
231
- }).map(modulePreloadInjection);
232
- }
233
- function symbolRootsFromBuildMetadata(metadata) {
234
- const roots = [];
235
- const seen = /* @__PURE__ */ new Set();
236
- for (const module of metadata.modules) for (const symbol of module.symbols) {
237
- if (!symbol.fileName || seen.has(symbol.symbolId)) continue;
238
- seen.add(symbol.symbolId);
239
- roots.push({
240
- name: symbol.symbolId,
241
- priority: "high"
242
- });
243
- }
244
- return roots;
245
- }
246
- function isBuildMetadata(value) {
247
- return !!value && typeof value === "object" && !Array.isArray(value) && Array.isArray(value.modules);
248
- }
249
- function injectHeadLinks(bundle, injections) {
250
- if (injections.length === 0) return;
251
- const links = injections.map(headLinkTag).join("");
252
- for (const output of Object.values(bundle)) {
253
- if (!isHtmlAssetWithSource(output)) continue;
254
- output.source = output.source.includes("</head>") ? output.source.replace("</head>", `${links}</head>`) : `${links}${output.source}`;
255
- }
256
- }
257
- function headLinkTag(injection) {
258
- const attributes = Object.entries(injection.attributes ?? {}).map(([name, value]) => `${name}="${value.replaceAll("\"", "&quot;")}"`);
259
- const open = attributes.length > 0 ? `<${injection.tag} ${attributes.join(" ")}>` : `<${injection.tag}>`;
260
- return injection.children === void 0 ? open : `${open}${injection.children}</${injection.tag}>`;
261
- }
262
- function isHtmlAssetWithSource(output) {
263
- if (!output || typeof output !== "object") return false;
264
- const asset = output;
265
- return asset.type === "asset" && typeof asset.fileName === "string" && asset.fileName.endsWith(".html") && typeof asset.source === "string";
266
- }
267
- function modulePreloadInjection(preload) {
268
- const attributes = {
269
- rel: "modulepreload",
270
- href: preload.href,
271
- crossorigin: "anonymous"
272
- };
273
- if (preload.fetchPriority && preload.fetchPriority !== "auto") attributes.fetchpriority = preload.fetchPriority;
274
- return {
275
- tag: "link",
276
- location: "head",
277
- attributes
278
- };
279
- }
280
- function stylesheetInjection(href) {
281
- return {
282
- tag: "link",
283
- location: "head",
284
- attributes: {
285
- rel: "stylesheet",
286
- href
287
- }
288
- };
289
- }
290
- //#endregion
291
- //#region src/build/build-metadata.ts
292
- function createBuildMetadata(bundle, transformManifests, root, options = {}) {
293
- const canonPath = options.canonPath ?? ((fileName) => fileName);
294
- const publicPath = options.publicPath ?? ((fileName) => fileName);
295
- const modules = [...transformManifests].map(cloneTransformManifest);
296
- const metadata = {
297
- version: 1,
298
- modules,
299
- bundles: {},
300
- assets: {},
301
- injections: [...options.injections ?? [], ...collectHeadLinkInjections(bundle, { publicPath })]
302
- };
303
- for (const item of Object.values(bundle)) {
304
- if (item.type === "asset") {
305
- if (item.fileName.endsWith(".js.map")) continue;
306
- metadata.assets[item.fileName] = assetInfo(item);
307
- continue;
308
- }
309
- const bundleFileName = canonPath(item.fileName);
310
- const origins = getOrigins(item, root);
311
- const asyncBundle = {
312
- size: item.code.length,
313
- total: item.code.length
314
- };
315
- const imports = mapBundleNames(bundle, item.imports, canonPath);
316
- if (imports.length > 0) asyncBundle.imports = imports;
317
- const dynamicImports = [...new Set([...mapBundleNames(bundle, item.dynamicImports, canonPath), ...mapBundleNames(bundle, scanEmittedDynamicImports(item.code, item.fileName), canonPath)])];
318
- if (dynamicImports.length > 0) asyncBundle.dynamicImports = dynamicImports;
319
- if (origins.length > 0) asyncBundle.origins = origins;
320
- finalizeVirtualModuleReferences(modules, item, bundleFileName);
321
- const symbols = modules.flatMap((module) => module.symbols.filter((symbol) => symbol.fileName === bundleFileName).map((symbol) => symbol.symbolId));
322
- if (symbols.length > 0) asyncBundle.symbols = symbols;
323
- metadata.bundles[bundleFileName] = asyncBundle;
324
- }
325
- computeTotals(metadata.bundles);
326
- sortBuildMetadata(metadata);
327
- if (options.bundleGraphAsset) {
328
- metadata.bundleGraph = convertManifestToBundleGraph(metadata, options.bundleGraphAdders);
329
- metadata.bundleGraphAsset = options.bundleGraphAsset;
330
- metadata.assets[options.bundleGraphAsset] = {
331
- name: "bundle-graph.json",
332
- size: JSON.stringify(metadata.bundleGraph).length
333
- };
334
- }
335
- return metadata;
336
- }
337
- function cloneTransformManifest(manifest) {
338
- return {
339
- source: manifest.source,
340
- payload: { ...manifest.payload },
341
- resolver: { ...manifest.resolver },
342
- symbols: manifest.symbols.map((symbol) => ({ ...symbol })),
343
- runtimeDemandMap: manifest.runtimeDemandMap
344
- };
345
- }
346
- function finalizeVirtualModuleReferences(modules, item, bundleFileName) {
347
- const ids = new Set([item.facadeModuleId ?? void 0, ...item.moduleIds].filter((id) => !!id).map(normalizeVirtualModuleId));
348
- for (const module of modules) {
349
- for (const reference of [module.payload, module.resolver]) if (ids.has(normalizeVirtualModuleId(reference.virtualModuleId))) reference.fileName = bundleFileName;
350
- for (const symbol of module.symbols) if (ids.has(normalizeVirtualModuleId(symbol.virtualModuleId))) symbol.fileName = bundleFileName;
351
- }
352
- }
353
- function normalizeVirtualModuleId(id) {
354
- if (id.startsWith("\0")) return id.slice(1);
355
- return id;
356
- }
357
- function assetInfo(item) {
358
- return {
359
- name: item.names?.[0] ?? item.name,
360
- size: item.source.length
361
- };
362
- }
363
- function mapBundleNames(bundle, names, canonPath) {
364
- return names.flatMap((name) => {
365
- const item = bundle[name];
366
- if (item) return [canonPath(item.fileName)];
367
- return [canonPath(name)];
368
- });
369
- }
370
- function getOrigins(item, root) {
371
- return item.moduleIds.filter((id) => !id.startsWith("\0")).map((id) => {
372
- if (root) return relative(root, id);
373
- return id;
374
- }).sort();
375
- }
376
- function computeTotals(bundles) {
377
- const collect = (name, seen) => {
378
- const bundle = bundles[name];
379
- if (!bundle || seen.has(name)) return;
380
- seen.add(name);
381
- for (const dep of bundle.imports ?? []) collect(dep, seen);
382
- };
383
- for (const name of Object.keys(bundles)) {
384
- const seen = /* @__PURE__ */ new Set();
385
- collect(name, seen);
386
- bundles[name].total = [...seen].reduce((sum, dep) => sum + (bundles[dep]?.size ?? 0), 0);
387
- }
388
- }
389
- function sortBuildMetadata(metadata) {
390
- metadata.modules = metadata.modules.sort((a, b) => a.source.localeCompare(b.source));
391
- metadata.bundles = sortRecord(metadata.bundles);
392
- metadata.assets = sortRecord(metadata.assets ?? {});
393
- metadata.injections?.sort((a, b) => injectionKey(a).localeCompare(injectionKey(b)));
394
- for (const bundle of Object.values(metadata.bundles)) {
395
- bundle.imports?.sort();
396
- bundle.dynamicImports?.sort();
397
- bundle.origins?.sort();
398
- bundle.symbols?.sort();
399
- }
400
- for (const module of metadata.modules) module.symbols.sort((a, b) => a.symbolId.localeCompare(b.symbolId));
401
- }
402
- function sortRecord(record) {
403
- const next = {};
404
- for (const key of Object.keys(record).sort()) {
405
- const value = record[key];
406
- if (value !== void 0) next[key] = value;
407
- }
408
- return next;
409
- }
410
- function injectionKey(injection) {
411
- return `${injection.location}:${injection.tag}:${injection.attributes?.href ?? ""}`;
412
- }
413
- //#endregion
414
- //#region src/build/preload-cleanup.ts
415
- function stripEmptyVitePreloadWrappers(code) {
416
- return stripImportedVitePreloadHelper(stripUnusedVitePreloadHelper(stripAsyncEmptyPreloadWrappers(stripDirectEmptyPreloadWrappers(code))));
417
- }
418
- const IMPORT_DECLARATION_CANDIDATE_RE = /\bimport\s*\{[\s\S]*?\}\s*from\s*["'][^"']+["'];?/g;
419
- function stripDirectEmptyPreloadWrappers(code) {
420
- let next = "";
421
- let cursor = 0;
422
- let changed = false;
423
- const wrapperRE = /\b[$A-Z_a-z][$\w]*\(\(\)\s*=>\s*/g;
424
- for (let match = wrapperRE.exec(code); match; match = wrapperRE.exec(code)) {
425
- const callStart = match.index;
426
- const bodyStart = match.index + match[0].length;
427
- if (!code.startsWith("import(", bodyStart)) continue;
428
- const wrapper = findEmptyPreloadWrapper(code, callStart, bodyStart);
429
- if (!wrapper) continue;
430
- next += code.slice(cursor, callStart);
431
- next += code.slice(bodyStart, wrapper.firstArgumentEnd);
432
- cursor = wrapper.callEnd + 1;
433
- wrapperRE.lastIndex = cursor;
434
- changed = true;
435
- }
436
- if (!changed) return code;
437
- return next + code.slice(cursor);
438
- }
439
- function stripAsyncEmptyPreloadWrappers(code) {
440
- let next = "";
441
- let cursor = 0;
442
- let changed = false;
443
- const wrapperRE = /\b[$A-Z_a-z][$\w]*\(\s*async\s*\(\)\s*=>\s*\{/g;
444
- for (let match = wrapperRE.exec(code); match; match = wrapperRE.exec(code)) {
445
- const callStart = match.index;
446
- const callOpen = code.indexOf("(", callStart);
447
- if (callOpen < 0) continue;
448
- const firstArgumentEnd = findTopLevelComma(code, callOpen + 1);
449
- if (firstArgumentEnd < 0) continue;
450
- const wrapper = findEmptyPreloadWrapper(code, callStart, callOpen + 1);
451
- if (!wrapper) continue;
452
- const loader = code.slice(callOpen + 1, firstArgumentEnd);
453
- next += code.slice(cursor, callStart);
454
- next += `(${loader})()`;
455
- cursor = wrapper.callEnd + 1;
456
- wrapperRE.lastIndex = cursor;
457
- changed = true;
458
- }
459
- if (!changed) return code;
460
- return next + code.slice(cursor);
461
- }
462
- function findEmptyPreloadWrapper(code, callStart, bodyStart) {
463
- const callOpen = code.indexOf("(", callStart);
464
- if (callOpen < 0 || callOpen >= bodyStart) return void 0;
465
- const firstArgumentEnd = findTopLevelComma(code, callOpen + 1);
466
- if (firstArgumentEnd < 0) return void 0;
467
- let cursor = skipSpaces(code, firstArgumentEnd + 1);
468
- if (code[cursor] !== "[" || code[cursor + 1] !== "]") return void 0;
469
- cursor = skipSpaces(code, cursor + 2);
470
- if (code[cursor] === ")") return {
471
- firstArgumentEnd,
472
- callEnd: cursor
473
- };
474
- if (code[cursor] !== ",") return void 0;
475
- cursor = skipSpaces(code, cursor + 1);
476
- if (!code.startsWith("import.meta.url", cursor)) return void 0;
477
- cursor = skipSpaces(code, cursor + 15);
478
- if (code[cursor] !== ")") return void 0;
479
- return {
480
- firstArgumentEnd,
481
- callEnd: cursor
482
- };
483
- }
484
- function findTopLevelComma(code, start) {
485
- let depth = 1;
486
- let quote = null;
487
- let escaped = false;
488
- for (let index = start; index < code.length; index++) {
489
- const char = code[index];
490
- if (quote) {
491
- if (escaped) {
492
- escaped = false;
493
- continue;
494
- }
495
- if (char === "\\") {
496
- escaped = true;
497
- continue;
498
- }
499
- if (char === quote) quote = null;
500
- continue;
501
- }
502
- if (char === "\"" || char === "'" || char === "`") {
503
- quote = char;
504
- continue;
505
- }
506
- if (char === "(" || char === "[" || char === "{") {
507
- depth++;
508
- continue;
509
- }
510
- if (char === ")" || char === "]" || char === "}") {
511
- depth--;
512
- if (depth === 0) return -1;
513
- continue;
514
- }
515
- if (char === "," && depth === 1) return index;
516
- }
517
- return -1;
518
- }
519
- function skipSpaces(code, start) {
520
- let cursor = start;
521
- while (/\s/.test(code[cursor] ?? "")) cursor++;
522
- return cursor;
523
- }
524
- function stripImportedVitePreloadHelper(code) {
525
- const helper = findImportedVitePreloadHelper(code);
526
- if (!helper) return code;
527
- const withoutImport = code.slice(0, helper.importStart) + code.slice(helper.importEnd);
528
- if (hasCallableReference(withoutImport, helper.preloadFunction)) return code;
529
- const initCall = `${escapeRegExp$1(helper.initFunction)}\\(\\)`;
530
- return withoutImport.replace(new RegExp(String.raw`,${initCall},`, "g"), ",").replace(new RegExp(String.raw`\{${initCall},`, "g"), "{").replace(new RegExp(String.raw`,${initCall},`, "g"), ",").replace(new RegExp(String.raw`,${initCall}\}`, "g"), "}").replace(new RegExp(String.raw`\{${initCall}\}`, "g"), "{}");
531
- }
532
- function findImportedVitePreloadHelper(code) {
533
- for (const match of code.matchAll(IMPORT_DECLARATION_CANDIDATE_RE)) {
534
- const importStart = match.index ?? -1;
535
- if (importStart < 0) continue;
536
- const statement = match[0];
537
- const declaration = asNodes(tryParseJavaScriptModule(statement)?.body).find((node) => node.type === "ImportDeclaration");
538
- if (!declaration) continue;
539
- let preloadFunction;
540
- let initFunction;
541
- for (const specifier of asNodes(declaration.specifiers)) {
542
- if (specifier.type !== "ImportSpecifier") continue;
543
- const imported = identifierName(specifier.imported);
544
- const local = identifierName(specifier.local);
545
- if (!imported || !local) continue;
546
- if (imported === "__vitePreload") preloadFunction = local;
547
- if (imported === "init_preload_helper") initFunction = local;
548
- }
549
- if (preloadFunction && initFunction) return {
550
- importStart,
551
- importEnd: importStart + statement.length,
552
- preloadFunction,
553
- initFunction
554
- };
555
- }
556
- }
557
- function stripUnusedVitePreloadHelper(code) {
558
- const marker = code.indexOf("vite:preloadError");
559
- if (marker < 0) return code;
560
- const helper = findVitePreloadHelperModule(code, marker);
561
- if (!helper) return code;
562
- const statementEnd = code[helper.removeStart] === "," && code[helper.removeEnd - 1] === ";" ? ";" : "";
563
- const outsideHelper = code.slice(0, helper.removeStart) + statementEnd + code.slice(helper.removeEnd);
564
- if (hasCallableReference(outsideHelper, helper.preloadFunction)) return code;
565
- let withoutHelper = outsideHelper;
566
- const chain = findVitePreloadHelperInitChain(withoutHelper, helper.moduleVariable);
567
- if (chain) withoutHelper = removeInitCall(withoutHelper.slice(0, chain.removeStart) + withoutHelper.slice(chain.removeEnd), chain.entryVariable);
568
- return removeInitCall(withoutHelper, helper.moduleVariable);
569
- }
570
- function findVitePreloadHelperModule(code, marker) {
571
- const initStart = code.lastIndexOf("=e((()=>{", marker);
572
- if (initStart < 0) return void 0;
573
- const moduleVariable = readIdentifierBefore(code, initStart);
574
- if (!moduleVariable) return void 0;
575
- const bodyStart = initStart + 9;
576
- const bodyEnd = findModuleInitEnd(code, initStart);
577
- if (bodyEnd < 0) return void 0;
578
- const helperBody = code.slice(bodyStart, bodyEnd);
579
- const preloadFunction = helperBody.match(/,([$A-Z_a-z][$\w]*)=function\([^)]*\)\{let\s+[$A-Z_a-z][$\w]*=Promise\.resolve\(\)/)?.[1];
580
- if (!preloadFunction) return void 0;
581
- const firstHelperVariable = helperBody.match(/^([$A-Z_a-z][$\w]*)=/)?.[1];
582
- if (!firstHelperVariable) return void 0;
583
- const removeStart = findHelperDeclarationStart(code, initStart, firstHelperVariable);
584
- if (removeStart < 0) return void 0;
585
- return {
586
- moduleVariable,
587
- preloadFunction,
588
- removeStart,
589
- removeEnd: bodyEnd + 4
590
- };
591
- }
592
- function findVitePreloadHelperInitChain(code, moduleVariable) {
593
- const match = new RegExp(`var\\s+([$A-Z_a-z][$\\w]*)=e\\(\\(\\(\\)=>\\{${escapeRegExp$1(moduleVariable)}\\(\\)\\}\\)\\),([$A-Z_a-z][$\\w]*)=e\\(\\(\\(\\)=>\\{\\1\\(\\)\\}\\)\\);`).exec(code);
594
- if (!match) return void 0;
595
- return {
596
- entryVariable: match[2],
597
- removeStart: match.index,
598
- removeEnd: match.index + match[0].length
599
- };
600
- }
601
- function removeInitCall(code, entryVariable) {
602
- return code.replace(new RegExp(`,${escapeRegExp$1(entryVariable)}\\(\\)`), "").replace(new RegExp(`${escapeRegExp$1(entryVariable)}\\(\\),`), "").replace(new RegExp(`\\{${escapeRegExp$1(entryVariable)}\\(\\)\\}`), "{}");
603
- }
604
- function readIdentifierBefore(code, index) {
605
- let end = index;
606
- while (/\s/.test(code[end - 1] ?? "")) end--;
607
- let start = end;
608
- while (/[$\w]/.test(code[start - 1] ?? "")) start--;
609
- const value = code.slice(start, end);
610
- return /^[$A-Z_a-z][$\w]*$/.test(value) ? value : void 0;
611
- }
612
- function findModuleInitEnd(code, initStart) {
613
- return code.indexOf("}));", initStart);
614
- }
615
- function findHelperDeclarationStart(code, initStart, firstHelperVariable) {
616
- const commaStart = code.lastIndexOf(`,${firstHelperVariable},`, initStart);
617
- if (commaStart >= 0) return commaStart;
618
- const varStart = code.lastIndexOf(`var ${firstHelperVariable},`, initStart);
619
- if (varStart >= 0) return varStart;
620
- return -1;
621
- }
622
- function escapeRegExp$1(value) {
623
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
624
- }
625
- function hasCallableReference(code, name) {
626
- const ast = tryParseJavaScriptModule(code);
627
- if (!ast) return true;
628
- let found = false;
629
- walkReferenceScopes(ast, [], (node, scopes) => {
630
- if (node.type !== "CallExpression") return;
631
- const callee = node.callee;
632
- if (identifierName(callee) !== name) return;
633
- if (isDeclaredInScope(name, scopes)) return;
634
- found = true;
635
- });
636
- return found;
637
- }
638
- function walkReferenceScopes(node, scopes, visit) {
639
- if (!node || typeof node !== "object") return;
640
- if (node.type === "Program") {
641
- const scope = collectScopeDeclarations(asNodes(node.body));
642
- visit(node, [scope]);
643
- for (const child of asNodes(node.body)) walkReferenceScopes(child, [scope], visit);
644
- return;
645
- }
646
- if (isFunctionNode(node)) {
647
- const scope = /* @__PURE__ */ new Set();
648
- collectBindingNames(node.id, scope);
649
- for (const parameter of asNodes(node.params)) collectBindingNames(parameter, scope);
650
- const nextScopes = [...scopes, scope];
651
- visit(node, nextScopes);
652
- walkReferenceScopes(node.body, nextScopes, visit);
653
- return;
654
- }
655
- if (node.type === "BlockStatement") {
656
- const scope = collectScopeDeclarations(asNodes(node.body));
657
- const nextScopes = [...scopes, scope];
658
- visit(node, nextScopes);
659
- for (const child of asNodes(node.body)) walkReferenceScopes(child, nextScopes, visit);
660
- return;
661
- }
662
- visit(node, scopes);
663
- for (const child of childNodes(node)) walkReferenceScopes(child, scopes, visit);
664
- }
665
- function collectScopeDeclarations(nodes) {
666
- const declarations = /* @__PURE__ */ new Set();
667
- for (const node of nodes) {
668
- if (node.type === "FunctionDeclaration" || node.type === "ClassDeclaration") {
669
- collectBindingNames(node.id, declarations);
670
- continue;
671
- }
672
- if (node.type === "ImportDeclaration") {
673
- for (const specifier of asNodes(node.specifiers)) collectBindingNames(specifier.local, declarations);
674
- continue;
675
- }
676
- if (node.type === "VariableDeclaration") for (const declaration of asNodes(node.declarations)) collectBindingNames(declaration.id, declarations);
677
- }
678
- return declarations;
679
- }
680
- function collectBindingNames(node, names) {
681
- if (!node) return;
682
- const name = identifierName(node);
683
- if (name) {
684
- names.add(name);
685
- return;
686
- }
687
- for (const child of childNodes(node)) collectBindingNames(child, names);
688
- }
689
- function isDeclaredInScope(name, scopes) {
690
- return scopes.some((scope) => scope.has(name));
691
- }
692
- function isFunctionNode(node) {
693
- return node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression";
694
- }
695
- function tryParseJavaScriptModule(code) {
696
- try {
697
- return parseJavaScriptModule(code);
698
- } catch {
699
- return;
700
- }
701
- }
702
- function childNodes(node) {
703
- const children = [];
704
- for (const [key, value] of Object.entries(node)) {
705
- if (ignoredAstKeys.has(key)) continue;
706
- if (Array.isArray(value)) {
707
- for (const item of value) if (isAstNode(item)) children.push(item);
708
- continue;
709
- }
710
- if (isAstNode(value)) children.push(value);
711
- }
712
- return children;
713
- }
714
- function asNodes(value) {
715
- return Array.isArray(value) ? value.filter(isAstNode) : [];
716
- }
717
- function isAstNode(value) {
718
- return typeof value === "object" && value !== null && typeof value.type === "string";
719
- }
720
- function identifierName(node) {
721
- return node?.type === "Identifier" && typeof node.name === "string" ? node.name : void 0;
722
- }
723
- const ignoredAstKeys = new Set([
724
- "closingElement",
725
- "id",
726
- "leadingComments",
727
- "loc",
728
- "metadata",
729
- "openingElement",
730
- "parent",
731
- "range",
732
- "trailingComments"
733
- ]);
734
- //#endregion
735
- //#region src/build/symbol-facade-cleanup.ts
736
- const TSRX_SOURCE_FILE$1 = /\.tsrx(?:[?#].*)?$/;
737
- const SYMBOL_INIT_EXPORT_PREFIX = "init__virtual_markless_symbol";
738
- const STRING_LITERAL_SOURCE = String.raw`(?:"[^"\\]*(?:\\.[^"\\]*)*"|'[^'\\]*(?:\\.[^'\\]*)*'|` + "`[^`\\\\]*(?:\\\\.[^`\\\\]*)*`)";
739
- const FUNCTION_DECLARATION_RE = /\bfunction\s+([$A-Z_a-z][$\w]*)\s*\(\s*([$A-Z_a-z][$\w]*)\s*\)\s*\{/g;
740
- const LOCAL_DYNAMIC_IMPORT_HELPER_RE = /import\(\s*(["'`])([^"'`]+)\1\s*\)\.then\(\s*\(?\s*([$A-Z_a-z][$\w]*)\s*\)?\s*=>\s*([$A-Z_a-z][$\w]*)\(\s*\3\s*,\s*(["'`])([^"'`]*)\5\s*\)\s*\)/g;
741
- const LOCAL_DYNAMIC_IMPORT_RE = /import\(\s*(["'`])([^"'`]+)\1\s*\)(?:\.then\(\s*\(?\s*([$A-Z_a-z][$\w]*)\s*\)?\s*=>\s*\3\.([$A-Z_a-z][$\w]*)\s*\))?/g;
742
- function rewriteGeneratedSymbolFacadeImports(bundle) {
743
- const chunks = collectChunks$1(bundle);
744
- const rewrites = findSymbolFacadeRewrites(chunks);
745
- const removedFacades = /* @__PURE__ */ new Set();
746
- if (rewrites.size === 0) return removedFacades;
747
- for (const chunk of chunks.values()) {
748
- if (!isGeneratedAsyncChunk(chunk)) continue;
749
- const result = rewriteDynamicImportSpecifiers(chunk, rewrites);
750
- chunk.code = result.code;
751
- chunk.dynamicImports = unique(chunk.dynamicImports.map((fileName) => result.rewrittenFacades.has(fileName) ? rewrites.get(fileName)?.target.fileName ?? fileName : fileName));
752
- }
753
- for (const rewrite of rewrites.values()) {
754
- const facadeId = rewrite.facade.facadeModuleId;
755
- if (facadeId && !rewrite.target.moduleIds.includes(facadeId)) rewrite.target.moduleIds = [...rewrite.target.moduleIds, facadeId];
756
- }
757
- for (const rewrite of rewrites.values()) {
758
- deleteBundleChunk(bundle, rewrite.facade.fileName);
759
- chunks.delete(rewrite.facade.fileName);
760
- removedFacades.add(rewrite.facade.fileName);
761
- }
762
- return removedFacades;
763
- }
764
- function rewriteGeneratedSymbolInitExports(bundle) {
765
- const chunks = collectChunks$1(bundle);
766
- const rewrites = findSymbolInitExportRewrites(chunks);
767
- if (rewrites.length === 0) return { renamed: 0 };
768
- const replacements = /* @__PURE__ */ new Map();
769
- for (const rewrite of rewrites) {
770
- rewrite.chunk.exports = rewrite.collapsed ? [...rewrite.collapsed.exports] : rewrite.chunk.exports.map((name) => rewrite.names.get(name) ?? name);
771
- if (rewrite.collapsed) rewrite.chunk.code = rewrite.collapsed.code;
772
- for (const [from, to] of rewrite.names) replacements.set(from, to);
773
- }
774
- for (const chunk of chunks.values()) {
775
- if (!isGeneratedAsyncChunk(chunk)) continue;
776
- chunk.code = replaceIdentifierNames(chunk.code, replacements);
777
- }
778
- return { renamed: replacements.size };
779
- }
780
- function compactGeneratedDirectSymbolLoaders(bundle) {
781
- let compacted = 0;
782
- for (const chunk of collectChunks$1(bundle).values()) {
783
- if (!isGeneratedAsyncChunk(chunk)) continue;
784
- if (!chunk.code.includes("?import(")) continue;
785
- const result = compactDirectSymbolLoadersInCode(chunk.code);
786
- if (result.compacted === 0) continue;
787
- chunk.code = result.code;
788
- compacted += result.compacted;
789
- }
790
- return { compacted };
791
- }
792
- function collectChunks$1(bundle) {
793
- const chunks = /* @__PURE__ */ new Map();
794
- for (const output of Object.values(bundle)) if (isGeneratedChunk$1(output)) chunks.set(output.fileName, output);
795
- return chunks;
796
- }
797
- function findSymbolFacadeRewrites(chunks) {
798
- const rewrites = /* @__PURE__ */ new Map();
799
- for (const chunk of chunks.values()) {
800
- const rewrite = findSymbolFacadeRewrite(chunk, chunks);
801
- if (rewrite) rewrites.set(chunk.fileName, rewrite);
802
- }
803
- return rewrites;
804
- }
805
- function findSymbolInitExportRewrites(chunks) {
806
- const rewrites = [];
807
- for (const chunk of chunks.values()) {
808
- const rewrite = findSymbolInitExportRewrite(chunk);
809
- if (rewrite) rewrites.push(rewrite);
810
- }
811
- return rewrites;
812
- }
813
- function findSymbolInitExportRewrite(chunk) {
814
- if (!isGeneratedAsyncChunk(chunk)) return void 0;
815
- const initExports = chunk.exports.filter(isGeneratedSymbolInitExport);
816
- if (initExports.length === 0) return void 0;
817
- const names = /* @__PURE__ */ new Map();
818
- const used = new Set(chunk.exports.filter((name) => !isGeneratedSymbolInitExport(name)));
819
- const collapsed = collapseGeneratedSymbolInitExports(chunk.code, initExports);
820
- if (collapsed) {
821
- for (const name of initExports) if (name !== SYMBOL_INIT_EXPORT_PREFIX) names.set(name, SYMBOL_INIT_EXPORT_PREFIX);
822
- return {
823
- chunk,
824
- names,
825
- collapsed
826
- };
827
- }
828
- for (const name of initExports) {
829
- const next = compactSymbolInitExportName(name, used);
830
- used.add(next);
831
- if (next !== name) names.set(name, next);
832
- }
833
- return names.size > 0 ? {
834
- chunk,
835
- names
836
- } : void 0;
837
- }
838
- function findSymbolFacadeRewrite(chunk, chunks) {
839
- if (!isGeneratedSymbolFacade(chunk)) return void 0;
840
- if (chunk.imports.length !== 1 || chunk.dynamicImports.length > 0) return void 0;
841
- const parsed = parseSymbolFacade(chunk.code);
842
- if (!parsed) return void 0;
843
- const target = chunks.get(chunk.imports[0]);
844
- if (!target) return void 0;
845
- const targetExports = new Set(target.exports);
846
- if (!chunk.exports.every((name) => targetExports.has(name))) return void 0;
847
- if (!parsed.initExports.every((name) => targetExports.has(name))) return void 0;
848
- return {
849
- facade: chunk,
850
- target,
851
- initExports: parsed.initExports
852
- };
853
- }
854
- function isGeneratedSymbolFacade(chunk) {
855
- return (chunk.facadeModuleId ? normalizeVirtualId$2(chunk.facadeModuleId) : "").startsWith(`${MARKLESS_VIRTUAL_PREFIX}symbol:`);
856
- }
857
- function isGeneratedSymbolInitExport(name) {
858
- return name === SYMBOL_INIT_EXPORT_PREFIX || name.startsWith(`${SYMBOL_INIT_EXPORT_PREFIX}_`) || /^\$\d+$/.test(name.slice(29));
859
- }
860
- function compactSymbolInitExportName(name, used) {
861
- const suffix = name.match(/\$(\d+)$/)?.[1];
862
- let candidate = suffix ? `${SYMBOL_INIT_EXPORT_PREFIX}$${suffix}` : SYMBOL_INIT_EXPORT_PREFIX;
863
- let nextSuffix = suffix ? Number(suffix) : 0;
864
- while (used.has(candidate)) {
865
- nextSuffix++;
866
- candidate = `${SYMBOL_INIT_EXPORT_PREFIX}$${nextSuffix}`;
867
- }
868
- return candidate;
869
- }
870
- function collapseGeneratedSymbolInitExports(code, initExports) {
871
- if (initExports.length < 2) return void 0;
872
- const match = code.match(/export\s*\{\s*([^}]*)\s*\}\s*;?\s*$/);
873
- if (!match || match.index === void 0) return void 0;
874
- const specifiers = parseExportSpecifiers(match[1]);
875
- if (!specifiers) return void 0;
876
- if (specifiers.some((specifier) => !isIdentifier(specifier.local))) return void 0;
877
- const initExportSet = new Set(initExports);
878
- const initLocals = unique(specifiers.filter((specifier) => initExportSet.has(specifier.exported)).map((specifier) => specifier.local));
879
- if (initLocals.length < 2) return void 0;
880
- const nonInitSpecifiers = specifiers.filter((specifier) => !initExportSet.has(specifier.exported));
881
- if (nonInitSpecifiers.some((specifier) => specifier.exported === SYMBOL_INIT_EXPORT_PREFIX)) return;
882
- const initLocal = uniqueIdentifier("$i", code);
883
- return {
884
- code: `${code.slice(0, match.index)}function ${initLocal}(){${initLocals.map((local) => `${local}()`).join(";")}}export{${[`${initLocal} as ${SYMBOL_INIT_EXPORT_PREFIX}`, ...nonInitSpecifiers.map(formatExportSpecifier)].join(",")}};`,
885
- exports: [SYMBOL_INIT_EXPORT_PREFIX, ...nonInitSpecifiers.map((specifier) => specifier.exported)]
886
- };
887
- }
888
- function rewriteDynamicImportSpecifiers(chunk, rewrites) {
889
- const rewrittenFacades = /* @__PURE__ */ new Set();
890
- return {
891
- code: chunk.code.replace(LOCAL_DYNAMIC_IMPORT_HELPER_RE, (match, quote, specifier, parameter, helperName, exportQuote, exportName) => {
892
- if (!isLocalSpecifier(specifier)) return match;
893
- const importedFileName = resolveChunkSpecifier$1(chunk.fileName, specifier);
894
- const rewrite = rewrites.get(importedFileName);
895
- if (!rewrite) return match;
896
- if (!rewrite.target.exports.includes(exportName)) return match;
897
- const nextSpecifier = relativeChunkSpecifier$1(chunk.fileName, rewrite.target.fileName);
898
- rewrittenFacades.add(importedFileName);
899
- return `import(${quote}${nextSpecifier}${quote}).then(${parameter}=>${helperName}(${parameter},${exportQuote}${exportName}${exportQuote}))`;
900
- }).replace(LOCAL_DYNAMIC_IMPORT_RE, (match, quote, specifier, parameter, exportName) => {
901
- if (!isLocalSpecifier(specifier)) return match;
902
- const importedFileName = resolveChunkSpecifier$1(chunk.fileName, specifier);
903
- const rewrite = rewrites.get(importedFileName);
904
- if (!rewrite) return match;
905
- if (rewrite.initExports.length > 0 && (!parameter || !exportName)) return match;
906
- const nextSpecifier = relativeChunkSpecifier$1(chunk.fileName, rewrite.target.fileName);
907
- rewrittenFacades.add(importedFileName);
908
- const nextImport = `import(${quote}${nextSpecifier}${quote})`;
909
- if (!parameter || !exportName || rewrite.initExports.length === 0) return nextImport;
910
- return `${nextImport}.then(${parameter}=>(${[...rewrite.initExports.map((name) => `${parameter}.${name}()`), `${parameter}.${exportName}`].join(",")}))`;
911
- }),
912
- rewrittenFacades
913
- };
914
- }
915
- function compactDirectSymbolLoadersInCode(code) {
916
- let next = "";
917
- let cursor = 0;
918
- let compacted = 0;
919
- for (let match = FUNCTION_DECLARATION_RE.exec(code); match; match = FUNCTION_DECLARATION_RE.exec(code)) {
920
- const functionStart = match.index;
921
- const bodyStart = FUNCTION_DECLARATION_RE.lastIndex;
922
- const bodyEnd = findBlockEnd(code, bodyStart - 1);
923
- if (bodyEnd < 0) continue;
924
- const body = code.slice(bodyStart, bodyEnd);
925
- const mapName = uniqueIdentifier("$s", `${code}${next}`);
926
- const moduleCacheName = uniqueIdentifier("$m", `${code}${next}${mapName}`);
927
- const replacement = compactDirectSymbolLoaderFunction({
928
- functionName: match[1],
929
- parameterName: match[2],
930
- body,
931
- mapName,
932
- moduleCacheName
933
- });
934
- if (!replacement) {
935
- FUNCTION_DECLARATION_RE.lastIndex = bodyEnd + 1;
936
- continue;
937
- }
938
- next += code.slice(cursor, functionStart);
939
- next += replacement;
940
- cursor = bodyEnd + 1;
941
- compacted++;
942
- FUNCTION_DECLARATION_RE.lastIndex = cursor;
943
- }
944
- if (compacted === 0) return {
945
- code,
946
- compacted
947
- };
948
- return {
949
- code: next + code.slice(cursor),
950
- compacted
951
- };
952
- }
953
- function compactDirectSymbolLoaderFunction(input) {
954
- const returnSource = input.body.trim();
955
- if (!returnSource.startsWith("return ")) return void 0;
956
- const parsed = parseDirectSymbolLoaderBranches(returnSource.slice(7), input.parameterName);
957
- if (!parsed) return void 0;
958
- const first = parsed.branches[0];
959
- if (parsed.branches.some((branch) => branch.importSpecifier !== first.importSpecifier || branch.helperName !== first.helperName)) return;
960
- const generatedCount = generatedSymbolRangeCount(parsed.branches);
961
- if (generatedCount !== void 0) return [
962
- `let ${input.moduleCacheName};`,
963
- `function ${input.functionName}(${input.parameterName}){`,
964
- `let t=+${input.parameterName}.slice(7);`,
965
- `if(${input.parameterName}===\`symbol:\${t}\`&&t>=0&&t<${generatedCount}){`,
966
- `if(${input.moduleCacheName})return ${first.helperName}(${input.moduleCacheName},\`symbol_\${t}\`);`,
967
- `return import(${JSON.stringify(first.importSpecifier)})`,
968
- `.then(${first.moduleParameter}=>(${input.moduleCacheName}=${first.moduleParameter},${first.helperName}(${first.moduleParameter},\`symbol_\${t}\`)))`,
969
- `}`,
970
- `return ${parsed.fallback}`,
971
- "}"
972
- ].join("");
973
- const exportVariable = input.parameterName === "t" ? "n" : "t";
974
- const mapEntries = parsed.branches.map((branch) => `${JSON.stringify(branch.symbolId)}:${JSON.stringify(branch.exportName)}`).join(",");
975
- return [
976
- `const ${input.mapName}={${mapEntries}};`,
977
- `let ${input.moduleCacheName};`,
978
- `function ${input.functionName}(${input.parameterName}){`,
979
- `let ${exportVariable}=${input.mapName}[${input.parameterName}];`,
980
- `if(${exportVariable}){`,
981
- `if(${input.moduleCacheName})return ${first.helperName}(${input.moduleCacheName},${exportVariable});`,
982
- `return import(${JSON.stringify(first.importSpecifier)})`,
983
- `.then(${first.moduleParameter}=>(${input.moduleCacheName}=${first.moduleParameter},${first.helperName}(${first.moduleParameter},${exportVariable})))`,
984
- `}`,
985
- `return ${parsed.fallback}`,
986
- "}"
987
- ].join("");
988
- }
989
- function parseDirectSymbolLoaderBranches(source, parameterName) {
990
- const branches = [];
991
- const branchRE = directSymbolLoaderBranchRE(parameterName);
992
- let cursor = 0;
993
- while (cursor < source.length) {
994
- const match = source.slice(cursor).match(branchRE);
995
- if (!match) break;
996
- const symbolId = simpleStringLiteralValue(match[1]);
997
- const importSpecifier = simpleStringLiteralValue(match[2]);
998
- const moduleParameter = match[3];
999
- const helperName = match[4];
1000
- const helperArgument = match[5];
1001
- const exportName = simpleStringLiteralValue(match[6]);
1002
- if (symbolId === void 0 || importSpecifier === void 0 || exportName === void 0 || moduleParameter !== helperArgument) return;
1003
- branches.push({
1004
- symbolId,
1005
- importSpecifier,
1006
- moduleParameter,
1007
- helperName,
1008
- exportName
1009
- });
1010
- cursor += match[0].length;
1011
- }
1012
- const fallback = source.slice(cursor);
1013
- if (branches.length < 2 || !fallback.startsWith("Promise.reject(")) return void 0;
1014
- return {
1015
- branches,
1016
- fallback
1017
- };
1018
- }
1019
- function generatedSymbolRangeCount(branches) {
1020
- for (const [index, branch] of branches.entries()) if (branch.symbolId !== `symbol:${index}` || branch.exportName !== `symbol_${index}`) return;
1021
- return branches.length;
1022
- }
1023
- function directSymbolLoaderBranchRE(parameterName) {
1024
- return new RegExp(`^${escapeRegExp(parameterName)}\\s*===\\s*(${STRING_LITERAL_SOURCE})\\s*\\?\\s*import\\(\\s*(${STRING_LITERAL_SOURCE})\\s*\\)\\.then\\(\\s*\\(?\\s*([$A-Z_a-z][$\\w]*)\\s*\\)?\\s*=>\\s*([$A-Z_a-z][$\\w]*)\\(\\s*([$A-Z_a-z][$\\w]*)\\s*,\\s*(${STRING_LITERAL_SOURCE})\\s*\\)\\s*\\)\\s*:`);
1025
- }
1026
- function simpleStringLiteralValue(source) {
1027
- const quote = source[0];
1028
- if (quote !== "\"" && quote !== "'" && quote !== "`" || source[source.length - 1] !== quote) return;
1029
- return source.slice(1, -1);
1030
- }
1031
- function findBlockEnd(code, open) {
1032
- let depth = 0;
1033
- let quote = null;
1034
- let escaped = false;
1035
- for (let index = open; index < code.length; index++) {
1036
- const char = code[index];
1037
- if (quote) {
1038
- if (escaped) {
1039
- escaped = false;
1040
- continue;
1041
- }
1042
- if (char === "\\") {
1043
- escaped = true;
1044
- continue;
1045
- }
1046
- if (char === quote) quote = null;
1047
- continue;
1048
- }
1049
- if (char === "\"" || char === "'" || char === "`") {
1050
- quote = char;
1051
- continue;
1052
- }
1053
- if (char === "{") {
1054
- depth++;
1055
- continue;
1056
- }
1057
- if (char === "}") {
1058
- depth--;
1059
- if (depth === 0) return index;
1060
- }
1061
- }
1062
- return -1;
1063
- }
1064
- function resolveChunkSpecifier$1(importerFileName, specifier) {
1065
- return normalize(join(dirname(importerFileName), specifier));
1066
- }
1067
- function relativeChunkSpecifier$1(importerFileName, targetFileName) {
1068
- const value = relative(dirname(importerFileName), targetFileName).replaceAll("\\", "/");
1069
- return value.startsWith(".") ? value : `./${value}`;
1070
- }
1071
- function isGeneratedAsyncChunk(chunk) {
1072
- return chunk.moduleIds.some((id) => {
1073
- return normalizeVirtualId$2(id).startsWith("virtual:markless:") || TSRX_SOURCE_FILE$1.test(id);
1074
- });
1075
- }
1076
- function deleteBundleChunk(bundle, fileName) {
1077
- for (const [key, output] of Object.entries(bundle)) if (isGeneratedChunk$1(output) && output.fileName === fileName) delete bundle[key];
1078
- }
1079
- function isGeneratedChunk$1(value) {
1080
- if (!value || typeof value !== "object") return false;
1081
- const chunk = value;
1082
- return chunk.type === "chunk" && typeof chunk.fileName === "string" && typeof chunk.code === "string" && Array.isArray(chunk.exports) && Array.isArray(chunk.imports) && Array.isArray(chunk.dynamicImports) && Array.isArray(chunk.moduleIds);
1083
- }
1084
- function unique(values) {
1085
- return [...new Set(values)];
1086
- }
1087
- function replaceIdentifierNames(code, replacements) {
1088
- const names = [...replacements.keys()].sort((a, b) => b.length - a.length);
1089
- let next = code;
1090
- for (const name of names) next = next.replace(identifierNameRE(name), replacements.get(name));
1091
- return next;
1092
- }
1093
- function identifierNameRE(name) {
1094
- return new RegExp(`(?<![$\\w])${escapeRegExp(name)}(?![$\\w])`, "g");
1095
- }
1096
- function escapeRegExp(value) {
1097
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1098
- }
1099
- function isLocalSpecifier(specifier) {
1100
- return specifier.startsWith("./") || specifier.startsWith("../");
1101
- }
1102
- function parseSymbolFacade(code) {
1103
- const match = code.trim().match(/^import\s*\{\s*([^}]*)\s*\}\s*from\s*(["'`])([^"'`]+)\2\s*;\s*([\s\S]*?)\s*export\s*\{\s*([^}]*)\s*\}\s*;?\s*$/);
1104
- if (!match) return void 0;
1105
- const imports = parseImportSpecifiers(match[1]);
1106
- const exportLocals = parseExportLocalNames(match[5]);
1107
- if (!imports || !exportLocals) return void 0;
1108
- const body = match[4].trim();
1109
- const initLocals = body ? body.split(";").map((statement) => statement.trim()).filter(Boolean).map((statement) => statement.match(/^([$A-Z_a-z][$\w]*)\(\)$/)?.[1]) : [];
1110
- if (initLocals.some((name) => !name)) return void 0;
1111
- for (const local of exportLocals) if (!imports.has(local)) return void 0;
1112
- return { initExports: unique(initLocals.filter((local) => !!local).map((local) => imports.get(local)).filter((name) => !!name)) };
1113
- }
1114
- function parseImportSpecifiers(value) {
1115
- const imports = /* @__PURE__ */ new Map();
1116
- for (const part of value.split(",")) {
1117
- const specifier = part.trim();
1118
- if (!specifier) continue;
1119
- const aliased = specifier.match(/^(.+?)\s+as\s+(.+)$/);
1120
- const imported = (aliased?.[1] ?? specifier).trim();
1121
- const local = (aliased?.[2] ?? specifier).trim();
1122
- if (!isIdentifier(imported) || !isIdentifier(local)) return void 0;
1123
- imports.set(local, imported);
1124
- }
1125
- return imports;
1126
- }
1127
- function parseExportLocalNames(value) {
1128
- const locals = [];
1129
- for (const part of value.split(",")) {
1130
- const specifier = part.trim();
1131
- if (!specifier) continue;
1132
- const aliased = specifier.match(/^(.+?)\s+as\s+(.+)$/);
1133
- const local = (aliased?.[1] ?? specifier).trim();
1134
- const exported = (aliased?.[2] ?? specifier).trim();
1135
- if (!isIdentifier(local) || !isIdentifier(exported)) return void 0;
1136
- locals.push(local);
1137
- }
1138
- return locals;
1139
- }
1140
- function parseExportSpecifiers(value) {
1141
- const specifiers = [];
1142
- for (const part of value.split(",")) {
1143
- const specifier = part.trim();
1144
- if (!specifier) continue;
1145
- const aliased = specifier.match(/^(.+?)\s+as\s+(.+)$/);
1146
- const local = (aliased?.[1] ?? specifier).trim();
1147
- const exported = (aliased?.[2] ?? specifier).trim();
1148
- if (!isIdentifier(local) || !isIdentifier(exported)) return void 0;
1149
- specifiers.push({
1150
- local,
1151
- exported
1152
- });
1153
- }
1154
- return specifiers;
1155
- }
1156
- function formatExportSpecifier(specifier) {
1157
- return specifier.local === specifier.exported ? specifier.local : `${specifier.local} as ${specifier.exported}`;
1158
- }
1159
- function uniqueIdentifier(base, code) {
1160
- let candidate = base;
1161
- let index = 0;
1162
- while (identifierNameRE(candidate).test(code)) {
1163
- index++;
1164
- candidate = `${base}${index}`;
1165
- }
1166
- return candidate;
1167
- }
1168
- function isIdentifier(value) {
1169
- return /^[$A-Z_a-z][$\w]*$/.test(value);
1170
- }
1171
- function normalizeVirtualId$2(id) {
1172
- return id.startsWith("\0") ? id.slice(1) : id;
1173
- }
1174
- //#endregion
1175
- //#region ../web/src/debug-channel.ts
1176
- function installDebugChannelLayer(root, initialPhase, initiallyActive = true) {
1177
- const global = globalThis;
1178
- const previous = global.__MARKLESS_DEBUG__?.version === 1 ? global.__MARKLESS_DEBUG__ : void 0;
1179
- let priorRoot;
1180
- try {
1181
- priorRoot = previous?.explainInteraction(root, "__markless_debug_root__");
1182
- } catch {}
1183
- const priorContainer = priorRoot && "containerId" in priorRoot ? previous?.containers.find((entry) => entry.id === priorRoot.containerId) : void 0;
1184
- const seed = `${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
1185
- const id = priorContainer?.id ?? `container:${seed}`;
1186
- const rootKey = priorContainer?.root.key ?? `root:${seed}`;
1187
- const rootRef = new WeakRef(root);
1188
- const events = /* @__PURE__ */ new WeakMap();
1189
- const keys = /* @__PURE__ */ new WeakMap();
1190
- const invalidated = /* @__PURE__ */ new WeakSet();
1191
- const routerSources = global[Symbol.for("markless.debug.channel.v1.router-sources")] ??= /* @__PURE__ */ new Set();
1192
- const ownViolations = [];
1193
- let phase = initialPhase;
1194
- let lifecycle = initiallyActive ? "active" : "registered";
1195
- let boundarySnapshots = Object.freeze([]);
1196
- let nextElement = 1;
1197
- let nextSequence = (previous?.violations.at(-1)?.sequence ?? 0) + 1;
1198
- let dropped = 0;
1199
- let pruned = false;
1200
- const freeze = (value) => Object.freeze(value);
1201
- const contains = (element) => {
1202
- const currentRoot = rootRef.deref();
1203
- return !!currentRoot && (currentRoot === element || currentRoot.contains?.(element) === true);
1204
- };
1205
- const keyFor = (element) => {
1206
- let key = keys.get(element);
1207
- if (!key) {
1208
- key = `${rootKey}:element:${nextElement++}`;
1209
- keys.set(element, key);
1210
- }
1211
- return key;
1212
- };
1213
- const eligibleAnchor = (element) => {
1214
- const anchor = element.closest?.("a[href]");
1215
- if (!anchor?.hasAttribute("data-markless-router-link") || anchor.hasAttribute("download")) return false;
1216
- const target = anchor.getAttribute("target");
1217
- if (target && target !== "_self" || anchor.relList?.contains("external")) return false;
1218
- try {
1219
- const base = global.location?.href ?? "http://localhost/";
1220
- return new URL(anchor.href ?? "", base).origin === new URL(base).origin;
1221
- } catch {
1222
- return false;
1223
- }
1224
- };
1225
- const none = (element, eventName, reason) => freeze({
1226
- kind: "none",
1227
- eventName,
1228
- reason,
1229
- containerId: id,
1230
- elementKey: keyFor(element)
1231
- });
1232
- const explain = (element, eventName) => {
1233
- if (lifecycle === "disposed" && (contains(element) || keys.has(element))) return none(element, eventName, "container-disposed");
1234
- if (!contains(element)) try {
1235
- return previous?.explainInteraction(element, eventName) ?? freeze({
1236
- kind: "none",
1237
- eventName,
1238
- reason: "outside-known-container"
1239
- });
1240
- } catch {
1241
- return freeze({
1242
- kind: "none",
1243
- eventName,
1244
- reason: "outside-known-container"
1245
- });
1246
- }
1247
- if (element.isConnected === false) return none(element, eventName, "element-disconnected");
1248
- if (eligibleAnchor(element)) {
1249
- const source = eventName === "navigate" && routerSources.has("navigation-event") ? "navigation-event" : eventName === "click" && routerSources.has("spa-click-listener") ? "spa-click-listener" : eventName === "click" && routerSources.has("ssr-link-bridge") ? "ssr-link-bridge" : void 0;
1250
- if (source) return freeze({
1251
- kind: "router-delegation",
1252
- source,
1253
- containerId: id,
1254
- elementKey: keyFor(element),
1255
- eventName
1256
- });
1257
- }
1258
- const interaction = events.get(element)?.get(eventName);
1259
- if (interaction) return freeze({ ...interaction });
1260
- if (invalidated.has(element)) return none(element, eventName, "not-registered");
1261
- try {
1262
- const prior = previous?.explainInteraction(element, eventName);
1263
- if (prior && prior.kind !== "none") return prior;
1264
- } catch {}
1265
- return none(element, eventName, "not-registered");
1266
- };
1267
- const cloneJson = (value, seen = /* @__PURE__ */ new Set()) => {
1268
- if (value === null) return null;
1269
- if (typeof value === "boolean" || typeof value === "string") return value;
1270
- if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
1271
- if (!value || typeof value !== "object" || seen.has(value)) return void 0;
1272
- seen.add(value);
1273
- if (Array.isArray(value)) {
1274
- const copy = value.map((entry) => cloneJson(entry, seen));
1275
- return copy.some((entry) => entry === void 0) ? void 0 : freeze(copy);
1276
- }
1277
- if (Object.getPrototypeOf(value) !== Object.prototype) return void 0;
1278
- const copy = {};
1279
- for (const [name, entry] of Object.entries(value)) {
1280
- const cloned = cloneJson(entry, seen);
1281
- if (cloned === void 0) return void 0;
1282
- copy[name] = cloned;
1283
- }
1284
- return freeze(copy);
1285
- };
1286
- const pushViolation = (input) => {
1287
- const cloned = input.details === void 0 ? void 0 : cloneJson(input.details);
1288
- const details = cloned && !Array.isArray(cloned) && typeof cloned === "object" ? cloned : void 0;
1289
- const { details: _details, ...metadata } = input;
1290
- ownViolations.push(freeze({
1291
- ...metadata,
1292
- ...details ? { details } : {},
1293
- sequence: nextSequence++,
1294
- timestamp: Date.now()
1295
- }));
1296
- if (input.details !== void 0 && !details) ownViolations.push(freeze({
1297
- code: "MARKLESS_DEBUG_DETAILS_DROPPED",
1298
- message: "Debug violation details were not JSON-safe and were dropped.",
1299
- sequence: nextSequence++,
1300
- timestamp: Date.now()
1301
- }));
1302
- while (ownViolations.length > 100) {
1303
- ownViolations.shift();
1304
- dropped++;
1305
- }
1306
- };
1307
- const channel = freeze({
1308
- version: 1,
1309
- get containers() {
1310
- const inherited = previous?.containers.filter((entry) => entry.id !== id) ?? [];
1311
- if (pruned || lifecycle === "disposed") return freeze([...inherited]);
1312
- const currentRoot = rootRef.deref();
1313
- const connected = !!currentRoot && currentRoot.isConnected !== false;
1314
- const snapshot = freeze({
1315
- id,
1316
- phase,
1317
- lifecycle: connected ? lifecycle : "disposed",
1318
- root: freeze({
1319
- key: rootKey,
1320
- connected
1321
- }),
1322
- boundaries: freeze([...boundarySnapshots])
1323
- });
1324
- if (!connected) pruned = true;
1325
- return freeze([...inherited, snapshot]);
1326
- },
1327
- get violations() {
1328
- return freeze([...previous?.violations ?? [], ...ownViolations].slice(-100));
1329
- },
1330
- violationCapacity: 100,
1331
- get droppedViolationCount() {
1332
- return (previous?.droppedViolationCount ?? 0) + dropped;
1333
- },
1334
- explainInteraction: explain
1335
- });
1336
- Object.defineProperty(global, "__MARKLESS_DEBUG__", {
1337
- configurable: true,
1338
- enumerable: false,
1339
- value: channel,
1340
- writable: false
1341
- });
1342
- return {
1343
- start(nextPhase, active = true) {
1344
- phase = nextPhase === "ssr-resume" && phase === "csr" ? "csr" : nextPhase;
1345
- if (active) lifecycle = "active";
1346
- return id;
1347
- },
1348
- activate: () => void (lifecycle === "disposed" || (lifecycle = "active")),
1349
- dispose() {
1350
- lifecycle = "disposed";
1351
- boundarySnapshots = freeze([]);
1352
- },
1353
- invalidate(element) {
1354
- events.delete(element);
1355
- invalidated.add(element);
1356
- },
1357
- record(element, eventName, input) {
1358
- if (lifecycle === "disposed") return;
1359
- let byName = events.get(element);
1360
- if (!byName) events.set(element, byName = /* @__PURE__ */ new Map());
1361
- const symbolIds = "symbolIds" in input ? freeze([...input.symbolIds]) : void 0;
1362
- byName.set(eventName, freeze({
1363
- ...input,
1364
- ...symbolIds ? { symbolIds } : {},
1365
- containerId: id,
1366
- elementKey: keyFor(element),
1367
- eventName
1368
- }));
1369
- },
1370
- violation: pushViolation,
1371
- router: (source) => void routerSources.add(source),
1372
- boundaries(value) {
1373
- boundarySnapshots = freeze(value.map((entry) => freeze({ ...entry })));
1374
- },
1375
- disposed: () => lifecycle === "disposed"
1376
- };
1377
- }
1378
- function __marklessDebugBootstrapSource() {
1379
- return `((root,phase,active)=>{const controls=(${installDebugChannelLayer.toString()})(root,phase,active);return Object.freeze({record:(element,eventName,input)=>controls.record(element,eventName,input),router:(source)=>controls.router(source),activate:()=>controls.activate()})})`;
1380
- }
1381
- //#endregion
1382
- //#region src/inline-resumer.ts
1383
- let oxcToolsPromise;
1384
- const compiledSources = /* @__PURE__ */ new Map();
1385
- function loadOxcTools() {
1386
- oxcToolsPromise ??= import("rolldown/experimental").then(({ minifySync, transformSync }) => ({
1387
- minifySync,
1388
- transformSync
1389
- }));
1390
- return oxcToolsPromise;
1391
- }
1392
- function compileInlineResumerSources(options) {
1393
- const cacheKey = `${options.debug ? "debug" : "production"}:${options.executionLog}`;
1394
- let compiled = compiledSources.get(cacheKey);
1395
- if (!compiled) {
1396
- compiled = compileInlineResumerSourceVariants(options);
1397
- compiledSources.set(cacheKey, compiled);
1398
- }
1399
- return compiled;
1400
- }
1401
- async function compileInlineResumerSourceVariants(options) {
1402
- const shared = {
1403
- debug: options.debug,
1404
- executionLog: options.executionLog
1405
- };
1406
- const [event, syncPolicy, graphSyncPolicyOwner, graphSyncPolicyConsumer] = await Promise.all([
1407
- compileInlineResumerSource({
1408
- ...shared,
1409
- graphSyncPolicy: false,
1410
- sharedGraphPolicy: false,
1411
- syncPolicy: false
1412
- }),
1413
- compileInlineResumerSource({
1414
- ...shared,
1415
- graphSyncPolicy: false,
1416
- sharedGraphPolicy: false,
1417
- syncPolicy: true
1418
- }),
1419
- compileInlineResumerSource({
1420
- ...shared,
1421
- graphSyncPolicy: true,
1422
- sharedGraphPolicy: true,
1423
- syncPolicy: true
1424
- }),
1425
- compileInlineResumerSource({
1426
- ...shared,
1427
- graphSyncPolicy: true,
1428
- sharedGraphPolicy: false,
1429
- syncPolicy: true
1430
- })
1431
- ]);
1432
- return {
1433
- ...shared,
1434
- event,
1435
- syncPolicy,
1436
- graphSyncPolicyOwner,
1437
- graphSyncPolicyConsumer
1438
- };
1439
- }
1440
- async function compileInlineResumerSource(options) {
1441
- const source = createInlineResumerSource({
1442
- ...options,
1443
- ...options.debug ? {
1444
- debugBootstrapSource: __marklessDebugBootstrapSource(),
1445
- debugRegistrationSource: createInlineResumerDebugRegistrationSource()
1446
- } : {}
1447
- });
1448
- const { minifySync, transformSync } = await loadOxcTools();
1449
- const transformed = transformSync("markless-inline-resumer.js", source, {
1450
- lang: "js",
1451
- sourceType: "script",
1452
- target: "es2020"
1453
- });
1454
- assertOxcResult("transform", transformed.errors);
1455
- const minified = minifySync("markless-inline-resumer.js", transformed.code, {
1456
- compress: true,
1457
- mangle: { toplevel: true },
1458
- module: false
1459
- });
1460
- assertOxcResult("minify", minified.errors);
1461
- return minified.code.trim();
1462
- }
1463
- function assertOxcResult(phase, errors) {
1464
- if (errors.length === 0) return;
1465
- throw new Error(`MARKLESS_INLINE_RESUMER_${phase.toUpperCase()}_FAILED:\n${errors.map((error) => error.message).join("\n")}`);
1466
- }
1467
- //#endregion
1468
- //#region src/transform.ts
1469
- let oxcTransformSyncPromise;
1470
- function loadOxcTransformSync() {
1471
- oxcTransformSyncPromise ??= import("rolldown/experimental").then((mod) => mod.transformSync, () => void 0);
1472
- return oxcTransformSyncPromise;
1473
- }
1474
- async function stripEmittedTypes(code) {
1475
- const oxcTransformSync = await loadOxcTransformSync();
1476
- if (!oxcTransformSync) return code;
1477
- try {
1478
- const out = oxcTransformSync("markless-emitted.ts", code);
1479
- if (!out.code || (out.errors?.length ?? 0) > 0) return code;
1480
- return out.code;
1481
- } catch {
1482
- return code;
1483
- }
1484
- }
1485
- async function transformTsrxModule(input) {
1486
- const encodedFilename = encodeURIComponent(input.filename);
1487
- const payloadId = `${MARKLESS_VIRTUAL_PREFIX}payload:${encodedFilename}`;
1488
- const resolverId = `${MARKLESS_VIRTUAL_PREFIX}resolver:${encodedFilename}`;
1489
- const resumeId = resumeVirtualModuleId(input.filename);
1490
- const { compiled, blockingDiagnostics } = await compileWithBlockingDiagnostics(input, resolverId);
1491
- throwIfBlocked(input, blockingDiagnostics);
1492
- const symbolRows = compiled.symbolModules.modules.map((module) => ({
1493
- id: module.symbolId,
1494
- chunk: symbolVirtualModuleId(input.filename, module.symbolId),
1495
- exportName: scopedSymbolExportName(input.filename, module.exportName)
1496
- }));
1497
- const importedBoundRows = compiled.boundSymbolResolver.rows.map((row) => row.loaderSymbolId ? {
1498
- ...row,
1499
- baseSymbolId: row.loaderSymbolId
1500
- } : row);
1501
- const resolverSource = adaptImportedCaptureResolver(emitSymbolResolverModule({
1502
- buildId: input.buildId,
1503
- symbols: uniqueSymbolsById([...input.symbols ?? [], ...symbolRows]),
1504
- boundSymbols: importedBoundRows
1505
- }), importedBoundRows.some((row) => row.loaderSymbolId !== void 0));
1506
- const symbolRoutes = compiled.semanticGraph.componentEdges.flatMap((edge, index) => edge.importSource ? [{
1507
- prefix: `c${index}:`,
1508
- importSource: edge.importSource,
1509
- componentEdgeId: edge.id
1510
- }] : []);
1511
- const executionLogModuleHookMode = input.executionLogModuleHooks === false ? "never" : input.executionLog;
1512
- const manifest = {
1513
- source: input.filename,
1514
- captureMetadata: compiled.captureAnalysis,
1515
- symbolRoutes,
1516
- payload: { virtualModuleId: payloadId },
1517
- resolver: { virtualModuleId: resolverId },
1518
- symbols: compiled.symbolModules.modules.map((module, index) => ({
1519
- symbolId: module.symbolId,
1520
- kind: module.kind,
1521
- exportName: symbolRows[index].exportName,
1522
- virtualModuleId: symbolVirtualModuleId(input.filename, module.symbolId)
1523
- })),
1524
- runtimeDemandMap: compiled.runtimeDemandMap
1525
- };
1526
- const styleScope = compiled.publicRenderPlan.styleScopes[0];
1527
- const styleId = styleScope ? `${MARKLESS_VIRTUAL_PREFIX}style:${encodedFilename}.css` : null;
1528
- const virtualModules = [
1529
- ...styleScope && styleId ? [{
1530
- id: styleId,
1531
- type: "style",
1532
- source: styleScope.cssText
1533
- }] : [],
1534
- {
1535
- id: payloadId,
1536
- type: "payload",
1537
- source: payloadModule({
1538
- ...compiled.payloadScripts,
1539
- runtimeDemandMap: compiled.runtimeDemandMap
1540
- })
1541
- },
1542
- {
1543
- id: resolverId,
1544
- type: "resolver",
1545
- source: resolverSource
1546
- },
1547
- {
1548
- id: resumeId,
1549
- type: "resume",
1550
- source: emitResumeModule({
1551
- payloadId,
1552
- resolverId,
1553
- payloadState: compiled.payloadScripts.state,
1554
- payloadView: containerScopedResumeView(compiled.payloadScripts.view),
1555
- runtimeDemandMap: compiled.runtimeDemandMap,
1556
- executionLog: input.executionLog,
1557
- needsFullResume: needsFullResume(compiled.protocolState, compiled.protocolView, compiled.runtimeDemandMap),
1558
- hasBoundSymbols: compiled.boundSymbolResolver.rows.length > 0,
1559
- symbols: symbolRows,
1560
- symbolRoutes
1561
- })
1562
- },
1563
- ...await Promise.all(compiled.symbolModules.modules.map(async (module, index) => ({
1564
- id: symbolVirtualModuleId(input.filename, module.symbolId),
1565
- type: "symbol",
1566
- symbolId: module.symbolId,
1567
- exportName: symbolRows[index].exportName,
1568
- source: injectExecutionLogModuleHook(await stripEmittedTypes(rewriteSymbolModuleExport(module.source, module.exportName, symbolRows[index].exportName)), `symbol:${module.symbolId}`, executionLogModuleHookMode)
1569
- })))
1570
- ];
1571
- const styleImport = styleId ? `import ${JSON.stringify(styleId)};\n` : "";
1572
- const inlineResumerSources = (input.environment ?? "lib") === "client" ? void 0 : await compileInlineResumerSources({
1573
- debug: input.inlineResumerDebug === true,
1574
- executionLog: input.executionLog ?? "never"
1575
- });
1576
- const headInjections = [...input.headInjections ?? [], ...styleId && input.styleModuleUrl ? [{
1577
- tag: "link",
1578
- location: "head",
1579
- attributes: {
1580
- rel: "stylesheet",
1581
- href: input.styleModuleUrl(styleId)
1582
- }
1583
- }] : []];
1584
- const storageSeeds = compiled.payloadArena.state.storage.map((storage) => {
1585
- const binding = compiled.semanticGraph.graphBindings.find((candidate) => candidate.id === storage.graphNodeId);
1586
- if (typeof binding?.initialValue !== "string") throw new Error(`MARKLESS_STORAGE_SEED_FALLBACK_MISSING: ${storage.graphNodeId} has no static string fallback.`);
1587
- return createStorageSeedMetadataFromGraphNodeId(storage.graphNodeId, storage.key, binding.initialValue);
1588
- });
1589
- return {
1590
- code: styleImport + await stripEmittedTypes(emitSourceModule({
1591
- filename: input.filename,
1592
- payloadId,
1593
- resolverId,
1594
- environment: input.environment ?? "lib",
1595
- clientOutput: input.clientOutput ?? "full",
1596
- executionLog: input.executionLog,
1597
- headInjections: headInjections.length > 0 ? headInjections : void 0,
1598
- storageSeeds: storageSeeds.length > 0 ? storageSeeds : void 0,
1599
- inlineResumerSources,
1600
- devResumeReexport: input.devResumeReexport === true,
1601
- needsFullResume: needsFullResume(compiled.protocolState, compiled.protocolView, compiled.runtimeDemandMap),
1602
- resumeModuleUrl: input.resumeModuleUrl,
1603
- publicRenderModuleSource: compiled.publicRenderModule.moduleSource,
1604
- publicRenderRootExportName: compiled.publicRenderModule.rootExportName,
1605
- publicCsrModuleSource: compiled.publicRenderModule.csrModuleSource,
1606
- publicRenderCsrExportName: compiled.publicRenderModule.csrExportName,
1607
- publicSsrModuleSource: compiled.publicRenderModule.ssrModuleSource,
1608
- publicRenderSsrExportName: compiled.publicRenderModule.ssrExportName,
1609
- hasBoundSymbols: compiled.boundSymbolResolver.rows.length > 0,
1610
- symbols: symbolRows,
1611
- symbolRoutes
1612
- })),
1613
- map: null,
1614
- virtualModules,
1615
- manifest
1616
- };
1617
- }
1618
- async function preflightTsrxModuleDiagnostics(input) {
1619
- const { blockingDiagnostics } = await compileWithBlockingDiagnostics(input, `${MARKLESS_VIRTUAL_PREFIX}resolver:${encodeURIComponent(input.filename)}`);
1620
- throwIfBlocked(input, blockingDiagnostics);
1621
- }
1622
- async function compileWithBlockingDiagnostics(input, resolverId) {
1623
- const compiled = await compileTsrxModule({
1624
- filename: input.filename,
1625
- source: input.source,
1626
- buildId: input.buildId,
1627
- resolverId,
1628
- symbols: input.symbols ?? []
1629
- });
1630
- return {
1631
- compiled,
1632
- blockingDiagnostics: collectTsrxModuleDiagnostics(compiled).filter((diagnostic) => diagnostic.severity === "error")
1633
- };
1634
- }
1635
- function throwIfBlocked(input, blockingDiagnostics) {
1636
- if (blockingDiagnostics.length === 0) return;
1637
- const details = formatBlockedCompileError(input, blockingDiagnostics);
1638
- throw new MarklessCompileError(createCompileErrorPayload({
1639
- filename: input.filename,
1640
- source: input.source,
1641
- diagnostics: blockingDiagnostics,
1642
- details
1643
- }));
1644
- }
1645
- function formatBlockedCompileError(input, diagnostics) {
1646
- return [`MARKLESS_COMPILE_BLOCKED: ${input.filename} has ${diagnostics.length} compiler error(s).`, ...diagnostics.map((diagnostic) => {
1647
- const position = diagnostic.primarySpan ? formatSourcePosition(input.source, diagnostic.primarySpan.start) : void 0;
1648
- const location = position ? ` (${diagnostic.primarySpan.filename}:${position.line}:${position.column})` : "";
1649
- return [
1650
- `${diagnostic.code}: ${diagnostic.message}${location}`,
1651
- diagnostic.why,
1652
- diagnostic.suggestions[0]?.message,
1653
- diagnostic.docsUrl
1654
- ].filter((line) => Boolean(line)).join("\n");
1655
- })].join("\n\n");
1656
- }
1657
- function formatSourcePosition(source, start) {
1658
- const sourceBeforeSpan = source.slice(0, start);
1659
- const lastLineBreak = sourceBeforeSpan.lastIndexOf("\n");
1660
- return {
1661
- line: sourceBeforeSpan.split("\n").length,
1662
- column: sourceBeforeSpan.length - lastLineBreak
1663
- };
1664
- }
1665
- function uniqueSymbolsById(symbols) {
1666
- return [...new Map(symbols.map((symbol) => [symbol.id, symbol])).values()];
1667
- }
1668
- function adaptImportedCaptureResolver(source, hasImportedRows) {
1669
- if (!hasImportedRows) return source;
1670
- const original = " return (context) => base({ ...context, capture: createCaptureContext(context, bound) });";
1671
- const replacement = [
1672
- " return async (context) => {",
1673
- " const pendingCallbacks = [];",
1674
- " const capture = createCaptureContext(context, bound);",
1675
- " const result = await base({ ...context, graph: createBoundGraph(context, bound, capture, pendingCallbacks), capture });",
1676
- " await Promise.all(pendingCallbacks);",
1677
- " return result;",
1678
- " };"
1679
- ].join("\n");
1680
- const helper = [
1681
- "function createBoundGraph(context, bound, capture, pendingCallbacks) {",
1682
- " const legacySlots = new Map(bound.captureSlots.flatMap((slot) => slot.legacyGraphRead ? [[JSON.stringify([slot.legacyGraphRead.graphNodeId, slot.legacyGraphRead.path ?? []]), slot]] : []));",
1683
- " return {",
1684
- " ...context.graph,",
1685
- " read(graphNodeId, path = []) {",
1686
- " const slot = legacySlots.get(JSON.stringify([graphNodeId, path]));",
1687
- " if (!slot) return context.graph.read(graphNodeId, path);",
1688
- " if (slot.route.kind === callbackRoute) return (...args) => {",
1689
- " const pending = context.invokeSymbol(slot.route.callbackSymbolId, { ...context, event: context.event, args });",
1690
- " pendingCallbacks.push(Promise.resolve(pending));",
1691
- " return pending;",
1692
- " };",
1693
- " return capture.read(slot.slotId);",
1694
- " },",
1695
- " };",
1696
- "}",
1697
- ""
1698
- ].join("\n");
1699
- return source.replace(original, replacement).replace("function createCaptureContext(context, bound) {", `${helper}function createCaptureContext(context, bound) {`);
1700
- }
1701
- function containerScopedResumeView(view) {
1702
- return {
1703
- ...view,
1704
- locators: (view.locators ?? []).map((locator) => ({
1705
- ...locator,
1706
- index: locator.index + 1
1707
- }))
1708
- };
1709
- }
1710
- function needsFullResume(state, view, runtimeDemandMap) {
1711
- if ((state.storage?.length ?? 0) > 0) return true;
1712
- if ((view.branches?.length ?? 0) > 0) return true;
1713
- if ((view.elementHandles?.length ?? 0) > 0) return true;
1714
- if ((view.asyncBoundaries?.length ?? 0) > 0) return true;
1715
- if ((view.keyedRepeats?.length ?? 0) === 0) return false;
1716
- return !recordKindReplaced(runtimeDemandMap, "keyed-repeat");
1717
- }
1718
- function recordKindReplaced(runtimeDemandMap, kind) {
1719
- return runtimeDemandMap.recordKinds.some((record) => record.kind === kind && record.replaced === true);
1720
- }
1721
- //#endregion
1722
- //#region src/build/symbol-table.ts
1723
- const SYMBOL_VIRTUAL_PREFIX = `${MARKLESS_VIRTUAL_PREFIX}symbol:`;
1724
- const PACKED_SYMBOL_VIRTUAL_LIST_RE = /(["'`])((?:virtual:markless:symbol:)[^"'`]+)\1\.split\(\s*(["'`]),\3\s*\)/g;
1725
- const SYMBOL_VIRTUAL_STRING_RE$1 = /(["'`])((?:virtual:markless:symbol:)[^"'`]+)\1/g;
1726
- const STRING_LIST_SOURCE = String.raw`(?:\[[^\]]*\]|["'\x60][^"'\x60]*["'\x60]\.split\(\s*["'\x60][^"'\x60]*["'\x60]\s*\))`;
1727
- const SYMBOL_MANIFEST_TUPLE_RE = new RegExp(String.raw`(\[1,(?:null|["'\x60][^"'\x60]*["'\x60]),(?:null|["'\x60][^"'\x60]*["'\x60]),)(${STRING_LIST_SOURCE}),(${STRING_LIST_SOURCE}),(\{[^}]*\})(\])`, "g");
1728
- const STRING_LITERAL_RE = /(["'`])([^"'`]*)\1/g;
1729
- const SYMBOL_ROW_RE = /((?:["'`][^"'`]*["'`])\s*:\s*\[)(\d+)(,\s*\d+\])/g;
1730
- const SYMBOL_ROW_CAPTURE_RE = /(["'`])([^"'`]*)\1\s*:\s*\[(\d+),\s*(\d+)\]/g;
1731
- function rewriteGeneratedSymbolTableUrls(bundle) {
1732
- const chunks = collectChunks(bundle);
1733
- const symbolFiles = collectGeneratedSymbolFiles(chunks);
1734
- let rewritten = 0;
1735
- const unresolved = /* @__PURE__ */ new Set();
1736
- for (const chunk of chunks.values()) {
1737
- if (!chunk.code.includes(SYMBOL_VIRTUAL_PREFIX)) continue;
1738
- const result = rewriteSymbolVirtualStrings(chunk, symbolFiles);
1739
- chunk.code = result.code;
1740
- rewritten += result.rewritten;
1741
- for (const id of result.unresolved) unresolved.add(id);
1742
- }
1743
- return {
1744
- rewritten,
1745
- unresolved: [...unresolved].sort()
1746
- };
1747
- }
1748
- /**
1749
- * Checks emitted resolver routes against compiler manifests and Rolldown's
1750
- * chunk ownership/export metadata. Table source is read only to recover each
1751
- * claimed file; termination evidence stays structural.
1752
- */
1753
- function verifyGeneratedSymbolTableRoutes(bundle, manifests) {
1754
- const chunks = collectChunks(bundle);
1755
- const errors = [];
1756
- let verified = 0;
1757
- for (const manifest of manifests) {
1758
- if (manifest.symbols.length === 0) continue;
1759
- const resolverChunk = findResolverRouteChunk(chunks, manifest.resolver.virtualModuleId, manifest.symbols);
1760
- const routeChunk = resolverChunk ?? findChunkForVirtualId(chunks, manifest.source);
1761
- if (!routeChunk) {
1762
- for (const symbol of manifest.symbols) errors.push({
1763
- symbolId: symbol.symbolId,
1764
- claimedChunk: "<missing route chunk>",
1765
- reason: `neither compiler resolver ${manifest.resolver.virtualModuleId} nor source ${manifest.source} was emitted`
1766
- });
1767
- continue;
1768
- }
1769
- const table = resolverChunk ? findSymbolTable(routeChunk.code, manifest.symbols) : void 0;
1770
- for (const symbol of manifest.symbols) {
1771
- if (!table) {
1772
- const directRoute = verifyDirectRoute(chunks, routeChunk, symbol);
1773
- if (directRoute.reason) errors.push({
1774
- symbolId: symbol.symbolId,
1775
- claimedChunk: directRoute.claimedChunk,
1776
- reason: directRoute.reason
1777
- });
1778
- else verified++;
1779
- continue;
1780
- }
1781
- const specifier = tableRouteSpecifier(table, symbol, routeChunk.fileName, errors);
1782
- if (!specifier) continue;
1783
- const claimedChunk = resolveChunkSpecifier(routeChunk.fileName, specifier);
1784
- const reason = routeTerminationError(chunks, claimedChunk, symbol);
1785
- if (reason) errors.push({
1786
- symbolId: symbol.symbolId,
1787
- claimedChunk,
1788
- reason
1789
- });
1790
- else verified++;
1791
- }
1792
- }
1793
- return {
1794
- verified,
1795
- errors
1796
- };
1797
- }
1798
- function collectChunks(bundle) {
1799
- const chunks = /* @__PURE__ */ new Map();
1800
- for (const output of Object.values(bundle)) if (isGeneratedChunk(output)) chunks.set(output.fileName, output);
1801
- return chunks;
1802
- }
1803
- function collectGeneratedSymbolFiles(chunks) {
1804
- const symbolFiles = /* @__PURE__ */ new Map();
1805
- for (const chunk of chunks.values()) {
1806
- const facadeId = chunk.facadeModuleId ? normalizeVirtualId$1(chunk.facadeModuleId) : void 0;
1807
- if (facadeId?.startsWith(SYMBOL_VIRTUAL_PREFIX)) symbolFiles.set(facadeId, chunk.fileName);
1808
- }
1809
- for (const chunk of chunks.values()) for (const id of chunk.moduleIds.map(normalizeVirtualId$1)) if (id.startsWith(SYMBOL_VIRTUAL_PREFIX) && !symbolFiles.has(id)) symbolFiles.set(id, chunk.fileName);
1810
- return symbolFiles;
1811
- }
1812
- function findSymbolTable(code, symbols) {
1813
- let bestMatch;
1814
- let bestScore = -1;
1815
- for (const match of code.matchAll(SYMBOL_MANIFEST_TUPLE_RE)) {
1816
- const moduleUrls = parseStringList(match[2]);
1817
- const exportNames = parseStringList(match[3]);
1818
- if (!moduleUrls || !exportNames) continue;
1819
- const rows = /* @__PURE__ */ new Map();
1820
- for (const row of match[4].matchAll(SYMBOL_ROW_CAPTURE_RE)) rows.set(row[2], [Number(row[3]), Number(row[4])]);
1821
- if (rows.size === 0) continue;
1822
- const score = symbols.filter((symbol) => exportNames.includes(symbol.exportName)).length;
1823
- if (score > bestScore) {
1824
- bestMatch = {
1825
- moduleUrls,
1826
- exportNames,
1827
- rows
1828
- };
1829
- bestScore = score;
1830
- }
1831
- }
1832
- return bestMatch;
1833
- }
1834
- function tableRouteSpecifier(table, symbol, resolverFileName, errors) {
1835
- const row = table.rows.get(symbol.symbolId);
1836
- if (!row) {
1837
- errors.push({
1838
- symbolId: symbol.symbolId,
1839
- claimedChunk: resolverFileName,
1840
- reason: "emitted symbol table has no row for this compiler symbol"
1841
- });
1842
- return;
1843
- }
1844
- const specifier = table.moduleUrls[row[0]];
1845
- if (!specifier) {
1846
- errors.push({
1847
- symbolId: symbol.symbolId,
1848
- claimedChunk: resolverFileName,
1849
- reason: `emitted symbol table references missing module URL index ${row[0]}`
1850
- });
1851
- return;
1852
- }
1853
- const exportName = table.exportNames[row[1]];
1854
- if (exportName !== symbol.exportName) {
1855
- errors.push({
1856
- symbolId: symbol.symbolId,
1857
- claimedChunk: resolveChunkSpecifier(resolverFileName, specifier),
1858
- reason: `emitted symbol table claims export ${exportName ?? `<missing index ${row[1]}>`} instead of ${symbol.exportName}`
1859
- });
1860
- return;
1861
- }
1862
- return specifier;
1863
- }
1864
- function verifyDirectRoute(chunks, routeChunk, symbol) {
1865
- const target = findChunkForVirtualId(chunks, symbol.virtualModuleId);
1866
- if (!target) return {
1867
- claimedChunk: "<missing symbol chunk>",
1868
- reason: `generated symbol module ${symbol.virtualModuleId} was not emitted`
1869
- };
1870
- if (!(target.exports ?? []).includes(symbol.exportName)) return {
1871
- claimedChunk: target.fileName,
1872
- reason: `claimed chunk does not export ${symbol.exportName}`
1873
- };
1874
- if (!dynamicRouteReachesChunk(chunks, routeChunk, target.fileName) && !rewrittenSpecifierRoutesTo(routeChunk, target.fileName)) return {
1875
- claimedChunk: target.fileName,
1876
- reason: `source chunk ${routeChunk.fileName} has no emitted dynamic route to the claimed chunk`
1877
- };
1878
- return { claimedChunk: target.fileName };
1879
- }
1880
- function rewrittenSpecifierRoutesTo(routeChunk, targetFileName) {
1881
- const specifier = relativeChunkSpecifier(routeChunk.fileName, targetFileName);
1882
- return routeChunk.code.includes(JSON.stringify(specifier)) || routeChunk.code.includes(`'${specifier}'`) || routeChunk.code.includes(`\`${specifier}\``);
1883
- }
1884
- function dynamicRouteReachesChunk(chunks, start, targetFileName) {
1885
- const pending = [start];
1886
- const visited = /* @__PURE__ */ new Set();
1887
- while (pending.length > 0) {
1888
- const chunk = pending.shift();
1889
- if (chunk.fileName === targetFileName) return true;
1890
- if (visited.has(chunk.fileName)) continue;
1891
- visited.add(chunk.fileName);
1892
- for (const importedFileName of chunk.dynamicImports ?? []) {
1893
- const imported = chunks.get(importedFileName);
1894
- if (imported) pending.push(imported);
1895
- }
1896
- }
1897
- return false;
1898
- }
1899
- function routeTerminationError(chunks, claimedChunk, symbol) {
1900
- const target = chunks.get(claimedChunk);
1901
- if (!target) return "claimed chunk was not emitted. markless debugging playbook: run pnpm doctor, or read agent/markless.md in the installed @markless/core package";
1902
- if (!chunkOrReexportChainContainsSymbol(chunks, target, normalizeVirtualId$1(symbol.virtualModuleId), symbol.exportName)) return `claimed chunk does not contain its generated symbol module ${symbol.virtualModuleId} or a live re-export chain to it. markless debugging playbook: run pnpm doctor, or read agent/markless.md in the installed @markless/core package`;
1903
- if (!(target.exports ?? []).includes(symbol.exportName)) return `claimed chunk does not export ${symbol.exportName}. markless debugging playbook: run pnpm doctor, or read agent/markless.md in the installed @markless/core package`;
1904
- }
1905
- function chunkOrReexportChainContainsSymbol(chunks, start, virtualId, exportName) {
1906
- const pending = [start];
1907
- const visited = /* @__PURE__ */ new Set();
1908
- while (pending.length > 0) {
1909
- const chunk = pending.shift();
1910
- if (visited.has(chunk.fileName)) continue;
1911
- visited.add(chunk.fileName);
1912
- if (virtualIds(chunk).includes(virtualId) && (chunk.exports ?? []).includes(exportName)) return true;
1913
- if (!(chunk.exports ?? []).includes(exportName)) continue;
1914
- for (const importedFileName of chunk.imports ?? []) {
1915
- const imported = chunks.get(importedFileName);
1916
- if (imported && (imported.exports ?? []).includes(exportName)) pending.push(imported);
1917
- }
1918
- }
1919
- return false;
1920
- }
1921
- function findChunkForVirtualId(chunks, virtualId) {
1922
- const normalized = normalizeVirtualId$1(virtualId);
1923
- return [...chunks.values()].find((chunk) => !!chunk.facadeModuleId && normalizeVirtualId$1(chunk.facadeModuleId) === normalized) ?? [...chunks.values()].find((chunk) => chunk.moduleIds.map(normalizeVirtualId$1).includes(normalized));
1924
- }
1925
- function findResolverRouteChunk(chunks, virtualId, symbols) {
1926
- const normalized = normalizeVirtualId$1(virtualId);
1927
- const candidates = [...chunks.values()].filter((chunk) => virtualIds(chunk).includes(normalized));
1928
- return candidates.find((chunk) => !!findSymbolTable(chunk.code, symbols)) ?? candidates.find((chunk) => chunk.moduleIds.map(normalizeVirtualId$1).includes(normalized)) ?? candidates[0];
1929
- }
1930
- function resolveChunkSpecifier(importerFileName, specifier) {
1931
- if (!specifier.startsWith(".")) return normalize(specifier);
1932
- return normalize(join(dirname(importerFileName), specifier));
1933
- }
1934
- function virtualIds(chunk) {
1935
- return [chunk.facadeModuleId ?? void 0, ...chunk.moduleIds].filter((id) => !!id).map(normalizeVirtualId$1);
1936
- }
1937
- function rewriteSymbolVirtualStrings(chunk, symbolFiles) {
1938
- let rewritten = 0;
1939
- const unresolved = /* @__PURE__ */ new Set();
1940
- return {
1941
- code: compactSymbolManifestTables(chunk.code.replace(PACKED_SYMBOL_VIRTUAL_LIST_RE, (match, _quote, packedVirtualIds) => {
1942
- const virtualIds = packedVirtualIds.split(",");
1943
- if (virtualIds.length < 2 || virtualIds.some((id) => !id.startsWith(SYMBOL_VIRTUAL_PREFIX))) return match;
1944
- return JSON.stringify(virtualIds.map((virtualId) => {
1945
- const fileName = symbolFiles.get(virtualId);
1946
- if (!fileName) return virtualId;
1947
- rewritten++;
1948
- return relativeChunkSpecifier(chunk.fileName, fileName);
1949
- }));
1950
- }).replace(SYMBOL_VIRTUAL_STRING_RE$1, (match, _quote, virtualId) => {
1951
- const fileName = symbolFiles.get(virtualId);
1952
- if (!fileName) {
1953
- unresolved.add(virtualId);
1954
- return match;
1955
- }
1956
- rewritten++;
1957
- return JSON.stringify(relativeChunkSpecifier(chunk.fileName, fileName));
1958
- })),
1959
- rewritten,
1960
- unresolved: [...unresolved]
1961
- };
1962
- }
1963
- function compactSymbolManifestTables(code) {
1964
- return code.replace(SYMBOL_MANIFEST_TUPLE_RE, (match, prefix, moduleUrlsSource, exportNamesSource, symbolRowsSource, suffix) => {
1965
- const moduleUrls = parseStringArray(moduleUrlsSource);
1966
- if (!moduleUrls) return match;
1967
- const nextModuleUrls = [];
1968
- const moduleIndexMap = /* @__PURE__ */ new Map();
1969
- const seen = /* @__PURE__ */ new Map();
1970
- for (const [index, moduleUrl] of moduleUrls.entries()) {
1971
- let nextIndex = seen.get(moduleUrl);
1972
- if (nextIndex === void 0) {
1973
- nextIndex = nextModuleUrls.length;
1974
- seen.set(moduleUrl, nextIndex);
1975
- nextModuleUrls.push(moduleUrl);
1976
- }
1977
- moduleIndexMap.set(index, nextIndex);
1978
- }
1979
- if (nextModuleUrls.length === moduleUrls.length) return match;
1980
- const nextSymbolRows = symbolRowsSource.replace(SYMBOL_ROW_RE, (rowMatch, rowPrefix, moduleIndexSource, rowSuffix) => {
1981
- const moduleIndex = Number(moduleIndexSource);
1982
- const nextModuleIndex = moduleIndexMap.get(moduleIndex);
1983
- if (nextModuleIndex === void 0) return rowMatch;
1984
- return `${rowPrefix}${nextModuleIndex}${rowSuffix}`;
1985
- });
1986
- return `${prefix}${JSON.stringify(nextModuleUrls)},${exportNamesSource},${nextSymbolRows}${suffix}`;
1987
- });
1988
- }
1989
- function parseStringArray(source) {
1990
- const values = [];
1991
- let end = 1;
1992
- for (const match of source.matchAll(STRING_LITERAL_RE)) {
1993
- values.push(match[2]);
1994
- end = (match.index ?? 0) + match[0].length;
1995
- }
1996
- if (source.slice(end).trim() !== "]") return void 0;
1997
- return values;
1998
- }
1999
- function parseStringList(source) {
2000
- if (source.startsWith("[")) return parseStringArray(source);
2001
- const packed = source.match(/^(["'`])([^"'`]*)\1\.split\(\s*(["'`])([^"'`]*)\3\s*\)$/);
2002
- return packed ? packed[2].split(packed[4]) : void 0;
2003
- }
2004
- function relativeChunkSpecifier(importerFileName, targetFileName) {
2005
- const value = relative(dirname(importerFileName), targetFileName).replaceAll("\\", "/");
2006
- return value.startsWith(".") ? value : `./${value}`;
2007
- }
2008
- function isGeneratedChunk(value) {
2009
- if (!value || typeof value !== "object") return false;
2010
- const chunk = value;
2011
- return chunk.type === "chunk" && typeof chunk.fileName === "string" && typeof chunk.code === "string" && Array.isArray(chunk.moduleIds);
2012
- }
2013
- function normalizeVirtualId$1(id) {
2014
- return id.startsWith("\0") ? id.slice(1) : id;
2015
- }
2016
- //#endregion
2017
- //#region src/dev.ts
2018
- function createMarklessDevGraph() {
2019
- const parentModules = /* @__PURE__ */ new Map();
2020
- return {
2021
- record(parent, ids, environment) {
2022
- const entries = [...ids];
2023
- for (const path of parentKeys(parent)) {
2024
- const key = parentKey(environment, path);
2025
- const existing = parentModules.get(key) ?? /* @__PURE__ */ new Set();
2026
- for (const id of entries) existing.add(id);
2027
- parentModules.set(key, existing);
2028
- }
2029
- },
2030
- clear(parent, environment) {
2031
- const deleted = [];
2032
- for (const currentEnvironment of targetEnvironments(environment)) for (const path of parentKeys(parent)) {
2033
- const key = parentKey(currentEnvironment, path);
2034
- const ids = parentModules.get(key);
2035
- if (!ids) continue;
2036
- deleted.push(...ids);
2037
- parentModules.delete(key);
2038
- }
2039
- return [...new Set(deleted)];
2040
- },
2041
- reset() {
2042
- parentModules.clear();
2043
- }
2044
- };
2045
- }
2046
- function targetEnvironments(environment) {
2047
- if (environment) return [environment];
2048
- return allEnvironments;
2049
- }
2050
- const allEnvironments = [
2051
- "client",
2052
- "server",
2053
- "lib"
2054
- ];
2055
- function parentKeys(parent) {
2056
- const path = pathname$1(parent);
2057
- const normalized = normalize(path);
2058
- const leadingPath = withLeadingSlash(normalized);
2059
- const barePath = leadingPath.slice(1);
2060
- return new Set([
2061
- path,
2062
- normalized,
2063
- leadingPath,
2064
- barePath
2065
- ]);
2066
- }
2067
- function parentKey(environment, parent) {
2068
- return `${environment}:${parent}`;
2069
- }
2070
- function pathname$1(id) {
2071
- return parsePath(id).pathname;
2072
- }
2073
- //#endregion
2074
- //#region src/rolldown.ts
2075
- const TSRX_SOURCE_FILE = /\.tsrx(?:[?#].*)?$/;
2076
- const MARKLESS_SYMBOL_SOURCE_QUERY_RE = /[?&]markless-symbols(?:[&#]|$)/;
2077
- const MARKLESS_RESUME_SOURCE_QUERY_RE = /[?&]markless-resume(?:[&#]|$)/;
2078
- const RESUME_VIRTUAL_ID_RE = /^virtual:markless:resume:([^:]+)$/;
2079
- const SYMBOL_VIRTUAL_STRING_RE = /(["'`])((?:virtual:markless:symbol:)[^"'`]+)\1/g;
2080
- const marklessClient = (options = {}) => createMarklessRolldownPlugin({
2081
- environment: "client",
2082
- options
2083
- });
2084
- const marklessServer = (options = {}) => createMarklessRolldownPlugin({
2085
- environment: "server",
2086
- options
2087
- });
2088
- const marklessLib = (options = {}) => createMarklessRolldownPlugin({
2089
- environment: "lib",
2090
- options
2091
- });
2092
- function createMarklessRolldownPlugin(input) {
2093
- const environment = input.environment;
2094
- const internalOptions = input.options ?? {};
2095
- const virtualModules = /* @__PURE__ */ new Map();
2096
- const transformManifests = /* @__PURE__ */ new Map();
2097
- const importedChildren = /* @__PURE__ */ new Map();
2098
- const importedChildSources = /* @__PURE__ */ new Set();
2099
- const emittedClientResolverSources = /* @__PURE__ */ new Set();
2100
- const sourceVirtualModules = /* @__PURE__ */ new Map();
2101
- const clientSymbolEntrySources = /* @__PURE__ */ new Set();
2102
- const executionLogEstimatedSizes = /* @__PURE__ */ new Map();
2103
- const dev = createMarklessDevGraph();
2104
- let root = internalOptions.rootDir;
2105
- const name = pluginName(environment);
2106
- function getEnvironment(context) {
2107
- if (typeof environment === "function") return environment(context);
2108
- return environment;
2109
- }
2110
- function getRoot() {
2111
- return root ?? internalOptions.rootDir;
2112
- }
2113
- return {
2114
- api: { invalidateGeneratedModules(parent, currentEnvironment) {
2115
- const ids = dev.clear(parent, currentEnvironment);
2116
- const resolvedIds = /* @__PURE__ */ new Set();
2117
- for (const id of ids) {
2118
- const type = virtualModules.get(id)?.type;
2119
- virtualModules.delete(id);
2120
- const resolvedId = resolveVirtualId(id);
2121
- resolvedIds.add(resolvedId);
2122
- if (type === "style") resolvedIds.add(`${resolvedId}?direct`);
2123
- }
2124
- if ((currentEnvironment === "client" || currentEnvironment === void 0 && environment === "client") && internalOptions.dev === true && normalizeExecutionLogMode(internalOptions.executionLog) !== "never") resolvedIds.add(resolveVirtualId(MARKLESS_EXECUTION_LOG_MODULE_ID));
2125
- return [...resolvedIds];
2126
- } },
2127
- name,
2128
- options(input) {
2129
- if (getEnvironment(this) !== "client") return input;
2130
- return {
2131
- ...input,
2132
- preserveEntrySignatures: input.preserveEntrySignatures ?? "allow-extension"
2133
- };
2134
- },
2135
- async buildStart(input) {
2136
- if (!root) root = internalOptions.rootDir ?? input.cwd;
2137
- clientSymbolEntrySources.clear();
2138
- virtualModules.clear();
2139
- transformManifests.clear();
2140
- importedChildren.clear();
2141
- importedChildSources.clear();
2142
- emittedClientResolverSources.clear();
2143
- sourceVirtualModules.clear();
2144
- executionLogEstimatedSizes.clear();
2145
- dev.reset();
2146
- const currentRoot = getRoot();
2147
- if (getEnvironment(this) === "client") for (const source of clientSymbolEntries(input.input, currentRoot)) clientSymbolEntrySources.add(source);
2148
- },
2149
- outputOptions(output) {
2150
- return outputDefaults(output, getEnvironment(this));
2151
- },
2152
- async resolveId(source, importer) {
2153
- if (source.startsWith("@markless/web/fns/")) {
2154
- const resolved = import.meta.resolve(source);
2155
- if (resolved?.startsWith("file://")) return { id: decodeURIComponent(resolved.slice(7)) };
2156
- }
2157
- if (source.startsWith("@markless/web/inline/")) {
2158
- const resolvedRoot = import.meta.resolve("@markless/web");
2159
- if (resolvedRoot?.startsWith("file://") && resolvedRoot.endsWith("/index.ts")) {
2160
- const helperPath = source.slice(14);
2161
- return { id: decodeURIComponent(resolvedRoot.slice(7, -8) + `${helperPath}.ts`) };
2162
- }
2163
- }
2164
- const normalized = normalizeVirtualId(source);
2165
- if (normalized === "virtual:markless:dev-log") return {
2166
- id: resolveVirtualId(MARKLESS_EXECUTION_LOG_MODULE_ID),
2167
- moduleSideEffects: true
2168
- };
2169
- const virtualModule = virtualModules.get(normalized);
2170
- if (virtualModule) {
2171
- const directQuery = virtualModule.type === "style" && /(?:[?&])direct(?:[=&]|$)/.test(source) ? "?direct" : "";
2172
- return {
2173
- id: `${resolveVirtualId(normalized)}${directQuery}`,
2174
- moduleSideEffects: true
2175
- };
2176
- }
2177
- const symbolSource = sourceForSymbolVirtualImporter(importer);
2178
- if (symbolSource && isRelativeImport(source)) return await this.resolve(source, symbolSource, { skipSelf: true });
2179
- const resumeSource = sourceForResumeVirtualImporter(importer);
2180
- if (resumeSource && isRelativeImport(source)) return await this.resolve(source, resumeSource, { skipSelf: true });
2181
- return null;
2182
- },
2183
- load(id) {
2184
- if (normalizeVirtualId(id) === "virtual:markless:dev-log") {
2185
- const embedsDevSizes = internalOptions.dev === true && getEnvironment(this) === "client";
2186
- return executionLogVirtualModuleSource({
2187
- moduleSizes: embedsDevSizes ? executionLogEstimatedSizes : void 0,
2188
- attribution: embedsDevSizes ? executionAttributionTables(transformManifests, getRoot(), importedChildren.values()) : void 0,
2189
- sizesUrl: internalOptions.dev === true ? void 0 : internalOptions.publicPath?.(MARKLESS_EXECUTION_SIZES) ?? `/${MARKLESS_EXECUTION_SIZES}`
2190
- });
2191
- }
2192
- const module = virtualModules.get(normalizeVirtualId(id));
2193
- if (module) return virtualModuleSourceForLoad(module, {
2194
- dev: internalOptions.dev === true && getEnvironment(this) === "client",
2195
- publicPath: internalOptions.publicPath
2196
- });
2197
- return null;
2198
- },
2199
- async transform(code, id) {
2200
- const currentEnvironment = getEnvironment(this);
2201
- const virtualId = normalizeVirtualId(id);
2202
- if (!TSRX_SOURCE_FILE.test(id)) {
2203
- if (currentEnvironment === "client" && internalOptions.dev === true && normalizeExecutionLogMode(internalOptions.executionLog) !== "never" && isMarklessRuntimeModule(id)) {
2204
- executionLogEstimatedSizes.set(executionLogRuntimeModuleId(id), code.length);
2205
- return {
2206
- code: injectExecutionLogModuleHook(code, executionLogRuntimeModuleId(id), internalOptions.executionLog),
2207
- map: null
2208
- };
2209
- }
2210
- return null;
2211
- }
2212
- if (virtualId.startsWith("virtual:markless:")) return null;
2213
- const source = pathname(id);
2214
- clearSourceVirtualModules(source, virtualModules, sourceVirtualModules);
2215
- let transformed = await transformTsrxModule({
2216
- filename: source,
2217
- source: code,
2218
- buildId: internalOptions.buildId,
2219
- executionLog: normalizeExecutionLogMode(internalOptions.executionLog),
2220
- executionLogModuleHooks: internalOptions.dev === true && currentEnvironment === "client",
2221
- inlineResumerDebug: internalOptions.inlineResumerDebug === true,
2222
- environment: currentEnvironment,
2223
- clientOutput: currentEnvironment === "client" && (clientSymbolEntrySources.has(source) || isSymbolOnlySourceRequest(id)) ? "symbols-only" : void 0,
2224
- resumeModuleUrl: internalOptions.dev === true && currentEnvironment === "server" ? devBrowserSourceModuleUrl(source, getRoot(), internalOptions.publicPath) : void 0,
2225
- styleModuleUrl: internalOptions.dev === true && currentEnvironment === "server" ? (virtualId) => withQuery(devBrowserVirtualModuleUrl(virtualId, internalOptions.publicPath), { direct: null }) : void 0,
2226
- headInjections: internalOptions.dev === true && currentEnvironment === "server" ? internalOptions.devInjections : void 0,
2227
- devResumeReexport: internalOptions.dev === true && currentEnvironment === "client"
2228
- });
2229
- registerTransformArtifacts({
2230
- source,
2231
- result: transformed,
2232
- virtualModules,
2233
- transformManifests,
2234
- sourceVirtualModules,
2235
- executionLogEstimatedSizes,
2236
- dev,
2237
- environment: currentEnvironment
2238
- });
2239
- const resolvedChildren = await resolveImportedChildren.call(this, source, transformed.manifest);
2240
- for (const child of resolvedChildren) {
2241
- importedChildren.set(importedChildKey(child), child);
2242
- importedChildSources.add(child.source);
2243
- }
2244
- for (const child of resolvedChildren) {
2245
- if (!transformManifests.has(child.source)) {
2246
- if (internalOptions.dev === true) await internalOptions.devServer?.transformRequest(child.source, currentEnvironment);
2247
- else if (typeof this.load === "function") await this.load({ id: child.source });
2248
- }
2249
- if (internalOptions.dev === true) validateImportedChild(child, transformManifests);
2250
- }
2251
- if (resolvedChildren.length > 0) transformed = await transformTsrxModule({
2252
- filename: source,
2253
- source: code,
2254
- buildId: internalOptions.buildId,
2255
- symbols: importedSymbolInputs(resolvedChildren, transformManifests),
2256
- executionLog: normalizeExecutionLogMode(internalOptions.executionLog),
2257
- executionLogModuleHooks: internalOptions.dev === true && currentEnvironment === "client",
2258
- inlineResumerDebug: internalOptions.inlineResumerDebug === true,
2259
- environment: currentEnvironment,
2260
- clientOutput: currentEnvironment === "client" && (clientSymbolEntrySources.has(source) || isSymbolOnlySourceRequest(id)) ? "symbols-only" : void 0,
2261
- resumeModuleUrl: internalOptions.dev === true && currentEnvironment === "server" ? devBrowserSourceModuleUrl(source, getRoot(), internalOptions.publicPath) : void 0,
2262
- styleModuleUrl: internalOptions.dev === true && currentEnvironment === "server" ? (virtualId) => withQuery(devBrowserVirtualModuleUrl(virtualId, internalOptions.publicPath), { direct: null }) : void 0,
2263
- headInjections: internalOptions.dev === true && currentEnvironment === "server" ? internalOptions.devInjections : void 0,
2264
- devResumeReexport: internalOptions.dev === true && currentEnvironment === "client"
2265
- });
2266
- registerTransformArtifacts({
2267
- source,
2268
- result: transformed,
2269
- virtualModules,
2270
- transformManifests,
2271
- sourceVirtualModules,
2272
- executionLogEstimatedSizes,
2273
- dev,
2274
- environment: currentEnvironment
2275
- });
2276
- for (const child of resolvedChildren) dev.record(child.source, [transformed.manifest.resolver.virtualModuleId], currentEnvironment);
2277
- if (currentEnvironment === "client" && isResumeSourceRequest(id)) {
2278
- const resumeModule = transformed.virtualModules.find((module) => module.type === "resume");
2279
- if (resumeModule) return {
2280
- code: resumeModule.source,
2281
- map: null
2282
- };
2283
- }
2284
- if (currentEnvironment === "client" && !internalOptions.dev) for (const module of transformed.virtualModules.filter((item) => {
2285
- if (item.type === "symbol") return true;
2286
- if (item.type === "resolver") return (importedChildSources.has(source) || (transformed.manifest.captureMetadata?.boundResolverRows?.length ?? 0) > 0) && !emittedClientResolverSources.has(source);
2287
- return item.type === "resume" && internalOptions.emitResumeModules === true && clientSymbolEntrySources.has(source);
2288
- })) {
2289
- this.emitFile({
2290
- type: "chunk",
2291
- id: module.id,
2292
- preserveSignature: "strict"
2293
- });
2294
- if (module.type === "resolver") emittedClientResolverSources.add(source);
2295
- }
2296
- return transformed;
2297
- },
2298
- generateBundle: {
2299
- order: "post",
2300
- async handler(_, bundle) {
2301
- for (const child of importedChildren.values()) validateImportedChild(child, transformManifests);
2302
- if (getEnvironment(this) !== "client") return;
2303
- stripEmptyPreloadWrappersFromChunks(bundle);
2304
- const removedSymbolFacades = rewriteGeneratedSymbolFacadeImports(bundle);
2305
- rewriteGeneratedSymbolInitExports(bundle);
2306
- compactGeneratedDirectSymbolLoaders(bundle);
2307
- const manifestBundle = bundleWithoutRemovedChunks(bundle, removedSymbolFacades);
2308
- const tableRewrite = rewriteGeneratedSymbolTableUrls(manifestBundle);
2309
- if (tableRewrite.unresolved.length > 0) this.error(`Markless symbol resolver table contains unresolved generated symbol chunks: ${tableRewrite.unresolved.join(", ")}. markless debugging playbook: run pnpm doctor, or read agent/markless.md in the installed @markless/core package`);
2310
- const tableIntegrity = verifyGeneratedSymbolTableRoutes(manifestBundle, transformManifests.values());
2311
- if (tableIntegrity.errors.length > 0) this.error(`Markless symbol resolver table integrity check failed:\n${tableIntegrity.errors.map((error) => `- ${error.symbolId} -> ${error.claimedChunk}: ${error.reason}`).join("\n")}`);
2312
- const clientManifest = createBuildMetadata(manifestBundle, transformManifests.values(), getRoot(), {
2313
- bundleGraphAsset: MARKLESS_BUNDLE_GRAPH,
2314
- bundleGraphAdders: internalOptions.bundleGraphAdders,
2315
- canonPath: stripBuildPrefix,
2316
- publicPath: internalOptions.publicPath,
2317
- injections: internalOptions.devInjections
2318
- });
2319
- const executionLogInjection = executionLogActivationInjection(internalOptions.executionLog);
2320
- if (executionLogInjection) injectHeadLinks(bundle, [executionLogInjection]);
2321
- injectHeadLinks(bundle, collectModulePreloadInjections(clientManifest, {
2322
- publicPath: internalOptions.publicPath,
2323
- entryChunks: Object.values(bundle).filter((output) => !!output && typeof output === "object" && output.type === "chunk" && output.isEntry === true).map((chunk) => stripBuildPrefix(chunk.fileName))
2324
- }));
2325
- this.emitFile({
2326
- type: "asset",
2327
- fileName: MARKLESS_BUNDLE_GRAPH,
2328
- source: JSON.stringify(clientManifest.bundleGraph)
2329
- });
2330
- this.emitFile(await createExecutionSizesAsset(manifestBundle, clientManifest, stripBuildPrefix, executionLogInjection ? executionAttributionTables(transformManifests, getRoot(), importedChildren.values()) : void 0));
2331
- this.emitFile({
2332
- type: "asset",
2333
- fileName: `${MARKLESS_BUILD_PREFIX}execution-demand.json`,
2334
- source: JSON.stringify(Object.fromEntries(clientManifest.modules.filter((module) => module.runtimeDemandMap).map((module) => [module.source, module.runtimeDemandMap])))
2335
- });
2336
- }
2337
- }
2338
- };
2339
- }
2340
- async function resolveImportedChildren(parent, manifest) {
2341
- return await Promise.all((manifest.symbolRoutes ?? []).map(async (route) => {
2342
- const resolvedImport = await this.resolve(route.importSource, parent, { skipSelf: true });
2343
- const resolvedId = typeof resolvedImport === "string" ? resolvedImport : resolvedImport && typeof resolvedImport === "object" && "id" in resolvedImport ? String(resolvedImport.id) : fallbackImportedSource(parent, route.importSource);
2344
- return {
2345
- parent,
2346
- specifier: route.importSource,
2347
- source: pathname(resolvedId),
2348
- componentEdgeId: route.componentEdgeId
2349
- };
2350
- }));
2351
- }
2352
- function importedSymbolInputs(children, manifests) {
2353
- return children.flatMap((child) => {
2354
- const manifest = manifests.get(child.source);
2355
- if (!manifest?.captureMetadata || !child.componentEdgeId) return [];
2356
- return manifest.symbols.flatMap((symbol) => {
2357
- const captureSymbol = manifest.captureMetadata?.extractedSymbols.find((candidate) => candidate.symbolId === symbol.symbolId);
2358
- return captureSymbol?.captureSlots.some((slot) => slot.propName !== void 0) ? [{
2359
- id: `imported:${encodeURIComponent(child.source)}:${symbol.symbolId}`,
2360
- chunk: symbol.virtualModuleId,
2361
- exportName: symbol.exportName,
2362
- componentEdgeId: child.componentEdgeId,
2363
- captureSymbol
2364
- }] : [];
2365
- });
2366
- });
2367
- }
2368
- function fallbackImportedSource(parent, specifier) {
2369
- const source = specifier.split("?")[0];
2370
- return isRelativeImport(source) ? resolve(dirname(parent), source) : source;
2371
- }
2372
- function importedChildKey(child) {
2373
- return `${child.parent}\0${child.specifier}\0${child.source}`;
2374
- }
2375
- function validateImportedChild(child, manifests) {
2376
- const parentMetadata = manifests.get(child.parent)?.captureMetadata;
2377
- const childMetadata = manifests.get(child.source)?.captureMetadata;
2378
- if (!childMetadata && isPlainTypeScriptSource(child.source)) return;
2379
- if (parentMetadata && childMetadata?.passId === parentMetadata.passId && Array.isArray(childMetadata.extractedSymbols) && Array.isArray(childMetadata.diagnostics)) return;
2380
- throw new Error(`MARKLESS_CAPTURE_METADATA_MISSING: Parent module ${JSON.stringify(child.parent)} composes imported child ${JSON.stringify(child.specifier)}, but its compiled artifact has no current capture metadata. Rebuild the child with the current Markless compiler and clear any stale build cache.`);
2381
- }
2382
- function isPlainTypeScriptSource(source) {
2383
- return /\.[cm]?tsx?$/.test(source);
2384
- }
2385
- function executionAttributionRoots(manifests, childrenByRoute) {
2386
- const children = /* @__PURE__ */ new Set();
2387
- for (const manifest of manifests.values()) for (const route of manifest.symbolRoutes ?? []) {
2388
- const child = resolvedRouteSource(manifest.source, route.importSource, childrenByRoute);
2389
- if (manifests.has(child)) children.add(child);
2390
- }
2391
- return [...manifests.keys()].filter((source) => !children.has(source));
2392
- }
2393
- function executionAttributionTables(manifests, root, children) {
2394
- const childrenByRoute = new Map([...children].map((child) => [routeKey(child.parent, child.specifier), child.source]));
2395
- return Object.fromEntries(executionAttributionRoots(manifests, childrenByRoute).sort().map((source) => [executionAttributionRouteKey(source, root), flattenExecutionAttributionScopes(source, manifests, childrenByRoute)]));
2396
- }
2397
- function executionAttributionRouteKey(source, root) {
2398
- const prefix = root ? `${root.replace(/[/\\]+$/, "")}/` : "";
2399
- return (prefix && source.startsWith(prefix) ? source.slice(prefix.length) : source).replace(/^[/\\]+/, "");
2400
- }
2401
- function flattenExecutionAttributionScopes(root, manifests, childrenByRoute) {
2402
- const scopes = {};
2403
- const visit = (source, scope, seen) => {
2404
- if (seen.has(source)) return;
2405
- scopes[scope] = encodedSymbolSource(source);
2406
- const manifest = manifests.get(source);
2407
- for (const route of manifest?.symbolRoutes ?? []) {
2408
- const child = resolvedRouteSource(source, route.importSource, childrenByRoute);
2409
- if (!manifests.has(child)) continue;
2410
- visit(child, scope + route.prefix, new Set([...seen, source]));
2411
- }
2412
- };
2413
- visit(root, "", /* @__PURE__ */ new Set());
2414
- return scopes;
2415
- }
2416
- function resolvedRouteSource(parent, specifier, childrenByRoute) {
2417
- return childrenByRoute.get(routeKey(parent, specifier)) ?? fallbackImportedSource(parent, specifier);
2418
- }
2419
- function routeKey(parent, specifier) {
2420
- return `${parent}\0${specifier}`;
2421
- }
2422
- function bundleWithoutRemovedChunks(bundle, removedFileNames) {
2423
- if (removedFileNames.size === 0) return bundle;
2424
- const next = {};
2425
- for (const [key, output] of Object.entries(bundle)) {
2426
- if (isChunkFile(output) && removedFileNames.has(output.fileName)) continue;
2427
- next[key] = output;
2428
- }
2429
- return next;
2430
- }
2431
- function stripEmptyPreloadWrappersFromChunks(bundle) {
2432
- for (const output of Object.values(bundle)) {
2433
- if (!isChunkWithCode(output)) continue;
2434
- const nextCode = stripEmptyVitePreloadWrappers(output.code);
2435
- if (nextCode !== output.code) output.code = nextCode;
2436
- }
2437
- }
2438
- function isChunkFile(output) {
2439
- if (!output || typeof output !== "object") return false;
2440
- const chunk = output;
2441
- return chunk.type === "chunk" && typeof chunk.fileName === "string";
2442
- }
2443
- function isChunkWithCode(output) {
2444
- if (!output || typeof output !== "object") return false;
2445
- const chunk = output;
2446
- return chunk.type === "chunk" && typeof chunk.code === "string";
2447
- }
2448
- function pluginName(environment) {
2449
- if (typeof environment === "function") return "markless:rolldown";
2450
- return `markless:rolldown:${environment}`;
2451
- }
2452
- function registerTransformArtifacts(input) {
2453
- const ids = /* @__PURE__ */ new Set();
2454
- for (const module of input.result.virtualModules) {
2455
- const isClientSymbol = input.environment === "client" && module.type === "symbol";
2456
- const stored = isClientSymbol ? {
2457
- ...module,
2458
- source: requalifyExecutionLogModuleHook(module.source, module.id)
2459
- } : module;
2460
- input.virtualModules.set(module.id, stored);
2461
- ids.add(module.id);
2462
- if (isClientSymbol) input.executionLogEstimatedSizes.set(module.id, stored.source.length);
2463
- }
2464
- input.transformManifests.set(input.source, input.result.manifest);
2465
- input.sourceVirtualModules.set(input.source, ids);
2466
- input.dev.record(input.source, ids, input.environment);
2467
- }
2468
- function clearSourceVirtualModules(source, virtualModules, sourceVirtualModules) {
2469
- const stale = sourceVirtualModules.get(source);
2470
- if (!stale) return;
2471
- for (const id of stale) virtualModules.delete(id);
2472
- sourceVirtualModules.delete(source);
2473
- }
2474
- function stripBuildPrefix(fileName) {
2475
- return fileName.startsWith(MARKLESS_BUILD_PREFIX) ? fileName.slice(MARKLESS_BUILD_PREFIX.length) : fileName;
2476
- }
2477
- function virtualModuleSourceForLoad(module, options) {
2478
- if (!options.dev || module.type !== "resolver") return module.source;
2479
- if (!module.source.includes("moduleUrls[row[0]]")) return module.source;
2480
- return module.source.replace(SYMBOL_VIRTUAL_STRING_RE, (_match, _quote, virtualId) => JSON.stringify(devBrowserVirtualModuleUrl(virtualId, options.publicPath)));
2481
- }
2482
- function devBrowserSourceModuleUrl(source, _root, publicPath) {
2483
- const path = withQuery(joinURL("@fs", withoutLeadingSlash(source)), { import: null });
2484
- return publicPath ? publicPath(path) : joinURL("/", path);
2485
- }
2486
- function devBrowserVirtualModuleUrl(virtualId, publicPath) {
2487
- const path = joinURL("@id", resolveVirtualId(virtualId).replace("\0", "__x00__"));
2488
- return publicPath ? publicPath(path) : joinURL("/", path);
2489
- }
2490
- function clientSymbolEntries(input, root) {
2491
- if (!input || typeof input !== "object" || Array.isArray(input)) return [];
2492
- const sources = [];
2493
- for (const [name, value] of Object.entries(input)) {
2494
- if (!/symbol/i.test(name)) continue;
2495
- for (const entry of inputEntryValues(value)) if (typeof entry === "string" && TSRX_SOURCE_FILE.test(entry)) sources.push(normalizeInputSource(entry, root));
2496
- }
2497
- return sources;
2498
- }
2499
- function inputEntryValues(value) {
2500
- return Array.isArray(value) ? value.flatMap(inputEntryValues) : [value];
2501
- }
2502
- function normalizeInputSource(source, root) {
2503
- const path = pathname(source);
2504
- if (isAbsolute(path)) return path;
2505
- return pathname(resolve(root ?? "", path));
2506
- }
2507
- function isSymbolOnlySourceRequest(id) {
2508
- return MARKLESS_SYMBOL_SOURCE_QUERY_RE.test(id);
2509
- }
2510
- function isResumeSourceRequest(id) {
2511
- return MARKLESS_RESUME_SOURCE_QUERY_RE.test(id);
2512
- }
2513
- function sourceForSymbolVirtualImporter(importer) {
2514
- if (!importer) return null;
2515
- return symbolVirtualModuleSourceFile(normalizeVirtualId(importer));
2516
- }
2517
- function sourceForResumeVirtualImporter(importer) {
2518
- if (!importer) return null;
2519
- const match = normalizeVirtualId(importer).match(RESUME_VIRTUAL_ID_RE);
2520
- return match?.[1] ? decodeURIComponent(match[1]) : null;
2521
- }
2522
- function isRelativeImport(source) {
2523
- return source.startsWith("./") || source.startsWith("../");
2524
- }
2525
- function isMarklessRuntimeModule(id) {
2526
- const path = pathname(id);
2527
- return /[/\\](?:web|runtime|serializer)[/\\]src[/\\].+\.ts$/.test(path);
2528
- }
2529
- function executionLogRuntimeModuleId(id) {
2530
- const path = pathname(id);
2531
- const match = path.match(/[/\\](web|runtime|serializer)[/\\]src[/\\]([^?#]+)\.ts$/);
2532
- return match ? `${match[1]}:${match[2].replace(/[/\\]/g, "/")}` : path;
2533
- }
2534
- function normalizeVirtualId(id) {
2535
- const bare = id.startsWith("\0") ? id.slice(1) : id;
2536
- if (!bare.startsWith("virtual:markless:")) return bare;
2537
- const queryIndex = bare.indexOf("?");
2538
- return `${MARKLESS_VIRTUAL_PREFIX}${(queryIndex === -1 ? bare : bare.slice(0, queryIndex)).slice(MARKLESS_VIRTUAL_PREFIX.length).split(":").map((segment) => {
2539
- try {
2540
- return encodeURIComponent(decodeURIComponent(segment));
2541
- } catch {
2542
- return segment;
2543
- }
2544
- }).join(":")}`;
2545
- }
2546
- function resolveVirtualId(id) {
2547
- if (id.startsWith("\0")) return id;
2548
- return `\0${id}`;
2549
- }
2550
- function pathname(id) {
2551
- return parsePath(id).pathname;
2552
- }
2553
- //#endregion
2554
- export { preflightTsrxModuleDiagnostics as a, collectHeadLinkInjections as c, marklessServer as i, convertManifestToBundleGraph as l, marklessClient as n, transformTsrxModule as o, marklessLib as r, createBuildMetadata as s, createMarklessRolldownPlugin as t, createPreloadGraphAdder as u };