@markless/bundler 0.1.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.
@@ -0,0 +1,876 @@
1
+ import { joinURL } from "ufo";
2
+ //#region src/build/preload-plan.ts
3
+ const DEFAULT_MIN_PROBABILITY = 0;
4
+ const JAVASCRIPT_MODULE_RE = /\.(?:mjs|js)(?:[?#].*)?$/;
5
+ const PRIORITY_RANK = {
6
+ high: 2,
7
+ auto: 1,
8
+ low: 0
9
+ };
10
+ function planModulePreloadUrls(input) {
11
+ return planModulePreloads(input).map((preload) => preload.href);
12
+ }
13
+ function planModulePreloads(input) {
14
+ const minProbability = input.minProbability ?? DEFAULT_MIN_PROBABILITY;
15
+ const maxPreloads = input.maxPreloads ?? Number.POSITIVE_INFINITY;
16
+ const graph = parseBundleGraph(input.bundleGraph);
17
+ const planned = /* @__PURE__ */ new Map();
18
+ const bestVisitByNode = /* @__PURE__ */ new Map();
19
+ let order = 0;
20
+ const addModule = (name, probability, priority, fetchPriority) => {
21
+ if (!isPreloadableModuleName(name)) return;
22
+ const href = preloadHref(input.base, name);
23
+ const existing = planned.get(href);
24
+ const nextRank = PRIORITY_RANK[priority];
25
+ const existingRank = existing ? PRIORITY_RANK[existing.priority] : -1;
26
+ if (existing && (existingRank > nextRank || existingRank === nextRank && existing.probability >= probability)) return;
27
+ planned.set(href, {
28
+ fetchPriority,
29
+ href,
30
+ name,
31
+ order: existing?.order ?? order++,
32
+ priority,
33
+ probability
34
+ });
35
+ };
36
+ const visit = (name, probability, priority, fetchPriority, seen, suppressed = false) => {
37
+ if (probability < minProbability || planned.size >= maxPreloads) return;
38
+ if (!suppressed) {
39
+ const priorityRank = PRIORITY_RANK[priority];
40
+ const previousBest = bestVisitByNode.get(name);
41
+ if (previousBest && (previousBest.priorityRank > priorityRank || previousBest.priorityRank === priorityRank && previousBest.probability >= probability)) return;
42
+ bestVisitByNode.set(name, {
43
+ priorityRank,
44
+ probability
45
+ });
46
+ }
47
+ if (seen.has(name)) return;
48
+ const nextSeen = new Set(seen);
49
+ nextSeen.add(name);
50
+ const record = graph.get(name);
51
+ if (!record) {
52
+ if (!suppressed) addModule(name, probability, priority, fetchPriority);
53
+ return;
54
+ }
55
+ for (const dep of record.deps.filter((item) => item.kind === "static")) visit(dep.name, probability * dep.probability, priority, fetchPriority, nextSeen, suppressed);
56
+ if (!suppressed) addModule(name, probability, priority, fetchPriority);
57
+ for (const dep of record.deps.filter((item) => item.kind === "dynamic")) {
58
+ const edgeProbability = JAVASCRIPT_MODULE_RE.test(name) ? dep.probability : 1;
59
+ visit(dep.name, probability * edgeProbability, priority, fetchPriority, nextSeen, false);
60
+ }
61
+ };
62
+ for (const root of input.roots) {
63
+ const normalized = normalizeRoot(root);
64
+ visit(normalized.name, 1, normalized.priority, normalized.fetchPriority, /* @__PURE__ */ new Set(), normalized.edges === "dynamic-only");
65
+ }
66
+ return [...planned.values()].sort((left, right) => {
67
+ const priority = PRIORITY_RANK[right.priority] - PRIORITY_RANK[left.priority];
68
+ if (priority !== 0) return priority;
69
+ return left.order - right.order;
70
+ }).slice(0, maxPreloads).map(({ order: _order, ...preload }) => preload);
71
+ }
72
+ function parseBundleGraph(graph) {
73
+ const records = /* @__PURE__ */ new Map();
74
+ if (!graph) return records;
75
+ let index = 0;
76
+ while (index < graph.length) {
77
+ const name = graph[index++];
78
+ if (typeof name !== "string") continue;
79
+ const deps = [];
80
+ let probability = 1;
81
+ let kind = "static";
82
+ while (typeof graph[index] === "number") {
83
+ const marker = graph[index++];
84
+ if (marker < 0) {
85
+ probability = -marker / 10;
86
+ kind = "dynamic";
87
+ continue;
88
+ }
89
+ const dep = graph[marker];
90
+ if (typeof dep === "string") deps.push({
91
+ name: dep,
92
+ kind,
93
+ probability
94
+ });
95
+ }
96
+ records.set(name, {
97
+ name,
98
+ deps
99
+ });
100
+ }
101
+ return records;
102
+ }
103
+ function preloadHref(base, name) {
104
+ if (!base || /^(?:[a-z]+:)?\/\//i.test(name)) return name;
105
+ return joinURL(base, name);
106
+ }
107
+ function isPreloadableModuleName(name) {
108
+ return JAVASCRIPT_MODULE_RE.test(name) || isViteDevModuleUrl(name);
109
+ }
110
+ function isViteDevModuleUrl(name) {
111
+ return (name.startsWith("/") || name.startsWith("@id/")) && /(?:^|[?&])import(?:[&#]|$)/.test(name);
112
+ }
113
+ function normalizeRoot(root) {
114
+ if (typeof root === "string") return {
115
+ name: root,
116
+ priority: "auto",
117
+ fetchPriority: "auto"
118
+ };
119
+ const priority = root.priority ?? "auto";
120
+ return {
121
+ name: root.name,
122
+ priority,
123
+ edges: root.edges,
124
+ fetchPriority: root.fetchPriority ?? priorityToFetchPriority(priority)
125
+ };
126
+ }
127
+ function priorityToFetchPriority(priority) {
128
+ if (priority === "auto") return "auto";
129
+ return priority;
130
+ }
131
+ const MARKLESS_BUILD_PREFIX = `build/`;
132
+ const MARKLESS_BUNDLE_GRAPH = `${MARKLESS_BUILD_PREFIX}bundle-graph.json`;
133
+ const WEB_RUNTIME_CAPABILITY_GROUPS = [
134
+ {
135
+ name: "markless-resume-branches",
136
+ test: fileBasenamePattern("resume-branches")
137
+ },
138
+ {
139
+ name: "markless-resume-behaviors",
140
+ test: fileBasenamePattern("resume-behaviors")
141
+ },
142
+ {
143
+ name: "markless-resume-repeats",
144
+ test: fileBasenamePattern("resume-keyed-repeats", "repeat-runtime")
145
+ },
146
+ {
147
+ name: "markless-resume-async",
148
+ test: fileBasenamePattern("resume-async-boundaries", "resume-async-wiring")
149
+ },
150
+ {
151
+ name: "markless-resume-shared-patch",
152
+ test: fileBasenamePattern("resume-shared-patch")
153
+ },
154
+ {
155
+ name: "markless-resume-runtime",
156
+ test: fileBasenamePattern("resume-runtime")
157
+ },
158
+ {
159
+ name: "markless-resume-runtime-start",
160
+ test: fileBasenamePattern("resume-runtime-start")
161
+ },
162
+ {
163
+ name: "markless-resume-runtime-shared",
164
+ test: fileBasenamePattern("resume-runtime-shared")
165
+ },
166
+ {
167
+ name: "markless-resume-events",
168
+ test: fileBasenamePattern("resume-events")
169
+ },
170
+ {
171
+ name: "markless-resume-handoff",
172
+ test: fileBasenamePattern("resume-handoff")
173
+ },
174
+ {
175
+ name: "markless-resume-locators",
176
+ test: fileBasenamePattern("resume-locators")
177
+ },
178
+ {
179
+ name: "markless-resume-errors",
180
+ test: fileBasenamePattern("resume-errors")
181
+ },
182
+ {
183
+ name: "markless-resume-sync-computed",
184
+ test: fileBasenamePattern("resume-sync-computed")
185
+ },
186
+ {
187
+ name: "markless-resume-sync-demand",
188
+ test: fileBasenamePattern("resume-sync-demand")
189
+ },
190
+ {
191
+ name: "markless-payload-full",
192
+ test: fileBasenamePattern("payload-full")
193
+ },
194
+ {
195
+ name: "markless-payload-resume",
196
+ test: fileBasenamePattern("payload-resume")
197
+ },
198
+ {
199
+ name: "markless-inline-payload-document",
200
+ test: /[/\\]web[/\\]src[/\\]inline[/\\]payload-document\.ts(?:[?#].*)?$/
201
+ },
202
+ {
203
+ name: "markless-payload-document",
204
+ test: fileBasenamePattern("payload-document", "payload-resume-registry")
205
+ },
206
+ {
207
+ name: "markless-payload-graph-construct",
208
+ test: fileBasenamePattern("payload-graph-construct")
209
+ },
210
+ {
211
+ name: "markless-dom-journal",
212
+ test: fileBasenamePattern("dom-journal")
213
+ },
214
+ {
215
+ name: "markless-protocol-decode",
216
+ test: fileBasenamePattern("protocol-client", "protocol-state")
217
+ },
218
+ {
219
+ name: "markless-value-decode",
220
+ test: fileBasenamePattern("value-decode-client", "value-decode-extensions")
221
+ },
222
+ {
223
+ name: "markless-payload-leaves",
224
+ test: fileBasenamePattern("payload", "payload-document")
225
+ },
226
+ {
227
+ name: "markless-dev-log",
228
+ test: /virtual:markless:dev-log|[/\\]web[/\\]src[/\\]dev-log\.ts(?:[?#].*)?$/
229
+ },
230
+ {
231
+ name: "markless-resume-core",
232
+ test: fileBasenamePattern("resume")
233
+ },
234
+ {
235
+ name: "markless-runtime-graph-core",
236
+ test: fileBasenamePattern("graph-core")
237
+ },
238
+ {
239
+ name: "markless-runtime-graph-collections",
240
+ test: fileBasenamePattern("graph-collections")
241
+ },
242
+ {
243
+ name: "markless-runtime-graph-computed",
244
+ test: fileBasenamePattern("graph-computed")
245
+ },
246
+ {
247
+ name: "markless-runtime-graph-async",
248
+ test: fileBasenamePattern("graph-async")
249
+ },
250
+ {
251
+ name: "markless-runtime-graph-scheduler",
252
+ test: fileBasenamePattern("graph-scheduler")
253
+ },
254
+ {
255
+ name: "markless-runtime-graph-shared",
256
+ test: fileBasenamePattern("graph-shared")
257
+ },
258
+ {
259
+ name: "markless-graph",
260
+ test: /[/\\](?:runtime[/\\]src[/\\](?!graph-(?:core|collections|computed|async|scheduler|shared)\.ts)|core[/\\]src[/\\]runtime)[/\\]?/
261
+ },
262
+ {
263
+ name: "markless-serializer",
264
+ test: /[/\\]serializer[/\\]src[/\\](?!protocol-validation)/
265
+ }
266
+ ];
267
+ function fileBasenamePattern(...names) {
268
+ return new RegExp(`[/\\\\](?:${names.join("|")})\\.ts(?:[?#].*)?$`);
269
+ }
270
+ const MARKLESS_RUNTIME_GROUPS = [...WEB_RUNTIME_CAPABILITY_GROUPS, {
271
+ name: "markless-runtime",
272
+ test: /[/\\]@markless[/\\]runtime[/\\]/
273
+ }];
274
+ function outputDefaults(output, environment) {
275
+ if (environment === "lib") return output;
276
+ const next = {
277
+ ...output,
278
+ hoistTransitiveImports: false
279
+ };
280
+ if (environment === "server") {
281
+ next.entryFileNames ??= "[name].js";
282
+ next.chunkFileNames ??= "chunk-[hash].js";
283
+ next.codeSplitting = marklessCodeSplitting(next.codeSplitting);
284
+ return next;
285
+ }
286
+ next.entryFileNames ??= `${MARKLESS_BUILD_PREFIX}chunk-[hash].js`;
287
+ next.chunkFileNames ??= `${MARKLESS_BUILD_PREFIX}chunk-[hash].js`;
288
+ next.minifyInternalExports = true;
289
+ next.strictExecutionOrder = true;
290
+ next.codeSplitting = marklessCodeSplitting(next.codeSplitting);
291
+ return next;
292
+ }
293
+ function marklessCodeSplitting(codeSplitting) {
294
+ if (typeof codeSplitting === "boolean") throw new Error("@markless/bundler requires output.codeSplitting to be an object so runtime chunks can be grouped.");
295
+ return {
296
+ ...codeSplitting,
297
+ groups: [...MARKLESS_RUNTIME_GROUPS, ...codeSplitting?.groups ?? []]
298
+ };
299
+ }
300
+ //#endregion
301
+ //#region src/execution-log.ts
302
+ const MARKLESS_EXECUTION_LOG_MODULE_ID = "virtual:markless:dev-log";
303
+ const MARKLESS_EXECUTION_SIZES = `${MARKLESS_BUILD_PREFIX}execution-sizes.json`;
304
+ function normalizeExecutionLogMode(mode) {
305
+ return mode ?? "auto";
306
+ }
307
+ function injectExecutionLogModuleHook(source, moduleId, mode) {
308
+ if (normalizeExecutionLogMode(mode) === "never") return source;
309
+ return `globalThis.__mxLog?.add(${JSON.stringify(moduleId)});\n${source}`;
310
+ }
311
+ const EXECUTION_LOG_HOOK_LINE = /^globalThis\.__mxLog\?\.add\("(?:[^"\\]|\\.)*"\);\n/;
312
+ function requalifyExecutionLogModuleHook(source, moduleId) {
313
+ if (!EXECUTION_LOG_HOOK_LINE.test(source)) return source;
314
+ return source.replace(EXECUTION_LOG_HOOK_LINE, `globalThis.__mxLog?.add(${JSON.stringify(moduleId)});\n`);
315
+ }
316
+ function executionLogVirtualModuleSource(options = {}) {
317
+ if (!options.moduleSizes) return executionLogVirtualModuleSourceWithOwnSize(options, null);
318
+ return executionLogVirtualModuleSourceWithOwnSize(options, executionLogVirtualModuleSourceWithOwnSize(options, 0).length);
319
+ }
320
+ function executionLogVirtualModuleSourceWithOwnSize(options, ownRawSize) {
321
+ const moduleSizes = options.moduleSizes ? Object.fromEntries([...[...options.moduleSizes].map(([id, raw]) => [id, {
322
+ raw,
323
+ estimated: true
324
+ }]), [MARKLESS_EXECUTION_LOG_MODULE_ID, {
325
+ raw: ownRawSize ?? 0,
326
+ estimated: true
327
+ }]]) : null;
328
+ return `
329
+ globalThis.__mxLog?.add(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)});
330
+ const marklessDefaultModuleSizes = ${JSON.stringify(moduleSizes)};
331
+ const marklessSizesUrl = ${JSON.stringify(options.sizesUrl ?? null)};
332
+ let marklessSizesPromise;
333
+ function modules(log) { return log ? [...log] : []; }
334
+ function sizeRecord(input) { return !input ? undefined : typeof input === 'number' ? { raw: input, estimated: true } : input; }
335
+ function normalizeSizes(input) { if (!input) return undefined; const map = new Map(); for (const id of Object.keys(input)) map.set(id, sizeRecord(input[id])); return map; }
336
+ async function loadModuleSizes(input) {
337
+ if (input.moduleSizes) return normalizeSizes(input.moduleSizes);
338
+ if (marklessDefaultModuleSizes) return normalizeSizes(marklessDefaultModuleSizes);
339
+ if (!marklessSizesUrl) return undefined;
340
+ marklessSizesPromise ||= fetch(marklessSizesUrl).then((response) => response.ok ? response.json() : undefined).then(normalizeSizes).catch(() => undefined);
341
+ return marklessSizesPromise;
342
+ }
343
+ function symbolParts(id) { const match = /^virtual:markless:symbol:([^:]+):([^:]+)$/.exec(id); if (!match) return null; try { return { source: decodeURIComponent(match[1]), symbolId: decodeURIComponent(match[2]) }; } catch { return null; } }
344
+ function canonicalId(id, sizes) {
345
+ if (!sizes || sizes.has(id)) return id;
346
+ const local = id.replace(/^(?:c\\d+:)+/, '');
347
+ if (!local.startsWith('symbol:')) return id;
348
+ const matches = [...sizes.keys()].filter((key) => { const parts = symbolParts(key); return !!parts && parts.symbolId === local; });
349
+ return matches.length === 1 ? matches[0] : id;
350
+ }
351
+ function displayId(id) { const parts = symbolParts(id); return parts ? parts.symbolId + ' (' + (parts.source.split('/').pop() || parts.source) + ')' : id; }
352
+ function kb(items, sizes) {
353
+ if (!sizes) return items.length === 1 ? '1 module' : items.length + ' modules';
354
+ const records = [...new Set(items.map((id) => canonicalId(id, sizes)))].map((id) => sizes.get(id)).filter(Boolean); const est = [...sizes.values()].some((record) => record.estimated); let total = 0;
355
+ for (const record of records) total += record.estimated ? record.raw : (record.gzip || record.raw || 0);
356
+ return (total / 1024).toFixed(1) + ' KB' + (est ? ' est.' : '');
357
+ }
358
+ function bytesText(items, sizes) { return !sizes ? (items.length === 1 ? '1 module executed' : items.length + ' modules executed') : kb(items, sizes) + ' executed'; }
359
+ function warmIds(event) { return [...new Set([event.dispatchModuleId, ...((event.eventRecord && event.eventRecord.symbolIds) || [])].filter(Boolean))]; }
360
+ function causeRows(input) {
361
+ const before = input.before || new Set(); const after = input.after || new Set(); const woken = [...after].filter((id) => !before.has(id)); const record = input.eventRecord;
362
+ const cause = record ? input.eventName + ' matched event record ' + record.hostNodeId : input.eventName + ' matched runtime records';
363
+ const label = (id) => displayId(canonicalId(id, input.moduleSizes));
364
+ const rows = woken.map((id) => 'woke ' + label(id) + (input.moduleSizes ? ' (' + kb([id], input.moduleSizes) + ')' : '') + ' <- ' + cause);
365
+ if (record) for (const id of warmIds(input)) rows.push('ran warm ' + label(id) + (input.moduleSizes ? ' (' + kb([id], input.moduleSizes) + ')' : '') + ' <- ' + cause);
366
+ if (record && !(input.view?.behaviors || []).some((b) => b.hostNodeId === record.hostNodeId)) rows.push('skip behavior — no matching record touched');
367
+ return rows;
368
+ }
369
+ function mirror(text) {
370
+ const root = document.documentElement; if (!root) return;
371
+ const count = Number(root.getAttribute('data-markless-log-interactions') || '0') + 1;
372
+ root.setAttribute('data-markless-log-interactions', String(count)); root.setAttribute('data-markless-log-last', text);
373
+ }
374
+ export async function installMarklessExecutionLog(input = {}) {
375
+ const log = globalThis.__mxLog; if (!log || log.__marklessInstalled) return;
376
+ log.__marklessInstalled = true;
377
+ const moduleSizes = await loadModuleSizes(input); const preloaded = input.preloadedModuleCount || document.querySelectorAll('link[rel="modulepreload"]').length; const current = modules(log);
378
+ if (input.printResumeSummary !== false) {
379
+ const summary = 'markless: resumed — ' + bytesText(current, moduleSizes) + ', ' + preloaded + ' modules preloaded (' + current.length + ' executed)';
380
+ console.log(summary); document.documentElement?.setAttribute('data-markless-log-summary', summary);
381
+ }
382
+ globalThis.__mxLogInteraction = (event) => {
383
+ const after = modules(log); const before = event.before || new Set(); const woken = after.filter((id) => !before.has(id)); const warm = warmIds(event);
384
+ if (event.noMatch) {
385
+ const line = 'markless: ' + event.eventName + ' [' + (event.selector || 'event target') + '] — no event record matched (0.0 KB)';
386
+ console.info(line); mirror(line); return;
387
+ }
388
+ const header = 'markless: ' + event.eventName + ' [' + (event.selector || 'event target') + '] · woke ' + woken.length + ' modules · ran warm ' + warm.length + ' modules · ' + kb([...new Set([...woken, ...warm])], moduleSizes);
389
+ console.groupCollapsed(header);
390
+ for (const row of causeRows({ ...event, after: new Set(after), moduleSizes })) console.log(row);
391
+ console.groupEnd(); mirror(header);
392
+ };
393
+ }
394
+ export async function logMarklessInteraction(event) { await installMarklessExecutionLog({ printResumeSummary: false }); globalThis.__mxLogInteraction?.(event); }
395
+ export async function logMarklessRenderSummary(input = {}) {
396
+ const log = globalThis.__mxLog; if (!log) return;
397
+ const moduleSizes = await loadModuleSizes(input); const current = modules(log);
398
+ const summary = 'markless: rendered — ' + current.length + ' ' + (current.length === 1 ? 'module' : 'modules') + ' executed (' + kb(current, moduleSizes) + ')';
399
+ console.log(summary); document.documentElement?.setAttribute('data-markless-log-summary', summary);
400
+ }
401
+ `;
402
+ }
403
+ async function createExecutionSizesAsset(bundle, metadata, canonPath = (fileName) => fileName) {
404
+ const entries = {};
405
+ const symbolLogIdsByChunk = /* @__PURE__ */ new Map();
406
+ for (const module of metadata.modules) for (const symbol of module.symbols) {
407
+ if (!symbol.fileName) continue;
408
+ const chunk = symbolLogIdsByChunk.get(symbol.fileName) ?? [];
409
+ chunk.push(stripResolvedIdMarker(symbol.virtualModuleId));
410
+ symbolLogIdsByChunk.set(symbol.fileName, chunk);
411
+ }
412
+ for (const item of Object.values(bundle)) {
413
+ if (item.type !== "chunk") continue;
414
+ const chunk = canonPath(item.fileName);
415
+ const logIds = new Set([...item.moduleIds.flatMap((id) => chunkModuleLogId(id) ?? []), ...symbolLogIdsByChunk.get(chunk) ?? []]);
416
+ if (logIds.size === 0) continue;
417
+ const size = {
418
+ raw: item.code.length,
419
+ gzip: await gzipByteLength(item.code),
420
+ chunk
421
+ };
422
+ for (const id of logIds) entries[id] = size;
423
+ }
424
+ return {
425
+ type: "asset",
426
+ fileName: MARKLESS_EXECUTION_SIZES,
427
+ source: JSON.stringify(sortRecord(entries))
428
+ };
429
+ }
430
+ function executionLogActivationInjection(mode) {
431
+ if (normalizeExecutionLogMode(mode) === "never") return null;
432
+ return {
433
+ tag: "script",
434
+ location: "head",
435
+ children: `(() => { const l = location; if (${mode === "always" ? "true" : "/^https?:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::|$)/.test(l.origin) || new URLSearchParams(l.search).has('markless-log') || (() => { try { return localStorage.getItem('marklessLog') === '1'; } catch { return false; } })()"}) globalThis.__mxLog = globalThis.__mxLog || new Set(); })();`
436
+ };
437
+ }
438
+ function chunkModuleLogId(id) {
439
+ const path = stripResolvedIdMarker(id);
440
+ if (path === "virtual:markless:dev-log") return path;
441
+ const match = path.match(/[/\\](web|runtime|serializer)[/\\]src[/\\]([^?#]+)\.ts$/);
442
+ return match ? `${match[1]}:${match[2].replace(/[/\\]/g, "/")}` : null;
443
+ }
444
+ function stripResolvedIdMarker(id) {
445
+ return id.startsWith("\0") ? id.slice(1) : id;
446
+ }
447
+ async function gzipByteLength(code) {
448
+ const encoded = new TextEncoder().encode(code);
449
+ const reader = new ReadableStream({ start(controller) {
450
+ controller.enqueue(encoded);
451
+ controller.close();
452
+ } }).pipeThrough(new CompressionStream("gzip")).getReader();
453
+ let total = 0;
454
+ while (true) {
455
+ const { done, value } = await reader.read();
456
+ if (done) break;
457
+ total += value.byteLength;
458
+ }
459
+ return total;
460
+ }
461
+ function sortRecord(record) {
462
+ const next = {};
463
+ for (const key of Object.keys(record).sort()) next[key] = record[key];
464
+ return next;
465
+ }
466
+ //#endregion
467
+ //#region src/source-module.ts
468
+ const MARKLESS_VIRTUAL_PREFIX = "virtual:markless:";
469
+ const SMALL_SYMBOL_DIRECT_LOAD_LIMIT = 8;
470
+ const SYMBOL_VIRTUAL_PREFIX = `${MARKLESS_VIRTUAL_PREFIX}symbol:`;
471
+ function symbolVirtualModuleId(filename, symbolId) {
472
+ return `${SYMBOL_VIRTUAL_PREFIX}${encodeURIComponent(filename)}:${encodeURIComponent(symbolId)}`;
473
+ }
474
+ function symbolVirtualModuleSourceFile(moduleId) {
475
+ const bare = moduleId.startsWith("\0") ? moduleId.slice(1) : moduleId;
476
+ if (!bare.startsWith(SYMBOL_VIRTUAL_PREFIX)) return null;
477
+ const encoded = bare.slice(SYMBOL_VIRTUAL_PREFIX.length);
478
+ const separator = encoded.indexOf(":");
479
+ if (separator <= 0 || separator === encoded.length - 1) return null;
480
+ if (encoded.includes(":", separator + 1)) return null;
481
+ try {
482
+ return decodeURIComponent(encoded.slice(0, separator));
483
+ } catch {
484
+ return null;
485
+ }
486
+ }
487
+ function resumeVirtualModuleId(filename) {
488
+ return `${MARKLESS_VIRTUAL_PREFIX}resume:${encodeURIComponent(filename)}`;
489
+ }
490
+ function scopedSymbolExportName(filename, exportName) {
491
+ return `${exportName}_${stringHash(filename)}`;
492
+ }
493
+ function rewriteSymbolModuleExport(source, fromExportName, toExportName) {
494
+ return source.replace(`export function ${fromExportName}`, `export function ${toExportName}`).replace(`export async function ${fromExportName}`, `export async function ${toExportName}`);
495
+ }
496
+ function payloadModule(payload) {
497
+ return [
498
+ `export const state = ${JSON.stringify(payload.state, null, " ")};`,
499
+ `export const runtimeDemandMap = ${JSON.stringify(payload.runtimeDemandMap, null, " ")};`,
500
+ `export const view = ${JSON.stringify(payload.view, null, " ")};`,
501
+ ""
502
+ ].join("\n");
503
+ }
504
+ function emitSourceModule(input) {
505
+ const symbolsOnly = input.environment === "client" && input.clientOutput === "symbols-only";
506
+ const routeSymbols = input.environment === "client" && input.symbolRoutes.length > 0;
507
+ return [
508
+ symbolsOnly ? "" : `import { state as payloadState, view as payloadView, runtimeDemandMap as payloadRuntimeDemandMap } from '${input.payloadId}';`,
509
+ "",
510
+ emitLoadSymbol(input),
511
+ input.environment === "client" && input.executionLog !== "never" ? emitExecutionLogLoader() : "",
512
+ routeSymbols ? "const marklessLoadLocalSymbol = loadSymbol;" : "",
513
+ symbolsOnly && !routeSymbols ? "export { loadSymbol };" : "",
514
+ symbolsOnly ? "" : "export { payloadView };",
515
+ symbolsOnly ? "" : "export { payloadRuntimeDemandMap };",
516
+ input.devResumeReexport && input.environment === "client" ? `export { resumeContainerEvent } from '${resumeVirtualModuleId(input.filename)}';` : "",
517
+ "",
518
+ input.environment === "server" || symbolsOnly ? "" : input.publicRenderModuleSource,
519
+ input.environment === "server" || symbolsOnly ? "" : input.publicCsrModuleSource,
520
+ input.environment === "client" ? "" : input.publicSsrModuleSource,
521
+ routeSymbols ? emitLazySymbolRouteFunction(input.symbolRoutes, "marklessSsrLoadSymbolRoute", "marklessLoadLocalSymbol") : "",
522
+ symbolsOnly && routeSymbols ? "export { marklessSsrLoadSymbolRoute as loadSymbol };" : "",
523
+ symbolsOnly ? "" : emitCompiledAppDefault({
524
+ environment: input.environment,
525
+ executionLog: input.executionLog,
526
+ headInjections: input.headInjections,
527
+ resumeModuleUrl: input.resumeModuleUrl,
528
+ rootExportName: input.publicRenderRootExportName,
529
+ csrExportName: input.publicRenderCsrExportName,
530
+ ssrExportName: input.publicRenderSsrExportName
531
+ }),
532
+ ""
533
+ ].filter((line) => line !== null).join("\n");
534
+ }
535
+ function emitResumeModule(input) {
536
+ const routeSymbols = input.symbolRoutes.length > 0;
537
+ const resumeSymbolLoader = routeSymbols ? "marklessSsrLoadSymbolRoute" : "loadSymbol";
538
+ const scalarSpecializations = scalarDispatcherSpecializations(input);
539
+ return [
540
+ `import { runtimeDemandMap as payloadRuntimeDemandMap } from '${input.payloadId}';`,
541
+ scalarSpecializations.length > 0 ? [
542
+ "import { marklessDecodeScalarCell, marklessFindElementAtDomOrderIndex, marklessReadScalarCell, marklessScalarSpecializedError } from '@markless/web/fns/scalar-specialized';",
543
+ "import { marklessWriteScalar } from '@markless/web/fns/write-scalar';",
544
+ "import { marklessUpdateText } from '@markless/web/fns/update-text';"
545
+ ].join("\n") : "",
546
+ "",
547
+ input.executionLog === "never" ? "" : emitExecutionLogLoader(),
548
+ "",
549
+ emitLoadSymbol(input),
550
+ routeSymbols ? "const marklessLoadLocalSymbol = loadSymbol;" : "",
551
+ routeSymbols ? emitLazySymbolRouteFunction(input.symbolRoutes, "marklessSsrLoadSymbolRoute", "marklessLoadLocalSymbol") : "",
552
+ routeSymbols ? "export { marklessSsrLoadSymbolRoute as loadSymbol };" : "",
553
+ emitResumeContainerEvent(resumeSymbolLoader, input.needsFullResume ?? false, input.symbolRoutes.length > 0 ? "none" : leanResumeMode(input.runtimeDemandMap), scalarSpecializations, input.runtimeDemandMap),
554
+ ""
555
+ ].filter((line) => line !== null).join("\n");
556
+ }
557
+ function emitLazySymbolRouteFunction(routes, functionName, fallbackName = "loadSymbol") {
558
+ if (routes.length === 0) return "";
559
+ return [
560
+ `function ${functionName}(symbolId) {`,
561
+ ...routes.flatMap((route) => [
562
+ ` if (symbolId.startsWith(${JSON.stringify(route.prefix)})) {`,
563
+ ` return import(${JSON.stringify(symbolRouteImportSource(route.importSource))}).then((mod) => mod.loadSymbol ? mod.loadSymbol(symbolId.slice(${route.prefix.length})) : Promise.reject(new Error(\`Unknown child async symbol \${symbolId}\`)));`,
564
+ " }"
565
+ ]),
566
+ ` return ${fallbackName}(symbolId);`,
567
+ "}"
568
+ ].join("\n");
569
+ }
570
+ function symbolRouteImportSource(importSource) {
571
+ return importSource.includes("?") ? `${importSource}&markless-symbols` : `${importSource}?markless-symbols`;
572
+ }
573
+ function emitCompiledAppDefault(input) {
574
+ const renderCsrEntry = (input.rootExportName || input.csrExportName) && input.environment !== "server" ? [` renderCsr: ${input.rootExportName ?? input.csrExportName},`] : [];
575
+ const renderSsrEntry = input.ssrExportName && input.environment !== "client" ? [
576
+ " renderSsr(props, marklessRenderContext) {",
577
+ ` return ${input.ssrExportName}(props, marklessRenderContext);`,
578
+ " },"
579
+ ] : [];
580
+ const resumeModuleEntry = input.resumeModuleUrl && input.environment !== "client" ? [` resumeModuleUrl: ${JSON.stringify(input.resumeModuleUrl)},`] : [];
581
+ const headInjectionEntry = input.headInjections?.length && input.environment !== "client" ? [` headInjections: ${JSON.stringify(input.headInjections)},`] : [];
582
+ const modulePreloadEntry = input.resumeModuleUrl && input.environment === "server" ? [` modulePreloads: [{ href: ${JSON.stringify(input.resumeModuleUrl)}, fetchPriority: "high" }],`] : [];
583
+ const metadataEntries = input.environment === "client" ? [] : [
584
+ ...headInjectionEntry,
585
+ ...resumeModuleEntry,
586
+ ...modulePreloadEntry,
587
+ input.executionLog && input.executionLog !== "never" ? ` executionLog: ${JSON.stringify(input.executionLog)},` : "",
588
+ " payloadView,"
589
+ ];
590
+ return [
591
+ "const marklessCompiledApp = {",
592
+ ...renderCsrEntry,
593
+ ...renderSsrEntry,
594
+ ...metadataEntries,
595
+ "};",
596
+ "export default marklessCompiledApp;"
597
+ ].join("\n");
598
+ }
599
+ function emitResumeContainerEvent(loadSymbolName, needsFullResume, leanMode, scalarSpecializations, runtimeDemandMap) {
600
+ const fullResumeHandoff = [
601
+ "async function marklessFullResumeHandoff(handoff) {",
602
+ " handoff.root.__asyncResumeRuntimeStarted = true;",
603
+ " const { resumeFromPayloadDocument } = await import('@markless/core/web/resume');",
604
+ " const { runtime } = await resumeFromPayloadDocument({",
605
+ " document: handoff.document,",
606
+ " root: handoff.root,",
607
+ ` loadSymbol: ${loadSymbolName},`,
608
+ " });",
609
+ " await runtime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
610
+ "}"
611
+ ].join("\n");
612
+ const scalarOnlySpecialized = leanMode === "scalar" && scalarSpecializations.length > 0 && allEventActionsHaveScalarPlan(runtimeDemandMap);
613
+ const scalarDispatcher = scalarSpecializations.length > 0 ? emitSpecializedScalarDispatcher(scalarSpecializations, loadSymbolName, scalarOnlySpecialized ? "fail" : "full") : emitSpecializedScalarDispatcher([], loadSymbolName, "full");
614
+ if (needsFullResume) return [
615
+ fullResumeHandoff,
616
+ "export async function resumeContainerEvent(input) {",
617
+ " await marklessFullResumeHandoff({ ...input, document: input.root });",
618
+ "}"
619
+ ].join("\n");
620
+ if (leanMode !== "none") {
621
+ const row = [
622
+ " const { resumeScalarRowEventFromPayloadDocument } = await import('@markless/web/event-only-lean/row');",
623
+ " await resumeScalarRowEventFromPayloadDocument({",
624
+ ...[
625
+ " document: input.root,",
626
+ " root: input.root,",
627
+ " event: input.event,",
628
+ " element: input.element,",
629
+ " runtimeDemandMap: payloadRuntimeDemandMap,",
630
+ " syncPolicyAlreadyApplied: input.syncPolicyAlreadyApplied === true,",
631
+ ` loadSymbol: ${loadSymbolName},`,
632
+ " });"
633
+ ]
634
+ ];
635
+ if (leanMode === "scalar") return [
636
+ scalarOnlySpecialized ? "" : fullResumeHandoff,
637
+ scalarDispatcher,
638
+ "export async function resumeContainerEvent(input) {",
639
+ " await marklessResumeSpecializedScalarEvent(input);",
640
+ "}"
641
+ ].join("\n");
642
+ if (leanMode === "row") return [
643
+ "export async function resumeContainerEvent(input) {",
644
+ ...row,
645
+ "}"
646
+ ].join("\n");
647
+ return [
648
+ fullResumeHandoff,
649
+ scalarDispatcher,
650
+ "export async function resumeContainerEvent(input) {",
651
+ " if (marklessScalarSpecializedAction(input)) {",
652
+ " await marklessResumeSpecializedScalarEvent(input);",
653
+ " return;",
654
+ " }",
655
+ ...row,
656
+ "}"
657
+ ].join("\n");
658
+ }
659
+ return [
660
+ fullResumeHandoff,
661
+ "export async function resumeContainerEvent(input) {",
662
+ " await marklessFullResumeHandoff({ ...input, document: input.root });",
663
+ "}"
664
+ ].join("\n");
665
+ }
666
+ function scalarDispatcherSpecializations(input) {
667
+ const state = input.payloadState;
668
+ const view = input.payloadView;
669
+ const map = input.runtimeDemandMap;
670
+ if ((input.symbolRoutes?.length ?? 0) > 0) return [];
671
+ const cells = state?.cells ?? [];
672
+ const locators = view?.locators ?? [];
673
+ return (map?.actions ?? []).flatMap((action, index) => {
674
+ const plan = action?.plan;
675
+ if (action?.recordKind !== "event" || plan?.version !== 1 || plan?.kind !== "scalar") return [];
676
+ const cellIndex = cells.findIndex((cell) => cell?.graphNodeId === plan.cell);
677
+ const host = locators.find((locator) => locator?.hostNodeId === action.hostNodeId);
678
+ const event = view?.events?.find((candidate) => candidate?.hostNodeId === action.hostNodeId && candidate?.eventName === action.eventName);
679
+ const symbolId = scalarActionSymbolId(plan.symbolId, event, input.symbolRoutes ?? []);
680
+ if (!symbolId) return [];
681
+ if (cellIndex < 0 || !host || typeof host.index !== "number") return [];
682
+ if (event && syncPolicyGraphNodeIds(event.syncPolicy).some((graphNodeId) => graphNodeId !== plan.cell)) return [];
683
+ const textUpdates = (plan.textUpdates ?? []).flatMap((update) => {
684
+ const locator = locators.find((candidate) => candidate?.hostNodeId === update.hostNodeId);
685
+ return locator && typeof locator.index === "number" ? [{
686
+ hostNodeId: update.hostNodeId,
687
+ index: locator.index,
688
+ tagName: String(locator.tagName ?? "*"),
689
+ ...update.prefix ? { prefix: update.prefix } : {}
690
+ }] : [];
691
+ });
692
+ if (textUpdates.length !== (plan.textUpdates ?? []).length) return [];
693
+ return [{
694
+ name: `marklessRunScalar${index}`,
695
+ hostNodeId: action.hostNodeId,
696
+ eventName: action.eventName,
697
+ symbolId,
698
+ cell: plan.cell,
699
+ cellIndex,
700
+ hostIndex: host.index,
701
+ hostTagName: String(host.tagName ?? "*"),
702
+ syncPolicy: event?.syncPolicy ?? null,
703
+ write: plan.write,
704
+ textUpdates
705
+ }];
706
+ });
707
+ }
708
+ function scalarActionSymbolId(plannedSymbolId, event, routes) {
709
+ if (typeof plannedSymbolId !== "string") return null;
710
+ const eventSymbolIds = Array.isArray(event?.symbolIds) ? event.symbolIds.filter((symbolId) => typeof symbolId === "string") : [];
711
+ const routedSymbolId = eventSymbolIds.find((symbolId) => routes.some((route) => symbolId.startsWith(route.prefix)));
712
+ if (routedSymbolId) return routedSymbolId;
713
+ if (eventSymbolIds.some((symbolId) => /^[^:]+:symbol:/.test(symbolId))) return null;
714
+ if (eventSymbolIds.length > 0 && !eventSymbolIds.includes(plannedSymbolId)) return null;
715
+ return plannedSymbolId;
716
+ }
717
+ function allEventActionsHaveScalarPlan(runtimeDemandMap) {
718
+ const eventActions = (runtimeDemandMap?.actions ?? []).filter((action) => action.recordKind === "event");
719
+ return eventActions.length > 0 && eventActions.every((action) => action.plan?.kind === "scalar");
720
+ }
721
+ function emitSpecializedScalarDispatcher(actions, loadSymbolName, fallback) {
722
+ const fallbackName = fallback === "fail" ? "marklessScalarSpecializedHostMiss" : "marklessScalarSpecializedFallback";
723
+ const fallbackBody = fallback === "full" ? [
724
+ "async function marklessScalarSpecializedFallback(input, site, syncPolicyAlreadyApplied = input.syncPolicyAlreadyApplied === true) {",
725
+ " if (import.meta.env?.DEV) console.warn(Object.assign(new Error(\"MARKLESS_SCALAR_SPECIALIZED_FALLBACK\"), { code: \"MARKLESS_SCALAR_SPECIALIZED_FALLBACK\", site }));",
726
+ " await marklessFullResumeHandoff({ ...input, document: input.root, syncPolicyAlreadyApplied });",
727
+ "}"
728
+ ] : [];
729
+ return [
730
+ "async function marklessResumeSpecializedScalarEvent(input) {",
731
+ " const action = marklessScalarSpecializedAction(input);",
732
+ " if (action) {",
733
+ " try {",
734
+ " return await action(input);",
735
+ " } catch (error) {",
736
+ ` if (error?.code === "MARKLESS_SCALAR_SPECIALIZED_ESCALATE") return ${fallbackName}(input, error.site ?? "escalate", error.syncPolicyAlreadyApplied === true);`,
737
+ " throw error;",
738
+ " }",
739
+ " }",
740
+ fallback === "fail" ? " return;" : ` return ${fallbackName}(input, "event-match");`,
741
+ "}",
742
+ fallback === "fail" ? "function marklessScalarSpecializedHostMiss(_input, site) { return marklessScalarSpecializedError(\"MARKLESS_SCALAR_SPECIALIZED_HOST_MISS\", site); }" : "function marklessScalarSpecializedHostMiss(input, site) { return marklessScalarSpecializedFallback(input, site); }",
743
+ "function marklessScalarSpecializedAction(input) {",
744
+ ...actions.map((action) => ` if (marklessScalarEventMatches(input, marklessFindElementAtDomOrderIndex(input.root, ${action.hostIndex}), ${JSON.stringify(action.hostTagName.toLowerCase())}, ${JSON.stringify(action.eventName)}, ${JSON.stringify(action.hostNodeId)})) return ${action.name};`),
745
+ "}",
746
+ "function marklessScalarEventMatches(input, host, tagName, eventName, hostNodeId) {",
747
+ " const eventTypeMatches = input.event?.type === eventName;",
748
+ " if (!eventTypeMatches) return false;",
749
+ " if (!host || (tagName !== \"*\" && host.tagName.toLowerCase() !== tagName)) return false;",
750
+ " const eventTarget = input.event?.target;",
751
+ " return host === eventTarget || (!!eventTarget?.nodeType && typeof host.contains === \"function\" && host.contains(eventTarget));",
752
+ "}",
753
+ ...actions.map((action) => emitScalarAction(action, loadSymbolName)),
754
+ ...fallbackBody
755
+ ].join("\n");
756
+ }
757
+ function emitScalarAction(action, loadSymbolName) {
758
+ return [
759
+ `async function ${action.name}(input) {`,
760
+ " let syncPolicyAlreadyApplied = input.syncPolicyAlreadyApplied === true;",
761
+ ` const state = { value: marklessDecodeScalarCell(marklessReadScalarCell(input.root, ${action.cellIndex}), ${JSON.stringify(action.cell)}, ${JSON.stringify(`markless/state cell[${action.cellIndex}]`)}), dirty: false };`,
762
+ " try {",
763
+ ` const host = marklessFindElementAtDomOrderIndex(input.root, ${action.hostIndex});`,
764
+ ` if (!host || (${JSON.stringify(action.hostTagName.toLowerCase())} !== "*" && host.tagName.toLowerCase() !== ${JSON.stringify(action.hostTagName.toLowerCase())})) return marklessScalarSpecializedHostMiss(input, "host");`,
765
+ ...action.textUpdates.map((update, index) => ` const textTarget${index} = marklessFindElementAtDomOrderIndex(input.root, ${update.index});`),
766
+ ...action.textUpdates.map((update, index) => ` if (!textTarget${index} || (${JSON.stringify(update.tagName.toLowerCase())} !== "*" && textTarget${index}.tagName.toLowerCase() !== ${JSON.stringify(update.tagName.toLowerCase())})) return marklessScalarSpecializedHostMiss(input, "text-target");`),
767
+ " const graph = {",
768
+ ` hasCell(graphNodeId) { return graphNodeId === ${JSON.stringify(action.cell)}; },`,
769
+ ` read(graphNodeId, path = []) { if (graphNodeId !== ${JSON.stringify(action.cell)} || path.length) return marklessScalarSpecializedError("MARKLESS_SCALAR_SPECIALIZED_ESCALATE", "read"); return state.value; },`,
770
+ ` write(write) { if (write.graphNodeId !== ${JSON.stringify(action.cell)} || (write.path?.length ?? 0)) return marklessScalarSpecializedError("MARKLESS_SCALAR_SPECIALIZED_ESCALATE", "write"); if (!Object.is(state.value, write.value)) { state.value = write.value; state.dirty = true; } },`,
771
+ ` update(update) { if (update.graphNodeId !== ${JSON.stringify(action.cell)} || (update.path?.length ?? 0)) return marklessScalarSpecializedError("MARKLESS_SCALAR_SPECIALIZED_ESCALATE", "update"); const previous = state.value; const next = update.update(previous); if (!Object.is(previous, next)) { state.value = next; state.dirty = true; } return update.returnValue === "previous" ? previous : update.returnValue === "next" ? next : undefined; },`,
772
+ " call() { return marklessScalarSpecializedError(\"MARKLESS_SCALAR_SPECIALIZED_ESCALATE\", \"call\"); },",
773
+ " async flush() {},",
774
+ " };",
775
+ ...action.syncPolicy ? [
776
+ ` const syncPolicy = ${JSON.stringify(action.syncPolicy)};`,
777
+ " if (syncPolicy && !syncPolicyAlreadyApplied) {",
778
+ " const { runSyncPolicyActions } = await import('@markless/web/inline/sync-policy-core');",
779
+ " runSyncPolicyActions(syncPolicy, graph, input.event);",
780
+ " syncPolicyAlreadyApplied = true;",
781
+ " }"
782
+ ] : [],
783
+ ...emitScalarWrite(action),
784
+ ` const symbol = await Promise.resolve(${loadSymbolName}(${JSON.stringify(action.symbolId)}));`,
785
+ " await Promise.resolve(symbol({ graph: { ...graph, write() {}, update(update) { const value = graph.read(update.graphNodeId, update.path ?? []); return update.returnValue === \"previous\" || update.returnValue === \"next\" ? value : undefined; } }, event: input.event, element: host, getElementHandle: () => undefined }));",
786
+ " if (state.dirty) {",
787
+ " state.dirty = false;",
788
+ ...action.textUpdates.map((update, index) => ` textTarget${index}.textContent = marklessUpdateText({ domUpdate: { hostNodeId: ${JSON.stringify(update.hostNodeId)} }, value: ${JSON.stringify(update.prefix ?? "")} + (state.value == null ? '' : String(state.value)) }, ${JSON.stringify(update.hostNodeId)}).value;`),
789
+ " }",
790
+ " } catch (error) {",
791
+ " if (error?.code === \"MARKLESS_SCALAR_SPECIALIZED_ESCALATE\") error.syncPolicyAlreadyApplied = syncPolicyAlreadyApplied;",
792
+ " throw error;",
793
+ " }",
794
+ "}"
795
+ ].join("\n");
796
+ }
797
+ function emitScalarWrite(action) {
798
+ if (action.write.kind === "update") return [
799
+ " marklessWriteScalar({ graph }, {",
800
+ ` graphNodeId: ${JSON.stringify(action.cell)},`,
801
+ " returnValue: \"next\",",
802
+ " update(value) {",
803
+ ` return Number(value) ${action.write.updateOperator === "--" ? "-" : "+"} 1;`,
804
+ " },",
805
+ " });"
806
+ ];
807
+ return [
808
+ " marklessWriteScalar({ graph }, {",
809
+ ` graphNodeId: ${JSON.stringify(action.cell)},`,
810
+ ` value: ${action.write.valueKind === "undefined" ? "undefined" : JSON.stringify(action.write.value)},`,
811
+ " });"
812
+ ];
813
+ }
814
+ function syncPolicyGraphNodeIds(policy) {
815
+ if (!policy || typeof policy !== "object") return [];
816
+ const branches = Array.isArray(policy.branches) ? policy.branches : [policy];
817
+ return [...new Set(branches.flatMap((branch) => conditionGraphNodeIds(branch.when)))].sort();
818
+ }
819
+ function conditionGraphNodeIds(condition) {
820
+ if (!condition || typeof condition !== "object") return [];
821
+ const typed = condition;
822
+ if (typed.type === "graph-truthy" && typeof typed.graphNodeId === "string") return [typed.graphNodeId];
823
+ if (typed.type === "not") return conditionGraphNodeIds(typed.condition);
824
+ if ((typed.type === "and" || typed.type === "or") && Array.isArray(typed.conditions)) return typed.conditions.flatMap(conditionGraphNodeIds);
825
+ return [];
826
+ }
827
+ function leanResumeMode(runtimeDemandMap) {
828
+ const recordKinds = runtimeDemandMap?.recordKinds;
829
+ if (!recordKinds) return "none";
830
+ const replaced = new Map(recordKinds.map((record) => [record.kind, record.replaced]));
831
+ const scalar = replaced.get("event") === true && replaced.get("dom-update") === true;
832
+ const row = replaced.get("keyed-repeat") === true && replaced.get("dom-update") === true;
833
+ if (scalar && row) return "mixed";
834
+ if (scalar) return "scalar";
835
+ if (row) return "row";
836
+ return "none";
837
+ }
838
+ function emitExecutionLogLoader() {
839
+ return `globalThis.__mxLoadLog ||= () => import(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)});`;
840
+ }
841
+ function emitLoadSymbol(input) {
842
+ if (input.symbols.length > 0 && input.symbols.length <= SMALL_SYMBOL_DIRECT_LOAD_LIMIT) return emitDirectSourceSymbolLoader(input.symbols);
843
+ return [
844
+ `const marklessSymbolResolverModule = () => import('${input.resolverId}');`,
845
+ "function loadSymbol(symbolId) {",
846
+ " return marklessSymbolResolverModule().then((mod) => mod.loadSymbol(symbolId));",
847
+ "}"
848
+ ].join("\n");
849
+ }
850
+ function emitDirectSourceSymbolLoader(symbols) {
851
+ return [
852
+ "function loadSymbol(symbolId) {",
853
+ ...symbols.flatMap((symbol) => [` if (symbolId === ${JSON.stringify(symbol.id)}) return import('${symbol.chunk}')`, ` .then((mod) => readMarklessSourceSymbol(mod, ${JSON.stringify(symbol.exportName)}));`]),
854
+ " return Promise.reject(new Error(`Unknown async symbol ${symbolId}`));",
855
+ "}",
856
+ emitSourceSymbolExportReader()
857
+ ].join("\n");
858
+ }
859
+ function emitSourceSymbolExportReader() {
860
+ return [
861
+ "function readMarklessSourceSymbol(mod, exportName) {",
862
+ " mod.init__virtual_markless_symbol?.();",
863
+ " return mod[exportName];",
864
+ "}"
865
+ ].join("\n");
866
+ }
867
+ function stringHash(value) {
868
+ let hash = 2166136261;
869
+ for (let index = 0; index < value.length; index++) {
870
+ hash ^= value.charCodeAt(index);
871
+ hash = Math.imul(hash, 16777619);
872
+ }
873
+ return (hash >>> 0).toString(36);
874
+ }
875
+ //#endregion
876
+ export { planModulePreloads as S, requalifyExecutionLogModuleHook as _, resumeVirtualModuleId as a, outputDefaults as b, symbolVirtualModuleId as c, MARKLESS_EXECUTION_SIZES as d, createExecutionSizesAsset as f, normalizeExecutionLogMode as g, injectExecutionLogModuleHook as h, payloadModule as i, symbolVirtualModuleSourceFile as l, executionLogVirtualModuleSource as m, emitResumeModule as n, rewriteSymbolModuleExport as o, executionLogActivationInjection as p, emitSourceModule as r, scopedSymbolExportName as s, MARKLESS_VIRTUAL_PREFIX as t, MARKLESS_EXECUTION_LOG_MODULE_ID as u, MARKLESS_BUILD_PREFIX as v, planModulePreloadUrls as x, MARKLESS_BUNDLE_GRAPH as y };