@jxsuite/compiler 9.1.0 → 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
  *
@@ -36,6 +37,8 @@ import {
36
37
  isString,
37
38
  isTemplateString,
38
39
  } from "@jxsuite/schema/guards";
40
+ import { cemManifest, cemManifestText } from "@jxsuite/schema/cem-manifest";
41
+ import type { CemDefinition } from "@jxsuite/schema/cem-manifest";
39
42
  import { errorMessage } from "@jxsuite/schema/parse";
40
43
  import {
41
44
  isNpmSpecifier,
@@ -45,7 +48,7 @@ import {
45
48
  siteBasePath,
46
49
  withBase,
47
50
  } from "@jxsuite/schema/asset-paths";
48
- import { rewriteHtmlBase } from "./base-path.ts";
51
+ import { rebaseDocument, rewriteCssUrls, rewriteHtmlBase } from "./base-path.ts";
49
52
  import {
50
53
  CLIENT_EXTERNALS,
51
54
  bundleEntries,
@@ -100,35 +103,43 @@ import { serverRoutePrefix } from "../targets/compile-server.ts";
100
103
  import type { SiteConnectorSpec, SiteMountSpec } from "../targets/compile-server.ts";
101
104
  import {
102
105
  buildComponentCSS,
106
+ componentStylesheetHref,
107
+ shadowSheetText,
103
108
  buildInitialScope,
104
109
  collectSrcImports,
105
110
  buildInstanceScope,
106
111
  collectStyles,
107
112
  colorSchemePrePaintScript,
113
+ computeLiveTags,
108
114
  createSlotFill,
109
115
  definitionHasSlot,
110
116
  escapeStyleText,
111
117
  evaluateStaticTemplate,
112
118
  inheritProjectFormulas,
113
- isComponentFullyStatic,
119
+ isLiveComponent,
114
120
  isPureNamedFormula,
115
121
  isRuntimeOnlyStateKey,
122
+ listSettled,
116
123
  isSingleExpression,
117
124
  liftPropsAttributes,
118
125
  observedAttributeProps,
119
126
  nextSlotId,
127
+ orderComponentTags,
120
128
  preRenderComponentHtml,
121
129
  pureSchemeOf,
122
130
  referencesStateKey,
123
131
  renderStaticNode,
132
+ resolveHostAttributes,
124
133
  resolveHostStyle,
125
- resolveRefValue,
134
+ refuseTemplateItems,
135
+ buildListRows,
136
+ tagNameToClassName,
126
137
  } from "../shared.ts";
127
138
  import type { ComponentPrerenderContext, StaticChild } from "../shared.ts";
128
139
  import { SLOT_ATTR } from "@jxsuite/runtime";
129
140
  import { resolvePrototypes } from "./prototype-resolver.ts";
130
141
  import { classEntrySource, locateClass, readsBuildContext } from "./external-class.ts";
131
- import { transformImageNodes } from "./image-transform.ts";
142
+ import { literalReplacement, transformImageNodes } from "./image-transform.ts";
132
143
  import { collectCspSources, emptyCspSources } from "./csp.ts";
133
144
  import { resolveShadowMode } from "../shadow.ts";
134
145
  import {
@@ -611,6 +622,26 @@ export async function buildSite(
611
622
 
612
623
  closePhase("content");
613
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
+
614
645
  // ── 5. Compile site components ──────────────────────────────────────────
615
646
  const compiledComponentTags: string[] = [];
616
647
  const componentCSS = new Map<string, string>(); // TagName → CSS text
@@ -638,6 +669,11 @@ export async function buildSite(
638
669
  // `<script>` and the CSS sidecar both use, wherever the source file lives. So a component's
639
670
  // `$elements` imports are renamed to match, which needs every component's tag up front.
640
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>();
641
677
 
642
678
  /*
643
679
  * A component is a JavaScript module the page loads, and the page rewrite (`rewriteHtmlBase`) never
@@ -662,6 +698,22 @@ export async function buildSite(
662
698
  componentDoc: JxDocument | JxElement,
663
699
  filePath: string | null,
664
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
+ );
665
717
  // Every document this build compiles is a file, so the empty key is never shared in practice.
666
718
  const key = filePath ?? "";
667
719
  const resolved = componentResolutions.get(key);
@@ -698,7 +750,13 @@ export async function buildSite(
698
750
  await prepareComponent(doc, componentPath);
699
751
  const elementOptions: CompileElementOptions = {
700
752
  formats: formatRegistry,
701
- prepareDocument: prepareComponent,
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
+ },
702
760
  resolveClass: (def, docDir, imports) =>
703
761
  withBase(componentBase, deliverClass(def, docDir, imports)),
704
762
  resolveElementPath: (refPath: string, currentDir: string | null) => {
@@ -711,10 +769,19 @@ export async function buildSite(
711
769
  rewriteSrc: (specifier: string, docDir: string | null) =>
712
770
  withBase(componentBase, rewriteSidecarSrc(specifier, docDir)),
713
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,
714
777
  };
715
778
  if (projectConfig.$media) {
716
779
  elementOptions.$media = projectConfig.$media;
717
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;
718
785
  const result = await compileElement(componentPath, elementOptions);
719
786
  for (const f of result.files) {
720
787
  // Name the output after the tag. `injectComponentScripts` emits
@@ -756,18 +823,22 @@ export async function buildSite(
756
823
  projectConfig.$media ?? {},
757
824
  componentShadow,
758
825
  );
759
- if (css) {
760
- /*
761
- * A shadow component's sheet is linked from inside its own declarative shadow root, so
762
- * it is written to disk but kept OUT of the page-level map: a `:host`-rooted rule in
763
- * the document head matches nothing, and the duplicate request is pure cost.
764
- */
765
- if (componentShadow === null) {
766
- componentCSS.set(doc.tagName, css);
767
- }
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);
768
830
  collectAssetRefs(css, assetMounts, assetRefs);
769
- writeFileSync(resolve(componentOutDir, `${doc.tagName}.css`), css, "utf8");
831
+ writeFileSync(
832
+ resolve(componentOutDir, `${doc.tagName}.css`),
833
+ rewriteCssUrls(css, componentBase),
834
+ "utf8",
835
+ );
770
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);
771
842
  }
772
843
  }
773
844
  } catch (error) {
@@ -777,11 +848,54 @@ export async function buildSite(
777
848
  console.error(`Error compiling component ${file}: ${message}`);
778
849
  }
779
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
+ }
780
864
  log(
781
865
  ` Compiled ${compiledComponentTags.length} component(s): ${compiledComponentTags.join(", ")}`,
782
866
  );
