@barefootjs/jsx 0.40.2 → 0.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/adapters/callback-method.d.ts +8 -1
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +14 -5
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +3 -12
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-row-type.d.ts +7 -0
  8. package/dist/adapters/loop-row-type.d.ts.map +1 -1
  9. package/dist/adapters/nil-reading.d.ts +15 -20
  10. package/dist/adapters/nil-reading.d.ts.map +1 -1
  11. package/dist/adapters/non-primitive-equality.d.ts +1 -1
  12. package/dist/adapters/number-value.d.ts +2 -1
  13. package/dist/adapters/number-value.d.ts.map +1 -1
  14. package/dist/adapters/parsed-expr-emitter.d.ts +11 -1
  15. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  16. package/dist/adapters/primitive-plan.d.ts +40 -11
  17. package/dist/adapters/primitive-plan.d.ts.map +1 -1
  18. package/dist/adapters/prop-classes.d.ts +5 -0
  19. package/dist/adapters/prop-classes.d.ts.map +1 -1
  20. package/dist/analyzer.d.ts.map +1 -1
  21. package/dist/index.d.ts +6 -7
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +566 -367
  24. package/dist/ir-to-client-js/child-props-object.d.ts +43 -1
  25. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/imports.d.ts +2 -2
  31. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -3
  33. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +3 -1
  35. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  36. package/dist/jsx-to-ir.d.ts.map +1 -1
  37. package/dist/nullable-signal-attr.d.ts +4 -46
  38. package/dist/nullable-signal-attr.d.ts.map +1 -1
  39. package/dist/props-binding.d.ts +58 -13
  40. package/dist/props-binding.d.ts.map +1 -1
  41. package/dist/ssr-defaults.d.ts +39 -3
  42. package/dist/ssr-defaults.d.ts.map +1 -1
  43. package/dist/types.d.ts +14 -0
  44. package/dist/types.d.ts.map +1 -1
  45. package/package.json +2 -2
  46. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +6 -6
  47. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +2 -2
  48. package/src/__tests__/body-destructured-props-live.test.ts +5 -5
  49. package/src/__tests__/client-js-generation.test.ts +3 -3
  50. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +7 -7
  51. package/src/__tests__/destructured-props-live.test.ts +1 -1
  52. package/src/__tests__/issue-3861-object-spread-child.test.ts +102 -0
  53. package/src/__tests__/memo-body-expr.test.ts +2 -2
  54. package/src/__tests__/nil-reading.test.ts +3 -2
  55. package/src/__tests__/nullable-signal-attr.test.ts +30 -103
  56. package/src/__tests__/primitive-plan.test.ts +90 -12
  57. package/src/__tests__/prop-default-undefined-only.test.ts +115 -0
  58. package/src/__tests__/prop-references.test.ts +2 -2
  59. package/src/__tests__/props-destructuring.test.ts +17 -0
  60. package/src/__tests__/prune-unused-prop-extractions.test.ts +3 -3
  61. package/src/__tests__/renamed-body-destructure-template.test.ts +7 -7
  62. package/src/__tests__/rewrite-destructured-props.test.ts +1 -1
  63. package/src/__tests__/ssr-defaults.test.ts +113 -25
  64. package/src/__tests__/static-const-child-prop.test.ts +85 -0
  65. package/src/__tests__/written-binding-substitution.test.ts +8 -8
  66. package/src/adapters/callback-method.ts +13 -5
  67. package/src/adapters/component-props.ts +20 -6
  68. package/src/adapters/dsl-template-adapter.ts +26 -28
  69. package/src/adapters/loop-row-type.ts +10 -0
  70. package/src/adapters/nil-reading.ts +23 -25
  71. package/src/adapters/non-primitive-equality.ts +1 -1
  72. package/src/adapters/number-value.ts +26 -2
  73. package/src/adapters/parsed-expr-emitter.ts +31 -2
  74. package/src/adapters/primitive-plan.ts +84 -15
  75. package/src/adapters/prop-classes.ts +16 -3
  76. package/src/analyzer.ts +27 -7
  77. package/src/index.ts +5 -12
  78. package/src/ir-to-client-js/child-props-object.ts +140 -6
  79. package/src/ir-to-client-js/collect-elements.ts +7 -14
  80. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +4 -2
  81. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +4 -2
  82. package/src/ir-to-client-js/html-template.ts +18 -9
  83. package/src/ir-to-client-js/imports.ts +1 -1
  84. package/src/ir-to-client-js/phases/props-extraction.ts +11 -7
  85. package/src/ir-to-client-js/plan/build-declaration-emit.ts +40 -7
  86. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +58 -5
  87. package/src/ir-to-client-js/rewrite-destructured-props.ts +31 -1
  88. package/src/jsx-to-ir.ts +113 -60
  89. package/src/nullable-signal-attr.ts +11 -138
  90. package/src/props-binding.ts +84 -19
  91. package/src/ssr-defaults.ts +100 -11
  92. package/src/types.ts +11 -0
  93. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +0 -42
  94. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +0 -1
  95. package/src/adapters/ambiguous-nil-arithmetic.ts +0 -103
@@ -18,7 +18,7 @@
18
18
  */
19
19
 
20
20
  import type { AttrValue } from '../types.ts'
21
- import { PROPS_PARAM, quotePropName } from './utils.ts'
21
+ import { codeSafeStringLiteral, PROPS_PARAM, quotePropName } from './utils.ts'
22
22
 
23
23
  /** One explicit prop's value as a call-site builder spells it. */
