@jxsuite/compiler 11.1.2 → 11.2.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.
@@ -39,8 +39,10 @@ import {
39
39
  } from "@jxsuite/schema/guards";
40
40
  import { cemManifest, cemManifestText } from "@jxsuite/schema/cem-manifest";
41
41
  import type { CemDefinition } from "@jxsuite/schema/cem-manifest";
42
- import { DEFAULT_CHARSET } from "@jxsuite/schema/defs";
42
+ import { DEFAULT_CHARSET, REDIRECT_STATUSES } from "@jxsuite/schema/defs";
43
+ import { classifyFunctionEntries } from "@jxsuite/schema/function-role";
43
44
  import { errorMessage } from "@jxsuite/schema/parse";
45
+ import { buildReferenceView, relationshipTargets } from "@jxsuite/schema/reference-view";
44
46
  import {
45
47
  isNpmSpecifier,
46
48
  npmAssetPath,
@@ -62,6 +64,7 @@ import {
62
64
  } from "./bundler.ts";
63
65
  import type { BundleRequest } from "./bundler.ts";
64
66
  import { negotiatesRoot } from "./locale-negotiation.ts";
67
+ import { pageRelativePath, routePatternProblem } from "@jxsuite/site/routes";
65
68
  import { loadProjectConfig } from "./site-loader.ts";
66
69
  import type { ResolvedProjectConfig } from "./site-loader.ts";
67
70
  import {
@@ -69,6 +72,7 @@ import {
69
72
  expandDynamicRoutes,
70
73
  readPageDocument,
71
74
  readTranslationKeys,
75
+ resolveRouteCollisions,
72
76
  } from "./pages-discovery.ts";
73
77
  import {
74
78
  buildHeaderRules,
@@ -78,7 +82,7 @@ import {
78
82
  writeNoJekyll,
79
83
  } from "./headers-emitter.ts";
80
84
  import { buildProjectExtensionRegistry } from "./format-host.ts";
81
- import { loadProjectSections } from "./project-sections.ts";
85
+ import { loadProjectSections, sectionOwnerActive } from "./project-sections.ts";
82
86
  import type { ProjectSections } from "./project-sections.ts";
83
87
  import { collectAssetRefs, copyMountedAssets, loadAssetMounts } from "./asset-mounts.ts";
84
88
  import type { AssetMount } from "@jxsuite/schema/asset-paths";
@@ -92,6 +96,7 @@ import {
92
96
  scriptRefSide,
93
97
  } from "@jxsuite/schema/document-scripts";
94
98
  import { layoutChain, resolveLayout } from "./layout-resolver.ts";
99
+ import { lowerExternalCases, wrapCaseDocument } from "../switch-cases.ts";
95
100
  import { dedupeServerEntries, documentServerEntries } from "./server-entries.ts";
96
101
  import type { DedupedServerEntries, ServerEntryRecord } from "./server-entries.ts";
97
102
  import { unrenderedHeadWarnings, mergeHead, renderHead } from "@jxsuite/site/head-merger";
@@ -114,15 +119,20 @@ import {
114
119
  buildInitialScope,
115
120
  collectSrcImports,
116
121
  buildInstanceScope,
122
+ cloneValue,
117
123
  collectStyles,
118
124
  colorSchemePrePaintScript,
119
125
  computeLiveTags,
120
126
  createSlotFill,
127
+ keepSlotted,
128
+ slotPlaceholder,
121
129
  definitionHasSlot,
122
130
  escapeStyleText,
123
131
  evaluateStaticTemplate,
124
132
  inheritProjectFormulas,
133
+ isLiteralNode,
125
134
  isLiveComponent,
135
+ markLiteral,
126
136
  isPureNamedFormula,
127
137
  isRuntimeOnlyStateKey,
128
138
  listSettled,
@@ -132,18 +142,22 @@ import {
132
142
  nextSlotId,
133
143
  orderComponentTags,
134
144
  preRenderComponentHtml,
145
+ refReadsRuntimeOnlyState,
146
+ resolveRefValue,
147
+ resolveStaticValue,
135
148
  pureSchemeOf,
136
149
  referencesStateKey,
137
- renderStaticNode,
138
150
  resolveHostAttributes,
139
151
  resolveHostStyle,
140
152
  refuseTemplateItems,
141
153
  buildListRows,
142
154
  tagNameToClassName,
155
+ assertExpressionRules,
143
156
  } from "../shared.ts";
144
- import type { ComponentPrerenderContext, StaticChild } from "../shared.ts";
157
+ import type { ComponentPrerenderContext, SlottedChild, StaticChild } from "../shared.ts";
145
158
  import { SLOT_ATTR } from "@jxsuite/runtime";
146
159
  import { resolvePrototypes } from "./prototype-resolver.ts";
160
+ import type { BuildRequestCache } from "./build-time-request.ts";
147
161
  import { classEntrySource, locateClass, readsBuildContext } from "./external-class.ts";
148
162
  import { literalReplacement, transformImageNodes } from "./image-transform.ts";
149
163
  import { withSocialImageSize } from "./social-image.ts";
@@ -537,13 +551,10 @@ export async function buildSite(
537
551
  // A mount is active when its class owns no project section, or the project declares a
538
552
  // Non-empty value for its section key. Sites with active mounts always get a worker; a
539
553
  // Static site cannot serve dynamic sections, so that combination is a build error.
540
- const activeMounts = registry.serverMounts().filter((entry) => {
541
- if (!entry.project) {
542
- return true;
543
- }
544
- const value = projectConfig[entry.project.key];
545
- return isNonNullObject(value) && Object.keys(value).length > 0;
546
- });
554
+ // (specs/extensions.md §8.4 defines empty.)
555
+ const activeMounts = registry
556
+ .serverMounts()
557
+ .filter((entry) => sectionOwnerActive(entry, projectConfig));
547
558
  if (activeMounts.length > 0 && !projectConfig.build.adapter) {
548
559
  const sections = activeMounts
549
560
  .map((entry) => (entry.project ? `"${entry.project.key}"` : `"${entry.server!.basePath}"`))
@@ -554,6 +565,11 @@ export async function buildSite(
554
565
  );
555
566
  }
556
567
 
568
+ // The worker's imports, resolved here rather than at step 6c so a mount or connector with no
569
+ // Import specifier (specs/extensions.md §11, §12) fails before dist/ is cleaned. Mount options
570
+ // Inline the project's section manifest, never a secret value (§13).
571
+ const workerImports = buildMountSpecs(activeMounts, registry, projectConfig);
572
+
557
573
  closePhase("setup");
558
574
 
559
575
  // ── 2. Clean output directory ───────────────────────────────────────────
@@ -571,6 +587,17 @@ export async function buildSite(
571
587
  const staticRoutes = await discoverPages(pagesDir, formatRegistry);
572
588
  log(` Found ${staticRoutes.length} page(s)`);
573
589
 
590
+ /* A page file whose name would derive a pattern outside the forms routes use is an error naming
591
+ the file (site-architecture.md §4.2). The route stays in the table so the rest builds. */
592
+ for (const route of staticRoutes) {
593
+ const problem = routePatternProblem(route.relativePath);
594
+ if (problem) {
595
+ const message = `pages/${pageRelativePath(route.relativePath)}: ${problem}. Rename the file.`;
596
+ errors.push(message);
597
+ console.error(message);
598
+ }
599
+ }
600
+
574
601
  // ── 3b. Load extension-contributed project sections ────────────────────
575
602
  log("Loading project sections...");
576
603
  const sections = await loadProjectSections(projectRoot, projectConfig, registry, { includeHeld });
@@ -601,16 +628,24 @@ export async function buildSite(
601
628
 
602
629
  // ── 4. Expand dynamic routes ────────────────────────────────────────────
603
630
  const extensionHead = await collectExtensionHead(registry, projectConfig, projectRoot);
604
-
605
- const expandedRoutes = await expandDynamicRoutes(
606
- staticRoutes,
607
- projectRoot,
608
- sections,
609
- registry,
610
- projectConfig,
611
- i18n,
612
- { errors },
631
+ // One build's `timing: "compiler"` `Request` fetches, shared by every page and component it serves.
632
+ // Declared before the expansion, which resolves a paged list's request from the same cache.
633
+ const requestCache: BuildRequestCache = new Map();
634
+
635
+ const { collisions, routes: expandedRoutes } = resolveRouteCollisions(
636
+ await expandDynamicRoutes(staticRoutes, projectRoot, sections, registry, projectConfig, i18n, {
637
+ errors,
638
+ requestCache,
639
+ }),
613
640
  );
641
+ for (const collision of collisions) {
642
+ if (collision.kind === "tie") {
643
+ errors.push(collision.message);
644
+ console.error(collision.message);
645
+ } else {
646
+ console.warn(collision.message);
647
+ }
648
+ }
614
649
  /*
615
650
  * Every route carries the locale it serves, resolved once here rather than re-derived by each
616
651
  * reader. It is what scopes a `ContentEntry` lookup on a localized collection: two translations
@@ -658,7 +693,12 @@ export async function buildSite(
658
693
  const componentPathByTag = new Map<string, string>();
659
694
  /* What this build compiles: every file directly in `components/`, plus every component a page,
660
695
  a layout or project.json names by `$ref`, wherever it lives (site-architecture.md §10.3). */
661
- const { components: siteComponents, errors: componentErrors } = await collectSiteComponents({
696
+ const {
697
+ components: siteComponents,
698
+ errors: componentErrors,
699
+ cases: siteCases,
700
+ caseReach,
701
+ } = await collectSiteComponents({
662
702
  formatRegistry,
663
703
  pageSources: routes.map((route) => route.sourcePath),
664
704
  projectConfig,
@@ -668,7 +708,15 @@ export async function buildSite(
668
708
  errors.push(message);
669
709
  console.error(message);
670
710
  }
671
- if (siteComponents.length > 0) {
711
+ /* Each external `$switch` case the build accepted is a compiled element under its generated tag
712
+ (spec.md §14.1). Every document is lowered against the file that declares it, so a case
713
+ reference becomes an instance of that element before any merge or compile. */
714
+ const casePathToTag = new Map(siteCases.map((c) => [c.path, c.tagName]));
715
+ const lowerCases = (doc: JxDocument, filePath: string): JxDocument =>
716
+ lowerExternalCases(doc, dirname(filePath), (path) => casePathToTag.get(path));
717
+ const caseTags = new Set(casePathToTag.values());
718
+ const elementCaseModules = new Map([...caseTags].map((tag) => [tag, `./${tag}.js`]));
719
+ if (siteComponents.length > 0 || siteCases.length > 0) {
672
720
  log("Compiling components...");
673
721
  const componentOutDir = resolve(outDir, "components");
674
722
  mkdirSync(componentOutDir, { recursive: true });
@@ -676,7 +724,9 @@ export async function buildSite(
676
724
  // Emitted modules are named after the component's `tagName` — the name the page's loader
677
725
  // `<script>` and the CSS sidecar both use, wherever the source file lives. So a component's
678
726
  // `$elements` imports are renamed to match, which needs every component's tag up front.
679
- const componentTagByPath = new Map(siteComponents.map((c) => [c.path, c.tagName]));
727
+ const componentTagByPath = new Map(
728
+ [...siteComponents, ...siteCases].map((c) => [c.path, c.tagName]),
729
+ );
680
730
  // The components whose stylesheet this build writes, and so the only ones a module may link.
681
731
  const localTags = new Set(componentTagByPath.values());
682
732
  // Each component's own rules, and which of them render into a shadow root (spec.md §16.6).
@@ -737,6 +787,7 @@ export async function buildSite(
737
787
  rewriteSidecarSrc(specifier, null);
738
788
  },
739
789
  registry,
790
+ requestCache,
740
791
  sections,
741
792
  },
742
793
  );
@@ -750,13 +801,23 @@ export async function buildSite(
750
801
  }
751
802
  };
752
803
 
753
- for (const { doc: written, path: componentPath } of siteComponents) {
804
+ const toCompile: { doc: JxDocument; path: string; caseTag?: string }[] = [
805
+ ...siteComponents.map((c) => ({ doc: c.doc, path: c.path })),
806
+ ...siteCases.map((c) => ({ caseTag: c.tagName, doc: c.doc, path: c.path })),
807
+ ];
808
+ for (const { doc: written, path: componentPath, caseTag } of toCompile) {
754
809
  /* The definition every page prerenders from, with the project formulas it reads (spec.md
755
- §13.4). The module is compiled from the file, and is given the same project state. */
756
- const doc = inheritProjectFormulas(written, projectConfig.state);
810
+ §13.4). The module is compiled from the file, and is given the same project state. A case
811
+ is its generated host holding the document's root, as `compileElement` wraps it. */
812
+ const lowered = lowerCases(written, componentPath);
813
+ const doc = inheritProjectFormulas(
814
+ caseTag === undefined ? lowered : wrapCaseDocument(lowered, caseTag),
815
+ projectConfig.state,
816
+ );
757
817
  try {
758
818
  await prepareComponent(doc, componentPath);
759
819
  const elementOptions: CompileElementOptions = {
820
+ caseModules: elementCaseModules,
760
821
  formats: formatRegistry,
761
822
  /* The module's own copy of the definition is re-rooted after its images are decided, so
762
823
  what the module draws is what the page rewrite makes of the prerender. The copy every
@@ -777,6 +838,7 @@ export async function buildSite(
777
838
  rewriteSrc: (specifier: string, docDir: string | null) =>
778
839
  withBase(componentBase, rewriteSidecarSrc(specifier, docDir)),
779
840
  serverBaseUrl,
841
+ transformDocument: lowerCases,
780
842
  /* A root the module attaches itself links the sheet its prerender would have. Only for
781
843
  a component whose sheet is written below; a `$elements` dependency compiled from
782
844
  elsewhere has none. */
@@ -790,6 +852,9 @@ export async function buildSite(
790
852
  it a page shipped a declarative root and a module that cleared the light DOM and
791
853
  rendered into the host beside it. */
792
854
  elementOptions.defaults = projectConfig.defaults;
855
+ if (caseTag !== undefined) {
856
+ elementOptions.caseTag = caseTag;
857
+ }
793
858
  const result = await compileElement(componentPath, elementOptions);
794
859
  for (const f of result.files) {
795
860
  // Name the output after the tag. `injectComponentScripts` emits
@@ -852,8 +917,9 @@ export async function buildSite(
852
917
  } catch (error) {
853
918
  const message = errorMessage(error);
854
919
  const file = relative(projectRoot, componentPath).replaceAll("\\", "/");
855
- errors.push(`Error compiling component ${file}: ${message}`);
856
- console.error(`Error compiling component ${file}: ${message}`);
920
+ const kind = caseTag === undefined ? "component" : "case";
921
+ errors.push(`Error compiling ${kind} ${file}: ${message}`);
922
+ console.error(`Error compiling ${kind} ${file}: ${message}`);
857
923
  }
858
924
  }
859
925
  /* A shadow component's file carries its own rules and those of every light component it can
@@ -882,8 +948,11 @@ export async function buildSite(
882
948
  * its own `package.json` and nothing else has to be rewritten. A build that compiled no
883
949
  * component writes none.
884
950
  */
885
- if (componentDefs.size > 0) {
886
- const definitions = [...componentDefs].map(([tag, doc]): CemDefinition => ({
951
+ /* The generated host of an external `$switch` case is the build's, not the project's own element
952
+ (spec.md §14.1), so the manifest leaves it out. */
953
+ const manifestDefs = [...componentDefs].filter(([tag]) => !caseTags.has(tag));
954
+ if (manifestDefs.length > 0) {
955
+ const definitions = manifestDefs.map(([tag, doc]): CemDefinition => ({
887
956
  className: tagNameToClassName(tag),
888
957
  doc,
889
958
  modulePath: relative(projectRoot, resolve(outDir, "components", `${tag}.js`))
@@ -1064,6 +1133,18 @@ export async function buildSite(
1064
1133
  * therefore on every page.
1065
1134
  */
1066
1135
  const warnedRelations = new Set<string>();
1136
+ /* Each case module's specifier from this route's own module, which is written beside its HTML:
1137
+ relative, so a base-path deployment resolves it as it resolves the module itself. */
1138
+ const pageCaseModules = (route: PageRoute): Map<string, string> => {
1139
+ const pageDir = dirname(routeToOutputPath(route.urlPattern, outDir, trailingSlash));
1140
+ return new Map(
1141
+ [...caseTags].map((tag) => {
1142
+ const target = relative(pageDir, resolve(outDir, "components", `${tag}.js`));
1143
+ const specifier = target.split(sep).join("/");
1144
+ return [tag, specifier.startsWith(".") ? specifier : `./${specifier}`];
1145
+ }),
1146
+ );
1147
+ };
1067
1148
  /* Head material the build does not render (a flat attribute key, a `<title>` entry) is as silent
1068
1149
  as a mistyped `rel`, and lives in the same shared heads, so it is warned once per message too. */
1069
1150
  const warnedUnrenderedHead = new Set<string>();
@@ -1101,6 +1182,9 @@ export async function buildSite(
1101
1182
  runtimeImports,
1102
1183
  registerElementBundle,
1103
1184
  deliverClass,
1185
+ lowerCases,
1186
+ pageCaseModules(route),
1187
+ requestCache,
1104
1188
  );
1105
1189
  siteServerEntries.push(...result.serverEntries);
1106
1190
 
@@ -1128,10 +1212,15 @@ export async function buildSite(
1128
1212
  result.html,
1129
1213
  compiledComponentTags,
1130
1214
  componentCSS,
1131
- new Set(compiledComponentTags.filter((tag) => !result.liveTags.has(tag))),
1215
+ new Set(
1216
+ compiledComponentTags.filter(
1217
+ (tag) => !result.liveTags.has(tag) && !result.liveInstanceTags.includes(tag),
1218
+ ),
1219
+ ),
1132
1220
  result.files.map((f: { content: string }) => f.content).join("\n"),
1133
1221
  runtimeImports,
1134
1222
  scriptOrder,
1223
+ { reach: caseReach, tags: caseTags },
1135
1224
  );
1136
1225
  }
1137
1226
 
@@ -1313,9 +1402,17 @@ export async function buildSite(
1313
1402
  console.error(error);
1314
1403
  }
1315
1404
 
1316
- // Extension server mounts: static imports of the mount modules and used connector classes,
1317
- // Inlined JSON options (the project's section manifest — identifiers only, never secrets).
1318
- const { mounts, connectors } = buildMountSpecs(activeMounts, registry, projectConfig);
1405
+ // The mount and connector specs were resolved at step 1c (`workerImports`). `references`
1406
+ // Inlines the referenced entries' `projectData` output (id and frontmatter), attached here
1407
+ // From the step-3b sections.
1408
+ const { connectors } = workerImports;
1409
+ const mounts = attachReferenceViews(
1410
+ workerImports.mounts,
1411
+ activeMounts,
1412
+ projectConfig,
1413
+ sections,
1414
+ log,
1415
+ );
1319
1416
  if (mounts.length > 0) {
1320
1417
  log(
1321
1418
  ` Mounting ${mounts.length} extension route(s): ${mounts.map((m) => m.basePath).join(", ")}`,
@@ -1539,12 +1636,8 @@ export async function buildSite(
1539
1636
  for (const entry of registry.emitters()) {
1540
1637
  const sectionKey = entry.project?.key;
1541
1638
  const sectionValue = sectionKey ? projectConfig[sectionKey] : undefined;
1542
- if (
1543
- sectionKey &&
1544
- (sectionValue == null ||
1545
- (isNonNullObject(sectionValue) && Object.keys(sectionValue).length === 0))
1546
- ) {
1547
- continue; // Section owner with nothing declared — same gating as sections/mounts
1639
+ if (!sectionOwnerActive(entry, projectConfig)) {
1640
+ continue; // The §8.4 gate, shared with assets, head and mount activation
1548
1641
  }
1549
1642
  try {
1550
1643
  /* The emit contract (extensions.md §8.4) answers outDir-relative files, or null for none; each
@@ -1806,6 +1899,12 @@ async function compilePage(
1806
1899
  docDir: string | null,
1807
1900
  imports: Record<string, string>,
1808
1901
  ) => string,
1902
+ /** Lowers a document's external `$switch` cases against the file that declares them. */
1903
+ lower: (doc: JxDocument, filePath: string) => JxDocument,
1904
+ /** Generated case tag to its module's specifier from this page's module (spec.md §14.1). */
1905
+ caseModules: ReadonlyMap<string, string>,
1906
+ /** The build's shared `timing: "compiler"` `Request` fetches (spec.md §11.3). */
1907
+ requestCache: BuildRequestCache,
1809
1908
  ) {
1810
1909
  /* Derived rather than passed as one more parameter: it is a pure function of
1811
1910
  `projectConfig.url`, which is already here, so the two cannot disagree. */
@@ -1813,14 +1912,17 @@ async function compilePage(
1813
1912
 
1814
1913
  // Load the raw page document (.json natively, other formats via the registry). Its `#client` and
1815
1914
  // `#server` name this page from here on, before a layout's can meet them (spec.md §23.2).
1816
- const pageDoc = qualifiedDocument(
1817
- await readPageDocument(route.sourcePath, formatRegistry),
1915
+ const pageDoc = lower(
1916
+ qualifiedDocument(
1917
+ await readPageDocument(route.sourcePath, formatRegistry),
1918
+ route.sourcePath,
1919
+ projectRoot,
1920
+ ),
1818
1921
  route.sourcePath,
1819
- projectRoot,
1820
1922
  );
1821
1923
 
1822
1924
  // Resolve layout (wraps page in layout with slot distribution)
1823
- const layoutDoc = await resolveLayout(pageDoc, projectConfig, projectRoot);
1925
+ const layoutDoc = await resolveLayout(pageDoc, projectConfig, projectRoot, lower);
1824
1926
 
1825
1927
  /*
1826
1928
  * This page's and its layouts' server entries, each read from the file that declares it, so a
@@ -1852,6 +1954,9 @@ async function compilePage(
1852
1954
  locale.translations,
1853
1955
  facts,
1854
1956
  );
1957
+ /* Before `resolvePrototypes` and `buildInitialScope` evaluate anything, so a refused page is never
1958
+ run at build time, and `project.json`'s state, merged in just above, is judged with it. */
1959
+ assertExpressionRules(layoutDoc);
1855
1960
  /* The title is page metadata and never the root's `title` attribute, which would be a tooltip over
1856
1961
  the whole page. `pageTitle` was read above and `injectContext` has just read `$page.title`; with
1857
1962
  no layout this is `pageDoc` itself, and with one it is a clone of the outermost layout, whose own
@@ -1886,6 +1991,14 @@ async function compilePage(
1886
1991
  layoutDoc.state[route.pagedState.key] = route.pagedState.items;
1887
1992
  }
1888
1993
 
1994
+ /* The keys the author declared `timing: "compiler"`, read before resolution: a resolved value is
1995
+ no longer a prototype def that says so, and an array value carries no marker to say so either. */
1996
+ const compilerTimedKeys = new Set(
1997
+ Object.entries(layoutDoc.state ?? {})
1998
+ .filter(([, def]) => isJsonObject(def) && def.timing === "compiler")
1999
+ .map(([key]) => key),
2000
+ );
2001
+
1889
2002
  // Resolve generic $prototype entries via .class.json imports (and lower registry classes)
1890
2003
  await resolvePrototypes(layoutDoc, route, projectRoot, {
1891
2004
  config: projectConfig,
@@ -1893,6 +2006,7 @@ async function compilePage(
1893
2006
  rewriteSidecarSrc(specifier, null);
1894
2007
  },
1895
2008
  registry,
2009
+ requestCache,
1896
2010
  sections,
1897
2011
  });
1898
2012
 
@@ -1908,6 +2022,7 @@ async function compilePage(
1908
2022
  const scope = buildInitialScope(layoutDoc.state ?? {}, null, {
1909
2023
  document: layoutDoc,
1910
2024
  holdMutable: true,
2025
+ roles: classifyFunctionEntries(layoutDoc),
1911
2026
  });
1912
2027
 
1913
2028
  /*
@@ -1975,13 +2090,6 @@ async function compilePage(
1975
2090
  };
1976
2091
  // One counter per page, so every `data-jx-slots` id on it is unique (spec.md §8.5).
1977
2092
  const slotIds = { n: 0 };
1978
- /* Children written inside an instance are serialized here, before the page compiles, so nothing
1979
- binds them afterwards (spec.md §15.2). A template the pass above left for the client would
1980
- therefore be lost, so it is resolved against a scope that does not hold: the entry's initial
1981
- value is what the page shows. Built on first use: most pages place no such template, and the
1982
- scope clones the page's whole state. */
1983
- let slotScopeMemo: JxScope | undefined;
1984
- const slotScope = () => (slotScopeMemo ??= buildInitialScope(layoutDoc.state ?? {}));
1985
2093
  /*
1986
2094
  * Which components ship their module on this page (compiler.md §8.1): a definition that is not
1987
2095
  * fully static, and every registered tag such a definition renders when this page draws it,
@@ -1990,12 +2098,14 @@ async function compilePage(
1990
2098
  * before the expansion, which replaces each instance's children with its prerender.
1991
2099
  */
1992
2100
  const liveTags = computeLiveTags(componentDefs, layoutDoc);
2101
+ const liveInstanceTags = new Set<string>();
1993
2102
  expandComponents(layoutDoc, componentDefs, {
1994
2103
  defaults: projectConfig.defaults,
2104
+ liveInstanceTags,
1995
2105
  liveTags,
2106
+ scope,
1996
2107
  slotCss,
1997
2108
  slotIds,
1998
- slotScope,
1999
2109
  });
2000
2110
 
2001
2111
  // Strip resolved timing: "compiler" state entries — they're now baked into the tree
@@ -2019,7 +2129,7 @@ async function compilePage(
2019
2129
  if (key === "$site" || key === "$page") {
2020
2130
  continue;
2021
2131
  }
2022
- if (isJsonObject(def) && def.timing === "compiler") {
2132
+ if (compilerTimedKeys.has(key) || (isJsonObject(def) && def.timing === "compiler")) {
2023
2133
  delete layoutDoc.state[key];
2024
2134
  } else if (Array.isArray(def)) {
2025
2135
  droppable.add(key);
@@ -2155,6 +2265,7 @@ async function compilePage(
2155
2265
 
2156
2266
  // Compile the document using the existing compiler
2157
2267
  const compileOptions: CompileOptions = {
2268
+ caseModules,
2158
2269
  lang: language.lang,
2159
2270
  prePaintScheme: false, // Injected via the merged <head> above, not the target template
2160
2271
  projectStyle: projectConfig.style ?? null,
@@ -2228,6 +2339,7 @@ async function compilePage(
2228
2339
  excludeFromSitemap: pageDoc.$sitemap === false,
2229
2340
  files: result.files,
2230
2341
  html: result.html,
2342
+ liveInstanceTags: [...liveInstanceTags],
2231
2343
  liveTags,
2232
2344
  /*
2233
2345
  * Reported rather than warned about here: a mistyped `rel` almost always lives in the site or
@@ -2251,8 +2363,11 @@ async function compilePage(
2251
2363
  *
2252
2364
  * Mount options inline the extension-contributed sections from project.json — identifiers only,
2253
2365
  * never secrets (§13). Connector classes are included when any section entry names their
2254
- * `connector.provider`; the import specifier comes from the descriptor's `connector.module` (bare
2255
- * specifier — Workers cannot import filesystem paths).
2366
+ * `connector.provider`; the import specifier comes from the descriptor's `connector.module`.
2367
+ *
2368
+ * Runs at step 1c of `buildSite`, before `dist/` is cleaned, so a missing import specifier leaves
2369
+ * the previous build in place. Specifiers resolve from the project root when the worker is bundled
2370
+ * (`bundleWorkerSource`).
2256
2371
  *
2257
2372
  * @param {FormatEntry[]} activeMounts - Server-mount classes with active sections
2258
2373
  * @param {ExtensionRegistry} registry
@@ -2280,10 +2395,12 @@ function buildMountSpecs(
2280
2395
  const mounts: SiteMountSpec[] = activeMounts.map((entry) => {
2281
2396
  const server = entry.server!;
2282
2397
  const { module } = server;
2398
+ const className = entry.classDef.title ?? entry.name;
2283
2399
  if (!isString(module) || module === "") {
2284
2400
  throw new Error(
2285
- `Extension class "${entry.name}": server.module (a bare import specifier) is required ` +
2286
- `to generate a deployable worker`,
2401
+ `Extension class "${entry.name}" mounts ${server.basePath} but declares no server.module, ` +
2402
+ `the import specifier (resolved from the project root) a deployable worker imports ` +
2403
+ `"${className}" from. The dev server's $implementation is not used for a build.`,
2287
2404
  );
2288
2405
  }
2289
2406
  /* Both are request paths in the deployed worker: the route it registers, and the prefix the
@@ -2292,7 +2409,7 @@ function buildMountSpecs(
2292
2409
  const mountBase = withBase(base, server.basePath);
2293
2410
  return {
2294
2411
  basePath: mountBase,
2295
- className: entry.classDef.title ?? entry.name,
2412
+ className,
2296
2413
  module,
2297
2414
  options: { basePath: mountBase, sections },
2298
2415
  order: server.order ?? 100,
@@ -2337,6 +2454,45 @@ function buildMountSpecs(
2337
2454
  return { connectors, mounts };
2338
2455
  }
2339
2456
 
2457
+ /**
2458
+ * Attach each mount's `references`: the entries of the file-based sections its own section points
2459
+ * at (specs/relationships.md §2), built from the step-3b loaded sections. A deployed worker has no
2460
+ * content directory, so this snapshot is how `?include=` reaches content. A mount whose section
2461
+ * holds no pointer keeps its options as they were.
2462
+ *
2463
+ * @param {SiteMountSpec[]} mounts - Specs from {@link buildMountSpecs}, one per active mount
2464
+ * @param {FormatEntry[]} activeMounts - The classes those specs were built from, in the same order
2465
+ * @param {ProjectConfig} projectConfig
2466
+ * @param {ProjectSections} sections - Extension-loaded project sections
2467
+ * @param {(message: string) => void} log
2468
+ * @returns {SiteMountSpec[]}
2469
+ */
2470
+ function attachReferenceViews(
2471
+ mounts: SiteMountSpec[],
2472
+ activeMounts: FormatEntry[],
2473
+ projectConfig: ProjectConfig,
2474
+ sections: ProjectSections,
2475
+ log: (message: string) => void,
2476
+ ): SiteMountSpec[] {
2477
+ return mounts.map((spec) => {
2478
+ const key = activeMounts.find(
2479
+ (entry) => (entry.classDef.title ?? entry.name) === spec.className,
2480
+ )?.project?.key;
2481
+ const targets = key === undefined ? [] : relationshipTargets(projectConfig[key]);
2482
+ const view = buildReferenceView(targets, sections, projectConfig);
2483
+ const named = targets.filter(({ name, section }) => view[section]?.[name] !== undefined);
2484
+ if (named.length === 0) {
2485
+ return spec;
2486
+ }
2487
+ log(
2488
+ ` Inlined referenced entries: ${named
2489
+ .map(({ name, section }) => `${section}/${name} (${view[section]![name]!.length})`)
2490
+ .join(", ")}`,
2491
+ );
2492
+ return { ...spec, options: { ...spec.options, references: view } };
2493
+ });
2494
+ }
2495
+
2340
2496
  /** What the generated worker imports and mounts, as `buildMountSpecs` derives it. */
2341
2497
  interface WorkerMountSpecs {
2342
2498
  mounts: SiteMountSpec[];
@@ -2360,7 +2516,7 @@ async function collectExtensionHead(
2360
2516
  for (const entry of registry.headProviders()) {
2361
2517
  const key = entry.project?.key;
2362
2518
  const sectionValue = key === undefined ? null : projectConfig[key];
2363
- if (key !== undefined && (sectionValue === undefined || sectionValue === null)) {
2519
+ if (!sectionOwnerActive(entry, projectConfig)) {
2364
2520
  continue;
2365
2521
  }
2366
2522
  try {
@@ -2541,8 +2697,9 @@ function textChildValue(value: JxScope[string]): string | null {
2541
2697
  * @returns {JxElement}
2542
2698
  */
2543
2699
  function expandMapTemplate(template: JxElement, scope: JxScope): JxElement {
2544
- // A map template is authored JSON, so a child reached by recursion may not be an object.
2545
- if (!isNonNullObject(template)) {
2700
+ // A map template is authored JSON, so a child reached by recursion may not be an object. Spliced
2701
+ // Content is data (spec.md §8.4) and is kept as it stands.
2702
+ if (!isNonNullObject(template) || isLiteralNode(template)) {
2546
2703
  return template;
2547
2704
  }
2548
2705
  const node: JxElement = {};
@@ -2584,7 +2741,11 @@ function expandMapTemplate(template: JxElement, scope: JxScope): JxElement {
2584
2741
  } else if (k === "$props" && isNonNullObject(template.$props)) {
2585
2742
  const props = { ...template.$props };
2586
2743
  for (const [pk, pv] of Object.entries(props)) {
2587
- if (isTemplateString(pv)) {
2744
+ if (isRef(pv) && pv.$ref.startsWith("$map/")) {
2745
+ // The row exists only at build time, so its pointer resolves here like its templates.
2746
+ /* SAFETY: as below, a prop leaves the build only as JSON, so the row value is one. */
2747
+ props[pk] = (cloneValue(resolveRefValue(pv.$ref, scope)) ?? null) as JsonValue;
2748
+ } else if (isTemplateString(pv)) {
2588
2749
  /* SAFETY: props leave the build only as JSON (`expandComponents` writes them into
2589
2750
  `data-jx-props` with JSON.stringify), so a result is serialized exactly as a value
2590
2751
  authored at that prop would be. */
@@ -2651,7 +2812,8 @@ function resolveDocTemplates(
2651
2812
  buildResolved: ReadonlySet<string>,
2652
2813
  ) {
2653
2814
  // Children are authored JSON, so a member reached by recursion may be neither node nor string.
2654
- if (!isNonNullObject(node)) {
2815
+ // Spliced content is data, never a template (spec.md §8.4).
2816
+ if (!isNonNullObject(node) || isLiteralNode(node)) {
2655
2817
  return;
2656
2818
  }
2657
2819
 
@@ -2733,13 +2895,9 @@ function resolveDocTemplates(
2733
2895
  if (isTemplateString(rawChildren)) {
2734
2896
  const resolved = evaluateStaticTemplate(rawChildren, scope);
2735
2897
  if (Array.isArray(resolved)) {
2736
- /* SAFETY: a children template that yields an array stands for the child list itself, and
2737
- every member is walked by `resolveDocTemplates` below, which skips non-objects. */
2738
- const resolvedNodes = resolved as (JxElement | string)[];
2739
- node.children = resolvedNodes;
2740
- for (const child of resolvedNodes) {
2741
- resolveDocTemplates(child, scope, buildResolved);
2742
- }
2898
+ /* SAFETY: a children template that yields an array stands for the child list itself, which
2899
+ is content: `markLiteral` keeps every template in it text. */
2900
+ node.children = markLiteral(resolved as (JxElement | string)[]);
2743
2901
  }
2744
2902
  } else if (Array.isArray(node.children)) {
2745
2903
  let i = 0;
@@ -2749,12 +2907,9 @@ function resolveDocTemplates(
2749
2907
  const resolved = evaluateStaticTemplate(child, scope);
2750
2908
  if (Array.isArray(resolved)) {
2751
2909
  /* SAFETY: a child template that yields an array stands for the children it splices in,
2752
- and every member is walked by `resolveDocTemplates` below, which skips non-objects. */
2753
- const resolvedNodes = resolved as (JxElement | string)[];
2910
+ which are content: `markLiteral` keeps every template in them text. */
2911
+ const resolvedNodes = markLiteral(resolved as (JxElement | string)[]);
2754
2912
  node.children.splice(i, 1, ...resolvedNodes);
2755
- for (const spliced of resolvedNodes) {
2756
- resolveDocTemplates(spliced, scope, buildResolved);
2757
- }
2758
2913
  i += resolvedNodes.length;
2759
2914
  continue;
2760
2915
  }
@@ -2915,8 +3070,10 @@ interface ExpandOptions {
2915
3070
  slotIds?: { n: number };
2916
3071
  /** The tags whose instances ship their module (`computeLiveTags`). */
2917
3072
  liveTags?: ReadonlySet<string>;
2918
- /** The scope the children written inside an instance resolve in: the page's, not holding. */
2919
- slotScope?: () => JxScope;
3073
+ /** The page's build-time scope, which a `$ref` prop of an instance resolves against. */
3074
+ scope?: JxScope;
3075
+ /** Collects the tags of instances left with a prop the page's module delivers (compiler.md §8.1). */
3076
+ liveInstanceTags?: Set<string>;
2920
3077
  }
2921
3078
 
2922
3079
  /**
@@ -2934,7 +3091,7 @@ function expandComponents(
2934
3091
  componentDefs: Map<string, JxElement>,
2935
3092
  options: ExpandOptions = {},
2936
3093
  ) {
2937
- const { defaults, liveTags, slotCss, slotIds, slotScope } = options;
3094
+ const { defaults, liveTags, slotCss, slotIds, scope, liveInstanceTags } = options;
2938
3095
  if (!isNonNullObject(node)) {
2939
3096
  return;
2940
3097
  }
@@ -2976,12 +3133,15 @@ function expandComponents(
2976
3133
  * was given. Instances written inside `def` itself are another matter — those are reached
2977
3134
  * below, through `preRenderComponentHtml`, with `node` as the first frame of the path.
2978
3135
  */
2979
- const childScope = (): JxScope => slotScope?.() ?? {};
2980
- const renderSlotted = (c: StaticChild | JxMappedArray) => {
3136
+ /* The children stay nodes on the instance and the markup holds a placeholder for each: the
3137
+ target that compiles the page renders them in the page's scope, so a binding among them is
3138
+ bound by the page's module (spec.md §15.2). Their styles are collected here, as before. */
3139
+ const slotted: SlottedChild[] = [];
3140
+ const renderSlotted = (c: SlottedChild) => {
2981
3141
  if (slotCss && isNonNullObject(c) && !Array.isArray(c)) {
2982
3142
  collectStyles(c, slotCss.rules, slotCss.media, "", slotCss.counter, "jxs");
2983
3143
  }
2984
- return renderStaticNode(c, childScope(), null);
3144
+ return slotPlaceholder(slotted, c);
2985
3145
  };
2986
3146
 
2987
3147
  /*
@@ -2996,7 +3156,31 @@ function expandComponents(
2996
3156
  element's module reads the attribute itself. The page walk has resolved the templates, so
2997
3157
  the attribute values resolve against nothing. */
2998
3158
  const observedProps = observedAttributeProps(def, node.attributes, {});
2999
- const props = observedProps ? { ...observedProps, ...node.$props } : node.$props || null;
3159
+ /* A prop is live when the build cannot settle it (compiler.md §8.1): the page's module
3160
+ delivers it. Every other prop is settled here, so the prerender and the payload carry it. */
3161
+ const live: Record<string, JsonValue> = {};
3162
+ const settled: Record<string, JsonValue> = {};
3163
+ for (const [key, value] of Object.entries(node.$props ?? {})) {
3164
+ if (key.startsWith("#")) {
3165
+ continue;
3166
+ }
3167
+ if (
3168
+ isTemplateString(value) ||
3169
+ (isRef(value) && refReadsRuntimeOnlyState(value.$ref, scope ?? null))
3170
+ ) {
3171
+ live[key] = value;
3172
+ } else if (isRef(value)) {
3173
+ const resolved = cloneValue(resolveStaticValue(value, scope ?? null));
3174
+ if (resolved !== undefined) {
3175
+ /* SAFETY: a prop leaves the build only as JSON, so a resolved value is one. */
3176
+ settled[key] = resolved as JsonValue;
3177
+ }
3178
+ } else {
3179
+ settled[key] = value;
3180
+ }
3181
+ }
3182
+ const hasLive = Object.keys(live).length > 0;
3183
+ const props = observedProps || node.$props ? { ...observedProps, ...settled } : null;
3000
3184
  // This instance is the first frame of the path, so a definition that names itself is reported
3001
3185
  // At the first nesting rather than after the stack overflows.
3002
3186
  const context: ComponentPrerenderContext = {
@@ -3006,7 +3190,7 @@ function expandComponents(
3006
3190
  path: [{ key: JSON.stringify(props ?? {}), tag: tagName }],
3007
3191
  slotIds,
3008
3192
  };
3009
- const isStatic = !isLiveComponent(tagName, def, liveTags);
3193
+ const isStatic = !hasLive && !isLiveComponent(tagName, def, liveTags);
3010
3194
  const { children } = node;
3011
3195
  /* Light mode places the children by slot name (spec.md §8.5). A live instance whose definition
3012
3196
  has a slot is stamped and its groups bracketed, so its element recovers them on upgrade. */
@@ -3021,7 +3205,7 @@ function expandComponents(
3021
3205
  const innerHTML = preRenderComponentHtml(
3022
3206
  def,
3023
3207
  props,
3024
- shadow ? null : createSlotFill(children, childScope(), renderSlotted, slotId),
3208
+ shadow ? null : createSlotFill(children, scope ?? null, renderSlotted, slotId),
3025
3209
  context,
3026
3210
  );
3027
3211
  if (slotId !== null) {
@@ -3040,6 +3224,9 @@ function expandComponents(
3040
3224
  `${innerHTML}</template>${slotContent ?? ""}`
3041
3225
  : innerHTML;
3042
3226
  delete node.children;
3227
+ if (slotted.length > 0) {
3228
+ keepSlotted(node, slotted);
3229
+ }
3043
3230
 
3044
3231
  /*
3045
3232
  * Resolve template-string host styles against the instance (per-instance values like
@@ -3081,13 +3268,19 @@ function expandComponents(
3081
3268
  * or an array would arrive stringified, and a key that is not lowercase would be dropped by
3082
3269
  * attribute-name folding.
3083
3270
  */
3084
- if (!isStatic && node.$props && Object.keys(node.$props).length > 0) {
3271
+ if (!isStatic && Object.keys(settled).length > 0) {
3272
+ // `${` is written `\u0024{`: still JSON, but no emitter reads it as a template.
3085
3273
  node.attributes = {
3086
3274
  ...node.attributes,
3087
- "data-jx-props": JSON.stringify(node.$props),
3275
+ "data-jx-props": JSON.stringify(settled).replaceAll("${", String.raw`\u0024{`),
3088
3276
  };
3089
3277
  }
3090
- delete node.$props;
3278
+ if (hasLive) {
3279
+ node.$props = live;
3280
+ liveInstanceTags?.add(tagName);
3281
+ } else {
3282
+ delete node.$props;
3283
+ }
3091
3284
 
3092
3285
  if (isStatic) {
3093
3286
  node.$static = true;
@@ -3103,23 +3296,30 @@ function expandComponents(
3103
3296
  *
3104
3297
  * @param {string} html
3105
3298
  * @param {string[]} allComponentTags - All compiled component tag names
3106
- * @param {Map<string, string>} [cssMap] - TagName → CSS text (for link injection)
3107
- * @param {Set<string>} [staticTags] - Tags where ALL instances are fully static (skip JS)
3108
- * @param {string} [islandSource] - Concatenated island modules emitted for this page
3109
- * @param {Record<string, string>} [runtimeImports] - The import map's `imports` object
3110
- * @param {readonly string[]} [scriptOrder] - The tags in the order their module scripts are written
3299
+ * @param {Map<string, string>} cssMap - TagName → CSS text (for link injection)
3300
+ * @param {Set<string>} staticTags - Tags where ALL instances are fully static (skip JS)
3301
+ * @param {string} islandSource - Concatenated island modules emitted for this page
3302
+ * @param {Record<string, string>} runtimeImports - The import map's `imports` object
3303
+ * @param {readonly string[]} scriptOrder - The tags in the order their module scripts are written
3111
3304
  * (`orderComponentTags`); the component CSS keeps the order of `allComponentTags`, so the cascade
3112
3305
  * does not move
3306
+ * @param {object} cases - The external `$switch` cases (spec.md §14.1): every generated case tag,
3307
+ * and what each module that renders a case, or a component a case declares, reaches. A case is
3308
+ * loaded by the switch that renders it, never by a `<script>`.
3113
3309
  * @returns {string}
3114
3310
  */
3115
3311
  function injectComponentScripts(
3116
3312
  html: string,
3117
3313
  allComponentTags: string[],
3118
- cssMap = new Map<string, string>(),
3119
- staticTags = new Set<string>(),
3120
- islandSource = "",
3121
- runtimeImports: Record<string, string> = {},
3122
- scriptOrder: readonly string[] = allComponentTags,
3314
+ cssMap: Map<string, string>,
3315
+ staticTags: Set<string>,
3316
+ islandSource: string,
3317
+ runtimeImports: Record<string, string>,
3318
+ scriptOrder: readonly string[],
3319
+ cases: {
3320
+ tags: ReadonlySet<string>;
3321
+ reach: ReadonlyMap<string, readonly string[]>;
3322
+ },
3123
3323
  ) {
3124
3324
  // A component reaches a page two ways: as a literal tag in the static HTML, or referenced only
3125
3325
  // From inside an island's client template — in which case the tag exists solely in the island's
@@ -3127,7 +3327,17 @@ function injectComponentScripts(
3127
3327
  // Kind entirely, so its module was never loaded and the element sat in the DOM un-upgraded.
3128
3328
  const inHtml = (tag: string) => html.includes(`<${tag}`); // Matches <tag> and <tag ...>
3129
3329
  const inIsland = (tag: string) => islandSource.includes(`<${tag}`);
3130
- const usedTags = allComponentTags.filter((tag: string) => inHtml(tag) || inIsland(tag));
3330
+ const direct = new Set(allComponentTags.filter((tag: string) => inHtml(tag) || inIsland(tag)));
3331
+ /* A module that renders a case imports it, and one that declares a component imports that: no
3332
+ scan of this page sees either. They count as used for the sheets, in first-seen order, and for
3333
+ no script (a case's module is loaded by the switch that renders it). */
3334
+ const reached = new Set(direct);
3335
+ for (const tag of reached) {
3336
+ for (const next of cases.reach.get(tag) ?? []) {
3337
+ reached.add(next);
3338
+ }
3339
+ }
3340
+ const usedTags = allComponentTags.filter((tag: string) => reached.has(tag));
3131
3341
  if (usedTags.length === 0) {
3132
3342
  return html;
3133
3343
  }
@@ -3164,9 +3374,9 @@ function injectComponentScripts(
3164
3374
  // Never prerendered, so it needs its module even when the component itself is fully static —
3165
3375
  // That module is what fills the element in client-side. This holds when the tag ALSO appears in
3166
3376
  // The static HTML: those instances are prerendered, but the ones the island creates are not.
3167
- const used = new Set(usedTags);
3168
3377
  const jsTags = scriptOrder.filter(
3169
- (tag: string) => used.has(tag) && (inIsland(tag) || !staticTags.has(tag)),
3378
+ (tag: string) =>
3379
+ direct.has(tag) && !cases.tags.has(tag) && (inIsland(tag) || !staticTags.has(tag)),
3170
3380
  );
3171
3381
  if (jsTags.length === 0) {
3172
3382
  return intoHead([styleBlock]);
@@ -3188,7 +3398,13 @@ function injectComponentScripts(
3188
3398
  * where each hop is a round trip. The component modules are hinted too so the whole set starts
3189
3399
  * downloading while the HTML is still being parsed.
3190
3400
  */
3191
- const preloads = [...pageRuntimeAssets, ...jsTags.map((tag: string) => `/components/${tag}.js`)]
3401
+ // A case the prerendered markup already holds is part of the first visit, so it is hinted.
3402
+ const prerenderedCases = [...cases.tags].filter((tag) => inHtml(tag));
3403
+ const preloads = [
3404
+ ...pageRuntimeAssets,
3405
+ ...jsTags.map((tag: string) => `/components/${tag}.js`),
3406
+ ...prerenderedCases.map((tag) => `/components/${tag}.js`),
3407
+ ]
3192
3408
  .map((href) => `<link rel="modulepreload" href="${href}">`)
3193
3409
  .join("\n ");
3194
3410
 
@@ -3334,14 +3550,6 @@ function routeToOutputPath(urlPattern: string, outDir: string, trailingSlash: st
3334
3550
  return join(outDir, `${segments}.html`);
3335
3551
  }
3336
3552
 
3337
- /**
3338
- * Generate redirect files (HTML meta refresh and _redirects).
3339
- *
3340
- * @param {Record<string, string | { destination: string; status?: number }>} redirects
3341
- * @param {string} outDir
3342
- * @param {Set<string>} [compiledUrls] - URL patterns of compiled routes, for conflict warnings
3343
- * @returns {number} Number of files written
3344
- */
3345
3553
  /**
3346
3554
  * Which statuses get an HTML fallback, and why each other one does not.
3347
3555
  *
@@ -3349,33 +3557,29 @@ function routeToOutputPath(urlPattern: string, outDir: string, trailingSlash: st
3349
3557
  * That is a reasonable stand-in for a 301 or a 303 on a host that ignores `_redirects`, and it is
3350
3558
  * actively wrong for everything else.
3351
3559
  *
3352
- * Keyed by the status's decimal string so an authored `"status": "301"` (schema-invalid, but
3353
- * project.json is not validated at build time) still matches the way an object-key lookup would.
3560
+ * Keyed by the schema's `REDIRECT_STATUSES` (schema.md §7, RFC 9110 row), so a status added there
3561
+ * fails typecheck here until it has a policy. Looked up through the status's number, so an authored
3562
+ * `"status": "301"` (schema-invalid, but project.json is not validated at build time) still
3563
+ * matches.
3354
3564
  */
3355
- const REDIRECT_HTML_POLICY = new Map<string, RedirectHtmlPolicy>([
3565
+ const REDIRECT_HTML_POLICY = {
3356
3566
  // The permanent case: a canonical link is exactly the right signal.
3357
- ["301", { canonical: true, html: true, why: "" }],
3567
+ 301: { canonical: true, html: true, why: "" },
3358
3568
  // Temporary — a canonical link would assert the permanence the status denies.
3359
- ["302", { canonical: false, html: true, why: "" }],
3569
+ 302: { canonical: false, html: true, why: "" },
3360
3570
  // "See other, with GET" is what a meta-refresh already does.
3361
- ["303", { canonical: false, html: true, why: "" }],
3362
- [
3363
- "307",
3364
- {
3365
- canonical: false,
3366
- html: false,
3367
- why: "307 preserves the request method and body; a meta-refresh silently converts POST to GET",
3368
- },
3369
- ],
3370
- [
3371
- "308",
3372
- {
3373
- canonical: false,
3374
- html: false,
3375
- why: "308 preserves the request method and body; a meta-refresh silently converts POST to GET",
3376
- },
3377
- ],
3378
- ]);
3571
+ 303: { canonical: false, html: true, why: "" },
3572
+ 307: {
3573
+ canonical: false,
3574
+ html: false,
3575
+ why: "307 preserves the request method and body; a meta-refresh silently converts POST to GET",
3576
+ },
3577
+ 308: {
3578
+ canonical: false,
3579
+ html: false,
3580
+ why: "308 preserves the request method and body; a meta-refresh silently converts POST to GET",
3581
+ },
3582
+ } satisfies Record<RedirectStatus, RedirectHtmlPolicy>;
3379
3583
 
3380
3584
  /** One redirection status's HTML-fallback rule, in {@link REDIRECT_HTML_POLICY}. */
3381
3585
  interface RedirectHtmlPolicy {
@@ -3384,6 +3588,13 @@ interface RedirectHtmlPolicy {
3384
3588
  why: string;
3385
3589
  }
3386
3590
 
3591
+ type RedirectStatus = (typeof REDIRECT_STATUSES)[number];
3592
+
3593
+ function isRedirectStatus(status: number): status is RedirectStatus {
3594
+ // SAFETY: widening the tuple to `readonly number[]` only lets `includes` take any number.
3595
+ return (REDIRECT_STATUSES as readonly number[]).includes(status);
3596
+ }
3597
+
3387
3598
  /**
3388
3599
  * Emit `dist/_redirects` plus an HTML fallback for the literal sources whose status has one.
3389
3600
  *
@@ -3419,10 +3630,17 @@ function generateRedirects(
3419
3630
  ? (target.status ?? 301)
3420
3631
  : 301;
3421
3632
 
3422
- if (!isRewrite && !REDIRECT_HTML_POLICY.has(String(status))) {
3633
+ const code = Number(status);
3634
+ const policy = isRewrite
3635
+ ? null
3636
+ : isRedirectStatus(code)
3637
+ ? REDIRECT_HTML_POLICY[code]
3638
+ : undefined;
3639
+
3640
+ if (policy === undefined) {
3423
3641
  errors.push(
3424
3642
  `Redirect "${source}" has status ${status}, which is not an RFC 9110 §15.4 redirection ` +
3425
- `status. Use one of ${[...REDIRECT_HTML_POLICY.keys()].join(", ")}, or ` +
3643
+ `status. Use one of ${REDIRECT_STATUSES.join(", ")}, or ` +
3426
3644
  `{ destination, rewrite: true } for a proxy.`,
3427
3645
  );
3428
3646
  continue;
@@ -3452,11 +3670,7 @@ function generateRedirects(
3452
3670
  * shadows the rewrite on hosts that honour `_redirects`, and turns it into a redirect on the
3453
3671
  * hosts that do not — so it is wrong in both directions. This was the bug.
3454
3672
  */
3455
- if (isRewrite) {
3456
- continue;
3457
- }
3458
- const policy = REDIRECT_HTML_POLICY.get(String(status))!;
3459
- if (!policy.html) {
3673
+ if (policy === null || !policy.html) {
3460
3674
  continue;
3461
3675
  }
3462
3676