783
867
  }
784
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
+
785
899
  // ── 5b. Collect server entries ──────────────────────────────────────────
786
900
  /*
787
901
  * Every `timing: "server"` entry the site declares, before deduplication: each compiled
@@ -823,24 +937,6 @@ export async function buildSite(
823
937
 
824
938
  // ── 6. Compile each route ───────────────────────────────────────────────
825
939
 
826
- const cfImages = projectConfig.images.optimize && projectConfig.images.service === "cloudflare";
827
- const imageCache = projectConfig.images.optimize && !cfImages ? loadCache(projectRoot) : null;
828
- const imageMetaCache: ImageMetaCache | null = cfImages ? new Map() : null;
829
- if (imageCache && projectConfig.images.formats?.includes("webp")) {
830
- console.warn(
831
- `images.formats lists "webp", which this compiler writes losslessly: its files are several ` +
832
- `times the size of AVIF or JPEG. Keep it only for pixel-exact output; ["avif", "jpeg"] ` +
833
- `is the default.`,
834
- );
835
- }
836
- if (cfImages) {
837
- console.log(
838
- `images.service is "cloudflare" — srcsets use /cdn-cgi/image transform URLs. ` +
839
- `Ensure Image Transformations are enabled for your zone (Cloudflare dashboard → ` +
840
- `Images → Transformations); these URLs do not work on *.pages.dev / *.workers.dev previews.`,
841
- );
842
- }
843
-
844
940
  // Sitemap is generated from the route table when a production `url` is configured
845
941
  // (absolute <loc> URLs require it) and not explicitly disabled via build.sitemap: false.
846
942
  const siteUrl = projectConfig.url;
@@ -1007,23 +1103,16 @@ export async function buildSite(
1007
1103
  }
1008
1104
  }
1009
1105
 
1010
- // Determine which component tags are fully static (for script omission)
1011
- const staticTags = new Set<string>();
1012
- for (const [tag, def] of componentDefs) {
1013
- if (isComponentFullyStatic(def)) {
1014
- staticTags.add(tag);
1015
- }
1016
- }
1017
-
1018
1106
  // Inject component CSS and JS scripts
1019
1107
  if (compiledComponentTags.length > 0) {
1020
1108
  result.html = injectComponentScripts(
1021
1109
  result.html,
1022
1110
  compiledComponentTags,
1023
1111
  componentCSS,
1024
- staticTags,
1112
+ new Set(compiledComponentTags.filter((tag) => !result.liveTags.has(tag))),
1025
1113
  result.files.map((f: { content: string }) => f.content).join("\n"),
1026
1114
  runtimeImports,
1115
+ scriptOrder,
1027
1116
  );
1028
1117
  }
1029
1118
 
@@ -1772,8 +1861,13 @@ async function compilePage(
1772
1861
  route.pagedState?.key,
1773
1862
  );
1774
1863
 
1775
- // Build scope from resolved state so template strings in title/$head can be evaluated
1776
- 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
+ });
1777
1871
 
1778
1872
  // Determine the page title — resolve template strings against the scope
1779
1873
  let title = pageTitle ?? projectConfig.name;
@@ -1819,7 +1913,28 @@ async function compilePage(
1819
1913
  };
1820
1914
  // One counter per page, so every `data-jx-slots` id on it is unique (spec.md §8.5).
1821
1915
  const slotIds = { n: 0 };
1822
- 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
+ });
1823
1938
 
1824
1939
  // Strip resolved timing: "compiler" state entries — they're now baked into the tree
1825
1940
  // And keeping them would cause isDynamic() to misclassify the page as dynamic.
@@ -1985,32 +2100,24 @@ async function compilePage(
1985
2100
  withBase(basePath, deliverClass(def, dirname(route.sourcePath), layoutDoc.imports ?? {})),
1986
2101
  rewriteSrc: (specifier: string) =>
1987
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,
1988
2111
  // The page's own module calls the worker's routes, under the same base the worker registers.
1989
2112
  serverBaseUrl: serverRoutePrefix(basePath),
1990
2113
  title,
1991
2114
  };
1992
- /*
1993
- * The page-template tiers emit their own import map, and it defaulted to the CDN — so a page
1994
- * that reached the client or custom-element target kept loading its runtime from esm.sh even after
1995
- * the self-hosting landed, because `injectComponentScripts` sees a map already present and
1996
- * declines to add its own. Both halves have to name the same URLs.
1997
- */
1998
- const reactivitySrc = runtimeImports["@vue/reactivity"];
1999
- if (reactivitySrc !== undefined) {
2000
- compileOptions.reactivitySrc = reactivitySrc;
2001
- }
2002
- const litHtmlSrc = runtimeImports["lit-html"];
2003
- if (litHtmlSrc !== undefined) {
2004
- compileOptions.litHtmlSrc = litHtmlSrc;
2005
- }
2006
2115
  const result = await compile(layoutDoc, compileOptions);
