@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.
@@ -7,8 +7,10 @@
7
7
 
8
8
  import { joinChildren, padChildren } from "../child-separator.ts";
9
9
  import { erasedDocument } from "../erased.ts";
10
+ import { wrapCaseDocument } from "../switch-cases.ts";
10
11
  import { qualifyScripts } from "@jxsuite/schema/document-scripts";
11
12
  import {
13
+ LIFECYCLE_KEYS,
12
14
  classifyFunctionEntries,
13
15
  declaresParameters,
14
16
  handlerParamNames,
@@ -18,7 +20,12 @@ import {
18
20
  ATTR_HELPER,
19
21
  DEFAULT_LIT_HTML_SRC,
20
22
  DEFAULT_REACTIVITY_SRC,
23
+ assertExpressionRules,
24
+ assertNoCallCycles,
21
25
  attrHelperSource,
26
+ caseLoaderSource,
27
+ formulaGuardSource,
28
+ hasCallableEntries,
22
29
  booleanAttrValue,
23
30
  definitionHasSlot,
24
31
  KEYED_LIST_HELPER,
@@ -43,6 +50,7 @@ import {
43
50
  emitExternalClassResolution,
44
51
  externalClassHelperSource,
45
52
  isClientExternalClass,
53
+ refuseBuiltInCompilerTiming,
46
54
  observedAttributeNames,
47
55
  observedDefaultsSource,
48
56
  SLOT_CAPTURE_HELPER,
@@ -59,6 +67,7 @@ import {
59
67
  compileOperandSource,
60
68
  compileStatements,
61
69
  emitFormulaFn,
70
+ emitStatementsFn,
62
71
  collectFunctionImports,
63
72
  emitSrcImports,
64
73
  refuseBodyWithSrc,
@@ -67,7 +76,7 @@ import {
67
76
  escapeHtml,
68
77
  inheritProjectFormulas,
69
78
  isMutating,
70
- isSchemaOnly,
79
+ isPureTypeDef,
71
80
  rewriteState,
72
81
  serverCallHelperSource,
73
82
  tagNameToClassName,
@@ -207,6 +216,23 @@ export interface CompileElementOptions {
207
216
  * Read for every `$elements` dependency too, and never for a light-DOM component.
208
217
  */
209
218
  stylesheetHref?: (tagName: string) => string | null;
219
+ /**
220
+ * Compile the root document as the host of this external `$switch` case (spec.md §14.1): the
221
+ * document is wrapped by `wrapCaseDocument` under this tag, and its `onMount` is called with the
222
+ * scope alone, as the interpreter calls a case's.
223
+ */
224
+ caseTag?: string;
225
+ /**
226
+ * Applied to every document read from disk, the root and each `$elements` dependency, before
227
+ * anything is compiled from it. A site build lowers each document's external `$switch` cases here
228
+ * (`lowerExternalCases`). Must not mutate its input.
229
+ */
230
+ transformDocument?: (doc: JxDocument, filePath: string) => JxDocument;
231
+ /**
232
+ * Generated case tag to the module specifier (relative to the emitted module) that defines it. A
233
+ * `$switch` case lowered to one of these tags loads its module the first time its key is active.
234
+ */
235
+ caseModules?: ReadonlyMap<string, string>;
210
236
  }
211
237
 
212
238
  /**
@@ -233,12 +259,16 @@ export async function compileElement(
233
259
  /** @type {{ path: string; content: string; tagName: string }[]} */
234
260
  const files: { path: string; content: string; tagName: string }[] = [];
235
261
  const visited = new Set<string>();
262
+ // The root call is the first one, and the only one `caseTag` applies to.
263
+ let rootPending = true;
236
264
 
237
265
  /**
238
266
  * @param {string | JxDocument} srcPath
239
267
  * @param {string | null} parentDir
240
268
  */
241
269
  async function processElement(srcPath: string | JxDocument, parentDir: string | null) {
270
+ const isRoot = rootPending;
271
+ rootPending = false;
242
272
  let doc: JxDocument;
243
273
  let filePath: string | null;
244
274
  if (isString(srcPath)) {
@@ -267,6 +297,9 @@ export async function compileElement(
267
297
  const { relative } = await import("node:path");
268
298
  doc = qualifyScripts(doc, relative(opts.projectRoot, filePath));
269
299
  }
300
+ if (opts.transformDocument) {
301
+ doc = opts.transformDocument(doc, filePath);
302
+ }
270
303
  } else {
271
304
  doc = erasedDocument(srcPath, srcPath.tagName ?? "a component");
272
305
  filePath = null;
@@ -278,6 +311,11 @@ export async function compileElement(
278
311
  }
279
312
  }
280
313
 
314
+ const caseHost = isRoot && opts.caseTag !== undefined;
315
+ if (caseHost) {
316
+ doc = wrapCaseDocument(doc, opts.caseTag!);
317
+ }
318
+
281
319
  await opts.prepareDocument?.(doc, filePath);
282
320
 
283
321
  const declaredState = doc.state ?? {};
@@ -287,6 +325,7 @@ export async function compileElement(
287
325
  if (!tagName || !tagName.includes("-")) {
288
326
  throw new Error(`compileElement: tagName "${tagName}" must contain a hyphen`);
289
327
  }
328
+ assertExpressionRules(doc);
290
329
 
291
330
  const { dirname: dn } = await import("node:path");
292
331
  const currentDir = filePath ? dn(filePath) : null;
@@ -330,6 +369,8 @@ export async function compileElement(
330
369
  ? (def: JxPrototypeDef) => resolveClass(def, currentDir, classImports)
331
370
  : undefined,
332
371
  opts.stylesheetHref?.(tagName) ?? null,
372
+ opts.caseModules,
373
+ caseHost,
333
374
  );
334
375
  const outputPath = filePath ? filePath.replace(/\.(?:json|jxn)$/i, ".js") : `${tagName}.js`;
335
376
  files.push({ content: jsContent, path: outputPath, tagName });
@@ -414,7 +455,7 @@ function extractInitialValue(def: JxStateDefinition) {
414
455
  return JSON.stringify(def.default);
415
456
  }
416
457
  // Pure schema-only type definitions — skip (no runtime value)
417
- if (isSchemaOnly(def)) {
458
+ if (isPureTypeDef(def)) {
418
459
  return; // Caller should skip this entry
419
460
  }
420
461
  // $prototype entries (LocalStorage, SessionStorage, Request, etc.)
@@ -454,7 +495,56 @@ export function emitElementModule(
454
495
  inherited: readonly string[] = [],
455
496
  resolveClass?: (def: JxPrototypeDef) => string,
456
497
  stylesheetHref: string | null = null,
457
- ) {
498
+ caseModules?: ReadonlyMap<string, string>,
499
+ caseHost = false,
500
+ ): string {
501
+ const previous = caseState;
502
+ caseState = { modules: caseModules ?? new Map(), needsLoader: false, warned: new Set() };
503
+ try {
504
+ const text = emitElementModuleText(
505
+ doc,
506
+ className,
507
+ elementImports,
508
+ rewriteSrc,
509
+ shadow,
510
+ serverBaseUrl,
511
+ inherited,
512
+ resolveClass,
513
+ stylesheetHref,
514
+ caseHost,
515
+ );
516
+ return text.replace(CASE_LOADER_MARKER, caseState.needsLoader ? `\n${caseLoaderSource()}` : "");
517
+ } finally {
518
+ caseState = previous;
519
+ }
520
+ }
521
+
522
+ /** Where a module that holds a lowered `$switch` case gets `_jxSwitch`, before any class uses it. */
523
+ const CASE_LOADER_MARKER = "\n// @jx-case-loader";
524
+
525
+ /**
526
+ * The external-case state of the module being emitted. `emitNodeInner` is reached through helpers
527
+ * that take no options and the emitter is synchronous, so it is held here, set on entry to
528
+ * {@link emitElementModule} and restored in `finally`.
529
+ */
530
+ let caseState: {
531
+ modules: ReadonlyMap<string, string>;
532
+ needsLoader: boolean;
533
+ warned: Set<string>;
534
+ } | null = null;
535
+
536
+ function emitElementModuleText(
537
+ doc: JxDocument,
538
+ className: string,
539
+ elementImports: string[],
540
+ rewriteSrc: ((specifier: string) => string) | undefined,
541
+ shadow: ShadowMode | null,
542
+ serverBaseUrl: string,
543
+ inherited: readonly string[],
544
+ resolveClass: ((def: JxPrototypeDef) => string) | undefined,
545
+ stylesheetHref: string | null,
546
+ caseHost: boolean,
547
+ ): string {
458
548
  const lines: string[] = ["// Generated by @jxsuite/compiler — do not edit manually"];
459
549
 
460
550
  if (doc.$id) {
@@ -467,6 +557,10 @@ export function emitElementModule(
467
557
 
468
558
  // Collect $src imports from state entries before emitting other imports
469
559
  const defs = doc.state ?? {};
560
+ for (const [key, def] of Object.entries(defs)) {
561
+ refuseBuiltInCompilerTiming(key, def);
562
+ }
563
+ assertNoCallCycles(defs);
470
564
  const roles = classifyFunctionEntries(doc);
471
565
  const srcImports = emitSrcImports(collectFunctionImports(defs, roles), rewriteSrc);
472
566
  // Bundleable specifiers (npm:…, ./relative) are rewritten to their /assets/ bundle URL;
@@ -482,7 +576,8 @@ export function emitElementModule(
482
576
  lines.push(...clientClasses.imports);
483
577
 
484
578
  // `$prototype: "Request"` entries each get an auto-fetch effect in connectedCallback, plus the
485
- // Machinery to stop those effects again on disconnect. Both are emitted only when one exists, so
579
+ // Machinery to stop those effects again on disconnect, and the `onEffectCleanup` import follows the
580
+ // Same rule. All are emitted only when one exists, so
486
581
  // Documents without a Request produce exactly the same module as before.
487
582
  const requestEntries = Object.entries(defs).flatMap(([key, def]): [string, JxPrototypeDef][] =>
488
583
  isPrototypeDef(def) && def.$prototype === "Request" ? [[key, def]] : [],
@@ -497,17 +592,27 @@ export function emitElementModule(
497
592
  /* What the document's lists need (compiler.md §4.7), decided before anything is emitted. A
498
593
  module with no filtered, sorted or keyed list carries none of it. */
499
594
  const lists = mappedArrayFeatures(doc);
595
+ const reactivityNames = ["reactive", "computed", "effect", "stop"];
596
+ if (lists.keyed) {
597
+ reactivityNames.push("shallowRef");
598
+ }
599
+ // `onEffectCleanup` aborts a Request fetch on a re-run and on `stop()`; only an auto-fetch needs it.
600
+ if (requestEntries.some(([, d]) => !d.manual)) {
601
+ reactivityNames.push("onEffectCleanup");
602
+ }
500
603
  lines.push(
501
- lists.keyed
502
- ? `import { reactive, computed, effect, stop, shallowRef } from '@vue/reactivity';`
503
- : `import { reactive, computed, effect, stop } from '@vue/reactivity';`,
604
+ `import { ${reactivityNames.join(", ")} } from '@vue/reactivity';`,
504
605
  /* `nothing` is what REMOVES an attribute in a lit template, and it is the only way to express a
505
606
  false presence attribute: writing `open="false"` produces an OPEN <details>. See
506
607
  `attrHelperSource`. */
507
608
  `import { render, html, nothing } from 'lit-html';`,
508
609
  ...(lists.keyed ? KEYED_LIST_IMPORTS : []),
509
610
  attrHelperSource(),
611
+ CASE_LOADER_MARKER.slice(1),
510
612
  );
613
+ if (hasCallableEntries(defs)) {
614
+ lines.push(formulaGuardSource());
615
+ }
511
616
  if (lists.arranged || lists.keyed) {
512
617
  lines.push(listHelperSource());
513
618
  }
@@ -529,7 +634,7 @@ export function emitElementModule(
529
634
  lines.push(`const __jxProps = ${JSON.stringify(propKeys)};`);
530
635
  /* The bridged keys the scope DERIVES (spec.md §16.2): each gets a getter and no setter, from
531
636
  the verdict the interpreter reads, and is never merged from a property. */
532
- const derived = derivedStateKeys(doc);
637
+ const derived = derivedStateKeys(doc, roles);
533
638
  const derivedKeys = bridgedKeys.filter((key) => derived.has(key));
534
639
  if (bridgedKeys.length > 0) {
535
640
  lines.push(`const __jxBridged = ${JSON.stringify(bridgedKeys)};`, propSupplyHelperSource());
@@ -690,18 +795,28 @@ export function emitElementModule(
690
795
  );
691
796
  } else if (hasStructuredBody(def)) {
692
797
  // Structured body (spec §20) — statements compiled against this.state; dispatch target is
693
- // The component instance itself (WHATWG dispatchEvent on the custom element).
798
+ // The component instance itself (WHATWG dispatchEvent on the custom element). A non-empty
799
+ // `parameters` list lowers to a positional callable (spec.md §20.3), else a handler.
694
800
  const compiled = compileStatements(def.body, {
695
801
  dispatchTarget: "this",
696
802
  eventParam: "e",
697
803
  indent: " ",
698
804
  statePrefix: "this.state",
699
805
  });
700
- lines.push(
701
- ` ${refAccessor("this.state", escapeToken(key))} = (s, e) => {`,
702
- compiled,
703
- " };",
704
- );
806
+ if (Array.isArray(def.parameters) && def.parameters.length > 0) {
807
+ lines.push(
808
+ ` ${refAccessor("this.state", escapeToken(key))} = ${emitStatementsFn(def, compiled)};`,
809
+ );
810
+ } else {
811
+ /* A lifecycle hook takes no event: the host the element passes second never reaches a verb. */
812
+ const lifecycle = LIFECYCLE_KEYS.has(key);
813
+ lines.push(
814
+ ` ${refAccessor("this.state", escapeToken(key))} = ${lifecycle ? "async (s)" : "async (s, e)"} => {`,
815
+ ...(lifecycle ? [" const e = null;"] : []),
816
+ compiled,
817
+ " };",
818
+ );
819
+ }
705
820
  } else {
706
821
  /* One calling convention (spec.md §4.3, §5.3 4d): every event site and lifecycle call invokes
707
822
  `s.fn(s, e)`, so a string body is built with `state` first and its other declared names after
@@ -1147,7 +1262,11 @@ export function emitElementModule(
1147
1262
  to an instance once. A parent's slot distribution moves a slotted element straight after it
1148
1263
  rendered, and a hook that ran per connection handed every slotted component its host twice. */
1149
1264
  " if (_first && typeof this.state.onMount === 'function') {",
1150
- " queueMicrotask(() => this.state.onMount.call(this, this.state, this));",
1265
+ /* A case host is not the case document's element, so its hook is called as the interpreter
1266
+ calls a case's: with the scope alone, and the scope as its receiver. */
1267
+ caseHost
1268
+ ? " queueMicrotask(() => this.state.onMount(this.state));"
1269
+ : " queueMicrotask(() => this.state.onMount.call(this, this.state, this));",
1151
1270
  " }",
1152
1271
  " }",
1153
1272
  "",
@@ -1531,6 +1650,18 @@ ${no}
1531
1650
  * @param {HoistScope | null} scope
1532
1651
  * @returns {string}
1533
1652
  */
1653
+ /** Warn, once per module, that an external case reached a target outside a site build. */
1654
+ function warnExternalCase(key: string, ref: string): void {
1655
+ const id = `${key}\u0000${ref}`;
1656
+ if (caseState && !caseState.warned.has(id)) {
1657
+ caseState.warned.add(id);
1658
+ console.warn(
1659
+ `Jx $switch: case "${key}" (${ref}) is an external document, which only a site build ` +
1660
+ `compiles; it renders an empty container.`,
1661
+ );
1662
+ }
1663
+ }
1664
+
1534
1665
  function emitNodeInner(
1535
1666
  def: JxMutableNode,
1536
1667
  indent: string,
@@ -1544,12 +1675,25 @@ function emitNodeInner(
1544
1675
  const switchRef = isRef(def.$switch) ? def.$switch.$ref : def.$switch;
1545
1676
  const switchExpr = refToExpr(switchRef);
1546
1677
  const rendered: [string, string][] = [];
1678
+ const modules: string[] = [];
1547
1679
  // A case value is document data, so a `null` or empty one can reach here and is skipped.
1548
1680
  for (const [key, caseDef] of Object.entries<LitChild>(def.cases ?? {})) {
1549
- if (!caseDef || isRef(caseDef)) {
1681
+ if (!caseDef) {
1682
+ continue;
1683
+ }
1684
+ if (isRef(caseDef)) {
1685
+ // Only a site build compiles an external case, by lowering it to a registered tag first.
1686
+ warnExternalCase(key, caseDef.$ref);
1550
1687
  continue;
1551
1688
  }
1552
1689
  rendered.push([key, emitLitNode(caseDef, `${indent} `, false, inMap, scope)]);
1690
+ const specifier =
1691
+ isNonNullObject(caseDef) && isString(caseDef.tagName)
1692
+ ? caseState?.modules.get(caseDef.tagName)
1693
+ : undefined;
1694
+ if (specifier !== undefined) {
1695
+ modules.push(`${JSON.stringify(key)}: ${JSON.stringify(specifier)}`);
1696
+ }
1553
1697
  }
1554
1698
  // Cases that emit byte-identical subtrees share one hoisted `const` rather than repeating it
1555
1699
  // Once per case — the authored document names the subtree once (#126).
@@ -1561,6 +1705,10 @@ function emitNodeInner(
1561
1705
  const body = scope && repeated.has(text) ? hoistSubtree(scope, text) : text;
1562
1706
  return ` ${JSON.stringify(key)}: html\`\n${body}\n \``;
1563
1707
  });
1708
+ if (modules.length > 0 && caseState) {
1709
+ caseState.needsLoader = true;
1710
+ return `\${_jxSwitch({\n${caseEntries.join(",\n")}\n}, {${modules.join(", ")}}, String(${switchExpr}))}`;
1711
+ }
1564
1712
  return `\${{\n${caseEntries.join(",\n")}\n}[${switchExpr}]}`;
1565
1713
  }
1566
1714
  if (def.textContent !== undefined) {
@@ -1956,7 +2104,7 @@ function handlerSource(val: JxDocumentValue | undefined, mapCtx: string): string
1956
2104
  return `(e) => { ${mapCtx}${compiled}; }`;
1957
2105
  }
1958
2106
  if (isFunctionDef(val)) {
1959
- return `(e) => { ${mapCtx}${inlineHandlerBody(val)} }`;
2107
+ return `${hasStructuredBody(val) ? "async " : ""}(e) => { ${mapCtx}${inlineHandlerBody(val)} }`;
1960
2108
  }
1961
2109
  return null;
1962
2110
  }
@@ -17,11 +17,17 @@ import {
17
17
  PREFORMATTED_TAGS,
18
18
  pureSchemeOf,
19
19
  resolveStaticTagName,
20
+ fillSlotted,
21
+ slottedChildren,
20
22
  isExpandedInstance,
23
+ isLiteralNode,
24
+ renderStaticNode,
21
25
  resolveStaticValue,
22
26
  SELF_CLOSING,
23
27
  } from "../shared.ts";
24
28
  import type { CompileContext } from "../shared.ts";
29
+ import { classifyFunctionEntries } from "@jxsuite/schema/function-role";
30
+ import type { FunctionRole } from "@jxsuite/schema/function-role";
25
31
  import { isBoolean, isNonNullObject, isNumber, isString } from "@jxsuite/schema/guards";
26
32
  import type { JsonPrimitive, JxDocument, JxMutableNode, JxStyle } from "@jxsuite/schema/types";
27
33
 
@@ -56,9 +62,11 @@ export function compileStaticPage(
56
62
  ) {
57
63
  const { title = "Jx App" } = opts;
58
64
 
59
- const rootContext = createCompileContext(raw, null, raw.state ?? {}, raw.$media ?? {});
65
+ // Classified once: the root is built into a context here and again as the first node.
66
+ const rootRoles = raw.state ? classifyFunctionEntries(raw) : undefined;
67
+ const rootContext = createCompileContext(raw, null, raw.state ?? {}, raw.$media ?? {}, rootRoles);
60
68
  const styleBlock = compileStyles(raw, raw.$media ?? {}, opts.projectStyle ?? null);
61
- const bodyContent = compileNode(raw, rootContext);
69
+ const bodyContent = compileNode(raw, rootContext, rootRoles);
62
70
 
63
71
  const files: EmittedFile[] = [];
64
72
 
@@ -95,7 +103,11 @@ export function compileStaticPage(
95
103
  * @param {CompileContext} context
96
104
  * @returns {string}
97
105
  */
98
- function compileNode(def: StaticChild, context: CompileContext): string {
106
+ function compileNode(
107
+ def: StaticChild,
108
+ context: CompileContext,
109
+ roles?: ReadonlyMap<string, FunctionRole>,
110
+ ): string {
99
111
  // String children are text nodes
100
112
  if (isString(def)) {
101
113
  return escapeHtml(def);
@@ -107,11 +119,17 @@ function compileNode(def: StaticChild, context: CompileContext): string {
107
119
  return "";
108
120
  }
109
121
 
122
+ // Spliced content is data (spec.md §8.4): rendered as written, with no template evaluated.
123
+ if (isLiteralNode(def)) {
124
+ return renderStaticNode(def, context.scope, null, null, context.preformatted === true);
125
+ }
126
+
110
127
  const nextContext = createCompileContext(
111
128
  def,
112
129
  context.scope,
113
130
  def.state ?? context.scopeDefs,
114
131
  def.$media ?? context.media,
132
+ roles,
115
133
  );
116
134
 
117
135
  // Resolved against the same scope the attributes are, so the prerendered element and its
@@ -148,7 +166,13 @@ function buildStaticInner(def: JxMutableNode, tag: string, context: CompileConte
148
166
  if (def.innerHTML) {
149
167
  // An expanded instance's markup is finished HTML, never a template (`isExpandedInstance`).
150
168
  if (isExpandedInstance(def)) {
151
- return def.innerHTML;
169
+ const slotted = slottedChildren(def);
170
+ /* The children written inside a page-level instance are compiled in the page's scope
171
+ (spec.md §15.2). SAFETY: a repeater among them is the pseudo-element the tree holds, which
172
+ `compileNode` renders as it does among any children. */
173
+ return slotted
174
+ ? fillSlotted(def.innerHTML, slotted, (c) => compileNode(c as StaticChild, context))
175
+ : def.innerHTML;
152
176
  }
153
177
  // Raw HTML may itself be a template; one that resolves to nothing keeps its authored text.
154
178
  const resolved = resolveStaticValue(def.innerHTML, context.scope);