@barefootjs/jsx 0.39.8 → 0.39.9

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 (92) hide show
  1. package/dist/adapters/callback-method.d.ts +19 -7
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/dsl-template-adapter.d.ts +2 -0
  4. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  5. package/dist/adapters/loop-plan.d.ts +133 -9
  6. package/dist/adapters/loop-plan.d.ts.map +1 -1
  7. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  8. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  9. package/dist/analyzer.d.ts.map +1 -1
  10. package/dist/assignment-target.d.ts +26 -0
  11. package/dist/assignment-target.d.ts.map +1 -0
  12. package/dist/errors.d.ts +1 -0
  13. package/dist/errors.d.ts.map +1 -1
  14. package/dist/index.d.ts +4 -4
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1913 -1457
  17. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  20. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  22. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  24. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  26. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  30. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  32. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  35. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  37. package/dist/jsx-to-ir.d.ts.map +1 -1
  38. package/dist/prop-rewrite.d.ts +17 -8
  39. package/dist/prop-rewrite.d.ts.map +1 -1
  40. package/dist/props-binding.d.ts +57 -0
  41. package/dist/props-binding.d.ts.map +1 -1
  42. package/dist/scope/binding-scope.d.ts +30 -2
  43. package/dist/scope/binding-scope.d.ts.map +1 -1
  44. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  45. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  46. package/dist/types.d.ts +25 -1
  47. package/dist/types.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  50. package/src/__tests__/binding-scope.test.ts +29 -0
  51. package/src/__tests__/create-query.test.ts +1 -1
  52. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  53. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  54. package/src/__tests__/loop-plan.test.ts +131 -1
  55. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  56. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  57. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  58. package/src/__tests__/props-alias-const.test.ts +60 -1
  59. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  60. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  61. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  62. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  63. package/src/adapters/callback-method.ts +25 -10
  64. package/src/adapters/dsl-template-adapter.ts +11 -0
  65. package/src/adapters/loop-plan.ts +201 -13
  66. package/src/adapters/parsed-expr-emitter.ts +37 -4
  67. package/src/analyzer.ts +283 -2
  68. package/src/assignment-target.ts +79 -0
  69. package/src/errors.ts +11 -0
  70. package/src/index.ts +13 -2
  71. package/src/ir-to-client-js/compute-inlinability.ts +6 -3
  72. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  73. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  74. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  75. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  76. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  77. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  78. package/src/ir-to-client-js/emit-registration.ts +6 -1
  79. package/src/ir-to-client-js/html-template.ts +18 -7
  80. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  81. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  82. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  83. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  84. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  85. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  86. package/src/ir-to-client-js/utils.ts +40 -96
  87. package/src/jsx-to-ir.ts +31 -12
  88. package/src/prop-rewrite.ts +31 -72
  89. package/src/props-binding.ts +73 -1
  90. package/src/scope/binding-scope.ts +34 -3
  91. package/src/scope/lexical-scope-walk.ts +167 -0
  92. package/src/types.ts +25 -1
@@ -18,6 +18,7 @@ import { BindingScope } from '../scope/binding-scope.ts'
18
18
  import { interp, spliceChildValue, conditionalMarkup, renderChildCall, mappedRowsMarkup, withOuterBindings, dangerousInnerHtml, EMPTY_MARKUP } from './safe-html.ts'
19
19
  import { markupSlotIdsOf } from './markup-slots.ts'
20
20
  import { isEventHandlerName } from '../event-handler-name.ts'
21
+ import { writesAnyBinding } from '../props-binding.ts'
21
22
 