24
24
  export interface ChildPropValue {
@@ -61,10 +61,22 @@ export function lastPropsObjectSpreadIndex(props: readonly ChildPropLike[]): num
61
61
  * merge is spelled into the value itself.
62
62
  */
63
63
  export function callerFirstPropExpr(name: string, expr: string): string {
64
- const key = JSON.stringify(name)
64
+ const key = codeSafeStringLiteral(name)
65
65
  return `(${key} in ${PROPS_PARAM} ? ${PROPS_PARAM}[${key}] : ${expr})`
66
66
  }
67
67
 
68
+ /**
69
+ * True for a spread of an arbitrary object onto a child component
70
+ * (`<Chip {...row} />`, a loop row `{...r}`): not one of the caller's own
71
+ * prop bags (`SpreadAttr.callerBag`, decided in Phase 1). Its keys are
72
+ * merged in source order through `spreadChildProps` (#3861). A caller-bag
73
+ * spread is the props object (`propsObject`, merged by `forwardProps`) or a
74
+ * `{...rest}` bag, which the top-level path forwards whole.
75
+ */
76
+ export function isObjectSpreadProp(prop: ChildPropLike): boolean {
77
+ return isSpreadPropName(prop.name) && prop.value.kind === 'spread' && prop.value.callerBag === undefined
78
+ }
79
+
68
80
  export interface ChildPropsObjectOptions {
69
81
  /** Entries appended after the explicit props (e.g. a row's `children` getter). */
70
82
  trailing?: readonly string[]
@@ -73,17 +85,89 @@ export interface ChildPropsObjectOptions {
73
85
  * top-level path's `{...rest}` forwarding, which predates the marker.
74
86
  */
75
87
  forwardCaller?: boolean
88
+ /**
89
+ * The caller's `{...rest}` bag as a props object (the caller's props
90
+ * without the keys the component destructured), so a call that also
91
+ * spreads an object merges the bag in source order as one more part.
92
+ * Without it a rest bag spread is left to `forwardCaller`.
93
+ */
94
+ restBag?: string
95
+ }
96
+
97
+ /**
98
+ * A JS array literal of code-safe string literals (`codeSafeStringLiteral`),
99
+ * printed exactly as `JSON.stringify` prints an array of ordinary names.
100
+ */
101
+ export function codeSafeStringArray(values: readonly string[]): string {
102
+ return `[${values.map(codeSafeStringLiteral).join(',')}]`
103
+ }
104
+
105
+ /** An object literal of `entries`, `{}` when there are none. */
106
+ function objectLiteral(entries: readonly string[]): string {
107
+ return entries.length > 0 ? `{ ${entries.join(', ')} }` : '{}'
108
+ }
109
+
110
+ /** Index of the last object spread (`isObjectSpreadProp`) in a child component call, or -1. */
111
+ export function lastObjectSpreadIndex(props: readonly ChildPropLike[]): number {
112
+ let at = -1
113
+ props.forEach((p, index) => {
114
+ if (isObjectSpreadProp(p)) at = index
115
+ })
116
+ return at
117
+ }
118
+
119
+ /**
120
+ * The value of the explicit prop at `index` for a reactive DOM mirror,
121
+ * merged with every spread written after it, as the props object merges
122
+ * them: a later object spread (`spreadOf` spells its value) wins when its
123
+ * object has the key, and a later props-object spread wins when the caller
124
+ * passed it (`callerFirstPropExpr`). `expr` as written when no spread
125
+ * follows.
126
+ */
127
+ export function mergedExplicitPropExpr<P extends ChildPropLike>(
128
+ props: readonly P[],
129
+ index: number,
130
+ expr: string,
131
+ spreadOf: (prop: P) => string,
132
+ ): string {
133
+ const name = props[index]!.name
134
+ const key = codeSafeStringLiteral(name)
135
+ let merged = expr
136
+ // The last spread kind applied: two props-object spreads in a row merge once.
137
+ let last: 'props' | 'object' | null = null
138
+ for (let at = index + 1; at < props.length; at++) {
139
+ const prop = props[at]!
140
+ if (prop.value.kind === 'spread' && prop.value.propsObject === true) {
141
+ if (last !== 'props') merged = callerFirstPropExpr(name, merged)
142
+ last = 'props'
143
+ } else if (isObjectSpreadProp(prop)) {
144
+ merged = `((__s) => __s != null && ${key} in Object(__s) ? Object(__s)[${key}] : ${merged})(${spreadOf(prop)})`
145
+ last = 'object'
146
+ }
147
+ }
148
+ return merged
76
149
  }
77
150
 
78
151
  /**
79
152
  * Build a child component's props object expression. `valueOf` spells one
80
- * explicit prop's value, or returns null to leave it out (e.g. `key`).
153
+ * explicit prop's value, or returns null to leave it out (e.g. `key`). It
154
+ * also spells an object spread's value (`isObjectSpreadProp`).
155
+ *
156
+ * Without an object spread, the explicit props form one object literal,
157
+ * wrapped in `forwardProps` for a props-object spread (or the caller
158
+ * forwarding). With one, every part merges in source order through
159
+ * `spreadChildProps` (#3861): each run of explicit props is an object
160
+ * literal, an object spread a thunk of its value, and a props-object spread
161
+ * the thunk `() => _p`, so a later part wins as in JS. A `{...rest}` bag is
162
+ * a part too when the caller spells it (`restBag`); otherwise it is
163
+ * forwarded off `_p` after the merge.
81
164
  */
82
165
  export function childPropsObjectExpr<P extends ChildPropLike>(
83
166
  props: readonly P[],
84
167
  valueOf: (prop: P) => ChildPropValue | null,
85
168
  options: ChildPropsObjectOptions = {},
86
169
  ): string {
170
+ if (lastObjectSpreadIndex(props) >= 0) return spreadPartsExpr(props, valueOf, options)
87
171
  const spreadAt = lastPropsObjectSpreadIndex(props)
88
172
  const entries: string[] = []
89
173
  const explicitNames: string[] = []
@@ -96,11 +180,61 @@ export function childPropsObjectExpr<P extends ChildPropLike>(
96
180
  if (index < spreadAt) {
97
181
  entries.push(`get ${key}() { return ${callerFirstPropExpr(prop.name, value.expr)} }`)
98
182
  } else {
99
- entries.push(value.getter ? `get ${key}() { return ${value.expr} }` : `${key}: ${value.expr}`)
183
+ entries.push(explicitEntry(key, value))
100
184
  }
101
185
  })
102
186
  entries.push(...(options.trailing ?? []))
103
- const object = entries.length > 0 ? `{ ${entries.join(', ')} }` : '{}'
187
+ const object = objectLiteral(entries)
104
188
  if (spreadAt < 0 && !options.forwardCaller) return object
105
- return `forwardProps(${PROPS_PARAM}, ${object}, ${JSON.stringify(explicitNames)})`
189
+ return `forwardProps(${PROPS_PARAM}, ${object}, ${codeSafeStringArray(explicitNames)})`
190
+ }
191
+
192
+ /** One explicit prop's object-literal entry: a getter or a data property. */
193
+ function explicitEntry(key: string, value: ChildPropValue): string {
194
+ return value.getter ? `get ${key}() { return ${value.expr} }` : `${key}: ${value.expr}`
195
+ }
196
+
197
+ /** {@link childPropsObjectExpr} for a call with an object spread: `spreadChildProps(...parts)`. */
198
+ function spreadPartsExpr<P extends ChildPropLike>(
199
+ props: readonly P[],
200
+ valueOf: (prop: P) => ChildPropValue | null,
201
+ options: ChildPropsObjectOptions,
202
+ ): string {
203
+ const parts: string[] = []
204
+ let entries: string[] = []
205
+ const explicitNames: string[] = []
206
+ let mergesCaller = false
207
+ const flush = (): void => {
208
+ if (entries.length > 0) parts.push(objectLiteral(entries))
209
+ entries = []
210
+ }
211
+ for (const prop of props) {
212
+ if (prop.value.kind === 'spread' && prop.value.propsObject === true) {
213
+ flush()
214
+ parts.push(`() => ${PROPS_PARAM}`)
215
+ mergesCaller = true
216
+ continue
217
+ }
218
+ if (prop.value.kind === 'spread' && prop.value.callerBag === 'rest' && options.restBag !== undefined) {
219
+ flush()
220
+ parts.push(options.restBag)
221
+ mergesCaller = true
222
+ continue
223
+ }
224
+ if (isSpreadPropName(prop.name) && !isObjectSpreadProp(prop)) continue
225
+ const value = valueOf(prop)
226
+ if (!value) continue
227
+ if (isObjectSpreadProp(prop)) {
228
+ flush()
229
+ parts.push(`() => (${value.expr})`)
230
+ continue
231
+ }
232
+ explicitNames.push(prop.name)
233
+ entries.push(explicitEntry(quotePropName(prop.name), value))
234
+ }
235
+ entries.push(...(options.trailing ?? []))
236
+ flush()
237
+ const merged = `spreadChildProps(${parts.join(', ')})`
238
+ if (!options.forwardCaller || mergesCaller) return merged
239
+ return `forwardProps(${PROPS_PARAM}, ${merged}, ${codeSafeStringArray(explicitNames)})`
106
240
  }
@@ -11,7 +11,7 @@ import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-pa
11
11
  import { expandDynamicPropValue, expandConstantForReactivity, resolveRestSpreadOrigin, resolveRestSpreadNames } from './prop-handling.ts'
12
12
  import { extractFreeIdentifiersFromText } from './csr-substitute.ts'
13
13
  import { walkIR, stopAt } from './walker.ts'
14
- import { callerFirstPropExpr, childPropsObjectExpr, isSpreadPropName, lastPropsObjectSpreadIndex } from './child-props-object.ts'
14
+ import { childPropsObjectExpr, codeSafeStringArray, isSpreadPropName, mergedExplicitPropExpr } from './child-props-object.ts'
15
15
  import { buildLoopChainExpr } from '../loop-chain.ts'
16
16
  import { classifyDOMProp } from '@barefootjs/shared'
17
17
  import type { BindingScope } from '../scope/binding-scope.ts'
@@ -568,15 +568,6 @@ function componentInitPropValue(prop: IRProp, ctx: ClientJsContext): { expr: str
568
568
  }
569
569
  }
