@jxsuite/compiler 9.0.1 → 10.0.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.
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * Coordinates the full site build pipeline: 1. Load project.json 2. Discover pages/ routes 3.
5
5
  * Expand dynamic routes ($paths) 4. For each route: resolve layout, merge $head, inject context,
6
- * compile 5. Emit compiled files to dist/ 6. Generate redirects
6
+ * compile 5. Emit compiled files to dist/, with the Custom Elements Manifest of the components it
7
+ * compiled (spec.md §16.8) 6. Generate redirects
7
8
  *
8
9
  * This is the Phase 1 implementation of site-architecture spec §12.
9
10
  *
@@ -12,25 +13,32 @@
12
13
  */
13
14
 
14
15
  import {
16
+ copyFileSync,
15
17
  cpSync,
16
18
  existsSync,
17
19
  mkdirSync,
20
+ mkdtempSync,
18
21
  readFileSync,
19
22
  rmSync,
20
23
  statSync,
21
24
  writeFileSync,
22
25
  } from "node:fs";
23
26
  import { createHash } from "node:crypto";
27
+ import { tmpdir } from "node:os";
24
28
  import { basename, dirname, join, relative, resolve, sep } from "node:path";
25
29
  import {
30
+ isBoolean,
26
31
  isJsonObject,
27
32
  isMappedArray,
28
33
  isNonNullObject,
34
+ isNumber,
29
35
  isPrototypeDef,
30
36
  isRef,
31
37
  isString,
32
38
  isTemplateString,
33
39
  } from "@jxsuite/schema/guards";
40
+ import { cemManifest, cemManifestText } from "@jxsuite/schema/cem-manifest";
41
+ import type { CemDefinition } from "@jxsuite/schema/cem-manifest";
34
42
  import { errorMessage } from "@jxsuite/schema/parse";