22
23
  /**
23
24
  * Split a template literal body into static segments and `${...}` interpolations,
@@ -2362,12 +2363,14 @@ function propResolvesUnsafe(
2362
2363
  env: CsrEnv,
2363
2364
  unsafeLocalNames: ReadonlySet<string>,
2364
2365
  ): boolean {
2365
- if (unsafeLocalNames.size === 0) return false
2366
2366
  let source: string | undefined
2367
2367
  switch (prop.value.kind) {
2368
2368
  case 'expression':
2369
2369
  case 'spread':
2370
- source = prop.value.expr
2370
+ // The same text the CSR `component` emit reads (`transformExpr(expr,
2371
+ // templateExpr)`): a prop read Phase 1 already lowered to
2372
+ // `_p.<key> ?? <default>` in `templateExpr` names no init local (#3579).
2373
+ source = prop.value.templateExpr ?? prop.value.expr
2371
2374
  break
2372
2375
  case 'template':
2373
2376
  source = attrValueToString(prop.value, { useTemplate: true }) ?? undefined
@@ -2377,8 +2380,8 @@ function propResolvesUnsafe(
2377
2380
  return false
2378
2381
  }
2379
2382
  if (!source) return false
2380
- const { freeIdentifiers } = csrSubstitute(source, env)
2381
- return setIntersects(freeIdentifiers, unsafeLocalNames)
2383
+ const { freeIdentifiers, writes } = csrSubstitute(source, env)
2384
+ return writes.size > 0 || setIntersects(freeIdentifiers, unsafeLocalNames)
2382
2385
  }
2383
2386
 
2384
2387
  /**
@@ -2403,7 +2406,10 @@ export function computeDeferredChildSlots(
2403
2406
  propsObjectName?: string | null,
2404
2407
  ): Set<string> {
2405
2408
  const deferred = new Set<string>()
2406
- if (!unsafeLocalNames || unsafeLocalNames.size === 0) return deferred
2409
+ // A prop can also be dropped for writing a binding (`get={() => ++id}`,
2410
+ // see `transformExpr`), which only a component that writes one can have.
2411
+ if (!writesAnyBinding(ctx) && (!unsafeLocalNames || unsafeLocalNames.size === 0)) return deferred
2412
+ const unsafe = unsafeLocalNames ?? new Set<string>()
2407
2413
  const env = buildCsrEnvForCtx(ctx, inlinableConstants, propsObjectName)
2408
2414
 
2409
2415
  const visit = (n: IRNode): void => {
@@ -2425,7 +2431,7 @@ export function computeDeferredChildSlots(
2425
2431
  if (p.name === 'ref') return false
2426
2432
  if (isEventHandlerName(p.name)) return false
2427
2433
  if (p.clientOnly) return false
2428
- return propResolvesUnsafe(p, env, unsafeLocalNames)
2434
+ return propResolvesUnsafe(p, env, unsafe)
2429
2435
  })
2430
2436
  if (dropped) deferred.add(n.slotId)
2431
2437
  }
@@ -2468,7 +2474,12 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2468
2474
  // the IR — emit does no string transformation of its own (#1277).
2469
2475
  const source = templateExpr ?? expr
2470
2476
  if (!source) return source
2471
- const { rewritten, freeIdentifiers } = csrSubstitute(source, env, opts.scope)
2477
+ const { rewritten, freeIdentifiers, writes } = csrSubstitute(source, env, opts.scope)
2478
+
2479
+ // An expression that writes a binding (`{++nextId}`, a child prop
2480
+ // `() => ++start`) cannot run here: the template has no binding to
2481
+ // write, and the write belongs to init's run of the component.
2482
+ if (writes.size > 0) return UNSAFE_TEMPLATE_EXPR
2472
2483
 
2473
2484
  // The CSR template runs at module scope, so any post-substitution
2474
2485
  // free identifier that lands in `unsafeLocalNames` (init-body-only
@@ -1,7 +1,9 @@
1
1
  /**
2
- * `props-extraction` phase — emit the one surviving one-time prop
3
- * extraction, `const children = _p.children [?? <default>]` (or
4
- * `const kids = _p.children` for a renamed `{ children: kids }`).
2
+ * `props-extraction` phase — emit the one-time prop extractions:
3
+ * `const children = _p.children [?? <default>]` (or `const kids =
4
+ * _p.children` for a renamed `{ children: kids }`), and `let start =
5
+ * _p.start [?? <default>]` for each prop the component writes
6
+ * (`ParamInfo.reassigned`, see `keepsDeclaredValue`).
5
7
  *
6
8
  * `children` must stay a ONE-TIME read: a prop's slot-children value is a
7
9
  * getter that INSTANTIATES child components when read (see
@@ -21,7 +23,7 @@
21
23
 
22
24
  import { type PropUsage, isChildrenPropParam } from '../../types.ts'
23
25
  import { computePropsUsedAsConditions } from '../compute-prop-usage.ts'
24
- import { propReadBase, propReadFallback } from '../../props-binding.ts'
26
+ import { propReadBase, propReadFallback, keepsDeclaredValue } from '../../props-binding.ts'
25
27
  import type { ClientJsContext } from '../types.ts'
26
28
 
27
29
  export function emitPropsExtraction(
@@ -31,6 +33,7 @@ export function emitPropsExtraction(
31
33
  propUsage: Map<string, PropUsage>,
32
34
  ): void {
33
35
  if (ctx.propsObjectName) return
36
+ emitWrittenPropLocals(lines, ctx, propUsage)
34
37
  // The children prop's local binding: `children`, or the renamed local of
35
38
  // `{ children: kids }` (`isChildrenPropParam`, #3572), which reads
36
39
  // `_p.children` the same one-time way. A local named `children` that binds
@@ -45,5 +48,23 @@ export function emitPropsExtraction(
45
48
  const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(local)
46
49
  const fallback = propReadFallback(prop, propUsage.get(local), usedAsCondition)
47
50
  const read = propReadBase(prop) + (fallback === null ? '' : ` ?? ${fallback}`)
48
- lines.push(` const ${local} = ${read}`, '')
51
+ // A children binding the component writes needs a `let` to take the write.
52
+ lines.push(` ${keepsDeclaredValue(prop) ? 'const' : 'let'} ${local} = ${read}`, '')
53
+ }
54
+
55
+ /**
56
+ * A prop the component writes (`++start`, `start = clamp(start)`) is a
57
+ * local it owns, as in JS: declared once from the prop, then read and
58
+ * written in place. It is declared whether or not `neededProps` lists it,
59
+ * since a write is itself a use.
60
+ */
61
+ function emitWrittenPropLocals(lines: string[], ctx: ClientJsContext, propUsage: Map<string, PropUsage>): void {
62
+ const written = ctx.propsParams.filter(p => !p.isRest && !isChildrenPropParam(p) && !keepsDeclaredValue(p))
63
+ if (written.length === 0) return
64
+ const usedAsCondition = computePropsUsedAsConditions(ctx, new Set(written.map(p => p.name)))
65
+ for (const prop of written) {
66
+ const fallback = propReadFallback(prop, propUsage.get(prop.name), usedAsCondition.has(prop.name))
67
+ lines.push(` let ${prop.name} = ${propReadBase(prop)}${fallback === null ? '' : ` ?? ${fallback}`}`)
68
+ }
69
+ lines.push('')
49
70
  }
