@barefootjs/jsx 0.38.0 → 0.39.1

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 (105) hide show
  1. package/dist/action-accessor.d.ts +159 -0
  2. package/dist/action-accessor.d.ts.map +1 -0
  3. package/dist/adapters/interface.d.ts +19 -0
  4. package/dist/adapters/interface.d.ts.map +1 -1
  5. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  6. package/dist/analyzer.d.ts +49 -1
  7. package/dist/analyzer.d.ts.map +1 -1
  8. package/dist/async-action-refusal.d.ts +45 -0
  9. package/dist/async-action-refusal.d.ts.map +1 -0
  10. package/dist/compiler.d.ts.map +1 -1
  11. package/dist/debug.d.ts +61 -5
  12. package/dist/debug.d.ts.map +1 -1
  13. package/dist/errors.d.ts +4 -0
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/format-date-refusal.d.ts +2 -6
  16. package/dist/format-date-refusal.d.ts.map +1 -1
  17. package/dist/html-types.d.ts +5 -0
  18. package/dist/html-types.d.ts.map +1 -1
  19. package/dist/index.d.ts +3 -2
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1261 -422
  22. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/collect-elements.d.ts +17 -1
  24. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/compute-scope.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  28. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/declaration-sort.d.ts +2 -1
  31. package/dist/ir-to-client-js/declaration-sort.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-module-level.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +7 -5
  35. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/reactivity.d.ts +10 -2
  38. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/types.d.ts +4 -0
  40. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +52 -9
  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/signal-initializer.d.ts +24 -0
  45. package/dist/signal-initializer.d.ts.map +1 -0
  46. package/dist/ssr-defaults.d.ts.map +1 -1
  47. package/dist/ssr-seed-plan.d.ts.map +1 -1
  48. package/dist/template-position-walk.d.ts +68 -0
  49. package/dist/template-position-walk.d.ts.map +1 -0
  50. package/dist/types.d.ts +95 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +2 -2
  53. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +194 -4
  54. package/src/__tests__/action-accessor.test.ts +166 -0
  55. package/src/__tests__/adapter-output.test.ts +142 -0
  56. package/src/__tests__/create-mutation.test.ts +250 -0
  57. package/src/__tests__/create-query.test.ts +696 -0
  58. package/src/__tests__/csr-fragment-root-scope-shape.test.ts +156 -0
  59. package/src/__tests__/debug.test.ts +305 -0
  60. package/src/__tests__/doc-examples.test.ts +66 -3
  61. package/src/__tests__/ir-fragment-transparency.test.ts +23 -0
  62. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +245 -0
  63. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +80 -0
  64. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +445 -0
  65. package/src/__tests__/props-destructuring.test.ts +79 -4
  66. package/src/__tests__/reactive-factory-arity.test.ts +311 -0
  67. package/src/__tests__/ssr-portal-ref-callback.test.ts +5 -3
  68. package/src/action-accessor.ts +289 -0
  69. package/src/adapters/interface.ts +19 -0
  70. package/src/adapters/jsx-adapter.ts +47 -20
  71. package/src/analyzer.ts +593 -44
  72. package/src/async-action-refusal.ts +254 -0
  73. package/src/compiler.ts +81 -46
  74. package/src/debug.ts +351 -104
  75. package/src/errors.ts +39 -0
  76. package/src/format-date-refusal.ts +6 -125
  77. package/src/html-types.ts +14 -0
  78. package/src/index.ts +3 -1
  79. package/src/ir-to-client-js/build-references.ts +6 -2
  80. package/src/ir-to-client-js/collect-elements.ts +65 -4
  81. package/src/ir-to-client-js/compute-inlinability.ts +2 -1
  82. package/src/ir-to-client-js/compute-scope.ts +3 -1
  83. package/src/ir-to-client-js/control-flow/plan/build-insert.ts +1 -0
  84. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  85. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +112 -3
  86. package/src/ir-to-client-js/control-flow/stringify/insert.ts +1 -1
  87. package/src/ir-to-client-js/csr-substitute.ts +11 -3
  88. package/src/ir-to-client-js/declaration-sort.ts +7 -3
  89. package/src/ir-to-client-js/emit-module-level.ts +7 -4
  90. package/src/ir-to-client-js/emit-registration.ts +5 -10
  91. package/src/ir-to-client-js/index.ts +7 -2
  92. package/src/ir-to-client-js/phases/ref-callbacks.ts +1 -1
  93. package/src/ir-to-client-js/plan/build-declaration-emit.ts +16 -15
  94. package/src/ir-to-client-js/plan/declaration-emit.ts +7 -5
  95. package/src/ir-to-client-js/prop-handling.ts +4 -0
  96. package/src/ir-to-client-js/reactivity.ts +32 -1
  97. package/src/ir-to-client-js/stringify/declaration-emit.ts +14 -7
  98. package/src/ir-to-client-js/types.ts +4 -0
  99. package/src/ir-to-client-js/utils.ts +184 -21
  100. package/src/jsx-to-ir.ts +111 -14
  101. package/src/signal-initializer.ts +36 -0
  102. package/src/ssr-defaults.ts +10 -0
  103. package/src/ssr-seed-plan.ts +12 -1
  104. package/src/template-position-walk.ts +203 -0
  105. package/src/types.ts +99 -0
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { ConstantInfo, FunctionInfo, MemoInfo, ReferencesGraph, SignalInfo } from '../types.ts'
11
11
  import { graphDeclarationReferences } from './build-references.ts'