2007
2116
 
2008
2117
  // Inject CSS rules collected from component slot content
2009
2118
  if (slotCss.rules.length > 0) {
2010
- result.html = result.html.replace(
2011
- "</head>",
2012
- `<style>\n${escapeStyleText(slotCss.rules.join("\n"))}\n</style>\n</head>`,
2013
- );
2119
+ const slotStyle = `<style>\n${escapeStyleText(slotCss.rules.join("\n"))}\n</style>\n</head>`;
2120
+ result.html = result.html.replace("</head>", literalReplacement(slotStyle));
2014
2121
  }
2015
2122
 
2016
2123
  // Post-process: inject merged <head> content into the compiled HTML
@@ -2053,6 +2160,7 @@ async function compilePage(
2053
2160
  excludeFromSitemap: pageDoc.$sitemap === false,
2054
2161
  files: result.files,
2055
2162
  html: result.html,
2163
+ liveTags,
2056
2164
  /*
2057
2165
  * Reported rather than warned about here: a mistyped `rel` almost always lives in the site or
2058
2166
  * layout `$head`, which means it is on every page, and the caller is the only scope that can
@@ -2668,9 +2776,10 @@ function isBuildResolvedListSource(
2668
2776
 
2669
2777
  /**
2670
2778
  * Statically expand a mapped array to its resolved item nodes, or null when the array node is left
2671
- * for client-side rendering: `items` does not resolve to an array at build time, or it resolves to
2672
- * an empty one out of client state, which the client may still fill. An empty array is returned
2673
- * 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}).
2674
2783
  *
2675
2784
  * @param {JxMappedArray} arrayDef
2676
2785
  * @param {JxScope} scope
@@ -2682,17 +2791,25 @@ function expandMappedArrayStatic(
2682
2791
  scope: JxScope,
2683
2792
  buildResolved: ReadonlySet<string>,
2684
2793
  ): (JxElement | string)[] | null {
2794
+ refuseTemplateItems(arrayDef);
2685
2795
  const itemsSrc = arrayDef.items;
2686
- // A non-array, non-ref `items` falls through to the array check below and expands to nothing.
2687
- const items = isRef(itemsSrc) ? resolveRefValue(itemsSrc.$ref, scope) : itemsSrc;
2688
2796
  const mapTemplate = arrayDef.map;
2689
- 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)) {
2690
2803
  return null;
2691
2804
  }
2692
- if (items.length === 0 && !isBuildResolvedListSource(itemsSrc, scope, buildResolved)) {
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) {
2808
+ return null;
2809
+ }
2810
+ if (rows.length === 0 && !isBuildResolvedListSource(itemsSrc, scope, buildResolved)) {
2693
2811
  return null;
2694
2812
  }
2695
- const rows: readonly JxScope[string][] = items;
2696
2813
  return rows.map((item, index) => {
2697
2814
  /* SAFETY: `Object.create(scope)` is a new object with no own keys whose prototype is `scope`,
2698
2815
  so every key it answers is a binding of `scope` until the row's own are set below. */
@@ -2713,6 +2830,20 @@ interface SlotCssCollector {
2713
2830
  media: Record<string, string>;
2714
2831
  }
2715
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
+
2716
2847
  /**
2717
2848
  * Walk the document tree and expand registered custom elements in-place. Applies $props via
2718
2849
  * preRenderComponentHtml, marks static/prerendered. Slot children get their static styles collected
@@ -2721,23 +2852,20 @@ interface SlotCssCollector {
2721
2852
  * @param {JxElement | string | (JxElement | string)[]} node - A nested array (authored JSON can
2722
2853
  * carry one among children) is walked member by member
2723
2854
  * @param {Map<string, JxElement>} componentDefs
2724
- * @param {SlotCssCollector} [slotCss]
2725
- * @param {ProjectConfig["defaults"]} [defaults] - Read for `defaults.shadow` (spec.md §16.6)
2726
- * @param {{ n: number }} [slotIds] - The page's `data-jx-slots` counter
2855
+ * @param {ExpandOptions} [options]
2727
2856
  */
2728
2857
  function expandComponents(
2729
2858
  node: JxElement | string | (JxElement | string)[],
2730
2859
  componentDefs: Map<string, JxElement>,
2731
- slotCss?: SlotCssCollector,
2732
- defaults?: ProjectConfig["defaults"],
2733
- slotIds?: { n: number },
2860
+ options: ExpandOptions = {},
2734
2861
  ) {
2862
+ const { defaults, liveTags, slotCss, slotIds, slotScope } = options;
2735
2863
  if (!isNonNullObject(node)) {
2736
2864
  return;
2737
2865
  }
2738
2866
  if (Array.isArray(node)) {
2739
2867
  for (const n of node) {
2740
- expandComponents(n, componentDefs, slotCss, defaults, slotIds);
2868
+ expandComponents(n, componentDefs, options);
2741
2869
  }
2742
2870
  return;
2743
2871
  }
@@ -2745,7 +2873,7 @@ function expandComponents(
2745
2873
  // Recurse into children first (bottom-up expansion)
2746
2874
  if (Array.isArray(node.children)) {
2747
2875
  for (const child of node.children) {
2748
- expandComponents(child, componentDefs, slotCss, defaults, slotIds);
2876
+ expandComponents(child, componentDefs, options);
2749
2877
  }
2750
2878
  }
2751
2879
 
@@ -2773,11 +2901,12 @@ function expandComponents(
2773
2901
  * was given. Instances written inside `def` itself are another matter — those are reached
2774
2902
  * below, through `preRenderComponentHtml`, with `node` as the first frame of the path.
2775
2903
  */
2776
- const renderSlotted = (c: StaticChild) => {
2904
+ const childScope = (): JxScope => slotScope?.() ?? {};
2905
+ const renderSlotted = (c: StaticChild | JxMappedArray) => {
2777
2906
  if (slotCss && isNonNullObject(c) && !Array.isArray(c)) {
2778
2907
  collectStyles(c, slotCss.rules, slotCss.media, "", slotCss.counter, "jxs");
2779
2908
  }
2780
- return renderStaticNode(c, {}, null);
2909
+ return renderStaticNode(c, childScope(), null);
2781
2910
  };
2782
2911
 
2783
2912
  /*
@@ -2798,10 +2927,11 @@ function expandComponents(
2798
2927
  const context: ComponentPrerenderContext = {
2799
2928
  componentDefs,
2800
2929
  defaults,
2930
+ liveTags,
2801
2931
  path: [{ key: JSON.stringify(props ?? {}), tag: tagName }],
2802
2932
  slotIds,
2803
2933
  };
2804
- const isStatic = isComponentFullyStatic(def);
2934
+ const isStatic = !isLiveComponent(tagName, def, liveTags);
2805
2935
  const { children } = node;
2806
2936
  /* Light mode places the children by slot name (spec.md §8.5). A live instance whose definition
2807
2937
  has a slot is stamped and its groups bracketed, so its element recovers them on upgrade. */
@@ -2815,7 +2945,7 @@ function expandComponents(
2815
2945
  const innerHTML = preRenderComponentHtml(
2816
2946
  def,
2817
2947
  props,
2818
- shadow ? null : createSlotFill(children, {}, renderSlotted, slotId),
2948
+ shadow ? null : createSlotFill(children, childScope(), renderSlotted, slotId),
2819
2949
  context,
2820
2950
  );
2821
2951
  if (slotId !== null) {
@@ -2830,7 +2960,7 @@ function expandComponents(
2830
2960
  */
2831
2961
  node.innerHTML = shadow
2832
2962
  ? `<template shadowrootmode="${shadow}">` +
2833
- `<link rel="stylesheet" href="/components/${tagName}.css">` +
2963
+ `<link rel="stylesheet" href="${componentStylesheetHref(tagName)}">` +
2834
2964
  `${innerHTML}</template>${slotContent ?? ""}`
2835
2965
  : innerHTML;
2836
2966
  delete node.children;
@@ -2846,7 +2976,8 @@ function expandComponents(
2846
2976
  * instance that took the definition's defaults with no host style at all — no size, no mask —
2847
2977
  * while the same instance one level down had them.
2848
2978
  */
2849
- const resolvedStyle = resolveHostStyle(def.style, buildInstanceScope(def, props));
2979
+ const instanceScope = buildInstanceScope(def, props);
2980
+ const resolvedStyle = resolveHostStyle(def.style, instanceScope);
2850
2981
  if (Object.keys(resolvedStyle).length > 0) {
2851
2982
  /* SAFETY: every value in `resolvedStyle` replaces a template-string declaration of
2852
2983
  `def.style`, and the page style pass interpolates declaration values into CSS text, so the
@@ -2854,6 +2985,15 @@ function expandComponents(
2854
2985
  node.style = { ...node.style, ...resolvedStyle } as JxStyle;
2855
2986
  }
2856
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
+
2857
2997
  /*
2858
2998
  * A non-static instance discards its prerendered markup on upgrade and re-renders, so the
2859
2999
  * props have to survive as data or the element comes back with its state defaults — correct
@@ -2891,6 +3031,9 @@ function expandComponents(
2891
3031
  * @param {Set<string>} [staticTags] - Tags where ALL instances are fully static (skip JS)
2892
3032
  * @param {string} [islandSource] - Concatenated island modules emitted for this page
2893
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
2894
3037
  * @returns {string}
2895
3038
  */
2896
3039
  function injectComponentScripts(
@@ -2900,6 +3043,7 @@ function injectComponentScripts(
2900
3043
  staticTags = new Set<string>(),
2901
3044
  islandSource = "",
2902
3045
  runtimeImports: Record<string, string> = {},
3046
+ scriptOrder: readonly string[] = allComponentTags,
2903
3047
  ) {
2904
3048
  // A component reaches a page two ways: as a literal tag in the static HTML, or referenced only
2905
3049
  // From inside an island's client template — in which case the tag exists solely in the island's
@@ -2937,14 +3081,17 @@ function injectComponentScripts(
2937
3081
  componentCss === "" ? "" : `<style>\n${escapeStyleText(componentCss)}\n </style>`;
2938
3082
  const intoHead = (fragments: string[]) => {
2939
3083
  const block = fragments.filter(Boolean).join("\n ");
2940
- return block === "" ? html : html.replace("</head>", ` ${block}\n</head>`);
3084
+ return block === "" ? html : html.replace("</head>", literalReplacement(` ${block}\n</head>`));
2941
3085
  };
2942
3086
 
2943
3087
  // Only inject JS for components that have non-static instances. An island-rendered instance is
2944
3088
  // Never prerendered, so it needs its module even when the component itself is fully static —
2945
3089
  // That module is what fills the element in client-side. This holds when the tag ALSO appears in
2946
3090
  // The static HTML: those instances are prerendered, but the ones the island creates are not.
2947
- 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
+ );
2948
3095
  if (jsTags.length === 0) {
2949
3096
  return intoHead([styleBlock]);
2950
3097
  }
@@ -2987,7 +3134,7 @@ function injectComponentScripts(
2987
3134
  .map((tag: string) => `<script type="module" src="/components/${tag}.js"></script>`)
2988
3135
  .join("\n ");
2989
3136
 
2990
- return result.replace("</body>", ` ${moduleScripts}\n</body>`);
3137
+ return result.replace("</body>", literalReplacement(` ${moduleScripts}\n</body>`));
2991
3138
  }
2992
3139
 
2993
3140
  /**
@@ -3016,7 +3163,10 @@ function injectNpmElementScripts(html: string, bundleUrl: string) {
3016
3163
  * documented breakage, not merely 462kb. Bundling the SET as one entry gives one copy, no
3017
3164
  * external, and 190kb for the seven-component demo that motivated this.
3018
3165
  */
3019
- 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
+ );
3020
3170
  }
3021
3171
 
3022
3172
  /**
@@ -3050,19 +3200,24 @@ function injectHead(
3050
3200
  }
3051
3201
  let result = html;
3052
3202
  if (headPattern.test(result)) {
3053
- 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
+ );
3054
3209
  }
3055
3210
 
3056
3211
  // Set lang and dir on <html>. `dir` matters for the same reason `lang` does: without it, a
3057
3212
  // Right-to-left page renders left-to-right, and the default is not "unset" but "ltr".
3058
3213
  result = result.replace(/<html\s[^>]*>/i, (match: string) => {
3059
3214
  let tag = /lang=/.test(match)
3060
- ? match.replace(/lang="[^"]*"/, `lang="${root.lang}"`)
3215
+ ? match.replace(/lang="[^"]*"/, literalReplacement(`lang="${root.lang}"`))
3061
3216
  : match.replace("<html", `<html lang="${root.lang}"`);
3062
3217
  if (root.dir !== undefined) {
3063
3218
  tag = /\sdir=/.test(tag)
3064
3219
  ? tag.replace(/\sdir="[^"]*"/, ` dir="${root.dir}"`)
3065
- : tag.replace("<html", `<html dir="${root.dir}"`);
3220
+ : tag.replace("<html", literalReplacement(`<html dir="${root.dir}"`));
3066
3221
  }
3067
3222
  return tag;
3068
3223
  });