@barefootjs/jsx 0.37.1 → 0.38.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.
Files changed (114) hide show
  1. package/dist/adapters/env-signal.d.ts +0 -8
  2. package/dist/adapters/env-signal.d.ts.map +1 -1
  3. package/dist/adapters/interface.d.ts +12 -0
  4. package/dist/adapters/interface.d.ts.map +1 -1
  5. package/dist/analyzer.d.ts +31 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/builtin-lowering-plugins.d.ts.map +1 -1
  8. package/dist/compiler.d.ts.map +1 -1
  9. package/dist/component-root-scope-comment.d.ts +36 -0
  10. package/dist/component-root-scope-comment.d.ts.map +1 -0
  11. package/dist/errors.d.ts +3 -0
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/event-handler-name.d.ts +13 -0
  14. package/dist/event-handler-name.d.ts.map +1 -0
  15. package/dist/expression-parser.d.ts +9 -0
  16. package/dist/expression-parser.d.ts.map +1 -1
  17. package/dist/format-date-refusal.d.ts +37 -0
  18. package/dist/format-date-refusal.d.ts.map +1 -0
  19. package/dist/index.d.ts +4 -2
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2421 -1787
  22. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-branch-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/lazy-row-eligibility.d.ts +1 -1
  29. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +57 -12
  30. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/control-flow/shared.d.ts +44 -3
  32. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +7 -5
  34. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/emit-reactive.d.ts +43 -2
  36. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/reactivity.d.ts +9 -1
  39. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/source-map.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +26 -0
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/jsx-to-ir.d.ts.map +1 -1
  44. package/dist/opaque-local-accessor.d.ts +27 -0
  45. package/dist/opaque-local-accessor.d.ts.map +1 -0
  46. package/dist/to-locale-date-lowering.d.ts +7 -4
  47. package/dist/to-locale-date-lowering.d.ts.map +1 -1
  48. package/dist/types.d.ts +53 -17
  49. package/dist/types.d.ts.map +1 -1
  50. package/package.json +2 -2
  51. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +724 -4564
  52. package/src/__tests__/binding-scope-ratchet.test.ts +21 -10
  53. package/src/__tests__/branch-local-in-raw-capture.test.ts +1 -1
  54. package/src/__tests__/branch-local-same-name-collision.test.ts +9 -9
  55. package/src/__tests__/client-js-generation.test.ts +175 -0
  56. package/src/__tests__/component-root-scope-comment.test.ts +106 -0
  57. package/src/__tests__/doc-examples.test.ts +12 -22
  58. package/src/__tests__/event-handler-name.test.ts +74 -0
  59. package/src/__tests__/flatmap-segments.test.ts +11 -9
  60. package/src/__tests__/format-date-refusal.test.ts +134 -0
  61. package/src/__tests__/fragment-wrapped-conditional-return-branch.test.ts +132 -0
  62. package/src/__tests__/hydrate-template.test.ts +9 -1
  63. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +2 -2
  64. package/src/__tests__/issue-3009-loop-branch-ref.test.ts +2 -2
  65. package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +213 -0
  66. package/src/__tests__/issue-3113-init-fn-name-collision.test.ts +133 -0
  67. package/src/__tests__/jsx-return-type-assertion.test.ts +2 -2
  68. package/src/__tests__/lazy-row-eligibility.test.ts +5 -4
  69. package/src/__tests__/loop-row-child-children-reactive-attrs.test.ts +108 -0
  70. package/src/__tests__/loop-row-child-text-children-markers.test.ts +158 -0
  71. package/src/__tests__/opaque-local-accessor.test.ts +90 -0
  72. package/src/__tests__/profiler-e2e.test.ts +13 -8
  73. package/src/__tests__/ref-attr-absent-at-ssr.test.ts +472 -0
  74. package/src/__tests__/ssr-portal-ref-callback.test.ts +217 -0
  75. package/src/adapters/env-signal.ts +2 -21
  76. package/src/adapters/interface.ts +13 -0
  77. package/src/analyzer.ts +31 -27
  78. package/src/builtin-lowering-plugins.ts +0 -2
  79. package/src/compiler.ts +24 -0
  80. package/src/component-root-scope-comment.ts +59 -0
  81. package/src/errors.ts +44 -1
  82. package/src/event-handler-name.ts +14 -0
  83. package/src/expression-parser.ts +41 -17
  84. package/src/format-date-refusal.ts +266 -0
  85. package/src/index.ts +12 -2
  86. package/src/ir-to-client-js/child-components.ts +8 -3
  87. package/src/ir-to-client-js/collect-elements.ts +27 -13
  88. package/src/ir-to-client-js/control-flow/plan/build-branch-loop.ts +2 -4
  89. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +67 -5
  90. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +3 -6
  91. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +2 -1
  92. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +23 -11
  93. package/src/ir-to-client-js/control-flow/plan/lazy-row-eligibility.ts +3 -3
  94. package/src/ir-to-client-js/control-flow/plan/loop.ts +51 -10
  95. package/src/ir-to-client-js/control-flow/shared.ts +78 -5
  96. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +25 -12
  97. package/src/ir-to-client-js/emit-reactive.ts +140 -10
  98. package/src/ir-to-client-js/emit-registration.ts +2 -2
  99. package/src/ir-to-client-js/generate-init.ts +2 -2
  100. package/src/ir-to-client-js/html-template.ts +41 -19
  101. package/src/ir-to-client-js/index.ts +4 -3
  102. package/src/ir-to-client-js/reactivity.ts +20 -16
  103. package/src/ir-to-client-js/source-map.ts +2 -1
  104. package/src/ir-to-client-js/utils.ts +34 -0
  105. package/src/jsx-to-ir.ts +737 -49
  106. package/src/opaque-local-accessor.ts +44 -0
  107. package/src/rich-type-refusal.ts +1 -1
  108. package/src/to-locale-date-lowering.ts +7 -4
  109. package/src/types.ts +51 -15
  110. package/dist/format-date-lowering.d.ts +0 -30
  111. package/dist/format-date-lowering.d.ts.map +0 -1
  112. package/src/__tests__/create-selector.test.ts +0 -124
  113. package/src/__tests__/format-date-lowering.test.ts +0 -125
  114. package/src/format-date-lowering.ts +0 -55
