@markless/bundler 0.7.0 → 0.9.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,11 +1,10 @@
1
1
  import { c as createCompileErrorPayload, s as MarklessCompileError } from "./dev-error-BEduK_R3.js";
2
- import { $ as MARKLESS_BUNDLE_GRAPH, A as isSymbolOnlySourceRequest, At as executionLogVirtualModuleSource, B as sourceForResumeVirtualImporter, C as isMarklessRuntimeModule, Ct as symbolVirtualModuleId, D as isResumeSourceRequest, Dt as MARKLESS_EXECUTION_LOG_GLOBAL, E as isRenderDataSourceRequest, Et as EXECUTION_LOG_DISPATCH_MODULE_IDS, F as resolveVirtualId, Ft as requalifyExecutionLogModuleHook, G as virtualModuleSourceForLoad, H as sourceForSymbolVirtualImporter, I as resolverVirtualModuleSourceFile, J as planPrerenderTriggerGroups, K as emitPrerenderBoundaryRendererModule, L as serverSharedSourceRequest, Lt as planModulePreloads, M as normalizeVirtualId$2, Mt as injectExecutionLogModuleHook, N as pathname$1, O as isRouteNavigationSourceRequest, Ot as MARKLESS_EXECUTION_LOG_MODULE_ID, P as renderDataReachedFromQuery, Pt as normalizeExecutionLogMode, Q as MARKLESS_BUILD_PREFIX, R as sharedReachedRenderDataRequest, S as isClientPrimarySourceRequest, St as symbolEntryVirtualModuleId, T as isRelativeImport, Tt as withoutFirstUse, U as sourceForTriggerGroupVirtualImporter, V as sourceForSettleVirtualImporter, W as stripBuildPrefix, X as adaptImportedCaptureResolver, Y as triggerGroupVirtualModuleId, Z as MARKLESS_BUILD_METADATA_FILES, _ as clientSymbolEntries, a as isStartupPack, at as outputDefaults, b as emittedBundleModuleIds, bt as scopedSymbolExportName, c as planRoutePackGroups, d as warmPacksSuffix, dt as emitResumeModule, et as MARKLESS_BYTE_ATTRIBUTION, f as MARKLESS_INTERACTION_CLOSURES_ASSET, ft as emitSettleModule, g as clientRouteArtifactReference, gt as prerenderWakeVirtualModuleId, h as TSRX_SOURCE_FILE$1, ht as payloadModule, it as MARKLESS_PUBLIC_BUILD_METADATA_FILES, j as materializedReachedRenderDataSource, jt as hasExecutionLogModuleHook, k as isScalarPlanSourceRequest, kt as executionLogActivationInjection, l as startupPackOfLazy, lt as demandsOverlay, m as MARKLESS_ROUTE_SOURCE_QUERY_RE, mt as encodedSymbolSource, nt as MARKLESS_EXECUTION_SIZES, ot as MARKLESS_VIRTUAL_PREFIX, pt as emitSourceModule, q as emitPrerenderTriggerGroupModule, rt as MARKLESS_INTERACTION_CLOSURES, s as marklessDeferredChunkFileNames, tt as MARKLESS_EXECUTION_DEMAND, ut as emitOverlayLoaderInstall, v as devBrowserSourceModuleUrl, vt as resumeVirtualModuleId, w as isPrerenderWakeSourceRequest, wt as symbolVirtualModuleSourceFile, x as executionLogRuntimeModuleId, xt as settleVirtualModuleId, y as devBrowserVirtualModuleUrl, yt as rewriteSymbolModuleExport, z as sourceForPrerenderWakeVirtualImporter } from "./route-pack-groups-BXc755qH.js";
2
+ import { $ as MARKLESS_BUILD_PREFIX, A as isScalarPlanSourceRequest, At as compileInlineResumerSources, B as sourceForPrerenderWakeVirtualImporter, Bt as hasExecutionLogModuleHook, C as isCompilerStatefulModuleId, Ct as symbolEntryVirtualModuleId, D as isRenderDataSourceRequest, Dt as isSharedInlineSourcesModuleId, E as isRelativeImport, Et as withoutFirstUse, F as renderDataReachedFromQuery, Ft as EXECUTION_LOG_DISPATCH_MODULE_IDS, G as stripBuildPrefix, H as sourceForSettleVirtualImporter, I as resolveVirtualId, It as MARKLESS_EXECUTION_LOG_GLOBAL, J as emitPrerenderTriggerGroupModule, K as virtualModuleSourceForLoad, Kt as planModulePreloads, L as resolverVirtualModuleSourceFile, Lt as MARKLESS_EXECUTION_LOG_MODULE_ID, M as materializedReachedRenderDataSource, N as normalizeVirtualId$2, O as isResumeSourceRequest, Ot as sharedInlineSourcesModuleId, P as pathname$1, Q as MARKLESS_BUILD_METADATA_FILES, R as serverSharedSourceRequest, Rt as executionLogActivationInjection, S as isClientPrimarySourceRequest, St as settleVirtualModuleId, T as isPrerenderWakeSourceRequest, Tt as symbolVirtualModuleSourceFile, U as sourceForSymbolVirtualImporter, Ut as normalizeExecutionLogMode, V as sourceForResumeVirtualImporter, Vt as injectExecutionLogModuleHook, W as sourceForTriggerGroupVirtualImporter, Wt as requalifyExecutionLogModuleHook, X as triggerGroupVirtualModuleId, Y as planPrerenderTriggerGroups, Z as adaptImportedCaptureResolver, _ as clientSymbolEntries, _t as prerenderWakeVirtualModuleId, a as isStartupPack, at as MARKLESS_PUBLIC_BUILD_METADATA_FILES, b as emittedBundleModuleIds, bt as rewriteSymbolModuleExport, c as planRoutePackGroups, d as warmPacksSuffix, dt as emitOverlayLoaderInstall, et as MARKLESS_BUNDLE_GRAPH, f as MARKLESS_INTERACTION_CLOSURES_ASSET, ft as emitResumeModule, g as clientRouteArtifactReference, gt as payloadModule, h as TSRX_SOURCE_FILE$1, ht as encodedSymbolSource, it as MARKLESS_INTERACTION_CLOSURES, j as isSymbolOnlySourceRequest, jt as compilePrerenderInlineResumerSources, k as isRouteNavigationSourceRequest, kt as sharedInlineSourcesModuleSource, l as startupPackOfLazy, m as MARKLESS_ROUTE_SOURCE_QUERY_RE, mt as emitSourceModule, nt as MARKLESS_EXECUTION_DEMAND, ot as outputDefaults, pt as emitSettleModule, q as emitPrerenderBoundaryRendererModule, rt as MARKLESS_EXECUTION_SIZES, s as marklessDeferredChunkFileNames, st as MARKLESS_VIRTUAL_PREFIX, tt as MARKLESS_BYTE_ATTRIBUTION, ut as demandsOverlay, v as devBrowserSourceModuleUrl, w as isMarklessRuntimeModule, wt as symbolVirtualModuleId, x as executionLogRuntimeModuleId, xt as scopedSymbolExportName, y as devBrowserVirtualModuleUrl, yt as resumeVirtualModuleId, z as sharedReachedRenderDataRequest, zt as executionLogVirtualModuleSource } from "./route-pack-groups-0vHmSVdv.js";
3
3
  import { joinURL, parsePath, withLeadingSlash, withQuery, withoutLeadingSlash } from "ufo";
4
4
  import { PROTOCOL_EVENT_ACTION_KIND, PROTOCOL_IDLE_EVENT_NAME, createStorageSeedMetadataFromGraphNodeId, jsonSourceWithNonFiniteNumbers } from "@markless/serializer";
5
5
  import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
6
6
  import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve } from "pathe";
7
7
  import { DEBUGGING_PLAYBOOK_HINT, LEAN_DISPATCH_MARKER_MODULES, RUNTIME_CAPABILITY_MODULE_IDS, artifactChildCandidates, callsImportedOrFreeName, collectTsrxModuleDiagnostics, compileTsrxModule, compileTsrxModuleLinkArtifact, componentEdgeSymbolRoutes, computeExecutionAttribution, computeLinkedInterfaces, delegateChildRenderPlan, delegateChildRendering, delegateChildResolutionRequests, delegateMaterializationScope, emitSymbolResolverModule, evaluateModuleConstants, importedNestedRepeats, importedRowComponentMints, importedRowSlotReaders, importedRowTemplateMints, importedSymbolRoutes, linkBarrelComponents, linkClaimManifests, linkDelegateChildren, linkImportedModules, linkedChildrenHaveBrowserTriggers, linkedImportedClaimsMissing, linkedImportedSymbolInputs, linkedManifestHasBrowserTriggers, linkedModuleChildDiagnostics, linkedModuleChildKey, linkedModuleClaimPlan, linkedModuleImportRequests, linkedModuleLoadSource, linkedRenderDataBoundarySymbols, linkedRenderDataOnlyChange, linkedRenderDataReachRoot, linkedResolverClaimVerdict, linkedRouteArtifactRegistration, linkedSymbolRouteRequests, moduleInterfaceHash, moduleLinkResolutionKey, overlayBarrelInterfaces, parseJavaScriptModule, planDelegateChildren, planEmittedClaimOwnership, planLinkedModuleChildren, planRenderDataModule, planTransformRequest, prerenderInterfacesComplete, renderDataClaimManifest, renderDataReachImportSources, uniqueLinkedModuleChildren } from "@markless/compiler";
8
- import { PRERENDER_INLINE_EVENT_NAMES_TOKEN, createInlineResumerDebugRegistrationSource, createInlineResumerSelfWakeSource, createInlineResumerSource, createPrerenderInlineResumerSource, createPrerenderSettleInlineResumerSource } from "@markless/web/inline/resumer";
9
8
  import { parse, parseSync } from "rolldown/experimental";
10
9
  import { copyFile, mkdir, readFile, readdir, rename, rm, rmdir } from "node:fs/promises";
11
10
  import { defDGraph } from "@thi.ng/dgraph";
