@barefootjs/jsx 0.39.2 → 0.39.4

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.
Files changed (98) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -0
  2. package/dist/adapters/boolean-result.d.ts.map +1 -0
  3. package/dist/adapters/line-statement-text.d.ts +17 -0
  4. package/dist/adapters/line-statement-text.d.ts.map +1 -0
  5. package/dist/analyzer.d.ts +1 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/augment-inherited-props.d.ts +20 -0
  8. package/dist/augment-inherited-props.d.ts.map +1 -1
  9. package/dist/errors.d.ts +1 -0
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/html-types.d.ts +15 -0
  12. package/dist/html-types.d.ts.map +1 -1
  13. package/dist/index.d.ts +6 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +595 -140
  16. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +5 -0
  20. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  22. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  24. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  26. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/composite-loop.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +14 -0
  31. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/imports.d.ts +2 -2
  34. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  36. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  39. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/types.d.ts +12 -0
  41. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/nullable-signal-attr.d.ts +94 -0
  44. package/dist/nullable-signal-attr.d.ts.map +1 -0
  45. package/dist/profiler.d.ts +9 -1
  46. package/dist/profiler.d.ts.map +1 -1
  47. package/dist/scope/root-prop-alias.d.ts +43 -0
  48. package/dist/scope/root-prop-alias.d.ts.map +1 -0
  49. package/package.json +2 -2
  50. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  51. package/src/__tests__/attribute-fallback-wrap.test.ts +24 -0
  52. package/src/__tests__/boolean-result.test.ts +27 -0
  53. package/src/__tests__/compiler-stress-1244.test.ts +10 -13
  54. package/src/__tests__/conditional-fallback-wrap.test.ts +20 -0
  55. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  56. package/src/__tests__/html-event-handler-names.test.ts +107 -0
  57. package/src/__tests__/line-statement-text.test.ts +25 -0
  58. package/src/__tests__/lookup-literal-const.test.ts +46 -0
  59. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +66 -19
  60. package/src/__tests__/nullable-signal-attr.test.ts +124 -0
  61. package/src/__tests__/profile-binding-ids.test.ts +102 -0
  62. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  63. package/src/__tests__/profiler.test.ts +10 -9
  64. package/src/__tests__/root-prop-alias.test.ts +62 -0
  65. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  66. package/src/adapters/boolean-result.ts +89 -0
  67. package/src/adapters/line-statement-text.ts +24 -0
  68. package/src/analyzer.ts +50 -26
  69. package/src/augment-inherited-props.ts +49 -0
  70. package/src/errors.ts +11 -0
  71. package/src/html-types.ts +15 -0
  72. package/src/index.ts +16 -2
  73. package/src/ir-to-client-js/collect-elements.ts +18 -4
  74. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +2 -2
  75. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  76. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  77. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +7 -2
  78. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  79. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  80. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  81. package/src/ir-to-client-js/control-flow/shared.ts +2 -0
  82. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  83. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  84. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  85. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  86. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  87. package/src/ir-to-client-js/html-template.ts +59 -8
  88. package/src/ir-to-client-js/imports.ts +3 -1
  89. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  90. package/src/ir-to-client-js/reactivity.ts +1 -0
  91. package/src/ir-to-client-js/safe-html.ts +10 -0
  92. package/src/ir-to-client-js/stringify/declaration-emit.ts +5 -5
  93. package/src/ir-to-client-js/types.ts +12 -0
  94. package/src/ir-to-client-js/utils.ts +88 -117
  95. package/src/jsx-to-ir.ts +145 -32
  96. package/src/nullable-signal-attr.ts +202 -0
  97. package/src/profiler.ts +79 -10
  98. package/src/scope/root-prop-alias.ts +81 -0
package/src/jsx-to-ir.ts CHANGED
@@ -4561,6 +4561,128 @@ function applyLoopKeyAttr(node: IRNode, name: string, value: string): void {
4561
4561
  }
4562
4562
  }
4563
4563
 