35
43
  import {
36
44
  isNpmSpecifier,
@@ -40,9 +48,10 @@ import {
40
48
  siteBasePath,
41
49
  withBase,
42
50
  } from "@jxsuite/schema/asset-paths";
43
- import { rewriteHtmlBase } from "./base-path.ts";
51
+ import { rebaseDocument, rewriteCssUrls, rewriteHtmlBase } from "./base-path.ts";
44
52
  import {
45
53
  CLIENT_EXTERNALS,
54
+ bundleEntries,
46
55
  bundleEntry,
47
56
  bundleWorkerSource,
48
57
  isBundleableSrc,
@@ -94,33 +103,43 @@ import { serverRoutePrefix } from "../targets/compile-server.ts";
94
103
  import type { SiteConnectorSpec, SiteMountSpec } from "../targets/compile-server.ts";
95
104
  import {
96
105
  buildComponentCSS,
106
+ componentStylesheetHref,
107
+ shadowSheetText,
97
108
  buildInitialScope,
98
109
  collectSrcImports,
99
110
  buildInstanceScope,
100
111
  collectStyles,
101
112
  colorSchemePrePaintScript,
113
+ computeLiveTags,
102
114
  createSlotFill,
103
115
  definitionHasSlot,
104
116
  escapeStyleText,
105
117
  evaluateStaticTemplate,
106
118
  inheritProjectFormulas,
107
- isComponentFullyStatic,
119
+ isLiveComponent,
108
120
  isPureNamedFormula,
109
121
  isRuntimeOnlyStateKey,
122
+ listSettled,
110
123
  isSingleExpression,
111
124
  liftPropsAttributes,
125
+ observedAttributeProps,
112
126
  nextSlotId,
127
+ orderComponentTags,
113
128
  preRenderComponentHtml,
114
129
  pureSchemeOf,
115
130
  referencesStateKey,
116
131
  renderStaticNode,
132
+ resolveHostAttributes,
117
133
  resolveHostStyle,
118
- resolveRefValue,
134
+ refuseTemplateItems,
135
+ buildListRows,
136
+ tagNameToClassName,
119
137
  } from "../shared.ts";
120
138
  import type { ComponentPrerenderContext, StaticChild } from "../shared.ts";
121
139
  import { SLOT_ATTR } from "@jxsuite/runtime";
122
140
  import { resolvePrototypes } from "./prototype-resolver.ts";
123
- import { transformImageNodes } from "./image-transform.ts";
141
+ import { classEntrySource, locateClass, readsBuildContext } from "./external-class.ts";
142
+ import { literalReplacement, transformImageNodes } from "./image-transform.ts";
124
143
  import { collectCspSources, emptyCspSources } from "./csp.ts";
125
144
  import { resolveShadowMode } from "../shadow.ts";
126
145
  import {
@@ -160,16 +179,18 @@ import {
160
179
  writeClientRuntime,
161
180
  writeRuntimeSubpaths,
162
181
  } from "./client-runtime.ts";
163
- import { getImageCacheDir, loadCache, saveCache } from "./image-cache.ts";
182
+ import { loadCache, saveCache, usedVariantPaths } from "./image-cache.ts";
164
183
  import type { ImageConfig } from "./image-optimizer.ts";
165
184
  import type { ImageMetaCache } from "./image-transform.ts";
166
185
  import type {
167
186
  JsonObject,
168
187
  JsonValue,
169
188
  JxAttributeValue,
189
+ JxDocument,
170
190
  JxElement,
171
191
  JxHeadEntry,
172
192
  JxMappedArray,
193
+ JxPrototypeDef,
173
194
  JxStateDefinition,
174
195
  JxStyle,
175
196
  ProjectConfig,
@@ -224,6 +245,9 @@ export type BuildTimings = Record<BuildPhase | "total", number>;
224
245
  * @param {boolean} [options.verbose] - Log progress
225
246
  * @param {boolean} [options.includeHeld] - Keep entries a content type's `hold` rules match, for a
226
247
  * preview. Left off, a build leaves them out (site-architecture.md §7.6).
248
+ * @param {boolean} [options.optimizeImages] - `false` builds as if the project said
249
+ * `images.optimize: false`, whatever it says: no variant is encoded and every `<img>` keeps its
250
+ * source. For a build nobody measures, such as a preview deploy (site-architecture.md §9.2.1).
227
251
  * @returns {Promise<{ routes: number; files: number; errors: string[]; timings: BuildTimings }>}
228
252
  */
229
253
  export async function buildSite(
@@ -232,9 +256,10 @@ export async function buildSite(
232
256
  clean?: boolean;
233
257
  verbose?: boolean;
234
258
  includeHeld?: boolean;
259
+ optimizeImages?: boolean;
235
260
  } = {},
236
261
  ) {
237
- const { clean = true, includeHeld = false, verbose = false } = options;
262
+ const { clean = true, includeHeld = false, optimizeImages = true, verbose = false } = options;
238
263
  const errors: string[] = [];
239
264
  const log = verbose ? console.log.bind(console) : () => {};
240
265
  const timings: BuildTimings = {
@@ -258,6 +283,10 @@ export async function buildSite(
258
283
  // ── 1. Load project configuration ──────────────────────────────────────────
259
284
  log("Loading project.json...");
260
285
  const { config: projectConfig } = loadProjectConfig(projectRoot);
286
+ if (!optimizeImages && projectConfig.images.optimize) {
287
+ projectConfig.images = { ...projectConfig.images, optimize: false };
288
+ console.log("Image optimization is off for this build: images are published as they are.");
289
+ }
261
290
 
262
291
  // The legacy imports-based content model is gone (specs/extensions.md v2) — fail loudly with
263
292
  // The migration path instead of silently ignoring the section.
@@ -454,6 +483,37 @@ export async function buildSite(
454
483
 
455
484
  // ── 1b. Build the extension registry from project.json#/extensions ─────
456
485
  const registry = await buildProjectExtensionRegistry(projectRoot, projectConfig);
486
+ /*
487
+ * Class modules: each `timing: "client"` external class a page or component names is delivered
488
+ * as an entry module that default-exports the class, keyed by its `/assets/class-<Name>.js` URL
489
+ * and bundled in ONE call after every document has compiled (compiler.md §12). One call, because
490
+ * two classes that import the same module have to meet the same instance of it in the browser.
491
+ */
492
+ const classEntries = new Map<string, string>();
493
+ const deliverClass = (
494
+ def: JxPrototypeDef,
495
+ docDir: string | null,
496
+ imports: Record<string, string>,
497
+ ): string => {
498
+ const located = locateClass(def, { docDir, imports, projectRoot, registry });
499
+ if (located === undefined) {
500
+ throw new Error(
501
+ `external class "${def.$prototype}" names no class: give it a $src or an imports ` +
502
+ `entry, or enable the extension that provides "${def.$prototype}"`,
503
+ );
504
+ }
505
+ if (readsBuildContext(located.classDef)) {
506
+ throw new Error(
507
+ `external class "${def.$prototype}" reads the build's context (#/$context/) and cannot ` +
508
+ `run in a browser: use "timing": "compiler"`,
509
+ );
510
+ }
511
+ const source = classEntrySource(located);
512
+ const assetPath = sidecarAssetPath(`class:${located.exportName}`);
513
+ claimAsset(assetPath, located.classJsonPath, def.$prototype);
514
+ classEntries.set(assetPath, source);
515
+ return assetPath;
516
+ };
457
517
  const formatRegistry = registry.formats;
458
518
  // Every document's own modules (spec.md §23.2), read with the formats this project registered.
459
519
  const scripts = documentScripts(projectRoot, (path) => readPageDocument(path, formatRegistry));
@@ -562,6 +622,26 @@ export async function buildSite(
562
622
 
563
623
  closePhase("content");
564
624
 
625
+ /* The image pipeline's state, opened before the components compile: a component's images are
626
+ decided on its definition (step 5), so its module and its prerender agree. */
627
+ const cfImages = projectConfig.images.optimize && projectConfig.images.service === "cloudflare";
628
+ const imageCache = projectConfig.images.optimize && !cfImages ? loadCache(projectRoot) : null;
629
+ const imageMetaCache: ImageMetaCache | null = cfImages ? new Map() : null;
630
+ if (imageCache && projectConfig.images.formats?.includes("webp")) {
631
+ console.warn(
632
+ `images.formats lists "webp", which this compiler writes losslessly: its files are several ` +
633
+ `times the size of AVIF or JPEG. Keep it only for pixel-exact output; ["avif", "jpeg"] ` +
634
+ `is the default.`,
635
+ );
636
+ }
637
+ if (cfImages) {
638
+ console.log(
639
+ `images.service is "cloudflare" — srcsets use /cdn-cgi/image transform URLs. ` +
640
+ `Ensure Image Transformations are enabled for your zone (Cloudflare dashboard → ` +
641
+ `Images → Transformations); these URLs do not work on *.pages.dev / *.workers.dev previews.`,
642
+ );
643
+ }
644
+
565
645
  // ── 5. Compile site components ──────────────────────────────────────────
566
646
  const compiledComponentTags: string[] = [];
567
647
  const componentCSS = new Map<string, string>(); // TagName → CSS text
@@ -589,6 +669,11 @@ export async function buildSite(
589
669
  // `<script>` and the CSS sidecar both use, wherever the source file lives. So a component's
590
670
  // `$elements` imports are renamed to match, which needs every component's tag up front.
591
671
  const componentTagByPath = new Map(siteComponents.map((c) => [c.path, c.tagName]));
672
+ // The components whose stylesheet this build writes, and so the only ones a module may link.
673
+ const localTags = new Set(componentTagByPath.values());
674
+ // Each component's own rules, and which of them render into a shadow root (spec.md §16.6).
675
+ const ownSheets = new Map<string, string>();
676
+ const shadowTags = new Set<string>();
592
677
 
593
678
  /*
594
679
  * A component is a JavaScript module the page loads, and the page rewrite (`rewriteHtmlBase`) never
@@ -601,13 +686,79 @@ export async function buildSite(
601
686
  // So it is given the deployment base now (site-architecture.md §14.7).
602
687
  const serverBaseUrl = serverRoutePrefix(componentBase);
603
688
 
689
+ /*
690
+ * A component's build-time external classes (compiler.md §3), resolved once per component file
691
+ * and written as its initial state, so the module compiled from the file and the definition
692
+ * every page prerenders from start from the same value. The file is read more than once (as a
693
+ * site component, as the module's source, as another component's `$elements` dependency), so
694
+ * the entries the first read resolved are kept and assigned onto each later one.
695
+ */
696
+ const componentResolutions = new Map<string, Promise<Record<string, JxStateDefinition>>>();
697
+ const prepareComponent = async (
698
+ componentDoc: JxDocument | JxElement,
699
+ filePath: string | null,
700
+ ): Promise<void> => {
701
+ /*
702
+ * A component's images are decided on its definition, before the module is compiled from it
703
+ * and before any page prerenders it (site-architecture.md §9.2.7). Decided on the page alone,
704
+ * as it was, they reached only the prerendered markup: the module then replaced an `<img>`
705
+ * carrying `loading="lazy"` and a candidate list with one that had neither.
706
+ */
707
+ await transformImageNodes(
708
+ componentDoc,
709
+ /* SAFETY: `loadProjectConfig` spreads its `images` defaults under the author's block, so
710
+ every member the optimizer's config requires is present. */
711
+ projectConfig.images as ImageConfig,
712
+ projectRoot,
713
+ imageCache,
714
+ imageMetaCache ?? undefined,
715
+ assetMounts,
716
+ );
717
+ // Every document this build compiles is a file, so the empty key is never shared in practice.
718
+ const key = filePath ?? "";
719
+ const resolved = componentResolutions.get(key);
720
+ if (resolved === undefined) {
721
+ const resolving = resolvePrototypes(
722
+ componentDoc,
723
+ filePath === null ? {} : { sourcePath: filePath },
724
+ projectRoot,
725
+ {
726
+ asInitialValues: true,
727
+ config: projectConfig,
728
+ registerBundle: (specifier: string) => {
729
+ rewriteSidecarSrc(specifier, null);
730
+ },
731
+ registry,
732
+ sections,
733
+ },
734
+ );
735
+ componentResolutions.set(key, resolving);
736
+ await resolving;
737
+ return;
738
+ }
739
+ const entries = await resolved;
740
+ if (componentDoc.state) {
741
+ Object.assign(componentDoc.state, entries);
742
+ }
743
+ };
744
+
604
745
  for (const { doc: written, path: componentPath } of siteComponents) {
605
746
  /* The definition every page prerenders from, with the project formulas it reads (spec.md
606
747
  §13.4). The module is compiled from the file, and is given the same project state. */
607
748
  const doc = inheritProjectFormulas(written, projectConfig.state);
608
749
  try {
750
+ await prepareComponent(doc, componentPath);
609
751
  const elementOptions: CompileElementOptions = {
610
752
  formats: formatRegistry,
753
+ /* The module's own copy of the definition is re-rooted after its images are decided, so
754
+ what the module draws is what the page rewrite makes of the prerender. The copy every
755
+ page prerenders from stays as written: its markup goes through that rewrite. */
756
+ prepareDocument: async (moduleDoc, filePath) => {
757
+ await prepareComponent(moduleDoc, filePath);
758
+ rebaseDocument(moduleDoc, componentBase);
759
+ },
760
+ resolveClass: (def, docDir, imports) =>
761
+ withBase(componentBase, deliverClass(def, docDir, imports)),
611
762
  resolveElementPath: (refPath: string, currentDir: string | null) => {
612
763
  const depPath = currentDir ? resolve(currentDir, refPath) : resolve(refPath);
613
764
  const depTag = componentTagByPath.get(depPath);
@@ -618,10 +769,19 @@ export async function buildSite(
618
769
  rewriteSrc: (specifier: string, docDir: string | null) =>
619
770
  withBase(componentBase, rewriteSidecarSrc(specifier, docDir)),
620
771
  serverBaseUrl,
772
+ /* A root the module attaches itself links the sheet its prerender would have. Only for
773
+ a component whose sheet is written below; a `$elements` dependency compiled from
774
+ elsewhere has none. */
775
+ stylesheetHref: (tag) =>
776
+ localTags.has(tag) ? withBase(componentBase, componentStylesheetHref(tag)) : null,
621
777
  };
622
778
  if (projectConfig.$media) {
623
779
  elementOptions.$media = projectConfig.$media;
624
780
  }
781
+ /* The project default decides the module's mode as it decides the prerender's: without
782
+ it a page shipped a declarative root and a module that cleared the light DOM and
783
+ rendered into the host beside it. */
784
+ elementOptions.defaults = projectConfig.defaults;
625
785
  const result = await compileElement(componentPath, elementOptions);
626
786
  for (const f of result.files) {
627
787
  // Name the output after the tag. `injectComponentScripts` emits
@@ -663,18 +823,22 @@ export async function buildSite(
663
823
  projectConfig.$media ?? {},
664
824
  componentShadow,
665
825
  );
666
- if (css) {
667
- /*
668
- * A shadow component's sheet is linked from inside its own declarative shadow root, so
669
- * it is written to disk but kept OUT of the page-level map: a `:host`-rooted rule in
670
- * the document head matches nothing, and the duplicate request is pure cost.
671
- */
672
- if (componentShadow === null) {
673
- componentCSS.set(doc.tagName, css);
674
- }
826
+ ownSheets.set(doc.tagName, css);
827
+ if (componentShadow === null) {
828
+ // Inlined into every page that uses it, and written for anything that links it.
829
+ componentCSS.set(doc.tagName, css);
675
830
  collectAssetRefs(css, assetMounts, assetRefs);
676
- writeFileSync(resolve(componentOutDir, `${doc.tagName}.css`), css, "utf8");
831
+ writeFileSync(
832
+ resolve(componentOutDir, `${doc.tagName}.css`),
833
+ rewriteCssUrls(css, componentBase),
834
+ "utf8",
835
+ );
677
836
  fileCount += 1;
837
+ } else {
838
+ /* Linked from inside its own root, so it is kept OUT of the page-level map: a
839
+ `:host` rule in the document head matches nothing. Written after the loop, once
840
+ every light component it renders has a sheet to carry in. */
841
+ shadowTags.add(doc.tagName);
678
842
  }
679
843
  }
680
844
  } catch (error) {
@@ -684,11 +848,54 @@ export async function buildSite(
684
848
  console.error(`Error compiling component ${file}: ${message}`);
685
849
  }
686
850
  }
851
+ /* A shadow component's file carries its own rules and those of every light component it can
852
+ render, because the page's sheet cannot reach into the root (spec.md §16.6). The file is
853
+ fetched as written, so its `url()` references are re-rooted here. */
854
+ for (const tag of shadowTags) {
855
+ const css = shadowSheetText(tag, componentDefs, ownSheets, shadowTags);
856
+ collectAssetRefs(css, assetMounts, assetRefs);
857
+ writeFileSync(
858
+ resolve(componentOutDir, `${tag}.css`),
859
+ rewriteCssUrls(css, componentBase),
860
+ "utf8",
861
+ );
862
+ fileCount += 1;
863
+ }
687
864
  log(
688
865
  ` Compiled ${compiledComponentTags.length} component(s): ${compiledComponentTags.join(", ")}`,
689
866
  );
690
867
  }
691
868
 
869
+ // ── 5a. Custom Elements Manifest (spec.md §16.8) ────────────────────────
870
+ /*
871
+ * One manifest for every definition this build compiled, written beside the modules it
872
+ * describes. Module paths are relative to the project root, which is the package root a
873
+ * manifest's paths are read against, so a project that publishes its `dist/` names this file in
874
+ * its own `package.json` and nothing else has to be rewritten. A build that compiled no
875
+ * component writes none.
876
+ */
877
+ if (componentDefs.size > 0) {
878
+ const definitions = [...componentDefs].map(([tag, doc]): CemDefinition => ({
879
+ className: tagNameToClassName(tag),
880
+ doc,
881
+ modulePath: relative(projectRoot, resolve(outDir, "components", `${tag}.js`))
882
+ .split(sep)
883
+ .join("/"),
884
+ shadow: resolveShadowMode(doc, projectConfig.defaults) !== null,
885
+ tagName: tag,
886
+ }));
887
+ const { manifest, warnings } = cemManifest(definitions);
888
+ for (const warning of warnings) {
889
+ console.warn(warning);
890
+ }
891
+ writeFileSync(resolve(outDir, "custom-elements.json"), cemManifestText(manifest), "utf8");
892
+ fileCount += 1;
893
+ log(` Wrote custom-elements.json (${definitions.length} element(s))`);
894
+ }
895
+
896
+ // A page writes its module scripts so each tag follows every tag it renders.
897
+ const scriptOrder = orderComponentTags(compiledComponentTags, componentDefs);
898
+
692
899
  // ── 5b. Collect server entries ──────────────────────────────────────────
693
900
  /*
694
901
  * Every `timing: "server"` entry the site declares, before deduplication: each compiled
@@ -730,24 +937,6 @@ export async function buildSite(
730
937
 
731
938
  // ── 6. Compile each route ───────────────────────────────────────────────
732
939
 
733
- const cfImages = projectConfig.images.optimize && projectConfig.images.service === "cloudflare";
734
- const imageCache = projectConfig.images.optimize && !cfImages ? loadCache(projectRoot) : null;
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
- }
743
- if (cfImages) {
744
- console.log(
745
- `images.service is "cloudflare" — srcsets use /cdn-cgi/image transform URLs. ` +
746
- `Ensure Image Transformations are enabled for your zone (Cloudflare dashboard → ` +
747
- `Images → Transformations); these URLs do not work on *.pages.dev / *.workers.dev previews.`,
748
- );
749
- }
750
-
751
940
  // Sitemap is generated from the route table when a production `url` is configured
752
941
  // (absolute <loc> URLs require it) and not explicitly disabled via build.sitemap: false.
753
942
  const siteUrl = projectConfig.url;
@@ -899,6 +1088,7 @@ export async function buildSite(
899
1088
  },
900
1089
  runtimeImports,
901
1090
  registerElementBundle,
1091
+ deliverClass,
902
1092
  );
903
1093
  siteServerEntries.push(...result.serverEntries);
904
1094
 
@@ -913,23 +1103,16 @@ export async function buildSite(
913
1103
  }
914
1104
  }
915
1105
 
916
- // Determine which component tags are fully static (for script omission)
917
- const staticTags = new Set<string>();
918
- for (const [tag, def] of componentDefs) {
919
- if (isComponentFullyStatic(def)) {
920
- staticTags.add(tag);
921
- }
922
- }
923
-
924
1106
  // Inject component CSS and JS scripts
925
1107
  if (compiledComponentTags.length > 0) {
926
1108
  result.html = injectComponentScripts(
927
1109
  result.html,
928
1110
  compiledComponentTags,
929
1111
  componentCSS,
930
- staticTags,
1112
+ new Set(compiledComponentTags.filter((tag) => !result.liveTags.has(tag))),
931
1113
  result.files.map((f: { content: string }) => f.content).join("\n"),
932
1114
  runtimeImports,
1115
+ scriptOrder,
933
1116
  );
934
1117
  }
935
1118
 
@@ -1030,7 +1213,7 @@ export async function buildSite(
1030
1213
  fileCount += 1;
1031
1214
  }
1032
1215
 
1033
- // Write any additional files (island modules, etc.)
1216
+ // Write any additional files (the page's own module, etc.)
1034
1217
  for (const file of result.files) {
1035
1218
  const filePath = resolve(dirname(outPath), file.path);
1036
1219
  mkdirSync(dirname(filePath), { recursive: true });
@@ -1051,11 +1234,15 @@ export async function buildSite(
1051
1234
  // Prune only on fully successful builds — a route that failed to compile never
1052
1235
  // Touched its images, and pruning would evict their still-valid entries.
1053
1236
  saveCache(projectRoot, imageCache, { prune: errors.length === 0 });
1054
- const cacheOptimizedDir = resolve(getImageCacheDir(projectRoot), "_optimized");
1055
- if (existsSync(cacheOptimizedDir)) {
1237
+ /* Only the variants of entries this build resolved, never the directory: whatever else the
1238
+ cache holds (another build's leftovers, a stray file) is not part of this site. */
1239
+ const used = usedVariantPaths(imageCache).filter((path) => existsSync(path));
1240
+ if (used.length > 0) {
1056
1241
  const distOptimizedDir = resolve(outDir, "images/_optimized");
1057
1242
  mkdirSync(distOptimizedDir, { recursive: true });
1058
- cpSync(cacheOptimizedDir, distOptimizedDir, { recursive: true });
1243
+ for (const path of used) {
1244
+ copyFileSync(path, resolve(distOptimizedDir, basename(path)));
1245
+ }
1059
1246
  }
1060
1247
  const totalImages = Object.keys(imageCache.entries).length;
1061
1248
  if (totalImages > 0) {
@@ -1237,6 +1424,36 @@ export async function buildSite(
1237
1424
  }
1238
1425
  }
1239
1426
 
1427
+ if (classEntries.size > 0) {
1428
+ log(`Bundling ${classEntries.size} external class module(s)...`);
1429
+ /* Each entry is written to a temporary directory under its asset's base name, which is the name
1430
+ the bundler gives its output; an entry's imports are absolute paths, so where it stands does
1431
+ not matter. */
1432
+ const entryDir = mkdtempSync(join(tmpdir(), "jx-class-entries-"));
1433
+ try {
1434
+ const entryPaths = [...classEntries].map(([assetPath, source]) => {
1435
+ const entryPath = join(entryDir, basename(assetPath));
1436
+ writeFileSync(entryPath, source, "utf8");
1437
+ return entryPath;
1438
+ });
1439
+ const written = await bundleEntries(entryPaths, resolve(outDir, "assets"), {
1440
+ external: CLIENT_EXTERNALS,
1441
+ minify,
1442
+ target: "browser",
1443
+ });
1444
+ fileCount += written.length;
1445
+ for (const assetPath of classEntries.keys()) {
1446
+ log(` ${assetPath}`);
1447
+ }
1448
+ } catch (error) {
1449
+ const msg = `Error bundling external classes: ${errorMessage(error)}`;
1450
+ errors.push(msg);
1451
+ console.error(msg);
1452
+ } finally {
1453
+ rmSync(entryDir, { force: true, recursive: true });
1454
+ }
1455
+ }
1456
+
1240
1457
  if (elementBundles.size > 0) {
1241
1458
  log(`Bundling ${elementBundles.size} npm element set(s)...`);
1242
1459
  for (const [assetPath, specifiers] of elementBundles) {
@@ -1546,8 +1763,14 @@ async function compilePage(
1546
1763
  runtimeImports: Record<string, string>,
1547
1764
  /** Registers a page's npm `$elements` set as one bundle and returns its URL. */
1548
1765
  registerElementBundle: (specifiers: string[]) => string,
1766
+ /** Registers a `timing: "client"` external class's module and returns its URL (compiler.md §3). */
1767
+ deliverClass: (
1768
+ def: JxPrototypeDef,
1769
+ docDir: string | null,
1770
+ imports: Record<string, string>,
1771
+ ) => string,
1549
1772
  ) {
1550
- /* Derived rather than passed as a seventeenth parameter: it is a pure function of
1773
+ /* Derived rather than passed as one more parameter: it is a pure function of
1551
1774
  `projectConfig.url`, which is already here, so the two cannot disagree. */
1552
1775
  const basePath = siteBasePath(projectConfig.url);
1553
1776
 
@@ -1638,8 +1861,13 @@ async function compilePage(
1638
1861
  route.pagedState?.key,
1639
1862
  );
1640
1863
 
1641
- // Build scope from resolved state so template strings in title/$head can be evaluated
1642
- const scope = buildInitialScope(layoutDoc.state ?? {});
1864
+ // Build scope from resolved state so template strings in title/$head can be evaluated. It HOLDS
1865
+ // Every entry a handler writes: the template pass below replaces a template with its value, and a
1866
+ // Value baked over a binding the page's module must keep is a dead binding (compiler.md §8.1).
1867
+ const scope = buildInitialScope(layoutDoc.state ?? {}, null, {
1868
+ document: layoutDoc,
1869
+ holdMutable: true,
1870
+ });
1643
1871
 
1644
1872
  // Determine the page title — resolve template strings against the scope
1645
1873
  let title = pageTitle ?? projectConfig.name;
@@ -1685,7 +1913,28 @@ async function compilePage(
1685
1913
  };
1686
1914
  // One counter per page, so every `data-jx-slots` id on it is unique (spec.md §8.5).
1687
1915
  const slotIds = { n: 0 };
1688
- expandComponents(layoutDoc, componentDefs, slotCss, projectConfig.defaults, slotIds);
1916
+ /* Children written inside an instance are serialized here, before the page compiles, so nothing
1917
+ binds them afterwards (spec.md §15.2). A template the pass above left for the client would
1918
+ therefore be lost, so it is resolved against a scope that does not hold: the entry's initial
1919
+ value is what the page shows. Built on first use: most pages place no such template, and the
1920
+ scope clones the page's whole state. */
1921
+ let slotScopeMemo: JxScope | undefined;
1922
+ const slotScope = () => (slotScopeMemo ??= buildInitialScope(layoutDoc.state ?? {}));
1923
+ /*
1924
+ * Which components ship their module on this page (compiler.md §8.1): a definition that is not
1925
+ * fully static, and every registered tag such a definition renders when this page draws it,
1926
+ * because its module creates that element bare and only the element's own module fills it in.
1927
+ * The rest are static here: stamped `data-jx-static`, with no module loaded for them. Read
1928
+ * before the expansion, which replaces each instance's children with its prerender.
1929
+ */
1930
+ const liveTags = computeLiveTags(componentDefs, layoutDoc);
1931
+ expandComponents(layoutDoc, componentDefs, {
1932
+ defaults: projectConfig.defaults,
1933
+ liveTags,
1934
+ slotCss,
1935
+ slotIds,
1936
+ slotScope,
1937
+ });
1689
1938
 
1690
1939
  // Strip resolved timing: "compiler" state entries — they're now baked into the tree
1691
1940
  // And keeping them would cause isDynamic() to misclassify the page as dynamic.
@@ -1845,34 +2094,30 @@ async function compilePage(
1845
2094
  * The page's own module (`app.js`) is JavaScript the page loads, like a component: the page
1846
2095
  * rewrite does not read it, so its `/assets/` imports are re-rooted on the site base here.
1847
2096
  */
2097
+ /* A `timing: "client"` external class the page still holds after resolution and lowering: its
2098
+ module is bundled under `/assets/`, and the page's module imports it (compiler.md §3). */
2099
+ resolveClass: (def: JxPrototypeDef) =>
2100
+ withBase(basePath, deliverClass(def, dirname(route.sourcePath), layoutDoc.imports ?? {})),
1848
2101
  rewriteSrc: (specifier: string) =>
1849
2102
  withBase(basePath, rewriteSidecarSrc(specifier, dirname(route.sourcePath))),
2103
+ /*
2104
+ * The page-template tiers emit their own import map, and `injectComponentScripts` sees a map
2105
+ * already present and declines to add its own, so both halves have to name the same URLs. The
2106
+ * whole map, prefix keys included: a compiled module imports lit subpaths (a keyed list's
2107
+ * `repeat`), and a page map holding only the two exact keys left those unresolvable on exactly
2108
+ * the pages that write their own map (site-architecture.md §8.7).
2109
+ */
2110
+ runtimeImports,
1850
2111
  // The page's own module calls the worker's routes, under the same base the worker registers.
1851
2112
  serverBaseUrl: serverRoutePrefix(basePath),
1852
2113
  title,
1853
2114
  };
1854
- /*
1855
- * The page-template tiers emit their own import map, and it defaulted to the CDN — so a page
1856
- * that reached compile-static/compile-client kept loading its runtime from esm.sh even after
1857
- * the self-hosting landed, because `injectComponentScripts` sees a map already present and
1858
- * declines to add its own. Both halves have to name the same URLs.
1859
- */
1860
- const reactivitySrc = runtimeImports["@vue/reactivity"];
1861
- if (reactivitySrc !== undefined) {
1862
- compileOptions.reactivitySrc = reactivitySrc;
1863
- }
1864
- const litHtmlSrc = runtimeImports["lit-html"];
1865
- if (litHtmlSrc !== undefined) {
1866
- compileOptions.litHtmlSrc = litHtmlSrc;
1867
- }
1868
2115
  const result = await compile(layoutDoc, compileOptions);
1869
2116
 
1870
2117
  // Inject CSS rules collected from component slot content
1871
2118
  if (slotCss.rules.length > 0) {
1872
- result.html = result.html.replace(
1873
- "</head>",
1874
- `<style>\n${escapeStyleText(slotCss.rules.join("\n"))}\n</style>\n</head>`,
1875
- );
2119
+ const slotStyle = `<style>\n${escapeStyleText(slotCss.rules.join("\n"))}\n</style>\n</head>`;
2120
+ result.html = result.html.replace("</head>", literalReplacement(slotStyle));
1876
2121
  }
1877
2122
 
1878
2123
  // Post-process: inject merged <head> content into the compiled HTML
@@ -1915,6 +2160,7 @@ async function compilePage(
1915
2160
  excludeFromSitemap: pageDoc.$sitemap === false,
1916
2161
  files: result.files,
1917
2162
  html: result.html,
2163
+ liveTags,
1918
2164
  /*
1919
2165
  * Reported rather than warned about here: a mistyped `rel` almost always lives in the site or
1920
2166
  * layout `$head`, which means it is on every page, and the caller is the only scope that can
@@ -2200,7 +2446,20 @@ function inertAttribute(resolved: string): string {
2200
2446
  }
2201
2447
 
2202
2448
  /**
2203
- * Deep-clone a map template, resolving template strings and $ref values against the given scope.
2449
+ * The text a resolved template text child stands for, or `null` when the result is not text: a
2450
+ * string, number or boolean is substituted, while `null`, `undefined` and an object keep the
2451
+ * template, as `textContent`'s fallback does (compiler.md §2.2).
2452
+ *
2453
+ * @param {JxScope[string]} value
2454
+ * @returns {string | null}
2455
+ */
2456
+ function textChildValue(value: JxScope[string]): string | null {
2457
+ return isString(value) || isNumber(value) || isBoolean(value) ? String(value) : null;
2458
+ }
2459
+
2460
+ /**
2461
+ * Deep-clone a map template, resolving template strings and $ref values against the given scope. A
2462
+ * template text child resolves per item like every other position.
2204
2463
  *
2205
2464
  * @param {JxElement} template
2206
2465
  * @param {JxScope} scope
@@ -2217,7 +2476,9 @@ function expandMapTemplate(template: JxElement, scope: JxScope): JxElement {
2217
2476
  if (k === "children" && Array.isArray(template.children)) {
2218
2477
  node.children = template.children.map((child) => {
2219
2478
  if (isString(child)) {
2220
- return child;
2479
+ return isTemplateString(child)
2480
+ ? (textChildValue(evaluateMapTemplate(child, scope)) ?? child)
2481
+ : child;
2221
2482
  }
2222
2483
  return expandMapTemplate(child, scope);
2223
2484
  });
@@ -2302,7 +2563,8 @@ function evaluateMapTemplate(str: string, scope: JxScope): JxScope[string] {
2302
2563
 
2303
2564
  /**
2304
2565
  * Recursively resolve template strings in a document tree against a scope. Mutates the document in
2305
- * place — evaluates ${...} in innerHTML, textContent, style values, and attribute values.
2566
+ * place — evaluates ${...} in innerHTML, textContent, style values, attribute values, and text
2567
+ * children (compiler.md §2.2).
2306
2568
  *
2307
2569
  * @param {JxElement | string} node
2308
2570
  * @param {JxScope} scope
@@ -2421,6 +2683,12 @@ function resolveDocTemplates(
2421
2683
  i += resolvedNodes.length;
2422
2684
  continue;
2423
2685
  }
2686
+ const resolvedText = textChildValue(resolved);
2687
+ if (resolvedText !== null) {
2688
+ node.children[i] = resolvedText;
2689
+ i += 1;
2690
+ continue;
2691
+ }
2424
2692
  }
2425
2693
  // Array pseudo-element among siblings: expand its items in place, on the same rule as the
2426
2694
  // Whole-children branch above. An empty expansion removes the member and nothing else.
@@ -2508,9 +2776,10 @@ function isBuildResolvedListSource(
2508
2776
 
2509
2777
  /**
2510
2778
  * 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}).
2779
+ * for client-side rendering: a source it reads is not settled at build time ({@link listSettled}),
2780
+ * `items` does not resolve to an array, or it resolves to an empty one out of client state, which
2781
+ * the client may still fill. An empty array is returned only for a source the build fully resolved
2782
+ * ({@link isBuildResolvedListSource}).
2514
2783
  *
2515
2784
  * @param {JxMappedArray} arrayDef
2516
2785
  * @param {JxScope} scope
@@ -2522,17 +2791,25 @@ function expandMappedArrayStatic(
2522
2791
  scope: JxScope,
2523
2792
  buildResolved: ReadonlySet<string>,
2524
2793
  ): (JxElement | string)[] | null {
2794
+ refuseTemplateItems(arrayDef);
2525
2795
  const itemsSrc = arrayDef.items;
2526
- // A non-array, non-ref `items` falls through to the array check below and expands to nothing.
2527
- const items = isRef(itemsSrc) ? resolveRefValue(itemsSrc.$ref, scope) : itemsSrc;
2528
2796
  const mapTemplate = arrayDef.map;
2529
- if (!Array.isArray(items) || !mapTemplate) {
2797
+ /* Expanded only when everything the list reads is settled at build time (spec.md §10.3). A list
2798
+ whose `items`, `filter` or `sort` reads state a handler writes, or that only exists after
2799
+ hydration, was baked: the page shipped its first rows and a module with no binding to change
2800
+ them. A list nested in the template is asked too, because a row left unexpanded inside an
2801
+ expanded one would lose the `$map` it reads. */
2802
+ if (!mapTemplate || !listSettled(arrayDef, scope)) {
2803
+ return null;
2804
+ }
2805
+ // `items` filtered, then sorted, or null when it is not an array or a read threw.
2806
+ const rows = buildListRows(arrayDef, scope);
2807
+ if (rows === null) {
2530
2808
  return null;
2531
2809
  }
2532
- if (items.length === 0 && !isBuildResolvedListSource(itemsSrc, scope, buildResolved)) {
2810
+ if (rows.length === 0 && !isBuildResolvedListSource(itemsSrc, scope, buildResolved)) {
2533
2811
  return null;
2534
2812
  }
2535
- const rows: readonly JxScope[string][] = items;
2536
2813
  return rows.map((item, index) => {
2537
2814
  /* SAFETY: `Object.create(scope)` is a new object with no own keys whose prototype is `scope`,
2538
2815
  so every key it answers is a binding of `scope` until the row's own are set below. */
@@ -2553,31 +2830,42 @@ interface SlotCssCollector {
2553
2830
  media: Record<string, string>;
2554
2831
  }
2555
2832
 
2833
+ /** What {@link expandComponents} carries down the page tree. */
2834
+ interface ExpandOptions {
2835
+ /** Collects the static styles of slotted children, which are serialized before the style pass. */
2836
+ slotCss?: SlotCssCollector;
2837
+ /** Project defaults, read for `defaults.shadow` (spec.md §16.6). */
2838
+ defaults?: ProjectConfig["defaults"];
2839
+ /** The page's `data-jx-slots` counter. */
2840
+ slotIds?: { n: number };
2841
+ /** The tags whose instances ship their module (`computeLiveTags`). */
2842
+ liveTags?: ReadonlySet<string>;
2843
+ /** The scope the children written inside an instance resolve in: the page's, not holding. */
2844
+ slotScope?: () => JxScope;
2845
+ }
2846
+
2556
2847
  /**
2557
2848
  * Walk the document tree and expand registered custom elements in-place. Applies $props via
2558
2849
  * preRenderComponentHtml, marks static/prerendered. Slot children get their static styles collected
2559
- * into `slotCss` (assigning jxs-N classes) before being serialized to HTML.
2850
+ * into `slotCss` (each styled one given its `jxs-<n>` handle) before being serialized to HTML.
2560
2851
  *
2561
2852
  * @param {JxElement | string | (JxElement | string)[]} node - A nested array (authored JSON can
2562
2853
  * carry one among children) is walked member by member
2563
2854
  * @param {Map<string, JxElement>} componentDefs
2564
- * @param {SlotCssCollector} [slotCss]
2565
- * @param {ProjectConfig["defaults"]} [defaults] - Read for `defaults.shadow` (spec.md §16.6)
2566
- * @param {{ n: number }} [slotIds] - The page's `data-jx-slots` counter
2855
+ * @param {ExpandOptions} [options]
2567
2856
  */
2568
2857
  function expandComponents(
2569
2858
  node: JxElement | string | (JxElement | string)[],
2570
2859
  componentDefs: Map<string, JxElement>,
2571
- slotCss?: SlotCssCollector,
2572
- defaults?: ProjectConfig["defaults"],
2573
- slotIds?: { n: number },
2860
+ options: ExpandOptions = {},
2574
2861
  ) {
2862
+ const { defaults, liveTags, slotCss, slotIds, slotScope } = options;
2575
2863
  if (!isNonNullObject(node)) {
2576
2864
  return;
2577
2865
  }
2578
2866
  if (Array.isArray(node)) {
2579
2867
  for (const n of node) {
2580
- expandComponents(n, componentDefs, slotCss, defaults, slotIds);
2868
+ expandComponents(n, componentDefs, options);
2581
2869
  }
2582
2870
  return;
2583
2871
  }
@@ -2585,7 +2873,7 @@ function expandComponents(
2585
2873
  // Recurse into children first (bottom-up expansion)
2586
2874
  if (Array.isArray(node.children)) {
2587
2875
  for (const child of node.children) {
2588
- expandComponents(child, componentDefs, slotCss, defaults, slotIds);
2876
+ expandComponents(child, componentDefs, options);
2589
2877
  }
2590
2878
  }
2591
2879
 
@@ -2613,11 +2901,12 @@ function expandComponents(
2613
2901
  * was given. Instances written inside `def` itself are another matter — those are reached
2614
2902
  * below, through `preRenderComponentHtml`, with `node` as the first frame of the path.
2615
2903
  */
2616
- const renderSlotted = (c: StaticChild) => {
2904
+ const childScope = (): JxScope => slotScope?.() ?? {};
2905
+ const renderSlotted = (c: StaticChild | JxMappedArray) => {
2617
2906
  if (slotCss && isNonNullObject(c) && !Array.isArray(c)) {
2618
2907
  collectStyles(c, slotCss.rules, slotCss.media, "", slotCss.counter, "jxs");
2619
2908
  }
2620
- return renderStaticNode(c, {}, null);
2909
+ return renderStaticNode(c, childScope(), null);
2621
2910
  };
2622
2911
 
2623
2912
  /*
@@ -2627,16 +2916,22 @@ function expandComponents(
2627
2916
  * render them twice.
2628
2917
  */
2629
2918
  const shadow = resolveShadowMode(def, defaults);
2630
- const props = node.$props || null;
2919
+ /* The instance's observed attributes, coerced, lie beneath its `$props` (spec.md §16.5): they
2920
+ feed the prerender, the host style and the path, and stay out of `data-jx-props`, because the
2921
+ element's module reads the attribute itself. The page walk has resolved the templates, so
2922
+ the attribute values resolve against nothing. */
2923
+ const observedProps = observedAttributeProps(def, node.attributes, {});
2924
+ const props = observedProps ? { ...observedProps, ...node.$props } : node.$props || null;
2631
2925
  // This instance is the first frame of the path, so a definition that names itself is reported
2632
2926
  // At the first nesting rather than after the stack overflows.
2633
2927
  const context: ComponentPrerenderContext = {
2634
2928
  componentDefs,
2635
2929
  defaults,
2930
+ liveTags,
2636
2931
  path: [{ key: JSON.stringify(props ?? {}), tag: tagName }],
2637
2932
  slotIds,
2638
2933
  };
2639
- const isStatic = isComponentFullyStatic(def);
2934
+ const isStatic = !isLiveComponent(tagName, def, liveTags);
2640
2935
  const { children } = node;
2641
2936
  /* Light mode places the children by slot name (spec.md §8.5). A live instance whose definition
2642
2937
  has a slot is stamped and its groups bracketed, so its element recovers them on upgrade. */
@@ -2650,7 +2945,7 @@ function expandComponents(
2650
2945
  const innerHTML = preRenderComponentHtml(
2651
2946
  def,
2652
2947
  props,
2653
- shadow ? null : createSlotFill(children, {}, renderSlotted, slotId),
2948
+ shadow ? null : createSlotFill(children, childScope(), renderSlotted, slotId),
2654
2949
  context,
2655
2950
  );
2656
2951
  if (slotId !== null) {
@@ -2665,7 +2960,7 @@ function expandComponents(
2665
2960
  */
2666
2961
  node.innerHTML = shadow
2667
2962
  ? `<template shadowrootmode="${shadow}">` +
2668
- `<link rel="stylesheet" href="/components/${tagName}.css">` +
2963
+ `<link rel="stylesheet" href="${componentStylesheetHref(tagName)}">` +
2669
2964
  `${innerHTML}</template>${slotContent ?? ""}`
2670
2965
  : innerHTML;
2671
2966
  delete node.children;
@@ -2681,7 +2976,8 @@ function expandComponents(
2681
2976
  * instance that took the definition's defaults with no host style at all — no size, no mask —
2682
2977
  * while the same instance one level down had them.
2683
2978
  */
2684
- const resolvedStyle = resolveHostStyle(def.style, buildInstanceScope(def, props));
2979
+ const instanceScope = buildInstanceScope(def, props);
2980
+ const resolvedStyle = resolveHostStyle(def.style, instanceScope);
2685
2981
  if (Object.keys(resolvedStyle).length > 0) {
2686
2982
  /* SAFETY: every value in `resolvedStyle` replaces a template-string declaration of
2687
2983
  `def.style`, and the page style pass interpolates declaration values into CSS text, so the
@@ -2689,10 +2985,19 @@ function expandComponents(
2689
2985
  node.style = { ...node.style, ...resolvedStyle } as JxStyle;
2690
2986
  }
2691
2987
 
2988
+ /* The definition's root attributes, resolved against the instance and written over the
2989
+ instance's own, as the element writes them on itself when it connects (spec.md §16.1). The
2990
+ prerendered host therefore already matches a rule keyed on one (`&[data-variant="accent"]`),
2991
+ and a static instance, which loads no module, carries them at all. */
2992
+ const hostAttributes = resolveHostAttributes(def.attributes, instanceScope);
2993
+ if (Object.keys(hostAttributes).length > 0) {
2994
+ node.attributes = { ...node.attributes, ...hostAttributes };
2995
+ }
2996
+
2692
2997
  /*
2693
2998
  * A non-static instance discards its prerendered markup on upgrade and re-renders, so the
2694
2999
  * props have to survive as data or the element comes back with its state defaults — correct
2695
- * content painting first and then being replaced by the wrong content. compiler.md §5.2 gives
3000
+ * content painting first and then being replaced by the wrong content. compiler.md §4.4 gives
2696
3001
  * connectedCallback three prop sources and this is the first of them; the compiler read it but
2697
3002
  * never wrote it, and lifting `props.*` into $props above removed the other channel too.
2698
3003
  *
@@ -2726,6 +3031,9 @@ function expandComponents(
2726
3031
  * @param {Set<string>} [staticTags] - Tags where ALL instances are fully static (skip JS)
2727
3032
  * @param {string} [islandSource] - Concatenated island modules emitted for this page
2728
3033
  * @param {Record<string, string>} [runtimeImports] - The import map's `imports` object
3034
+ * @param {readonly string[]} [scriptOrder] - The tags in the order their module scripts are written
3035
+ * (`orderComponentTags`); the component CSS keeps the order of `allComponentTags`, so the cascade
3036
+ * does not move
2729
3037
  * @returns {string}
2730
3038
  */
2731
3039
  function injectComponentScripts(
@@ -2735,6 +3043,7 @@ function injectComponentScripts(
2735
3043
  staticTags = new Set<string>(),
2736
3044
  islandSource = "",
2737
3045
  runtimeImports: Record<string, string> = {},
3046
+ scriptOrder: readonly string[] = allComponentTags,
2738
3047
  ) {
2739
3048
  // A component reaches a page two ways: as a literal tag in the static HTML, or referenced only
2740
3049
  // From inside an island's client template — in which case the tag exists solely in the island's
@@ -2772,14 +3081,17 @@ function injectComponentScripts(
2772
3081
  componentCss === "" ? "" : `<style>\n${escapeStyleText(componentCss)}\n </style>`;
2773
3082
  const intoHead = (fragments: string[]) => {
2774
3083
  const block = fragments.filter(Boolean).join("\n ");
2775
- return block === "" ? html : html.replace("</head>", ` ${block}\n</head>`);
3084
+ return block === "" ? html : html.replace("</head>", literalReplacement(` ${block}\n</head>`));
2776
3085
  };
2777
3086
 
2778
3087
  // Only inject JS for components that have non-static instances. An island-rendered instance is
2779
3088
  // Never prerendered, so it needs its module even when the component itself is fully static —
2780
3089
  // That module is what fills the element in client-side. This holds when the tag ALSO appears in
2781
3090
  // The static HTML: those instances are prerendered, but the ones the island creates are not.
2782
- const jsTags = usedTags.filter((tag: string) => inIsland(tag) || !staticTags.has(tag));
3091
+ const used = new Set(usedTags);
3092
+ const jsTags = scriptOrder.filter(
3093
+ (tag: string) => used.has(tag) && (inIsland(tag) || !staticTags.has(tag)),
3094
+ );
2783
3095
  if (jsTags.length === 0) {
2784
3096
  return intoHead([styleBlock]);
2785
3097
  }
@@ -2822,7 +3134,7 @@ function injectComponentScripts(
2822
3134
  .map((tag: string) => `<script type="module" src="/components/${tag}.js"></script>`)
2823
3135
  .join("\n ");
2824
3136
 
2825
- return result.replace("</body>", ` ${moduleScripts}\n</body>`);
3137
+ return result.replace("</body>", literalReplacement(` ${moduleScripts}\n</body>`));
2826
3138
  }
2827
3139
 
2828
3140
  /**
@@ -2851,7 +3163,10 @@ function injectNpmElementScripts(html: string, bundleUrl: string) {
2851
3163
  * documented breakage, not merely 462kb. Bundling the SET as one entry gives one copy, no
2852
3164
  * external, and 190kb for the seven-component demo that motivated this.
2853
3165
  */
2854
- return html.replace("</body>", ` <script type="module" src="${bundleUrl}"></script>\n</body>`);
3166
+ return html.replace(
3167
+ "</body>",
3168
+ literalReplacement(` <script type="module" src="${bundleUrl}"></script>\n</body>`),
3169
+ );
2855
3170
  }
2856
3171
 
2857
3172
  /**
@@ -2885,19 +3200,24 @@ function injectHead(
2885
3200
  }
2886
3201
  let result = html;
2887
3202
  if (headPattern.test(result)) {
2888
- result = result.replace(headPattern, `<head>\n ${headHtml}${preservedBlocks}\n</head>`);
3203
+ /* Escaped, never raw: a replacement STRING reads `$1`, `$&` and `$'` as patterns, so a
3204
+ * head entry holding "$10 a month" spliced capture group 1 (the old head) into the tag. */
3205
+ result = result.replace(
3206
+ headPattern,
3207
+ literalReplacement(`<head>\n ${headHtml}${preservedBlocks}\n</head>`),
3208
+ );
2889
3209
  }
2890
3210
 
2891
3211
  // Set lang and dir on <html>. `dir` matters for the same reason `lang` does: without it, a
2892
3212
  // Right-to-left page renders left-to-right, and the default is not "unset" but "ltr".
2893
3213
  result = result.replace(/<html\s[^>]*>/i, (match: string) => {
2894
3214
  let tag = /lang=/.test(match)
2895
- ? match.replace(/lang="[^"]*"/, `lang="${root.lang}"`)
3215
+ ? match.replace(/lang="[^"]*"/, literalReplacement(`lang="${root.lang}"`))
2896
3216
  : match.replace("<html", `<html lang="${root.lang}"`);
2897
3217
  if (root.dir !== undefined) {
2898
3218
  tag = /\sdir=/.test(tag)
2899
3219
  ? tag.replace(/\sdir="[^"]*"/, ` dir="${root.dir}"`)
2900
- : tag.replace("<html", `<html dir="${root.dir}"`);
3220
+ : tag.replace("<html", literalReplacement(`<html dir="${root.dir}"`));
2901
3221
  }
2902
3222
  return tag;
2903
3223
  });