570
570
 
571
- /**
572
- * The merged value of the explicit prop at `index` for a reactive DOM
573
- * mirror: caller-first when a later props-object spread (at `spreadAt`, see
574
- * `lastPropsObjectSpreadIndex`) overrides it, `expr` as written otherwise.
575
- */
576
- function mergedMirrorExpr(name: string, expr: string, index: number, spreadAt: number): string {
577
- return index < spreadAt ? callerFirstPropExpr(name, expr) : expr
578
- }
579
-
580
571
  /**
581
572
  * Which caller bag an element's spread attribute forwards, for
582
573
  * `applyRestAttrs`: its text resolved through any `const x__alias = x` hop
@@ -612,8 +603,12 @@ function buildComponentPropsExpr(props: IRProp[], ctx: ClientJsContext): string
612
603
  // rest/props binding — see `resolveRestSpreadOrigin`'s docstring.
613
604
  return resolveRestSpreadOrigin(ctx, expr) !== null
614
605
  })
606
+ // The rest bag without the keys the component destructured, keyed the
607
+ // way they arrive on `_p` (the `applyRestAttrs` exclusion set).
608
+ const consumedKeys = ctx.propsParams.map(p => p.sourceName ?? p.name)
615
609
  return childPropsObjectExpr(props, prop => componentInitPropValue(prop, ctx), {
616
610
  forwardCaller: knownSpreadProp !== undefined,
611
+ restBag: `forwardProps(${PROPS_PARAM}, {}, ${codeSafeStringArray(consumedKeys)})`,
617
612
  })
618
613
  }
619
614
 
@@ -623,7 +618,6 @@ function buildComponentPropsExpr(props: IRProp[], ctx: ClientJsContext): string
623
618
  * side-effect helper so `buildComponentPropsExpr` stays a pure function.
624
619
  */
