@jxsuite/compiler 11.1.2 → 11.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/shared.ts CHANGED
@@ -27,6 +27,8 @@ import {
27
27
  commentedRuleText,
28
28
  declaredDefaults,
29
29
  enumeratedAttrNames,
30
+ COOKIE_HOST_PREFIX,
31
+ COOKIE_SECURE_PREFIX,
30
32
  camelToKebab,
31
33
  isSingleExpression,
32
34
  mappedListItems,
@@ -35,14 +37,22 @@ import type { CssBuildOptions } from "@jxsuite/runtime/css";
35
37
  import { isContentProperty, reflectedAttribute } from "@jxsuite/runtime/dom-properties";
36
38
  import type { Reflection } from "@jxsuite/runtime/dom-properties";
37
39
  import {
40
+ CALL_DEPTH_EXCEEDED,
41
+ MAX_CALL_DEPTH,
42
+ bindFormulaArgs,
38
43
  compileOperandSource,
39
44
  evaluateExpression,
45
+ findCallCycles,
46
+ formulaCallable,
40
47
  formulaScopeReads,
41
48
  inheritableFormulas,
49
+ isCallableEntry,
42
50
  isMutating,
43
51
  isPureNamedFormula,
44
52
  } from "@jxsuite/runtime/expression";
45
53
  import { runStatements } from "@jxsuite/runtime/statements";
54
+ import { findExpressionDefects } from "@jxsuite/schema/expressions";
55
+ import type { ExpressionSource } from "@jxsuite/schema/expressions";
46
56
  import { BUILT_IN_PROTOTYPES } from "@jxsuite/schema/defs";
47
57
  import { buildSiteStyleCSS } from "@jxsuite/site/site-style";
48
58
  import {
@@ -59,8 +69,8 @@ import {
59
69
  isNonNullObject,
60
70
  isNumber,
61
71
  isPrototypeDef,
72
+ isPureTypeDef,
62
73
  isRef,
63
- isSchemaOnlyDef,
64
74
  isServerFnDef,
65
75
  isString,
66
76
  isTagExpression,
@@ -129,8 +139,13 @@ export function emitFormulaFn(
129
139
  def: { parameters?: readonly FormulaParameter[] | undefined },
130
140
  compiledBody: string,
131
141
  ): string {
142
+ return `(..._a) => ${FORMULA_GUARD}(() => { const _args = ${formulaArgsSource(def.parameters)}; return ${compiledBody}; })`;
143
+ }
144
+
145
+ /** The `{ "name": _a[i] … }` literal a positional callable binds its `$args/` names from. */
146
+ function formulaArgsSource(parameters: readonly FormulaParameter[] | undefined): string {
132
147
  const entries: string[] = [];
133
- for (const [i, p] of (def.parameters ?? []).entries()) {
148
+ for (const [i, p] of (parameters ?? []).entries()) {
134
149
  const name = formulaParameterName(p);
135
150
  if (!name) {
136
151
  continue;
@@ -140,7 +155,91 @@ export function emitFormulaFn(
140
155
  : `_a[${i}]`;
141
156
  entries.push(`${JSON.stringify(name)}: ${arg}`);
142
157
  }
143
- return `(..._a) => { const _args = { ${entries.join(", ")} }; return ${compiledBody}; }`;
158
+ return `{ ${entries.join(", ")} }`;
159
+ }
160
+
161
+ /** The inlined call-depth guard's function name in a generated module. */
162
+ export const FORMULA_GUARD = "__jxFormula";
163
+
164
+ /**
165
+ * The call-depth bound a generated module inlines (spec.md §19.4c): a copy of the interpreter's
166
+ * `withCallDepth`, with its limit and message serialized from the runtime's exports rather than
167
+ * retyped. A module that declares a callable entry carries it once, beside `attrHelperSource()`.
168
+ *
169
+ * @returns {string} The guard's source, ready to push into a module's line list.
170
+ */
171
+ export function formulaGuardSource(): string {
172
+ return (
173
+ `let __jxFormulaDepth = 0;\n` +
174
+ `function ${FORMULA_GUARD}(run) {\n` +
175
+ ` if (__jxFormulaDepth >= ${MAX_CALL_DEPTH}) throw new Error(${JSON.stringify(CALL_DEPTH_EXCEEDED)});\n` +
176
+ ` __jxFormulaDepth++;\n` +
177
+ ` try { return run(); } finally { __jxFormulaDepth--; }\n` +
178
+ `}`
179
+ );
180
+ }
181
+
182
+ /**
183
+ * The message for one call cycle, from its path (`["a", "b", "a"]`).
184
+ *
185
+ * @param cycle The path {@link findCallCycles} returned
186
+ * @returns {string}
187
+ */
188
+ export function callCycleMessage(cycle: string[]): string {
189
+ return `$expression: call cycle ${cycle.join(" → ")}: a named formula may not reach itself (spec.md §19.4c)`;
190
+ }
191
+
192
+ /**
193
+ * Refuse a scope whose callable entries reach themselves (spec.md §19.4c).
194
+ *
195
+ * @param defs The scope's state entries
196
+ * @throws {Error} One message per cycle, joined by newlines
197
+ */
198
+ export function assertNoCallCycles(defs: Record<string, JxStateDefinition>): void {
199
+ const cycles = findCallCycles(defs);
200
+ if (cycles.length > 0) {
201
+ throw new Error(cycles.map((c) => callCycleMessage(c)).join("\n"));
202
+ }
203
+ }
204
+
205
+ /**
206
+ * Refuse a document that breaks a compile-time expression rule: an unknown operator, a mutating
207
+ * node outside a handler boundary, or an `event#/` pointer outside handler position (spec.md §19.3
208
+ * to §19.5). `jx validate` reports the same findings as issues.
209
+ *
210
+ * @param doc The document, or `project.json`
211
+ * @throws {Error} One line per defect, each naming its JSON Pointer
212
+ */
213
+ export function assertExpressionRules(doc: ExpressionSource): void {
214
+ const defects = findExpressionDefects(doc);
215
+ if (defects.length > 0) {
216
+ throw new Error(
217
+ `expression rules (spec.md §19):\n${defects.map((d) => ` ${d.pointer}: ${d.message}`).join("\n")}`,
218
+ );
219
+ }
220
+ }
221
+
222
+ /**
223
+ * Whether a scope declares a callable entry, so its module needs {@link formulaGuardSource}.
224
+ *
225
+ * @param defs The scope's state entries
226
+ * @returns {boolean}
227
+ */
228
+ export function hasCallableEntries(defs: Record<string, JxStateDefinition>): boolean {
229
+ return Object.values(defs).some((d) => isCallableEntry(d));
230
+ }
231
+
232
+ /**
233
+ * The positional callable a structured body with `parameters` lowers to (spec.md §20.3): arguments
234
+ * bind to `$args/` names, and the body runs without an event. The callable is `async`: a `call` of
235
+ * it always suspends its caller (spec.md §20.2).
236
+ */
237
+ export function emitStatementsFn(
238
+ def: { parameters?: readonly FormulaParameter[] | undefined },
239
+ compiledStatements: string,
240
+ eventParam = "e",
241
+ ): string {
242
+ return `async (..._a) => ${FORMULA_GUARD}(async () => {\nconst _args = ${formulaArgsSource(def.parameters)};\nconst ${eventParam} = null;\n${compiledStatements}\n})`;
144
243
  }
145
244
 
146
245
  /**
@@ -226,6 +325,13 @@ type SrcExportOwner =
226
325
  * A template `url` is read inside the effect, so the fetch re-runs whenever the interpolated state
227
326
  * changes; an URL that still interpolates to `undefined` is skipped rather than fetched.
228
327
  *
328
+ * `debounce` (a finite number above 0) delays every fetch by that many milliseconds, the first
329
+ * included. Each run passes `fetch` an `AbortController` signal, and the effect's cleanup aborts it
330
+ * and clears a pending delay, so a change cancels the fetch it replaces and `stop()` cancels one
331
+ * still in flight. An `AbortError` is never written to the entry. A caller that emits a
332
+ * non-`manual` entry must import `onEffectCleanup` from `@vue/reactivity`; every tracked read has
333
+ * to happen synchronously before the timer.
334
+ *
229
335
  * @param {string} key - State key receiving the response
230
336
  * @param {JxPrototypeDef} def - The Request definition
231
337
  * @param {{ statePrefix?: string; indent?: string; collect?: string }} [opts] - `statePrefix` is
@@ -244,6 +350,8 @@ export function emitRequestFetch(
244
350
  const { url } = def;
245
351
  const isTemplateUrl = isTemplateString(url);
246
352
  const method = def.method ?? "GET";
353
+ const debounceMs =
354
+ isNumber(def.debounce) && Number.isFinite(def.debounce) && def.debounce > 0 ? def.debounce : 0;
247
355
 
248
356
  if (def.manual) {
249
357
  return `${indent}// ${key}: manual Request — fetch triggered by user action`;
@@ -263,6 +371,8 @@ export function emitRequestFetch(
263
371
  lines.push(` const url = ${JSON.stringify(url)};`);
264
372
  }
265
373
 
374
+ lines.push(" const _ac = new AbortController();");
375
+
266
376
  const fetchOpts: string[] = [];
267
377
  if (method !== "GET") {
268
378
  fetchOpts.push(`method: ${JSON.stringify(method)}`);
@@ -276,15 +386,26 @@ export function emitRequestFetch(
276
386
  : JSON.stringify(def.body);
277
387
  fetchOpts.push(`body: ${bodyStr}`);
278
388
  }
389
+ fetchOpts.push("signal: _ac.signal");
279
390
 
280
- const optsStr = fetchOpts.length > 0 ? `, { ${fetchOpts.join(", ")} }` : "";
281
- lines.push(
282
- ` fetch(url${optsStr})`,
283
- " .then(r => r.ok ? r.json() : Promise.reject(r.statusText))",
284
- ` .then(d => { ${statePrefix}.${key} = d; })`,
285
- ` .catch(e => { ${statePrefix}.${key} = { error: String(e) }; });`,
286
- collect ? "}));" : "});",
287
- );
391
+ const chain = [
392
+ `fetch(url, { ${fetchOpts.join(", ")} })`,
393
+ " .then(r => r.ok ? r.json() : Promise.reject(r.statusText))",
394
+ ` .then(d => { ${statePrefix}.${key} = d; })`,
395
+ ` .catch(e => { if (e?.name !== "AbortError") ${statePrefix}.${key} = { error: String(e) }; });`,
396
+ ];
397
+
398
+ if (debounceMs > 0) {
399
+ lines.push(
400
+ " const _t = setTimeout(() => {",
401
+ ...chain.map((line) => ` ${line}`),
402
+ ` }, ${debounceMs});`,
403
+ " onEffectCleanup(() => { _ac.abort(); clearTimeout(_t); });",
404
+ );
405
+ } else {
406
+ lines.push(" onEffectCleanup(() => _ac.abort());", ...chain.map((line) => ` ${line}`));
407
+ }
408
+ lines.push(collect ? "}));" : "});");
288
409
 
289
410
  return lines.map((line) => `${indent}${line}`).join("\n");
290
411
  }
@@ -447,11 +568,7 @@ export function pageImportMap(sources: PageImportSources): string {
447
568
  // ─── Schema keywords & detection ─────────────────────────────────────────────
448
569
  // Centralized in @jxsuite/schema/guards; re-exported here for existing callers.
449
570
 
450
- export {
451
- SCHEMA_KEYWORDS,
452
- isSchemaOnlyDef as isSchemaOnly,
453
- isTemplateString,
454
- } from "@jxsuite/schema/guards";
571
+ export { SCHEMA_KEYWORDS, isPureTypeDef, isTemplateString } from "@jxsuite/schema/guards";
455
572
 
456
573
  /**
457
574
  * Returns true if a $src path points to a .class.json schema-defined class.
@@ -574,6 +691,54 @@ function withoutPureFormulas(def: JxElement | JxMutableNode): string {
574
691
  return JSON.stringify({ ...def, state });
575
692
  }
576
693
 
694
+ /** The internal key a spliced node carries: no string in its subtree is a template (spec.md §8.4). */
695
+ export const LITERAL_KEY = "$literal";
696
+
697
+ /**
698
+ * Whether a node is spliced content: an element `markLiteral` marked, whose text, attributes and
699
+ * styles every pass writes as they stand (spec.md §8.4).
700
+ *
701
+ * @param {unknown} node
702
+ * @returns {boolean}
703
+ */
704
+ export function isLiteralNode(node: StaticChild | JxMappedArray): boolean {
705
+ return (
706
+ isNonNullObject(node) && !Array.isArray(node) && LITERAL_KEY in node && node.$literal === true
707
+ );
708
+ }
709
+
710
+ /**
711
+ * Mark content a computed-children template splices in as literal (spec.md §8.4). Each element, at
712
+ * every depth, is copied with `$literal: true` (the entry's cached tree is not mutated), and a
713
+ * string holding `${` is split after each `$` so no part holds a template and the parts render as
714
+ * one run of text.
715
+ *
716
+ * @param {(JxElement | string)[]} nodes
717
+ * @returns {(JxElement | string)[]}
718
+ */
719
+ export function markLiteral(nodes: (JxElement | string)[]): (JxElement | string)[] {
720
+ return nodes.flatMap((node): (JxElement | string)[] => {
721
+ if (isString(node)) {
722
+ const parts: string[] = [];
723
+ let rest = node;
724
+ for (let at = rest.indexOf("${"); at >= 0; at = rest.indexOf("${")) {
725
+ parts.push(rest.slice(0, at + 1));
726
+ rest = rest.slice(at + 1);
727
+ }
728
+ parts.push(rest);
729
+ return parts;
730
+ }
731
+ if (!isNonNullObject(node) || Array.isArray(node)) {
732
+ return [node];
733
+ }
734
+ const copy: JxElement = { ...node, [LITERAL_KEY]: true };
735
+ if (Array.isArray(copy.children)) {
736
+ copy.children = markLiteral(copy.children);
737
+ }
738
+ return [copy];
739
+ });
740
+ }
741
+
577
742
  /**
578
743
  * Determine whether a node (or any of its descendants) requires client-side JavaScript.
579
744
  *
@@ -589,7 +754,8 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
589
754
  if (isString(def)) {
590
755
  return isTemplateString(def);
591
756
  }
592
- if (!isNonNullObject(def)) {
757
+ // Spliced content is data: a template in it is text, so it never needs the client (spec.md §8.4).
758
+ if (!isNonNullObject(def) || isLiteralNode(def)) {
593
759
  return false;
594
760
  }
595
761
 
@@ -624,7 +790,7 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
624
790
  if ("default" in d) {
625
791
  return true;
626
792
  }
627
- if (isSchemaOnlyDef(d)) {
793
+ if (isPureTypeDef(d)) {
628
794
  continue;
629
795
  }
630
796
  return true;
@@ -641,6 +807,12 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
641
807
  if (Array.isArray(def.children) && def.children.some((c) => isDynamic(c))) {
642
808
  return true;
643
809
  }
810
+ // The children an instance was given wait on it until the page's target compiles them.
811
+ /* SAFETY: a slotted child is a child of the instance as written: an element, a string or a
812
+ repeater, and `isDynamic` answers true for the repeater before reading it as an element. */
813
+ if (slottedChildren(def)?.some((c) => isDynamic(c as JxElement | string))) {
814
+ return true;
815
+ }
644
816
 
645
817
  const finished = isExpandedInstance(def);
646
818
  for (const [key, val] of Object.entries(def)) {
@@ -656,6 +828,14 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
656
828
  }
657
829
  }
658
830
 
831
+ if (isNonNullObject(def.$props)) {
832
+ for (const [key, val] of Object.entries(def.$props)) {
833
+ if (!key.startsWith("#") && (isRef(val) || isTemplateString(val))) {
834
+ return true;
835
+ }
836
+ }
837
+ }
838
+
659
839
  if (isNonNullObject(def.style)) {
660
840
  for (const val of Object.values(def.style)) {
661
841
  if (isTemplateString(val)) {
@@ -675,6 +855,78 @@ export function isDynamic(def: JxElement | JxMutableNode | string) {
675
855
  return false;
676
856
  }
677
857
 
858
+ /** The key an expanded page-level instance holds its slotted children under (compiler.md §8.1). */
859
+ export const SLOTTED_KEY = "$slotted";
860
+
861
+ const SLOTTED_PLACEHOLDER = /<!--jx-slotted (\d+)-->/g;
862
+
863
+ /** A child written inside a component instance: what `createSlotFill` is given. */
864
+ export type SlottedChild = StaticChild | JxMappedArray;
865
+
866
+ /**
867
+ * The children an expanded page-level instance waits to have compiled by the page's target.
868
+ *
869
+ * @param {JxElement | JxMutableNode} def
870
+ * @returns {readonly SlottedChild[] | undefined}
871
+ */
872
+ export function slottedChildren(
873
+ def: JxElement | JxMutableNode,
874
+ ): readonly SlottedChild[] | undefined {
875
+ const slotted = def[SLOTTED_KEY];
876
+ /* SAFETY: `keepSlotted` is the only writer of `$slotted`, and it writes a `SlottedChild[]`. */
877
+ return Array.isArray(slotted) ? (slotted as SlottedChild[]) : undefined;
878
+ }
879
+
880
+ /**
881
+ * Hand an instance the children it was written with, for the page's target to compile.
882
+ *
883
+ * @param {JxElement | JxMutableNode} node
884
+ * @param {SlottedChild[]} slotted
885
+ */
886
+ export function keepSlotted(node: JxElement | JxMutableNode, slotted: SlottedChild[]): void {
887
+ /* SAFETY: `$slotted` is internal: only the page's target reads it, between the expansion and the
888
+ compile, so its nodes are never serialised as document values. */
889
+ node[SLOTTED_KEY] = slotted as JxDocumentValue;
890
+ }
891
+
892
+ /**
893
+ * Keep a child written inside an instance for the page's target and return the placeholder that
894
+ * stands where its markup goes (`fillSlotted` swaps it back).
895
+ *
896
+ * @param {SlottedChild[]} slotted - The instance's list, appended to
897
+ * @param {SlottedChild} child
898
+ * @returns {string}
899
+ */
900
+ export function slotPlaceholder(slotted: SlottedChild[], child: SlottedChild): string {
901
+ slotted.push(child);
902
+ return `<!--jx-slotted ${slotted.length - 1}-->`;
903
+ }
904
+
905
+ /**
906
+ * Replace each slotted placeholder in an instance's markup with its child as the page's target
907
+ * renders it, so the child is compiled in the page's scope (spec.md §15.2).
908
+ *
909
+ * @param {string} html - The instance's `innerHTML`
910
+ * @param {readonly SlottedChild[]} slotted - The instance's `$slotted`
911
+ * @param {(child: SlottedChild) => string} render
912
+ * @returns {string}
913
+ */
914
+ export function fillSlotted(
915
+ html: string,
916
+ slotted: readonly SlottedChild[],
917
+ render: (child: SlottedChild) => string,
918
+ ): string {
919
+ return html.replaceAll(SLOTTED_PLACEHOLDER, (_match, index: string) => {
920
+ const n = Number(index);
921
+ if (n >= slotted.length) {
922
+ throw new Error(
923
+ `A slotted placeholder (${n}) names no child of its component instance: a pass rewrote the markup.`,
924
+ );
925
+ }
926
+ return render(slotted[n]!);
927
+ });
928
+ }
929
+
678
930
  /**
679
931
  * Whether a node is a component instance the site build already expanded: it carries the stamp, and
680
932
  * its `innerHTML` is the definition's prerender. That markup is finished HTML, resolved against the
@@ -706,6 +958,8 @@ export interface CompileContext {
706
958
  * @param {JxScope | null} [parentScope]
707
959
  * @param {Record<string, JxStateDefinition>} [scopeDefs]
708
960
  * @param {Record<string, string>} [media]
961
+ * @param roles The node's verdicts when the caller already classified this same node, so the
962
+ * document is not walked for usage twice.
709
963
  * @returns {CompileContext}
710
964
  */
711
965
  export function createCompileContext(
@@ -713,9 +967,10 @@ export function createCompileContext(
713
967
  parentScope: JxScope | null = null,
714
968
  scopeDefs: Record<string, JxStateDefinition> = {},
715
969
  media: Record<string, string> = {},
970
+ roles?: ReadonlyMap<string, FunctionRole>,
716
971
  ): CompileContext {
717
972
  const scope = raw?.state
718
- ? buildInitialScope(raw.state, parentScope)
973
+ ? buildInitialScope(raw.state, parentScope, { roles: roles ?? classifyFunctionEntries(raw) })
719
974
  : (parentScope ?? emptyScope());
720
975
  return { media, scope, scopeDefs };
721
976
  }
@@ -1089,6 +1344,12 @@ export interface BuildScopeOptions {
1089
1344
  * held too (compiler.md §8.1 scans "every handler body in the document").
1090
1345
  */
1091
1346
  document?: JxElement | JxMutableNode | undefined;
1347
+ /**
1348
+ * The document's verdicts from `classifyFunctionEntries`. A caller that holds the document passes
1349
+ * them so a use outside `state` (an `on*` binding, a template's `state.key(…)`) counts. Absent,
1350
+ * only a use inside `state` does (spec.md §5.3 4b).
1351
+ */
1352
+ roles?: ReadonlyMap<string, FunctionRole>;
1092
1353
  }
1093
1354
 
1094
1355
  /**
@@ -1105,6 +1366,7 @@ export function buildInitialScope(
1105
1366
  parentScope: JxScope | null = null,
1106
1367
  options: BuildScopeOptions = {},
1107
1368
  ) {
1369
+ assertNoCallCycles(defs);
1108
1370
  const scope = emptyScope(parentScope);
1109
1371
  // Keys whose real value only exists after hydration, so prerender must not interpolate them —
1110
1372
  // See `readsRuntimeOnlyState`. Seeded from the parent so nested scopes inherit the marks.
@@ -1143,7 +1405,7 @@ export function buildInitialScope(
1143
1405
  }
1144
1406
 
1145
1407
  // The same verdict every other tier reads (spec.md §5.3 4b, 4d).
1146
- const roles = classifyFunctionEntries({ state: defs });
1408
+ const roles = options.roles ?? classifyFunctionEntries({ state: defs });
1147
1409
 
1148
1410
  for (const [key, def] of Object.entries(defs)) {
1149
1411
  if (!isNonNullObject(def) || Array.isArray(def)) {
@@ -1160,7 +1422,7 @@ export function buildInitialScope(
1160
1422
  runtimeOnly.add(key);
1161
1423
  continue;
1162
1424
  }
1163
- if (!def.$prototype && !("$expression" in def) && !isSchemaOnlyDef(def)) {
1425
+ if (!def.$prototype && !("$expression" in def) && !isPureTypeDef(def)) {
1164
1426
  setOwnScopeValue(scope, key, cloneValue(def));
1165
1427
  }
1166
1428
  }
@@ -1192,19 +1454,7 @@ export function buildInitialScope(
1192
1454
  entrySources.push([key, JSON.stringify(node)]);
1193
1455
  if (isNamedFormulaDef(def)) {
1194
1456
  // Named formula: callable, positional args mapped onto its declared parameters.
1195
- const params: readonly FormulaParameter[] = def.parameters;
1196
- setOwnScopeValue(scope, key, (...argValues: JxScope[string][]) => {
1197
- const args: JxScope = {};
1198
- for (const [i, p] of params.entries()) {
1199
- const name = formulaParameterName(p);
1200
- if (!name) {
1201
- continue;
1202
- }
1203
- args[name] =
1204
- argValues[i] === undefined && hasParameterDefault(p) ? p.default : argValues[i];
1205
- }
1206
- return evaluateExpression(node, scope, null, { args });
1207
- });
1457
+ setOwnScopeValue(scope, key, formulaCallable(node, def.parameters, scope));
1208
1458
  } else if (isMutating(node.operator)) {
1209
1459
  setOwnScopeValue(scope, key, (s: JxScope, event: Event) =>
1210
1460
  evaluateExpression(node, s, event),
@@ -1221,9 +1471,18 @@ export function buildInitialScope(
1221
1471
  // Code may call it bare, so the scope it runs against falls back to this one.
1222
1472
  const { body } = def;
1223
1473
  entrySources.push([key, JSON.stringify(body)]);
1224
- setOwnScopeValue(scope, key, (s?: JxScope, event?: Event) => {
1225
- void runStatements(body, s ?? scope, event ?? null);
1226
- });
1474
+ if (Array.isArray(def.parameters) && def.parameters.length > 0) {
1475
+ // A non-empty `parameters` list makes a positional callable (spec.md §20.3). No dispatch
1476
+ // Target: the build has no DOM.
1477
+ const params: readonly FormulaParameter[] = def.parameters;
1478
+ setOwnScopeValue(scope, key, (...argValues: JxScope[string][]) =>
1479
+ runStatements(body, scope, null, { args: bindFormulaArgs(params, argValues) }),
1480
+ );
1481
+ } else {
1482
+ setOwnScopeValue(scope, key, (s?: JxScope, event?: Event) =>
1483
+ runStatements(body, s ?? scope, event ?? null),
1484
+ );
1485
+ }
1227
1486
  } else if (isString(def.body)) {
1228
1487
  const { body } = def;
1229
1488
  // One parameter list in every tier (spec.md §5.3 4d): `state` first, then the other declared
@@ -1397,31 +1656,70 @@ function readsRuntimeOnlyState(str: string, scope: JxScope | null) {
1397
1656
  if (!scope) {
1398
1657
  return false;
1399
1658
  }
1400
- const runtimeOnly = runtimeOnlyKeysOf(scope);
1401
1659
  for (const match of str.matchAll(/\bstate\.([A-Za-z_$][\w$]*)\s*(\()?/g)) {
1402
1660
  if (match[2]) {
1403
1661
  continue;
1404
1662
  }
1405
1663
  // SAFETY: capture group 1 is outside any optional part of the pattern, so a match has it.
1406
1664
  const key = match[1] as string;
1407
- if (runtimeOnly?.has(key)) {
1408
- return true;
1409
- }
1410
- // Reading the key can run a computed's getter, which is free to throw on partial build-time
1411
- // Data. A throw says nothing about whether the entry is runtime-only, so it is not a mark.
1412
- let value: JxScope[string];
1413
- try {
1414
- value = scope[key];
1415
- } catch {
1416
- continue;
1417
- }
1418
- if (isFunction(value)) {
1665
+ if (isRuntimeOnlyKey(scope, key)) {
1419
1666
  return true;
1420
1667
  }
1421
1668
  }
1422
1669
  return false;
1423
1670
  }
1424
1671
 
1672
+ /**
1673
+ * Whether one state key holds no build-time value: it carries a runtime-only mark, or reading it
1674
+ * yields a function (a placeholder for a bodyless `$src`, or a handler).
1675
+ *
1676
+ * @param {JxScope} scope
1677
+ * @param {string} key
1678
+ * @returns {boolean}
1679
+ */
1680
+ function isRuntimeOnlyKey(scope: JxScope, key: string): boolean {
1681
+ if (runtimeOnlyKeysOf(scope)?.has(key)) {
1682
+ return true;
1683
+ }
1684
+ // Reading the key can run a computed's getter, which is free to throw on partial build-time
1685
+ // Data. A throw says nothing about whether the entry is runtime-only, so it is not a mark.
1686
+ let value: JxScope[string];
1687
+ try {
1688
+ value = scope[key];
1689
+ } catch {
1690
+ return false;
1691
+ }
1692
+ return isFunction(value);
1693
+ }
1694
+
1695
+ /**
1696
+ * Whether a `$ref` reads state the build cannot settle (compiler.md §8.1): `window#/` and
1697
+ * `document#/` have no build-time value, a `$map/` pointer is a row value, and a state pointer
1698
+ * (`#/state/`, `parent#/` or a bare path) is judged by its head entry.
1699
+ *
1700
+ * @param {string} ref
1701
+ * @param {JxScope | null} scope
1702
+ * @returns {boolean}
1703
+ */
1704
+ export function refReadsRuntimeOnlyState(ref: string, scope: JxScope | null): boolean {
1705
+ if (ref.startsWith("window#/") || ref.startsWith("document#/")) {
1706
+ return true;
1707
+ }
1708
+ if (ref.startsWith("$map/") || !scope) {
1709
+ return false;
1710
+ }
1711
+ let path = ref;
1712
+ if (ref.startsWith("#/state/")) {
1713
+ path = ref.slice("#/state/".length);
1714
+ } else if (ref.startsWith("parent#/")) {
1715
+ path = ref.slice("parent#/".length);
1716
+ } else if (ref.includes("#/")) {
1717
+ return false;
1718
+ }
1719
+ const [head] = refSegments(path);
1720
+ return head !== undefined && head !== "" && isRuntimeOnlyKey(scope, head);
1721
+ }
1722
+
1425
1723
  /**
1426
1724
  * Whether an entry's source reads a state key already marked runtime-only: a `#/state/<key>`
1427
1725
  * pointer in a structured body or an `$expression`, or a `state.<key>` member in a string body.
@@ -1536,6 +1834,7 @@ export function cloneValue<T>(value: T): T {
1536
1834
  export function inlineStyleDeclarations(
1537
1835
  style: JxStyle | null | undefined,
1538
1836
  scope: JxScope | null,
1837
+ literal = false,
1539
1838
  ): string {
1540
1839
  if (!style || !scope) {
1541
1840
  return "";
@@ -1551,7 +1850,7 @@ export function inlineStyleDeclarations(
1551
1850
  isTemplateString(v),
1552
1851
  )
1553
1852
  .map(([k, v]) => {
1554
- const value = resolveStaticValue(v, scope);
1853
+ const value = literal ? v : resolveStaticValue(v, scope);
1555
1854
  return value == null ? null : `${camelToKebab(k)}: ${value}`;
1556
1855
  })
1557
1856
  .filter(Boolean)
@@ -1680,7 +1979,13 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1680
1979
  // Allocated by the first live row: most elements have none.
1681
1980
  let live: Set<string> | undefined;
1682
1981
 
1683
- const id = resolveStaticValue(def.id, scope);
1982
+ /* Spliced content is data, never a template (spec.md §8.4): its values are written as they stand. */
1983
+ const literal = isLiteralNode(def);
1984
+ /* SAFETY: a template resolves to a scope value, the same as `resolvePropertyValue` reads it. */
1985
+ const resolve = (value: JxDocumentValue | undefined): JxDocumentValue | JxScope[string] =>
1986
+ literal ? value : (resolveStaticValue(value, scope) as JxScope[string]);
1987
+
1988
+ const id = resolve(def.id);
1684
1989
  if (id) {
1685
1990
  written.set("id", serializeAttr("id", String(id), false));
1686
1991
  }
@@ -1688,7 +1993,7 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1688
1993
  handle (spec.md §9.2). The author's are `attributes.class` when the element writes one, which
1689
1994
  is what the runtime leaves in effect, since it applies attributes after properties. */
1690
1995
  const mergesClass = writesMergedClass(def);
1691
- const authorClass = mergesClass ? resolveStaticValue(authorClassValue(def), scope) : null;
1996
+ const authorClass = mergesClass ? resolve(authorClassValue(def)) : null;
1692
1997
  const className = [
1693
1998
  isString(authorClass) || isNumber(authorClass) ? String(authorClass) : "",
1694
1999
  styleHandleOf(def) ?? "",
@@ -1708,7 +2013,9 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1708
2013
  if (!reflection) {
1709
2014
  return;
1710
2015
  }
1711
- const resolved = resolvePropertyValue(value, scope);
2016
+ /* SAFETY: a literal property is a document value the build reads as the scope value it
2017
+ would have resolved to; the reflection below ignores any that is not text. */
2018
+ const resolved = literal ? (value as JxScope[string]) : resolvePropertyValue(value, scope);
1712
2019
  /* A live row decides its attribute even when it writes none: `checked: false` leaves the box
1713
2020
  unchecked whatever `attributes.checked` says afterwards. A value the build cannot read
1714
2021
  decides nothing. */
@@ -1751,7 +2058,7 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1751
2058
  if (mergesClass && k === "class") {
1752
2059
  continue;
1753
2060
  }
1754
- const value = resolveStaticValue(v, scope);
2061
+ const value = resolve(v);
1755
2062
  /*
1756
2063
  * A boolean is the attribute's PRESENCE or its text, depending on which family HTML puts the
1757
2064
  * attribute in — `booleanAttrValue` owns that judgement, and the runtime asks it the same
@@ -1802,7 +2109,9 @@ export function buildAttrs(def: JxElement | JxMutableNode, scope: JxScope | null
1802
2109
  // The host declarations go last: in one `style` attribute the later declaration of a property
1803
2110
  // Wins, and the page walk gives the definition's resolved host style the same precedence over an
1804
2111
  // Instance's own (`{ ...node.style, ...resolvedStyle }`), so the two paths agree.
1805
- const inline = [inlineStyleDeclarations(def.style, scope), hostStyle].filter(Boolean).join("; ");
2112
+ const inline = [inlineStyleDeclarations(def.style, scope, literal), hostStyle]
2113
+ .filter(Boolean)
2114
+ .join("; ");
1806
2115
  if (inline) {
1807
2116
  /*
1808
2117
  * Escaped like every other attribute. Both halves carry values a template string resolved
@@ -2077,6 +2386,117 @@ export function attrHelperSource(): string {
2077
2386
  );
2078
2387
  }
2079
2388
 
2389
+ /**
2390
+ * The source of `_jxSwitch`, the loader a compiled `$switch` calls for an external case (spec.md
2391
+ * §14.1, compiler.md §11). It returns the case's template for the key and, the first time a key
2392
+ * with a module is active, starts `import()`ing that module, which defines the case's element.
2393
+ * Inlined for the reason {@link attrHelperSource} gives, and only into a module that holds a
2394
+ * lowered case, so a module without one is byte-identical to what it was.
2395
+ *
2396
+ * @returns {string} A `const` and one `function` declaration, ready to push into a module's lines.
2397
+ */
2398
+ export function caseLoaderSource(): string {
2399
+ return (
2400
+ "const _jxCaseLoads = new Set();\n" +
2401
+ "function _jxSwitch(templates, modules, key) {\n" +
2402
+ " const spec = Object.hasOwn(modules, key) ? modules[key] : undefined;\n" +
2403
+ " if (spec !== undefined && !_jxCaseLoads.has(spec)) {\n" +
2404
+ " _jxCaseLoads.add(spec);\n" +
2405
+ " import(spec).catch((e) => {\n" +
2406
+ " _jxCaseLoads.delete(spec);\n" +
2407
+ ' console.error("Jx $switch: failed to load external case", spec, e);\n' +
2408
+ " });\n" +
2409
+ " }\n" +
2410
+ " return templates[key];\n" +
2411
+ "}"
2412
+ );
2413
+ }
2414
+
2415
+ /** The cookie-reading helper the generated modules call; prefixed like {@link ATTR_HELPER}. */
2416
+ export const COOKIE_READ_HELPER = "__jxCookieRead";
2417
+
2418
+ /** The cookie-serializing helper the generated modules call. */
2419
+ export const COOKIE_WRITE_HELPER = "__jxCookieText";
2420
+
2421
+ /**
2422
+ * The source of the two cookie helpers, to be emitted into a module that binds a `Cookie` entry
2423
+ * (spec.md §11.2a).
2424
+ *
2425
+ * Inlined for the reason {@link attrHelperSource} gives: a built module loads without
2426
+ * `@jxsuite/runtime`. The rule is `readCookieValue` and `serializeCookie` from the runtime, with
2427
+ * the two prefixes serialized from the runtime's exports. `cookie-helper.test.ts` compares the
2428
+ * copy's output with the runtime's over every prefix, attribute and value combination, so a changed
2429
+ * branch goes red as well as a changed prefix.
2430
+ *
2431
+ * @returns {string} Two `function` declarations.
2432
+ */
2433
+ export function cookieHelperSource(): string {
2434
+ const host = JSON.stringify(COOKIE_HOST_PREFIX);
2435
+ const secure = JSON.stringify(COOKIE_SECURE_PREFIX);
2436
+ return (
2437
+ `function ${COOKIE_READ_HELPER}(h, n) {\n` +
2438
+ ` for (const p of h.split(";")) {\n` +
2439
+ ` const i = p.indexOf("=");\n` +
2440
+ ` if (i === -1 || p.slice(0, i).trim() !== n) continue;\n` +
2441
+ ` const r = p.slice(i + 1);\n` +
2442
+ ` try { return JSON.parse(decodeURIComponent(r)); } catch { return r; }\n` +
2443
+ ` }\n` +
2444
+ ` return null;\n` +
2445
+ `}\n` +
2446
+ `function ${COOKIE_WRITE_HELPER}(n, v, o) {\n` +
2447
+ ` const host = n.startsWith(${host});\n` +
2448
+ ` const parts = [n + "=" + encodeURIComponent(JSON.stringify(v))];\n` +
2449
+ ` if (o.maxAge !== undefined) parts.push("Max-Age=" + o.maxAge);\n` +
2450
+ ` const path = host ? "/" : o.path;\n` +
2451
+ ` if (path) parts.push("Path=" + path);\n` +
2452
+ ` if (o.domain && !host) parts.push("Domain=" + o.domain);\n` +
2453
+ ` if (o.secure === true || host || n.startsWith(${secure}) || o.sameSite?.toLowerCase() === "none") parts.push("Secure");\n` +
2454
+ ` if (o.sameSite) parts.push("SameSite=" + o.sameSite);\n` +
2455
+ ` return parts.join("; ");\n` +
2456
+ `}`
2457
+ );
2458
+ }
2459
+
2460
+ /**
2461
+ * Emit the binding for one `Cookie` state entry: read the cookie into state on creation, then
2462
+ * persist through an effect whose first run writes it, so a declared `default` reaches the server
2463
+ * from the first load (spec.md §11.2a). The block is self-contained, so two entries in one module
2464
+ * do not redeclare its constants. The name and key appear only as JSON string literals or through
2465
+ * `refAccessor`, never in a comment.
2466
+ *
2467
+ * @param {string} key - State key
2468
+ * @param {JxPrototypeDef} def - The Cookie definition
2469
+ * @param {{ statePrefix?: string; indent?: string; collect?: string }} [opts] - As
2470
+ * {@link emitRequestFetch}.
2471
+ * @returns {string}
2472
+ */
2473
+ export function emitCookieBinding(
2474
+ key: string,
2475
+ def: JxPrototypeDef,
2476
+ opts: { statePrefix?: string; indent?: string; collect?: string } = {},
2477
+ ) {
2478
+ const { statePrefix = "state", indent = "", collect } = opts;
2479
+ const accessor = refAccessor(statePrefix, escapeToken(key));
2480
+ const options: Record<string, JsonValue> = {};
2481
+ for (const field of ["domain", "maxAge", "path", "sameSite", "secure"] as const) {
2482
+ const declared = def[field];
2483
+ if (declared !== undefined) {
2484
+ options[field] = declared;
2485
+ }
2486
+ }
2487
+ const write = `document.cookie = ${COOKIE_WRITE_HELPER}(_n, ${accessor}, _o);`;
2488
+ const lines = [
2489
+ "// Cookie entry",
2490
+ "{",
2491
+ ` const _n = ${JSON.stringify(def.name ?? key)};`,
2492
+ ` const _o = ${JSON.stringify(options)};`,
2493
+ ` ${accessor} = ${COOKIE_READ_HELPER}(document.cookie, _n) ?? ${JSON.stringify(def.default ?? null)};`,
2494
+ collect ? ` ${collect}.push(effect(() => { ${write} }));` : ` effect(() => { ${write} });`,
2495
+ "}",
2496
+ ];
2497
+ return lines.map((line) => `${indent}${line}`).join("\n");
2498
+ }
2499
+
2080
2500
  /** What the mapped arrays of a document need from the module compiled for it. */
2081
2501
  export interface MappedArrayFeatures {
2082
2502
  /** Some list declares a `$ref` `filter` or `sort`, so the module carries `__jxListItems`. */
@@ -2551,6 +2971,32 @@ export function isClientExternalClass(def: unknown): def is JxPrototypeDef {
2551
2971
  return isExternalClassDef(def) && def.timing === "client";
2552
2972
  }
2553
2973
 
2974
+ /**
2975
+ * Refuses a built-in prototype at `timing: "compiler"` reaching a compile target. A site build
2976
+ * resolves each one it has a value for (`prototype-resolver.ts`), and fails on the rest, so a
2977
+ * target that sees one was compiled outside a site build, where nothing would bake it (spec.md
2978
+ * §11.3).
2979
+ *
2980
+ * @param key - The state key of the entry
2981
+ * @param def - The state entry
2982
+ * @throws {Error} For a `Request`, or any other built-in, at compiler timing
2983
+ */
2984
+ export function refuseBuiltInCompilerTiming(key: string, def: JxStateDefinition): void {
2985
+ if (
2986
+ !isPrototypeDef(def) ||
2987
+ def.timing !== "compiler" ||
2988
+ !BUILT_IN_PROTOTYPE_NAMES.has(def.$prototype)
2989
+ ) {
2990
+ return;
2991
+ }
2992
+ throw new Error(
2993
+ def.$prototype === "Request"
2994
+ ? `state entry "${key}": a timing "compiler" Request resolves only in a site build`
2995
+ : `state entry "${key}" ($prototype "${def.$prototype}"): has no build-time value; ` +
2996
+ `remove "timing" or use "client"`,
2997
+ );
2998
+ }
2999
+
2554
3000
  /** The name of the helper a module holding a `timing: "client"` external class declares once. */
2555
3001
  export const EXTERNAL_CLASS_HELPER = "__jxInstantiate";
2556
3002
 
@@ -3532,7 +3978,7 @@ export function buildInstanceScope(
3532
3978
  props: Record<string, JsonValue> | null,
3533
3979
  ): JxScope {
3534
3980
  if (!props) {
3535
- return buildInitialScope(doc.state ?? {}, null);
3981
+ return buildInitialScope(doc.state ?? {}, null, { roles: classifyFunctionEntries(doc) });
3536
3982
  }
3537
3983
  const stateDefs = { ...doc.state };
3538
3984
  for (const [key, value] of Object.entries(props)) {
@@ -3542,7 +3988,9 @@ export function buildInstanceScope(
3542
3988
  ? { ...existing, default: value }
3543
3989
  : value;
3544
3990
  }
3545
- return buildInitialScope(stateDefs, null);
3991
+ return buildInitialScope(stateDefs, null, {
3992
+ roles: classifyFunctionEntries({ ...doc, state: stateDefs }),
3993
+ });
3546
3994
  }
3547
3995
 
3548
3996
  /**
@@ -3685,16 +4133,24 @@ function renderInner(
3685
4133
  context: ComponentPrerenderContext | null,
3686
4134
  preformatted = false,
3687
4135
  ): string {
4136
+ // Spliced content is data (spec.md §8.4): its text is escaped and written, never evaluated.
4137
+ const literal = isLiteralNode(node);
3688
4138
  if (node.textContent !== undefined) {
3689
- const val = resolveStaticValue(node.textContent, scope);
4139
+ const val = literal ? node.textContent : resolveStaticValue(node.textContent, scope);
3690
4140
  return val != null ? escapeHtml(String(val)) : "";
3691
4141
  }
3692
4142
  if (node.innerHTML) {
3693
- const val = resolveStaticValue(node.innerHTML, scope);
3694
- return val != null ? String(val) : node.innerHTML;
4143
+ const val = literal ? node.innerHTML : resolveStaticValue(node.innerHTML, scope);
4144
+ const html = val != null ? String(val) : node.innerHTML;
4145
+ const slotted = slottedChildren(node);
4146
+ return slotted
4147
+ ? fillSlotted(html, slotted, (c) => renderStaticNode(c, scope, null, context, preformatted))
4148
+ : html;
3695
4149
  }
3696
4150
  // A content property is the element's text (spec.md §8.1).
3697
- const content = contentPropertyText(node, resolveStaticTagName(node.tagName, scope), scope);
4151
+ const content = literal
4152
+ ? undefined
4153
+ : contentPropertyText(node, resolveStaticTagName(node.tagName, scope), scope);
3698
4154
  if (content !== undefined) {
3699
4155
  return content;
3700
4156
  }
@@ -3868,8 +4324,9 @@ export function renderStaticNode(
3868
4324
  }
3869
4325
 
3870
4326
  // $switch/cases — resolve the key statically and render the matched case inside a container
3871
- // Element (mirrors the runtime's renderSwitch DOM shape). External $ref cases can't be fetched
3872
- // At compile time, so they render the empty container.
4327
+ // Element (mirrors the runtime's renderSwitch DOM shape). A site build lowers an external $ref
4328
+ // Case to a registered tag, which is expanded like any component; an unlowered one only exists
4329
+ // Outside a site build, and renders the empty container.
3873
4330
  if (node.$switch) {
3874
4331
  const switchTag = node.tagName ?? "div";
3875
4332
  const attrs = buildAttrs(node, scope);