@barefootjs/jsx 0.39.8 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/adapters/attr-plan.d.ts +1 -20
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +19 -7
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +79 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-plan.d.ts +173 -9
  8. package/dist/adapters/loop-plan.d.ts.map +1 -1
  9. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  10. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  11. package/dist/analyzer.d.ts.map +1 -1
  12. package/dist/assignment-target.d.ts +26 -0
  13. package/dist/assignment-target.d.ts.map +1 -0
  14. package/dist/augment-inherited-props.d.ts.map +1 -1
  15. package/dist/css-layer-prefixer.d.ts.map +1 -1
  16. package/dist/debug.d.ts.map +1 -1
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2566 -2007
  22. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  31. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  37. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  40. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +1 -1
  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/module-exports.d.ts.map +1 -1
  45. package/dist/prop-rewrite.d.ts +17 -8
  46. package/dist/prop-rewrite.d.ts.map +1 -1
  47. package/dist/props-binding.d.ts +57 -0
  48. package/dist/props-binding.d.ts.map +1 -1
  49. package/dist/scope/binding-scope.d.ts +32 -2
  50. package/dist/scope/binding-scope.d.ts.map +1 -1
  51. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  52. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  53. package/dist/template-parts.d.ts +1 -1
  54. package/dist/template-parts.d.ts.map +1 -1
  55. package/dist/types.d.ts +30 -2
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  59. package/src/__tests__/attr-plan.test.ts +1 -14
  60. package/src/__tests__/binding-scope.test.ts +29 -0
  61. package/src/__tests__/client-template-escape-soundness.test.ts +17 -4
  62. package/src/__tests__/client-template-static-delimiters.test.ts +57 -0
  63. package/src/__tests__/create-query.test.ts +1 -1
  64. package/src/__tests__/dsl-template-adapter.test.ts +70 -0
  65. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  66. package/src/__tests__/extract-function-params.test.ts +37 -0
  67. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +18 -0
  68. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +11 -0
  69. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  70. package/src/__tests__/loop-plan.test.ts +196 -1
  71. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  72. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  73. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  74. package/src/__tests__/props-alias-const.test.ts +60 -1
  75. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  76. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  77. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  78. package/src/__tests__/template-parts-literal-boundary.test.ts +22 -0
  79. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  80. package/src/adapters/attr-plan.ts +2 -54
  81. package/src/adapters/callback-method.ts +25 -10
  82. package/src/adapters/dsl-template-adapter.ts +155 -2
  83. package/src/adapters/loop-plan.ts +267 -14
  84. package/src/adapters/parsed-expr-emitter.ts +37 -4
  85. package/src/analyzer.ts +283 -2
  86. package/src/assignment-target.ts +79 -0
  87. package/src/augment-inherited-props.ts +5 -9
  88. package/src/css-layer-prefixer.ts +4 -5
  89. package/src/debug.ts +1 -0
  90. package/src/errors.ts +11 -0
  91. package/src/index.ts +23 -4
  92. package/src/ir-to-client-js/compute-inlinability.ts +7 -4
  93. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  94. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  95. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  96. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  97. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  98. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  99. package/src/ir-to-client-js/emit-registration.ts +6 -1
  100. package/src/ir-to-client-js/html-template.ts +70 -52
  101. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  102. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  103. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  104. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  105. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  106. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  107. package/src/ir-to-client-js/utils.ts +41 -97
  108. package/src/jsx-to-ir.ts +65 -32
  109. package/src/loop-destructure.ts +4 -1
  110. package/src/module-exports.ts +13 -21
  111. package/src/prop-rewrite.ts +31 -72
  112. package/src/props-binding.ts +73 -1
  113. package/src/rich-type-refusal.ts +3 -1
  114. package/src/scope/binding-scope.ts +39 -3
  115. package/src/scope/lexical-scope-walk.ts +167 -0
  116. package/src/template-parts.ts +4 -2
  117. package/src/template-position-walk.ts +3 -1
  118. package/src/types.ts +27 -2