625
620
  function collectReactiveChildProps(node: IRComponent, ctx: ClientJsContext): void {
626
- const spreadAt = lastPropsObjectSpreadIndex(node.props)
627
621
  for (const [index, prop] of node.props.entries()) {
628
622
  if (prop.name === '...' || prop.name.startsWith('...')) continue
629
623
  if (prop.value.kind === 'jsx-children') continue
@@ -664,7 +658,7 @@ function collectReactiveChildProps(node: IRComponent, ctx: ClientJsContext): voi
664
658
  slotId: node.slotId,
665
659
  propName: prop.name,
666
660
  attrName,
667
- expression: mergedMirrorExpr(prop.name, expandedValue, index, spreadAt),
661
+ expression: mergedExplicitPropExpr(node.props, index, expandedValue, spread => expandDynamicPropValue(attrValueToString(spread.value)!, ctx)),
668
662
  ...pickAttrMetaFromIR(prop),
669
663
  })
670
664
  }
@@ -1039,7 +1033,6 @@ export function collectElements(
1039
1033
  component: ({ node: c, descend, descendJsxChildren }) => {
1040
1034
  if (c.slotId) {
1041
1035
  // Reactive props need effects to update the element when values change.
1042
- const spreadAt = lastPropsObjectSpreadIndex(c.props)
1043
1036
  for (const [index, prop] of c.props.entries()) {
1044
1037
  if (prop.value.kind === 'jsx-children') continue
1045
1038
  if (isEventHandlerName(prop.name)) continue
@@ -1056,7 +1049,7 @@ export function collectElements(
1056
1049
  ctx.reactiveProps.push({
1057
1050
  slotId: c.slotId,
1058
1051
  propName: prop.name,
1059
- expression: mergedMirrorExpr(prop.name, value, index, spreadAt),
1052
+ expression: mergedExplicitPropExpr(c.props, index, value, spread => expandDynamicPropValue(attrValueToString(spread.value)!, ctx)),
1060
1053
  componentName: c.name,
1061
1054
  })
1062
1055
  }
@@ -69,11 +69,13 @@ function wrapAttrValueExpression(value: AttrValue, wrap: (s: string) => string):
69
69
  return AttrValueOf.expression(wrap(flat ?? 'undefined'))
70
70
  }
71
71
  case 'spread':
72
- // Keep the Phase-1 props-object marker: the props object merges this
73
- // spread in source order (#3713).
72
+ // Keep the Phase-1 caller-bag markers: the props object merges this
73
+ // spread in source order (#3713), and any other spread of an object
74
+ // merges its own keys (#3861).
74
75
  return {
75
76
  ...AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined),
76
77
  ...(value.propsObject && { propsObject: true as const }),
78
+ ...(value.callerBag !== undefined && { callerBag: value.callerBag }),
77
79
  }
78
80
  }
79
81
  }
@@ -58,11 +58,13 @@ function wrapAttrValueExpression(value: AttrValue, wrap: (s: string) => string):
58
58
  return AttrValueOf.expression(wrap(flat ?? 'undefined'))
59
59
  }
60
60
  case 'spread':
61
- // Keep the Phase-1 props-object marker: the props object merges this
62
- // spread in source order (#3713).
61
+ // Keep the Phase-1 caller-bag markers: the props object merges this
62
+ // spread in source order (#3713), and any other spread of an object
63
+ // merges its own keys (#3861).
63
64
  return {
64
65
  ...AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined),
65
66
  ...(value.propsObject && { propsObject: true as const }),
67
+ ...(value.callerBag !== undefined && { callerBag: value.callerBag }),
66
68
  }
67
69
  }
68
70
  }
