@barefootjs/jsx 0.39.4 → 0.39.6

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 (97) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  14. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  15. package/dist/adapters/literal-value.d.ts +22 -0
  16. package/dist/adapters/literal-value.d.ts.map +1 -0
  17. package/dist/adapters/loop-plan.d.ts +53 -0
  18. package/dist/adapters/loop-plan.d.ts.map +1 -0
  19. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  20. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  21. package/dist/adapters/prop-classes.d.ts +37 -0
  22. package/dist/adapters/prop-classes.d.ts.map +1 -0
  23. package/dist/adapters/template-name-collisions.d.ts +21 -0
  24. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  25. package/dist/analyzer-context.d.ts.map +1 -1
  26. package/dist/expression-parser.d.ts +48 -0
  27. package/dist/expression-parser.d.ts.map +1 -1
  28. package/dist/index.d.ts +20 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +2077 -1000
  31. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +8 -0
  33. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  35. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow/shared.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/utils.d.ts +39 -1
  39. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  40. package/dist/jsx-to-ir.d.ts +465 -1
  41. package/dist/jsx-to-ir.d.ts.map +1 -1
  42. package/dist/nullable-signal-attr.d.ts +31 -0
  43. package/dist/nullable-signal-attr.d.ts.map +1 -1
  44. package/dist/scope/binding-scope.d.ts +10 -0
  45. package/dist/scope/binding-scope.d.ts.map +1 -1
  46. package/dist/types.d.ts +7 -0
  47. package/dist/types.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  50. package/src/__tests__/action-accessor.test.ts +6 -24
  51. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  52. package/src/__tests__/attr-plan.test.ts +121 -0
  53. package/src/__tests__/binding-scope-ratchet.test.ts +13 -13
  54. package/src/__tests__/binding-scope.test.ts +11 -0
  55. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  56. package/src/__tests__/boolean-result.test.ts +34 -1
  57. package/src/__tests__/callback-method.test.ts +189 -0
  58. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  59. package/src/__tests__/component-props.test.ts +148 -0
  60. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  61. package/src/__tests__/doc-examples.test.ts +1 -0
  62. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  63. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  64. package/src/__tests__/loop-plan.test.ts +104 -0
  65. package/src/__tests__/map-call-decisions.test.ts +521 -0
  66. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  67. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  68. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  69. package/src/__tests__/template-name-collisions.test.ts +81 -0
  70. package/src/adapters/array-method.ts +193 -0
  71. package/src/adapters/attr-plan.ts +200 -0
  72. package/src/adapters/boolean-result.ts +208 -12
  73. package/src/adapters/callback-method.ts +301 -0
  74. package/src/adapters/component-props.ts +144 -0
  75. package/src/adapters/component-tree.ts +118 -0
  76. package/src/adapters/filter-capture-collisions.ts +29 -0
  77. package/src/adapters/literal-value.ts +36 -0
  78. package/src/adapters/loop-plan.ts +88 -0
  79. package/src/adapters/parsed-expr-emitter.ts +18 -0
  80. package/src/adapters/prop-classes.ts +73 -0
  81. package/src/adapters/template-name-collisions.ts +120 -0
  82. package/src/analyzer-context.ts +15 -1
  83. package/src/expression-parser.ts +569 -374
  84. package/src/index.ts +58 -3
  85. package/src/ir-to-client-js/collect-elements.ts +11 -7
  86. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +31 -10
  87. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  88. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  89. package/src/ir-to-client-js/control-flow/shared.ts +4 -1
  90. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  91. package/src/ir-to-client-js/html-template.ts +13 -7
  92. package/src/ir-to-client-js/index.ts +7 -2
  93. package/src/ir-to-client-js/utils.ts +81 -7
  94. package/src/jsx-to-ir.ts +1328 -991
  95. package/src/nullable-signal-attr.ts +116 -6
  96. package/src/scope/binding-scope.ts +19 -0
  97. package/src/types.ts +7 -0