@@ -130,6 +130,13 @@ function buildSingleCompPlan(
130
130
  indexParam: elem.index || '__idx',
131
131
  outerPreludeStatements: staticPreludeStatements(elem.preamble),
132
132
  propsExpr: buildStaticPropsExpr(props),
133
+ // #3607: the static twin of the component-root loop's `rowEvents` — a
134
+ // static array has no delegation pass for a component row either
135
+ // (`loopEventDelegationVariant`), so each hydrated row attaches the
136
+ // handlers on its forwarded children directly.
137
+ rowEvents: elem.bindings.events
138
+ .filter(ev => ev.nestedLoops.length === 0)
139
+ .map(ev => ({ childSlotId: ev.childSlotId, eventName: ev.eventName, handler: ev.handler })),
133
140
  }
134
141
  }
135
142
 
@@ -25,6 +25,7 @@
25
25
  * shapes were determined by inline branching on the IR.
26
26
  */
27
27
 
28
+ import type { LoopRowEventBinding } from '../control-flow/plan/loop.ts'
28
29
  import type { PreludeStatements } from '../control-flow/plan/inner-loop.ts'
29
30
  import type { LoopChildRefBinding } from '../control-flow/plan/loop.ts'
30
31
  import type { LoopChildReactiveAttr, LoopChildReactiveText } from '../types.ts'
@@ -71,6 +72,13 @@ export interface SingleCompInitPlan {
71
72
  outerPreludeStatements: PreludeStatements
72
73
  /** Pre-built props object expression for the child component. */
73
74
  propsExpr: PropsExpr
75
+ /**
76
+ * Event handlers on elements forwarded as the row component's own
77
+ * `children`, outside any inner loop (#3607). Attached to each hydrated
78
+ * row after its `initChild`. Unwrapped: the forEach binds `param` to the
79
+ * plain item, as for `propsExpr`.
80
+ */
81
+ rowEvents: readonly LoopRowEventBinding[]
74
82
  }
75
83
 
76
84
  /** Plan for one depth-0 component inside `loop.nestedComponents`. */
@@ -27,7 +27,7 @@
27
27
  import ts from 'typescript'
28
28
  import { type PropUsage, isChildrenPropParam } from '../types.ts'
29
29
  import { computePropsUsedAsConditions } from './compute-prop-usage.ts'