12
+ import { signalSecondBinding } from '../signal-initializer.ts'
12
13
 
13
14
  // =============================================================================
14
15
  // Declaration types
@@ -22,14 +23,17 @@ export type Declaration =
22
23
 
23
24
  /**
24
25
  * Return the names defined by a declaration.
25
- * Signals define both getter and setter names.
26
+ * Signals define both getter and setter names (an async factory's second
27
+ * binding is its action, #3165).
26
28
  */
27
29
  export function providedNames(decl: Declaration): string[] {
28
30
  switch (decl.kind) {
29
31
  case 'constant':
30
32
  return [decl.info.name]
31
- case 'signal':
32
- return decl.info.setter ? [decl.info.getter, decl.info.setter] : [decl.info.getter]
33
+ case 'signal': {
34
+ const second = signalSecondBinding(decl.info)
35
+ return second ? [decl.info.getter, second] : [decl.info.getter]
36
+ }
33
37
  case 'memo':
34
38
  return [decl.info.name]
35
39
  case 'function':
@@ -26,6 +26,7 @@ import {
26
26
  collectUserDomImports,
27
27
  detectUsedImports,
28
28
  } from './imports.ts'
29
+ import { signalFactoryInitializer, signalSecondBinding } from '../signal-initializer.ts'
29
30
 
30
31
  /**
31
32
  * Build the module-level code block that replaces `MODULE_CONSTANTS_PLACEHOLDER`.
@@ -70,13 +71,15 @@ export function emitModuleLevelDeclarations(
70
71
  }
71
72
  for (const signal of moduleLevelSignals) {
72
73
  const tupleVar = `__bf_m_${signal.getter}_tuple`
74
+ const initializer = signalFactoryInitializer(signal) ?? `createSignal(${signal.initialValue})`
75
+ const second = signalSecondBinding(signal)
73
76
  if (signal.isExported) {
74
- lines.push(`export const [${signal.getter}${signal.setter ? `, ${signal.setter}` : ''}] = createSignal(${signal.initialValue})`)
77
+ lines.push(`export const [${signal.getter}${second ? `, ${second}` : ''}] = ${initializer}`)
75
78
  } else {
76
- lines.push(`var ${tupleVar} = ${tupleVar} ?? createSignal(${signal.initialValue})`)
79
+ lines.push(`var ${tupleVar} = ${tupleVar} ?? ${initializer}`)
77
80
  lines.push(`var ${signal.getter} = ${tupleVar}[0]`)
78
- if (signal.setter) {
79
- lines.push(`var ${signal.setter} = ${tupleVar}[1]`)
81
+ if (second) {
82
+ lines.push(`var ${second} = ${tupleVar}[1]`)
80
83
  }
81
84
  }
82
85
  }
@@ -4,9 +4,9 @@
4
4
  * and the final hydrate() call emission.
5
5
  */
6
6
 
7
- import type { ComponentIR, IRFragment, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
7
+ import type { ComponentIR, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
8
8
  import type { ClientJsContext } from './types.ts'
9
- import { PROPS_PARAM, isCommentScopedRoot, initFunctionName } from './utils.ts'
9
+ import { PROPS_PARAM, componentDefScopeFlags, initFunctionName } from './utils.ts'
10
10
  import { computeInlinability, toLegacyInlinability } from './compute-inlinability.ts'
11
11
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate, createStringProtector } from './html-template.ts'
12
12
  import { markupSlotIdsOf } from './markup-slots.ts'
@@ -214,8 +214,8 @@ export function emitRegistrationAndHydration(
214
214
  // ITS OWN real scope id — the wrapping comment marks a scope with no
215
215
  // DOM presence of its own, and `materializeComponent` must leave
216
216
  // `scopeId` null so it doesn't stamp over (or duplicate) the child's.
217
- const isFragmentRoot = _ir.root.type === 'fragment' && !!(_ir.root as IRFragment).needsScopeComment
218
- const isCommentScope = isCommentScopedRoot(_ir.root)
217
+ // Both flags come from `componentDefScopeFlags` (utils.ts), shared with
218
+ // the template-only registration path (`generateTemplateOnlyMount`).
219
219
 
220
220
  // Build ComponentDef object for hydrate()
221
221
  const defParts: string[] = [`init: ${initFunctionName(name)}`]
@@ -243,12 +243,7 @@ export function emitRegistrationAndHydration(
243
243
  }
244
244
  }
245
245
  // No else: top-level-only components skip template entirely (save bytes)
246
- if (isCommentScope) {
247
- defParts.push('comment: true')
248
- }
249
- if (isFragmentRoot) {
250
- defParts.push('fragmentRoot: true')
251
- }
246
+ defParts.push(...componentDefScopeFlags(_ir.root))
252
247
 
253
248
  const registryKey = nameForRegistryRef(name)
254
249
  // When the registry key was file-scoped (`Name__<8hex>`, for a
@@ -16,7 +16,7 @@ import { buildReferencesGraph, graphUsedIdentifiers } from './build-references.t
16
16
  import { addConstantPropRefsToSet } from './init-declarations.ts'
17
17
  import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate } from './html-template.ts'
18
18
  import { markupSlotIdsOf } from './markup-slots.ts'
19
- import { PROPS_PARAM, initFunctionName } from './utils.ts'
19
+ import { PROPS_PARAM, initFunctionName, componentDefScopeFlags } from './utils.ts'
20
20
  import { buildInlinableConstants, csrInlinableConstantsFromCtx } from './emit-registration.ts'
21
21
  import { buildEnvFromCtx } from './compute-inlinability.ts'
22
22
  import { nameForRegistryRef, buildImportAliasMap, setActiveImportAliases } from './component-scope.ts'
@@ -363,7 +363,12 @@ function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): strin
363
363
  // `emitRegistrationAndHydration`: the hashed key must not reach `bf-s`
364
364
  // (#2518).
365
365
  const nameField = registryKey !== name ? `, name: '${name}'` : ''
366
- lines.push(`hydrate('${registryKey}', { init: ${initName}, template: (${PROPS_PARAM}) => \`${templateHtml}\`${nameField} })`)
366
+ // Scope-shape flags from the same helper `emitRegistrationAndHydration`
367
+ // uses — a fragment-rooted stateless child must declare `comment` /
368
+ // `fragmentRoot` too, or `renderChild()` stamps `bf-s` onto its first
369
+ // element while SSR scopes it with a comment pair.
370
+ const scopeFlags = componentDefScopeFlags(ir.root).map((f) => `, ${f}`).join('')
371
+ lines.push(`hydrate('${registryKey}', { init: ${initName}, template: (${PROPS_PARAM}) => \`${templateHtml}\`${scopeFlags}${nameField} })`)
367
372
  // See `emitRegistrationAndHydration` (./emit-registration.ts) for the
368
373
  // rationale on why the component is also emitted as a callable
369
374
  // shim. The same applies for template-only components since they
@@ -16,6 +16,6 @@ export function emitRefCallbacks(
16
16
  for (const elem of ctx.refElements) {
17
17
  if (conditionalSlotIds.has(elem.slotId)) continue
18
18
  const v = varSlotId(elem.slotId)
19
- lines.push(` if (_${v}) ${emitRefCall(elem.callback, `_${v}`)}`)
19
+ lines.push(` if (_${v}) ${emitRefCall(elem.callback, `_${v}`, elem.ssrPortalOwner)}`)
20
20
  }
21
21
  }
@@ -14,7 +14,7 @@ import type { ClientJsContext } from '../types.ts'
14
14
  import type { ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM } from '../utils.ts'
16
16
  import { livePropReadExpr } from '../../props-binding.ts'
17
- import { ENV_SIGNAL_CLIENT_FACTORY } from '../../adapters/env-signal.ts'
17
+ import { signalFactoryInitializer, signalSecondBinding } from '../../signal-initializer.ts'
18
18
  import type {
19
19
  ControlledSignalEffectPlan,
20
20
  DeclarationEmitPlan,
@@ -87,20 +87,21 @@ function buildSignalPlan(
87
87
  ctx: ClientJsContext,
88
88
  lookups: DeclarationEmitLookups,
89
89
  ): SignalEmitPlan {
90
- if (signal.envReader) {
91
- // Emit the factory as written (alias / namespace aware, #2057), falling back
92
- // to the canonical name if the callee text wasn't captured.
93
- const factory = signal.envFactory ?? ENV_SIGNAL_CLIENT_FACTORY[signal.envReader]
94
- if (factory) {
95
- return {
96
- kind: 'signal',
97
- getter: signal.getter,
98
- setter: signal.setter,
99
- getterElided: signal.getterElided,
100
- initialValueExpr: '',
101
- controlledEffect: null,
102
- initializerOverride: `${factory}()`,
103
- }
90
+ // Env signals (#2057) and async factories (#3165) re-emit their own factory
91
+ // call, as written (alias / namespace aware), instead of `createSignal`.
92
+ const initializerOverride = signalFactoryInitializer(signal)
93
+ if (initializerOverride) {
94
+ return {
95
+ kind: 'signal',
96
+ getter: signal.getter,
97
+ setter: signalSecondBinding(signal),
98
+ getterElided: signal.getterElided,
99
+ initialValueExpr: '',
100
+ controlledEffect: null,
101
+ initializerOverride,
102
+ // An env signal is a stable request-scoped view, emitted unconditionally;
103
+ // an async factory owns a request, so it is created only on its branch.
104
+ branchCondition: signal.factory ? signal.branchCondition : undefined,
104
105
  }
105
106
  }
106
107
  const controlledEffect = buildControlledSignalEffect(signal, lookups)
@@ -62,11 +62,13 @@ export interface SignalEmitPlan {
62
62
  bfId?: string
63
63
  /**
64
64
  * When set, the full initializer expression to emit verbatim instead of
65
- * `createSignal(<initialValueExpr>)`. Env signals (#2057) emit their own
66
- * factory call — e.g. `createSearchParams()` — with no baked initial value,
67
- * profile id, controlled effect, or branch condition (the tuple is a stable
68
- * request-scoped view, not stored state). When present the stringifier emits
69
- * `const [<getter>, <setter>] = <initializerOverride>` and nothing else.
65
+ * `createSignal(<initialValueExpr>)`. Env signals (#2057) and async
66
+ * factories (#3165) emit their own factory call — e.g.
67
+ * `createSearchParams()`, `createQuery(fn, options)` — with no baked initial
68
+ * value, profile id, or controlled effect; `setter` then holds the tuple's
69
+ * second binding (an async factory's action). When present the stringifier
70
+ * emits `const [<getter>, <setter>] = <initializerOverride>` (or the
71
+ * `branchCondition` form, which only an async factory sets) and nothing else.
70
72
  */
71
73
  initializerOverride?: string
72
74
  }
@@ -189,6 +189,10 @@ export function getControlledPropName(
189
189
  propsParams: ParamInfo[],
190
190
  propsObjectName: string | null = null
191
191
  ): string | null {
192
+ // An async factory's value (`createQuery(fn, { initial: props.posts })`,
193
+ // #3165) takes `initial` once; later values come from its own requests, so
194
+ // it is never re-synced from the prop.
195
+ if (signal.factory) return null
192
196
  const initialValue = signal.initialValue.trim()
193
197
  const isDefaultProp = (propName: string) => propName.startsWith('default')
194
198
  // Use the source-level props name for pattern matching (not the generated PROPS_PARAM)
@@ -2,7 +2,7 @@
2
2
  * Reactivity detection: reactive expression checking, event/ref collection.
3
3
  */
4
4
 
5
- import { type IRNode, type IRElement, type IRComponent, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin } from '../types.ts'
5
+ import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin } from '../types.ts'
6
6
  import type {
7
7
  ClientJsContext,
8
8
  ConditionalBranchEvent,
@@ -15,6 +15,16 @@ import type {
15
15
  NestedLoop,
16
16
  } from './types.ts'
17
17
  import { attrValueToString, freeIdsFromRefs, tokenContainsIdent } from './utils.ts'
18
+ // `resolveLoopOffset` lives in `collect-elements.ts` (the sibling-offset
19
+ // pre-pass, #1693) — imported here (not duplicated) so the delegated-event
20
+ // `NestedLoop` chain built below resolves the SAME static-sibling-count
21
+ // offset the hydration-side `NestedLoop` (`collectInnerLoops`) already
22
+ // applies, rather than growing a second copy of that resolution (#3240
23
+ // follow-up). `collect-elements.ts` imports several collectors back from
24
+ // this module, so this is a deliberate circular import; both sides only use
25
+ // the other's export inside function bodies invoked well after module init,
26
+ // never at top-level, so the cycle resolves safely.
27
+ import { resolveLoopOffset } from './collect-elements.ts'
18
28
  import { expandConstantForReactivity } from './prop-handling.ts'
19
29
  import { extractFreeIdentifiersFromText } from './csr-substitute.ts'
20
30
  import { walkIR, stopAt } from './walker.ts'
@@ -488,6 +498,7 @@ export function collectConditionalBranchRefs(node: IRNode): ConditionalBranchRef
488
498
  refs.push({
489
499
  slotId: el.slotId,
490
500
  callback: el.ref,
501
+ ...(el.ssrPortalOwnerScope && { ssrPortalOwner: true }),
491
502
  })
492
503
  }
493
504
  }, true)
@@ -569,6 +580,14 @@ export function collectLoopChildEvents(node: IRNode): LoopChildEvent[] {
569
580
  export function collectLoopChildEventsWithNesting(
570
581
  node: IRNode,
571
582
  initialNestingStack: NestedLoop[] = [],
583
+ /**
584
+ * The whole-component sibling-offset pre-pass (`computeLoopSiblingOffsets`,
585
+ * `collect-elements.ts`), keyed by IR loop-node identity. Optional — a
586
+ * caller with no sibling-offset data (none exist today) gets `nested.offset`
587
+ * left `undefined`, same as before #3240's follow-up fix, rather than a
588
+ * required param forcing every call site to thread an empty Map.
589
+ */
590
+ siblingOffsets?: Map<IRLoop, IRNode[]>,
572
591
  ): LoopChildEvent[] {
573
592
  type Scope = {
574
593
  nestingStack: NestedLoop[]
@@ -624,6 +643,18 @@ export function collectLoopChildEventsWithNesting(
624
643
  markerId: l.markerId,
625
644
  containerSlotId: scope.lastElementSlotId,
626
645
  bindings: emptyLoopChildBindings(),
646
+ // #3240 follow-up: a static-index delegated event resolves each
647
+ // nested level's item POSITIONALLY (`emitStaticIndexLookup` /
648
+ // `emitNestedIndexParams` in `stringify/event-delegation.ts`),
649
+ // so this level's item is wrong whenever anything precedes its
650
+ // `.map()` within its container (a static sibling, or another
651
+ // loop sharing the same parent) and this offset is left unset —
652
+ // the keyed path's nested resolution (`data-key-N` + `find()`)
653
+ // never needed it, which is why this field went unset from
654
+ // #2189 through the original #3240 fix. Resolved the same way
655
+ // the hydration-side `NestedLoop` does (`collectInnerLoops`
656
+ // above, `offset: resolveLoopOffset(siblingOffsets.get(n))`).
657
+ offset: siblingOffsets ? resolveLoopOffset(siblingOffsets.get(l)) : undefined,
627
658
  },
628
659
  ],
629
660
  })
@@ -70,15 +70,22 @@ function emitSignal(lines: string[], plan: SignalEmitPlan): void {
70
70
  // getter name into output (#2468 sweep — dropping the declaration
71
71
  // entirely left the setter as a guaranteed ReferenceError).
72
72
  const getterSlot = plan.getterElided ? '' : plan.getter
73
- // Env signal (#2057): emit its own factory call verbatim (`createSearchParams()`)
74
- // — a stable request-scoped view, so no baked initial value, profile id,
75
- // controlled effect, or branch condition applies.
73
+ // Env signal (#2057) or async factory (#3165): emit its own factory call
74
+ // verbatim (`createSearchParams()`, `createQuery(fn, options)`) — no baked
75
+ // initial value, profile id, or controlled effect applies. Only an async
76
+ // factory carries a branch condition (see `SignalEmitPlan.branchCondition`).
76
77
  if (plan.initializerOverride) {
77
- if (plan.setter) {
78
- lines.push(` const [${getterSlot}, ${plan.setter}] = ${plan.initializerOverride}`)
79
- } else {
80
- lines.push(` const [${plan.getter}] = ${plan.initializerOverride}`)
78
+ const bindings = plan.setter ? `${getterSlot}, ${plan.setter}` : plan.getter
79
+ if (plan.branchCondition) {
80
+ lines.push(plan.setter
81
+ ? (plan.getterElided ? ` let ${plan.setter}` : ` let ${plan.getter}, ${plan.setter}`)
82
+ : ` let ${plan.getter}`)
83
+ lines.push(` if (${plan.branchCondition}) {`)
84
+ lines.push(` ;[${bindings}] = ${plan.initializerOverride}`)
85
+ lines.push(` }`)
86
+ return
81
87
  }
88
+ lines.push(` const [${bindings}] = ${plan.initializerOverride}`)
82
89
  return
83
90
  }
84
91
  const id = bfIdArg(plan.bfId)
@@ -203,6 +203,8 @@ export interface ConditionalBranchEvent {
203
203
  export interface ConditionalBranchRef {
204
204
  slotId: string
205
205
  callback: string
206
+ /** Mirrors `IRElement.ssrPortalOwnerScope` — see `emitRefCall`. */
207
+ ssrPortalOwner?: boolean
206
208
  }
207
209
 
208
210
  export interface ConditionalBranchChildComponent {
@@ -740,6 +742,8 @@ export type CollectedLoop = TopLevelLoop | BranchLoop | NestedLoop
740
742
  export interface RefElement {
741
743
  slotId: string
742
744
  callback: string
745
+ /** Mirrors `IRElement.ssrPortalOwnerScope` — see `emitRefCall`. */
746
+ ssrPortalOwner?: boolean
743
747
  }
744
748
 
745
749
  export interface ChildInit {
@@ -6,6 +6,7 @@
6
6
  import ts from 'typescript'
7
7
  import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR } from '../types.ts'
8
8
  import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
+ import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
9
10
  import { buildLoopChainExpr } from '../loop-chain.ts'
10
11
  import { templatePartsToJsExpr } from '../template-parts.ts'
11
12
  import { escapeIdentifierForRegex, ID_BOUNDARY_BEFORE, ID_BOUNDARY_AFTER } from '../identifier-pattern.ts'
@@ -26,6 +27,7 @@ import {
26
27
  loopItemMarker,
27
28
  toHTMLAttrName as toHtmlAttrName,
28
29
  keyAttrName as sharedKeyAttrName,
30
+ BF_PORTAL_OWNER,
29
31
  } from '@barefootjs/shared'
30
32
  import { RUNTIME_IMPORT_CANDIDATES } from './imports.ts'
31
33
 
@@ -81,7 +83,42 @@ export function initFunctionName(componentName: string): string {
81
83
  * — the wrapping comment marks a scope with no DOM presence of its own.
82
84
  */
83
85
  export function isCommentScopedRoot(root: ComponentIR['root']): boolean {
84
- return (root.type === 'fragment' && !!(root as IRFragment).needsScopeComment) || root.type === 'component'
86
+ return isScopeCommentFragmentRoot(root) || root.type === 'component'
87
+ }
88
+
89
+ /**
90
+ * True for a genuine `needsScopeComment` fragment root — the `fragmentRoot:
91
+ * true` def flag's condition (#2722). SSR renders it wrapped in
92
+ * `<!--bf-scope:-->` comments with no scope attribute on any element, so the
93
+ * CSR runtime must be told to mirror that (`materializeComponent` /
94
+ * `renderChild` in component.ts) instead of stamping `bf-s` onto the first
95
+ * rendered element.
96
+ */
97
+ export function isScopeCommentFragmentRoot(root: ComponentIR['root']): boolean {
98
+ return root.type === 'fragment' && !!(root as IRFragment).needsScopeComment
99
+ }
100
+
101
+ /**
102
+ * The scope-shape flags (`comment: true` / `fragmentRoot: true`) a
103
+ * component's `hydrate()` def declares — the ONE answer both registration
104
+ * emitters read: `emitRegistrationAndHydration` (emit-registration.ts, a
105
+ * component with an init body) and `generateTemplateOnlyMount` (index.ts, a
106
+ * stateless component registered for `renderChild()` only). The template-
107
+ * only emitter used to re-derive the def by hand and declared neither flag,
108
+ * so a fragment-rooted stateless child rendered by CSR got `bf-s` stamped on
109
+ * its first element while SSR (and so hydration) scoped it with a comment
110
+ * pair — a hydrated-vs-csr-mount divergence.
111
+ *
112
+ * A component-call root (#2649) never reaches the template-only emitter:
113
+ * its root child call always pushes a `childInits` entry
114
+ * (collect-elements.ts), so `needsClientJs` routes it to the init-bearing
115
+ * path. Both paths therefore share one answer here.
116
+ */
117
+ export function componentDefScopeFlags(root: ComponentIR['root']): string[] {
118
+ const flags: string[] = []
119
+ if (isCommentScopedRoot(root)) flags.push('comment: true')
120
+ if (isScopeCommentFragmentRoot(root)) flags.push('fragmentRoot: true')
121
+ return flags
85
122
  }
86
123
 
87
124
  /**
@@ -397,18 +434,30 @@ export function wrapHandlerForTurn(handler: string, handlerId: string, loc?: str
397
434
  * Heuristic: a single bare identifier (e.g. `attachPane`) is a local binding;
398
435
  * anything else (member access, call, arrow, …) is treated as a possibly-
399
436
  * undefined source and emitted with optional-call (`?.()`).
437
+ *
438
+ * `ssrPortalOwner` (the element's `IRElement.ssrPortalOwnerScope`, #3059):
439
+ * every SSR adapter renders that element at its portal outlet with
440
+ * `bf-po="<this component's scope id>"` — the owner marker hydration's
441
+ * portal-aware slot lookup finds it by, and which hydration keeps as-is.
442
+ * The CSR mirror stamps the same owner right AFTER the ref callback ran (not
443
+ * in the template: a `bf-po` present before the callback makes its
444
+ * `!isSSRPortal(el)` guard skip the move). Without it the owner came only
445
+ * from the callback's own `createPortal(el, …, { ownerScope })`, which
446
+ * derives it from `el.closest('[bf-s]')` — this component's root for an
447
+ * element root, but nothing (or an unrelated outer scope) for a
448
+ * `needsScopeComment` fragment root, whose scope id lives on a comment, so
449
+ * a CSR mount diverged from SSR/hydration on the attribute.
400
450
  */
401
- export function emitRefCall(callback: string, elementVar: string): string {
451
+ export function emitRefCall(callback: string, elementVar: string, ssrPortalOwner = false): string {
402
452
  const trimmed = callback.trim()
403
453
  const isBareIdent = /^[a-zA-Z_$][\w$]*$/.test(trimmed)
404
- if (isBareIdent) {
405
- return `(${callback})(${elementVar})`
406
- }
407
454
  // Wrap non-identifier expressions in parens so `?.()` binds to the whole
408
455
  // expression (e.g. `(_p.onMount)?.(_s0)` not `_p.onMount?.(_s0)` — both
409
456
  // parse the same here, but the parens preserve the legacy emit shape's
410
457
  // intent and stay safe for arbitrary callback expressions).
411
- return `(${callback})?.(${elementVar})`
458
+ const call = isBareIdent ? `(${callback})(${elementVar})` : `(${callback})?.(${elementVar})`
459
+ if (!ssrPortalOwner) return call
460
+ return `{ ${call}; if (__scopeId) ${elementVar}.setAttribute('${BF_PORTAL_OWNER}', __scopeId) }`
412
461
  }
413
462
 
414
463
  /** Infer a sensible JS default value literal from a type descriptor. */
@@ -635,9 +684,12 @@ function renderLoopBindingAccess(b: LoopParamBinding, base: string): string {
635
684
  * e.g., "item.text" → "item().text", "item" → "item()"
636
685
  * Does not double-wrap: "item().text" stays "item().text"
637
686
  *
638
- * String-context aware: skips replacements inside string literals and template
639
- * literal string parts (e.g., CSS class name "preview-field" stays unchanged
640
- * when paramName is "field"). Handles arbitrarily nested template literals.
687
+ * The plain-param branch (`rewriteIdentifierAsAccessor`) walks the real AST,
688
+ * so it is inherently string/template-literal-context aware (a CSS class
689
+ * name like "preview-field" never surfaces as an `Identifier` node when
690
+ * `paramName` is "field") AND skips object-literal keys, shorthand
691
+ * properties, and member/property names — tokens that spell `paramName`
692
+ * without referencing it (#3239).
641
693
  *
642
694
  * When `bindings` is supplied (destructured `.map()` callback, #951), each
643
695
  * binding name is rewritten to `__bfItem()${path}` instead of wrapping the
@@ -669,12 +721,7 @@ export function wrapLoopParamAsAccessor(
669
721
  if (bindings && bindings.length > 0) {
670
722
  result = rewriteLoopBindingRefs(expr, bindings, '__bfItem()')
671
723
  } else {
672
- // `paramName` is a legal JS identifier and may itself start with `$`
673
- // (`$1`, `$&`, …) — a plain string replacement would risk `String.replace`
674
- // reading those as backreference/whole-match sequences, so use a replacer
675
- // function to insert the accessor text literally (#2592).
676
- const re = new RegExp(`${ID_BOUNDARY_BEFORE}${escapeIdentifierForRegex(paramName)}(?!\\s*\\()(?!-)${ID_BOUNDARY_AFTER}`, 'gu')
677
- result = replaceInExprContexts(expr, re, () => `${paramName}()`)
724
+ result = rewriteIdentifierAsAccessor(expr, paramName)
678
725
  }
679
726
  if (indexParam && indexParam !== paramName) {
680
727
  result = wrapIndexParamAsAccessor(result, indexParam)
@@ -683,10 +730,11 @@ export function wrapLoopParamAsAccessor(
683
730
  }
684
731
 
685
732
  /**
686
- * The index-only half of `wrapLoopParamAsAccessor` — same regex shape, own
687
- * identifier. Factored out so `wrapLoopParamAsAccessor` can run it as a
688
- * second pass regardless of which item-rewrite branch (bindings vs. plain
689
- * param) ran first (#2859).
733
+ * The index-only half of `wrapLoopParamAsAccessor` — same AST-aware
734
+ * identifier rewrite (`rewriteIdentifierAsAccessor`), own identifier.
735
+ * Factored out so `wrapLoopParamAsAccessor` can run it as a second pass
736
+ * regardless of which item-rewrite branch (bindings vs. plain param) ran
737
+ * first (#2859).
690
738
  *
691
739
  * Also exported standalone for `build-loop.ts`/`build-branch-loop.ts`: a
692
740
  * plain loop's `template`/`mapPreambleWrapped` are built ONCE, before lazy
@@ -698,8 +746,123 @@ export function wrapLoopParamAsAccessor(
698
746
  * is NOT going lazy.
699
747
  */
700
748
  export function wrapIndexParamAsAccessor(expr: string, indexParam: string): string {
701
- const re = new RegExp(`${ID_BOUNDARY_BEFORE}${escapeIdentifierForRegex(indexParam)}(?!\\s*\\()(?!-)${ID_BOUNDARY_AFTER}`, 'gu')
702
- return replaceInExprContexts(expr, re, () => `${indexParam}()`)
749
+ return rewriteIdentifierAsAccessor(expr, indexParam)
750
+ }
751
+
752
+ /**
753
+ * AST-aware engine behind `wrapLoopParamAsAccessor`'s plain-param branch and
754
+ * `wrapIndexParamAsAccessor`: rewrite every genuine value reference to
755
+ * `name` in `expr` into `${name}()`, while leaving alone every token that
756
+ * merely SPELLS `name` without referencing it — an object-literal key
757
+ * (`{ name: 1 }`), a shorthand property (`{ name }`, expanded to
758
+ * `{ name: name() }` in one edit — the same transformation #1244 gave the
759
+ * destructured-binding path via `expandShorthandBindings`), and a
760
+ * member/property name (`obj.name`, `obj?.name`).
761
+ *
762
+ * The previous implementation was a `\bname\b`-style regex
763
+ * (`ID_BOUNDARY_BEFORE`/`AFTER` only know about identifier-character
764
+ * boundaries, not JS grammar), so it matched those non-reference tokens too:
765
+ * a key or shorthand rewrite produces invalid JS (`{ name(): 1 }`,
766
+ * `{ name() }`) that fails at parse time; a member-name rewrite produces
767
+ * valid-but-wrong JS (`obj.name()`) that throws `TypeError: obj.name is not
768
+ * a function` at row-creation time (#3239). Parsing the real AST — the same
769
+ * technique `expandShorthandBindings` already uses below — makes each of
770
+ * those positions a type of AST node this function can name and skip,
771
+ * instead of a regex guessing from surrounding characters.
772
+ *
773
+ * A nested declaration that re-binds `name` (a parameter, a `const`/`let`,
774
+ * or a destructured local) is deliberately NOT skipped, unlike
775
+ * `analyzer.ts`'s rename `classify()`: this rewrite has no scope tracking,
776
+ * so it cannot tell a reference to the shadowing local from a reference to
777
+ * the outer loop param past that point, and silently wrapping only the
778
+ * OUTER-scope references while leaving the shadowed ones alone (or vice
779
+ * versa) would just move the #3239 bug rather than fix it. Wrapping the
780
+ * shadowing declaration's own name is always a syntax break at the
781
+ * declaration site itself (`const name = 1` → `const name() = 1`, `(name)
782
+ * => …` → `(name()) => …` — a call can't legally appear where a binding
783
+ * name is expected), so the module fails to parse instead of silently
784
+ * running with the wrong value — the same loud, build-time failure the old
785
+ * regex produced for this shape (it had no shadow-awareness either).
786
+ *
787
+ * A NAMED function expression is the one shadowing shape this function
788
+ * skips wholesale rather than leaving loud: `(function name() { ... })`'s
789
+ * own name is scoped to exactly that expression's body and nowhere else, so
790
+ * `visit` never descends into it at all once it sees the self-shadowing
791
+ * name — no reference inside can possibly mean the outer `name`. A
792
+ * `function`/`class` DECLARATION's name is different: its binding reaches
793
+ * into the surrounding scope too (a function declaration's name is hoisted
794
+ * above it; a class declaration's own static/instance members can
795
+ * self-reference it), so the same whole-subtree skip isn't sound here —
796
+ * a self-reference to a `function`/`class` declaration whose name happens
797
+ * to match `name` is still silently misrewritten, an accepted
798
+ * pre-existing-shaped gap the old regex had too (the "followed by `(`"
799
+ * exclusion below only protects the declaration's OWN name token, not
800
+ * references reachable from within or after it).
801
+ */
802
+ function rewriteIdentifierAsAccessor(expr: string, name: string): string {
803
+ // Fast path: `name` doesn't occur in the text at all → nothing to rewrite.
804
+ // A cheap substring check only ever causes an unnecessary parse below
805
+ // (e.g. `name` occurs only as part of a longer identifier), never a wrong
806
+ // answer, since the AST walk re-checks the exact identifier text.
807
+ if (!expr.includes(name)) return expr
808
+
809
+ const wrapped = `(${expr})`
810
+ const sf = ts.createSourceFile('__bf_expr.ts', wrapped, ts.ScriptTarget.Latest, /* setParentNodes */ true)
811
+ const edits: Array<{ start: number; end: number; replacement: string }> = []
812
+
813
+ const visit = (node: ts.Node): void => {
814
+ // A named function expression's own name is scoped to exactly its own
815
+ // body, so nothing reachable inside it can refer to the outer `name` —
816
+ // skip the whole subtree instead of only its declaration-name
817
+ // identifier (see this function's docstring for why a `function`/
818
+ // `class` DECLARATION can't get the same treatment this cheaply).
819
+ if (ts.isFunctionExpression(node) && node.name?.text === name) return
820
+
821
+ if (ts.isIdentifier(node) && node.text === name) {
822
+ const p = node.parent
823
+ // Pure-key / non-reference positions — never rewrite. Shared with
824
+ // `analyzer.ts`'s factory-rename `classify()`, which answers the same
825
+ // "is this identifier actually a value reference" question.
826
+ if (isNonReferenceIdentifierPosition(node)) return
827
+ // A function declaration's own name is always followed by `(` in
828
+ // valid source, which is exactly the shape the old
829
+ // `\bname\b(?!\s*\()`-style regex used to recognize and skip. Leaving
830
+ // it unwrapped (rather than declining loudly, as the shadowing
831
+ // declarations below do) matches the old behavior instead of
832
+ // regressing code that used to compile. A `class name {}`
833
+ // declaration's name is followed by `{`/`extends`, not `(`, so the
834
+ // old regex did NOT protect it either — wrapping it is a pre-existing
835
+ // syntax break, not a regression, so it's left to the shadowing-decl
836
+ // path below like any other declaration name.
837
+ if (ts.isFunctionDeclaration(p) && p.name === node) return
838
+ if (ts.isCallExpression(p) && p.expression === node) return // already `name()` — no double-wrap (#2592)
839
+ if (ts.isNewExpression(p) && p.expression === node) return // `new name()` — same "followed by (" shape as a call
840
+
841
+ // Shorthand property (`{ name }`) expands key + wraps value in one
842
+ // edit — the plain-param analogue of `expandShorthandBindings` below.
843
+ // Every other reachable position here is a genuine value reference —
844
+ // OR a shadowing declaration name (nested parameter/`const`/`let`/
845
+ // destructured local): both get wrapped, per this function's
846
+ // docstring on why a shadow is left to fail loudly rather than
847
+ // silently misrewritten.
848
+ const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
849
+ const start = node.getStart(sf) - 1
850
+ const end = node.getEnd() - 1
851
+ edits.push({ start, end, replacement: isShorthand ? `${name}: ${name}()` : `${name}()` })
852
+ return
853
+ }
854
+ ts.forEachChild(node, visit)
855
+ }
856
+ visit(sf)
857
+
858
+ if (edits.length === 0) return expr
859
+ // Apply right-to-left so earlier offsets stay valid as later ones grow.
860
+ edits.sort((a, b) => b.start - a.start)
861
+ let out = expr
862
+ for (const e of edits) {
863
+ out = out.slice(0, e.start) + e.replacement + out.slice(e.end)
864
+ }
865
+ return out
703
866
  }
704
867
 
705
868
  /**