@jxsuite/compiler 8.6.0 → 9.0.1

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.
@@ -6,6 +6,9 @@
6
6
  * compile 5. Emit compiled files to dist/ 6. Generate redirects
7
7
  *
8
8
  * This is the Phase 1 implementation of site-architecture spec §12.
9
+ *
10
+ * @docs framework/build
11
+ * @docs framework/concepts/lists
9
12
  */
10
13
 
11
14
  import {
@@ -13,7 +16,6 @@ import {
13
16
  existsSync,
14
17
  mkdirSync,
15
18
  readFileSync,
16
- readdirSync,
17
19
  rmSync,
18
20
  statSync,
19
21
  writeFileSync,
@@ -24,6 +26,7 @@ import {
24
26
  isJsonObject,
25
27
  isMappedArray,
26
28
  isNonNullObject,
29
+ isPrototypeDef,
27
30
  isRef,
28
31
  isString,
29
32
  isTemplateString,
@@ -46,6 +49,7 @@ import {
46
49
  bundleSource,
47
50
  resolveSidecarEntry,
48
51
  } from "./bundler.ts";
52
+ import type { BundleRequest } from "./bundler.ts";
49
53
  import { loadProjectConfig } from "./site-loader.ts";
50
54
  import type { ResolvedProjectConfig } from "./site-loader.ts";
51
55
  import {
@@ -68,6 +72,13 @@ import { collectAssetRefs, copyMountedAssets, loadAssetMounts } from "./asset-mo
68
72
  import type { AssetMount } from "@jxsuite/schema/asset-paths";
69
73
  import type { FormatEntry, FormatRegistry } from "@jxsuite/schema/format-registry";
70
74
  import type { ExtensionRegistry } from "@jxsuite/schema/extension-registry";
75
+ import { collectSiteComponents } from "./component-set.ts";
76
+ import { documentScripts, qualifiedDocument } from "./document-scripts.ts";
77
+ import {
78
+ isScriptSpecifier,
79
+ parseScriptSpecifier,
80
+ scriptRefSide,
81
+ } from "@jxsuite/schema/document-scripts";
71
82
  import { layoutChain, resolveLayout } from "./layout-resolver.ts";
72
83
  import { dedupeServerEntries, documentServerEntries } from "./server-entries.ts";
73
84
  import type { DedupedServerEntries, ServerEntryRecord } from "./server-entries.ts";
@@ -84,6 +95,7 @@ import type { SiteConnectorSpec, SiteMountSpec } from "../targets/compile-server
84
95
  import {
85
96
  buildComponentCSS,
86
97
  buildInitialScope,
98
+ collectSrcImports,
87
99
  buildInstanceScope,
88
100
  collectStyles,
89
101
  colorSchemePrePaintScript,
@@ -91,12 +103,16 @@ import {
91
103
  definitionHasSlot,
92
104
  escapeStyleText,
93
105
  evaluateStaticTemplate,
106
+ inheritProjectFormulas,
94
107
  isComponentFullyStatic,
108
+ isPureNamedFormula,
109
+ isRuntimeOnlyStateKey,
95
110
  isSingleExpression,
96
111
  liftPropsAttributes,
97
112
  nextSlotId,
98
113
  preRenderComponentHtml,
99
114
  pureSchemeOf,
115
+ referencesStateKey,
100
116
  renderStaticNode,
101
117
  resolveHostStyle,
102
118
  resolveRefValue,
@@ -182,6 +198,23 @@ declare module "@jxsuite/schema/format-registry" {
182
198
  const ADAPTER_REMEDY =
183
199
  'set build.adapter to "cloudflare-workers", "cloudflare-pages", "node", or "bun".';
184
200
 
201
+ /**
202
+ * The phases a build's time is divided into, in the order they run. Each is the wall-clock time
203
+ * between two points in `buildSite`, so together they account for all of `total`:
204
+ *
205
+ * - `setup`: reading the project file, the extension registry, document scripts and server mounts.
206
+ * - `content`: discovering pages, loading extension project sections (collections), asset mounts and
207
+ * expanding dynamic routes. This is extension code, not the compiler's own.
208
+ * - `components`: compiling the site's components to modules and style sheets.
209
+ * - `routes`: compiling every route, including optimizing the images each one uses.
210
+ * - `bundles`: the image cache, the server worker, client bundles and extension-emitted assets.
211
+ * - `outputs`: redirects, sitemap, copied assets, the manifest, the service worker and headers.
212
+ */
213
+ export type BuildPhase = "setup" | "content" | "components" | "routes" | "bundles" | "outputs";
214
+
215
+ /** Milliseconds per phase, and for the whole build. Measured, never estimated. */
216
+ export type BuildTimings = Record<BuildPhase | "total", number>;
217
+
185
218
  /**
186
219
  * Build an entire Jx site from a project directory.
187
220
  *
@@ -191,7 +224,7 @@ const ADAPTER_REMEDY =
191
224
  * @param {boolean} [options.verbose] - Log progress
192
225
  * @param {boolean} [options.includeHeld] - Keep entries a content type's `hold` rules match, for a
193
226
  * preview. Left off, a build leaves them out (site-architecture.md §7.6).
194
- * @returns {Promise<{ routes: number; files: number; errors: string[] }>}
227
+ * @returns {Promise<{ routes: number; files: number; errors: string[]; timings: BuildTimings }>}
195
228
  */
196
229
  export async function buildSite(
197
230
  projectRoot: string,
@@ -204,6 +237,23 @@ export async function buildSite(
204
237
  const { clean = true, includeHeld = false, verbose = false } = options;
205
238
  const errors: string[] = [];
206
239
  const log = verbose ? console.log.bind(console) : () => {};
240
+ const timings: BuildTimings = {
241
+ bundles: 0,
242
+ components: 0,
243
+ content: 0,
244
+ outputs: 0,
245
+ routes: 0,
246
+ setup: 0,
247
+ total: 0,
248
+ };
249
+ const started = performance.now();
250
+ let lap = started;
251
+ /** Close the phase that just ran: everything since the last one closed is its time. */
252
+ const closePhase = (name: BuildPhase) => {
253
+ const now = performance.now();
254
+ timings[name] = now - lap;
255
+ lap = now;
256
+ };
207
257
 
208
258
  // ── 1. Load project configuration ──────────────────────────────────────────
209
259
  log("Loading project.json...");
@@ -234,7 +284,9 @@ export async function buildSite(
234
284
  // Client sidecar bundles: bundleable Function-def `$src` specifiers (and lowered-def `$bundle`
235
285
  // Hints) are rewritten to their /assets/ URL during compilation, registered here, and bundled
236
286
  // In step 6d (spec.md §12). Keyed by asset path so duplicate specifiers bundle once.
237
- const sidecarBundles = new Map<string, { entryPath: string; specifier: string }>();
287
+ /* A document's own script (spec.md §23.2) is bundled like a sidecar, but it is not a file: an
288
+ entry with `script` is one, named by its qualified specifier and read from its document. */
289
+ const sidecarBundles = new Map<string, { entryPath: string; specifier: string; script?: true }>();
238
290
  /*
239
291
  * Files a `$head` entry names by bare specifier — a package's stylesheet, most often. Copied
240
292
  * rather than bundled.
@@ -307,7 +359,57 @@ export async function buildSite(
307
359
  }
308
360
  assetClaims.set(assetPath, { entryPath, specifier });
309
361
  };
362
+ /*
363
+ * A document's client module: one bundle per document, keyed on the document's project-relative
364
+ * path, so two documents each exporting `bump` are two files (spec.md §23.2). Whether the
365
+ * document carries a client script at all is found when the bundle is made, which reports it.
366
+ */
367
+ const scriptErrors = new Set<string>();
368
+ /** A layout's entry is rewritten once per page it wraps, and its mistake is one mistake. */
369
+ const scriptError = (message: string) => {
370
+ if (!scriptErrors.has(message)) {
371
+ scriptErrors.add(message);
372
+ errors.push(message);
373
+ console.error(message);
374
+ }
375
+ };
376
+ const rewriteScriptSrc = (specifier: string): string => {
377
+ const parsed = parseScriptSpecifier(specifier);
378
+ if (parsed === null) {
379
+ scriptError(`$src "${specifier}" is not a document script specifier`);
380
+ return specifier;
381
+ }
382
+ if (parsed.side === "server") {
383
+ scriptError(
384
+ `${parsed.path}: a client function names "#server". A server module is called by a ` +
385
+ `timing: "server" entry and never imported by a page`,
386
+ );
387
+ return specifier;
388
+ }
389
+ try {
390
+ const assetPath = sidecarAssetPath(`./${parsed.path}`);
391
+ claimAsset(assetPath, specifier, specifier);
392
+ sidecarBundles.set(assetPath, { entryPath: specifier, script: true, specifier });
393
+ return assetPath;
394
+ } catch (error) {
395
+ scriptError(`Script of ${parsed.path}: ${errorMessage(error)}`);
396
+ return specifier;
397
+ }
398
+ };
310
399
  const rewriteSidecarSrc = (specifier: string, docDir: string | null): string => {
400
+ if (isScriptSpecifier(specifier)) {
401
+ return rewriteScriptSrc(specifier);
402
+ }
403
+ if (scriptRefSide(specifier) !== null) {
404
+ /* Every document the build reads is qualified as it is read, so this is an entry written
405
+ somewhere that has no document of its own to name: `project.json`'s `state`. */
406
+ scriptError(
407
+ `$src "${specifier}" names its own document's script, but it is not in a document: ` +
408
+ `project.json has no $script. Move the entry into the page, layout or component that ` +
409
+ `carries the script`,
410
+ );
411
+ return specifier;
412
+ }
311
413
  if (!isBundleableSrc(specifier)) {
312
414
  return specifier;
313
415
  }
@@ -353,6 +455,8 @@ export async function buildSite(
353
455
  // ── 1b. Build the extension registry from project.json#/extensions ─────
354
456
  const registry = await buildProjectExtensionRegistry(projectRoot, projectConfig);
355
457
  const formatRegistry = registry.formats;
458
+ // Every document's own modules (spec.md §23.2), read with the formats this project registered.
459
+ const scripts = documentScripts(projectRoot, (path) => readPageDocument(path, formatRegistry));
356
460
  if (formatRegistry.entries.length > 0) {
357
461
  log(
358
462
  ` Registered ${formatRegistry.entries.length} format(s): ${formatRegistry.entries
@@ -382,6 +486,8 @@ export async function buildSite(
382
486
  );
383
487
  }
384
488
 
489
+ closePhase("setup");
490
+
385
491
  // ── 2. Clean output directory ───────────────────────────────────────────
386
492
  if (clean && existsSync(outDir)) {
387
493
  rmSync(outDir, { force: true, recursive: true });
@@ -454,41 +560,35 @@ export async function buildSite(
454
560
 
455
561
  let fileCount = 0;
456
562
 
563
+ closePhase("content");
564
+
457
565
  // ── 5. Compile site components ──────────────────────────────────────────
458
- const componentsDir = resolve(projectRoot, "components");
459
566
  const compiledComponentTags: string[] = [];
460
567
  const componentCSS = new Map<string, string>(); // TagName → CSS text
461
568
  const componentDefs = new Map<string, JxElement>(); // TagName → parsed component definition
462
569
  // TagName → the absolute path its definition was read from, for what is relative to that file.
463
570
  const componentPathByTag = new Map<string, string>();
464
- if (existsSync(componentsDir)) {
571
+ /* What this build compiles: every file directly in `components/`, plus every component a page,
572
+ a layout or project.json names by `$ref`, wherever it lives (site-architecture.md §10.3). */
573
+ const { components: siteComponents, errors: componentErrors } = await collectSiteComponents({
574
+ formatRegistry,
575
+ pageSources: routes.map((route) => route.sourcePath),
576
+ projectConfig,
577
+ projectRoot,
578
+ });
579
+ for (const message of componentErrors) {
580
+ errors.push(message);
581
+ console.error(message);
582
+ }
583
+ if (siteComponents.length > 0) {
465
584
  log("Compiling components...");
466
- const componentExtensions = [".json", ...formatRegistry.documentExtensions("component")];
467
- /* Sorted, because this order is the order of the sheets in every page's `<head>`, and readdir
468
- has none of its own: on ext4 it follows a hash of the name, so the same project built to
469
- different bytes on different machines. */
470
- const componentFiles = readdirSync(componentsDir)
471
- .filter((f: string) => componentExtensions.some((ext) => f.endsWith(ext)))
472
- .toSorted();
473
585
  const componentOutDir = resolve(outDir, "components");
474
586
  mkdirSync(componentOutDir, { recursive: true });
475
587
 
476
588
  // Emitted modules are named after the component's `tagName` — the name the page's loader
477
- // `<script>` and the CSS sidecar both use. So a component whose source basename differs from
478
- // Its tag needs its `$elements` imports renamed to match, and those get resolved before the
479
- // Dependency itself is compiled. Hence: read every component's tag up front.
480
- const componentTagByPath = new Map<string, string>();
481
- for (const file of componentFiles) {
482
- const componentPath = resolve(componentsDir, file);
483
- try {
484
- const { tagName: depTag } = await readPageDocument(componentPath, formatRegistry);
485
- if (depTag) {
486
- componentTagByPath.set(componentPath, depTag);
487
- }
488
- } catch {
489
- // Left to the compile pass below, which reports the parse failure with its file context.
490
- }
491
- }
589
+ // `<script>` and the CSS sidecar both use, wherever the source file lives. So a component's
590
+ // `$elements` imports are renamed to match, which needs every component's tag up front.
591
+ const componentTagByPath = new Map(siteComponents.map((c) => [c.path, c.tagName]));
492
592
 
493
593
  /*
494
594
  * A component is a JavaScript module the page loads, and the page rewrite (`rewriteHtmlBase`) never
@@ -501,9 +601,11 @@ export async function buildSite(
501
601
  // So it is given the deployment base now (site-architecture.md §14.7).
502
602
  const serverBaseUrl = serverRoutePrefix(componentBase);
503
603
 
504
- for (const file of componentFiles) {
604
+ for (const { doc: written, path: componentPath } of siteComponents) {
605
+ /* The definition every page prerenders from, with the project formulas it reads (spec.md
606
+ §13.4). The module is compiled from the file, and is given the same project state. */
607
+ const doc = inheritProjectFormulas(written, projectConfig.state);
505
608
  try {
506
- const componentPath = resolve(componentsDir, file);
507
609
  const elementOptions: CompileElementOptions = {
508
610
  formats: formatRegistry,
509
611
  resolveElementPath: (refPath: string, currentDir: string | null) => {
@@ -511,6 +613,8 @@ export async function buildSite(
511
613
  const depTag = componentTagByPath.get(depPath);
512
614
  return depTag ? `./${depTag}.js` : refPath.replace(/\.(?:json|jxn)$/i, ".js");
513
615
  },
616
+ projectRoot,
617
+ projectState: projectConfig.state,
514
618
  rewriteSrc: (specifier: string, docDir: string | null) =>
515
619
  withBase(componentBase, rewriteSidecarSrc(specifier, docDir)),
516
620
  serverBaseUrl,
@@ -548,7 +652,6 @@ export async function buildSite(
548
652
  }
549
653
 
550
654
  // Pre-render component HTML scaffold and CSS sidecar
551
- const doc = await readPageDocument(componentPath, formatRegistry);
552
655
  if (doc.tagName) {
553
656
  componentDefs.set(doc.tagName, doc);
554
657
  componentPathByTag.set(doc.tagName, componentPath);
@@ -576,6 +679,7 @@ export async function buildSite(
576
679
  }
577
680
  } catch (error) {
578
681
  const message = errorMessage(error);
682
+ const file = relative(projectRoot, componentPath).replaceAll("\\", "/");
579
683
  errors.push(`Error compiling component ${file}: ${message}`);
580
684
  console.error(`Error compiling component ${file}: ${message}`);
581
685
  }
@@ -601,22 +705,41 @@ export async function buildSite(
601
705
  );
602
706
  }
603
707
  if (projectConfig.state) {
604
- siteServerEntries.push(
605
- ...documentServerEntries(
606
- /* SAFETY: `ProjectConfig.state` is a plain record of state entries, and the collector reads
607
- only a document's `state`, so a document carrying that one member is all it needs. */
608
- { state: projectConfig.state } as JxElement,
609
- projectFilePath(projectRoot),
610
- projectRoot,
611
- ),
708
+ const projectEntries = documentServerEntries(
709
+ /* SAFETY: `ProjectConfig.state` is a plain record of state entries, and the collector reads
710
+ only a document's `state`, so a document carrying that one member is all it needs. */
711
+ { state: projectConfig.state } as JxElement,
712
+ projectFilePath(projectRoot),
713
+ projectRoot,
612
714
  );
715
+ for (const entry of projectEntries) {
716
+ // `project.json` carries no `$script`, so a `#server` written there names nothing.
717
+ if (scriptRefSide(entry.src) === null) {
718
+ siteServerEntries.push(entry);
719
+ } else {
720
+ scriptError(
721
+ `Server function "${entry.exportName}" in ${entry.declaredIn} names "${entry.src}", ` +
722
+ `its own document's script, but project.json has no $script. Move the entry into ` +
723
+ `the page, layout or component that carries the script`,
724
+ );
725
+ }
726
+ }
613
727
  }
614
728
 
729
+ closePhase("components");
730
+
615
731
  // ── 6. Compile each route ───────────────────────────────────────────────
616
732
 
617
733
  const cfImages = projectConfig.images.optimize && projectConfig.images.service === "cloudflare";
618
734
  const imageCache = projectConfig.images.optimize && !cfImages ? loadCache(projectRoot) : null;
619
735
  const imageMetaCache: ImageMetaCache | null = cfImages ? new Map() : null;
736
+ if (imageCache && projectConfig.images.formats?.includes("webp")) {
737
+ console.warn(
738
+ `images.formats lists "webp", which this compiler writes losslessly: its files are several ` +
739
+ `times the size of AVIF or JPEG. Keep it only for pixel-exact output; ["avif", "jpeg"] ` +
740
+ `is the default.`,
741
+ );
742
+ }
620
743
  if (cfImages) {
621
744
  console.log(
622
745
  `images.service is "cloudflare" — srcsets use /cdn-cgi/image transform URLs. ` +
@@ -921,6 +1044,8 @@ export async function buildSite(
921
1044
  }
922
1045
  }
923
1046
 
1047
+ closePhase("routes");
1048
+
924
1049
  // ── 6b. Save image cache and copy variants to dist ──────────────────────
925
1050
  if (imageCache && projectConfig.images.optimize) {
926
1051
  // Prune only on fully successful builds — a route that failed to compile never
@@ -1015,6 +1140,8 @@ export async function buildSite(
1015
1140
  await bundleWorkerSource(workerSource, {
1016
1141
  adapter,
1017
1142
  outfile: resolve(outDir, workerName),
1143
+ // A server function may live in a document's own server script (spec.md §23.2).
1144
+ plugins: [scripts.serverPlugin],
1018
1145
  projectRoot,
1019
1146
  });
1020
1147
  fileCount += 1;
@@ -1086,10 +1213,20 @@ export async function buildSite(
1086
1213
  try {
1087
1214
  const outfile = resolve(outDir, assetPath.replace(/^\//, ""));
1088
1215
  mkdirSync(dirname(outfile), { recursive: true });
1089
- await bundleEntry(
1090
- { entryPath: bundle.entryPath, outfile },
1091
- { external: CLIENT_EXTERNALS, minify, target: "browser" },
1092
- );
1216
+ /* A document's script is bundled from its text, standing beside its document. Every
1217
+ bundle gets the plugin, because a file module may import a `.jxn` document too. */
1218
+ const request: BundleRequest = { entryPath: bundle.entryPath, outfile };
1219
+ if (bundle.script) {
1220
+ const module = await scripts.module(bundle.specifier);
1221
+ request.entryPath = module.path;
1222
+ request.contents = module.contents;
1223
+ }
1224
+ await bundleEntry(request, {
1225
+ external: CLIENT_EXTERNALS,
1226
+ minify,
1227
+ plugins: [scripts.clientPlugin],
1228
+ target: "browser",
1229
+ });
1093
1230
  fileCount += 1;
1094
1231
  log(` ${bundle.specifier} → ${assetPath}`);
1095
1232
  } catch (error) {
@@ -1182,6 +1319,8 @@ export async function buildSite(
1182
1319
  }
1183
1320
  }
1184
1321
 
1322
+ closePhase("bundles");
1323
+
1185
1324
  // ── 7. Generate redirects ───────────────────────────────────────────────
1186
1325
  if (projectConfig.redirects && Object.keys(projectConfig.redirects).length > 0) {
1187
1326
  log("Generating redirects...");
@@ -1352,7 +1491,9 @@ export async function buildSite(
1352
1491
  log(` ${errors.length} error(s)`);
1353
1492
  }
1354
1493
 
1355
- return { errors, files: fileCount, routes: routes.length, serverEntries };
1494
+ closePhase("outputs");
1495
+ timings.total = performance.now() - started;
1496
+ return { errors, files: fileCount, routes: routes.length, serverEntries, timings };
1356
1497
  }
1357
1498
 
1358
1499
  /** The route `compilePage` renders: a URL and the page document that produces it. */
@@ -1410,8 +1551,13 @@ async function compilePage(
1410
1551
  `projectConfig.url`, which is already here, so the two cannot disagree. */
1411
1552
  const basePath = siteBasePath(projectConfig.url);
1412
1553
 
1413
- // Load the raw page document (.json natively, other formats via the registry)
1414
- const pageDoc = await readPageDocument(route.sourcePath, formatRegistry);
1554
+ // Load the raw page document (.json natively, other formats via the registry). Its `#client` and
1555
+ // `#server` name this page from here on, before a layout's can meet them (spec.md §23.2).
1556
+ const pageDoc = qualifiedDocument(
1557
+ await readPageDocument(route.sourcePath, formatRegistry),
1558
+ route.sourcePath,
1559
+ projectRoot,
1560
+ );
1415
1561
 
1416
1562
  // Resolve layout (wraps page in layout with slot distribution)
1417
1563
  const layoutDoc = await resolveLayout(pageDoc, projectConfig, projectRoot);
@@ -1422,11 +1568,10 @@ async function compilePage(
1422
1568
  * `injectContext`: with no layout `resolveLayout` hands back `pageDoc` itself, and injection
1423
1569
  * then adds project.json's state to it, which `buildSite` collects once, as project.json's own.
1424
1570
  */
1571
+ const layoutLevels = layoutChain(pageDoc, projectConfig, projectRoot);
1425
1572
  const serverEntries = [
1426
1573
  ...documentServerEntries(pageDoc, route.sourcePath, projectRoot),
1427
- ...layoutChain(pageDoc, projectConfig, projectRoot).flatMap((level) =>
1428
- documentServerEntries(level.doc, level.path, projectRoot),
1429
- ),
1574
+ ...layoutLevels.flatMap((level) => documentServerEntries(level.doc, level.path, projectRoot)),
1430
1575
  ];
1431
1576
 
1432
1577
  // Extract head arrays before they get lost in the merge
@@ -1446,7 +1591,13 @@ async function compilePage(
1446
1591
  delete layoutDoc._pageTitle;
1447
1592
 
1448
1593
  // Inject $site and $page context
1594
+ const declaredStateKeys = new Set(Object.keys(layoutDoc.state ?? {}));
1449
1595
  injectContext(layoutDoc, projectConfig, route, projectRoot, locale.i18n, locale.translations);
1596
+ /* The project `state` entries this page did not declare, nor its layout: the ones the injection
1597
+ just copied in, which the page keeps only while something on it reads them (compiler.md §8.1). */
1598
+ const inheritedStateKeys = Object.keys(projectConfig.state ?? {}).filter(
1599
+ (key) => key !== "$site" && key !== "$page" && !declaredStateKeys.has(key),
1600
+ );
1450
1601
 
1451
1602
  /*
1452
1603
  * The page's language and writing direction. `$lang` on the document wins over the locale its
@@ -1464,6 +1615,9 @@ async function compilePage(
1464
1615
  * A page of a paged list gets its slice in place of the entry it pages. The entry was resolved
1465
1616
  * once while the route was expanded, so it is not queried again for every page.
1466
1617
  */
1618
+ /* The state as authored, read after resolution to tell which entries the build itself resolved
1619
+ (see `buildResolvedStateKeys`). A shallow copy: only the identity of each entry is compared. */
1620
+ const authoredState = { ...layoutDoc.state };
1467
1621
  if (route.pagedState && layoutDoc.state && route.pagedState.key in layoutDoc.state) {
1468
1622
  layoutDoc.state[route.pagedState.key] = route.pagedState.items;
1469
1623
  }
@@ -1478,6 +1632,12 @@ async function compilePage(
1478
1632
  sections,
1479
1633
  });
1480
1634
 
1635
+ const buildResolved = buildResolvedStateKeys(
1636
+ authoredState,
1637
+ layoutDoc.state ?? {},
1638
+ route.pagedState?.key,
1639
+ );
1640
+
1481
1641
  // Build scope from resolved state so template strings in title/$head can be evaluated
1482
1642
  const scope = buildInitialScope(layoutDoc.state ?? {});
1483
1643
 
@@ -1513,7 +1673,7 @@ async function compilePage(
1513
1673
 
1514
1674
  // Resolve template strings in the document tree (innerHTML, textContent, style, attributes)
1515
1675
  // So that timing: "compiler" data is baked into the static HTML
1516
- resolveDocTemplates(layoutDoc, scope);
1676
+ resolveDocTemplates(layoutDoc, scope, buildResolved);
1517
1677
 
1518
1678
  // Expand registered custom elements (apply $props, pre-render, mark static/prerendered).
1519
1679
  // Slot children are serialized to HTML strings during expansion — before compileStyles can walk
@@ -1536,8 +1696,14 @@ async function compilePage(
1536
1696
  // Expansion is one consumer, not the only one: the same array is routinely also read by a
1537
1697
  // Computed at runtime, and dropping it there left `state.rows` undefined in the browser while
1538
1698
  // The build reported success (issue #122). `timing: "compiler"` is excluded from this rescue —
1539
- // That is the author declaring the entry build-time-only, so it is stripped as before.
1540
- const strippable = new Set<string>();
1699
+ // That is the author declaring the entry build-time-only, so it is stripped as before. An
1700
+ // Inherited project entry is only droppable on the same terms (compiler.md §8.1).
1701
+ // A pure named formula is droppable on those terms too, wherever it is declared: every call
1702
+ // The build resolved is gone from the tree, so a formula nothing left for the client reads is
1703
+ // Dead, and keeping it would make a page with one date tag a client page (compiler.md §3).
1704
+ const droppable = new Set<string>();
1705
+ /** Entries a `$src` module may read unseen: the inherited ones, and every pure formula. */
1706
+ const unseenReads = new Set<string>(inheritedStateKeys);
1541
1707
  for (const [key, def] of Object.entries(layoutDoc.state)) {
1542
1708
  if (key === "$site" || key === "$page") {
1543
1709
  continue;
@@ -1545,26 +1711,55 @@ async function compilePage(
1545
1711
  if (isJsonObject(def) && def.timing === "compiler") {
1546
1712
  delete layoutDoc.state[key];
1547
1713
  } else if (Array.isArray(def)) {
1548
- strippable.add(key);
1714
+ droppable.add(key);
1715
+ } else if (isPureNamedFormula(def)) {
1716
+ droppable.add(key);
1717
+ unseenReads.add(key);
1549
1718
  }
1550
1719
  }
1551
- // Iterated to a fixpoint: rescuing one array can reveal a read of another from its own def.
1720
+ for (const key of inheritedStateKeys) {
1721
+ if (key in layoutDoc.state) {
1722
+ droppable.add(key);
1723
+ }
1724
+ }
1725
+ // Iterated to a fixpoint: rescuing one entry can reveal a read of another from its own def.
1552
1726
  let rescued = true;
1553
1727
  while (rescued) {
1554
1728
  rescued = false;
1555
1729
  const surviving = { ...layoutDoc.state };
1556
- for (const key of strippable) {
1730
+ /* `$site` holds project definitions as written and never runs, so a handler body there is no
1731
+ read; scanning it would keep every entry a project handler names alive on every page. */
1732
+ delete surviving.$site;
1733
+ delete surviving.$page;
1734
+ for (const key of droppable) {
1557
1735
  delete surviving[key];
1558
1736
  }
1559
- const haystack = JSON.stringify({ children: layoutDoc.children, state: surviving });
1560
- for (const key of strippable) {
1737
+ /* The whole document, because a root-level `attributes`, `style` or `$switch` read is a read;
1738
+ minus `$head` and `title`, which are resolved into `<head>` and never reach the island, and
1739
+ `$paths`, which route discovery consumed before this page existed: its `paginate` pointer
1740
+ names the paged entry, and read as a reference it kept every page of a paged list dynamic. */
1741
+ const { $head: _head, $paths: _paths, title: _title, ...body } = layoutDoc;
1742
+ const probe: JxElement = { ...body, state: surviving };
1743
+ /* A `$src` module's reads are invisible to the scan below, so while one survives every
1744
+ inherited entry stays, and every pure formula with it. Judged on the surviving state: a
1745
+ project-level `$src` Function is itself inherited, and must not keep everything alive on
1746
+ pages that never use it. */
1747
+ if (collectSrcImports(probe).length > 0) {
1748
+ for (const key of unseenReads) {
1749
+ if (droppable.delete(key)) {
1750
+ rescued = true;
1751
+ }
1752
+ }
1753
+ }
1754
+ const haystack = JSON.stringify(probe);
1755
+ for (const key of droppable) {
1561
1756
  if (referencesStateKey(haystack, key)) {
1562
- strippable.delete(key);
1757
+ droppable.delete(key);
1563
1758
  rescued = true;
1564
1759
  }
1565
1760
  }
1566
1761
  }
1567
- for (const key of strippable) {
1762
+ for (const key of droppable) {
1568
1763
  delete layoutDoc.state[key];
1569
1764
  }
1570
1765
  }
@@ -1702,9 +1897,12 @@ async function compilePage(
1702
1897
  typeof e === "string" && !e.startsWith("./") && !e.startsWith("../");
1703
1898
  const npmElements = [
1704
1899
  ...new Set(
1705
- [...(layoutDoc.$elements ?? []), ...(pageDoc.$elements ?? [])].filter((e) =>
1706
- isNpmElementEntry(e),
1707
- ),
1900
+ [
1901
+ ...(layoutDoc.$elements ?? []),
1902
+ // Every layout in the chain: resolution keeps only the outermost layout's entries.
1903
+ ...layoutLevels.flatMap((level) => level.doc.$elements ?? []),
1904
+ ...(pageDoc.$elements ?? []),
1905
+ ].filter((e) => isNpmElementEntry(e)),
1708
1906
  ),
1709
1907
  ];
1710
1908
  if (npmElements.length > 0) {
@@ -2108,8 +2306,13 @@ function evaluateMapTemplate(str: string, scope: JxScope): JxScope[string] {
2108
2306
  *
2109
2307
  * @param {JxElement | string} node
2110
2308
  * @param {JxScope} scope
2309
+ * @param {ReadonlySet<string>} buildResolved - See {@link buildResolvedStateKeys}
2111
2310
  */
2112
- function resolveDocTemplates(node: JxElement | string, scope: JxScope) {
2311
+ function resolveDocTemplates(
2312
+ node: JxElement | string,
2313
+ scope: JxScope,
2314
+ buildResolved: ReadonlySet<string>,
2315
+ ) {
2113
2316
  // Children are authored JSON, so a member reached by recursion may be neither node nor string.
2114
2317
  if (!isNonNullObject(node)) {
2115
2318
  return;
@@ -2178,14 +2381,14 @@ function resolveDocTemplates(node: JxElement | string, scope: JxScope) {
2178
2381
  }
2179
2382
  const rawChildren = node.children;
2180
2383
  // Legacy whole-children repeater: expand the items into the node's static children.
2181
- // Only when the expansion actually produced nodes. `expandMappedArrayStatic` returns `null` when
2182
- // `items` cannot be resolved at build time and `[]` when it resolves to an empty array — and `[]`
2183
- // Is truthy, so an empty build-time list used to replace the repeater with nothing, discarding the
2184
- // Definition the client needed. There is no prerendered output to preserve in that case, so the
2185
- // Repeater is left in place for the client to bind (a page containing one is never zero-JS).
2384
+ // `expandMappedArrayStatic` answers `null` for a list the client must keep: one whose `items`
2385
+ // Cannot be resolved at build time, and one that resolves to an EMPTY array out of client state.
2386
+ // Replacing the second with its empty expansion would discard the definition the client needs,
2387
+ // And the list could never populate. An empty array comes back only for a list the build itself
2388
+ // Resolved, which renders nothing and leaves nothing for the client (compiler.md §8.1).
2186
2389
  if (isMappedArray(rawChildren)) {
2187
- const expanded = expandMappedArrayStatic(rawChildren, scope);
2188
- if (expanded && expanded.length > 0) {
2390
+ const expanded = expandMappedArrayStatic(rawChildren, scope, buildResolved);
2391
+ if (expanded) {
2189
2392
  node.children = expanded;
2190
2393
  return;
2191
2394
  }
@@ -2198,7 +2401,7 @@ function resolveDocTemplates(node: JxElement | string, scope: JxScope) {
2198
2401
  const resolvedNodes = resolved as (JxElement | string)[];
2199
2402
  node.children = resolvedNodes;
2200
2403
  for (const child of resolvedNodes) {
2201
- resolveDocTemplates(child, scope);
2404
+ resolveDocTemplates(child, scope, buildResolved);
2202
2405
  }
2203
2406
  }
2204
2407
  } else if (Array.isArray(node.children)) {
@@ -2213,52 +2416,111 @@ function resolveDocTemplates(node: JxElement | string, scope: JxScope) {
2213
2416
  const resolvedNodes = resolved as (JxElement | string)[];
2214
2417
  node.children.splice(i, 1, ...resolvedNodes);
2215
2418
  for (const spliced of resolvedNodes) {
2216
- resolveDocTemplates(spliced, scope);
2419
+ resolveDocTemplates(spliced, scope, buildResolved);
2217
2420
  }
2218
2421
  i += resolvedNodes.length;
2219
2422
  continue;
2220
2423
  }
2221
2424
  }
2222
- // Array pseudo-element among siblings: expand its items in place, on the same
2223
- // Produced-nothing rule as the whole-children branch above.
2425
+ // Array pseudo-element among siblings: expand its items in place, on the same rule as the
2426
+ // Whole-children branch above. An empty expansion removes the member and nothing else.
2224
2427
  if (isMappedArray(child)) {
2225
- const expanded = expandMappedArrayStatic(child, scope);
2226
- if (expanded && expanded.length > 0) {
2428
+ const expanded = expandMappedArrayStatic(child, scope, buildResolved);
2429
+ if (expanded) {
2227
2430
  node.children.splice(i, 1, ...expanded);
2228
2431
  i += expanded.length;
2229
2432
  continue;
2230
2433
  }
2231
2434
  }
2232
- resolveDocTemplates(child, scope);
2435
+ resolveDocTemplates(child, scope, buildResolved);
2233
2436
  i += 1;
2234
2437
  }
2235
2438
  }
2236
2439
  }
2237
2440
 
2238
2441
  /**
2239
- * Whether a serialized document fragment still reads a given state key — as a `${state.key}`
2240
- * template, a bare `state.key` inside a handler or computed body, or a `#/state/key` $ref.
2442
+ * The top-level state keys whose value the BUILD produced, so nothing in the browser fills them in
2443
+ * later: an entry resolved through its class (`timing: "compiler"`, or no `timing` and a class
2444
+ * mapping, which is how a content collection is written), the entry a paged route replaced with its
2445
+ * slice, and the injected `$site` and `$page` context.
2446
+ *
2447
+ * An authored value is not in the set, whatever its shape: `{ "default": [] }` and a bare `[]` are
2448
+ * client state that starts empty, and a list over one is the client's to populate. A key in the set
2449
+ * that a handler writes is excluded where the set is read ({@link isBuildResolvedListSource}).
2241
2450
  *
2242
- * @param {string} haystack - JSON-serialized document fragment
2243
- * @param {string} key
2451
+ * @param {Record<string, JxStateDefinition>} authored - The state before `resolvePrototypes` ran
2452
+ * @param {Record<string, JxStateDefinition>} resolved - The same state afterwards
2453
+ * @param {string} [pagedKey] - The entry a paged route replaced with its slice
2454
+ * @returns {Set<string>}
2455
+ */
2456
+ function buildResolvedStateKeys(
2457
+ authored: Record<string, JxStateDefinition>,
2458
+ resolved: Record<string, JxStateDefinition>,
2459
+ pagedKey?: string,
2460
+ ): Set<string> {
2461
+ const keys = new Set<string>(["$site", "$page"]);
2462
+ if (pagedKey !== undefined) {
2463
+ keys.add(pagedKey);
2464
+ }
2465
+ for (const [key, def] of Object.entries(authored)) {
2466
+ // `resolvePrototypes` replaces an entry it resolved and leaves one it could not resolve as the
2467
+ // Same object, so identity says which happened. A client- or server-timed entry it LOWERED is
2468
+ // Replaced too, by a definition the browser runs, and is not build-resolved.
2469
+ if (
2470
+ isPrototypeDef(def) &&
2471
+ (def.timing === undefined || def.timing === "compiler") &&
2472
+ resolved[key] !== def
2473
+ ) {
2474
+ keys.add(key);
2475
+ }
2476
+ }
2477
+ return keys;
2478
+ }
2479
+
2480
+ /**
2481
+ * Whether a mapped array's `items` is a source the build fully resolved, so an empty result is the
2482
+ * list's final answer: a literal, a `$map/` pointer (a row exists only while the build expands it),
2483
+ * or a `#/state/` pointer into a build-resolved entry no handler writes.
2484
+ *
2485
+ * @param {JxMappedArray["items"]} itemsSrc
2486
+ * @param {JxScope} scope
2487
+ * @param {ReadonlySet<string>} buildResolved - See {@link buildResolvedStateKeys}
2244
2488
  * @returns {boolean}
2245
2489
  */
2246
- function referencesStateKey(haystack: string, key: string): boolean {
2247
- const escaped = key.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
2248
- return new RegExp(String.raw`\bstate\.${escaped}\b|#/state/${escaped}(?=["/])`).test(haystack);
2490
+ function isBuildResolvedListSource(
2491
+ itemsSrc: JxMappedArray["items"],
2492
+ scope: JxScope,
2493
+ buildResolved: ReadonlySet<string>,
2494
+ ): boolean {
2495
+ if (!isRef(itemsSrc)) {
2496
+ return true;
2497
+ }
2498
+ const ref = itemsSrc.$ref;
2499
+ if (ref.startsWith("$map/")) {
2500
+ return true;
2501
+ }
2502
+ // The first reference token, unescaped as RFC 6901 §4 orders it (`~1` before `~0`). A pointer in
2503
+ // Any other scheme names nothing the build is known to have resolved.
2504
+ const [token = ""] = ref.slice("#/state/".length).split("/");
2505
+ const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
2506
+ return ref.startsWith("#/state/") && buildResolved.has(key) && !isRuntimeOnlyStateKey(scope, key);
2249
2507
  }
2250
2508
 
2251
2509
  /**
2252
- * Statically expand a mapped array to its resolved item nodes when `items` resolves to an array at
2253
- * build time, or null otherwise (leave the array node for client-side rendering).
2510
+ * Statically expand a mapped array to its resolved item nodes, or null when the array node is left
2511
+ * for client-side rendering: `items` does not resolve to an array at build time, or it resolves to
2512
+ * an empty one out of client state, which the client may still fill. An empty array is returned
2513
+ * only for a source the build fully resolved ({@link isBuildResolvedListSource}).
2254
2514
  *
2255
2515
  * @param {JxMappedArray} arrayDef
2256
2516
  * @param {JxScope} scope
2517
+ * @param {ReadonlySet<string>} buildResolved - See {@link buildResolvedStateKeys}
2257
2518
  * @returns {(JxElement | string)[] | null}
2258
2519
  */
2259
2520
  function expandMappedArrayStatic(
2260
2521
  arrayDef: JxMappedArray,
2261
2522
  scope: JxScope,
2523
+ buildResolved: ReadonlySet<string>,
2262
2524
  ): (JxElement | string)[] | null {
2263
2525
  const itemsSrc = arrayDef.items;
2264
2526
  // A non-array, non-ref `items` falls through to the array check below and expands to nothing.
@@ -2267,6 +2529,9 @@ function expandMappedArrayStatic(
2267
2529
  if (!Array.isArray(items) || !mapTemplate) {
2268
2530
  return null;
2269
2531
  }
2532
+ if (items.length === 0 && !isBuildResolvedListSource(itemsSrc, scope, buildResolved)) {
2533
+ return null;
2534
+ }
2270
2535
  const rows: readonly JxScope[string][] = items;
2271
2536
  return rows.map((item, index) => {
2272
2537
  /* SAFETY: `Object.create(scope)` is a new object with no own keys whose prototype is `scope`,
@@ -2276,7 +2541,7 @@ function expandMappedArrayStatic(
2276
2541
  childScope["$map/item"] = item;
2277
2542
  childScope["$map/index"] = index;
2278
2543
  const expanded = expandMapTemplate(mapTemplate, childScope);
2279
- resolveDocTemplates(expanded, childScope);
2544
+ resolveDocTemplates(expanded, childScope, buildResolved);
2280
2545
  return expanded;
2281
2546
  });
2282
2547
  }