package/src/jsx-to-ir.ts CHANGED
@@ -32,7 +32,7 @@ import {
32
32
  type PreambleSegment,
33
33
  type PreambleRegionSource,
34
34
  type PreambleValueDeclaration,
35
- tsxSourceText,
35
+ tsxSourceText, type TsxSourceText,
36
36
  type SourceLocation,
37
37
  type TypeInfo,
38
38
  type OriginInfo,
@@ -54,6 +54,7 @@ import {
54
54
  } from './prop-rewrite.ts'
55
55
  import { boundPropLocalNames, buildPropAliasMap, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
56
56
  import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
57
+ import { walkIR } from './ir-to-client-js/walker.ts'
57
58
  import { resolveFreeRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
58
59
  import { computeFileScope } from './ir-to-client-js/component-scope.ts'
59
60
  import { createTemplateAwareStringProtector } from './ir-to-client-js/html-template.ts'
@@ -61,13 +62,14 @@ import { extractFreeIdentifiersFromText } from './ir-to-client-js/csr-substitute
61
62
  import { datePlugin, DATE_METHODS } from './date-lowering.ts'
62
63
  import { toLocaleDatePlugin, foldedArgToClientJs } from './to-locale-date-lowering.ts'
63
64
  import type { LoweringMatcher } from './lowering-registry.ts'
64
- import { extractFreeIdentifiersFromNode, initializerShapeContainsJsx, extractMultiReturnJsxBranches, type MultiReturnJsxBranches } from './analyzer.ts'
65
+ import { extractFreeIdentifiersFromNode, initializerShapeContainsJsx, extractMultiReturnJsxBranches, rootIdentifierOf, type MultiReturnJsxBranches } from './analyzer.ts'
65
66
  import { iterateJsTokens, replaceInExprContexts } from './scanner/js-scanner.ts'
66
67
  import { reconstructAsSegments } from './strip-types.ts'
67
68
  import { templatePartsToJsExpr } from './template-parts.ts'
68
69
  import { toHTMLAttrName, decodeEntities, BF_KEY, keyAttrName } from '@barefootjs/shared'
69
70
  import { BindingScope } from './scope/binding-scope.ts'
70
71
  import { identifierPattern, identifierCallPattern } from './identifier-pattern.ts'
72
+ import { isEventHandlerName } from './event-handler-name.ts'
71
73
 
72
74
  // =============================================================================
73
75
  // Transform Context
@@ -236,6 +238,14 @@ interface TransformContext {
236
238
  * aliased `import { Async as Boundary }` maps `<Boundary>` to the built-in.
237
239
  */
238
240
  _clientBuiltinTags?: Map<string, ClientBuiltinTag>
241
+ /** Lazily computed local name → export name of every `@barefootjs/client` value import. */
242
+ _clientValueImports?: ReadonlyMap<string, string>
243
+ /**
244
+ * BF063 candidates keyed by element position (`line:column`), recorded
245
+ * while transforming and reported by `reportRefAttrsAbsentAtSsr` once the
246
+ * IR shows which elements SSR renders.
247
+ */
248
+ _refAttrAbsences?: Map<string, RefAttrAbsence>
239
249
  /**
240
250
  * Cached `datePlugin` matcher (#2292), bound once to this component's
241
251
  * metadata. `undefined` = not yet computed; `null` = computed and
@@ -284,6 +294,53 @@ function hasLeadingClientDirective(expr: ts.Expression, sourceFile: ts.SourceFil
284
294
  return false
285
295
  }
286
296
 
297
+ /** Whether `node`'s subtree renders any child component (a `component` IR node). */
298
+ function irSubtreeRendersComponent(node: IRNode): boolean {
299
+ let found = false
300
+ walkIR(node, null, {
301
+ component: () => { found = true },
302
+ })
303
+ return found
304
+ }
305
+
306
+ /**
307
+ * #3063: refuse a fragment-wrapped branch of a multi-return client
308
+ * component loudly instead of silently shipping a branch whose events
309
+ * never bind after hydrating existing SSR markup (see
310
+ * `ErrorCodes.FRAGMENT_WRAPPED_CONDITIONAL_RETURN_BRANCH`'s docstring for
311
+ * the mechanism). Called once per branch from `buildIfStatementChain`,
312
+ * right after that branch transforms — `rawNode` is the branch's own raw
313
+ * JSX return expression (needed for the `/* @client *\/` escape check;
314
+ * `transformNode`'s output doesn't retain a pointer back to it), `node` is
315
+ * what that transform produced.
316
+ *
317
+ * Fires when the component hydrates this branch: either it is a
318
+ * `'use client'` component, or the fragment branch itself renders a child
319
+ * component. In the second case a non-client parent still gets
320
+ * `needsInit` and an `initChild` for that child, which runs only if the
321
+ * branch's scope is claimed, so the child's own events never bind either.
322
+ * A non-client component whose fragment branch renders no component has
323
+ * nothing to initialize there and compiles as before. The check is
324
+ * branch-local on purpose: a child component in a DIFFERENT branch doesn't
325
+ * make this branch's missing claim observable.
326
+ */
327
+ function checkFragmentWrappedConditionalReturnBranch(
328
+ node: IRNode | null,
329
+ rawNode: ts.Expression | null | undefined,
330
+ ctx: TransformContext
331
+ ): void {
332
+ if (!node || node.type !== 'fragment' || !(node as IRFragment).needsScopeComment) return
333
+ if (!ctx.analyzer.hasUseClientDirective && !irSubtreeRendersComponent(node)) return
334
+ if (!rawNode || hasLeadingClientDirective(rawNode, ctx.sourceFile)) return
335
+ ctx.analyzer.errors.push(
336
+ createError(ErrorCodes.FRAGMENT_WRAPPED_CONDITIONAL_RETURN_BRANCH, node.loc, {
337
+ suggestion: {
338
+ message: 'Add /* @client */ immediately before this branch\'s JSX to compile it anyway.',
339
+ },
340
+ })
341
+ )
342
+ }
343
+
287
344
  /**
288
345
  * The set of known reactive getter names (signal accessors + memo names) for the
289
346
  * component, built once and cached on `ctx`. These reads are idempotent within a
@@ -1126,19 +1183,20 @@ function resolveRootKeyAttr(node: IRNode | null): void {
1126
1183
  }
1127
1184
 
1128
1185
  export function jsxToIR(analyzer: AnalyzerContext): IRNode | null {
1129
- const root = buildIRRoot(analyzer)
1186
+ const ctx = createTransformContext(analyzer)
1187
+ const root = buildIRRoot(analyzer, ctx)
1130
1188
  if (root) {
1189
+ reportRefAttrsAbsentAtSsr(root, ctx)
1131
1190
  attachParsedExpressions(root, analyzer)
1132
1191
  resolveRootKeyAttr(root)
1133
1192
  }
1134
1193
  return root
1135
1194
  }
1136
1195
 
1137
- function buildIRRoot(analyzer: AnalyzerContext): IRNode | null {
1196
+ function buildIRRoot(analyzer: AnalyzerContext, ctx: TransformContext): IRNode | null {
1138
1197
  // If there are conditional returns (if statements with JSX returns),
1139
1198
  // build an if-statement chain instead of a single node
1140
1199
  if (analyzer.conditionalReturns.length > 0) {
1141
- const ctx = createTransformContext(analyzer)
1142
1200
  // #2463: a chain whose conditions are ALL reactive (signal/memo reads)
1143
1201
  // is semantically the root ternary, and the IRIfStatement contract
1144
1202
  // ("client JS handles all branches and switches at runtime") demands
@@ -1174,7 +1232,6 @@ function buildIRRoot(analyzer: AnalyzerContext): IRNode | null {
1174
1232
 
1175
1233
  if (!analyzer.jsxReturn) return null
1176
1234
 
1177
- const ctx = createTransformContext(analyzer)
1178
1235
  const jsxReturn = analyzer.jsxReturn
1179
1236
 
1180
1237
  // Direct JSX return — the IR root is an `IRElement` / `IRFragment` that
@@ -1369,21 +1426,34 @@ function transformNode(node: ts.Node, ctx: TransformContext): IRNode | null {
1369
1426
  function clientBuiltinTags(ctx: TransformContext): Map<string, ClientBuiltinTag> {
1370
1427
  if (ctx._clientBuiltinTags) return ctx._clientBuiltinTags
1371
1428
  const map = new Map<string, ClientBuiltinTag>()
1429
+ for (const [local, name] of clientValueImports(ctx)) {
1430
+ if (isClientBuiltinName(name)) map.set(local, name)
1431
+ }
1432
+ ctx._clientBuiltinTags = map
1433
+ return map
1434
+ }
1435
+
1436
+ /**
1437
+ * Local name → export name of every named VALUE import from
1438
+ * `@barefootjs/client` (`import { createEffect as ce }` → `ce` →
1439
+ * `createEffect`), from the analyzer's import metadata. The one answer to
1440
+ * "is this identifier that client export" for import-scoped recognition — a
1441
+ * same-named local declaration never matches. Value imports only: `import
1442
+ * type { Async }` / `import { type Async }` bring no value binding into scope
1443
+ * (and are never runtime imports) (#1915 review). Memoized on `ctx`; the
1444
+ * import list is fixed for the compile.
1445
+ */
1446
+ function clientValueImports(ctx: TransformContext): ReadonlyMap<string, string> {
1447
+ if (ctx._clientValueImports) return ctx._clientValueImports
1448
+ const map = new Map<string, string>()
1372
1449
  for (const imp of ctx.analyzer.imports) {
1373
- // Require a *value* import: the tag is used as a JSX value, and the design
1374
- // is import-value-required. `import type { Async }` brings no value binding
1375
- // into scope (and is never a runtime import), so it does not scope the
1376
- // built-in — `<Async>` then falls through to BF054 (#1915 review).
1377
1450
  if (imp.source !== CLIENT_BUILTIN_SOURCE || imp.isTypeOnly) continue
1378
1451
  for (const spec of imp.specifiers) {
1379
- // Skip per-specifier `import { type Async }` — no value binding.
1380
1452
  if (spec.isDefault || spec.isNamespace || spec.isTypeOnly) continue
1381
- if (isClientBuiltinName(spec.name)) {
1382
- map.set(spec.alias ?? spec.name, spec.name)
1383
- }
1453
+ map.set(spec.alias ?? spec.name, spec.name)
1384
1454
  }
1385
1455
  }
1386
- ctx._clientBuiltinTags = map
1456
+ ctx._clientValueImports = map
1387
1457
  return map
1388
1458
  }
1389
1459
 
@@ -1694,7 +1764,7 @@ function transformHtmlElement(
1694
1764
  ctx: TransformContext,
1695
1765
  tagName: string
1696
1766
  ): IRElement {
1697
- const { attrs, events, ref } = processAttributes(
1767
+ const { attrs, events, ref, ssrPortalOwnerScope } = processAttributes(
1698
1768
  node.openingElement.attributes,
1699
1769
  ctx
1700
1770
  )
@@ -1726,6 +1796,7 @@ function transformHtmlElement(
1726
1796
  children,
1727
1797
  slotId,
1728
1798
  needsScope,
1799
+ ...(ssrPortalOwnerScope && { ssrPortalOwnerScope }),
1729
1800
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
1730
1801
  }
1731
1802
  }
@@ -1759,7 +1830,7 @@ function transformSelfClosingElement(
1759
1830
  return transformSelfClosingComponent(node, ctx, resolved ?? tagName)
1760
1831
  }
1761
1832
 
1762
- const { attrs, events, ref } = processAttributes(node.attributes, ctx)
1833
+ const { attrs, events, ref, ssrPortalOwnerScope } = processAttributes(node.attributes, ctx)
1763
1834
  const selfClosingChildren: IRNode[] = []
1764
1835
  lowerFormControlValueSsr(tagName, attrs, selfClosingChildren)
1765
1836
 
@@ -1779,6 +1850,7 @@ function transformSelfClosingElement(
1779
1850
  children: selfClosingChildren,
1780
1851
  slotId,
1781
1852
  needsScope,
1853
+ ...(ssrPortalOwnerScope && { ssrPortalOwnerScope }),
1782
1854
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
1783
1855
  }
1784
1856
  }
@@ -4291,7 +4363,7 @@ function leafIsWirelessElement(el: ts.JsxElement | ts.JsxSelfClosingElement): bo
4291
4363
  if (ts.isJsxSpreadAttribute(attr)) { ok = false; return }
4292
4364
  if (ts.isJsxAttribute(attr)) {
4293
4365
  const name = attr.name.getText()
4294
- if (isEventHandlerAttrName(name)) { ok = false; return }
4366
+ if (isEventHandlerName(name)) { ok = false; return }
4295
4367
  }
4296
4368
  }
4297
4369
  }
@@ -5364,7 +5436,7 @@ function transformMapCall(
5364
5436
  .map((p) => ({
5365
5437
  name: p.name,
5366
5438
  value: p.value,
5367
- isEventHandler: p.name.startsWith('on') && p.name.length > 2,
5439
+ isEventHandler: isEventHandlerName(p.name),
5368
5440
  })),
5369
5441
  children: comp.children,
5370
5442
  }
@@ -5552,11 +5624,16 @@ function buildFlatMapCallback(
5552
5624
  // the map-preamble collector.
5553
5625
  const leafSpans: Array<{ start: number; end: number }> = []
5554
5626
  const leafIrs: IRNode[] = []
5627
+ const leafKeyAttrs: ts.JsxAttribute[] = []
5555
5628
  let refusalNode: ts.Node | undefined
5556
5629
  const collectJsx = (n: ts.Node, underTemplate: boolean): void => {
5557
5630
  if (ts.isJsxElement(n) || ts.isJsxSelfClosingElement(n) || ts.isJsxFragment(n)) {
5558
5631
  if (underTemplate) refusalNode ??= n
5559
5632
  leafSpans.push({ start: n.getStart(ctx.sourceFile), end: n.getEnd() })
5633
+ if (!ts.isJsxFragment(n)) {
5634
+ const keyAttr = findKeyJsxAttribute(ts.isJsxElement(n) ? n.openingElement : n)
5635
+ if (keyAttr) leafKeyAttrs.push(keyAttr)
5636
+ }
5560
5637
  const ir = transformNode(n as ts.Expression, ctx)
5561
5638
  leafIrs.push(ir ?? { type: 'text', value: '', loc: getSourceLocation(n, ctx.sourceFile, ctx.filePath) })
5562
5639
  return
@@ -5662,8 +5739,50 @@ function buildFlatMapCallback(
5662
5739
  return {
5663
5740
  params: `(${paramsText})`,
5664
5741
  segments,
5665
- rawBody: tsxSourceText(body.getText(ctx.sourceFile)),
5742
+ rawBody: flatMapRawBodyWithLeafKeys(body, leafKeyAttrs, ctx.sourceFile),
5743
+ }
5744
+ }
5745
+
5746
+ /**
5747
+ * The raw TSX body a JSX-runtime SSR adapter evaluates, with every keyed
5748
+ * leaf's reconciliation attribute made explicit: ` data-key={String(<key>)}`
5749
+ * spliced in right after the leaf's own `key={…}` attribute. A JSX runtime
5750
+ * strips `key` from the rendered HTML, so without this the server row
5751
+ * carries no `data-key` while the client runtime stamps one on every row it
5752
+ * adopts or creates (`mapArray`'s `BF_KEY` default — the descriptor path
5753
+ * never passes a depth-suffixed name) — a pre-/post-hydration divergence on
5754
+ * exactly the attribute reconciliation keys on. `String(...)` matches the
5755
+ * client's `String(__bfD.k ?? __bfI)` stamping, and the runtime escapes the
5756
+ * value like any other attribute. Position-based splice over the AST's own
5757
+ * attribute spans — the body text is never pattern-matched.
5758
+ */
5759
+ function flatMapRawBodyWithLeafKeys(
5760
+ body: ts.Block | ts.Expression,
5761
+ leafKeyAttrs: readonly ts.JsxAttribute[],
5762
+ sourceFile: ts.SourceFile,
5763
+ ): TsxSourceText {
5764
+ const text = body.getText(sourceFile)
5765
+ if (leafKeyAttrs.length === 0) return tsxSourceText(text)
5766
+ const bodyStart = body.getStart(sourceFile)
5767
+ const insertions = leafKeyAttrs
5768
+ .map((attr) => {
5769
+ const init = attr.initializer
5770
+ const keyText = init === undefined
5771
+ ? 'true'
5772
+ : ts.isJsxExpression(init)
5773
+ ? (init.expression?.getText(sourceFile) ?? 'undefined')
5774
+ : init.getText(sourceFile)
5775
+ return { at: attr.getEnd() - bodyStart, text: ` ${BF_KEY}={String(${keyText})}` }
5776
+ })
5777
+ .sort((a, b) => a.at - b.at)
5778
+ let out = ''
5779
+ let cursor = 0
5780
+ for (const { at, text: ins } of insertions) {
5781
+ out += text.slice(cursor, at) + ins
5782
+ cursor = at
5666
5783
  }
5784
+ out += text.slice(cursor)
5785
+ return tsxSourceText(out)
5667
5786
  }
5668
5787
 
5669
5788
  /**
@@ -6092,7 +6211,7 @@ function neutralPreambleDeclarations(
6092
6211
  // JSX attribute position, e.g. `const handleClick = () => {...}`) has
6093
6212
  // no template-expression form on any backend — no DSL here has a
6094
6213
  // callable value. But every adapter's own SSR component-prop builder
6095
- // already skips an event-handler prop (`isEventHandlerAttrName`)
6214
+ // already skips an event-handler prop (`isEventHandlerName`)
6096
6215
  // outright, so a name read ONLY that way needs no SSR representation
6097
6216
  // at all — elide the declaration instead of refusing the whole
6098
6217
  // preamble. The client-JS preamble (`segments`, not `declarations`)
@@ -6131,7 +6250,7 @@ function isFunctionLiteral(node: ts.Expression): boolean {
6131
6250
  * Whether every read of `name` in `bodyStatements`, other than its own
6132
6251
  * binding site, sits inside an event-handler `JsxAttribute`'s
6133
6252
  * (`onClick`/`onInput`/...) value — i.e. `name={<ident>}` where the
6134
- * attribute's own name passes {@link isEventHandlerAttrName}, the exact
6253
+ * attribute's own name passes {@link isEventHandlerName}, the exact
6135
6254
  * predicate every DSL adapter's own SSR prop-builder already uses to skip an
6136
6255
  * event-handler prop (e.g. `packages/adapter-jinja/src/adapter/
6137
6256
  * jinja-adapter.ts`'s `renderComponent`, `packages/adapter-go-template/...`'s
@@ -6165,7 +6284,7 @@ function everyReadIsEventHandlerPropValue(name: string, bodyStatements: readonly
6165
6284
  ts.isJsxAttribute(attr) &&
6166
6285
  attr.initializer === jsxExpr &&
6167
6286
  ts.isIdentifier(attr.name) &&
6168
- isEventHandlerAttrName(attr.name.text)
6287
+ isEventHandlerName(attr.name.text)
6169
6288
  if (!isEventHandlerAttrValue) return true
6170
6289
  }
6171
6290
  }
@@ -6174,18 +6293,6 @@ function everyReadIsEventHandlerPropValue(name: string, bodyStatements: readonly
6174
6293
  return !bodyStatements.some(findDisallowedRead)
6175
6294
  }
6176
6295
 
6177
- /**
6178
- * Whether a JSX attribute name is an event handler (`onClick`, `onInput`,
6179
- * ...) rather than a plain attribute/prop. Shared by every site in this file
6180
- * that needs the same call: native-element attribute extraction (routes into
6181
- * `IREvent`, never rendered HTML), the preamble-verbatim-leaf wiring guard,
6182
- * and {@link everyReadIsEventHandlerPropValue}'s elision safety check — one
6183
- * decision, one implementation, per CLAUDE.md.
6184
- */
6185
- function isEventHandlerAttrName(name: string): boolean {
6186
- return /^on[A-Z]/.test(name)
6187
- }
6188
-
6189
6296
  /** Drop the trailing separator space from the final js segment. */
6190
6297
  function trimPreambleSegments(segments: PreambleSegment[]): PreambleSegment[] {
6191
6298
  const last = segments[segments.length - 1]
@@ -6326,7 +6433,7 @@ function collectNestedComponents(nodes: IRNode[]): IRLoopChildComponent[] {
6326
6433
  .map(p => ({
6327
6434
  name: p.name,
6328
6435
  value: p.value,
6329
- isEventHandler: p.name.startsWith('on') && p.name.length > 2,
6436
+ isEventHandler: isEventHandlerName(p.name),
6330
6437
  })),
6331
6438
  children: node.children,
6332
6439
  loopDepth,
@@ -6375,6 +6482,8 @@ interface ProcessedAttributes {
6375
6482
  attrs: IRAttribute[]
6376
6483
  events: IREvent[]
6377
6484
  ref: string | null
6485
+ /** See {@link isSsrPortalRefCallback}. */
6486
+ ssrPortalOwnerScope: boolean
6378
6487
  }
6379
6488
 
6380
6489
  // Spread expansion: shared between HTML attrs and component props.
@@ -6510,9 +6619,12 @@ function processAttributes(
6510
6619
  const attrs: IRAttribute[] = []
6511
6620
  const events: IREvent[] = []
6512
6621
  let ref: string | null = null
6622
+ let refExpr: ts.Expression | null = null
6623
+ let hasSpread = false
6513
6624
 
6514
6625
  for (const attr of attributes.properties) {
6515
6626
  if (ts.isJsxSpreadAttribute(attr)) {
6627
+ hasSpread = true
6516
6628
  attrs.push(...expandSpreadAttribute(attr, ctx))
6517
6629
  continue
6518
6630
  }
@@ -6529,6 +6641,7 @@ function processAttributes(
6529
6641
  if (attr.initializer && ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
6530
6642
  reportJsxBranchLocalInCallback(attr.initializer.expression, ctx)
6531
6643
  ref = ctx.getJS(attr.initializer.expression)
6644
+ refExpr = attr.initializer.expression
6532
6645
  }
6533
6646
  continue
6534
6647
  }
@@ -6537,7 +6650,7 @@ function processAttributes(
6537
6650
  // they're wired up at hydration time (delegated event registration) and
6538
6651
  // must not leak into rendered HTML. The DOM event name is lowercase
6539
6652
  // (`click`, not `Click`), so strip the `on` prefix and downcase.
6540
- if (isEventHandlerAttrName(rawName)) {
6653
+ if (isEventHandlerName(rawName)) {
6541
6654
  if (attr.initializer && ts.isJsxExpression(attr.initializer) && attr.initializer.expression) {
6542
6655
  const eventName = rawName.slice(2).toLowerCase()
6543
6656
  reportJsxBranchLocalInCallback(attr.initializer.expression, ctx)
@@ -6600,7 +6713,537 @@ function processAttributes(
6600
6713
  })
6601
6714
  }
6602
6715
 
6603
- return { attrs, events, ref }
6716
+ // The ref callback is resolved once, for both the SSR-portal recognition
6717
+ // and BF063. BF063 runs after the loop so it sees every attribute this
6718
+ // element's JSX renders, whether `ref` came before or after it.
6719
+ let ssrPortalOwnerScope = false
6720
+ if (refExpr) {
6721
+ const refCallback = resolveRefCallback(refExpr)
6722
+ ssrPortalOwnerScope = isSsrPortalRefCallback(refCallback)
6723
+ if (!hasSpread) recordRefAttrsAbsentAtSsr(refExpr, refCallback, attributes, attrs, ctx)
6724
+ }
6725
+
6726
+ return { attrs, events, ref, ssrPortalOwnerScope }
6727
+ }
6728
+
6729
+ // =============================================================================
6730
+ // Ref-written attribute absent at SSR (BF063)
6731
+ // =============================================================================
6732
+
6733
+ /**
6734
+ * BF063: a `ref` callback that unconditionally writes an attribute at mount
6735
+ * which the element's own JSX never renders. A `ref` callback never runs at
6736
+ * SSR, so the server HTML always lacks that attribute and the first client
6737
+ * pass adds it — the pre- and post-hydration DOM differ, a visible snap at
6738
+ * the hydrate boundary.
6739
+ *
6740
+ * Deliberately narrow, so it only fires where the divergence is certain:
6741
+ *
6742
+ * - The callback resolves statically (`resolveRefCallback`): an inline
6743
+ * arrow / function expression, or a named local function. Anything else
6744
+ * — an imported helper, a prop, a call result — is opaque.
6745
+ * - Only mount-time writes to the callback's own element parameter count
6746
+ * (see `collectMountAttrWrites`), and only those no later removal
6747
+ * cancels.
6748
+ * - An attribute the JSX renders in any form is skipped: SSR emits it, and
6749
+ * whether an effect's first run agrees with the rendered value is not
6750
+ * decidable here — `data-state="closed"` overwritten by an effect that
6751
+ * computes `closed` on mount is the correct, common case.
6752
+ * - An element with a spread (`{...props}`, which may render the
6753
+ * attribute) is skipped by the caller, and a leading `/* @client *\/` on
6754
+ * the ref expression opts out (the author accepts the attribute
6755
+ * appearing only after hydration).
6756
+ *
6757
+ * Whether SSR renders the element at all is only known once the IR is built
6758
+ * (a client-only conditional or loop around it), so this records a
6759
+ * candidate and `reportRefAttrsAbsentAtSsr` decides.
6760
+ */
6761
+ function recordRefAttrsAbsentAtSsr(
6762
+ refExpr: ts.Expression,
6763
+ callback: RefCallback | undefined,
6764
+ attributes: ts.JsxAttributes,
6765
+ attrs: readonly IRAttribute[],
6766
+ ctx: TransformContext,
6767
+ ): void {
6768
+ if (!callback?.param || hasLeadingClientDirective(refExpr, ctx.sourceFile)) return
6769
+ const rendered = new Set(attrs.map(a => a.name.toLowerCase()))
6770
+ const writes = collectMountAttrWrites(callback.body, callback.param, ctx).filter(w => !rendered.has(w.name))
6771
+ if (writes.length === 0) return
6772
+ const element = attributes.parent
6773
+ const key = sourcePositionKey(getSourceLocation(element, ctx.sourceFile, ctx.filePath))
6774
+ ctx._refAttrAbsences ??= new Map()
6775
+ ctx._refAttrAbsences.set(key, { element: `<${element.tagName.getText(ctx.sourceFile)}> at ${key}`, writes })
6776
+ }
6777
+
6778
+ /** `line:column` of a location's start — the `-->` notation `formatError` prints. */
6779
+ function sourcePositionKey(loc: SourceLocation): string {
6780
+ return `${loc.start.line}:${loc.start.column}`
6781
+ }
6782
+
6783
+ /**
6784
+ * Report the candidates `recordRefAttrsAbsentAtSsr` recorded on elements SSR
6785
+ * actually renders. An element inside a client-only conditional or loop (a
6786
+ * `/* @client *\/` child, a module-level client signal, an auto-deferred
6787
+ * reactive-brand condition — whatever set the IR's `clientOnly`) never
6788
+ * reaches the server HTML, so there is nothing for hydration to diverge
6789
+ * from. One error per write site: a handler shared by several elements is
6790
+ * reported once, naming every element that lacks the attribute.
6791
+ */
6792
+ function reportRefAttrsAbsentAtSsr(root: IRNode, ctx: TransformContext): void {
6793
+ const pending = ctx._refAttrAbsences
6794
+ if (!pending) return
6795
+ const bySite = new Map<string, { write: RefAttrWrite; elements: string[] }>()
6796
+ walkIR<boolean>(root, false, {
6797
+ element: ({ node, scope: clientOnly, descend }) => {
6798
+ const key = sourcePositionKey(node.loc)
6799
+ const absence = clientOnly ? undefined : pending.get(key)
6800
+ if (absence) {
6801
+ // A source element transformed more than once (an inlined JSX
6802
+ // helper) is still one element.
6803
+ pending.delete(key)
6804
+ for (const write of absence.writes) {
6805
+ const site = `${write.node.getStart(ctx.sourceFile)}:${write.name}`
6806
+ const group = bySite.get(site) ?? { write, elements: [] }
6807
+ group.elements.push(absence.element)
6808
+ bySite.set(site, group)
6809
+ }
6810
+ }
6811
+ descend()
6812
+ },
6813
+ conditional: ({ node, scope, descend }) => descend(scope || !!node.clientOnly),
6814
+ loop: ({ node, scope, descend }) => descend(scope || !!node.clientOnly),
6815
+ async: ({ node, walk, descend }) => {
6816
+ walk(node.fallback)
6817
+ descend()
6818
+ },
6819
+ component: ({ descend, descendJsxChildren }) => {
6820
+ descend()
6821
+ descendJsxChildren()
6822
+ },
6823
+ })
6824
+ for (const { write, elements } of bySite.values()) {
6825
+ ctx.analyzer.errors.push(
6826
+ createError(ErrorCodes.REF_ATTR_ABSENT_AT_SSR, getSourceLocation(write.node, ctx.sourceFile, ctx.filePath), {
6827
+ message:
6828
+ `The ref callback writes '${write.name}' on mount, but the JSX of ${elements.join(' and ')} never renders it. ` +
6829
+ 'A ref callback never runs at SSR, so the server HTML lacks the attribute and hydration adds it — ' +
6830
+ 'the DOM visibly changes at the hydrate boundary.',
6831
+ suggestion: {
6832
+ message:
6833
+ `Render '${write.name}' in the element's JSX from props or signals (e.g. \`${write.name}={…}\`) so SSR ` +
6834
+ 'and hydration agree — the ref may keep writing it afterwards. Or add /* @client */ before the ref ' +
6835
+ 'expression to accept the attribute appearing only after hydration.',
6836
+ escape: [{ kind: 'rewrite' }, { kind: 'client-directive' }],
6837
+ },
6838
+ }),
6839
+ )
6840
+ }
6841
+ }
6842
+
6843
+ /** A BF063 candidate awaiting `reportRefAttrsAbsentAtSsr`. */
6844
+ interface RefAttrAbsence {
6845
+ /** `<tag> at line:column`, naming the element in the diagnostic. */
6846
+ element: string
6847
+ /** Mount-time writes of attributes this element's JSX never renders. */
6848
+ writes: RefAttrWrite[]
6849
+ }
6850
+
6851
+ interface RefAttrWrite {
6852
+ /** Lower-cased HTML attribute name (`data-*` for a `dataset` write). */
6853
+ name: string
6854
+ node: ts.Node
6855
+ }
6856
+
6857
+ /** Mount-time primitives: both run their callback synchronously on creation. */
6858
+ const MOUNT_TIME_PRIMITIVES: ReadonlySet<string> = new Set(['createEffect', 'onMount'])
6859
+
6860
+ /**
6861
+ * The writes to `param` in a ref body that are certain to have happened, and
6862
+ * not been undone, when the ref's mount-time run ends — first write per
6863
+ * attribute, in order.
6864
+ *
6865
+ * The run is the ref body's top-level statements plus, inline at their call
6866
+ * position, the top-level statements of a `createEffect` / `onMount` callback
6867
+ * that is itself a top-level statement of the ref body (both run
6868
+ * synchronously on creation). Within it:
6869
+ *
6870
+ * - A write is a top-level `param.setAttribute('<lit>', …)`,
6871
+ * `param.dataset.<key> = …` or `param.dataset['<key>'] = …`; writes
6872
+ * anywhere else (under an `if`, in a listener, a timer, any closure) may
6873
+ * never run on mount and are ignored.
6874
+ * - A top-level `param.removeAttribute('<lit>')` / `delete
6875
+ * param.dataset.<key>` cancels the earlier write; a removal under an
6876
+ * `if`, a loop, … makes it uncertain, so cancels it too.
6877
+ * - A statement holding a `return` / `throw` of its function (an early-exit
6878
+ * guard, a `try` / loop / `switch` that can return) may skip everything
6879
+ * after it, so collection stops there — for the whole run, since a
6880
+ * `throw` in a nested callback propagates out of the ref.
6881
+ * - A body that redeclares `param` (a `const` / `var` / `function` /
6882
+ * destructuring, or a nested callback parameter) writes some other
6883
+ * node, so contributes nothing.
6884
+ */
6885
+ function collectMountAttrWrites(body: ts.ConciseBody, param: string, ctx: TransformContext): RefAttrWrite[] {
6886
+ const live = new Map<string, RefAttrWrite>()
6887
+ const apply = (effect: RefAttrEffect): void => {
6888
+ if (effect.kind === 'remove') live.delete(effect.name)
6889
+ else if (!live.has(effect.name)) live.set(effect.name, effect)
6890
+ }
6891
+ // Removals anywhere in `node` outside nested closures; true when it can
6892
+ // end the run early.
6893
+ const scan = (node: ts.Node): boolean => {
6894
+ let exits = false
6895
+ const visit = (n: ts.Node): void => {
6896
+ if (ts.isFunctionLike(n) || ts.isClassLike(n)) return
6897
+ if (ts.isReturnStatement(n) || ts.isThrowStatement(n)) exits = true
6898
+ const effect = matchRefAttrEffect(n, param)
6899
+ if (effect?.kind === 'remove') live.delete(effect.name)
6900
+ ts.forEachChild(n, visit)
6901
+ }
6902
+ visit(node)
6903
+ return exits
6904
+ }
6905
+ // False when the run may have ended before this body's end.
6906
+ const run = (fnBody: ts.ConciseBody, allowNested: boolean): boolean => {
6907
+ if (findScopeDeclaration(param, fnBody)) return true
6908
+ const units: readonly ts.Node[] = ts.isBlock(fnBody) ? fnBody.statements : [fnBody]
6909
+ for (const unit of units) {
6910
+ const expr = ts.isExpressionStatement(unit) ? unit.expression : ts.isExpression(unit) ? unit : undefined
6911
+ const effect = expr && matchRefAttrEffect(expr, param)
6912
+ if (effect) {
6913
+ apply(effect)
6914
+ continue
6915
+ }
6916
+ const nested = expr && allowNested ? mountCallbackBody(expr, param, ctx) : undefined
6917
+ if (nested ? !run(nested, false) : scan(unit)) return false
6918
+ }
6919
+ return true
6920
+ }
6921
+ run(body, true)
6922
+ return [...live.values()]
6923
+ }
6924
+
6925
+ /**
6926
+ * `createEffect(() => {…})` / `onMount(function () {…})` → the callback body,
6927
+ * unless its parameters rebind `param`. The callee must be a value import of
6928
+ * the primitive from `@barefootjs/client` (an alias included), so a local
6929
+ * function that happens to be named `onMount` is not one.
6930
+ */
6931
+ function mountCallbackBody(expr: ts.Expression, param: string, ctx: TransformContext): ts.ConciseBody | undefined {
6932
+ const call = unwrapTransparentTsWrappers(expr)
6933
+ if (!ts.isCallExpression(call) || !ts.isIdentifier(call.expression)) return undefined
6934
+ const primitive = clientValueImports(ctx).get(call.expression.text)
6935
+ if (!primitive || !MOUNT_TIME_PRIMITIVES.has(primitive)) return undefined
6936
+ const fn = call.arguments[0] && unwrapTransparentTsWrappers(call.arguments[0])
6937
+ if (!fn || !(ts.isArrowFunction(fn) || ts.isFunctionExpression(fn))) return undefined
6938
+ if (fn.parameters.some(p => bindingDeclares(p.name, param))) return undefined
6939
+ return fn.body
6940
+ }
6941
+
6942
+ interface RefAttrEffect extends RefAttrWrite {
6943
+ kind: 'set' | 'remove'
6944
+ }
6945
+
6946
+ /**
6947
+ * `param.setAttribute('<lit>', …)` / `param.dataset.<key> = …` (a set) or
6948
+ * `param.removeAttribute('<lit>')` / `delete param.dataset.<key>` (a remove).
6949
+ */
6950
+ function matchRefAttrEffect(node: ts.Node, param: string): RefAttrEffect | undefined {
6951
+ if (!ts.isExpression(node)) return undefined
6952
+ const expr = unwrapTransparentTsWrappers(node)
6953
+ if (ts.isCallExpression(expr)) {
6954
+ const callee = expr.expression
6955
+ if (!ts.isPropertyAccessExpression(callee)) return undefined
6956
+ const kind = callee.name.text === 'setAttribute' ? 'set' : callee.name.text === 'removeAttribute' ? 'remove' : undefined
6957
+ const [nameArg] = expr.arguments
6958
+ if (kind && nameArg && ts.isStringLiteralLike(nameArg) && isParamReference(callee.expression, param)) {
6959
+ return { kind, name: nameArg.text.toLowerCase(), node: expr }
6960
+ }
6961
+ return undefined
6962
+ }
6963
+ const target =
6964
+ ts.isBinaryExpression(expr) && expr.operatorToken.kind === ts.SyntaxKind.EqualsToken ? { kind: 'set' as const, lhs: expr.left }
6965
+ : ts.isDeleteExpression(expr) ? { kind: 'remove' as const, lhs: expr.expression }
6966
+ : undefined
6967
+ const name = target && datasetAttrName(target.lhs, param)
6968
+ return name ? { kind: target.kind, name, node: expr } : undefined
6969
+ }
6970
+
6971
+ /** `param.dataset.<key>` / `param.dataset['<key>']` → the `data-*` attribute it maps to. */
6972
+ function datasetAttrName(target: ts.Expression, param: string): string | undefined {
6973
+ const access = unwrapTransparentTsWrappers(target)
6974
+ const key = ts.isPropertyAccessExpression(access)
6975
+ ? access.name.text
6976
+ : ts.isElementAccessExpression(access) && ts.isStringLiteralLike(access.argumentExpression)
6977
+ ? access.argumentExpression.text
6978
+ : undefined
6979
+ if (key === undefined) return undefined
6980
+ const dataset = unwrapTransparentTsWrappers((access as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression)
6981
+ if (!ts.isPropertyAccessExpression(dataset) || dataset.name.text !== 'dataset') return undefined
6982
+ return isParamReference(dataset.expression, param) ? datasetKeyToAttrName(key) : undefined
6983
+ }
6984
+
6985
+ function isParamReference(expr: ts.Expression, param: string): boolean {
6986
+ const inner = unwrapTransparentTsWrappers(expr)
6987
+ return ts.isIdentifier(inner) && inner.text === param
6988
+ }
6989
+
6990
+ /** `nmOpenDelay` → `data-nm-open-delay` (the DOMStringMap camelCase → attribute mapping). */
6991
+ function datasetKeyToAttrName(key: string): string {
6992
+ let out = 'data-'
6993
+ for (const ch of key) {
6994
+ out += ch >= 'A' && ch <= 'Z' ? `-${ch.toLowerCase()}` : ch
6995
+ }
6996
+ return out
6997
+ }
6998
+
6999
+ // =============================================================================
7000
+ // Ref callback resolution
7001
+ // =============================================================================
7002
+
7003
+ interface LocalCallback {
7004
+ param: string | undefined
7005
+ body: ts.ConciseBody
7006
+ }
7007
+
7008
+ interface RefCallback extends LocalCallback {
7009
+ /** Bound by name (`ref={handleMount}`) rather than written inline. */
7010
+ named: boolean
7011
+ /**
7012
+ * True only for a named callback declared in the `ref`'s innermost
7013
+ * enclosing function scope; false for an inline callback and for one
7014
+ * `findNamedCallback`'s outward walk found further out (e.g. a `ref` in a
7015
+ * `.map()` row naming a component-body handler). BF063 ignores this;
7016
+ * `isSsrPortalRefCallback` requires it.
7017
+ */
7018
+ innermostScope: boolean
7019
+ }
7020
+
7021
+ /**
7022
+ * Resolve a `ref={…}` expression to its callback's first param + body, when
7023
+ * statically visible: an inline arrow / function expression, or an
7024
+ * identifier naming a local function (`findNamedCallback`). Resolved once per
7025
+ * element and shared by the SSR-portal recognition and BF063.
7026
+ */
7027
+ function resolveRefCallback(refExpr: ts.Expression): RefCallback | undefined {
7028
+ const expr = unwrapTransparentTsWrappers(refExpr)
7029
+ if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) {
7030
+ return { param: firstSimpleParamName(expr), body: expr.body, named: false, innermostScope: false }
7031
+ }
7032
+ if (!ts.isIdentifier(expr)) return undefined
7033
+ const resolved = findNamedCallback(expr)
7034
+ return resolved && { ...resolved.callback, named: true, innermostScope: resolved.innermostScope }
7035
+ }
7036
+
7037
+ type FunctionLike = ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration
7038
+
7039
+ function isFunctionLike(node: ts.Node): node is FunctionLike {
7040
+ return ts.isArrowFunction(node) || ts.isFunctionExpression(node) || ts.isFunctionDeclaration(node)
7041
+ }
7042
+
7043
+ /**
7044
+ * Walk `.parent` links up from `node` to the nearest enclosing function
7045
+ * (arrow, function expression, or `function` declaration).
7046
+ */
7047
+ function findEnclosingFunctionLike(node: ts.Node): FunctionLike | undefined {
7048
+ let current: ts.Node | undefined = node.parent
7049
+ while (current) {
7050
+ if (isFunctionLike(current)) return current
7051
+ current = current.parent
7052
+ }
7053
+ return undefined
7054
+ }
7055
+
7056
+ /**
7057
+ * Resolve `ident` to a NAMED local function (`const name = (…) => {…}`,
7058
+ * `const name = function (…) {…}`, or `function name(…) {…}`), searching the
7059
+ * enclosing function scopes innermost-first up to the outermost — the
7060
+ * component — so a `ref` inside a `.map()` row arrow still finds a handler
7061
+ * declared in the component body. The first scope binding the name decides:
7062
+ * a parameter, or a declaration that is not a function, makes it opaque.
7063
+ * Never searches a nested function's own body: two sibling components in the
7064
+ * same file can each declare their own, unrelated `handleMount`, and reaching
7065
+ * into the wrong one's closure would misattribute its behavior to this `ref`.
7066
+ * `innermostScope` reports whether the deciding scope was the `ref`'s own
7067
+ * innermost one: BF063 accepts any scope, the SSR-portal recognition only
7068
+ * that one (see `isSsrPortalRefCallback`).
7069
+ */
7070
+ function findNamedCallback(
7071
+ ident: ts.Identifier,
7072
+ ): { callback: LocalCallback; innermostScope: boolean } | undefined {
7073
+ const innermost = findEnclosingFunctionLike(ident)
7074
+ for (let fn = innermost; fn; fn = findEnclosingFunctionLike(fn)) {
7075
+ if (fn.parameters.some(p => bindingDeclares(p.name, ident.text))) return undefined
7076
+ const decl = fn.body && findScopeDeclaration(ident.text, fn.body)
7077
+ if (!decl) continue
7078
+ const callback = localCallbackOf(decl)
7079
+ return callback && { callback, innermostScope: fn === innermost }
7080
+ }
7081
+ return undefined
7082
+ }
7083
+
7084
+ /** The callback a scope declaration binds, when it binds a function at all. */
7085
+ function localCallbackOf(
7086
+ decl: ts.VariableDeclaration | ts.FunctionDeclaration | ts.ClassDeclaration,
7087
+ ): LocalCallback | undefined {
7088
+ if (ts.isFunctionDeclaration(decl)) return decl.body && { param: firstSimpleParamName(decl), body: decl.body }
7089
+ const init = ts.isVariableDeclaration(decl) && ts.isIdentifier(decl.name) && decl.initializer
7090
+ ? unwrapTransparentTsWrappers(decl.initializer)
7091
+ : undefined
7092
+ return init && (ts.isArrowFunction(init) || ts.isFunctionExpression(init))
7093
+ ? { param: firstSimpleParamName(init), body: init.body }
7094
+ : undefined
7095
+ }
7096
+
7097
+ /**
7098
+ * The first declaration of `name` in `scopeBody` — a `const` / `let` / `var`
7099
+ * (destructuring included), a `function` with a body (not an overload
7100
+ * signature) or a `class` — at any block depth, but never inside a nested
7101
+ * function or class, which scope their own names. Block depth is not
7102
+ * distinguished (a `const` inside an `if` block counts too): both callers
7103
+ * want a conservative "is this name rebound here" answer.
7104
+ */
7105
+ function findScopeDeclaration(
7106
+ name: string,
7107
+ scopeBody: ts.Node,
7108
+ ): ts.VariableDeclaration | ts.FunctionDeclaration | ts.ClassDeclaration | undefined {
7109
+ let found: ts.VariableDeclaration | ts.FunctionDeclaration | ts.ClassDeclaration | undefined
7110
+ const visit = (node: ts.Node): void => {
7111
+ if (found) return
7112
+ if (ts.isVariableDeclaration(node) && bindingDeclares(node.name, name)) {
7113
+ found = node
7114
+ return
7115
+ }
7116
+ if (((ts.isFunctionDeclaration(node) && node.body) || ts.isClassDeclaration(node)) && node.name?.text === name) {
7117
+ found = node
7118
+ return
7119
+ }
7120
+ if (ts.isFunctionLike(node) || ts.isClassLike(node)) return
7121
+ ts.forEachChild(node, visit)
7122
+ }
7123
+ visit(scopeBody)
7124
+ return found
7125
+ }
7126
+
7127
+ function bindingDeclares(binding: ts.BindingName, name: string): boolean {
7128
+ const names = new Set<string>()
7129
+ collectBindingNames(binding, names)
7130
+ return names.has(name)
7131
+ }
7132
+
7133
+ // =============================================================================
7134
+ // SSR portal ref-callback recognition (#3059)
7135
+ // =============================================================================
7136
+
7137
+ /**
7138
+ * Structural (AST-only, no text/regex matching) recognition of the
7139
+ * `ref`-callback portal pattern the Dialog/DropdownMenu/Popover/Portal
7140
+ * primitives use: a `ref` bound to a LOCAL, NAMED function (arrow-const,
7141
+ * function-expression-const, or `function` declaration) whose body — at
7142
+ * any statement depth, e.g. inside an `if` guard — directly calls
7143
+ * `createPortal(<the callback's own first param>, document.body, { ownerScope: … })`.
7144
+ *
7145
+ * Recognizing only the DIRECT call (never through a second helper
7146
+ * function) is a deliberate, checked choice, not a shortcut: every
7147
+ * shipped `ref`-callback portal user (dialog, dropdown-menu, popover,
7148
+ * portal, combobox, select) calls `createPortal` directly inside the
7149
+ * `ref` callback itself (`SelectContent`/`ComboboxContent`'s deferral
7150
+ * through `queueMicrotask` is still the SAME callback's own call, not a
7151
+ * second helper — see `containsSsrPortalPlacementCall`'s docstring) —
7152
+ * there is no indirection through a shared `moveToBody`-style helper
7153
+ * anywhere in `ui/components/ui/*` today. Recognizing through a helper
7154
+ * (the "worth the scope-walk?" open question from #3059) is therefore
7155
+ * left for when a real caller needs it.
7156
+ *
7157
+ * The callback must be declared in the `ref`'s INNERMOST enclosing
7158
+ * function scope (`RefCallback.innermostScope`) — BF063 shares the
7159
+ * resolution but may walk further out; this recognition may not. The gate
7160
+ * only restores the scope limit recognition had before BF063 widened the
7161
+ * lookup, so sharing the resolution does not widen what is recognized. It
7162
+ * is not a `.map()`-row guard: a portal element inside a row is broken
7163
+ * either way (a row-declared callback is still recognized, and still
7164
+ * breaks), a pre-existing defect tracked separately.
7165
+ *
7166
+ * A match makes `element.ssrPortalOwnerScope` true, which every adapter
7167
+ * (#3119) uses to place the element's SSR markup at its own portal
7168
+ * outlet instead of inline.
7169
+ */
7170
+ function isSsrPortalRefCallback(callback: RefCallback | undefined): boolean {
7171
+ return (
7172
+ !!callback?.named &&
7173
+ callback.innermostScope &&
7174
+ !!callback.param &&
7175
+ containsSsrPortalPlacementCall(callback.body, callback.param)
7176
+ )
7177
+ }
7178
+
7179
+ function firstSimpleParamName(
7180
+ fn: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration,
7181
+ ): string | undefined {
7182
+ const first = fn.parameters[0]
7183
+ return first && ts.isIdentifier(first.name) ? first.name.text : undefined
7184
+ }
7185
+
7186
+ /**
7187
+ * Walk every descendant of `body` for a `createPortal(<paramName>,
7188
+ * document.body, { ownerScope: … })` call — the exact triple the
7189
+ * shipped components pass. Requires the `ownerScope` option: without it
7190
+ * the client-side `createPortal` never stamps `bf-po`, so SSR placing
7191
+ * the element at the outlet and adding `bf-po` would itself create a new
7192
+ * SSR/hydration mismatch instead of closing the existing one.
7193
+ *
7194
+ * Deliberately does NOT stop at a nested function/arrow boundary the way
7195
+ * `findScopeDeclaration` does: `SelectContent`
7196
+ * (`ui/components/ui/select/index.tsx`) defers its call through
7197
+ * `queueMicrotask(() => createPortal(el, document.body, { ownerScope
7198
+ * }))` — still the SAME `ref` callback's own call, just scheduled async,
7199
+ * not routed through a separately-declared helper — and must match here
7200
+ * the same as a direct call. The `if (…) createPortal(…)` guard that
7201
+ * decides WHETHER to call still runs synchronously inside `handleMount`
7202
+ * itself; only the call is deferred. So once SSR places the element at
7203
+ * the outlet with `bf-po`, hydration's `isSSRPortal(el)` check is true
7204
+ * before the microtask would even be scheduled, keeping the guard a
7205
+ * no-op exactly like the direct-call components. The "DIRECT call only"
7206
+ * guarantee `isSsrPortalRefCallback`'s docstring describes is about NOT
7207
+ * crossing into a separately-declared helper function's own body — which
7208
+ * this walk never does, because it does not resolve call targets: a
7209
+ * `moveToBody(el)` call inside the callback is just a call node, and the
7210
+ * helper's declaration is never visited — not about this same-callback
7211
+ * scheduling deferral.
7212
+ */
7213
+ function containsSsrPortalPlacementCall(body: ts.Node, paramName: string): boolean {
7214
+ let found = false
7215
+ const visit = (node: ts.Node): void => {
7216
+ if (found) return
7217
+ if (ts.isCallExpression(node) && isSsrPortalPlacementCall(node, paramName)) {
7218
+ found = true
7219
+ return
7220
+ }
7221
+ ts.forEachChild(node, visit)
7222
+ }
7223
+ visit(body)
7224
+ return found
7225
+ }
7226
+
7227
+ function isSsrPortalPlacementCall(call: ts.CallExpression, paramName: string): boolean {
7228
+ if (!ts.isIdentifier(call.expression) || call.expression.text !== 'createPortal') return false
7229
+ const [target, container, options] = call.arguments
7230
+ if (!target || !ts.isIdentifier(target) || target.text !== paramName) return false
7231
+ if (!container || !isDocumentBodyAccess(container)) return false
7232
+ if (!options || !ts.isObjectLiteralExpression(options)) return false
7233
+ return options.properties.some(p => {
7234
+ if (ts.isShorthandPropertyAssignment(p)) return p.name.text === 'ownerScope'
7235
+ if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name)) return p.name.text === 'ownerScope'
7236
+ return false
7237
+ })
7238
+ }
7239
+
7240
+ function isDocumentBodyAccess(expr: ts.Expression): boolean {
7241
+ return (
7242
+ ts.isPropertyAccessExpression(expr) &&
7243
+ ts.isIdentifier(expr.expression) &&
7244
+ expr.expression.text === 'document' &&
7245
+ expr.name.text === 'body'
7246
+ )
6604
7247
  }
6605
7248
 
6606
7249
  function getAttributeValue(attr: ts.JsxAttribute, ctx: TransformContext): AttrValue {
@@ -8039,9 +8682,23 @@ function checkBareSignalOrMemoIdentifier(
8039
8682
  * `const toggleItems__alias = toggleItems`, any number of hops, `const`
8040
8683
  * or `let`, #2724 — see `propAliasHopCandidates`'s docstring for why
8041
8684
  * `let` stays eligible)
8042
- * (b) A PropertyAccessExpression rooted at the props object (e.g. `props.items`),
8043
- * OR one whose object reaches the props object through the same kind of
8044
- * alias-hop chain as (a) (e.g. `const p = props; p.items`, #2724 review)
8685
+ * (b) A PropertyAccessExpression whose ROOT identifier (walking through any
8686
+ * number of chained `.foo` accesses via `rootIdentifierOf`, e.g.
8687
+ * `props.data.items` or `data.items`) is itself recognized by (a)'s
8688
+ * same terminal (`isDirectPropBindingName`) — the whole props object
8689
+ * (e.g. `props.items`) OR a destructured OBJECT-shaped prop (e.g.
8690
+ * `data.items` where `data` is the prop, #3044) — OR reaches either of
8691
+ * those through the same kind of alias-hop chain as (a) (e.g.
8692
+ * `const p = props; p.items`, #2724 review)
8693
+ *
8694
+ * (b) covers a REACTIVE PROP whose value is itself an object: the prop
8695
+ * identifier (`data`) is bound to a fresh object on every parent re-render,
8696
+ * so a `.map()` over one of its own properties (`data.items`) needs the same
8697
+ * `mapArray` reconciliation as a top-level array prop — before #3044 this
8698
+ * shape (destructured OBJECT prop + nested member access, as opposed to
8699
+ * `props.items`'s single member access off the WHOLE props object) fell
8700
+ * through both (a) and (b) and silently stayed on the static SSR-row-bind
8701
+ * path, so a parent's array-from-empty update never reached the child.
8045
8702
  *
8046
8703
  * Unlike the regex-based `isPropsReference`, this avoids false positives from
8047
8704
  * unrelated identifiers that happen to share a prop name (e.g. `state.items`
@@ -8065,16 +8722,14 @@ function checkBareSignalOrMemoIdentifier(
8065
8722
  * `isPropsReference`/`isSignalOrMemoReference`'s chain walk.
8066
8723
  */
8067
8724
  function isArrayExprDirectPropRef(arrayExpr: ts.Expression, ctx: TransformContext): boolean {
8068
- const propsObjName = ctx.analyzer.propsObjectName
8069
-
8070
8725
  if (ts.isIdentifier(arrayExpr)) {
8071
8726
  return resolveAliasOrigin(propAliasHopCandidates(ctx), arrayExpr.text, name => (isDirectPropBindingName(name, ctx) ? true : null)) === true
8072
8727
  }
8073
8728
 
8074
- if (ts.isPropertyAccessExpression(arrayExpr) && propsObjName) {
8075
- const obj = arrayExpr.expression
8076
- if (ts.isIdentifier(obj)) {
8077
- return resolveAliasOrigin(propAliasHopCandidates(ctx), obj.text, name => (name === propsObjName ? true : null)) === true
8729
+ if (ts.isPropertyAccessExpression(arrayExpr)) {
8730
+ const root = rootIdentifierOf(arrayExpr.expression)
8731
+ if (root !== null) {
8732
+ return resolveAliasOrigin(propAliasHopCandidates(ctx), root, name => (isDirectPropBindingName(name, ctx) ? true : null)) === true
8078
8733
  }
8079
8734
  }
8080
8735
 
@@ -8111,14 +8766,36 @@ function isArrayExprDirectPropRef(arrayExpr: ts.Expression, ctx: TransformContex
8111
8766
  * (needed so its regex still matches `props.<key>`) rather than local
8112
8767
  * bindings, so a same-named module const was matching here as if it were
8113
8768
  * the prop itself.
8769
+ *
8770
+ * Recognizes the WHOLE props object identifier itself (`name === propsObjName`)
8771
+ * as directly denoting a prop — needed so a hop landing on the bare `props`
8772
+ * identifier (e.g. `const p = props; p.items`, #2724 review) terminates
8773
+ * here rather than each caller re-checking `propsObjName` separately
8774
+ * (folded in during #3044 pullfrog review to remove exactly that
8775
+ * duplication, which had also skipped this function's shadow guard).
8776
+ *
8777
+ * The member-parsed branch walks `parsed.object` to the chain's ROOT (e.g.
8778
+ * `const items = props.data.items` or `const items = data.items`, #3044
8779
+ * pullfrog review), accepting it whether the root is the whole props object
8780
+ * OR itself a destructured prop binding — the same two-way root check
8781
+ * `isArrayExprDirectPropRef`'s own property-access branch makes (via
8782
+ * `rootIdentifierOf` + this same terminal) for the `.map()` array
8783
+ * expression directly. Without this, aliasing a nested prop-object array to
8784
+ * a local const first (an extremely common pattern) reproduced #3044's
8785
+ * exact silent-freeze bug one hop away from the direct expression this fix
8786
+ * otherwise covers.
8114
8787
  */
8115
8788
  function isDirectPropBindingName(name: string, ctx: TransformContext): boolean {
8116
8789
  if (ctx.scope.isBound(name)) return false
8117
8790
  if (ctx.boundPropNames.has(name)) return true
8118
8791
  const propsObjName = ctx.analyzer.propsObjectName
8119
- if (!propsObjName) return false
8792
+ if (propsObjName && name === propsObjName) return true
8120
8793
  const parsed = constantsByName(ctx).get(name)?.parsed
8121
- return !!parsed && parsed.kind === 'member' && !parsed.computed && parsed.object.kind === 'identifier' && parsed.object.name === propsObjName
8794
+ if (!parsed || parsed.kind !== 'member' || parsed.computed) return false
8795
+ let root: ParsedExpr = parsed.object
8796
+ while (root.kind === 'member' && !root.computed) root = root.object
8797
+ if (root.kind !== 'identifier' || ctx.scope.isBound(root.name)) return false
8798
+ return root.name === propsObjName || ctx.boundPropNames.has(root.name)
8122
8799
  }
8123
8800
 
8124
8801
  /**
@@ -8579,6 +9256,14 @@ function buildIfStatementChain(
8579
9256
  if (analyzer.jsxReturn) {
8580
9257
  ctx.isRoot = !asConditional
8581
9258
  alternate = transformNode(analyzer.jsxReturn, ctx)
9259
+ // #3063: only the `if-statement` chain shape is at risk — in
9260
+ // `asConditional` mode (#2463) branches sit inside the caller's
9261
+ // synthetic `display:contents` wrapper element and never claim their
9262
+ // own root scope, so the per-component `comment`/`fragmentRoot` flag
9263
+ // this refusal exists for doesn't apply.
9264
+ if (!asConditional) {
9265
+ checkFragmentWrappedConditionalReturnBranch(alternate, analyzer.jsxReturn, ctx)
9266
+ }
8582
9267
  }
8583
9268
 
8584
9269
  // Build the if-else chain from the last conditional to the first
@@ -8711,6 +9396,9 @@ function buildIfStatementChain(
8711
9396
  let consequent: IRNode | null
8712
9397
  try {
8713
9398
  consequent = transformNode(condReturn.jsxReturn, ctx)
9399
+ if (!asConditional) {
9400
+ checkFragmentWrappedConditionalReturnBranch(consequent, condReturn.jsxReturn, ctx)
9401
+ }
8714
9402
  } finally {
8715
9403
  if (branchNames.length > 0) {
8716
9404
  ctx.getJS = prevCtxGetJS