@jxsuite/compiler 8.5.0 → 8.6.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.
@@ -6,6 +6,11 @@
6
6
  */
7
7
 
8
8
  import { erasedDocument } from "../erased.ts";
9
+ import {
10
+ classifyFunctionEntries,
11
+ declaresParameters,
12
+ handlerParamNames,
13
+ } from "@jxsuite/schema/function-role";
9
14
  import { RESERVED_KEYS, camelToKebab } from "@jxsuite/runtime";
10
15
  import {
11
16
  ATTR_HELPER,
@@ -22,6 +27,7 @@ import {
22
27
  compileOperandSource,
23
28
  compileStatements,
24
29
  emitFormulaFn,
30
+ refuseBodyWithSrc,
25
31
  emitRequestFetch,
26
32
  emitServerCall,
27
33
  escapeHtml,
@@ -35,7 +41,6 @@ import {
35
41
  templateValueSource,
36
42
  } from "../shared.ts";
37
43
  import {
38
- bodyReturnsValue,
39
44
  hasStructuredBody,
40
45
  isExpressionDef,
41
46
  isBoolean,
@@ -49,7 +54,6 @@ import {
49
54
  isServerFnDef,
50
55
  isString,
51
56
  isTagExpression,
52
- paramNames,
53
57
  } from "@jxsuite/schema/guards";
54
58
  import { isNativeDocumentPath, parseNativeDocument } from "@jxsuite/schema/jxn";
55
59
  import { resolveShadowMode } from "../shadow.ts";
@@ -307,75 +311,6 @@ function extractInitialValue(def: JxStateDefinition) {
307
311
  return JSON.stringify(def);
308
312
  }
309
313
 
310
- /** Lifecycle hooks the generated element calls itself, so they are never `$ref`'d (spec.md §16.4). */
311
- const LIFECYCLE_KEYS = new Set(["onMount", "onUnmount", "onAdopted"]);
312
-
313
- /**
314
- * Collect the state keys a document uses as a _callable_, at any depth: bound to an `on*` event,
315
- * invoked by an `$expression` `call` node, or called as `state.key(…)` from a template string or
316
- * another function's body.
317
- *
318
- * A bodyless `$src` Function carries no body to classify by, and unlike the interpreter — which
319
- * introspects the imported function — a compiler only has the document to go on. Anything not used
320
- * as a callable has its return value read reactively, and so becomes a computed (spec.md §5.3 4b).
321
- * Defaulting the other way round would turn a called helper into a value and break its call site.
322
- *
323
- * @param {JxDocument} doc
324
- * @returns {Set<string>}
325
- */
326
- function collectCallableRefs(doc: JxDocument) {
327
- const keys = new Set<string>();
328
- const seen = new Set<object>();
329
-
330
- const addStateRef = (ref: string) => {
331
- if (ref.startsWith("#/state/")) {
332
- /* SAFETY: `String.prototype.split` always returns at least one element (the whole string
333
- when the separator is absent), so index 0 is present. */
334
- keys.add(ref.slice("#/state/".length).split("/")[0] as string);
335
- }
336
- };
337
-
338
- const visit = (node: JxDocumentValue | undefined) => {
339
- if (isString(node)) {
340
- // `${state.formatDate(d)}` in a template, or `state.helper(x)` in another function's body.
341
- for (const call of node.matchAll(/\bstate\.([A-Za-z_$][\w$]*)\s*\(/g)) {
342
- /* SAFETY: the pattern's one capture group is not optional, so every match fills
343
- index 1 with the called member's name. */
344
- keys.add(call[1] as string);
345
- }
346
- return;
347
- }
348
- if (!isNonNullObject(node) || seen.has(node)) {
349
- return;
350
- }
351
- seen.add(node);
352
- if (Array.isArray(node)) {
353
- for (const item of node) {
354
- visit(item);
355
- }
356
- return;
357
- }
358
- /* SAFETY: `node` is a non-null, non-array object reached from `doc.children` or `doc.state`,
359
- and every such object in a parsed Jx document is a JSON object whose members are document
360
- values; the view only reads members, and each is checked before use. */
361
- const record = node as Readonly<Record<string, JxDocumentValue | undefined>>;
362
- // An `$expression` `call` node names its callee in `target` (spec.md §19.4c).
363
- if (record.operator === "call" && isRef(record.target)) {
364
- addStateRef(record.target.$ref);
365
- }
366
- for (const [key, val] of Object.entries(record)) {
367
- if (key.startsWith("on") && key !== "observedAttributes" && isRef(val)) {
368
- addStateRef(val.$ref);
369
- }
370
- visit(val);
371
- }
372
- };
373
-
374
- visit(doc.children);
375
- visit(doc.state);
376
- return keys;
377
- }
378
-
379
314
  /**
380
315
  * Generate a complete ES module string for a custom element.
381
316
  *
@@ -407,8 +342,9 @@ export function emitElementModule(
407
342
  /** `$lazy` `$src` modules → the (export, local binding) pairs each one supplies. */
408
343
  const lazySrcMap = new Map<string, { binding: string; exportName: string }[]>();
409
344
  const defs = doc.state ?? {};
410
- const callableRefs = collectCallableRefs(doc);
345
+ const roles = classifyFunctionEntries(doc);
411
346
  for (const [key, def] of Object.entries(defs)) {
347
+ refuseBodyWithSrc(`state entry "${key}"`, def);
412
348
  if (isFunctionDef(def) && def.$src) {
413
349
  const srcPath = def.$src;
414
350
  if (def.$lazy === true) {
@@ -417,7 +353,7 @@ export function emitElementModule(
417
353
  * promise. Silently producing `computed(() => Promise)` would render "[object Promise]" in
418
354
  * whatever the template bound it to, so this is a build error rather than a surprise.
419
355
  */
420
- if (!callableRefs.has(key) && !LIFECYCLE_KEYS.has(key)) {
356
+ if (roles.get(key) === "computed") {
421
357
  throw new Error(
422
358
  `"${key}" declares "$lazy": true but is used as a computed value, not called. ` +
423
359
  `A lazily loaded function resolves to a promise; a computed must resolve now. ` +
@@ -533,20 +469,7 @@ export function emitElementModule(
533
469
  computedEntries.push([key, def]);
534
470
  }
535
471
  } else if (isFunctionDef(def)) {
536
- if (def.$src && !isString(def.body)) {
537
- // Bodyless `$src` entry — classify by document usage, not by an absent body. `body` and
538
- // `$src` are mutually exclusive (spec.md §5.3 4d), so this is the only shape a
539
- // Spec-conformant external Function takes.
540
- if (callableRefs.has(key) || LIFECYCLE_KEYS.has(key)) {
541
- functionEntries.push([key, def]);
542
- } else {
543
- computedEntries.push([key, def]);
544
- }
545
- } else if (isString(def.body) && bodyReturnsValue(def.body)) {
546
- computedEntries.push([key, def]);
547
- } else {
548
- functionEntries.push([key, def]);
549
- }
472
+ (roles.get(key) === "computed" ? computedEntries : functionEntries).push([key, def]);
550
473
  } else if (isString(def) && def.includes("${")) {
551
474
  /* A TEMPLATE STRING IS A COMPUTED, and the runtime has always said so — `runtime.ts`'s
552
475
  second state pass is `if (typeof def === "string" && def.includes("${")) state[key] =
@@ -607,45 +530,20 @@ export function emitElementModule(
607
530
  " };",
608
531
  );
609
532
  } else {
610
- const args = def.parameters ? paramNames(def.parameters) : (def.arguments ?? ["state"]);
611
- const paramList = args.join(", ");
612
- const body = isString(def.body) ? def.body : "";
613
- // Every call site invokes a state function as `(state, event)` — the template's
614
- // `s.fn(s, e)`, `onMount`, `onUnmount`. Declared names that already start with `state` line
615
- // Up positionally, so they are emitted directly. Any other declaration — including the
616
- // `"parameters": ["event"]` form that examples/components/{todo-app,fetch-demo}.json use — is
617
- // Mapped onto the arguments by name, the way the client target does it
618
- // (compile-client.ts), with `state` bound as the outer parameter so a body referencing bare
619
- // `state` resolves regardless of the declared arity.
620
- if (args[0] === "state") {
621
- if (def.$src) {
622
- // $src function — wrap imported function so it receives state
623
- lines.push(
624
- ` ${refAccessor("this.state", escapeToken(key))} = (${paramList}) => ${key}(${paramList});`,
625
- );
626
- } else {
627
- lines.push(
628
- ` ${refAccessor("this.state", escapeToken(key))} = (${paramList}) => {`,
629
- ` ${body}`,
630
- " };",
631
- );
632
- }
533
+ /* One calling convention (spec.md §4.3, §5.3 4d): every event site and lifecycle call invokes
534
+ `s.fn(s, e)`, so a string body is built with `state` first and its other declared names after
535
+ it, which binds `state` by name and the event by position. A `$src` entry is its import,
536
+ called as its call site calls it. Nothing here maps a name onto an argument. */
537
+ const target = refAccessor("this.state", escapeToken(key));
538
+ if (def.$src) {
539
+ lines.push(` ${target} = ${key};`);
633
540
  } else {
634
- const callArgs = args.map((a: string) => (a === "state" ? "state" : "e")).join(", ");
635
- if (def.$src) {
636
- lines.push(
637
- ` ${refAccessor("this.state", escapeToken(key))} = (state, e) => ${key}(${callArgs});`,
638
- );
639
- } else {
640
- lines.push(
641
- ` ${refAccessor("this.state", escapeToken(key))} = (state, e) => {`,
642
- ` const _fn = (${paramList}) => {`,
643
- ` ${body}`,
644
- " };",
645
- ` return _fn(${callArgs});`,
646
- " };",
647
- );
648
- }
541
+ const body = isString(def.body) ? def.body : "";
542
+ lines.push(
543
+ ` ${target} = (${handlerParamNames(def).join(", ")}) => {`,
544
+ ` ${body}`,
545
+ " };",
546
+ );
649
547
  }
650
548
  }
651
549
  }
@@ -1213,6 +1111,7 @@ ${no}
1213
1111
  if (!key.startsWith("on") || key === "observedAttributes") {
1214
1112
  continue;
1215
1113
  }
1114
+ refuseBodyWithSrc(`inline "${key}" handler`, val);
1216
1115
  const eventName = key.slice(2).toLowerCase();
1217
1116
  if (isBoundRef(val)) {
1218
1117
  parts.push(
@@ -1412,6 +1311,7 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1412
1311
  if (!key.startsWith("on")) {
1413
1312
  continue;
1414
1313
  }
1314
+ refuseBodyWithSrc(`inline "${key}" handler`, val);
1415
1315
  const eventName = key.slice(2).toLowerCase();
1416
1316
  if (isRef(val)) {
1417
1317
  parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${refToExpr(val.$ref)}(s, e); }}"`);
@@ -1421,6 +1321,9 @@ function emitMappedArray(arrayDef: JxMappedArray, indent: string) {
1421
1321
  statePrefix: "s",
1422
1322
  });
1423
1323
  parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${compiled}; }}"`);
1324
+ } else if (isFunctionDef(val)) {
1325
+ // A map root binds an inline handler as any other element does, with the iteration published.
1326
+ parts.push(`@${eventName}="\${(e) => { s.$map = $map; ${inlineHandlerBody(val)} }}"`);
1424
1327
  }
1425
1328
  }
1426
1329
 
@@ -1573,15 +1476,12 @@ function inlineHandlerBody(def: JxFunctionDef) {
1573
1476
  });
1574
1477
  }
1575
1478
  const body = isString(def.body) ? def.body : "";
1576
- const declared = def.parameters ? paramNames(def.parameters) : (def.arguments ?? []);
1577
- if (declared.length > 0) {
1578
- // The call site supplies only `(e)`, so map the declared names onto the arguments the handler
1579
- // Actually has — `state` to the `s` alias, anything else to the event. Binding by name means the
1580
- // Body needs no textual rewriting, and a declared `event` stops silently resolving to the
1581
- // Deprecated `window.event` global (any other declared name threw ReferenceError outright).
1582
- const args = declared.map((name: string) => (name === "state" ? "s" : "e")).join(", ");
1583
- // The newline ends a last-line comment before the brace does.
1584
- return `((${declared.join(", ")}) => { ${body}\n})(${args});`;
1479
+ if (declaresParameters(def)) {
1480
+ /* The same list every tier builds a body with, called `(s, e)` like any other handler: `state`
1481
+ binds by name, the first other declared name is the event, and a declared `event` stops
1482
+ silently resolving to the deprecated `window.event` global. The newline ends a last-line
1483
+ comment before the brace does. */
1484
+ return `((${handlerParamNames(def).join(", ")}) => { ${body}\n})(s, e);`;
1585
1485
  }
1586
1486
  return `${rewriteState(body, "s", { bare: true })}\n`;
1587
1487
  }