@@ -18,6 +18,15 @@ 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'
22
+
23
+ /** Static HTML is embedded in a JS template literal; dynamic expressions use interp(). */
24
+ function escapeStaticTemplateHtml(text: string): string {
25
+ return escapeHtml(text)
26
+ .replace(/\\/g, '\\\\')
27
+ .replace(/`/g, '\\`')
28
+ .replace(/\$\{/g, '\\${')
29
+ }
21
30
 
22
31
  /**
23
32
  * Split a template literal body into static segments and `${...}` interpolations,
@@ -358,7 +367,7 @@ function renderTemplateAttrPart(
358
367
  case 'boolean-attr':
359
368
  return attrName
360
369
  case 'literal':
361
- return `${attrName}="${escapeHtml(v.value)}"`
370
+ return `${attrName}="${escapeStaticTemplateHtml(v.value)}"`
362
371
  case 'expression': {
363
372
  const valExpr = wrap(v.expr)
364
373
  return templateAttrExpr(attrName, valExpr, v.presenceOrUndefined)
@@ -792,7 +801,7 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
792
801
  case 'text':
793
802
  // IRText carries the entity-DECODED value; this string is parsed
794
803
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
795
- return escapeHtml(node.value)
804
+ return escapeStaticTemplateHtml(node.value)
796
805
 
797
806
  case 'expression': {
798
807
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -927,7 +936,9 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
927
936
  if (childrenEntry) propsEntries.push(childrenEntry)
928
937
  const propsExpr = propsEntries.length > 0 ? `{${propsEntries.join(', ')}}` : '{}'
929
938
  const keyProp = node.props.find(p => p.name === 'key')
930
- const keyArg = keyProp ? `, ${attrValueToString(keyProp.value) ?? 'undefined'}` : ''
939
+ const keyArg = keyProp
940
+ ? `, ${transformKeyValue(keyProp.value, (expr, templateExpr) => wrapExpr(templateExpr ?? expr))}`
941
+ : ''
931
942
  // Pass slotId as suffix so $c() can find the child component by slot
932
943
  // after branch swap. A loop-item-root component owns a separate scope
933
944
  // per iteration (identified by `data-key`) rather than deriving from
@@ -1071,7 +1082,7 @@ export function buildLoopSkeletonTemplate(node: IRNode, safe: LoopSkeletonSafeSl
1071
1082
  const v = a.value
1072
1083
  switch (v.kind) {
1073
1084
  case 'literal':
1074
- attrParts.push(`${toHtmlAttrName(a.name)}="${escapeHtml(v.value)}"`)
1085
+ attrParts.push(`${toHtmlAttrName(a.name)}="${escapeStaticTemplateHtml(v.value)}"`)
1075
1086
  break
1076
1087
  case 'boolean-attr':
1077
1088
  attrParts.push(toHtmlAttrName(a.name))
@@ -1127,7 +1138,7 @@ export function buildLoopSkeletonTemplate(node: IRNode, safe: LoopSkeletonSafeSl
1127
1138
  case 'text':
1128
1139
  // IRText carries the entity-DECODED value; this string is parsed
1129
1140
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
1130
- return escapeHtml(node.value)
1141
+ return escapeStaticTemplateHtml(node.value)
1131
1142
 
1132
1143
  case 'expression':
1133
1144
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -1401,7 +1412,7 @@ export function irToPlaceholderTemplate(node: IRNode, restSpreadNames?: Readonly
1401
1412
  case 'text':
1402
1413
  // IRText carries the entity-DECODED value; this string is parsed
1403
1414
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
1404
- return escapeHtml(node.value)
1415
+ return escapeStaticTemplateHtml(node.value)
1405
1416
 
1406
1417
  case 'expression': {
1407
1418
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -1626,6 +1637,33 @@ export function addCondAttrToTemplate(html: string, condId: string): string {
1626
1637
  return `<!--bf-cond-start:${condId}-->${html}<!--bf-cond-end:${condId}-->`
1627
1638
  }
1628
1639
 
1640
+ function* templateHtmlTags(html: string): Generator<{ raw: string; end: number }> {
1641
+ let cursor = 0
1642
+ let noCommentEnd = false
1643
+ while (cursor < html.length) {
1644
+ const start = html.indexOf('<', cursor)
1645
+ if (start < 0) break
1646
+ cursor = start + 1
1647
+ if (html.startsWith('<!--', start) && !noCommentEnd) {
1648
+ const commentEnd = html.indexOf('-->', start + 4)
1649
+ if (commentEnd >= 0) {
1650
+ cursor = commentEnd + 3
1651
+ continue
1652
+ }
1653
+ // A failed search covers the entire remaining suffix, not just this opener.
1654
+ noCommentEnd = true
1655
+ }
1656
+ const nameStart = html[start + 1] === '/' ? start + 2 : start + 1
1657
+ if (nameStart >= html.length || /[\s/>]/.test(html[nameStart])) continue
1658
+ const end = html.indexOf('>', nameStart + 1)
1659
+ if (end < 0) break
1660
+ cursor = end + 1
1661
+ const raw = html.slice(start, cursor)
1662
+ if (raw.startsWith('<!--')) continue
1663
+ yield { raw, end: cursor }
1664
+ }
1665
+ }
1666
+
1629
1667
  /**
1630
1668
  * Check if HTML string has a single root element (not multiple siblings).
1631
1669
  *
@@ -1653,44 +1691,14 @@ function isSingleRootElement(html: string): boolean {
1653
1691
  // BOTH the `bf-c` stamp and the comment-wrap fallback for those roots.
1654
1692
  const match = trimmed.match(/^<(\w+)[\s>]/)
1655
1693
  if (!match) return false
1656
- // Self-closing tags like <br/>, <input/> with nothing else.
1657
- if (/^<\w+[^>]*\/>$/.test(trimmed)) return true
1658
-
1659
- // Walk top-level tags tracking nesting depth — see the docstring above
1660
- // for why (#2960). The comment alternative must come first so it wins at a `<!--`
1661
- // position — without it, a BarefootJS marker comment like
1662
- // `<!--bf:s1-->`/`<!--/-->` (a reactive text slot nested inside a
1663
- // genuine single root) matches the generic tag alternative too (its
1664
- // body has no `\s`, `/` or `>` before the closing `-->`) and gets
1665
- // miscounted as an opening tag, throwing off the depth count for
1666
- // perfectly ordinary single-root branches.
1667
- const tagPattern = /<!--[\s\S]*?-->|<\/?[^\s/>]+[^>]*>/g
1668
1694
  let depth = 0
1669
- let tagMatch: RegExpExecArray | null
1670
- while ((tagMatch = tagPattern.exec(trimmed))) {
1671
- const raw = tagMatch[0]
1672
- if (raw.startsWith('<!--')) continue // HTML comment, not a tag: depth unchanged
1695
+ for (const { raw, end } of templateHtmlTags(trimmed)) {
1673
1696
  if (raw.endsWith('/>')) {
1674
- // Self-closing/void tag (e.g. `<input .../>`). The whole-string
1675
- // check above only catches a self-closing tag with NOTHING else in
1676
- // the string — a self-closing root FOLLOWED by more content (e.g.
1677
- // `<input .../><label>...</label>`, a genuine two-root branch) still
1678
- // reaches here with the guard above already satisfied (it only
1679
- // looks at the tag name and the very next character, not whether
1680
- // the tag turns out to self-close). At depth 0 this tag completes a
1681
- // whole top-level unit by itself, so treat it exactly like any
1682
- // other tag's closing point: single root only if nothing follows.
1683
- // Nested inside another element (depth > 0) it's just an ordinary
1684
- // child and doesn't affect depth.
1685
- if (depth === 0) return tagPattern.lastIndex === trimmed.length
1697
+ if (depth === 0) return end === trimmed.length
1686
1698
  continue
1687
1699
  }
1688
1700
  depth += raw.startsWith('</') ? -1 : 1
1689
- if (depth === 0) {
1690
- // Back to depth 0: the root element's own closing tag. Single root
1691
- // only if nothing else follows it.
1692
- return tagPattern.lastIndex === trimmed.length
1693
- }
1701
+ if (depth === 0) return end === trimmed.length
1694
1702
  }
1695
1703
  return false
1696
1704
  }
@@ -1933,7 +1941,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1933
1941
  return templateAttrExpr(keyName, transformExpr(tmplStr))
1934
1942
  }
1935
1943
  case 'literal':
1936
- return `${keyName}="${escapeHtml(v.value)}"`
1944
+ return `${keyName}="${escapeStaticTemplateHtml(v.value)}"`
1937
1945
  default:
1938
1946
  return ''
1939
1947
  }
@@ -1943,7 +1951,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1943
1951
  case 'boolean-attr':
1944
1952
  return attrName
1945
1953
  case 'literal':
1946
- return `${attrName}="${escapeHtml(v.value)}"`
1954
+ return `${attrName}="${escapeStaticTemplateHtml(v.value)}"`
1947
1955
  case 'expression':
1948
1956
  return templateAttrExpr(attrName, transformExpr(v.expr, v.templateExpr), v.presenceOrUndefined)
1949
1957
  case 'template': {
@@ -1976,7 +1984,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1976
1984
  case 'text':
1977
1985
  // IRText carries the entity-DECODED value; this string is parsed
1978
1986
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
1979
- return escapeHtml(node.value)
1987
+ return escapeStaticTemplateHtml(node.value)
1980
1988
 
1981
1989
  case 'expression': {
1982
1990
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -2362,12 +2370,14 @@ function propResolvesUnsafe(
2362
2370
  env: CsrEnv,
2363
2371
  unsafeLocalNames: ReadonlySet<string>,
2364
2372
  ): boolean {
2365
- if (unsafeLocalNames.size === 0) return false
2366
2373
  let source: string | undefined
2367
2374
  switch (prop.value.kind) {
2368
2375
  case 'expression':
2369
2376
  case 'spread':
2370
- source = prop.value.expr
2377
+ // The same text the CSR `component` emit reads (`transformExpr(expr,
2378
+ // templateExpr)`): a prop read Phase 1 already lowered to
2379
+ // `_p.<key> ?? <default>` in `templateExpr` names no init local (#3579).
2380
+ source = prop.value.templateExpr ?? prop.value.expr
2371
2381
  break
2372
2382
  case 'template':
2373
2383
  source = attrValueToString(prop.value, { useTemplate: true }) ?? undefined
@@ -2377,8 +2387,8 @@ function propResolvesUnsafe(
2377
2387
  return false
2378
2388
  }
2379
2389
  if (!source) return false
2380
- const { freeIdentifiers } = csrSubstitute(source, env)
2381
- return setIntersects(freeIdentifiers, unsafeLocalNames)
2390
+ const { freeIdentifiers, writes } = csrSubstitute(source, env)
2391
+ return writes.size > 0 || setIntersects(freeIdentifiers, unsafeLocalNames)
2382
2392
  }
2383
2393
 
2384
2394
  /**
@@ -2403,7 +2413,10 @@ export function computeDeferredChildSlots(
2403
2413
  propsObjectName?: string | null,
2404
2414
  ): Set<string> {
2405
2415
  const deferred = new Set<string>()
2406
- if (!unsafeLocalNames || unsafeLocalNames.size === 0) return deferred
2416
+ // A prop can also be dropped for writing a binding (`get={() => ++id}`,
2417
+ // see `transformExpr`), which only a component that writes one can have.
2418
+ if (!writesAnyBinding(ctx) && (!unsafeLocalNames || unsafeLocalNames.size === 0)) return deferred
2419
+ const unsafe = unsafeLocalNames ?? new Set<string>()
2407
2420
  const env = buildCsrEnvForCtx(ctx, inlinableConstants, propsObjectName)
2408
2421
 
2409
2422
  const visit = (n: IRNode): void => {
@@ -2425,7 +2438,7 @@ export function computeDeferredChildSlots(
2425
2438
  if (p.name === 'ref') return false
2426
2439
  if (isEventHandlerName(p.name)) return false
2427
2440
  if (p.clientOnly) return false
2428
- return propResolvesUnsafe(p, env, unsafeLocalNames)
2441
+ return propResolvesUnsafe(p, env, unsafe)
2429
2442
  })
2430
2443
  if (dropped) deferred.add(n.slotId)
2431
2444
  }
@@ -2468,7 +2481,12 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2468
2481
  // the IR — emit does no string transformation of its own (#1277).
2469
2482
  const source = templateExpr ?? expr
2470
2483
  if (!source) return source
2471
- const { rewritten, freeIdentifiers } = csrSubstitute(source, env, opts.scope)
2484
+ const { rewritten, freeIdentifiers, writes } = csrSubstitute(source, env, opts.scope)
2485
+
2486
+ // An expression that writes a binding (`{++nextId}`, a child prop
2487
+ // `() => ++start`) cannot run here: the template has no binding to
2488
+ // write, and the write belongs to init's run of the component.
2489
+ if (writes.size > 0) return UNSAFE_TEMPLATE_EXPR
2472
2490
 
2473
2491
  // The CSR template runs at module scope, so any post-substitution
2474
2492
  // free identifier that lands in `unsafeLocalNames` (init-body-only
@@ -2555,7 +2573,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2555
2573
  case 'boolean-attr':
2556
2574
  return keyName
2557
2575
  case 'literal':
2558
- return `${keyName}="${escapeHtml(v.value)}"`
2576
+ return `${keyName}="${escapeStaticTemplateHtml(v.value)}"`
2559
2577
  case 'expression':
2560
2578
  return templateAttrExpr(keyName, transformExpr(v.expr, v.templateExpr), v.presenceOrUndefined)
2561
2579
  case 'template': {
@@ -2572,7 +2590,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2572
2590
  case 'boolean-attr':
2573
2591
  return attrName
2574
2592
  case 'literal':
2575
- return `${attrName}="${escapeHtml(v.value)}"`
2593
+ return `${attrName}="${escapeStaticTemplateHtml(v.value)}"`
2576
2594
  case 'expression':
2577
2595
  return templateAttrExpr(attrName, transformExpr(v.expr, v.templateExpr), v.presenceOrUndefined)
2578
2596
  case 'template': {
@@ -2605,7 +2623,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2605
2623
  case 'text':
2606
2624
  // IRText carries the entity-DECODED value; this string is parsed
2607
2625
  // as HTML (template.innerHTML), so re-escape for the HTML parser.
2608
- return escapeHtml(node.value)
2626
+ return escapeStaticTemplateHtml(node.value)
2609
2627
 
2610
2628
  case 'expression':
2611
2629
  if (node.expr === 'null' || node.expr === 'undefined') return ''
@@ -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'
@@ -212,7 +213,7 @@ export { templatePartsToJsExpr }
212
213
  * `boolean-shorthand`, `jsx-children`) — callers must branch on `value.kind`
213
214
  * before reaching them.
214
215
  *
215
- * When `opts.useTemplate` is set, prefers `templateExpr` / `templateValue` /
216
+ * When `opts.useTemplate` is set, prefers `templateExpr` /
216
217
  * `templateCondition` / `templateKey` (the prop-rewritten variant) over the
217
218
  * raw source form, for use in SSR template-literal interpolation.
218
219
  */
@@ -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.