@@ -19,6 +19,7 @@ import { interp, spliceChildValue, conditionalMarkup, renderChildCall, mappedRow
19
19
  import { markupSlotIdsOf } from './markup-slots.ts'
20
20
  import { isEventHandlerName } from '../event-handler-name.ts'
21
21
  import { writesAnyBinding } from '../props-binding.ts'
22
+ import { isObjectSpreadProp } from './child-props-object.ts'
22
23
 
23
24
  /** Static HTML is embedded in a JS template literal; dynamic expressions use interp(). */
24
25
  function escapeStaticTemplateHtml(text: string): string {
@@ -419,11 +420,16 @@ function renderTemplateAttrPart(
419
420
  * (`SpreadAttr.propsObject`, decided in Phase 1): kept in source order next
420
421
  * to the explicit props, the object literal merges like the JSX call does
421
422
  * (#3688) — a later key overrides an earlier one, and the spread overrides
422
- * only the keys the caller passed. Any other spread stays out.
423
+ * only the keys the caller passed. A spread of any other object
424
+ * (`isObjectSpreadProp`: a loop row, an object prop, a local) is kept the
425
+ * same way, so its keys reach the child in source order (#3861). A
426
+ * `{...rest}` bag stays out: the init forwards it.
423
427
  */
424
428
  function keepsTemplateComponentProp(p: IRProp): boolean {
425
429
  if (p.name === 'key') return false
426
- if (p.name === '...' || p.name.startsWith('...')) return p.value.kind === 'spread' && p.value.propsObject === true
430
+ if (p.name === '...' || p.name.startsWith('...')) {
431
+ return p.value.kind === 'spread' && (p.value.propsObject === true || isObjectSpreadProp(p))
432
+ }
427
433
  return true
428
434
  }
429
435
 
@@ -2476,13 +2482,16 @@ export function computeDeferredChildSlots(
2476
2482
  }
2477
2483
  if (n.slotId) {
2478
2484
  const dropped = n.props.some(p => {
2479
- // Spread props (`...`) are forwarded via the rest-spread path
2480
- // (`restSpreadNames`), not the per-prop inline form, so they are
2481
- // out of scope for this drop check; `key` and event handlers
2482
- // (`onX`) likewise never carry init-scope render values. This
2483
- // filter set MUST mirror the `propsEntries` filter in the CSR
2484
- // `component` emit below so the deferral decision matches output.
2485
- if (p.name === '...' || p.name.startsWith('...') || p.name === 'key') return false
2485
+ // A caller-bag spread (`...props`, `...rest`) is forwarded off
2486
+ // `_p`, not the per-prop inline form, so it is out of scope for
2487
+ // this drop check; a spread of any other object is inlined like
2488
+ // an explicit prop and checked the same way (#3861). `key` and
2489
+ // event handlers (`onX`) never carry init-scope render values.
2490
+ // This filter set MUST mirror the `propsEntries` filter in the
2491
+ // CSR `component` emit below so the deferral decision matches
2492
+ // output.
2493
+ if (p.name === 'key') return false
2494
+ if ((p.name === '...' || p.name.startsWith('...')) && !isObjectSpreadProp(p)) return false
2486
2495
  if (p.name === 'ref') return false
2487
2496
  if (isEventHandlerName(p.name)) return false
2488
2497
  if (p.clientOnly) return false
@@ -35,7 +35,7 @@ export const RUNTIME_IMPORT_CANDIDATES = [
35
35
  'withParentScope',
36
36
  'createPortal',
37
37
  'provideContext', 'createContext', 'useContext',
38
- 'forwardProps', 'applyRestAttrs', 'splitProps', 'spreadAttrs', 'styleToCss', 'escapeAttr', 'escapeText', 'escapeTextOrNode',
38
+ 'forwardProps', 'spreadChildProps', 'applyRestAttrs', 'splitProps', 'spreadAttrs', 'styleToCss', 'escapeAttr', 'escapeText', 'escapeTextOrNode',
39
39
  // Whole-item loop conditional's `bf-loop-i:<key>` anchor comment (#1665,
40
40
  // #2795 follow-up) — neutralizes `-` so a key can't close the comment early.
41
41
  'escapeCommentText',
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * `props-extraction` phase — emit the one-time prop extractions:
3
- * `const children = _p.children [?? <default>]` (or `const kids =
3
+ * `const children = _p.children [<fallback>]` (or `const kids =
4
4
  * _p.children` for a renamed `{ children: kids }`), and `let start =
5
5
  * _p.start [?? <default>]` for each prop the component writes
6
6
  * (`ParamInfo.reassigned`, see `keepsDeclaredValue`).
@@ -12,9 +12,9 @@
12
12
  * other destructured prop is rewritten to a live read instead, by
13
13
  * `rewriteDestructuredPropReads` (`generate-init.ts`).
14
14
  *
15
- * The line is composed from `propReadBase`/`propReadFallback` rather than
15
+ * The line is composed with `composePropRead` rather than
16
16
  * `livePropReadExpr` so it stays unparenthesized — that exact
17
- * `const X = _p.X [?? d]` shape is what `pruneUnusedPropExtractions`'s AST
17
+ * `const X = <prop read>` shape is what `pruneUnusedPropExtractions`'s AST
18
18
  * matcher recognizes when the init body never reads `children`.
19
19
  *
20
20
  * Skipped entirely for an opaque props object (`propsObjectName != null`):
@@ -23,7 +23,7 @@
23
23
 
24
24
  import { type PropUsage, isChildrenPropParam } from '../../types.ts'
25
25
  import { computePropsUsedAsConditions } from '../compute-prop-usage.ts'
26
- import { propReadBase, propReadFallback, keepsDeclaredValue } from '../../props-binding.ts'
26
+ import { composePropRead, propReadBase, propReadFallback, keepsDeclaredValue, retainedPropLocals } from '../../props-binding.ts'
27
27
  import type { ClientJsContext } from '../types.ts'
28
28
 
29
29
  export function emitPropsExtraction(
@@ -47,7 +47,7 @@ export function emitPropsExtraction(
47
47
 
48
48
  const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(local)
49
49
  const fallback = propReadFallback(prop, propUsage.get(local), usedAsCondition)
50
- const read = propReadBase(prop) + (fallback === null ? '' : ` ?? ${fallback}`)
50
+ const read = composePropRead(propReadBase(prop), fallback)
51
51
  // A children binding the component writes needs a `let` to take the write.
52
52
  lines.push(` ${keepsDeclaredValue(prop) ? 'const' : 'let'} ${local} = ${read}`, '')
53
53
  }
@@ -62,9 +62,13 @@ function emitWrittenPropLocals(lines: string[], ctx: ClientJsContext, propUsage:
62
62
  const written = ctx.propsParams.filter(p => !p.isRest && !isChildrenPropParam(p) && !keepsDeclaredValue(p))
63
63
  if (written.length === 0) return
64
64
  const usedAsCondition = computePropsUsedAsConditions(ctx, new Set(written.map(p => p.name)))
65
+ // The locals are declared in parameter order, so a default reading an
66
+ // earlier written prop reads its local, as in JS (`{ a = [], b = a }`
67
+ // shares `a`'s array); an earlier prop that is not written reads live.
68
+ const retained = retainedPropLocals(ctx)
65
69
  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}`}`)
70
+ const fallback = propReadFallback(prop, propUsage.get(prop.name), usedAsCondition.has(prop.name), retained)
71
+ lines.push(` let ${prop.name} = ${composePropRead(propReadBase(prop), fallback)}`)
68
72
  }
69
73
  lines.push('')
70
74
  }
@@ -11,9 +11,9 @@
11
11
  import type { ControlledSignal } from '../init-declarations.ts'
12
12
  import type { Declaration } from '../declaration-sort.ts'
13
13
  import type { ClientJsContext } from '../types.ts'
14
- import type { ParamInfo, SignalInfo } from '../../types.ts'
14
+ import type { ConstantInfo, ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM, readsBareProp } from '../utils.ts'
16
- import { livePropReadExpr, propDefaultText } from '../../props-binding.ts'
16
+ import { coalesceDefaultText, composePropRead, livePropReadExpr, propDefaultText } from '../../props-binding.ts'
17
17
  import { signalFactoryInitializer, signalSecondBinding } from '../../signal-initializer.ts'
18
18
  import type {
19
19
  ControlledSignalEffectPlan,
@@ -54,7 +54,7 @@ export function buildDeclarationEmitPlan(
54
54
  kind: 'constant',
55
55
  keyword: c.declarationKind ?? 'const',
56
56
  name: c.name,
57
- valueExpr: c.value !== undefined ? c.value : null,
57
+ valueExpr: bodyDestructureValue(c, ctx) ?? (c.value !== undefined ? c.value : null),
58
58
  }
59
59
  }
60
60
  case 'signal':
@@ -126,7 +126,7 @@ function buildSignalPlan(
126
126
  * `<it> ?? <inferred default>`, so the signal never starts as
127
127
  * `undefined`.
128
128
  * 2. A controlled signal seeded by a bare destructured binding →
129
- * `_p.<caller key> ?? <the prop's default>`.
129
+ * `_p.<caller key>` with the prop's default (`composePropRead`).
130
130
  * 3. Anything else (a `??` / `||` fallback the user wrote, any other
131
131
  * expression) → the initializer as written; `generateInit`'s
132
132
  * `rewritePropsObjectRef` maps its `props.X` reads to `_p.X`.
@@ -138,14 +138,47 @@ function resolveSignalInitialValue(signal: SignalInfo, lookups: DeclarationEmitL
138
138
  const controlled = lookups.controlledBySignal.get(signal)
139
139
  if (controlled) {
140
140
  const prop = lookups.propByName.get(controlled.propName)
141
- const defaultVal = (prop && propDefaultText(prop)) ?? inferDefaultValue(signal.type)
142
- // `_p` is always keyed by the caller-facing name (#2524 CSR half).
143
- return `${PROPS_PARAM}.${prop?.sourceName ?? controlled.propName} ?? ${defaultVal}`
141
+ const defaultText = prop && propDefaultText(prop)
142
+ // `_p` is always keyed by the caller-facing name (#2524 CSR half). The
143
+ // prop's own default applies to an absent or `undefined` prop only;
144
+ // the inferred one keeps the signal from starting as either nil.
145
+ const base = `${PROPS_PARAM}.${prop?.sourceName ?? controlled.propName}`
146
+ return composePropRead(
147
+ base,
148
+ defaultText
149
+ ? { kind: 'default', text: coalesceDefaultText(defaultText, prop.defaultContainsArrow) }
150
+ : { kind: 'guard', text: inferDefaultValue(signal.type) },
151
+ )
144
152
  }
145
153
  }
146
154
  return signal.initialValue
147
155
  }
148
156
 
157
+ /**
158
+ * The client-JS initializer of a body destructure of the props object with
159
+ * a default (`const { label = 'x' } = props`): its prop read with the
160
+ * default applied to an absent or `undefined` prop only
161
+ * (`composePropRead`). The IR encodes the destructure as `props.label ??
162
+ * 'x'` (`ConstantInfo.value`), which the SSR seed plans read; built here
163
+ * from the props param the analyzer overlays the default onto (#2943), not
164
+ * from that text. The default is the authored expression: a read of an
165
+ * earlier binding (`{ a = [], b = a }`) stays a read of that local, which
166
+ * `rewriteBodyAliasReads` turns into a live prop read only where it drops
167
+ * the local's declaration. Null for any other constant, which keeps its own
168
+ * value.
169
+ */
170
+ function bodyDestructureValue(c: ConstantInfo, ctx: ClientJsContext): string | null {
171
+ const sourceKey = c.propsDestructure?.sourceKey
172
+ if (sourceKey === undefined || ctx.propsObjectName === null) return null
173
+ const param = ctx.propsParams.find(p => p.name === c.name && (p.sourceName ?? p.name) === sourceKey)
174
+ const defaultText = param?.defaultValue
175
+ if (!param || !defaultText) return null
176
+ return composePropRead(`${ctx.propsObjectName}.${sourceKey}`, {
177
+ kind: 'default',
178
+ text: coalesceDefaultText(defaultText, param.defaultContainsArrow),
179
+ })
180
+ }
181
+
149
182
  function buildControlledSignalEffect(
150
183
  signal: SignalInfo,
151
184
  lookups: DeclarationEmitLookups,
@@ -37,7 +37,8 @@ import { collectValueReferencedNames } from '../value-references.ts'
37
37
  import { PROPS_PARAM } from './utils.ts'
38
38
 
39
39
  /**
40
- * Does `init` read `<objectName>.<key>` or `<objectName>.<key> ?? <fallback>`?
40
+ * Does `init` read `<objectName>.<key>`, `<objectName>.<key> ?? <fallback>`,
41
+ * or a defaulted `<objectName>.<key> === undefined ? <default> : <objectName>.<key>`?
41
42
  * The one recognizer for "a prop read initializer", shared by
42
43
  * `propExtractionName` below (which additionally requires the bound name to
43
44
  * equal `key` unless `key` is `children`, and always reads off `_p`), `rewriteBodyAliasReads`
@@ -50,7 +51,9 @@ import { PROPS_PARAM } from './utils.ts'
50
51
  export function parsePropReadInitializer(
51
52
  init: ts.Expression,
52
53
  objectName: string = PROPS_PARAM,
53
- ): { key: string; fallback: ts.Expression | null } | null {
54
+ ): { key: string; fallback: ts.Expression | null; coalescesNull: boolean } | null {
55
+ const defaulted = parseDefaultedPropRead(init, objectName)
56
+ if (defaulted) return { ...defaulted, coalescesNull: false }
54
57
  let core: ts.Expression = init
55
58
  let fallback: ts.Expression | null = null
56
59
  if (
@@ -60,9 +63,30 @@ export function parsePropReadInitializer(
60
63
  fallback = core.right
61
64
  core = core.left
62
65
  }
63
- if (!ts.isPropertyAccessExpression(core)) return null
64
- if (!ts.isIdentifier(core.expression) || core.expression.text !== objectName) return null
65
- return { key: core.name.text, fallback }
66
+ const key = propReadKey(core, objectName)
67
+ // A `??` fallback (`props.x ?? d`, the author's own) replaces `null` too.
68
+ return key === null ? null : { key, fallback, coalescesNull: fallback !== null }
69
+ }
70
+
71
+ /** `<objectName>.<key>`'s key, or null for any other expression. */
72
+ function propReadKey(expr: ts.Expression, objectName: string): string | null {
73
+ if (!ts.isPropertyAccessExpression(expr)) return null
74
+ if (!ts.isIdentifier(expr.expression) || expr.expression.text !== objectName) return null
75
+ return expr.name.text
76
+ }
77
+
78
+ /**
79
+ * A destructure default as `composePropRead` spells it:
80
+ * `<objectName>.<key> === undefined ? <default> : <objectName>.<key>`.
81
+ */
82
+ function parseDefaultedPropRead(init: ts.Expression, objectName: string): { key: string; fallback: ts.Expression } | null {
83
+ if (!ts.isConditionalExpression(init)) return null
84
+ const test = init.condition
85
+ if (!ts.isBinaryExpression(test) || test.operatorToken.kind !== ts.SyntaxKind.EqualsEqualsEqualsToken) return null
86
+ if (!ts.isIdentifier(test.right) || test.right.text !== 'undefined') return null
87
+ const key = propReadKey(test.left, objectName)
88
+ if (key === null || propReadKey(init.whenFalse, objectName) !== key) return null
89
+ return { key, fallback: init.whenTrue }
66
90
  }
67
91
 
68
92
  /** Is `stmt` a single-declarator `const X = _p.X…` prop extraction whose
@@ -80,9 +104,38 @@ function propExtractionName(stmt: ts.Statement): string | null {
80
104
 
81
105
  const parsed = parsePropReadInitializer(decl.initializer)
82
106
  if (parsed === null || (parsed.key !== decl.name.text && parsed.key !== 'children')) return null
107
+ // A default that does something when it runs (`{ a = 1, b = (a = 2) }`)
108
+ // runs whether or not its binding is read, so its declaration stays.
109
+ if (parsed.fallback !== null && mayHaveSideEffect(parsed.fallback)) return null
83
110
  return decl.name.text
84
111
  }
85
112
 
113
+ /** `=`, `+=`, `??=` and the other compound assignments. */
114
+ function isAssignmentOperator(kind: ts.SyntaxKind): boolean {
115
+ return kind >= ts.SyntaxKind.FirstAssignment && kind <= ts.SyntaxKind.LastAssignment
116
+ }
117
+
118
+ /**
119
+ * Whether evaluating `expr` may do more than produce a value: an
120
+ * assignment, an update, a call, `new`, `delete`, `await` or `yield`. The
121
+ * body of a function `expr` creates is not evaluated, so it does not count.
122
+ */
123
+ function mayHaveSideEffect(expr: ts.Node): boolean {
124
+ if (ts.isArrowFunction(expr) || ts.isFunctionExpression(expr)) return false
125
+ if (ts.isBinaryExpression(expr) && isAssignmentOperator(expr.operatorToken.kind)) return true
126
+ if (ts.isPrefixUnaryExpression(expr) || ts.isPostfixUnaryExpression(expr)) {
127
+ const op = expr.operator
128
+ if (op === ts.SyntaxKind.PlusPlusToken || op === ts.SyntaxKind.MinusMinusToken) return true
129
+ }
130
+ if (
131
+ ts.isCallExpression(expr) || ts.isNewExpression(expr) || ts.isDeleteExpression(expr) ||
132
+ ts.isAwaitExpression(expr) || ts.isYieldExpression(expr) || ts.isTaggedTemplateExpression(expr)
133
+ ) {
134
+ return true
135
+ }
136
+ return ts.forEachChild(expr, child => (mayHaveSideEffect(child) ? true : undefined)) ?? false
137
+ }
138
+
86
139
  /**
87
140
  * Remove prop-extraction consts inside `init*` functions whose bound name
88
141
  * is never referenced as a value anywhere else in `code`. Returns the code
@@ -113,6 +113,31 @@ function bodyAliasDefaultParts(ctx: ClientJsContext, local: string, key: string)
113
113
  return param?.defaultParts ? { defaultParts: param.defaultParts } : {}
114
114
  }
115
115
 
116
+ /**
117
+ * Drop from `aliases` every body alias whose default reads an earlier
118
+ * binding the init body keeps as a local (`const { a = [], b = a } = props;
119
+ * a.push(x)`, or a `let` destructure): JS binds `b` to that local's value
120
+ * once, so `b` keeps its declaration (`const b = _p.b === undefined ? a :
121
+ * _p.b`) instead of a live read that would build a fresh `a` default. The
122
+ * kept locals are the body-destructured constants that are not aliases;
123
+ * an alias dropped here is kept too, so the walk repeats until it settles.
124
+ */
125
+ function keepAliasesReadingRetainedLocals(aliases: Map<string, { key: string }>, ctx: ClientJsContext): void {
126
+ const retained = new Set(
127
+ ctx.localConstants.filter(c => c.propsDestructure && !c.isModule && !aliases.has(c.name)).map(c => c.name),
128
+ )
129
+ for (let changed = true; changed; ) {
130
+ changed = false
131
+ for (const [local, alias] of aliases) {
132
+ const parts = bodyAliasDefaultParts(ctx, local, alias.key).defaultParts ?? []
133
+ if (!parts.some(part => part.kind === 'param' && retained.has(part.param.name))) continue
134
+ aliases.delete(local)
135
+ retained.add(local)
136
+ changed = true
137
+ }
138
+ }
139
+ }
140
+
116
141
  /**
117
142
  * Rewrite every bare value-position read of a BODY-destructured (or
118
143
  * bare-member-alias) prop local in `code` to a live `_p.<key>` read, for a
@@ -154,6 +179,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
154
179
  for (const [local, alias] of aliases) {
155
180
  if (alias.key === 'children') aliases.delete(local)
156
181
  }
182
+ keepAliasesReadingRetainedLocals(aliases, ctx)
157
183
  if (aliases.size === 0) return code
158
184
  // Quick exit when none of the candidate local names appear at all.
159
185
  if (![...aliases.keys()].some((name) => identifierPattern(name).test(code))) return code
@@ -161,7 +187,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
161
187
  const sourceFile = ts.createSourceFile('init-body.ts', code, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS)
162
188
 
163
189
  const spans: Array<readonly [number, number]> = []
164
- const located = new Map<string, Pick<LivePropReadInfo, 'defaultValue' | 'defaultContainsArrow' | 'defaultParts'> & { key: string }>()
190
+ const located = new Map<string, Pick<LivePropReadInfo, 'defaultValue' | 'defaultContainsArrow' | 'defaultParts' | 'coalescesNull'> & { key: string }>()
165
191
  for (const stmt of sourceFile.statements) {
166
192
  if (!ts.isFunctionDeclaration(stmt) || !stmt.name?.text.startsWith('init') || !stmt.body) continue
167
193
  for (const inner of stmt.body.statements) {
@@ -179,6 +205,9 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
179
205
  located.set(decl.name.text, {
180
206
  key: alias.key,
181
207
  defaultValue: parsedInit.fallback?.getText(sourceFile),
208
+ // An author's `props.x ?? d` keeps its `??`; a destructure default
209
+ // reads `undefined` only (`composePropRead`).
210
+ coalescesNull: parsedInit.coalescesNull,
182
211
  // `alias.defaultContainsArrow` mirrors `c.containsArrow`, computed
183
212
  // against the ORIGINAL initializer before #2940's fix wrapped an
184
213
  // arrow/function-expression default in its own protective parens
@@ -221,6 +250,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
221
250
  sourceName: info.key,
222
251
  defaultValue: info.defaultValue,
223
252
  defaultContainsArrow: info.defaultContainsArrow,
253
+ coalescesNull: info.coalescesNull,
224
254
  ...(info.defaultParts && { defaultParts: info.defaultParts }),
225
255
  }
226
256
  return livePropReadExpr(prop, undefined, false)