4564
+ /**
4565
+ * Give every SSR-portal element (`ssrPortalOwnerScope`) in a `.map()` row
4566
+ * the row's key attribute (#3318). SSR places such an element at its portal
4567
+ * outlet, outside the row, so its slot and owner scope alone cannot say
4568
+ * which row it belongs to; the row key on the element itself lets
4569
+ * hydration pair it with its row (`claimRowPortals`) and lets the loop's
4570
+ * delegated listener resolve the row from the element
4571
+ * (`closest('[data-key]')`). Every SSR adapter renders `IRElement.keyAttr`,
4572
+ * and the client templates render it from a `key` attribute, so the element
4573
+ * also gets a copy of the row root's `key` attribute; no adapter changes
4574
+ * are needed.
4575
+ *
4576
+ * Only a keyed top-level loop (`depth === 0`) is supported. A nested loop's
4577
+ * row key is not unique on its own and an unkeyed row has none, so a
4578
+ * portal element there is refused (BF064) rather than rendered at an
4579
+ * outlet nothing can pair. So is one forwarded as a child component's
4580
+ * `children` (or inside a provider / `<Async>`), where the row's key is not
4581
+ * this element's to render; one inside a reactive conditional in the row,
4582
+ * whose `ref` the conditional's branch runs rather than the row; and the
4583
+ * row root itself, whose move leaves no inline row for hydration to find.
4584
+ * Nested loops are skipped: their own construction applies this to their
4585
+ * rows (a nested loop's portaled row root is refused here, as it already
4586
+ * carries its `keyAttr`).
4587
+ */
4588
+ function applyRowPortalKeyAttrs(
4589
+ children: IRNode[],
4590
+ key: string | null,
4591
+ depth: number,
4592
+ ctx: TransformContext,
4593
+ ): void {
4594
+ const refuse = (el: IRElement, reason: string): void => {
4595
+ ctx.analyzer.errors.push(
4596
+ createError(ErrorCodes.ROW_PORTAL_UNPAIRABLE, el.loc, {
4597
+ message:
4598
+ `A ref callback portals <${el.tag}> out of a .map() row, but ${reason}, so hydration cannot pair the ` +
4599
+ 'portaled element with its row and its event handlers would stop running after hydration.',
4600
+ suggestion: {
4601
+ message:
4602
+ 'Portal an element inside the root of a keyed top-level .map() row (`key={…}` on the row root), ' +
4603
+ "outside reactive conditionals and child components' children, or move the portal outside the loop.",
4604
+ escape: [{ kind: 'rewrite' }],
4605
+ },
4606
+ }),
4607
+ )
4608
+ }
4609
+ // `blocked` names why an element at this position cannot be paired with
4610
+ // its row; `null` means it can.
4611
+ const visit = (node: IRNode, blocked: string | null): void => {
4612
+ switch (node.type) {
4613
+ case 'element':
4614
+ if (node.ssrPortalOwnerScope) {
4615
+ // `applyLoopKeyAttr` stamps the row root (of this loop, or of a
4616
+ // nested loop already built) before this pass: a portaled row root
4617
+ // leaves no inline row for hydration to find.
4618
+ if (node.keyAttr) refuse(node, 'it is the root element of the row')
4619
+ else if (blocked) refuse(node, blocked)
4620
+ else if (key === null) refuse(node, 'the loop has no `key`')
4621
+ else if (depth > 0) refuse(node, 'the loop is nested inside another loop')
4622
+ else {
4623
+ node.keyAttr = { name: keyAttrName(depth), value: key }
4624
+ // The client templates render the row key from a `key` attribute
4625
+ // gated on `keyAttr`, as they do for the row root, so the element
4626
+ // carries a copy of the row root's.
4627
+ if (!node.attrs.some((a) => a.name === 'key')) {
4628
+ node.attrs.push(rowKeyAttribute(children) ?? { name: 'key', value: { kind: 'expression', expr: key }, loc: node.loc })
4629
+ }
4630
+ }
4631
+ }
4632
+ for (const c of node.children) visit(c, blocked)
4633
+ return
4634
+ case 'fragment':
4635
+ for (const c of node.children) visit(c, blocked)
4636
+ return
4637
+ case 'conditional': {
4638
+ // A reactive conditional (`slotId`) owns its branch's refs, which
4639
+ // the row's ref collection skips, so the row cannot adopt them.
4640
+ const inner = blocked ?? (node.slotId ? 'it is rendered inside a reactive conditional in the row' : null)
4641
+ visit(node.whenTrue, inner)
4642
+ visit(node.whenFalse, inner)
4643
+ return
4644
+ }
4645
+ case 'if-statement':
4646
+ visit(node.consequent, blocked)
4647
+ if (node.alternate) visit(node.alternate, blocked)
4648
+ return
4649
+ case 'component':
4650
+ case 'provider':
4651
+ for (const c of node.children) visit(c, blocked ?? "it is rendered inside another component's children")
4652
+ return
4653
+ case 'async':
4654
+ visit(node.fallback, blocked ?? "it is rendered inside another component's children")
4655
+ for (const c of node.children) visit(c, blocked ?? "it is rendered inside another component's children")
4656
+ return
4657
+ default:
4658
+ return
4659
+ }
4660
+ }
4661
+ for (const c of children) visit(c, null)
4662
+ }
4663
+
4664
+ /** The `key` attribute the row's key was read from (`extractLoopKey`), when it is on an element. */
4665
+ function rowKeyAttribute(children: IRNode[]): IRAttribute | null {
4666
+ const find = (node: IRNode): IRAttribute | null => {
4667
+ switch (node.type) {
4668
+ case 'element':
4669
+ return node.attrs.find((a) => a.name === 'key') ?? null
4670
+ case 'conditional':
4671
+ return find(node.whenTrue)
4672
+ case 'fragment': {
4673
+ const first = node.children.find(
4674
+ (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
4675
+ )
4676
+ return first ? find(first) : null
4677
+ }
4678
+ default:
4679
+ return null
4680
+ }
4681
+ }
4682
+ const first = children.find((c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim()))
4683
+ return first ? find(first) : null
4684
+ }
4685
+
4564
4686
  function loopBodyItemConditional(children: IRNode[]): IRConditional | null {
4565
4687
  const real = children.filter(
4566
4688
  (c) => !(c.type === 'text' && typeof c.value === 'string' && !c.value.trim())
@@ -5419,6 +5541,7 @@ function transformMapCall(
5419
5541
  applyLoopKeyAttr(children[0], resolvedKeyAttrName, key)
5420
5542
  }
5421
5543
  }
5544
+ applyRowPortalKeyAttrs(children, key, depth, ctx)
5422
5545
 
5423
5546
  // Stage 3 / D5 (spec/callback-fidelity.md) — the keyFn is hoisted: `mapArray`
5424
5547
  // computes it from the raw item BEFORE the callback body runs, so the key must
@@ -7092,14 +7215,6 @@ interface LocalCallback {
7092
7215
  interface RefCallback extends LocalCallback {
7093
7216
  /** Bound by name (`ref={handleMount}`) rather than written inline. */
7094
7217
  named: boolean
7095
- /**
7096
- * True only for a named callback declared in the `ref`'s innermost
7097
- * enclosing function scope; false for an inline callback and for one
7098
- * `findNamedCallback`'s outward walk found further out (e.g. a `ref` in a
7099
- * `.map()` row naming a component-body handler). BF063 ignores this;
7100
- * `isSsrPortalRefCallback` requires it.
7101
- */
7102
- innermostScope: boolean
7103
7218
  }
7104
7219
 
7105
7220
  /**
@@ -7111,11 +7226,11 @@ interface RefCallback extends LocalCallback {
7111
7226
  function resolveRefCallback(refExpr: ts.Expression): RefCallback | undefined {
7112
7227
  const expr = unwrapTransparentTsWrappers(refExpr)
7113
7228
  if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
7114
- return { param: firstSimpleParamName(expr), body: expr.body, named: false, innermostScope: false }
7229
+ return { param: firstSimpleParamName(expr), body: expr.body, named: false }
7115
7230
  }
7116
7231
  if (!ts.isIdentifier(expr)) return undefined
7117
- const resolved = findNamedCallback(expr)
7118
- return resolved && { ...resolved.callback, named: true, innermostScope: resolved.innermostScope }
7232
+ const callback = findNamedCallback(expr)
7233
+ return callback && { ...callback, named: true }
7119
7234
  }
7120
7235
 
7121
7236
  type FunctionLike = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration
@@ -7147,20 +7262,13 @@ function findEnclosingFunctionLike(node: ts.Node): FunctionLike | undefined {
7147
7262
  * Never searches a nested function's own body: two sibling components in the
7148
7263
  * same file can each declare their own, unrelated `handleMount`, and reaching
7149
7264
  * into the wrong one's closure would misattribute its behavior to this `ref`.
7150
- * `innermostScope` reports whether the deciding scope was the `ref`'s own
7151
- * innermost one: BF063 accepts any scope, the SSR-portal recognition only
7152
- * that one (see `isSsrPortalRefCallback`).
7153
7265
  */
7154
- function findNamedCallback(
7155
- ident: ts.Identifier,
7156
- ): { callback: LocalCallback; innermostScope: boolean } | undefined {
7157
- const innermost = findEnclosingFunctionLike(ident)
7158
- for (let fn = innermost; fn; fn = findEnclosingFunctionLike(fn)) {
7266
+ function findNamedCallback(ident: ts.Identifier): LocalCallback | undefined {
7267
+ for (let fn = findEnclosingFunctionLike(ident); fn; fn = findEnclosingFunctionLike(fn)) {
7159
7268
  if (fn.parameters.some(p => bindingDeclares(p.name, ident.text))) return undefined
7160
7269
  const decl = fn.body && findScopeDeclaration(ident.text, fn.body)
7161
7270
  if (!decl) continue
7162
- const callback = localCallbackOf(decl)
7163
- return callback && { callback, innermostScope: fn === innermost }
7271
+ return localCallbackOf(decl)
7164
7272
  }
7165
7273
  return undefined
7166
7274
  }
@@ -7238,24 +7346,22 @@ function bindingDeclares(binding: ts.BindingName, name: string): boolean {
7238
7346
  * (the "worth the scope-walk?" open question from #3059) is therefore
7239
7347
  * left for when a real caller needs it.
7240
7348
  *
7241
- * The callback must be declared in the `ref`'s INNERMOST enclosing
7242
- * function scope (`RefCallback.innermostScope`) — BF063 shares the
7243
- * resolution but may walk further out; this recognition may not. The gate
7244
- * only restores the scope limit recognition had before BF063 widened the
7245
- * lookup, so sharing the resolution does not widen what is recognized. It
7246
- * is not a `.map()`-row guard: a portal element inside a row is broken
7247
- * either way (a row-declared callback is still recognized, and still
7248
- * breaks) — the known limitation `loop-row-ref-portal`
7249
- * (`packages/adapter-tests/limitations/loop-row-ref-portal.ts`).
7349
+ * The callback may be declared in any enclosing function scope
7350
+ * (`findNamedCallback`, shared with BF063): a `ref` in a `.map()` row
7351
+ * naming a handler declared in the component body is recognized too. The
7352
+ * resolution never crosses into a sibling function's body and stops at a
7353
+ * shadowing parameter or non-function binding, so the callback found is
7354
+ * the one that runs.
7250
7355
  *
7251
7356
  * A match makes `element.ssrPortalOwnerScope` true, which every adapter
7252
7357
  * (#3119) uses to place the element's SSR markup at its own portal
7253
- * outlet instead of inline.
7358
+ * outlet instead of inline. Inside a keyed top-level `.map()` row the
7359
+ * element also carries the row key (`applyRowPortalKeyAttrs`, #3318), so
7360
+ * hydration pairs it with its row; a nested or unkeyed row refuses (BF064).
7254
7361
  */
7255
7362
  function isSsrPortalRefCallback(callback: RefCallback | undefined): boolean {
7256
7363
  return (
7257
7364
  !!callback?.named &&
7258
- callback.innermostScope &&
7259
7365
  !!callback.param &&
7260
7366
  containsSsrPortalPlacementCall(callback.body, callback.param)
7261
7367
  )
@@ -9203,6 +9309,13 @@ function hasReactiveAttributes(attrs: IRAttribute[], ctx: TransformContext): boo
9203
9309
  if (isSignalOrMemoReference(valueToCheck, ctx) || isPropsReference(valueToCheck, ctx)) {
9204
9310
  return true
9205
9311
  }
9312
+ // The Solid-style wrap-by-default fallback (#940): an attribute with a
9313
+ // call the analyzer can't prove non-reactive (`hidden={v().hide}`,
9314
+ // `v` reading an untyped or class-held store) gets a createEffect from
9315
+ // `decideWrapForAttr`. That effect addresses the element by slot id,
9316
+ // so the element needs one even with no other dynamic content —
9317
+ // otherwise the attribute is never applied on the client (#3266).
9318
+ if (attr.callsReactiveGetters || attr.hasFunctionCalls) return true
9206
9319
  // Check if attribute references any active loop-bound VALUE names —
9207
9320
  // loop root elements need a slotId so className can be updated
9208
9321
  // reactively. REACTIVITY/slotId classifier — value bindings only
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Nullish-attribute omission for signal reads (#3304).
3
+ *
4
+ * Hono omits an attribute whose value is `undefined` or `null`
5
+ * (`title={s()}` with `s()` undefined renders no `title`). A DSL adapter
6
+ * emits `name="<value>"` unconditionally, so a nil value renders
7
+ * `title=""` unless the adapter guards the attribute on a nil check. Each
8
+ * DSL adapter already guards a bare reference to a no-default optional prop
9
+ * that way; this module is the one decision for the signal half, which
10
+ * every adapter consults instead of re-deriving it.
11
+ *
12
+ * Only the SSR value matters here — a signal's SSR value is its initial
13
+ * value — and the guard is presence-only: a non-nil value renders exactly
14
+ * as it did unguarded, so over-including a signal never changes output for
15
+ * a non-nil value.
16
+ */
17
+
18
+ import type { ParsedExpr } from './expression-parser.ts'
19
+ import type { ComponentIR, MemoInfo, SignalInfo, TypeInfo } from './types.ts'
20
+
21
+ function isNullishType(type: TypeInfo): boolean {
22
+ return type.kind === 'primitive' && (type.primitive === 'undefined' || type.primitive === 'null')
23
+ }
24
+
25
+ /** `T | undefined` / `T | null`, or bare `undefined` / `null`. */
26
+ function admitsNullish(type: TypeInfo): boolean {
27
+ if (isNullishType(type)) return true
28
+ return type.kind === 'union' && (type.unionTypes ?? []).some(isNullishType)
29
+ }
30
+
31
+ /** `undefined` / `null` as a parsed initial value. */
32
+ export function isNullishLiteral(expr: ParsedExpr | undefined): boolean {
33
+ if (!expr) return false
34
+ if (expr.kind === 'identifier') return expr.name === 'undefined'
35
+ return expr.kind === 'literal' && expr.literalType === 'null'
36
+ }
37
+
38
+ /**
39
+ * Whether the signal's SSR value can be nullish. The witness is its type
40
+ * admitting `undefined`/`null` (a zero-arg `createSignal<T>()` is typed
41
+ * `T | undefined`, #3215), or, for an untyped signal, a literal `undefined` /
42
+ * `null` initial value.
43
+ */
44
+ export function isNullableSignal(signal: SignalInfo): boolean {
45
+ if (admitsNullish(signal.type)) return true
46
+ return signal.type.kind === 'unknown' && isNullishLiteral(signal.parsed)
47
+ }
48
+
49
+ /** Getter names of the component's signals whose SSR value can be nullish. */
50
+ export function collectNullableSignalGetters(ir: ComponentIR): Set<string> {
51
+ return new Set((ir.metadata.signals ?? []).filter(isNullableSignal).map(s => s.getter))
52
+ }
53
+
54
+ /**
55
+ * The getter an attribute value reads when the whole value is a bare,
56
+ * zero-argument getter call (`s()`); `null` for any other shape. A member
57
+ * read, a ternary or a template literal around the call is not matched:
58
+ * the attribute's presence then depends on more than the signal.
59
+ */
60
+ export function bareGetterCallName(parsed: ParsedExpr | undefined): string | null {
61
+ if (!parsed || parsed.kind !== 'call' || parsed.args.length !== 0) return null
62
+ return parsed.callee.kind === 'identifier' ? parsed.callee.name : null
63
+ }
64
+
65
+ /**
66
+ * The signal getter whose nil check should guard this attribute, or `null`
67
+ * when the attribute is not a bare read of a nullable signal. `nullable` is
68
+ * the set `collectNullableSignalGetters` built for the component.
69
+ */
70
+ export function nullableSignalAttrGetter(
71
+ parsed: ParsedExpr | undefined,
72
+ nullable: ReadonlySet<string>,
73
+ ): string | null {
74
+ const getter = bareGetterCallName(parsed)
75
+ return getter !== null && nullable.has(getter) ? getter : null
76
+ }
77
+
78
+ /**
79
+ * What `attrValueMayBeNullish` needs to know about the component: its
80
+ * nullable signal getters and its memos by name.
81
+ */
82
+ export interface NullishAttrContext {
83
+ readonly nullableSignals: ReadonlySet<string>
84
+ /** Signals seeded with a literal `null`: their SSR value is `null`, not
85
+ * `undefined` (`arithmeticOperandIsNull`). */
86
+ readonly nullSeededSignals?: ReadonlySet<string>
87
+ readonly memos: ReadonlyMap<string, MemoInfo>
88
+ }
89
+
90
+ export function collectNullishAttrContext(ir: ComponentIR): NullishAttrContext {
91
+ const signals = ir.metadata.signals ?? []
92
+ return {
93
+ nullableSignals: collectNullableSignalGetters(ir),
94
+ nullSeededSignals: new Set(
95
+ signals.filter(s => s.parsed?.kind === 'literal' && s.parsed.literalType === 'null').map(s => s.getter),
96
+ ),
97
+ memos: new Map((ir.metadata.memos ?? []).map(m => [m.name, m])),
98
+ }
99
+ }
100
+
101
+ /**
102
+ * Whether an attribute value's SSR value can be `undefined` / `null`, so a
103
+ * DSL adapter must guard the attribute on a nil check to omit it the way
104
+ * Hono does (#3322) — the derived-value half of the bare-signal guard
105
+ * (`nullableSignalAttrGetter`, #3304). Matches a value that reaches a
106
+ * nullish value through:
107
+ *
108
+ * - a read of a nullable signal or of a memo whose type or body can be
109
+ * nullish (`label()` with `label = createMemo(() => s())`);
110
+ * - an optional member read (`user()?.name`), or a member read of a value
111
+ * that can itself be nullish;
112
+ * - a ternary branch, or an `??` / `||` / `&&` operand the result can be;
113
+ * - a literal `undefined` / `null`.
114
+ *
115
+ * Like the bare-signal guard it is presence-only: a non-nil value renders
116
+ * exactly as unguarded, so over-including a value never changes output for
117
+ * a present value (`''`, `0` and `false` still render). `isShadowed` names
118
+ * a getter a loop binding hides at the attribute site, which is then not
119
+ * the signal / memo; a memo's own body is read in its declaration scope.
120
+ */
121
+ export function attrValueMayBeNullish(
122
+ parsed: ParsedExpr | undefined,
123
+ ctx: NullishAttrContext,
124
+ isShadowed: (name: string) => boolean = () => false,
125
+ ): boolean {
126
+ const visiting = new Set<string>()
127
+ // `shadowed` is the scope the expression is read in: the attribute site's
128
+ // loop bindings at the top level, none inside a memo body — its getters
129
+ // resolve where the memo is declared, not where it is read.
130
+ const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): boolean => {
131
+ switch (expr.kind) {
132
+ case 'identifier':
133
+ return expr.name === 'undefined'
134
+ case 'literal':
135
+ return expr.literalType === 'null'
136
+ case 'call': {
137
+ const getter = bareGetterCallName(expr)
138
+ if (getter === null || shadowed(getter)) return false
139
+ if (ctx.nullableSignals.has(getter)) return true
140
+ const memo = ctx.memos.get(getter)
141
+ if (!memo || visiting.has(getter)) return false
142
+ if (admitsNullish(memo.type)) return true
143
+ visiting.add(getter)
144
+ const result = memo.parsed !== undefined && walk(memo.parsed, () => false)
145
+ visiting.delete(getter)
146
+ return result
147
+ }
148
+ case 'member':
149
+ return expr.optional || walk(expr.object, shadowed)
150
+ case 'index-access':
151
+ return walk(expr.object, shadowed)
152
+ case 'conditional':
153
+ return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed)
154
+ case 'logical':
155
+ return expr.op === '&&'
156
+ ? walk(expr.left, shadowed) || walk(expr.right, shadowed)
157
+ : walk(expr.right, shadowed)
158
+ default:
159
+ return false
160
+ }
161
+ }
162
+ return parsed !== undefined && walk(parsed, isShadowed)
163
+ }
164
+
165
+ /**
166
+ * Whether an arithmetic operand's SSR value is certainly `null` — a literal
167
+ * `null`, a read of a signal seeded with `null`, or a memo whose body is
168
+ * such a read (`same = () => s()`). JS `ToNumber(null)` is `0` but
169
+ * `ToNumber(undefined)` is `NaN`, and a template engine holds both as one
170
+ * nil, so only a value known to be `null` may be coerced to `0` (#3350).
171
+ * A bare identifier is read as the getter call: a memo seed lowers `s()` to
172
+ * `s` before the adapter sees it.
173
+ */
174
+ export function arithmeticOperandIsNull(
175
+ parsed: ParsedExpr | undefined,
176
+ ctx: NullishAttrContext,
177
+ isShadowed: (name: string) => boolean = () => false,
178
+ ): boolean {
179
+ const visiting = new Set<string>()
180
+ const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): boolean => {
181
+ if (expr.kind === 'literal') return expr.literalType === 'null'
182
+ const getter = expr.kind === 'identifier' ? expr.name : bareGetterCallName(expr)
183
+ if (getter === null || shadowed(getter)) return false
184
+ if (ctx.nullSeededSignals?.has(getter)) return true
185
+ const memo = ctx.memos.get(getter)
186
+ if (!memo?.parsed || visiting.has(getter)) return false
187
+ visiting.add(getter)
188
+ const result = walk(memo.parsed, () => false)
189
+ visiting.delete(getter)
190
+ return result
191
+ }
192
+ return parsed !== undefined && walk(parsed, isShadowed)
193
+ }
194
+
195
+ /**
196
+ * Arithmetic operators JS applies `ToNumber` to, so a `null` operand reads
197
+ * as `0` (`null * 2` is `0`). A template engine's native operator rejects a
198
+ * nil operand instead and the render throws (#3350), so adapters coerce an
199
+ * operand that `arithmeticOperandIsNull` matches. `+` is excluded: it
200
+ * concatenates when either side is a string.
201
+ */
202
+ export const NULL_COERCING_ARITHMETIC_OPS: ReadonlySet<string> = new Set(['-', '*', '/', '%', '**'])
package/src/profiler.ts CHANGED
@@ -30,6 +30,8 @@ import {
30
30
  type UpdatePathEntry,
31
31
  } from './debug.ts'
32
32
  import { listComponentFunctions, createProgramForFile } from './analyzer.ts'
33
+ import { walkIR } from './ir-to-client-js/walker.ts'
34
+ import type { ComponentIR } from './types.ts'
33
35
  import type { ProfilerEvent } from '@barefootjs/shared'
34
36
 
35
37
  /**
@@ -509,6 +511,46 @@ export function buildIdIndex(graph: ComponentGraph): IdIndex {
509
511
  return index
510
512
  }
511
513
 
514
+ /**
515
+ * Handler sites behind a rest/props spread on an intrinsic element
516
+ * (`<button {...props}>`), keyed by their turn-id prefix
517
+ * `<Component>#handler:<slotId>` (#3376). The compiler wires the event handlers
518
+ * such a spread carries at runtime (`applyRestAttrs`), so which events they are
519
+ * is only known once a caller passes them — the turn id appends the DOM event
520
+ * name the runtime saw. Resolving a recorded turn id to its spread site needs
521
+ * only the prefix, so every spread with a slot is listed: one the compiler
522
+ * applies statically never produces such a turn id, and its entry stays unused.
523
+ */
524
+ function buildRestHandlerSites(componentName: string, ir: ComponentIR): Map<string, ResolvedNode> {
525
+ const sites = new Map<string, ResolvedNode>()
526
+ walkIR(ir.root, undefined, {
527
+ element({ node, descend }) {
528
+ const spread = node.slotId ? node.attrs.find(a => a.name === '...') : undefined
529
+ if (spread && node.slotId) {
530
+ const loc = spread.loc ?? node.loc
531
+ sites.set(`${componentName}#handler:${node.slotId}`, {
532
+ kind: 'handler',
533
+ // Completed with the event name per turn id: `click@s0 {...}`.
534
+ name: `@${node.slotId} {...}`,
535
+ loc: { file: loc.file, line: loc.start.line },
536
+ })
537
+ }
538
+ descend()
539
+ },
540
+ component({ descend, descendJsxChildren }) {
541
+ descend()
542
+ descendJsxChildren()
543
+ },
544
+ })
545
+ return sites
546
+ }
547
+
548
+ /** The spread site a rest-forwarded turn id (`<site>:<event>`) belongs to. */
549
+ function restSiteOf(handlerId: string, sites: ReadonlyMap<string, ResolvedNode>): ResolvedNode | undefined {
550
+ const colon = handlerId.lastIndexOf(':')
551
+ return colon < 0 ? undefined : sites.get(handlerId.slice(0, colon))
552
+ }
553
+
512
554
  /** A profiler id that no IR node could be found for (SR4 coverage gap). */
513
555
  export interface UnattributedId {
514
556
  id: string
@@ -1358,7 +1400,15 @@ export interface DiagnosticsSummary {
1358
1400
  export interface ProfileCoverage {
1359
1401
  /** Distinct handlers exercised (turns observed). */
1360
1402
  handlersFired: number
1361
- /** Handlers the IR knows about (`buildEventSummary`). */
1403
+ /**
1404
+ * DOM handler sites in the run (#3377): one per instrumented DOM listener —
1405
+ * every `<el on*={…}>` event binding the IR knows about, plus each
1406
+ * rest-forwarded listener (`<el {...props}>`, #3376) the run observed (its
1407
+ * events are decided by the caller, so it is known only once wired). The same
1408
+ * unit the numerator counts — a turn is recorded per DOM listener — so a
1409
+ * callback prop a parent hands a child (`<Child onClick={…}>`) is not a unit
1410
+ * of its own: it runs inside the child's DOM turn.
1411
+ */
1362
1412
  handlersTotal: number
1363
1413
  /**
1364
1414
  * `handlersFired / handlersTotal` in `[0,1]` — the fraction of known handlers
@@ -1607,7 +1657,11 @@ export function buildProfileReport(input: ProfileReportInput): ProfileReport {
1607
1657
  // turn id → the handler binding + the component graph that owns it (so the
1608
1658
  // safety oracle reasons over the right component's memos).
1609
1659
  const turnBindings = new Map<string, { binding: EventBinding; graph: ComponentGraph }>()
1610
- let handlersTotal = 0
1660
+ // Coverage inventory (#3377): the turn ids of every DOM event binding — the
1661
+ // same inventory the auto scenario fires and the static budget lists.
1662
+ const staticHandlerIds = new Set<string>()
1663
+ // Spread sites whose runtime-wired handlers carry their own turn ids (#3376).
1664
+ const restSites = new Map<string, ResolvedNode>()
1611
1665
  // Per-file lines of the `createEffect` calls the compiler instrumented (top
1612
1666
  // level, carry a `__bfId`). Subtracted from a source scan to find the
1613
1667
  // uninstrumented ones behind anonymous `e<n>` ids (#1849 B6).
@@ -1628,12 +1682,17 @@ export function buildProfileReport(input: ProfileReportInput): ProfileReport {
1628
1682
  if (componentNames.length === 0) componentNames = [undefined as unknown as string]
1629
1683
  for (const name of componentNames) {
1630
1684
  let graph: ComponentGraph
1685
+ let ir: ComponentIR
1631
1686
  try {
1632
- graph = buildComponentAnalysis(s.source, s.filePath, name, program).graph
1687
+ ;({ graph, ir } = buildComponentAnalysis(s.source, s.filePath, name, program))
1633
1688
  } catch {
1634
1689
  continue
1635
1690
  }
1636
- for (const [k, v] of buildIdIndex(graph)) index.set(k, v)
1691
+ for (const [k, v] of buildIdIndex(graph)) {
1692
+ index.set(k, v)
1693
+ if (v.kind === 'handler') staticHandlerIds.add(k)
1694
+ }
1695
+ for (const [k, v] of buildRestHandlerSites(graph.componentName, ir)) restSites.set(k, v)
1637
1696
  for (const e of graph.effects) {
1638
1697
  const set = instrumentedEffectLines.get(e.loc.file) ?? new Set<number>()
1639
1698
  set.add(e.loc.line)
@@ -1641,7 +1700,6 @@ export function buildProfileReport(input: ProfileReportInput): ProfileReport {
1641
1700
  }
1642
1701
  try {
1643
1702
  const summary = buildEventSummary(s.source, s.filePath, name, program)
1644
- handlersTotal += summary.events.length
1645
1703
  for (const [turn, binding] of turnToEventBinding(graph, summary.events)) {
1646
1704
  turnBindings.set(turn, { binding, graph })
1647
1705
  }
@@ -1651,6 +1709,14 @@ export function buildProfileReport(input: ProfileReportInput): ProfileReport {
1651
1709
  }
1652
1710
  }
1653
1711
 
1712
+ // A rest-forwarded turn id resolves to its spread site (#3376), so its batch
1713
+ // candidate and findings cite source like any explicit handler's.
1714
+ for (const e of events) {
1715
+ if (e.turn === null || index.has(e.turn)) continue
1716
+ const site = restSiteOf(e.turn, restSites)
1717
+ if (site) index.set(e.turn, { ...site, name: `${e.turn.slice(e.turn.lastIndexOf(':') + 1)}${site.name}` })
1718
+ }
1719
+
1654
1720
  // Candidate sites for uninstrumented `createEffect` ids, across every source
1655
1721
  // in the run (a compound scenario spans several files), so an `e<n>` row can
1656
1722
  // cite where to look (#1849 B6). The per-file AST scan is only ever consumed
@@ -1701,6 +1767,11 @@ export function buildProfileReport(input: ProfileReportInput): ProfileReport {
1701
1767
  handlerIds.add(e.turn)
1702
1768
  }
1703
1769
  }
1770
+ // The inventory is every static DOM handler site plus every one the run
1771
+ // observed — a turn id the IR could not list (a rest-forwarded listener) is
1772
+ // still a DOM handler that exists. Numerator and denominator count the same
1773
+ // unit, so a fully exercised component reads 1 and the ratio can't pass 1.
1774
+ const handlersTotal = new Set([...staticHandlerIds, ...handlerIds]).size
1704
1775
 
1705
1776
  const findings = buildAgentFindings(primary.componentName, hotSubscribers, wastedReReruns, batchAdvisor, unattributed)
1706
1777
  // Status is measurement-only here: any warning/error finding ⇒ `warning`. A
@@ -1709,11 +1780,9 @@ export function buildProfileReport(input: ProfileReportInput): ProfileReport {
1709
1780
  const status: ProfileStatus = findings.some(f => f.severity === 'warning' || f.severity === 'error') ? 'warning' : 'ok'
1710
1781
 
1711
1782
  // Coverage ratio: 1 when there is nothing to cover (no handlers), else the
1712
- // exercised fraction. Clamped to `[0,1]` — a malformed stream (more distinct
1713
- // turn ids than `buildEventSummary` knows about, e.g. missing `extraSources`)
1714
- // must not push the ratio past 1 and break a gate's assumptions. Drives
1715
- // `--min-coverage` and the guidance below.
1716
- const ratio = handlersTotal > 0 ? Math.min(1, handlerIds.size / handlersTotal) : 1
1783
+ // exercised fraction — in `[0,1]` by construction, since every exercised id
1784
+ // is in the inventory. Drives `--min-coverage` and the guidance below.
1785
+ const ratio = handlersTotal > 0 ? handlerIds.size / handlersTotal : 1
1717
1786
  let guidance: ScenarioGuidance | undefined
1718
1787
  if (turnSeqs.size === 0) {
1719
1788
  guidance =
@@ -0,0 +1,81 @@
1
+ import { collectLoopBoundNames } from '../adapters/loop-bound-names.ts'
2
+ import type { ComponentIR } from '../types.ts'
3
+ import type { BindingScope } from './binding-scope.ts'
4
+
5
+ /**
6
+ * Root-prop aliases for template engines that flatten `props.X` to the bare
7
+ * template variable `X` (#3314). A loop that binds the same name (`.map(value
8
+ * => …)`) shadows that variable for its whole body, so an explicit
9
+ * `props.value` inside the row read the ROW's `value` instead of the prop.
10
+ *
11
+ * The adapter assigns each shadowed prop to an alias just before the loop
12
+ * header — where the bare name still means the prop — and an explicit
13
+ * `props.X` read inside the row uses the alias. Only the template syntax
14
+ * of the assignment is per-adapter; which names need one, and their alias
15
+ * name, are decided here once.
16
+ */
17
+
18
+ /**
19
+ * The template variable each prop in `propNames` is aliased to: `__bf_root_<name>`,
20
+ * extended with `_` until it names nothing else the component turns into a
21
+ * template variable — a prop, a local const or function, a signal or memo,
22
+ * any loop binding, or another prop's alias. The `__bf_` namespace is
23
+ * reserved only by convention, so an alias must not overwrite a user prop
24
+ * spelled `__bf_root_value` nor be shadowed by a binding of that name.
25
+ * Computed once per component so the assignment before a loop and every
26
+ * `props.X` read inside it agree on the name.
27
+ */
28
+ export function rootPropAliasNames(ir: ComponentIR, propNames: Iterable<string>): ReadonlyMap<string, string> {
29
+ const { metadata } = ir
30
+ const props = [...propNames]
31
+ const taken = new Set<string>([
32
+ ...props,
33
+ ...metadata.localConstants.map(c => c.name),
34
+ ...metadata.localFunctions.map(f => f.name),
35
+ ...metadata.signals.flatMap(s => (s.setter ? [s.getter, s.setter] : [s.getter])),
36
+ ...metadata.memos.map(m => m.name),
37
+ ...collectLoopBoundNames(ir),
38
+ ])
39
+ const aliases = new Map<string, string>()
40
+ for (const name of props) {
41
+ let alias = `__bf_root_${name}`
42
+ while (taken.has(alias)) alias += '_'
43
+ taken.add(alias)
44
+ aliases.set(name, alias)
45
+ }
46
+ return aliases
47
+ }
48
+
49
+ /**
50
+ * Props the loop row newly shadows, with their aliases: names `row` binds
51
+ * that `outer` did not (an enclosing loop that already bound a name already
52
+ * aliased it, and a re-assignment here would capture that loop's row value)
53
+ * and that are component props (keys of `aliases`). In source order of
54
+ * `row`'s bindings.
55
+ */
56
+ export function rootPropAliasesForLoop(
57
+ outer: BindingScope,
58
+ row: BindingScope,
59
+ aliases: ReadonlyMap<string, string>,
60
+ ): { name: string; alias: string }[] {
61
+ const shadowed: { name: string; alias: string }[] = []
62
+ for (const name of row.boundNames()) {
63
+ const alias = aliases.get(name)
64
+ if (alias !== undefined && !outer.isBound(name)) shadowed.push({ name, alias })
65
+ }
66
+ return shadowed
67
+ }
68
+
69
+ /**
70
+ * The template variable an explicit `props.<name>` read resolves to at a
71
+ * position with `scope`: the alias (from `rootPropAliasNames`) while a loop
72
+ * binding shadows `name`, else `name` itself.
73
+ */
74
+ export function rootPropReadName(
75
+ name: string,
76
+ scope: BindingScope,
77
+ aliases: ReadonlyMap<string, string>,
78
+ ): string {
79
+ if (!scope.isBound(name)) return name
80
+ return aliases.get(name) ?? name
81
+ }