30
- import { boundPropLocalNames, livePropReadExpr, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
30
+ import { boundPropLocalNames, livePropReadExpr, keepsDeclaredValue, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
31
31
  import { parsePropReadInitializer } from './prune-unused-prop-extractions.ts'
32
32
  import { rewriteScopedValueRefs } from '../prop-rewrite.ts'
33
33
  import { identifierPattern } from '../identifier-pattern.ts'
@@ -75,7 +75,7 @@ function rewriteParamDestructuredReads(
75
75
  propUsage: ReadonlyMap<string, PropUsage>,
76
76
  ): string {
77
77
  const names = new Set(boundPropLocalNames(ctx))
78
- for (const p of ctx.propsParams) if (isChildrenPropParam(p)) names.delete(p.name)
78
+ for (const p of ctx.propsParams) if (isChildrenPropParam(p) || !keepsDeclaredValue(p)) names.delete(p.name)
79
79
  if (names.size === 0) return code
80
80
 
81
81
  const propsUsedAsConditions = computePropsUsedAsConditions(ctx, names)
@@ -27,6 +27,7 @@ import ts from 'typescript'
27
27
  import { PROPS_PARAM } from './utils.ts'
28
28
  import { identifierPattern } from '../identifier-pattern.ts'
29
29
  import type { BindingScope } from '../scope/binding-scope.ts'
30
+ import { walkWithScope } from '../scope/lexical-scope-walk.ts'
30
31
 
31
32
  export interface PropsObjectRewriteOptions {
32
33
  /**
@@ -105,15 +106,20 @@ function rewriteOneName(code: string, srcPropsName: string): string {
105
106
  // Spans are sorted by `start` ascending in the order TS visits them
106
107
  // (depth-first, source order), so we can apply replacements right-to-
107
108
  // left without re-sorting.
109
+ //
110
+ // Only references that resolve to the component's props binding are
111
+ // renamed. An identifier an inner binding of the same spelling shadows
112
+ // (`.map((props) => …)` row callbacks and their `const props = () =>
113
+ // __e.item` accessors, a handler's own `(props) => …` parameter, a nested
114
+ // `function f(props)`) belongs to that binding: renaming it — binder and
115
+ // references alike — to `_p` would capture every compiler-emitted
116
+ // `_p.<prop>` read of the OUTER props object inside that scope (a
117
+ // destructured prop referenced in the row, a forwarded child prop).
108
118
  const spans: Array<readonly [number, number]> = []
109
-
110
- function visit(node: ts.Node): void {
111
- if (ts.isIdentifier(node) && node.text === srcPropsName && shouldRewrite(node)) {
112
- spans.push([node.getStart(sourceFile), node.getEnd()])
113
- }
114
- ts.forEachChild(node, visit)
115
- }
116
- visit(sourceFile)
119
+ walkWithScope(sourceFile, (node, _parent, shadowed) => {
120
+ if (shadowed || node.text !== srcPropsName || !shouldRewrite(node)) return
121
+ spans.push([node.getStart(sourceFile), node.getEnd()])
122
+ })
117
123
 
118
124
  if (spans.length === 0) return code
119
125
 
@@ -12,6 +12,7 @@
12
12
  * <i> const <param> = <array>[<idx>]
13
13
  * <i> <outerPreludeStatements*> // raw outer preamble (#1064)
14
14
  * <i> initChild('<name>', childScope, <props>)
15
+ * <i> {<each row event: qsa(childScope, …) + addEventListener>}
15
16
  * <i> })
16
17
  * <i>}
17
18
  *
@@ -62,6 +63,7 @@ import { varSlotId } from '../utils.ts'
62
63
  import { emitDedupedAttrUpdate, DEDUP_STORE_DECL } from '../emit-reactive.ts'
63
64
  import { claimPlanLiteral, claimWriterVarName, type ClaimSlotSpec } from '../control-flow/stringify/claim-plan.ts'
64
65
  import { emitLoopChildRefs } from '../control-flow/stringify/loop.ts'
66
+ import { emitRowEventListener } from '../control-flow/shared.ts'
65
67
 
66
68
  export function stringifyStaticArrayChildInits(
67
69
  lines: string[],
@@ -90,7 +92,7 @@ function stringifyOne(lines: string[], plan: StaticArrayChildInitPlan): void {
90
92
  }
91
93
 
92
94
  function emitSingleComp(lines: string[], plan: SingleCompInitPlan): void {
93
- const { containerVar, componentName, childSelector, arrayExpr, param, indexParam, outerPreludeStatements, propsExpr } = plan
95
+ const { containerVar, componentName, childSelector, arrayExpr, param, indexParam, outerPreludeStatements, propsExpr, rowEvents } = plan
94
96
  lines.push(` // Initialize static array children (hydrate skips nested instances)`)
95
97
  lines.push(` if (${containerVar}) {`)
96
98
  lines.push(` const __childScopes = qsaChildScopes(${containerVar}, ${childSelector})`)
@@ -103,6 +105,7 @@ function emitSingleComp(lines: string[], plan: SingleCompInitPlan): void {
103
105
  lines.push(` ${stmt}`)
104
106
  }
105
107
  lines.push(` initChild('${nameForRegistryRef(componentName)}', childScope, ${propsExpr})`)
108
+ for (const ev of rowEvents) emitRowEventListener(lines, ' ', 'childScope', ev)
106
109
  lines.push(` })`)
107
110
  lines.push(` }`)
108
111
  lines.push('')
@@ -7,6 +7,7 @@ import ts from 'typescript'
7
7
  import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR, JsSourceText } from '../types.ts'
8
8
  import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
9
  import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
10
+ import { walkWithScope } from '../scope/lexical-scope-walk.ts'
10
11
  import { BindingScope, type LoopBindingSource } from '../scope/binding-scope.ts'
11
12
  import { buildLoopChainExpr } from '../loop-chain.ts'
12
13
  import { templatePartsToJsExpr } from '../template-parts.ts'
@@ -795,34 +796,15 @@ export function wrapIndexParamAsAccessor(expr: string, indexParam: string): stri
795
796
  * of those positions a type of AST node this function can name and skip,
796
797
  * instead of a regex guessing from surrounding characters.
797
798
  *
798
- * A nested declaration that re-binds `name` (a parameter, a `const`/`let`,
799
- * or a destructured local) is deliberately NOT skipped, unlike
800
- * `analyzer.ts`'s rename `classify()`: this rewrite has no scope tracking,
801
- * so it cannot tell a reference to the shadowing local from a reference to
802
- * the outer loop param past that point, and silently wrapping only the
803
- * OUTER-scope references while leaving the shadowed ones alone (or vice
804
- * versa) would just move the #3239 bug rather than fix it. Wrapping the
805
- * shadowing declaration's own name is always a syntax break at the
806
- * declaration site itself (`const name = 1` → `const name() = 1`, `(name)
807
- * => …` → `(name()) => …` — a call can't legally appear where a binding
808
- * name is expected), so the module fails to parse instead of silently
809
- * running with the wrong value — the same loud, build-time failure the old
810
- * regex produced for this shape (it had no shadow-awareness either).
811
- *
812
- * A NAMED function expression is the one shadowing shape this function
813
- * skips wholesale rather than leaving loud: `(function name() { ... })`'s
814
- * own name is scoped to exactly that expression's body and nowhere else, so
815
- * `visit` never descends into it at all once it sees the self-shadowing
816
- * name — no reference inside can possibly mean the outer `name`. A
817
- * `function`/`class` DECLARATION's name is different: its binding reaches
818
- * into the surrounding scope too (a function declaration's name is hoisted
819
- * above it; a class declaration's own static/instance members can
820
- * self-reference it), so the same whole-subtree skip isn't sound here —
821
- * a self-reference to a `function`/`class` declaration whose name happens
822
- * to match `name` is still silently misrewritten, an accepted
823
- * pre-existing-shaped gap the old regex had too (the "followed by `(`"
824
- * exclusion below only protects the declaration's OWN name token, not
825
- * references reachable from within or after it).
799
+ * A name an inner binding re-binds — a nested callback's parameter (an inner
800
+ * `.map((tag, i) => …)` reusing the outer index name, #3595), a
801
+ * `const`/`let`, a destructured local, a `function`/`class` declaration, a
802
+ * named function expression's own name — is that binding's, not the outer
803
+ * loop param's, for the binding's whole scope. The walk follows the shared
804
+ * lexical-scope model (`walkWithScope`, `scope/lexical-scope-walk.ts`, the
805
+ * same frames the props rewrites use), so it never rewrites the binder
806
+ * itself (`(tag, i()) =>` is not a binding pattern) and leaves every
807
+ * reference the binder shadows alone.
826
808
  */
827
809
  function rewriteIdentifierAsAccessor(expr: string, name: string): string {
828
810
  return rewriteIdentifierReferences(expr, new Map([[name, `${name}()`]]), { skipCallee: true })
@@ -837,14 +819,13 @@ function rewriteIdentifierAsAccessor(expr: string, name: string): string {
837
819
  * reference and why; both callers answer that question here, so they cannot
838
820
  * drift apart (#3260).
839
821
  *
840
- * `skipCallee` leaves `name()` / `new name()` and a `function name()`
841
- * declaration's own name alone. It is the accessor rewrite's no-double-wrap
842
- * rule (#2592): there `name()` already IS the accessor call, and the old
843
- * regex's "followed by (" lookahead skipped all three. A destructured
844
- * binding has no such shape — `handler()` with `({ handler })` calls the
845
- * item's field, so it must become `__bfItem().handler()` — and its caller
846
- * passes `false`, which also leaves a shadowing function declaration to
847
- * fail loudly, as it did under the old destructured regex.
822
+ * `skipCallee` leaves `name()` / `new name()` alone. It is the accessor
823
+ * rewrite's no-double-wrap rule (#2592): there `name()` already IS the
824
+ * accessor call. A destructured binding has no such shape — `handler()` with
825
+ * `({ handler })` calls the item's field, so it must become
826
+ * `__bfItem().handler()` — and its caller passes `false`. A nested
827
+ * `function name() {}` declaration needs neither rule: it binds `name` for
828
+ * its block, so the scope walk leaves its name and its calls alone.
848
829
  *
849
830
  * One pass over the AST, so a replacement is never re-scanned: a binding
850
831
  * `a` with path `.a` cannot cascade into `__bfItem().__bfItem().a`.
@@ -868,66 +849,29 @@ function rewriteIdentifierReferences(
868
849
  const sf = ts.createSourceFile('__bf_expr.ts', wrapped, ts.ScriptTarget.Latest, /* setParentNodes */ true)
869
850
  const edits: Array<{ start: number; end: number; replacement: string }> = []
870
851
 
871
- const visit = (node: ts.Node, active: ReadonlyMap<string, string>): void => {
872
- // A named function expression's own name is scoped to exactly its own
873
- // body, so nothing reachable inside it can refer to the outer binding of
874
- // that name — drop it for the whole subtree instead of only its
875
- // declaration-name identifier (see `rewriteIdentifierAsAccessor`'s
876
- // docstring for why a `function`/`class` DECLARATION can't get the same
877
- // treatment this cheaply). Other names stay active inside.
878
- if (ts.isFunctionExpression(node) && node.name && active.has(node.name.text)) {
879
- const inner = new Map(active)
880
- inner.delete(node.name.text)
881
- if (inner.size === 0) return
882
- ts.forEachChild(node, child => visit(child, inner))
883
- return
884
- }
885
-
886
- if (ts.isIdentifier(node)) {
887
- const replacement = active.get(node.text)
888
- if (replacement === undefined) return
889
- const p = node.parent
890
- // Pure-key / non-reference positions — never rewrite. Shared with
891
- // `analyzer.ts`'s factory-rename `classify()`, which answers the same
892
- // "is this identifier actually a value reference" question.
893
- if (isNonReferenceIdentifierPosition(node)) return
894
- // A function declaration's own name is always followed by `(` in
895
- // valid source, which is exactly the shape the old
896
- // `\bname\b(?!\s*\()`-style regex used to recognize and skip. Leaving
897
- // it unwrapped (rather than declining loudly, as the shadowing
898
- // declarations below do) matches the old behavior instead of
899
- // regressing code that used to compile. A `class name {}`
900
- // declaration's name is followed by `{`/`extends`, not `(`, so the
901
- // old regex did NOT protect it either — wrapping it is a pre-existing
902
- // syntax break, not a regression, so it's left to the shadowing-decl
903
- // path below like any other declaration name.
904
- //
905
- // Accessor mode only: the old destructured-binding regex had no such
906
- // exemption, so there a shadowing `function color() {}` broke the
907
- // declaration loudly. Skipping its name here would keep the local
908
- // function while rewriting its calls to `__bfItem().color()` — valid
909
- // JS that calls the wrong value (#3260 review).
910
- if (opts.skipCallee) {
911
- if (ts.isFunctionDeclaration(p) && p.name === node) return
912
- if (ts.isCallExpression(p) && p.expression === node) return // already `name()` — no double-wrap (#2592)
913
- if (ts.isNewExpression(p) && p.expression === node) return // `new name()` — same "followed by (" shape as a call
914
- }
915
-
916
- // Shorthand property (`{ name }`) expands key + rewrites value in one
917
- // edit (#1244). Every other reachable position here is a genuine
918
- // value reference — OR a shadowing declaration name (nested
919
- // parameter/`const`/`let`/destructured local): both get rewritten,
920
- // per `rewriteIdentifierAsAccessor`'s docstring on why a shadow is
921
- // left to fail loudly rather than silently misrewritten.
922
- const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
923
- const start = node.getStart(sf) - 1
924
- const end = node.getEnd() - 1
925
- edits.push({ start, end, replacement: isShorthand ? `${node.text}: ${replacement}` : replacement })
926
- return
927
- }
928
- ts.forEachChild(node, child => visit(child, active))
929
- }
930
- visit(sf, replacements)
852
+ walkWithScope(sf, (node, p, shadowed) => {
853
+ // An inner binding of the name — the binder itself and every reference
854
+ // it shadows — is not the outer loop param (#3595).
855
+ if (shadowed) return
856
+ const replacement = replacements.get(node.text)
857
+ if (replacement === undefined || !p) return
858
+ // Pure-key / non-reference positions — never rewrite. Shared with
859
+ // `analyzer.ts`'s factory-rename `classify()`, which answers the same
860
+ // "is this identifier actually a value reference" question.
861
+ if (isNonReferenceIdentifierPosition(node)) return
862
+ // Accessor mode only: `name()` already IS the accessor call (#2592), and
863
+ // `new name()` has the same "followed by (" shape. A destructured binding
864
+ // called as a function (`handler()` with `({ handler })`) calls the
865
+ // item's field, so it must become `__bfItem().handler()`.
866
+ if (opts.skipCallee && (ts.isCallExpression(p) || ts.isNewExpression(p)) && p.expression === node) return
867
+
868
+ // Shorthand property (`{ name }`) expands key + rewrites value in one
869
+ // edit (#1244).
870
+ const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
871
+ const start = node.getStart(sf) - 1
872
+ const end = node.getEnd() - 1
873
+ edits.push({ start, end, replacement: isShorthand ? `${node.text}: ${replacement}` : replacement })
874
+ })
931
875
 
932
876
  if (edits.length === 0) return expr
933
877
  // Apply right-to-left so earlier offsets stay valid as later ones grow.
package/src/jsx-to-ir.ts CHANGED
@@ -55,7 +55,7 @@ import {
55
55
  collectAstPropRefs,
56
56
  rewriteScopedValueRefs,
57
57
  } from './prop-rewrite.ts'
58
- import { boundPropLocalNames, buildPropAliasMap, isPropsAliasConst, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
58
+ import { boundPropLocalNames, buildPropAliasMap, isPropsAliasConst, isRenamedBodyPropParam, keepsDeclaredValue, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
59
59
  import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
60
60
  import { walkIR } from './ir-to-client-js/walker.ts'
61
61
  import { resolveFreeRefs, rebindHelperParamRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
@@ -745,17 +745,7 @@ function collectBranchLocalPropRefsViaSubstitution(
745
745
  */
746
746
  function getDestructuredPropNames(ctx: TransformContext): Set<string> | null {
747
747
  if (ctx._destructuredPropNames === undefined) {
748
- const shadowed = new Set<string>()
749
- if (ctx.analyzer.propsObjectName) {
750
- for (const s of ctx.analyzer.signals) {
751
- shadowed.add(s.getter)
752
- if (s.setter) shadowed.add(s.setter)
753
- }
754
- for (const m of ctx.analyzer.memos) shadowed.add(m.name)
755
- for (const c of ctx.analyzer.localConstants) {
756
- if (!isPropsAliasConst(c, ctx.analyzer.propsObjectName)) shadowed.add(c.name)
757
- }
758
- }
748
+ const shadowed = propShadowingNames(ctx.analyzer)
759
749
  const eligible = ctx.analyzer.propsParams.filter(p => !shadowed.has(p.name))
760
750
  const names = eligible.map(p => p.name)
761
751
  ctx._destructuredPropNames = names.length > 0 ? new Set(names) : null
@@ -772,6 +762,35 @@ function getDestructuredPropNames(ctx: TransformContext): Set<string> | null {
772
762
  return ctx._destructuredPropNames ?? null
773
763
  }
774
764
 
765
+ /**
766
+ * The component-scope names that shadow a prop of the same name in a
767
+ * `(props)`-arg component (`getDestructuredPropNames`' shadow guard): its
768
+ * signals, memos and locals, except a local that is the prop itself.
769
+ */
770
+ function propShadowingNames(analyzer: AnalyzerContext): Set<string> {
771
+ const shadowed = new Set<string>()
772
+ if (!analyzer.propsObjectName) return shadowed
773
+ for (const s of analyzer.signals) {
774
+ shadowed.add(s.getter)
775
+ if (s.setter) shadowed.add(s.setter)
776
+ }
777
+ for (const m of analyzer.memos) shadowed.add(m.name)
778
+ for (const c of analyzer.localConstants) {
779
+ // A body destructure binding that is reassigned or mutated no longer
780
+ // holds its prop, renamed or not, so the template keeps it a local.
781
+ if (c.propsDestructure && !keepsDeclaredValue(c)) {
782
+ shadowed.add(c.name)
783
+ continue
784
+ }
785
+ if (isPropsAliasConst(c, analyzer.propsObjectName)) continue
786
+ // A renamed body binding with a default reads as its own prop entry,
787
+ // like the parameter form (#3579).
788
+ if (isRenamedBodyPropParam(c, analyzer.propsParams)) continue
789
+ shadowed.add(c.name)
790
+ }
791
+ return shadowed
792
+ }
793
+
775
794
  /**
776
795
  * Companion to `getDestructuredPropNames`: local-name → `ParamInfo` for the
777
796
  * same shadow-filtered eligible set. Both caches are written in one pass.
@@ -7,84 +7,23 @@
7
7
  * references in the emitted text via a second scope-aware walk over
8
8
  * the text's own AST.
9
9
  *
10
- * Scope model: a name bound INSIDE the expression — a nested arrow /
11
- * function parameter, a block-scoped declaration, a catch variable —
12
- * refers to that binding, not the prop, for the whole binding's scope.
13
- * Both the discovery walk and the rewrite walk carry the same binding
14
- * stack, so `items.map((title) => title.a)` never turns into the
15
- * syntactically invalid `.map((_p.title) => _p.title.a)` when `title`
16
- * is also a prop. (Names bound by loop callbacks that ENCLOSE the
17
- * expression are the caller's job — see the `ctx.scope` filter in
10
+ * Scope model (`walkWithScope`, `scope/lexical-scope-walk.ts`): a name
11
+ * bound INSIDE the expression — a nested arrow / function parameter, a
12
+ * block-scoped declaration, a catch variable — refers to that binding,
13
+ * not the prop, for the whole binding's scope. Both the discovery walk
14
+ * and the rewrite walk carry the same binding stack, so
15
+ * `items.map((title) => title.a)` never turns into the syntactically
16
+ * invalid `.map((_p.title) => _p.title.a)` when `title` is also a prop.
17
+ * (Names bound by loop callbacks that ENCLOSE the expression are the
18
+ * caller's job — see the `ctx.scope` filter in
18
19
  * `jsx-to-ir.ts`'s `rewriteBarePropRefs` wrapper, #2222.)
19
20
  */
20
21
 
21
22
  import ts from 'typescript'
22
23
  import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
23
24
  import { createTemplateAwareStringProtector } from './ir-to-client-js/html-template.ts'
24
-
25
- /** Collect every name introduced by a binding name (identifier or pattern). */
26
- function collectBindingNames(name: ts.BindingName, out: Set<string>): void {
27
- if (ts.isIdentifier(name)) {
28
- out.add(name.text)
29
- return
30
- }
31
- for (const el of name.elements) {
32
- if (ts.isBindingElement(el)) collectBindingNames(el.name, out)
33
- }
34
- }
35
-
36
- /**
37
- * Names bound by `n` for its subtree, or null when `n` introduces no
38
- * scope. Function-likes bind their parameters (and a function
39
- * expression its own name); blocks bind their statement-level
40
- * variable/function declarations; catch clauses bind their variable.
41
- */
42
- function scopeFrameOf(n: ts.Node): Set<string> | null {
43
- if (ts.isFunctionLike(n)) {
44
- const frame = new Set<string>()
45
- for (const p of n.parameters) collectBindingNames(p.name, frame)
46
- if ((ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n)) && n.name) frame.add(n.name.text)
47
- return frame.size > 0 ? frame : null
48
- }
49
- if (ts.isBlock(n)) {
50
- const frame = new Set<string>()
51
- for (const st of n.statements) {
52
- if (ts.isVariableStatement(st)) {
53
- for (const d of st.declarationList.declarations) collectBindingNames(d.name, frame)
54
- } else if (ts.isFunctionDeclaration(st) && st.name) {
55
- frame.add(st.name.text)
56
- }
57
- }
58
- return frame.size > 0 ? frame : null
59
- }
60
- if (ts.isCatchClause(n) && n.variableDeclaration) {
61
- const frame = new Set<string>()
62
- collectBindingNames(n.variableDeclaration.name, frame)
63
- return frame.size > 0 ? frame : null
64
- }
65
- return null
66
- }
67
-
68
- /**
69
- * Depth-first walk that maintains the binding stack described above and
70
- * reports every identifier along with whether a binding within `root`
71
- * currently shadows it.
72
- */
73
- function walkWithScope(
74
- root: ts.Node,
75
- visit: (ident: ts.Identifier, parent: ts.Node | undefined, shadowed: boolean) => void,
76
- ): void {
77
- const scopeStack: Set<string>[] = []
78
- const isShadowed = (name: string) => scopeStack.some(frame => frame.has(name))
79
- function rec(n: ts.Node, parent?: ts.Node) {
80
- const frame = scopeFrameOf(n)
81
- if (frame) scopeStack.push(frame)
82
- if (ts.isIdentifier(n)) visit(n, parent, isShadowed(n.text))
83
- ts.forEachChild(n, child => rec(child, n))
84
- if (frame) scopeStack.pop()
85
- }
86
- rec(root)
87
- }
25
+ import { isAssignmentTargetIdentifier } from './assignment-target.ts'
26
+ import { walkWithScope } from './scope/lexical-scope-walk.ts'
88
27
 
89
28
  /**
90
29
  * True when `n` sits in a non-value position where a prop rewrite must
@@ -148,6 +87,22 @@ export function collectAstPropRefs(
148
87
  })
149
88
  }
150
89
 
90
+ /**
91
+ * The identifiers below `node` that write a name in `names`
92
+ * (`isAssignmentTargetIdentifier`: an assignment, an update, a destructuring
93
+ * assignment or a `for … of/in` head), nested functions included. A write to
94
+ * a name an inner binding shadows (a handler's own `let start`, a
95
+ * `for (let i …)`) is that binding's, not the outer one's, and is left out.
96
+ */
97
+ export function collectAssignmentTargets(node: ts.Node, names: ReadonlySet<string>): ts.Identifier[] {
98
+ const targets: ts.Identifier[] = []
99
+ walkWithScope(node, (n, _parent, shadowed) => {
100
+ if (shadowed || !names.has(n.text)) return
101
+ if (isAssignmentTargetIdentifier(n)) targets.push(n)
102
+ })
103
+ return targets
104
+ }
105
+
151
106
  /**
152
107
  * Scope-aware rewrite: parse `text` as an expression, walk it with the
153
108
  * binding stack, and splice `replacementFor(name)` onto exactly the
@@ -194,6 +149,9 @@ export function rewriteScopedValueRefs(
194
149
  walkWithScope(sf, (n, parent, shadowed) => {
195
150
  if (shadowed || !names.has(n.text)) return
196
151
  if (isNonValuePosition(n, parent)) return
152
+ // A written name (`++title`, `title = x`) keeps its binding: a
153
+ // replacement value is not an assignment target.
154
+ if (isAssignmentTargetIdentifier(n)) return
197
155
  const start = n.getStart(sf) - usedPrefix.length
198
156
  const end = n.getEnd() - usedPrefix.length
199
157
  if (start < 0 || end > text.length) return
@@ -235,6 +193,7 @@ export function splitScopedValueRefs(text: string, names: ReadonlySet<string>):
235
193
  walkWithScope(sf, (n, parent, shadowed) => {
236
194
  if (shadowed || !names.has(n.text)) return
237
195
  if (isNonValuePosition(n, parent)) return
196
+ if (isAssignmentTargetIdentifier(n)) return
238
197
  const start = n.getStart(sf) - prefix.length
239
198
  const end = n.getEnd() - prefix.length
240
199
  if (start < 0 || end > text.length) return