@@ -253,10 +252,16 @@ function rootRelativeRegionComments(bundle, root) {
253
252
  //#region src/module-id.ts
254
253
  const linkedPackagesByRoot = /* @__PURE__ */ new Map();
255
254
  const mintedSources = /* @__PURE__ */ new Map();
255
+ const mintedIds = /* @__PURE__ */ new Map();
256
256
  function moduleIdFor(filename, root) {
257
257
  if (!root || !isAbsolute(filename)) return filename;
258
- const relativeId = relative(root, filename);
259
- const id = !relativeId.startsWith("..") && !relativeId.includes("node_modules/") ? relativeId : packageRootedModuleId(filename, root) ?? (outsideCheckout(filename, root) ? namedPackageModuleId(filename) : null) ?? relativeId;
258
+ const key = `${root}\0${filename}`;
259
+ let id = mintedIds.get(key);
260
+ if (id === void 0) {
261
+ const relativeId = relative(root, filename);
262
+ id = !relativeId.startsWith("..") && !relativeId.includes("node_modules/") ? relativeId : packageRootedModuleId(filename, root) ?? (outsideCheckout(filename, root) ? namedPackageModuleId(filename) : null) ?? relativeId;
263
+ mintedIds.set(key, id);
264
+ }
260
265
  mintedSources.set(`${root}\0${id}`, filename);
261
266
  return id;
262
267
  }
@@ -363,483 +368,6 @@ function rootRelativeId(id, root) {
363
368
  return `${prefix}${spelled === source ? moduleId : encodeURIComponent(moduleId)}${rest}`;
364
369
  }
365
370
  //#endregion
366
- //#region ../web/src/debug-channel.ts
367
- function installDebugChannelLayer(root, initialPhase, initiallyActive = true) {
368
- const global = globalThis;
369
- const previous = global.__MARKLESS_DEBUG__?.version === 1 ? global.__MARKLESS_DEBUG__ : void 0;
370
- let priorRoot;
371
- try {
372
- priorRoot = previous?.explainInteraction(root, "__markless_debug_root__");
373
- } catch {}
374
- const priorContainer = priorRoot && "containerId" in priorRoot ? previous?.containers.find((entry) => entry.id === priorRoot.containerId) : void 0;
375
- const seed = `${Date.now().toString(36)}:${Math.random().toString(36).slice(2)}`;
376
- const id = priorContainer?.id ?? `container:${seed}`;
377
- const rootKey = priorContainer?.root.key ?? `root:${seed}`;
378
- const rootRef = new WeakRef(root);
379
- const events = /* @__PURE__ */ new WeakMap();
380
- const delegatedEvents = /* @__PURE__ */ new Set();
381
- const keys = /* @__PURE__ */ new WeakMap();
382
- const invalidated = /* @__PURE__ */ new WeakSet();
383
- const routerSources = global[Symbol.for("markless.debug.channel.v1.router-sources")] ??= /* @__PURE__ */ new Set();
384
- const ownViolations = [];
385
- let phase = initialPhase;
386
- let lifecycle = initiallyActive ? "active" : "registered";
387
- let boundarySnapshots = Object.freeze([]);
388
- let nextElement = 1;
389
- let nextSequence = (previous?.violations.at(-1)?.sequence ?? 0) + 1;
390
- let dropped = 0;
391
- let pruned = false;
392
- const freeze = (value) => Object.freeze(value);
393
- const contains = (element) => {
394
- const currentRoot = rootRef.deref();
395
- return !!currentRoot && (currentRoot === element || currentRoot.contains?.(element) === true);
396
- };
397
- const keyFor = (element) => {
398
- let key = keys.get(element);
399
- if (!key) {
400
- key = `${rootKey}:element:${nextElement++}`;
401
- keys.set(element, key);
402
- }
403
- return key;
404
- };
405
- const eligibleAnchor = (element) => {
406
- const anchor = element.closest?.("a[href]");
407
- if (!anchor?.hasAttribute("data-markless-router-link") || anchor.hasAttribute("download")) return false;
408
- const target = anchor.getAttribute("target");
409
- if (target && target !== "_self" || anchor.relList?.contains("external")) return false;
410
- try {
411
- const base = global.location?.href ?? "http://localhost/";
412
- return new URL(anchor.href ?? "", base).origin === new URL(base).origin;
413
- } catch {
414
- return false;
415
- }
416
- };
417
- const none = (element, eventName, reason) => freeze({
418
- kind: "none",
419
- eventName,
420
- reason,
421
- containerId: id,
422
- elementKey: keyFor(element)
423
- });
424
- const explain = (element, eventName) => {
425
- if (lifecycle === "disposed" && (contains(element) || keys.has(element))) return none(element, eventName, "container-disposed");
426
- if (!contains(element)) try {
427
- return previous?.explainInteraction(element, eventName) ?? freeze({
428
- kind: "none",
429
- eventName,
430
- reason: "outside-known-container"
431
- });
432
- } catch {
433
- return freeze({
434
- kind: "none",
435
- eventName,
436
- reason: "outside-known-container"
437
- });
438
- }
439
- if (element.isConnected === false) return none(element, eventName, "element-disconnected");
440
- if (eligibleAnchor(element)) {
441
- 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;
442
- if (source) return freeze({
443
- kind: "router-delegation",
444
- source,
445
- containerId: id,
446
- elementKey: keyFor(element),
447
- eventName
448
- });
449
- }
450
- const interaction = events.get(element)?.get(eventName);
451
- if (interaction) return freeze({ ...interaction });
452
- if (delegatedEvents.has(eventName)) return freeze({
453
- kind: "inline-resumer",
454
- source: "ssr-inline",
455
- containerId: id,
456
- elementKey: keyFor(element),
457
- eventName
458
- });
459
- if (invalidated.has(element)) return none(element, eventName, "not-registered");
460
- try {
461
- const prior = previous?.explainInteraction(element, eventName);
462
- if (prior && prior.kind !== "none") return prior;
463
- } catch {}
464
- return none(element, eventName, "not-registered");
465
- };
466
- const cloneJson = (value, seen = /* @__PURE__ */ new Set()) => {
467
- if (value === null) return null;
468
- if (typeof value === "boolean" || typeof value === "string") return value;
469
- if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
470
- if (!value || typeof value !== "object" || seen.has(value)) return void 0;
471
- seen.add(value);
472
- if (Array.isArray(value)) {
473
- const copy = value.map((entry) => cloneJson(entry, seen));
474
- return copy.some((entry) => entry === void 0) ? void 0 : freeze(copy);
475
- }
476
- if (Object.getPrototypeOf(value) !== Object.prototype) return void 0;
477
- const copy = {};
478
- for (const [name, entry] of Object.entries(value)) {
479
- const cloned = cloneJson(entry, seen);
480
- if (cloned === void 0) return void 0;
481
- copy[name] = cloned;
482
- }
483
- return freeze(copy);
484
- };
485
- const pushViolation = (input) => {
486
- const cloned = input.details === void 0 ? void 0 : cloneJson(input.details);
487
- const details = cloned && !Array.isArray(cloned) && typeof cloned === "object" ? cloned : void 0;
488
- const { details: _details, ...metadata } = input;
489
- ownViolations.push(freeze({
490
- ...metadata,
491
- ...details ? { details } : {},
492
- sequence: nextSequence++,
493
- timestamp: Date.now()
494
- }));
495
- if (input.details !== void 0 && !details) ownViolations.push(freeze({
496
- code: "MARKLESS_DEBUG_DETAILS_DROPPED",
497
- message: "Debug violation details were not JSON-safe and were dropped.",
498
- sequence: nextSequence++,
499
- timestamp: Date.now()
500
- }));
501
- while (ownViolations.length > 100) {
502
- ownViolations.shift();
503
- dropped++;
504
- }
505
- };
506
- const channel = freeze({
507
- version: 1,
508
- get containers() {
509
- const inherited = previous?.containers.filter((entry) => entry.id !== id) ?? [];
510
- if (pruned || lifecycle === "disposed") return freeze([...inherited]);
511
- const currentRoot = rootRef.deref();
512
- const connected = !!currentRoot && currentRoot.isConnected !== false;
513
- const snapshot = freeze({
514
- id,
515
- phase,
516
- lifecycle: connected ? lifecycle : "disposed",
517
- root: freeze({
518
- key: rootKey,
519
- connected
520
- }),
521
- boundaries: freeze([...boundarySnapshots])
522
- });
523
- if (!connected) pruned = true;
524
- return freeze([...inherited, snapshot]);
525
- },
526
- get violations() {
527
- return freeze([...previous?.violations ?? [], ...ownViolations].slice(-100));
528
- },
529
- violationCapacity: 100,
530
- get droppedViolationCount() {
531
- return (previous?.droppedViolationCount ?? 0) + dropped;
532
- },
533
- explainInteraction: explain
534
- });
535
- Object.defineProperty(global, "__MARKLESS_DEBUG__", {
536
- configurable: true,
537
- enumerable: false,
538
- value: channel,
539
- writable: false
540
- });
541
- return {
542
- start(nextPhase, active = true) {
543
- phase = nextPhase === "ssr-resume" && phase === "csr" ? "csr" : nextPhase;
544
- if (active) lifecycle = "active";
545
- return id;
546
- },
547
- activate: () => void (lifecycle === "disposed" || (lifecycle = "active")),
548
- dispose() {
549
- lifecycle = "disposed";
550
- boundarySnapshots = freeze([]);
551
- },
552
- invalidate(element) {
553
- events.delete(element);
554
- invalidated.add(element);
555
- },
556
- record(element, eventName, input) {
557
- if (lifecycle === "disposed") return;
558
- let byName = events.get(element);
559
- if (!byName) events.set(element, byName = /* @__PURE__ */ new Map());
560
- const symbolIds = "symbolIds" in input ? freeze([...input.symbolIds]) : void 0;
561
- byName.set(eventName, freeze({
562
- ...input,
563
- ...symbolIds ? { symbolIds } : {},
564
- containerId: id,
565
- elementKey: keyFor(element),
566
- eventName
567
- }));
568
- },
569
- delegated(eventNames) {
570
- if (lifecycle === "disposed") return;
571
- for (const eventName of eventNames) delegatedEvents.add(eventName);
572
- },
573
- violation: pushViolation,
574
- router: (source) => void routerSources.add(source),
575
- boundaries(value) {
576
- boundarySnapshots = freeze(value.map((entry) => freeze({ ...entry })));
577
- },
578
- disposed: () => lifecycle === "disposed"
579
- };
580
- }
581
- function __marklessDebugBootstrapSource() {
582
- return `((root,phase,active)=>{const controls=(${installDebugChannelLayer.toString()})(root,phase,active);return Object.freeze({record:(element,eventName,input)=>controls.record(element,eventName,input),delegated:(eventNames)=>controls.delegated(eventNames),router:(source)=>controls.router(source),activate:()=>controls.activate()})})`;
583
- }
584
- //#endregion
585
- //#region ../serializer/src/protocol-event-names.ts
586
- const PROTOCOL_VISIBLE_EVENT_NAME = "visible";
587
- const PROTOCOL_IDLE_EVENT_NAME$1 = "idle";
588
- //#endregion
589
- //#region ../serializer/src/protocol-locator-paths.ts
590
- /**
591
- * The container attribute that lets resume find each located element by its
592
- * position under its parent, so a node a third-party script adds or swaps
593
- * elsewhere cannot shift it. Format: protocol-locator-paths-format.ts.
594
- */
595
- const PROTOCOL_LOCATOR_PATHS_ATTRIBUTE = "data-markless-paths";
596
- //#endregion
597
- //#region ../serializer/src/protocol-page-markers.ts
598
- const PROTOCOL_CONTAINER_START_COMMENT = "markless:page-start";
599
- const PROTOCOL_CONTAINER_END_COMMENT = "markless:page-end";
600
- //#endregion
601
- //#region ../web/src/inline/defer.ts
602
- /**
603
- * The one startup helper deferred triggers share. Serialized whole into a served
604
- * page that has one; a client mount and the runtime call it directly. Hosts come
605
- * from compiler-emitted DOM-order indexes, index 0 being the container itself,
606
- * which hands records the runtime owns (arms, rows) to the runtime.
607
- */
608
- function createMarklessDefer(loadModule, pageStart, pageEnd, pathsAttribute) {
609
- const scope = globalThis;
610
- const clockOf = (root) => root.__mClock || {
611
- frame: (run) => requestAnimationFrame(run),
612
- idle: (run) => scope.scheduler?.postTask ? scope.scheduler.postTask(run, { priority: "background" }) : typeof requestIdleCallback === "function" ? requestIdleCallback(run, { timeout: 2e3 }) : setTimeout(run, 200)
613
- };
614
- const census = (root) => {
615
- const live = [root];
616
- const walker = document.createTreeWalker(root, 129);
617
- for (let next = walker.nextNode(); next; next = walker.nextNode()) if (next.nodeType !== 8) live.push(next);
618
- else if (next.data === pageStart) live.length = 1;
619
- else if (next.data === pageEnd) break;
620
- return live;
621
- };
622
- const idle = (root, run) => {
623
- const clock = clockOf(root);
624
- const next = () => clock.idle(() => root.__marklessArmRegistering?.size ? next() : run());
625
- const loaded = () => clock.frame(() => scope.__mArm?.idle ? scope.__mArm.idle(next) : next());
626
- if (document.readyState === "complete") loaded();
627
- else addEventListener("load", loaded, { once: true });
628
- };
629
- const trigger = (target, lane, hostIndexes, eventName) => {
630
- const root = target;
631
- const url = document.currentScript?.getAttribute("data-markless-resume-module");
632
- if (!root || !url) return;
633
- const fired = root.__mFired ||= /* @__PURE__ */ new WeakSet();
634
- const claimed = /* @__PURE__ */ new WeakSet();
635
- let pending = 0;
636
- const claim = (host) => {
637
- if (fired.has(host) || claimed.has(host)) return;
638
- const input = {
639
- root,
640
- event: {
641
- type: eventName,
642
- target: host,
643
- bubbles: false
644
- },
645
- element: host
646
- };
647
- const queue = root.__marklessDispatch;
648
- if (!queue && root.__marklessDelegatedDispatch === true) return idle(root, () => claim(host));
649
- claimed.add(host);
650
- if (lane !== "visible") fired.add(host);
651
- root.__marklessCensus ||= census(root);
652
- root.__marklessDelegatedDispatch ||= eventName;
653
- pending++;
654
- (queue ? Promise.resolve(queue(input)) : (root.__mResume ||= loadModule(url)).then((module) => module.resumeContainerEvent(input))).then(() => {
655
- if (root.__asyncResumeRuntimeStarted) return;
656
- fired.add(host);
657
- if (!--pending && root.__marklessDelegatedDispatch === eventName) root.__marklessDelegatedDispatch = void 0;
658
- });
659
- };
660
- const all = root.__marklessCensus ?? census(root);
661
- const paths = pathsAttribute && root.getAttribute?.(pathsAttribute);
662
- if (paths && parseInt(paths) !== all.length) root.__marklessShifted = 1;
663
- const hosts = root.__marklessShifted ? [root] : hostIndexes.flatMap((index) => {
664
- const host = all[index];
665
- return host ? [host] : [];
666
- });
667
- if (lane === "idle") return idle(root, () => hosts.forEach(claim));
668
- const observer = new IntersectionObserver((entries) => {
669
- for (const entry of entries) if (entry.isIntersecting) {
670
- observer.unobserve(entry.target);
671
- claim(entry.target);
672
- }
673
- });
674
- for (const host of hosts) observer.observe(host);
675
- };
676
- return Object.assign(trigger, { idle });
677
- }
678
- const INLINE_DEFER_LOADER_SOURCE = "(url) => import(/* @vite-ignore */ url)";
679
- /** An expression that installs the helper once per document and evaluates to it; a build passes the factory minified. */
680
- function inlineDeferSource(factory = createMarklessDefer.toString()) {
681
- return `(globalThis.__mDefer||=(${factory})(${INLINE_DEFER_LOADER_SOURCE},${JSON.stringify(PROTOCOL_CONTAINER_START_COMMENT)},${JSON.stringify(PROTOCOL_CONTAINER_END_COMMENT)},${JSON.stringify(PROTOCOL_LOCATOR_PATHS_ATTRIBUTE)}))`;
682
- }
683
- /** One lane's registration, appended only to a served page whose records name that lane's event. */
684
- function createInlineDeferTriggerSource(lane, hostIndexes) {
685
- const eventName = lane === "idle" ? PROTOCOL_IDLE_EVENT_NAME$1 : PROTOCOL_VISIBLE_EVENT_NAME;
686
- return `;${inlineDeferSource()}(document.currentScript?.closest('[data-async-container]'),${JSON.stringify(lane)},${JSON.stringify(hostIndexes)},${JSON.stringify(eventName)});`;
687
- }
688
- //#endregion
689
- //#region src/inline-resumer.ts
690
- let oxcToolsPromise;
691
- const compiledSources = /* @__PURE__ */ new Map();
692
- function loadOxcTools() {
693
- oxcToolsPromise ??= import("rolldown/experimental").then(({ minifySync, transformSync }) => ({
694
- minifySync,
695
- transformSync
696
- }));
697
- return oxcToolsPromise;
698
- }
699
- function compileInlineResumerSources(options) {
700
- const cacheKey = `${options.debug ? "debug" : "production"}:${options.executionLog}`;
701
- let compiled = compiledSources.get(cacheKey);
702
- if (!compiled) {
703
- compiled = compileInlineResumerSourceVariants(options);
704
- compiledSources.set(cacheKey, compiled);
705
- }
706
- return compiled;
707
- }
708
- async function compileInlineResumerSourceVariants(options) {
709
- const shared = {
710
- debug: options.debug,
711
- executionLog: options.executionLog
712
- };
713
- const [event, syncPolicy, graphSyncPolicyOwner, graphSyncPolicyConsumer] = await Promise.all([
714
- compileInlineResumerSource({
715
- ...shared,
716
- graphSyncPolicy: false,
717
- sharedGraphPolicy: false,
718
- syncPolicy: false
719
- }),
720
- compileInlineResumerSource({
721
- ...shared,
722
- graphSyncPolicy: false,
723
- sharedGraphPolicy: false,
724
- syncPolicy: true
725
- }),
726
- compileInlineResumerSource({
727
- ...shared,
728
- graphSyncPolicy: true,
729
- sharedGraphPolicy: true,
730
- syncPolicy: true
731
- }),
732
- compileInlineResumerSource({
733
- ...shared,
734
- graphSyncPolicy: true,
735
- sharedGraphPolicy: false,
736
- syncPolicy: true
737
- })
738
- ]);
739
- const defer = await compileDeferFactorySource();
740
- return {
741
- ...shared,
742
- event,
743
- syncPolicy,
744
- graphSyncPolicyOwner,
745
- graphSyncPolicyConsumer,
746
- defer
747
- };
748
- }
749
- async function compileDeferFactorySource() {
750
- const binding = "var __marklessDeferFactory=";
751
- const { minifySync, transformSync } = await loadOxcTools();
752
- const transformed = transformSync("markless-defer.js", `${binding}${createMarklessDefer.toString()};`, {
753
- lang: "js",
754
- sourceType: "script",
755
- target: "es2020"
756
- });
757
- assertOxcResult("transform", transformed.errors);
758
- const minified = minifySync("markless-defer.js", transformed.code, {
759
- compress: true,
760
- mangle: { toplevel: false },
761
- module: false
762
- });
763
- assertOxcResult("minify", minified.errors);
764
- const code = minified.code.trim().replace(/;$/, "");
765
- if (!code.startsWith(binding)) throw new Error("MARKLESS_INLINE_DEFER_FACTORY_UNWRAPPABLE");
766
- return code.slice(27);
767
- }
768
- async function compileInlineResumerSource(options) {
769
- const source = createInlineResumerSource({
770
- ...options,
771
- ...options.debug ? {
772
- debugBootstrapSource: __marklessDebugBootstrapSource(),
773
- debugRegistrationSource: createInlineResumerDebugRegistrationSource()
774
- } : {}
775
- });
776
- const { minifySync, transformSync } = await loadOxcTools();
777
- const transformed = transformSync("markless-inline-resumer.js", source, {
778
- lang: "js",
779
- sourceType: "script",
780
- target: "es2020"
781
- });
782
- assertOxcResult("transform", transformed.errors);
783
- const minified = minifySync("markless-inline-resumer.js", transformed.code, {
784
- compress: true,
785
- mangle: { toplevel: true },
786
- module: false
787
- });
788
- assertOxcResult("minify", minified.errors);
789
- return minified.code.trim();
790
- }
791
- function assertOxcResult(phase, errors) {
792
- if (errors.length === 0) return;
793
- throw new Error(`MARKLESS_INLINE_RESUMER_${phase.toUpperCase()}_FAILED:\n${errors.map((error) => error.message).join("\n")}`);
794
- }
795
- const compiledPrerenderSources = /* @__PURE__ */ new Map();
796
- function compilePrerenderInlineResumerSources() {
797
- let compiled = compiledPrerenderSources.get("production");
798
- if (!compiled) {
799
- compiled = compilePrerenderVariants();
800
- compiledPrerenderSources.set("production", compiled);
801
- }
802
- return compiled;
803
- }
804
- async function compilePrerenderVariants() {
805
- const [prerender, prerenderSelfWake, prerenderSettle] = await Promise.all([
806
- compilePrerenderInlineResumerSource(false),
807
- compilePrerenderInlineResumerSource(true),
808
- compilePrerenderInlineResumerSource("settle")
809
- ]);
810
- return {
811
- prerender,
812
- prerenderSelfWake,
813
- prerenderSettle
814
- };
815
- }
816
- async function compilePrerenderInlineResumerSource(selfWake) {
817
- const source = parameterizedPrerenderInlineResumerSource(selfWake);
818
- const { minifySync, transformSync } = await loadOxcTools();
819
- const transformed = transformSync("markless-prerender-inline-resumer.js", source, {
820
- lang: "js",
821
- sourceType: "script",
822
- target: "es2020"
823
- });
824
- assertOxcResult("transform", transformed.errors);
825
- const minified = minifySync("markless-prerender-inline-resumer.js", transformed.code, {
826
- compress: true,
827
- mangle: { toplevel: true },
828
- module: false
829
- });
830
- assertOxcResult("minify", minified.errors);
831
- const code = minified.code.trim();
832
- if (code.split(PRERENDER_INLINE_EVENT_NAMES_TOKEN).length !== 2) throw new Error("MARKLESS_PRERENDER_INLINE_RESUMER_EVENT_NAMES_TOKEN_LOST");
833
- return code;
834
- }
835
- function parameterizedPrerenderInlineResumerSource(selfWake) {
836
- const placeholder = [PRERENDER_INLINE_EVENT_NAMES_TOKEN];
837
- const literal = JSON.stringify(placeholder);
838
- const plain = selfWake === "settle" ? createPrerenderSettleInlineResumerSource(placeholder, void 0) : createPrerenderInlineResumerSource(placeholder, void 0);
839
- if (plain.split(literal).length !== 2) throw new Error("MARKLESS_PRERENDER_INLINE_RESUMER_EVENT_NAMES_UNPLACEABLE");
840
- return `${plain.replace(literal, PRERENDER_INLINE_EVENT_NAMES_TOKEN)}${selfWake === true ? createInlineResumerSelfWakeSource(void 0) : ""}`;
841
- }
842
- //#endregion
843
371
  //#region src/build/symbol-bundles.ts
844
372
  const SYMBOL_BUNDLE_VIRTUAL_PREFIX = `${MARKLESS_VIRTUAL_PREFIX}symbol-bundle:`;
845
373
  function symbolBundleVirtualModuleId(filename, index) {
@@ -1272,6 +800,10 @@ async function transformTsrxModuleWithPrerenderWakeClosure(input, linkedChildHas
1272
800
  storageSeeds: storageSeeds.length > 0 ? storageSeeds : void 0,
1273
801
  inlineResumerSources,
1274
802
  prerenderBoot,
803
+ ...input.environment === "server" ? { sharedInlineSourcesModuleId: sharedInlineSourcesModuleId({
804
+ debug: input.inlineResumerDebug === true,
805
+ executionLog: input.executionLog ?? "never"
806
+ }) } : {},
1275
807
  devResumeReexport: input.devResumeReexport === true,
1276
808
  needsFullResume: prerenderClosureNeedsWake,
1277
809
  prerenderRecords: input.prerenderRecords,
@@ -1646,32 +1178,62 @@ function authorsPendingArm(markup) {
1646
1178
  }
1647
1179
  //#endregion
1648
1180
  //#region src/build/chunk-ast.ts
1181
+ const UNNAMED_CHUNK = "chunk.js";
1649
1182
  const parsedByExtension = /* @__PURE__ */ new Map();
1183
+ const PARSED_CHUNK_CACHE_MAX_CODE_LENGTH = 16777216;
1184
+ let cachedCodeLength = 0;
1185
+ const codeByFile = /* @__PURE__ */ new Map();
1650
1186
  function parsedFor(fileName) {
1651
1187
  const extension = fileName.slice(fileName.lastIndexOf("."));
1652
1188
  let parsed = parsedByExtension.get(extension);
1653
1189
  if (!parsed) parsedByExtension.set(extension, parsed = /* @__PURE__ */ new Map());
1654
1190
  return parsed;
1655
1191
  }
1656
- function parseChunkCode(fileName, code) {
1192
+ const renderedChunkCounts = /* @__PURE__ */ new WeakMap();
1193
+ function renderedChunkCount(chunks) {
1194
+ let count = renderedChunkCounts.get(chunks);
1195
+ if (count === void 0) renderedChunkCounts.set(chunks, count = Object.keys(chunks).length);
1196
+ return count;
1197
+ }
1198
+ function forgetSuperseded(fileName, code) {
1199
+ const previous = codeByFile.get(fileName);
1200
+ if (previous === void 0 || previous === code) return;
1201
+ if (parsedFor(fileName).delete(previous)) cachedCodeLength -= previous.length;
1202
+ codeByFile.delete(fileName);
1203
+ }
1204
+ function admits(fileName, code) {
1205
+ if (fileName !== UNNAMED_CHUNK) forgetSuperseded(fileName, code);
1206
+ return cachedCodeLength + code.length <= PARSED_CHUNK_CACHE_MAX_CODE_LENGTH;
1207
+ }
1208
+ function remember(fileName, code, result) {
1657
1209
  const parsed = parsedFor(fileName);
1658
- let result = parsed.get(code);
1659
- if (!result) parsed.set(code, result = parseSync(fileName, code));
1210
+ if (parsed.has(code)) return;
1211
+ if (fileName !== UNNAMED_CHUNK) codeByFile.set(fileName, code);
1212
+ parsed.set(code, result);
1213
+ cachedCodeLength += code.length;
1214
+ }
1215
+ function parseChunkCode(fileName, code) {
1216
+ const cached = parsedFor(fileName).get(code);
1217
+ if (cached) return cached;
1218
+ const result = parseSync(fileName, code);
1219
+ if (admits(fileName, code)) remember(fileName, code, result);
1660
1220
  return result;
1661
1221
  }
1662
1222
  async function prefetchChunkParses(chunks) {
1663
1223
  const pending = [];
1224
+ let reserved = 0;
1664
1225
  for (const { fileName, code } of chunks) {
1665
- const parsed = parsedFor(fileName);
1666
- if (parsed.has(code)) continue;
1667
- pending.push(parse(fileName, code).then((result) => {
1668
- if (!parsed.has(code)) parsed.set(code, result);
1669
- }, () => {}));
1226
+ if (parsedFor(fileName).has(code)) continue;
1227
+ if (!admits(fileName, code) || cachedCodeLength + reserved + code.length > 16777216) continue;
1228
+ reserved += code.length;
1229
+ pending.push(parse(fileName, code).then((result) => remember(fileName, code, result), () => {}));
1670
1230
  }
1671
1231
  await Promise.all(pending);
1672
1232
  }
1673
1233
  function clearParsedChunkCode() {
1674
1234
  parsedByExtension.clear();
1235
+ codeByFile.clear();
1236
+ cachedCodeLength = 0;
1675
1237
  }
1676
1238
  function mayContainDynamicImport(code) {
1677
1239
  for (let index = code.indexOf("import"); index >= 0; index = code.indexOf("import", index + 1)) {
@@ -2035,8 +1597,9 @@ const MARKLESS_CHUNK_SPECIFIER_PREFIX = "@markless/c/";
2035
1597
  const SPECIFIER_KEY_LENGTH = 8;
2036
1598
  const PATH_CHARACTER = /[\w\-./~%@+]/;
2037
1599
  /**
2038
- * Rewrites every quoted reference to another hashed chunk (`./chunk-x.js`, `/base/build/chunk-x.js`)
2039
- * into a stable bare specifier, so a chunk's bytes stop depending on the names of the chunks it loads.
1600
+ * Rewrites every quoted reference to a hashed chunk several pages load (`./chunk-x.js`, `/base/build/chunk-x.js`)
1601
+ * into a stable bare specifier, so a shared chunk's new bytes rename only itself. A chunk one page loads keeps
1602
+ * its path and renames that page's chunks, which keeps the document's import map to the shared chunks.
2040
1603
  * References in any other shape keep the file name and stay covered by the content-hash rename.
2041
1604
  */
2042
1605
  async function specifyChunkReferences(bundle, options) {
@@ -2051,19 +1614,42 @@ async function specifyChunkReferences(bundle, options) {
2051
1614
  const matcher = basenameMatcher(hashed.values());
2052
1615
  const keys = await specifierKeys([...hashed.keys()], options.root);
2053
1616
  const specified = /* @__PURE__ */ new Set();
2054
- if (matcher) for (const chunk of chunks) {
2055
- let code = "";
2056
- let cursor = 0;
2057
- for (const match of chunk.code.matchAll(matcher)) {
2058
- const target = byBasename.get(match[0]);
2059
- if (!target) continue;
2060
- const span = quotedReference(chunk, target, match.index, match[0].length, options);
2061
- if (!span || span.start < cursor) continue;
2062
- code += chunk.code.slice(cursor, span.start) + keys.get(target);
2063
- cursor = span.end;
2064
- specified.add(target);
1617
+ if (matcher) {
1618
+ const references = /* @__PURE__ */ new Map();
1619
+ const importers = /* @__PURE__ */ new Map();
1620
+ for (const chunk of chunks) {
1621
+ const found = [];
1622
+ let cursor = 0;
1623
+ for (const match of chunk.code.matchAll(matcher)) {
1624
+ const target = byBasename.get(match[0]);
1625
+ if (!target) continue;
1626
+ const span = quotedReference(chunk, target, match.index, match[0].length, options);
1627
+ if (!span || span.start < cursor) continue;
1628
+ found.push({
1629
+ target,
1630
+ ...span
1631
+ });
1632
+ cursor = span.end;
1633
+ if (target !== chunk) {
1634
+ const set = importers.get(target) ?? /* @__PURE__ */ new Set();
1635
+ set.add(chunk);
1636
+ importers.set(target, set);
1637
+ }
1638
+ }
1639
+ references.set(chunk, found);
1640
+ }
1641
+ const named = namedBySpecifier(chunks, references, importers, options);
1642
+ for (const chunk of chunks) {
1643
+ let code = "";
1644
+ let cursor = 0;
1645
+ for (const { target, start, end } of references.get(chunk)) {
1646
+ if (!named(target)) continue;
1647
+ code += chunk.code.slice(cursor, start) + keys.get(target);
1648
+ cursor = end;
1649
+ specified.add(target);
1650
+ }
1651
+ if (cursor > 0) chunk.code = code + chunk.code.slice(cursor);
2065
1652
  }
2066
- if (cursor > 0) chunk.code = code + chunk.code.slice(cursor);
2067
1653
  }
2068
1654
  return { importMap() {
2069
1655
  const imports = {};
@@ -2071,6 +1657,76 @@ async function specifyChunkReferences(bundle, options) {
2071
1657
  return { imports };
2072
1658
  } };
2073
1659
  }
1660
+ const SHARED = "\0shared";
1661
+ function moduleSourceFile(id, root) {
1662
+ let bare = id.startsWith("\0") ? id.slice(1) : id;
1663
+ const virtual = /^virtual:markless:[\w-]+:(.*)$/.exec(bare);
1664
+ if (virtual) {
1665
+ bare = virtual[1].replace(/:\d+$/, "");
1666
+ try {
1667
+ bare = decodeURIComponent(bare);
1668
+ } catch {}
1669
+ }
1670
+ return withoutMachinePaths(bare.replace(/[?#].*$/, ""), root);
1671
+ }
1672
+ function chunkModuleIds(chunk) {
1673
+ return chunk.moduleIds?.length ? chunk.moduleIds : chunk.facadeModuleId ? [chunk.facadeModuleId] : [];
1674
+ }
1675
+ function chunkPage(chunk, options) {
1676
+ const ids = chunkModuleIds(chunk);
1677
+ const { packs, isRoute, root } = options;
1678
+ if (packs) {
1679
+ const names = new Set(ids.map((id) => startupPackOfLazy(packs.packOf(id) ?? "").replace(/~\d+$/, "")));
1680
+ const [pack] = names;
1681
+ if (names.size === 1 && pack) {
1682
+ const page = /^(?:route|navigation):(?!shared(?::|$))(.+)$/.exec(pack)?.[1];
1683
+ if (page) return page;
1684
+ const routes = pack.startsWith("shared:") ? packs.packRoutes(pack) : void 0;
1685
+ return routes?.length === 1 ? routes[0] : SHARED;
1686
+ }
1687
+ }
1688
+ const sources = new Set(ids.map((id) => moduleSourceFile(id, root)));
1689
+ const [only] = sources;
1690
+ return sources.size === 1 && isRoute?.(only) ? only : void 0;
1691
+ }
1692
+ function namedBySpecifier(chunks, references, importers, options) {
1693
+ if (!options.isRoute && !options.packs) return () => true;
1694
+ const page = /* @__PURE__ */ new Map();
1695
+ for (const chunk of chunks) {
1696
+ const owner = chunkPage(chunk, options);
1697
+ if (owner) page.set(chunk, owner);
1698
+ }
1699
+ const hubs = /* @__PURE__ */ new Set();
1700
+ for (const chunk of chunks) {
1701
+ const pages = /* @__PURE__ */ new Set();
1702
+ for (const { target } of references.get(chunk) ?? []) {
1703
+ const owner = page.get(target);
1704
+ if (owner && owner !== SHARED) pages.add(owner);
1705
+ }
1706
+ if (pages.size > 1) hubs.add(chunk);
1707
+ }
1708
+ const loadedBy = (chunk) => [...importers.get(chunk) ?? []].filter((importer) => !hubs.has(importer));
1709
+ const owners = /* @__PURE__ */ new Map();
1710
+ for (const chunk of chunks) {
1711
+ const own = page.get(chunk);
1712
+ owners.set(chunk, new Set(own ? [own] : loadedBy(chunk).length === 0 ? [SHARED] : []));
1713
+ }
1714
+ for (let changed = true; changed;) {
1715
+ changed = false;
1716
+ for (const chunk of chunks) {
1717
+ const set = owners.get(chunk);
1718
+ if (set.has(SHARED)) continue;
1719
+ const before = set.size;
1720
+ for (const importer of loadedBy(chunk)) for (const owner of owners.get(importer)) set.add(owner);
1721
+ if (set.size > 1) {
1722
+ set.clear();
1723
+ set.add(SHARED);
1724
+ }
1725
+ if (set.size !== before) changed = true;
1726
+ }
1727
+ }
1728
+ return (target) => owners.get(target).size !== 1 || owners.get(target).has(SHARED);
1729
+ }
2074
1730
  function quotedReference(importer, target, index, length, options) {
2075
1731
  const code = importer.code;
2076
1732
  let start = index;
@@ -2346,6 +2002,18 @@ function* bundleGraphEdges(graph) {
2346
2002
  function normalizeManifestOrigin(origin) {
2347
2003
  return withoutLeadingSlash(normalize(origin));
2348
2004
  }
2005
+ function entryReachableModuleIds(context) {
2006
+ const ids = [...context.getModuleIds()];
2007
+ const reached = /* @__PURE__ */ new Set();
2008
+ const pending = ids.filter((id) => context.getModuleInfo(id)?.isEntry);
2009
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
2010
+ if (reached.has(id)) continue;
2011
+ reached.add(id);
2012
+ const info = context.getModuleInfo(id);
2013
+ if (info) pending.push(...info.importedIds, ...info.dynamicallyImportedIds);
2014
+ }
2015
+ return ids.filter((id) => reached.has(id));
2016
+ }
2349
2017
  //#endregion
2350
2018
  //#region src/build/byte-attribution.ts
2351
2019
  const BYTE_CATEGORY = {
@@ -2512,7 +2180,7 @@ function lazyModuleFacadesPlugin(root = () => "", packOf, packRoutes, eagerLazyR
2512
2180
  resolve,
2513
2181
  reject
2514
2182
  });
2515
- if (pending.size !== Object.keys(meta.chunks).length) return;
2183
+ if (pending.size !== renderedChunkCount(meta.chunks)) return;
2516
2184
  const collapse = () => {
2517
2185
  try {
2518
2186
  const results = /* @__PURE__ */ new Map();
@@ -3159,8 +2827,7 @@ function planShortExportNames(chunks) {
3159
2827
  return true;
3160
2828
  }, strings);
3161
2829
  }
3162
- const text = strings.join("\n");
3163
- for (const chunk of chunks) if (text.includes(chunk.fileName.slice(chunk.fileName.lastIndexOf("/") + 1))) escaping.add(chunk.fileName);
2830
+ for (const fileName of namedInStrings(strings, chunks.map((chunk) => chunk.fileName))) escaping.add(fileName);
3164
2831
  const renames = /* @__PURE__ */ new Map();
3165
2832
  const pruned = /* @__PURE__ */ new Map();
3166
2833
  const finalNames = /* @__PURE__ */ new Map();
@@ -3235,6 +2902,39 @@ function planShortExportNames(chunks) {
3235
2902
  exports: new Map([...finalNames].map(([fileName, list]) => [fileName, list.filter((name) => !pruned.get(fileName)?.has(name)).map((name) => renames.get(fileName)?.get(name) ?? name)]))
3236
2903
  };
3237
2904
  }
2905
+ function namedInStrings(strings, fileNames) {
2906
+ const baseOf = (fileName) => fileName.slice(fileName.lastIndexOf("/") + 1);
2907
+ const byExtension = /* @__PURE__ */ new Map();
2908
+ const bare = [];
2909
+ for (const fileName of fileNames) {
2910
+ const base = baseOf(fileName);
2911
+ if (!base.includes(".")) {
2912
+ bare.push(base);
2913
+ continue;
2914
+ }
2915
+ const extension = base.slice(base.lastIndexOf("."));
2916
+ const bases = byExtension.get(extension) ?? /* @__PURE__ */ new Set();
2917
+ bases.add(base);
2918
+ byExtension.set(extension, bases);
2919
+ }
2920
+ const found = /* @__PURE__ */ new Set();
2921
+ for (const [extension, bases] of byExtension) {
2922
+ const lengths = [...new Set([...bases].map((base) => base.length))];
2923
+ for (const value of strings) for (let at = value.indexOf(extension); at !== -1; at = value.indexOf(extension, at + 1)) {
2924
+ const end = at + extension.length;
2925
+ for (const length of lengths) {
2926
+ if (length > end) continue;
2927
+ const candidate = value.slice(end - length, end);
2928
+ if (bases.has(candidate)) found.add(candidate);
2929
+ }
2930
+ }
2931
+ }
2932
+ if (bare.length) {
2933
+ const text = strings.join("\n");
2934
+ for (const base of bare) if (text.includes(base)) found.add(base);
2935
+ }
2936
+ return fileNames.filter((fileName) => found.has(baseOf(fileName)));
2937
+ }
3238
2938
  /** Deterministic: each name is the shortest prefix of its own hash that no other name in the set shares. */
3239
2939
  function shortNames(names, taken = /* @__PURE__ */ new Set()) {
3240
2940
  const hashes = [...new Set(names)].map((name) => [name, identifierHash(name)]);
@@ -3276,7 +2976,7 @@ function shortExportNamesPlugin(removedChunks = () => /* @__PURE__ */ new Set())
3276
2976
  resolve,
3277
2977
  reject
3278
2978
  });
3279
- if (pending.size !== Object.keys(meta.chunks).length) return;
2979
+ if (pending.size !== renderedChunkCount(meta.chunks)) return;
3280
2980
  try {
3281
2981
  const plan = planShortExportNames([...pending.values()].map((item) => item.chunk));
3282
2982
  exports = new Map(plan.exports);
@@ -3705,6 +3405,11 @@ function withUndemandedReExportDoors(modules, undemanded) {
3705
3405
  }
3706
3406
  return result;
3707
3407
  }
3408
+ //#endregion
3409
+ //#region src/build/interaction-closures.ts
3410
+ function isAuthoredLazyImport(id) {
3411
+ return !isCompilerStatefulModuleId(id) && !isMarklessRuntimeModule(id) && !/^\0|^virtual:|\.mdx(?:$|\?)|[\\/]@markless[\\/]/.test(id) && runtimeModuleIdFromOrigin(id.split("?")[0]) === void 0;
3412
+ }
3708
3413
  const RUNS_WITHOUT_INPUT = {
3709
3414
  "async-boundary": true,
3710
3415
  behavior: true,
@@ -3741,6 +3446,7 @@ function computeInteractionClosures(input) {
3741
3446
  for (const [route, ids] of input.routes) for (const id of ids) routeOf.set(id, route);
3742
3447
  const knownRuntimeIds = /* @__PURE__ */ new Set();
3743
3448
  for (const merged of demand.values()) for (const id of merged.unknownRecordModuleIds) knownRuntimeIds.add(id);
3449
+ const sharedClosures = /* @__PURE__ */ new Map();
3744
3450
  const useClosure = (route, reach, seeds, bound, named) => {
3745
3451
  const seen = /* @__PURE__ */ new Set();
3746
3452
  const pending = [...seeds].map((id) => [id, void 0]);
@@ -3759,6 +3465,7 @@ function computeInteractionClosures(input) {
3759
3465
  for (const dependency of module.dependencies) pending.push([dependency, inside]);
3760
3466
  for (const target of module.dynamicDependencies ?? []) {
3761
3467
  if (routeOf.has(target) && routeOf.get(target) !== (inside ?? route)) continue;
3468
+ if (!routeOf.has(target) && isAuthoredLazyImport(target)) continue;
3762
3469
  if (!bound) {
3763
3470
  pending.push([target, inside]);
3764
3471
  continue;
@@ -3770,7 +3477,12 @@ function computeInteractionClosures(input) {
3770
3477
  pending.push([target, inside]);
3771
3478
  }
3772
3479
  }
3773
- return [...seen].sort();
3480
+ const ids = [...seen].sort();
3481
+ const key = ids.join("\0");
3482
+ const shared = sharedClosures.get(key);
3483
+ if (shared) return shared;
3484
+ sharedClosures.set(key, ids);
3485
+ return ids;
3774
3486
  };
3775
3487
  const result = [];
3776
3488
  for (const route of [...input.routes.keys()].sort()) {
@@ -3824,6 +3536,13 @@ function computeInteractionClosures(input) {
3824
3536
  const bootRoots = roots.filter((id) => !isSymbolModule(id) && !renderRoots.includes(id));
3825
3537
  const landingReach = useClosure(route, reach, roots.filter((id) => !renderRoots.includes(id)));
3826
3538
  const page = pageIndex(files, demand);
3539
+ const actionClosures = /* @__PURE__ */ new Map();
3540
+ const actionClosure = (seeds, runtimeIds) => {
3541
+ const key = `${[...seeds].join("\0")}\u0001${[...runtimeIds].sort().join("\0")}`;
3542
+ let ids = actionClosures.get(key);
3543
+ if (!ids) actionClosures.set(key, ids = useClosure(route, reach, seeds, { runtimeIds }, seeds));
3544
+ return ids;
3545
+ };
3827
3546
  const resume = joinPage(page.resume, page);
3828
3547
  const bootSeeds = new Set(bootRoots);
3829
3548
  let bootBounded = resume !== "unknown" && [...files].every((file) => !demand.get(file).replaced);
@@ -3905,7 +3624,7 @@ function computeInteractionClosures(input) {
3905
3624
  kind: "action",
3906
3625
  ...conservative ? { conservative } : {},
3907
3626
  ...lean ? { lean: true } : {},
3908
- modules: useClosure(route, reach, seeds, { runtimeIds }, seeds)
3627
+ modules: actionClosure(seeds, runtimeIds)
3909
3628
  });
3910
3629
  }
3911
3630
  }
@@ -3924,9 +3643,32 @@ function interactionClosuresAsset(input) {
3924
3643
  };
3925
3644
  const packs = /* @__PURE__ */ new Map();
3926
3645
  for (const [id, name] of input.packs) push(packs, name, display(id, input.root));
3646
+ const displayed = /* @__PURE__ */ new Map();
3647
+ for (const route of input.closures) for (const consumer of route.consumers) for (const id of consumer.modules) if (!displayed.has(id)) displayed.set(id, display(id, input.root));
3648
+ const modules = [...new Set(displayed.values())].sort();
3649
+ const moduleIndex = new Map(modules.map((id, index) => [id, index]));
3650
+ const closureSets = [];
3651
+ const closureIndex = /* @__PURE__ */ new Map();
3652
+ const closureByKey = /* @__PURE__ */ new Map();
3653
+ const closureOf = (ids) => {
3654
+ const known = closureIndex.get(ids);
3655
+ if (known !== void 0) return known;
3656
+ const indexes = [...new Set(ids.map((id) => moduleIndex.get(displayed.get(id))))].sort((a, b) => a - b);
3657
+ const key = indexes.join(",");
3658
+ let index = closureByKey.get(key);
3659
+ if (index === void 0) {
3660
+ index = closureSets.length;
3661
+ closureSets.push(indexes);
3662
+ closureByKey.set(key, index);
3663
+ }
3664
+ closureIndex.set(ids, index);
3665
+ return index;
3666
+ };
3927
3667
  return JSON.stringify({
3928
- version: 1,
3668
+ version: 2,
3929
3669
  partition: input.partition,
3670
+ modules,
3671
+ closures: closureSets,
3930
3672
  routes: input.closures.map((route) => ({
3931
3673
  route: route.route,
3932
3674
  ...route.fallback ? { fallback: route.fallback } : {},
@@ -3939,7 +3681,7 @@ function interactionClosuresAsset(input) {
3939
3681
  kind: consumer.kind,
3940
3682
  ...consumer.conservative ? { conservative: consumer.conservative } : {},
3941
3683
  ...consumer.lean ? { lean: true } : {},
3942
- modules: consumer.modules.map((id) => display(id, input.root)).sort()
3684
+ closure: closureOf(consumer.modules)
3943
3685
  }))
3944
3686
  })),
3945
3687
  packs: Object.fromEntries([...packs].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([name, ids]) => [name, ids.sort()])),
@@ -4175,6 +3917,10 @@ function nativePackingPlugins(root, demandMaps = () => [], demandSources = () =>
4175
3917
  return [
4176
3918
  {
4177
3919
  name: "markless:route-packs",
3920
+ api: {
3921
+ packOf: (id) => groups.get(id),
3922
+ packRoutes: (pack) => routeSets.get(pack)
3923
+ },
4178
3924
  options(input) {
4179
3925
  return {
4180
3926
  ...input,
@@ -4193,7 +3939,7 @@ function nativePackingPlugins(root, demandMaps = () => [], demandSources = () =>
4193
3939
  const routeSources = /* @__PURE__ */ new Set();
4194
3940
  const entrySources = /* @__PURE__ */ new Set();
4195
3941
  const entryIds = /* @__PURE__ */ new Set();
4196
- for (const id of this.getModuleIds()) {
3942
+ for (const id of entryReachableModuleIds(this)) {
4197
3943
  const info = this.getModuleInfo(id);
4198
3944
  if (!info || "isExternal" in info && info.isExternal) continue;
4199
3945
  const handlerSource = sourceForSymbolVirtualImporter(id);
@@ -4385,12 +4131,13 @@ function resolverVirtualModuleId(source) {
4385
4131
  }
4386
4132
  function linkedClaims(metadata, sources, environment, unawaited = /* @__PURE__ */ new Set()) {
4387
4133
  for (const source of sources) if (!unawaited.has(source)) metadata.assertSourceClaimsSealed(environment, source);
4134
+ const requests = sources.map((source) => ({
4135
+ source,
4136
+ resolverId: resolverVirtualModuleId(source)
4137
+ }));
4388
4138
  return linkClaimManifests({
4389
- byEmittedModule: metadata.symbolClaimMap(),
4390
- sources: sources.map((source) => ({
4391
- source,
4392
- resolverId: resolverVirtualModuleId(source)
4393
- }))
4139
+ byEmittedModule: metadata.symbolClaimMapForResolvers(requests.map((request) => request.resolverId)),
4140
+ sources: requests
4394
4141
  });
4395
4142
  }
4396
4143
  function sourceSymbolManifest(metadata, source, environment, unawaited) {
@@ -4548,7 +4295,9 @@ async function resolveImportedChildren(context, parent, manifest, fallbackSource
4548
4295
  }
4549
4296
  async function forceImportedModules(context, children, moduleArtifacts, metadata, options, environment) {
4550
4297
  for (const child of children) {
4551
- const loadSource = linkedModuleLoadSource(child, moduleArtifacts.has(child.source));
4298
+ const artifact = moduleArtifacts.get(child.source);
4299
+ const pendingRequest = options.dev === true || metadata.waitsOn(environment, child.source, pathname$1(child.parent)) ? void 0 : artifact?.provisionalUntil;
4300
+ const loadSource = linkedModuleLoadSource(child, artifact !== void 0 && pendingRequest === void 0) && (pendingRequest ?? child.source);
4552
4301
  if (loadSource !== void 0) await metadata.whileWaiting(environment, pathname$1(child.parent), child.source, async () => {
4553
4302
  if (options.dev === true) await options.devServer?.transformRequest(loadSource, environment);
4554
4303
  else if (typeof context.load === "function") await context.load({ id: loadSource });
@@ -4672,6 +4421,16 @@ function moduleLinkArtifact(result) {
4672
4421
  delegateChildren: delegateChildResolutionRequests(result.artifactChildren).length > 0
4673
4422
  };
4674
4423
  }
4424
+ function publishModuleLinkArtifact(artifacts, source, artifact, options) {
4425
+ const current = artifacts.get(source);
4426
+ if (options.provisionalUntil !== void 0) {
4427
+ if (!options.dev && current && current.provisionalUntil === void 0) return;
4428
+ artifacts.set(source, {
4429
+ ...artifact,
4430
+ provisionalUntil: options.provisionalUntil
4431
+ });
4432
+ } else artifacts.set(source, artifact);
4433
+ }
4675
4434
  async function materializeDelegateChildren(context, parent, candidates, options = {}) {
4676
4435
  const resolution = {};
4677
4436
  for (const candidate of delegateChildResolutionRequests(candidates)) {
@@ -4821,6 +4580,8 @@ function createBuildDelegateLoader() {
4821
4580
  async function moduleCode(id, resolve, root) {
4822
4581
  const virtual = virtualSources.get(normalizeVirtualId$2(id));
4823
4582
  if (virtual !== void 0) return virtual;
4583
+ const sharedInlineSources = await sharedInlineSourcesModuleSource(normalizeVirtualId$2(id));
4584
+ if (sharedInlineSources !== null) return sharedInlineSources;
4824
4585
  const file = pathname$1(id);
4825
4586
  const source = await readFile(file, "utf8");
4826
4587
  if (!isTsrxModule(file)) return await stripEmittedTypes(source, file);
@@ -4837,6 +4598,7 @@ function createBuildDelegateLoader() {
4837
4598
  }
4838
4599
  async function importSpecifier(specifier, importer, resolve, root) {
4839
4600
  const virtualId = normalizeVirtualId$2(specifier);
4601
+ if (isSharedInlineSourcesModuleId(virtualId)) return await load(virtualId, resolve, root);
4840
4602
  const virtualOwner = marklessVirtualModuleSourceFile(virtualId, root);
4841
4603
  if (virtualOwner) {
4842
4604
  if (!virtualSources.has(virtualId)) await load(virtualOwner, resolve, root);
@@ -4912,6 +4674,9 @@ function publicationKey(environment, source) {
4912
4674
  var ModuleMetadataRegistry = class ModuleMetadataRegistry {
4913
4675
  #captureManifestsBySource = /* @__PURE__ */ new Map();
4914
4676
  #symbolClaimsByEmittedModule = /* @__PURE__ */ new Map();
4677
+ #claimOwnersByResolver = /* @__PURE__ */ new Map();
4678
+ #claimOrder = /* @__PURE__ */ new Map();
4679
+ #nextClaimOrder = 0;
4915
4680
  #sourceClaimPublications = /* @__PURE__ */ new Map();
4916
4681
  #waits = /* @__PURE__ */ new Map();
4917
4682
  #publication(environment, source) {
@@ -4952,6 +4717,8 @@ var ModuleMetadataRegistry = class ModuleMetadataRegistry {
4952
4717
  clear() {
4953
4718
  this.#captureManifestsBySource.clear();
4954
4719
  this.#symbolClaimsByEmittedModule.clear();
4720
+ this.#claimOwnersByResolver.clear();
4721
+ this.#claimOrder.clear();
4955
4722
  this.#sourceClaimPublications.clear();
4956
4723
  this.#waits.clear();
4957
4724
  }
@@ -4966,11 +4733,28 @@ var ModuleMetadataRegistry = class ModuleMetadataRegistry {
4966
4733
  this.#captureManifestsBySource.delete(source);
4967
4734
  }
4968
4735
  recordSymbolClaims(emittedModule, manifest) {
4736
+ const previous = this.#symbolClaimsByEmittedModule.get(emittedModule);
4737
+ if (previous) this.#unindexClaimOwner(emittedModule, previous);
4738
+ else this.#claimOrder.set(emittedModule, this.#nextClaimOrder++);
4969
4739
  this.#symbolClaimsByEmittedModule.set(emittedModule, manifest);
4740
+ const resolverId = manifest.resolver.virtualModuleId;
4741
+ const owners = this.#claimOwnersByResolver.get(resolverId);
4742
+ if (owners) owners.add(emittedModule);
4743
+ else this.#claimOwnersByResolver.set(resolverId, /* @__PURE__ */ new Set([emittedModule]));
4970
4744
  }
4971
4745
  deleteSymbolClaims(emittedModule) {
4746
+ const previous = this.#symbolClaimsByEmittedModule.get(emittedModule);
4747
+ if (!previous) return;
4748
+ this.#unindexClaimOwner(emittedModule, previous);
4749
+ this.#claimOrder.delete(emittedModule);
4972
4750
  this.#symbolClaimsByEmittedModule.delete(emittedModule);
4973
4751
  }
4752
+ #unindexClaimOwner(emittedModule, manifest) {
4753
+ const resolverId = manifest.resolver.virtualModuleId;
4754
+ const owners = this.#claimOwnersByResolver.get(resolverId);
4755
+ owners?.delete(emittedModule);
4756
+ if (owners?.size === 0) this.#claimOwnersByResolver.delete(resolverId);
4757
+ }
4974
4758
  hasSymbolClaims(emittedModule) {
4975
4759
  return this.#symbolClaimsByEmittedModule.has(emittedModule);
4976
4760
  }
@@ -5106,6 +4890,13 @@ var ModuleMetadataRegistry = class ModuleMetadataRegistry {
5106
4890
  symbolClaimMap() {
5107
4891
  return this.#symbolClaimsByEmittedModule;
5108
4892
  }
4893
+ /** The claims routed through these resolvers, in the order `symbolClaimMap` lists them. */
4894
+ symbolClaimMapForResolvers(resolverIds) {
4895
+ const owners = /* @__PURE__ */ new Set();
4896
+ for (const resolverId of resolverIds) for (const owner of this.#claimOwnersByResolver.get(resolverId) ?? []) owners.add(owner);
4897
+ const order = this.#claimOrder;
4898
+ return new Map([...owners].sort((left, right) => order.get(left) - order.get(right)).map((owner) => [owner, this.#symbolClaimsByEmittedModule.get(owner)]));
4899
+ }
5109
4900
  /**
5110
4901
  * The publication barrier every reader shares: an emitted sibling that has
5111
4902
  * begun publishing must have finished a publication before its source's claims
@@ -5220,7 +5011,7 @@ function registerTransformArtifacts(state, input) {
5220
5011
  const stored = {
5221
5012
  ...module,
5222
5013
  ...isClientSymbol ? { source: requalifyExecutionLogModuleHook(module.source, logId) } : {},
5223
- ...input.finalPublication === false && (module.type === "resolver" || module.type === "symbol") ? { provisional: true } : {}
5014
+ ...input.finalPublication === false && (module.type === "resolver" || module.type === "symbol" || module.type === "render-data" && input.devServer !== true) ? { provisional: true } : {}
5224
5015
  };
5225
5016
  const published = publishesVirtualModule(stored, state.virtualModules.get(module.id));
5226
5017
  if (published) state.virtualModules.set(module.id, stored);
@@ -5253,7 +5044,10 @@ function registerTransformArtifacts(state, input) {
5253
5044
  });
5254
5045
  if (input.tracksSourceClaimPublication === true) state.moduleMetadata.finishSourceSymbolClaims(input.environment, input.source, input.manifestSource);
5255
5046
  }
5256
- state.moduleLinkArtifacts(input.environment).set(input.source, moduleLinkArtifact(input.result));
5047
+ publishModuleLinkArtifact(state.moduleLinkArtifacts(input.environment), input.source, moduleLinkArtifact(input.result), {
5048
+ provisionalUntil: input.finalPublication === false ? input.request : void 0,
5049
+ dev: input.devServer === true
5050
+ });
5257
5051
  const previouslyOwned = state.transformVirtualModules.get(input.owner) ?? /* @__PURE__ */ new Set();
5258
5052
  if (input.replaceOwnedArtifacts === true) {
5259
5053
  for (const staleId of previouslyOwned) {
@@ -5273,8 +5067,8 @@ function registerTransformArtifacts(state, input) {
5273
5067
  function publishesVirtualModule(next, current) {
5274
5068
  if (!current) return true;
5275
5069
  if (next.provisional === true) return false;
5070
+ if (current.provisional === true) return true;
5276
5071
  if (next.type === "resolver" && current.type === "resolver") {
5277
- if (current.provisional === true) return true;
5278
5072
  const verdict = linkedResolverClaimVerdict({
5279
5073
  resolverId: next.id,
5280
5074
  current: current.symbolClaims,
@@ -7613,9 +7407,10 @@ function rewriteGeneratedSymbolInitExports(bundle) {
7613
7407
  if (rewrite.collapsed) rewrite.chunk.code = rewrite.collapsed.code;
7614
7408
  for (const [from, to] of rewrite.names) replacements.set(from, to);
7615
7409
  }
7410
+ const rename = identifierRenamer(replacements);
7616
7411
  for (const chunk of chunks.values()) {
7617
7412
  if (!isGeneratedAsyncChunk(chunk)) continue;
7618
- chunk.code = replaceIdentifierNames(chunk.code, replacements);
7413
+ chunk.code = rename(chunk.code);
7619
7414
  }
7620
7415
  return { renamed: replacements.size };
7621
7416
  }
@@ -7941,30 +7736,32 @@ function isGeneratedChunk(value) {
7941
7736
  function unique(values) {
7942
7737
  return [...new Set(values)];
7943
7738
  }
7944
- function replaceIdentifierNames(code, replacements) {
7739
+ function identifierRenamer(replacements) {
7945
7740
  const names = [...replacements.keys()].sort((a, b) => b.length - a.length);
7946
7741
  const resolved = /* @__PURE__ */ new Map();
7947
7742
  for (const name of names.reverse()) {
7948
7743
  const replacement = replacements.get(name);
7949
7744
  resolved.set(name, resolved.get(replacement) ?? replacement);
7950
7745
  }
7951
- if (names.some((name) => !name.includes(SYMBOL_INIT_EXPORT_PREFIX) && !/\$\d/.test(name))) return code.replace(/(?<![$\w])[$A-Z_a-z][$\w]*/g, (name) => resolved.get(name) ?? name);
7952
- const anchors = new RegExp(`${escapeRegExp(SYMBOL_INIT_EXPORT_PREFIX)}|\\$\\d`, "g");
7953
- let next = "";
7954
- let cursor = 0;
7955
- for (let match = anchors.exec(code); match; match = anchors.exec(code)) {
7956
- let start = match.index;
7957
- while (start > 0 && isIdentifierPart(code.charCodeAt(start - 1))) start--;
7958
- let end = match.index + match[0].length;
7959
- while (end < code.length && isIdentifierPart(code.charCodeAt(end))) end++;
7960
- anchors.lastIndex = end;
7961
- if (start < cursor || isDigit(code.charCodeAt(start))) continue;
7962
- const replacement = resolved.get(code.slice(start, end));
7963
- if (replacement === void 0) continue;
7964
- next += code.slice(cursor, start) + replacement;
7965
- cursor = end;
7966
- }
7967
- return cursor === 0 ? code : next + code.slice(cursor);
7746
+ if (names.some((name) => !name.includes(SYMBOL_INIT_EXPORT_PREFIX) && !/\$\d/.test(name))) return (code) => code.replace(/(?<![$\w])[$A-Z_a-z][$\w]*/g, (name) => resolved.get(name) ?? name);
7747
+ return (code) => {
7748
+ const anchors = new RegExp(`${escapeRegExp(SYMBOL_INIT_EXPORT_PREFIX)}|\\$\\d`, "g");
7749
+ let next = "";
7750
+ let cursor = 0;
7751
+ for (let match = anchors.exec(code); match; match = anchors.exec(code)) {
7752
+ let start = match.index;
7753
+ while (start > 0 && isIdentifierPart(code.charCodeAt(start - 1))) start--;
7754
+ let end = match.index + match[0].length;
7755
+ while (end < code.length && isIdentifierPart(code.charCodeAt(end))) end++;
7756
+ anchors.lastIndex = end;
7757
+ if (start < cursor || isDigit(code.charCodeAt(start))) continue;
7758
+ const replacement = resolved.get(code.slice(start, end));
7759
+ if (replacement === void 0) continue;
7760
+ next += code.slice(cursor, start) + replacement;
7761
+ cursor = end;
7762
+ }
7763
+ return cursor === 0 ? code : next + code.slice(cursor);
7764
+ };
7968
7765
  }
7969
7766
  function isIdentifierPart(char) {
7970
7767
  return char >= 48 && char <= 57 || char >= 65 && char <= 90 || char >= 97 && char <= 122 || char === 36 || char === 95;
@@ -8075,7 +7872,9 @@ async function finalizeBundle(context, bundle, input) {
8075
7872
  if (tableIntegrity.errors.length > 0) context.error(`Markless symbol resolver table integrity check failed:\n${tableIntegrity.errors.map((error) => `- ${error.symbolId} -> ${error.claimedChunk}: ${error.reason}`).join("\n")}`);
8076
7873
  const specifiers = chunkImportMapEnabled(options) ? await specifyChunkReferences(manifestBundle, {
8077
7874
  publicPath: options.publicPath ?? ((fileName) => `/${fileName}`),
8078
- root: input.root
7875
+ root: input.root,
7876
+ isRoute: options.routeModules,
7877
+ packs: input.packs
8079
7878
  }) : void 0;
8080
7879
  await renameChunksToContentHashes(manifestBundle, { hashCharacters: input.hashCharacters });
8081
7880
  resortInteractionClosuresFiles(bundle);
@@ -8211,7 +8010,7 @@ function injectImportMap(bundle, script) {
8211
8010
  }
8212
8011
  //#endregion
8213
8012
  //#region src/hooks/generate-bundle.ts
8214
- async function generateBundleHook(ctx, pluginContext, bundle, hashCharacters) {
8013
+ async function generateBundleHook(ctx, pluginContext, bundle, hashCharacters, packs) {
8215
8014
  const { internalOptions, linkedChildren } = ctx;
8216
8015
  const { moduleMetadata, executionLogEmittedIds } = ctx.state;
8217
8016
  throwLinkedModuleChildDiagnostics(moduleMetadata, [...linkedChildren.values()]);
@@ -8222,7 +8021,8 @@ async function generateBundleHook(ctx, pluginContext, bundle, hashCharacters) {
8222
8021
  root: ctx.getRoot(),
8223
8022
  executionLogEmittedIds,
8224
8023
  executionAttributionTables: ctx.attributionTables,
8225
- hashCharacters
8024
+ hashCharacters,
8025
+ packs
8226
8026
  });
8227
8027
  }
8228
8028
  //#endregion
@@ -8232,6 +8032,7 @@ async function resolveIdHook(ctx, pluginContext, source, importer) {
8232
8032
  const runtimeCatalogId = marklessRuntimeSpecifierId(source);
8233
8033
  if (runtimeCatalogId) return { id: runtimeCatalogId };
8234
8034
  const normalized = normalizeVirtualId$2(source);
8035
+ if (isSharedInlineSourcesModuleId(normalized)) return { id: resolveVirtualId(normalized) };
8235
8036
  if (normalized === "virtual:markless:dev-log") return {
8236
8037
  id: resolveVirtualId(MARKLESS_EXECUTION_LOG_MODULE_ID),
8237
8038
  moduleSideEffects: true
@@ -8264,10 +8065,12 @@ async function loadHook(ctx, pluginContext, id) {
8264
8065
  return executionLogVirtualModuleSource({
8265
8066
  moduleSizes: embedsDevSizes ? executionLogEstimatedSizes : void 0,
8266
8067
  attribution: embedsDevSizes ? ctx.attributionTables(moduleMetadata.symbolClaimMap().values()) : void 0,
8267
- sizesUrl: internalOptions.dev === true ? void 0 : internalOptions.publicPath?.(MARKLESS_EXECUTION_SIZES) ?? `/${MARKLESS_EXECUTION_SIZES}`
8068
+ sizesUrl: internalOptions.dev === true ? void 0 : internalOptions.publicPath?.("build/execution-sizes.json") ?? `/build/execution-sizes.json`
8268
8069
  });
8269
8070
  }
8270
8071
  const normalizedId = normalizeVirtualId$2(id);
8072
+ const sharedInlineSources = await sharedInlineSourcesModuleSource(normalizedId);
8073
+ if (sharedInlineSources !== null) return sharedInlineSources;
8271
8074
  const resolverSource = resolverVirtualModuleSourceFile(normalizedId);
8272
8075
  const symbolSource = symbolVirtualModuleSourceFile(normalizedId);
8273
8076
  const renderDataSource = normalizedId.startsWith(`virtual:markless:render-data:`) ? marklessVirtualModuleSourceFile(normalizedId, ctx.getRoot()) : null;
@@ -8284,7 +8087,7 @@ async function loadHook(ctx, pluginContext, id) {
8284
8087
  }
8285
8088
  const module = await virtualModuleForRequest(ctx, normalizedId, ctx.getEnvironment(pluginContext), { waitForRegeneration: true });
8286
8089
  if (module?.provisional === true) {
8287
- const kind = module.type === "symbol" ? "SYMBOL" : "RESOLVER";
8090
+ const kind = module.type === "symbol" ? "SYMBOL" : module.type === "resolver" ? "RESOLVER" : "RENDER_DATA";
8288
8091
  throw new Error(`MARKLESS_${kind}_UNPUBLISHED: ${module.type} ${JSON.stringify(normalizedId)} was loaded before its owner ${JSON.stringify(ownerSource)} published a final compile.`);
8289
8092
  }
8290
8093
  if (module) return virtualModuleSourceForLoad(module, {
@@ -8689,12 +8492,17 @@ function registerFirstPassArtifacts(request, transformed) {
8689
8492
  environment: currentEnvironment,
8690
8493
  finalPublication: false,
8691
8494
  tracksSourceClaimPublication: false,
8495
+ devServer: internalOptions.dev === true,
8496
+ request: request.id,
8692
8497
  updateDevPrerenderHashes: internalOptions.updateDevPrerenderHashes
8693
8498
  });
8694
8499
  else {
8695
8500
  moduleMetadata.recordCaptureMetadata(source, transformed.manifest);
8696
8501
  moduleMetadata.recordSymbolClaims(manifestSource, renderDataClaimManifest(transformed.manifest, manifestSource));
8697
- moduleLinkArtifacts.set(source, moduleLinkArtifact(transformed));
8502
+ publishModuleLinkArtifact(moduleLinkArtifacts, source, moduleLinkArtifact(transformed), {
8503
+ provisionalUntil: request.id,
8504
+ dev: internalOptions.dev === true
8505
+ });
8698
8506
  }
8699
8507
  }
8700
8508
  function registerFinalTransformArtifacts(request, transformed) {
@@ -8718,6 +8526,7 @@ function registerFinalTransformArtifacts(request, transformed) {
8718
8526
  else {
8719
8527
  moduleMetadata.recordCaptureMetadata(source, transformed.manifest);
8720
8528
  moduleMetadata.recordSymbolClaims(manifestSource, renderDataClaimManifest(transformed.manifest, manifestSource));
8529
+ state.moduleLinkArtifacts(currentEnvironment).set(source, moduleLinkArtifact(transformed));
8721
8530
  }
8722
8531
  }
8723
8532
  function recordLinkedTransform(request, transformed, linkedTransformInput, linked) {
@@ -8857,7 +8666,7 @@ function sharesCanonicalRenderData(request, renderDataModule) {
8857
8666
  if (renderDataReachedFromQuery(request.id) !== void 0) return false;
8858
8667
  if (renderDataModule.type !== "render-data" || renderDataModule.canonicalRenderData !== true) return false;
8859
8668
  const registered = request.ctx.state.virtualModules.get(renderDataModule.id);
8860
- return registered?.canonicalRenderData !== true || registered.source === renderDataModule.source;
8669
+ return registered?.canonicalRenderData !== true || registered.provisional === true || registered.source === renderDataModule.source;
8861
8670
  }
8862
8671
  function registerClientRouteArtifactSource(ctx, source) {
8863
8672
  const { internalOptions } = ctx;
@@ -9020,7 +8829,10 @@ async function runFirstPassTransform(request) {
9020
8829
  } catch {
9021
8830
  throw error;
9022
8831
  }
9023
- moduleLinkArtifacts.set(source, provisional);
8832
+ publishModuleLinkArtifact(moduleLinkArtifacts, source, provisional, {
8833
+ provisionalUntil: request.id,
8834
+ dev: internalOptions.dev === true
8835
+ });
9024
8836
  const provisionalImports = await resolveImportedModuleInterfaces(pluginContext, manifestSource, provisional.moduleImports, fallbackImportedSource);
9025
8837
  let provisionalBarrels;
9026
8838
  try {
@@ -9141,6 +8953,7 @@ function createMarklessRolldownPlugin(input) {
9141
8953
  function getRoot() {
9142
8954
  return root ?? internalOptions.rootDir;
9143
8955
  }
8956
+ let declaredPacks;
9144
8957
  const [packing, facades] = environment === "client" && nativePackingEnabled(internalOptions) && !internalOptions.dev ? nativePackingPlugins(() => getRoot() ?? "", runtimeDemandMaps, runtimeDemandSources) : [];
9145
8958
  function* runtimeDemandMaps() {
9146
8959
  for (const manifest of state.moduleMetadata.symbolClaimManifests()) yield manifest.runtimeDemandMap;
@@ -9188,6 +9001,9 @@ function createMarklessRolldownPlugin(input) {
9188
9001
  },
9189
9002
  declareRouteModules: (isRoute) => {
9190
9003
  internalOptions.routeModules = isRoute;
9004
+ },
9005
+ declarePackOwnership: (packs) => {
9006
+ declaredPacks = packs;
9191
9007
  }
9192
9008
  },
9193
9009
  name,
@@ -9240,7 +9056,8 @@ function createMarklessRolldownPlugin(input) {
9240
9056
  async handler(output, bundle, isWrite) {
9241
9057
  const hook = facades?.generateBundle;
9242
9058
  await (typeof hook === "function" ? hook : hook?.handler)?.call(this, output, bundle, isWrite);
9243
- await generateBundleHook(context, this, bundle, output.hashCharacters);
9059
+ await generateBundleHook(context, this, bundle, output.hashCharacters, packing?.api ?? declaredPacks);
9060
+ clearParsedChunkCode();
9244
9061
  }
9245
9062
  },
9246
9063
  async writeBundle(output, bundle) {
@@ -9264,4 +9081,4 @@ function pluginName(environment) {
9264
9081
  return `markless:rolldown:${environment}`;
9265
9082
  }
9266
9083
  //#endregion
9267
- export { createInlineDeferTriggerSource as A, MARKLESS_IMPORT_MAP_ASSET as C, preflightTsrxModuleDiagnostics as D, prefetchChunkParses as E, moduleIdFor as M, transformTsrxModule as O, MARKLESS_CHUNK_SPECIFIER_PREFIX as S, insertImportMapScript as T, createPreloadGraphAdder as _, collapseInitFacadeImports as a, marklessBuildManifestPath as b, collectHeadLinkInjections as c, nativePackingEnabled as d, nativePackingPlugins as f, convertManifestToBundleGraph as g, withUndemandedReExportDoors as h, marklessServer as i, inlineDeferSource as j, INLINE_DEFER_LOADER_SOURCE as k, marklessRuntimeSpecifierId as l, undemandedRuntimeModules as m, marklessClient as n, unwrapAsyncImportWrappers as o, isReExportDoor as p, marklessLib as r, createBuildMetadata as s, createMarklessRolldownPlugin as t, DEPRECATED_NATIVE_PACKING_WARNING as u, runtimeModuleIdFromOrigin as v, importMapScript as w, marklessImportMapPath as x, marklessBuildManifestDir as y };
9084
+ export { moduleIdFor as A, MARKLESS_CHUNK_SPECIFIER_PREFIX as C, prefetchChunkParses as D, insertImportMapScript as E, preflightTsrxModuleDiagnostics as O, marklessImportMapPath as S, importMapScript as T, createPreloadGraphAdder as _, collapseInitFacadeImports as a, marklessBuildManifestDir as b, collectHeadLinkInjections as c, nativePackingEnabled as d, nativePackingPlugins as f, convertManifestToBundleGraph as g, withUndemandedReExportDoors as h, marklessServer as i, transformTsrxModule as k, marklessRuntimeSpecifierId as l, undemandedRuntimeModules as m, marklessClient as n, unwrapAsyncImportWrappers as o, isReExportDoor as p, marklessLib as r, createBuildMetadata as s, createMarklessRolldownPlugin as t, DEPRECATED_NATIVE_PACKING_WARNING as u, entryReachableModuleIds as v, MARKLESS_IMPORT_MAP_ASSET as w, marklessBuildManifestPath as x, runtimeModuleIdFromOrigin as y };