package/src/index.ts CHANGED
@@ -117,14 +117,68 @@ export type {
117
117
  export { JsxAdapter } from './adapters/jsx-adapter.ts'
118
118
  export type { JsxAdapterConfig } from './adapters/jsx-adapter.ts'
119
119
  export { rewriteImportsForTemplate, rewriteDynamicImportsInSource } from './adapters/template-imports.ts'
120
- export { emitParsedExpr, groupBinaryOperand, groupObjectLiteralSegments, isStringTypedOperand, isStringConcatBinary } from './adapters/parsed-expr-emitter.ts'
120
+ export { emitParsedExpr, groupBinaryOperand, groupObjectLiteralSegments, isStringTypedOperand, isStringConcatBinary, isNumericArithmeticResult } from './adapters/parsed-expr-emitter.ts'
121
121
  export type { ParsedExprEmitter, LoweringEmitter, HigherOrderMethod, ArrayMethod, SortMethod, LiteralType } from './adapters/parsed-expr-emitter.ts'
122
122
  export { collectLoopBoundNames } from './adapters/loop-bound-names.ts'
123
- export { isBooleanResultParsed, stringifyBooleanTernaryBranches } from './adapters/boolean-result.ts'
123
+ export { filterCaptureCollisions } from './adapters/filter-capture-collisions.ts'
124
+ export { templateNameCollisionErrors } from './adapters/template-name-collisions.ts'
125
+ export {
126
+ collectBooleanValueNames,
127
+ isAriaBooleanAttr,
128
+ isBooleanResultExpr,
129
+ isBooleanResultParsed,
130
+ isExplicitStringCall,
131
+ stringifyBooleanTernaryBranches,
132
+ } from './adapters/boolean-result.ts'
133
+ export { isBareStringLiteral, isLiteralIndex, isStringTypeInfo } from './adapters/literal-value.ts'
134
+ export { collectBooleanTypedProps, collectNullableOptionalProps, isBooleanTypedPropRef } from './adapters/prop-classes.ts'
135
+ export type { BooleanTypedPropContext } from './adapters/prop-classes.ts'
136
+ export { collectImportedLoopChildComponentErrors, hasClientInteractivity } from './adapters/component-tree.ts'
137
+ export {
138
+ ARRAY_METHOD_CATALOGUE,
139
+ emitArrayMethod,
140
+ lowerArrayMethod,
141
+ prefixedArrayMethodSpelling,
142
+ } from './adapters/array-method.ts'
143
+ export {
144
+ emitCallbackEval,
145
+ isPredicateMethod,
146
+ lowerCallbackMethod,
147
+ nestedCallbackRefusal,
148
+ sortEvalPlan,
149
+ sortRefusal,
150
+ } from './adapters/callback-method.ts'
151
+ export type {
152
+ CallbackEvalHelper,
153
+ CallbackEvalOperand,
154
+ CallbackEvalPlan,
155
+ CallbackEvalSpelling,
156
+ CallbackLoweringOptions,
157
+ CallbackPlan,
158
+ PredicateMethod,
159
+ } from './adapters/callback-method.ts'
160
+ export type {
161
+ ArrayMethodArg,
162
+ ArrayMethodDefault,
163
+ ArrayMethodEntry,
164
+ ArrayMethodHelper,
165
+ ArrayMethodParam,
166
+ ArrayMethodPlan,
167
+ ArrayMethodSpelling,
168
+ } from './adapters/array-method.ts'
124
169
  export { derivesScopeFromSlot } from './adapters/child-scope.ts'
170
+ export { childTemplateName, componentPropKey, isEmptyComponentProps, planComponentProps, spellComponentProps } from './adapters/component-props.ts'
171
+ export type { ComponentPropEntry, ComponentPropSegment, ComponentPropSpelling, ComponentPropsOptions, SpelledComponentPropSegment } from './adapters/component-props.ts'
172
+ export { parseUndefinedAlternateTernary, planAttrExpression, planSpreadAttr, unsupportedAttrExpression } from './adapters/attr-plan.ts'
173
+ export type { AttrExpressionPlan, AttrPlanContext, SpreadAttrPlan, SpreadPlanContext, UndefinedAlternateTernary } from './adapters/attr-plan.ts'
174
+ export { planLoop } from './adapters/loop-plan.ts'
175
+ export type { LoopPlan, LoopPlanContext } from './adapters/loop-plan.ts'
125
176
  export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
126
177
  export {
127
178
  arithmeticOperandIsNull,
179
+ arithmeticOperandIsUndefined,
180
+ arithmeticOperandCoercion,
181
+ bareGetterCallName,
128
182
  attrValueMayBeNullish,
129
183
  collectNullableSignalGetters,
130
184
  collectNullishAttrContext,
@@ -133,6 +187,7 @@ export {
133
187
  NULL_COERCING_ARITHMETIC_OPS,
134
188
  nullableSignalAttrGetter,
135
189
  type NullishAttrContext,
190
+ type ArithmeticCoercion,
136
191
  } from './nullable-signal-attr.ts'
137
192
  export { importsSearchParams, searchParamsLocalNames, envSignalLocalNames, envSignalReaderFor, ENV_SIGNAL_READERS, queryHrefLocalNames, matchSearchParamsMethodCall } from './adapters/env-signal.ts'
138
193
  export type { EnvSignalReader } from './adapters/env-signal.ts'
@@ -249,7 +304,7 @@ export { ErrorCodes, createError, formatError, generateCodeFrame } from './error
249
304
  export { isValueReferenceIdentifier, collectValueReferencedNames } from './value-references.ts'
250
305
 
251
306
  // Expression Parser
252
- export { parseExpression, tsNodeToParsedExpr, asCallbackMethodCall, CALLBACK_METHODS, sortComparatorFromArrow, serializeParsedExpr, freeVarsInBody, freeIdentifiers, materializeGetterCalls, isSupported, isSupportedValue, exprToString, stringifyParsedExpr, identifierPath, parseBlockBody, parseBlockBodyTolerant, foldBlockToExpr, predicateTernaryToLogical, containsHigherOrder, extractArrowBodyExpression, parseStyleObjectEntries, hasUnsafeStyleValue, parseProviderObjectLiteral, isFunctionShapedExpression, type ProviderObjectMember, type FoldBlockOptions } from './expression-parser.ts'
307
+ export { parseExpression, tsNodeToParsedExpr, asCallbackMethodCall, hasOpaqueCall, unboundCallbackParamRead, unboundCallbackParamReason, CALLBACK_METHODS, sortComparatorFromArrow, serializeParsedExpr, freeVarsInBody, freeIdentifiers, renameFreeIdentifiers, materializeGetterCalls, isSupported, isSupportedValue, exprToString, stringifyParsedExpr, identifierPath, parseBlockBody, parseBlockBodyTolerant, foldBlockToExpr, predicateTernaryToLogical, containsHigherOrder, extractArrowBodyExpression, parseStyleObjectEntries, hasUnsafeStyleValue, parseProviderObjectLiteral, isFunctionShapedExpression, type ProviderObjectMember, type FoldBlockOptions } from './expression-parser.ts'
253
308
  export type { StyleObjectEntry } from './expression-parser.ts'
254
309
  export { literalMemberIndex } from './literal-member-index.ts'
255
310
  export { PARSED_EXPR_KINDS, ARRAY_METHOD_NAMES, SORT_KEY_TYPES, SORT_KEY_TARGETS, SORT_KEY_DIRECTIONS } from './expression-parser.ts'
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { type IRNode, type IRElement, type IRComponent, type IRConditional, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
6
6
  import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
7
- import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, type LoopParamSpec } from './utils.ts'
7
+ import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, rowBoundNames, withRowAccessor, type LoopParamSpec } from './utils.ts'
8
8
  import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectConditionalBranchComponentNodes, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
9
9
  import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
10
10
  import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
@@ -328,12 +328,16 @@ export function collectInnerLoops(
328
328
  },
329
329
  loop: ({ node: n, scope, descend }) => {
330
330
  const emitDepth = fixedDepth ?? scope.depth + 1
331
+ // This nested row reads its destructure bindings through its own
332
+ // accessor, not the enclosing row's `__bfItem` (#3397).
333
+ const rowBindings = withRowAccessor(n.paramBindings, n.markerId)
331
334
  // Generate item template for CSR rendering in mapArray.
332
335
  // Pass loopParams so expressions are wrapped at generation time (not post-hoc regex).
333
336
  // Forward destructured bindings (#951) so inner-loop template
334
337
  // references to the destructured locals are rewritten.
338
+ // The outer spec skips the names this row rebinds (#3394).
335
339
  const loopParamsForTemplate = outerSpec
336
- ? [outerSpec, { param: n.param, bindings: n.paramBindings, index: n.index }]
340
+ ? [{ ...outerSpec, shadowed: rowBoundNames(n) }, { param: n.param, bindings: rowBindings, index: n.index }]
337
341
  : undefined
338
342
  const template = n.children.map(c => irToPlaceholderTemplate(c, undefined, emitDepth, loopParamsForTemplate)).join('')
339
343
  // Per-item bindings for inner loop body, collected uniformly when
@@ -369,8 +373,8 @@ export function collectInnerLoops(
369
373
  // guarantees the branch's marker is mounted the moment this
370
374
  // effect first runs (issue-2706-nested-loop-conditional-slot
371
375
  // .test.ts's original repro).
372
- bindings.reactiveTexts.push(...collectLoopChildReactiveTexts(child, ctx, n.param, n.paramBindings, true, innerPreambleNames, n.index, scope.bindingScope))
373
- bindings.reactiveAttrs.push(...collectLoopChildReactiveAttrs(child, ctx, n.param, n.paramBindings, true, innerPreambleNames, n.index, scope.bindingScope))
376
+ bindings.reactiveTexts.push(...collectLoopChildReactiveTexts(child, ctx, n.param, rowBindings, true, innerPreambleNames, n.index, scope.bindingScope))
377
+ bindings.reactiveAttrs.push(...collectLoopChildReactiveAttrs(child, ctx, n.param, rowBindings, true, innerPreambleNames, n.index, scope.bindingScope))
374
378
  bindings.refs.push(...collectLoopChildRefs(child))
375
379
  }
376
380
  bindings.conditionals.push(...collectLoopChildConditionals(
@@ -378,7 +382,7 @@ export function collectInnerLoops(
378
382
  ctx,
379
383
  siblingOffsets,
380
384
  n.param,
381
- n.paramBindings,
385
+ rowBindings,
382
386
  innerPreambleNames,
383
387
  n.index,
384
388
  // Render a branch's HTML against the FULL ancestor chain (outer
@@ -427,7 +431,7 @@ export function collectInnerLoops(
427
431
  array: n.array,
428
432
  arrayFreeIdentifiers: n.arrayFreeIdentifiers,
429
433
  param: n.param,
430
- paramBindings: n.paramBindings,
434
+ paramBindings: rowBindings,
431
435
  index: n.index,
432
436
  key: n.key,
433
437
  markerId: n.markerId,
@@ -451,7 +455,7 @@ export function collectInnerLoops(
451
455
  descend({
452
456
  ...scope,
453
457
  depth: scope.depth + 1,
454
- bindingScope: buildLoopRowScope(n.param, n.paramBindings, innerPreambleNames, n.index, scope.bindingScope),
458
+ bindingScope: buildLoopRowScope(n.param, rowBindings, innerPreambleNames, n.index, scope.bindingScope),
455
459
  })
456
460
  }
457
461
  },
@@ -36,6 +36,9 @@ import type {
36
36
  import { AttrValueOf, pickAttrMeta } from '../../../types.ts'
37
37
  import {
38
38
  wrapLoopParamAsAccessor,
39
+ rowBoundNames,
40
+ unionNames,
41
+ type ShadowableWrap,
39
42
  attrValueToString,
40
43
  } from '../../utils.ts'
41
44
  import { buildChildRefBindings } from '../shared.ts'
@@ -93,6 +96,13 @@ export interface BuildInnerLoopsArgs {
93
96
  * inside it is looked up through the row's registered roots (`qsaItem`).
94
97
  */
95
98
  rowHasPortal?: boolean
99
+ /**
100
+ * Every enclosing loop's accessor rewrite, composed (#3397). A recursion
101
+ * for a deeper level passes it so a row two or more loops deep still
102
+ * rewrites its grandparent's bindings; the top call builds it from
103
+ * `outerLoopParam`.
104
+ */
105
+ wrapOuter?: ShadowableWrap
96
106
  }
97
107
 
98
108
  /**
@@ -102,9 +112,9 @@ export interface BuildInnerLoopsArgs {
102
112
  */
103
113
  export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
104
114
  const { levels, parentElVar, outerLoopParam, outerLoopParamBindings, outerLoopIndex, rowHasPortal } = args
105
- const wrapOuter = outerLoopParam
106
- ? (expr: string) => wrapLoopParamAsAccessor(expr, outerLoopParam, outerLoopParamBindings, outerLoopIndex)
107
- : (expr: string) => expr
115
+ const wrapOuter: ShadowableWrap = args.wrapOuter ?? (outerLoopParam
116
+ ? (expr, shadowed) => wrapLoopParamAsAccessor(expr, outerLoopParam, outerLoopParamBindings, outerLoopIndex, shadowed)
117
+ : expr => expr)
108
118
 
109
119
  const plan: InnerLoopPlan[] = []
110
120
  let i = 0
@@ -142,6 +152,12 @@ export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
142
152
  outerLoopParam: inner.param,
143
153
  outerLoopParamBindings: inner.paramBindings,
144
154
  outerLoopIndex: inner.index,
155
+ // This row's accessor over every enclosing one, so a deeper row
156
+ // still rewrites the outer rows' bindings (#3397).
157
+ wrapOuter: (expr, shadowed) => wrapLoopParamAsAccessor(
158
+ wrapOuter(expr, unionNames(rowBoundNames(inner), shadowed)),
159
+ inner.param, inner.paramBindings, inner.index, shadowed,
160
+ ),
145
161
  })
146
162
  : []
147
163
 
@@ -170,14 +186,19 @@ export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
170
186
  function buildReactiveEmit(
171
187
  inner: NestedLoop,
172
188
  level: DepthLevel,
173
- wrapOuter: (expr: string) => string,
189
+ wrapOuter: ShadowableWrap,
174
190
  uidSuffix: string,
175
191
  outerLoopParam?: string,
176
192
  outerLoopParamBindings?: readonly LoopParamBinding[],
177
193
  outerLoopIndex?: string | null,
178
194
  ): InnerLoopReactiveEmit {
179
195
  const wrapInner = (expr: string) => wrapLoopParamAsAccessor(expr, inner.param, inner.paramBindings, inner.index)
180
- const wrapBoth = (expr: string) => wrapLoopParamAsAccessor(wrapOuter(expr), inner.param, inner.paramBindings, inner.index)
196
+ // Inside the inner row, a name it rebinds (item, index, destructure
197
+ // binding, preamble local) is not the outer row's binding (#3394).
198
+ const innerShadowed = rowBoundNames(inner)
199
+ const wrapOuterRow: ShadowableWrap = (expr, shadowed) => wrapOuter(expr, unionNames(innerShadowed, shadowed))
200
+ const wrapBoth: ShadowableWrap = (expr, shadowed) =>
201
+ wrapLoopParamAsAccessor(wrapOuterRow(expr, shadowed), inner.param, inner.paramBindings, inner.index, shadowed)
181
202
  const { head: paramHead, unwrap: paramUnwrap } = destructureLoopParam(inner.param, inner.paramBindings)
182
203
  const wrappedKey = inner.key
183
204
  ? wrapLoopParamAsAccessor(inner.key, inner.param, inner.paramBindings, inner.index)
@@ -217,12 +238,12 @@ function buildReactiveEmit(
217
238
 
218
239
  const reactiveTexts: InnerLoopText[] = inner.bindings.reactiveTexts.map(text => ({
219
240
  slotId: text.slotId,
220
- wrappedExpression: wrapLoopParamAsAccessor(wrapOuter(text.expression), inner.param, inner.paramBindings, inner.index),
241
+ wrappedExpression: wrapLoopParamAsAccessor(wrapOuterRow(text.expression), inner.param, inner.paramBindings, inner.index),
221
242
  insideConditional: !!text.insideConditional,
222
243
  }))
223
244
 
224
245
  const reactiveAttrs: InnerLoopReactiveAttr[] = inner.bindings.reactiveAttrs.map(attr => {
225
- const wrapped = wrapLoopParamAsAccessor(wrapOuter(attr.expression), inner.param, inner.paramBindings, inner.index)
246
+ const wrapped = wrapLoopParamAsAccessor(wrapOuterRow(attr.expression), inner.param, inner.paramBindings, inner.index)
226
247
  return {
227
248
  slotId: attr.childSlotId,
228
249
  attrName: attr.attrName,
@@ -252,15 +273,15 @@ function buildReactiveEmit(
252
273
  if (paramUnwrap) preludeStatements.push(paramUnwrap)
253
274
  if (inner.preamble) {
254
275
  // Leaf JSX renders under both param contexts, mirroring the
255
- // wrapInner(wrapOuter(...)) applied to the js text.
276
+ // wrapInner(wrapOuterRow(...)) applied to the js text.
256
277
  const leafLoopParams = outerLoopParam
257
278
  ? [
258
- { param: outerLoopParam, bindings: outerLoopParamBindings, index: outerLoopIndex },
279
+ { param: outerLoopParam, bindings: outerLoopParamBindings, index: outerLoopIndex, shadowed: innerShadowed },
259
280
  { param: inner.param, bindings: inner.paramBindings, index: inner.index },
260
281
  ]
261
282
  : [{ param: inner.param, bindings: inner.paramBindings, index: inner.index }]
262
283
  preludeStatements.push(renderPreamble(inner.preamble, {
263
- transformJs: (t) => wrapInner(wrapOuter(t)),
284
+ transformJs: (t) => wrapInner(wrapOuterRow(t)),
264
285
  renderLeaf: (ir) => irToHtmlTemplate(ir, undefined, 1, leafLoopParams, undefined),
265
286
  }))
266
287
  }
@@ -24,7 +24,7 @@ import type {
24
24
  LoopParamBinding,
25
25
  } from '../../../types.ts'
26
26
  import { AttrValueOf, pickAttrMeta } from '../../../types.ts'
27
- import { quotePropName, wrapLoopParamAsAccessor, attrValueToString } from '../../utils.ts'
27
+ import { quotePropName, wrapLoopParamAsAccessor, attrValueToString, rowBoundNames, unionNames, type ShadowableWrap } from '../../utils.ts'
28
28
  import { addCondAttrToTemplate, irChildrenToJsExpr } from '../../html-template.ts'
29
29
  import type { ReactiveAttrSlot } from './reactive-effects.ts'
30
30
 
@@ -234,7 +234,7 @@ export interface BuildBranchInnerLoopsArgs {
234
234
  * Outer-wrap closure — defaults to wrapping with `outerLoopParam`. Overridden
235
235
  * by `emitNestedLoopChildConditionals` recursion (which threads its own wrap).
236
236
  */
237
- wrapOuter: (expr: string) => string
237
+ wrapOuter: ShadowableWrap
238
238
  }
239
239
 
240
240
  /**
@@ -269,7 +269,14 @@ export function buildBranchInnerLoopsPlan(
269
269
  if (!inner.template) continue
270
270
 
271
271
  const wrapInner = (expr: string) => wrapLoopParamAsAccessor(expr, inner.param, inner.paramBindings, inner.index)
272
- const wrapBoth = (expr: string) => wrapLoopParamAsAccessor(wrapOuter(expr), inner.param, inner.paramBindings, inner.index)
272
+ // Inside the inner row, a name it rebinds is not the outer row's
273
+ // binding (#3394).
274
+ // `wrapOuter` already composes every enclosing loop's rewrite; pass the
275
+ // shadowed names through it so each of them skips them.
276
+ const innerShadowed = rowBoundNames(inner)
277
+ const wrapOuterRow: ShadowableWrap = (expr, shadowed) => wrapOuter(expr, unionNames(innerShadowed, shadowed))
278
+ const wrapBoth: ShadowableWrap = (expr, shadowed) =>
279
+ wrapLoopParamAsAccessor(wrapOuterRow(expr, shadowed), inner.param, inner.paramBindings, inner.index, shadowed)
273
280
 
274
281
  const csl = inner.containerSlotId
275
282
  // Inner loop's container: host-side `bf="<slot>"` slot marker first,
@@ -378,7 +385,7 @@ export interface BuildLoopChildConditionalsArgs {
378
385
  /** Element variable used as `insert(scopeVar, ...)` first arg. */
379
386
  scopeVar: string
380
387
  /** Wrap closure for condition / HTML / handlers. */
381
- wrap: (expr: string) => string
388
+ wrap: ShadowableWrap
382
389
  /**
383
390
  * Loop param identifier — the wrap that wires the recursion's nested
384
391
  * inner loops uses this. Typically equals the inner loop's param when
@@ -501,7 +508,7 @@ export function buildArmTextsPlan(
501
508
 
502
509
  interface BuildLoopChildArmArgs {
503
510
  branch: LoopChildBranchSummary
504
- wrap: (expr: string) => string
511
+ wrap: ShadowableWrap
505
512
  loopParam: string
506
513
  loopParamBindings?: readonly LoopParamBinding[]
507
514
  /** Loop's index param name, when it declares one (#2861). */
@@ -29,7 +29,7 @@ import type {
29
29
  } from '../../types.ts'
30
30
  import type { LoopParamBinding } from '../../../types.ts'
31
31
  import { pickAttrMeta } from '../../../types.ts'
32
- import { wrapLoopParamAsAccessor } from '../../utils.ts'
32
+ import { wrapLoopParamAsAccessor, type ShadowableWrap } from '../../utils.ts'
33
33
  import { addCondAttrToTemplate } from '../../html-template.ts'
34
34
  import {
35
35
  buildArmAttrsPlan,
@@ -65,7 +65,7 @@ export function buildReactiveEffectsPlan(
65
65
  args: BuildReactiveEffectsArgs,
66
66
  ): ReactiveEffectsPlan {
67
67
  const { attrs, texts, conditionals, loopParam, loopParamBindings, loopIndex, profileComponentName } = args
68
- const wrap = (expr: string) => wrapLoopParamAsAccessor(expr, loopParam, loopParamBindings, loopIndex)
68
+ const wrap: ShadowableWrap = (expr, shadowed) => wrapLoopParamAsAccessor(expr, loopParam, loopParamBindings, loopIndex, shadowed)
69
69
 
70
70
  // 1. Group attrs by slot, preserving declaration order (Map insertion order
71
71
  // matches the legacy iteration that produced byte-identical output).
@@ -232,7 +232,10 @@ export function destructureLoopParam(
232
232
  ): { head: string; unwrap: string } {
233
233
  if (param.startsWith('[') || param.startsWith('{')) {
234
234
  if (paramBindings && paramBindings.length > 0) {
235
- return { head: '__bfItem', unwrap: '' }
235
+ // A nested row names its accessor after its loop (`withRowAccessor`,
236
+ // #3397), so it does not shadow an enclosing row's `__bfItem`.
237
+ const accessor = paramBindings[0].accessor
238
+ return { head: accessor ? accessor.replace(/\(\)$/, '') : '__bfItem', unwrap: '' }
236
239
  }
237
240
  return {
238
241
  head: '__bfItem',
@@ -221,7 +221,7 @@ function emitKeyedLookup(
221
221
  if (hasBindings) {
222
222
  // TDZ-safe shape — see #951.
223
223
  ls.push(` const __bfLoopItem = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`)
224
- ls.push(` if (__bfLoopItem) {`)
224
+ ls.push(` if (__bfLoopItem !== undefined) {`)
225
225
  ls.push(` const ${param} = __bfLoopItem`)
226
226
  if (preambleLine) ls.push(` ${preambleLine}`)
227
227
  if (idxLine) ls.push(` ${idxLine}`)
@@ -239,8 +239,10 @@ function emitKeyedLookup(
239
239
  // the item null guard — a `.find()` miss (stale-DOM race, e.g. the
240
240
  // clicked row's key no longer in the current array) must short-circuit
241
241
  // before a preamble that dereferences the item ever runs (BUG-4).
242
+ // Every item guard here tests for that miss (`undefined`), never
243
+ // truthiness: a row item can be `0`, `''` or `false` (#3433).
242
244
  ls.push(` const ${param} = ${arrayExpr}.find(item => String(${keyWithItem}) === key)`)
243
- ls.push(` if (${param}) {`)
245
+ ls.push(` if (${param} !== undefined) {`)
244
246
  if (preambleLine) ls.push(` ${preambleLine}`)
245
247
  if (idxLine) ls.push(` ${idxLine}`)
246
248
  ls.push(` ;${handlerCall}`)
@@ -273,14 +275,14 @@ function emitKeyedLookup(
273
275
  ? substituteLoopBindings(rawKey, nested.paramBindings, 'item')
274
276
  : rawKey.replace(identifierPattern(nested.param, 'g'), 'item')
275
277
  const outerRef = hasBindings ? '__bfLoopItem' : param
276
- ls.push(` const ${nested.param} = ${outerRef} && ${nested.array}.find(item => String(${innerKeyExpr}) === innerKey${nested.depth})`)
278
+ ls.push(` const ${nested.param} = ${outerRef} !== undefined ? ${nested.array}.find(item => String(${innerKeyExpr}) === innerKey${nested.depth}) : undefined`)
277
279
  }
278
280
  const outerGuard = hasBindings ? '__bfLoopItem' : param
279
281
  const allParams = [outerGuard, ...ev.nestedLoops.map(n => n.param)]
280
282
  // Preamble and idx binding run INSIDE the combined item guard (BUG-4) —
281
283
  // a nested `.find()` miss must short-circuit before the preamble runs.
282
284
  const idxLine = indexBindingLine(ev.handler, indexParam, `${arrayExpr}.findIndex(item => String(${keyWithItem}) === outerKey)`)
283
- ls.push(` if (${allParams.join(' && ')}) {`)
285
+ ls.push(` if (${allParams.map(p => `${p} !== undefined`).join(' && ')}) {`)
284
286
  if (preambleLine) ls.push(` ${preambleLine}`)
285
287
  if (idxLine) ls.push(` ${idxLine}`)
286
288
  ls.push(` ;${handlerCall}`)
@@ -301,7 +303,7 @@ function emitDynamicIndexLookup(
301
303
  ls.push(` const idx = Array.from(li.parentElement.children).indexOf(li)`)
302
304
  if (hasBindings) {
303
305
  ls.push(` const __bfLoopItem = ${arrayExpr}[idx]`)
304
- ls.push(` if (__bfLoopItem) {`)
306
+ ls.push(` if (__bfLoopItem !== undefined) {`)
305
307
  ls.push(` const ${param} = __bfLoopItem`)
306
308
  if (preambleLine) ls.push(` ${preambleLine}`)
307
309
  if (idxLine) ls.push(` ${idxLine}`)
@@ -311,7 +313,7 @@ function emitDynamicIndexLookup(
311
313
  // Preamble and idx binding run INSIDE the item null guard (BUG-4) — an
312
314
  // out-of-range index (stale-DOM race) must short-circuit first.
313
315
  ls.push(` const ${param} = ${arrayExpr}[idx]`)
314
- ls.push(` if (${param}) {`)
316
+ ls.push(` if (${param} !== undefined) {`)
315
317
  if (preambleLine) ls.push(` ${preambleLine}`)
316
318
  if (idxLine) ls.push(` ${idxLine}`)
317
319
  ls.push(` ;${handlerCall}`)
@@ -338,7 +340,7 @@ function emitStaticIndexLookup(
338
340
  ls.push(` const ${param} = ${arrayExpr}[__idx]`)
339
341
  // Preamble and idx binding run INSIDE the item null guard (BUG-4) — an
340
342
  // out-of-range index (stale-DOM race) must short-circuit first.
341
- ls.push(` if (${param}) {`)
343
+ ls.push(` if (${param} !== undefined) {`)
342
344
  // Nested static `.map()` params (#3240): static arrays carry no
343
345
  // data-key markers, so — unlike `emitKeyedLookup`'s nested branch, which
344
346
  // resolves each level via `closest('[data-key-N]')` — each nested level's
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type { AttrValue, FlatMapCallback, IRAttribute, IRElement, IRExpression, IRNode, IRProp, MapCallbackPreamble } from '../types.ts'
6
6
  import { isBooleanAttr } from '../html-constants.ts'
7
- import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_PH, keyAttrName, loopStartMarker, loopEndMarker, loopItemMarker, freeIdsFromRefs, setIntersects, wrapExprWithLoopParams } from './utils.ts'
7
+ import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_PH, keyAttrName, loopStartMarker, loopEndMarker, loopItemMarker, freeIdsFromRefs, setIntersects, wrapExprWithLoopParams, specsInsideRow } from './utils.ts'
8
8
  import type { LoopParamSpec } from './utils.ts'
9
9
  import { nameForRegistryRef } from './component-scope.ts'
10
10
  import { assertNever } from './walker.ts'
@@ -965,7 +965,10 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
965
965
  // Increment loopDepth so inner key attrs become data-key-N
966
966
  // Forward loopParams so expressions referencing outer/inner loop params
967
967
  // get wrapped as signal accessors (e.g., task.title → task().title).
968
- const innerRecurse = (n: IRNode): string => irToHtmlTemplate(n, restSpreadNames, loopDepth + 1, loopParams, branchSlotsVar)
968
+ // Inside the row, a name the row rebinds is no longer an enclosing
969
+ // loop's binding (#3394).
970
+ const rowLoopParams = specsInsideRow(loopParams, node)
971
+ const innerRecurse = (n: IRNode): string => irToHtmlTemplate(n, restSpreadNames, loopDepth + 1, rowLoopParams, branchSlotsVar)
969
972
  let childTemplate = node.children.map(innerRecurse).join('')
970
973
  // Whole-item conditional loops (#1665): prepend an always-present
971
974
  // `<!--bf-loop-i:KEY-->` anchor before each item's (possibly empty)
@@ -1001,13 +1004,13 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
1001
1004
  // `mapArray` stamps on adoption/creation, so SSR, hydrate template and
1002
1005
  // csr-mount agree on it (see `leafKeyAsDataKeyAttr`).
1003
1006
  const body = renderPreamble(node.flatMapCallback, {
1004
- renderLeaf: (ir) => irToHtmlTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, loopParams, branchSlotsVar),
1007
+ renderLeaf: (ir) => irToHtmlTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, rowLoopParams, branchSlotsVar),
1005
1008
  })
1006
1009
  mapExpr = interp(mappedRowsMarkup(wrappedArray, 'flatMap', node.flatMapCallback.params, body))
1007
1010
  } else if (node.preamble) {
1008
1011
  // Stage 3 / D4 — render JSX leaves in an arbitrary array-builder
1009
1012
  // preamble (the hydrate-template context uses the bare loop param).
1010
- const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToHtmlTemplate(ir, restSpreadNames, loopDepth + 1, loopParams, branchSlotsVar) })
1013
+ const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToHtmlTemplate(ir, restSpreadNames, loopDepth + 1, rowLoopParams, branchSlotsVar) })
1011
1014
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`))
1012
1015
  } else {
1013
1016
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `\`${childTemplate}\``))
@@ -1455,7 +1458,10 @@ export function irToPlaceholderTemplate(node: IRNode, restSpreadNames?: Readonly
1455
1458
  case 'loop': {
1456
1459
  // Inner loops: generate inline .map().join('') with placeholders for components
1457
1460
  // Forward loopParams so inner loop param expressions get wrapped as signal accessors.
1458
- const innerRecurse = (n: IRNode): string => irToPlaceholderTemplate(n, restSpreadNames, loopDepth + 1, loopParams)
1461
+ // Inside the row, a name the row rebinds is no longer an enclosing
1462
+ // loop's binding (#3394).
1463
+ const rowLoopParams = specsInsideRow(loopParams, node)
1464
+ const innerRecurse = (n: IRNode): string => irToPlaceholderTemplate(n, restSpreadNames, loopDepth + 1, rowLoopParams)
1459
1465
  const childTemplate = node.children.map(innerRecurse).join('')
1460
1466
  const indexParam = node.index ? `, ${node.index}` : ''
1461
1467
  // Apply sort / filter chain (#1448 Tier B) — same shape as the
@@ -1468,12 +1474,12 @@ export function irToPlaceholderTemplate(node: IRNode, restSpreadNames?: Readonly
1468
1474
  if (node.flatMapCallback) {
1469
1475
  const body = renderPreamble(node.flatMapCallback, {
1470
1476
  // Leaf `key` → `data-key` — see the irToHtmlTemplate site above.
1471
- renderLeaf: (ir) => irToPlaceholderTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, loopParams),
1477
+ renderLeaf: (ir) => irToPlaceholderTemplate(leafKeyAsDataKeyAttr(ir), restSpreadNames, loopDepth + 1, rowLoopParams),
1472
1478
  })
1473
1479
  mapExpr = interp(mappedRowsMarkup(wrappedArray, 'flatMap', node.flatMapCallback.params, body))
1474
1480
  } else if (node.preamble) {
1475
1481
  // Stage 3 / D4 — render JSX leaves in an arbitrary array-builder preamble.
1476
- const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToPlaceholderTemplate(ir, restSpreadNames, loopDepth + 1, loopParams) })
1482
+ const preamble = renderPreamble(node.preamble, { textVariant: 'client', renderLeaf: (ir) => irToPlaceholderTemplate(ir, restSpreadNames, loopDepth + 1, rowLoopParams) })
1477
1483
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`))
1478
1484
  } else {
1479
1485
  mapExpr = interp(mappedRowsMarkup(wrappedArray, iterMethod, callbackParam, `\`${childTemplate}\``))
@@ -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, componentDefScopeFlags } from './utils.ts'
19
+ import { PROPS_PARAM, initFunctionName, componentDefScopeFlags, isTransparentFragmentRoot } 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'
@@ -367,7 +367,12 @@ function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): strin
367
367
  // uses — a fragment-rooted stateless child must declare `comment` /
368
368
  // `fragmentRoot` too, or `renderChild()` stamps `bf-s` onto its first
369
369
  // element while SSR scopes it with a comment pair.
370
- const scopeFlags = componentDefScopeFlags(ir.root).map((f) => `, ${f}`).join('')
370
+ // A stateless transparent root (`<>{children}</>`) owns no scope at all —
371
+ // SSR renders the caller's content unmarked — so `renderChild()` must not
372
+ // stamp one either (#3355). Only the template-only path declares it: a
373
+ // stateful child still needs a scope for its init to bind against.
374
+ const transparentFlag = isTransparentFragmentRoot(ir.root) ? ['transparent: true'] : []
375
+ const scopeFlags = [...componentDefScopeFlags(ir.root), ...transparentFlag].map((f) => `, ${f}`).join('')
371
376
  lines.push(`hydrate('${registryKey}', { init: ${initName}, template: (${PROPS_PARAM}) => \`${templateHtml}\`${scopeFlags}${nameField} })`)
372
377
  // See `emitRegistrationAndHydration` (./emit-registration.ts) for the
373
378
  // rationale on why the component is also emitted as a callable
@@ -7,6 +7,7 @@ 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
9
  import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
10
+ import { BindingScope, type LoopBindingSource } from '../scope/binding-scope.ts'
10
11
  import { buildLoopChainExpr } from '../loop-chain.ts'
11
12
  import { templatePartsToJsExpr } from '../template-parts.ts'
12
13
  import {
@@ -96,6 +97,16 @@ export function isScopeCommentFragmentRoot(root: ComponentIR['root']): boolean {
96
97
  return root.type === 'fragment' && !!(root as IRFragment).needsScopeComment
97
98
  }
98
99
 
100
+ /**
101
+ * True for a transparent fragment root (`<>{children}</>`). SSR renders it
102
+ * with no scope marker of any kind, so a stateless component of this shape
103
+ * declares `transparent: true` and `renderChild()` emits its markup as-is
104
+ * (#3355).
105
+ */
106
+ export function isTransparentFragmentRoot(root: ComponentIR['root']): boolean {
107
+ return root.type === 'fragment' && !!(root as IRFragment).transparent
108
+ }
109
+
99
110
  /**
100
111
  * The scope-shape flags (`comment: true` / `fragmentRoot: true`) a
101
112
  * component's `hydrate()` def declares — the ONE answer both registration
@@ -655,7 +666,7 @@ function scanForIdentifiers(expr: string, predicate: (token: string) => boolean)
655
666
  * native array method (no runtime helper required).
656
667
  */
657
668
  function renderLoopBindingAccess(b: LoopParamBinding, base: string): string {
658
- const parent = `${base}${b.path}`
669
+ const parent = `${b.accessor ?? base}${b.path}`
659
670
  if (b.rest?.kind === 'object') {
660
671
  if (b.rest.exclude.length === 0) {
661
672
  // No sibling keys to omit. A fresh shallow clone — not a direct alias
@@ -714,19 +725,48 @@ export function wrapLoopParamAsAccessor(
714
725
  paramName: string,
715
726
  bindings?: readonly LoopParamBinding[],
716
727
  indexParam?: string | null,
728
+ shadowed?: ReadonlySet<string>,
717
729
  ): string {
730
+ // `shadowed`: names a nearer row rebinds (`rowBoundNames`), so inside that
731
+ // row they mean the nearer binding and keep their plain spelling (#3394).
732
+ const destructured = !!bindings && bindings.length > 0
733
+ const liveBindings = destructured && shadowed ? bindings.filter(b => !shadowed.has(b.name)) : bindings
734
+ const liveIndex = indexParam && shadowed?.has(indexParam) ? null : indexParam
718
735
  let result: string
719
- if (bindings && bindings.length > 0) {
720
- result = rewriteLoopBindingRefs(expr, bindings, '__bfItem()')
736
+ if (destructured) {
737
+ result = liveBindings && liveBindings.length > 0 ? rewriteLoopBindingRefs(expr, liveBindings, '__bfItem()') : expr
721
738
  } else {
722
- result = rewriteIdentifierAsAccessor(expr, paramName)
739
+ result = shadowed?.has(paramName) ? expr : rewriteIdentifierAsAccessor(expr, paramName)
723
740
  }
724
- if (indexParam && indexParam !== paramName) {
725
- result = wrapIndexParamAsAccessor(result, indexParam)
741
+ if (liveIndex && liveIndex !== paramName) {
742
+ result = wrapIndexParamAsAccessor(result, liveIndex)
726
743
  }
727
744
  return result
728
745
  }
729
746
 
747
+ /**
748
+ * A loop-param accessor rewrite that can be told which names a nearer row
749
+ * rebinds (#3394). Each wrap passes `shadowed` on to the enclosing loops'
750
+ * wraps it composes, so every ancestor rewrite skips them too.
751
+ */
752
+ export type ShadowableWrap = (expr: string, shadowed?: ReadonlySet<string>) => string
753
+
754
+ /** `a` and `b` together; `a` alone when `b` is empty or absent. */
755
+ export function unionNames(a: ReadonlySet<string>, b?: ReadonlySet<string>): ReadonlySet<string> {
756
+ return b && b.size > 0 ? new Set([...a, ...b]) : a
757
+ }
758
+
759
+ /**
760
+ * Every name the row of `loop` binds — its item (or destructure bindings),
761
+ * index and preamble locals — via `BindingScope.enterLoopRow`. Inside that
762
+ * row an enclosing loop's accessor rewrite must skip these names, or an
763
+ * inner `const name = …` that shadows an outer destructure binding becomes
764
+ * `const __bfItem().name = …` (#3394).
765
+ */
766
+ export function rowBoundNames(loop: LoopBindingSource): ReadonlySet<string> {
767
+ return BindingScope.EMPTY.enterLoopRow(loop).boundNames()
768
+ }
769
+
730
770
  /**
731
771
  * The index-only half of `wrapLoopParamAsAccessor` — same AST-aware
732
772
  * identifier rewrite (`rewriteIdentifierAsAccessor`), own identifier.
@@ -962,6 +1002,8 @@ export interface LoopParamSpec {
962
1002
  bindings?: readonly LoopParamBinding[]
963
1003
  /** This loop's index parameter name, when it declares one (#2859). */
964
1004
  index?: string | null
1005
+ /** Names a nearer row rebinds, left as written (#3394). */
1006
+ shadowed?: ReadonlySet<string>
965
1007
  }
966
1008
 
967
1009
  /**
@@ -991,8 +1033,40 @@ export function wrapExprWithLoopParams(expr: string, loopParams?: ReadonlyArray<
991
1033
  let result = expr
992
1034
  for (const p of loopParams) {
993
1035
  const spec = typeof p === 'string' ? { param: p } : p
994
- result = wrapLoopParamAsAccessor(result, spec.param, spec.bindings, spec.index)
1036
+ result = wrapLoopParamAsAccessor(result, spec.param, spec.bindings, spec.index, spec.shadowed)
995
1037
  }
996
1038
  return result
997
1039
  }
998
1040
 
1041
+ /**
1042
+ * Enclosing loop specs as seen inside the row of `loop`: each spec also
1043
+ * skips the names that row rebinds (`rowBoundNames`, #3394).
1044
+ */
1045
+ export function specsInsideRow(
1046
+ specs: ReadonlyArray<string | LoopParamSpec> | undefined,
1047
+ loop: LoopBindingSource,
1048
+ ): ReadonlyArray<string | LoopParamSpec> | undefined {
1049
+ if (!specs) return specs
1050
+ const names = rowBoundNames(loop)
1051
+ if (names.size === 0) return specs
1052
+ return specs.map(p => {
1053
+ const spec = typeof p === 'string' ? { param: p } : p
1054
+ const shadowed = spec.shadowed ? new Set([...spec.shadowed, ...names]) : names
1055
+ return { ...spec, shadowed }
1056
+ })
1057
+ }
1058
+
1059
+ /**
1060
+ * The bindings of a nested destructured `.map()` row, each reading through
1061
+ * the row's own accessor `__bfItem_<markerId>()` (#3397). Every nested row
1062
+ * then names its render callback's item accessor differently, so a row
1063
+ * inside another destructured row can still read the outer row's bindings.
1064
+ */
1065
+ export function withRowAccessor(
1066
+ bindings: readonly LoopParamBinding[] | undefined,
1067
+ markerId: string,
1068
+ ): readonly LoopParamBinding[] | undefined {
1069
+ if (!bindings || bindings.length === 0) return bindings
1070
+ const accessor = `__bfItem_${markerId}()`
1071
+ return bindings.map(b => ({ ...b, accessor }))
1072
+ }