@barefootjs/jsx 0.39.7 → 0.39.8

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 (146) hide show
  1. package/dist/adapters/callback-method.d.ts +17 -0
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +80 -13
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +151 -0
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  7. package/dist/adapters/jsx-adapter.d.ts +4 -0
  8. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  9. package/dist/adapters/literal-value.d.ts +2 -2
  10. package/dist/adapters/literal-value.d.ts.map +1 -1
  11. package/dist/adapters/parsed-expr-emitter.d.ts +27 -0
  12. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  13. package/dist/adapters/style-object.d.ts +33 -0
  14. package/dist/adapters/style-object.d.ts.map +1 -0
  15. package/dist/analyzer.d.ts.map +1 -1
  16. package/dist/children-nullish.d.ts +22 -0
  17. package/dist/children-nullish.d.ts.map +1 -0
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/expression-parser.d.ts +9 -19
  21. package/dist/expression-parser.d.ts.map +1 -1
  22. package/dist/free-refs.d.ts +6 -0
  23. package/dist/free-refs.d.ts.map +1 -1
  24. package/dist/index.d.ts +14 -11
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +14685 -14000
  27. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  29. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  31. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  34. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  37. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  39. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  42. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  44. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/imports.d.ts +23 -2
  46. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -2
  48. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  50. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  53. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  55. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/types.d.ts +3 -3
  57. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/utils.d.ts +2 -11
  59. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  60. package/dist/jsx-to-ir.d.ts.map +1 -1
  61. package/dist/nullable-signal-attr.d.ts +40 -10
  62. package/dist/nullable-signal-attr.d.ts.map +1 -1
  63. package/dist/prop-rewrite.d.ts +18 -0
  64. package/dist/prop-rewrite.d.ts.map +1 -1
  65. package/dist/props-binding.d.ts +9 -1
  66. package/dist/props-binding.d.ts.map +1 -1
  67. package/dist/scanner/js-scanner.d.ts.map +1 -1
  68. package/dist/scanner/js-scanner.js +30 -2
  69. package/dist/signal-prop-name-collision.d.ts +6 -5
  70. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  71. package/dist/ssr-defaults.d.ts +28 -0
  72. package/dist/ssr-defaults.d.ts.map +1 -1
  73. package/dist/ssr-seed-plan.d.ts +39 -14
  74. package/dist/ssr-seed-plan.d.ts.map +1 -1
  75. package/dist/types.d.ts +108 -18
  76. package/dist/types.d.ts.map +1 -1
  77. package/dist/value-references.d.ts +21 -0
  78. package/dist/value-references.d.ts.map +1 -1
  79. package/package.json +2 -2
  80. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  81. package/src/__tests__/adapter-output.test.ts +5 -3
  82. package/src/__tests__/analyzer.test.ts +33 -0
  83. package/src/__tests__/arithmetic-lowering.test.ts +44 -0
  84. package/src/__tests__/children-read.test.ts +226 -0
  85. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  86. package/src/__tests__/component-props.test.ts +68 -1
  87. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  88. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  89. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  90. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  91. package/src/__tests__/expression-parser.test.ts +1 -44
  92. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  93. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  94. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  95. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  96. package/src/__tests__/ssr-defaults.test.ts +19 -1
  97. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  98. package/src/__tests__/style-object-plan.test.ts +54 -0
  99. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  100. package/src/adapters/callback-method.ts +23 -0
  101. package/src/adapters/component-props.ts +130 -12
  102. package/src/adapters/dsl-template-adapter.ts +248 -0
  103. package/src/adapters/jsx-adapter.ts +12 -6
  104. package/src/adapters/literal-value.ts +2 -2
  105. package/src/adapters/parsed-expr-emitter.ts +34 -0
  106. package/src/adapters/style-object.ts +61 -0
  107. package/src/analyzer.ts +114 -15
  108. package/src/children-nullish.ts +33 -0
  109. package/src/debug.ts +2 -2
  110. package/src/errors.ts +12 -0
  111. package/src/expression-parser.ts +56 -53
  112. package/src/free-refs.ts +28 -17
  113. package/src/index.ts +18 -8
  114. package/src/ir-to-client-js/compute-inlinability.ts +29 -2
  115. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  116. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  117. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  118. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  119. package/src/ir-to-client-js/csr-substitute.ts +12 -2
  120. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  121. package/src/ir-to-client-js/emit-registration.ts +28 -57
  122. package/src/ir-to-client-js/generate-init.ts +17 -1
  123. package/src/ir-to-client-js/html-template.ts +30 -50
  124. package/src/ir-to-client-js/identifiers.ts +75 -24
  125. package/src/ir-to-client-js/imports.ts +56 -19
  126. package/src/ir-to-client-js/index.ts +2 -1
  127. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  128. package/src/ir-to-client-js/phases/props-extraction.ts +16 -15
  129. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  130. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  131. package/src/ir-to-client-js/reactivity.ts +2 -2
  132. package/src/ir-to-client-js/rewrite-destructured-props.ts +21 -4
  133. package/src/ir-to-client-js/safe-html.ts +29 -35
  134. package/src/ir-to-client-js/types.ts +3 -2
  135. package/src/ir-to-client-js/utils.ts +2 -26
  136. package/src/jsx-to-ir.ts +279 -78
  137. package/src/nullable-signal-attr.ts +149 -33
  138. package/src/prop-rewrite.ts +41 -0
  139. package/src/props-binding.ts +17 -2
  140. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  141. package/src/scanner/js-scanner.ts +64 -4
  142. package/src/signal-prop-name-collision.ts +50 -24
  143. package/src/ssr-defaults.ts +47 -20
  144. package/src/ssr-seed-plan.ts +103 -23
  145. package/src/types.ts +115 -19
  146. package/src/value-references.ts +132 -0
@@ -46,9 +46,95 @@ export function isNullableSignal(signal: SignalInfo): boolean {
46
46
  return signal.type.kind === 'unknown' && isNullishLiteral(signal.parsed)
47
47
  }
48
48
 
49
- /** Getter names of the component's signals whose SSR value can be nullish. */
49
+ /**
50
+ * Getter names of the component's signals whose SSR value can be nullish:
51
+ * a nullable signal (`isNullableSignal`), or one whose seed can evaluate to
52
+ * an absent optional prop (`createSignal(props.label)`,
53
+ * `createSignal(wide ? props.label : 'narrow')`, #3567). The seed is read in
54
+ * the form the SSR seed plan resolved it to, so a hop through a
55
+ * component-scope const counts too.
56
+ */
50
57
  export function collectNullableSignalGetters(ir: ComponentIR): Set<string> {
51
- return new Set((ir.metadata.signals ?? []).filter(isNullableSignal).map(s => s.getter))
58
+ const absentReads = collectAbsentPropSeedReads(ir)
59
+ return new Set(
60
+ (ir.metadata.signals ?? []).filter(s => isNullableSignal(s) || absentReads.has(s.getter)).map(s => s.getter),
61
+ )
62
+ }
63
+
64
+ /**
65
+ * For each signal whose seed can evaluate to an absent optional prop, the
66
+ * props (by param name) it can read whole (#3567). The seed is read in the
67
+ * form the SSR seed plan resolved it to. A backend that types a prop by
68
+ * value (Go) flips each of these props to a nillable field so the absence
69
+ * survives into the signal.
70
+ */
71
+ export function collectAbsentPropSeedReads(ir: ComponentIR): Map<string, Set<string>> {
72
+ const nullableProps = collectNullablePropReads(ir)
73
+ const out = new Map<string, Set<string>>()
74
+ if (nullableProps.size === 0) return out
75
+ const resolved = new Map<string, ParsedExpr>()
76
+ for (const step of ir.metadata.ssrSeedPlan?.steps ?? []) {
77
+ if (step.kind === 'derived' && step.origin === 'signal') resolved.set(step.name, step.parsed)
78
+ }
79
+ for (const s of ir.metadata.signals ?? []) {
80
+ const reads = new Set<string>()
81
+ collectSeedPropReads(resolved.get(s.getter) ?? s.parsed, nullableProps, reads)
82
+ if (reads.size > 0) out.set(s.getter, reads)
83
+ }
84
+ return out
85
+ }
86
+
87
+ /**
88
+ * Reads of a prop that can be absent at SSR time (optional or typed with
89
+ * `undefined` / `null`, no default, not a rest param): the name a read
90
+ * uses (the binding name, or `<propsObjectName>.<key>` for a member read)
91
+ * mapped to the param name.
92
+ */
93
+ function collectNullablePropReads(ir: ComponentIR): ReadonlyMap<string, string> {
94
+ const names = new Map<string, string>()
95
+ const objectName = ir.metadata.propsObjectName
96
+ for (const p of ir.metadata.propsParams) {
97
+ if (p.isRest || p.defaultValue !== undefined) continue
98
+ if (!p.optional && !(p.type && admitsNullish(p.type))) continue
99
+ names.set(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name, p.name)
100
+ }
101
+ return names
102
+ }
103
+
104
+ /**
105
+ * Add to `out` the params of `nullableProps` a seed's value can be read
106
+ * whole from: a bare read, a ternary branch, the right operand of `??` /
107
+ * `||`, or either operand of `&&`. A call, a member read past the prop, or
108
+ * any other shape produces its own value, so it does not count.
109
+ */
110
+ function collectSeedPropReads(
111
+ expr: ParsedExpr | undefined,
112
+ nullableProps: ReadonlyMap<string, string>,
113
+ out: Set<string>,
114
+ ): void {
115
+ if (!expr) return
116
+ const add = (key: string): void => {
117
+ const param = nullableProps.get(key)
118
+ if (param !== undefined) out.add(param)
119
+ }
120
+ switch (expr.kind) {
121
+ case 'identifier':
122
+ add(expr.name)
123
+ return
124
+ case 'member':
125
+ if (!expr.computed && expr.object.kind === 'identifier') add(`${expr.object.name}.${expr.property}`)
126
+ return
127
+ case 'conditional':
128
+ collectSeedPropReads(expr.consequent, nullableProps, out)
129
+ collectSeedPropReads(expr.alternate, nullableProps, out)
130
+ return
131
+ case 'logical':
132
+ if (expr.op === '&&') collectSeedPropReads(expr.left, nullableProps, out)
133
+ collectSeedPropReads(expr.right, nullableProps, out)
134
+ return
135
+ default:
136
+ return
137
+ }
52
138
  }
53
139
 
54
140
  /**
@@ -91,10 +177,23 @@ export interface NullishAttrContext {
91
177
  readonly memos: ReadonlyMap<string, MemoInfo>
92
178
  /** Props declared as a number that may be `null` or absent (`n: number |
93
179
  * null`, `n?: number`), by the name a read uses: the binding name, and
94
- * `<propsObjectName>.<key>` for a member read (#3474). */
95
- readonly nullableNumberProps?: ReadonlySet<string>
180
+ * `<propsObjectName>.<key>` for a member read (#3474), mapped to what the
181
+ * engine's nil stands for there (`NullableNumberPropNil`, #3533). */
182
+ readonly nullableNumberProps?: ReadonlyMap<string, NullableNumberPropNil>
96
183
  }
97
184
 
185
+ /**
186
+ * What a nullable number prop's nil stands for at SSR (#3533). JS reads an
187
+ * absent prop as `undefined` (`NaN` in arithmetic) and a `null` one as `0`,
188
+ * while a template engine holds both as the same nil, so the declared type
189
+ * decides. A prop whose type admits `null` (`n: number | null`) reads its
190
+ * nil as `null`. A prop that can only be absent (`n?: number`,
191
+ * `n: number | undefined`) reads it as `undefined`; a present value, `0`
192
+ * included, is unaffected. A prop that admits both (`n?: number | null`)
193
+ * keeps the `null` reading: its nil can be either.
194
+ */
195
+ export type NullableNumberPropNil = 'null' | 'undefined'
196
+
98
197
  export function collectNullishAttrContext(ir: ComponentIR): NullishAttrContext {
99
198
  const signals = ir.metadata.signals ?? []
100
199
  return {
@@ -110,23 +209,29 @@ export function collectNullishAttrContext(ir: ComponentIR): NullishAttrContext {
110
209
  }
111
210
  }
112
211
 
113
- /** Whether `type` is a number that admits `null` / `undefined` and no other family. */
114
- function isNullableNumberType(type: TypeInfo | undefined, optional: boolean): boolean {
115
- if (!type) return false
212
+ /**
213
+ * What the nil of a number prop that admits `null` / `undefined` and no other
214
+ * family stands for (`NullableNumberPropNil`); `null` for any other type.
215
+ */
216
+ function nullableNumberPropNil(type: TypeInfo | undefined, optional: boolean): NullableNumberPropNil | null {
217
+ if (!type) return null
116
218
  const members = type.kind === 'union' ? (type.unionTypes ?? []) : [type]
117
219
  const families = new Set(members.map(m => (m.kind === 'primitive' ? m.primitive : m.kind)))
118
- const nullable = optional || families.has('null') || families.has('undefined')
220
+ const admitsNull = families.has('null')
221
+ const nullable = optional || admitsNull || families.has('undefined')
119
222
  families.delete('null')
120
223
  families.delete('undefined')
121
- return nullable && families.size === 1 && families.has('number')
224
+ if (!nullable || families.size !== 1 || !families.has('number')) return null
225
+ return admitsNull ? 'null' : 'undefined'
122
226
  }
123
227
 
124
- function collectNullableNumberProps(ir: ComponentIR): ReadonlySet<string> {
125
- const names = new Set<string>()
228
+ function collectNullableNumberProps(ir: ComponentIR): ReadonlyMap<string, NullableNumberPropNil> {
229
+ const names = new Map<string, NullableNumberPropNil>()
126
230
  const objectName = ir.metadata.propsObjectName
127
231
  for (const p of ir.metadata.propsParams) {
128
- if (p.isRest || p.defaultValue !== undefined || !isNullableNumberType(p.type, p.optional)) continue
129
- names.add(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name)
232
+ if (p.isRest || p.defaultValue !== undefined) continue
233
+ const nil = nullableNumberPropNil(p.type, p.optional)
234
+ if (nil !== null) names.set(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name, nil)
130
235
  }
131
236
  return names
132
237
  }
@@ -230,17 +335,25 @@ export function arithmeticOperandIsUndefined(
230
335
  return arithmeticOperandSeed(parsed, ctx, isShadowed) === 'undefined'
231
336
  }
232
337
 
338
+ /**
339
+ * What an arithmetic operand's SSR nil stands for: `'null'` / `'undefined'`
340
+ * when the operand is that value (a nullable number prop's `null` reading
341
+ * included), `'absent'` when it is a number prop that may be absent
342
+ * (`n?: number`), whose nil is `undefined` but which may hold a number.
343
+ */
344
+ type OperandSeed = 'null' | 'undefined' | 'absent' | null
345
+
233
346
  function arithmeticOperandSeed(
234
347
  parsed: ParsedExpr | undefined,
235
348
  ctx: NullishAttrContext,
236
349
  isShadowed: (name: string) => boolean,
237
- ): 'null' | 'undefined' | null {
350
+ ): OperandSeed {
238
351
  const visiting = new Set<string>()
239
- const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): 'null' | 'undefined' | null => {
352
+ const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): OperandSeed => {
240
353
  if (expr.kind === 'literal') return expr.literalType === 'null' ? 'null' : null
241
354
  if (expr.kind === 'identifier' && expr.name === 'undefined' && !shadowed('undefined')) return 'undefined'
242
355
  const prop = nullableNumberPropRead(expr, ctx, shadowed)
243
- if (prop) return 'null'
356
+ if (prop !== null) return prop === 'undefined' ? 'absent' : 'null'
244
357
  const getter = expr.kind === 'identifier' ? expr.name : bareGetterCallName(expr)
245
358
  if (getter === null || shadowed(getter)) return null
246
359
  if (ctx.nullSeededSignals?.has(getter)) return 'null'
@@ -256,22 +369,20 @@ function arithmeticOperandSeed(
256
369
  }
257
370
 
258
371
  /**
259
- * A read of a prop declared as a nullable number. Its SSR value may be
260
- * `null` or absent; it is coerced like a `null` operand. JS reads an absent
261
- * prop as `undefined` (`NaN` in arithmetic), which a template engine cannot
262
- * tell from `null` (the `omitted-optional-number-arithmetic` limitation).
372
+ * What the nil of a read of a prop declared as a nullable number stands for
373
+ * (`NullableNumberPropNil`), or `null` when the read is not such a prop.
263
374
  */
264
375
  function nullableNumberPropRead(
265
376
  expr: ParsedExpr,
266
377
  ctx: NullishAttrContext,
267
378
  shadowed: (name: string) => boolean,
268
- ): boolean {
269
- if (!ctx.nullableNumberProps?.size) return false
270
- if (expr.kind === 'identifier') return !shadowed(expr.name) && ctx.nullableNumberProps.has(expr.name)
379
+ ): NullableNumberPropNil | null {
380
+ if (!ctx.nullableNumberProps?.size) return null
381
+ if (expr.kind === 'identifier') return shadowed(expr.name) ? null : (ctx.nullableNumberProps.get(expr.name) ?? null)
271
382
  if (expr.kind === 'member' && !expr.computed && expr.object.kind === 'identifier' && !shadowed(expr.object.name)) {
272
- return ctx.nullableNumberProps.has(`${expr.object.name}.${expr.property}`)
383
+ return ctx.nullableNumberProps.get(`${expr.object.name}.${expr.property}`) ?? null
273
384
  }
274
- return false
385
+ return null
275
386
  }
276
387
 
277
388
  /**
@@ -285,18 +396,21 @@ export const NULL_COERCING_ARITHMETIC_OPS: ReadonlySet<string> = new Set(['-', '
285
396
 
286
397
  /** How a DSL adapter coerces an arithmetic operand (#3474): `'null'` reads a
287
398
  * nil as `0` (JS `ToNumber(null)`), `'undefined'` reads it as `NaN`
288
- * (`ToNumber(undefined)`), `null` leaves the operand as is. */
399
+ * (`ToNumber(undefined)`), `null` leaves the operand as is. Either coercion
400
+ * leaves a non-nil operand's value as it is. */
289
401
  export type ArithmeticCoercion = 'null' | 'undefined' | null
290
402
 
291
403
  /**
292
404
  * The one decision behind every DSL adapter's arithmetic over a nullish
293
405
  * operand (#3474). An operand known to be `null` / `undefined`
294
- * (`arithmeticOperandIsNull` / `arithmeticOperandIsUndefined`, or a nullable
295
- * number prop) is coerced under the operators JS applies `ToNumber` to
296
- * ({@link NULL_COERCING_ARITHMETIC_OPS}), and under `+` when the other
297
- * operand is a number literal, where `+` cannot concatenate. Each adapter
298
- * only spells the coercion; one whose engine already reads nil as `0`
299
- * spells `'null'` as the operand itself.
406
+ * (`arithmeticOperandIsNull` / `arithmeticOperandIsUndefined`), or a
407
+ * nullable number prop, whose nil reads as its type says
408
+ * (`NullableNumberPropNil`, #3533), is coerced under the operators JS
409
+ * applies `ToNumber` to ({@link NULL_COERCING_ARITHMETIC_OPS}), and under
410
+ * `+` when the other operand is a number literal, where `+` cannot
411
+ * concatenate. Unary minus applies `ToNumber` too: it passes `'-'` with no
412
+ * `other`. Each adapter only spells the coercion; one whose engine already
413
+ * reads nil as `0` spells `'null'` as the operand itself.
300
414
  */
301
415
  export function arithmeticOperandCoercion(
302
416
  op: string,
@@ -306,7 +420,9 @@ export function arithmeticOperandCoercion(
306
420
  isShadowed: (name: string) => boolean = () => false,
307
421
  ): ArithmeticCoercion {
308
422
  const numeric = NULL_COERCING_ARITHMETIC_OPS.has(op) || (op === '+' && isNumberLiteral(other))
309
- return numeric ? arithmeticOperandSeed(operand, ctx, isShadowed) : null
423
+ if (!numeric) return null
424
+ const seed = arithmeticOperandSeed(operand, ctx, isShadowed)
425
+ return seed === 'absent' ? 'undefined' : seed
310
426
  }
311
427
 
312
428
  function isNumberLiteral(expr: ParsedExpr | undefined): boolean {
@@ -213,6 +213,47 @@ export function rewriteScopedValueRefs(
213
213
  return result
214
214
  }
215
215
 
216
+ /** A piece of `splitScopedValueRefs`'s result: text between references, or one reference. */
217
+ export type ScopedValueRefPiece = { kind: 'text'; text: string } | { kind: 'ref'; name: string }
218
+
219
+ /**
220
+ * The structured twin of `rewriteScopedValueRefs`: the same scope-aware walk,
221
+ * but instead of splicing a replacement it splits `text` at each value
222
+ * reference to a name in `names`, so a later stage renders each reference by
223
+ * its own rule without touching the text again (#3531). A shorthand property
224
+ * (`{ off }`) keeps its key as text (`off: `) before the reference. Returns
225
+ * null when `text` doesn't parse as an expression, and an empty reference set
226
+ * leaves one `text` piece.
227
+ */
228
+ export function splitScopedValueRefs(text: string, names: ReadonlySet<string>): ScopedValueRefPiece[] | null {
229
+ const prefix = '('
230
+ const sf = ts.createSourceFile('__bf_scoped_split.ts', `${prefix}${text}\n)`, ts.ScriptTarget.Latest, true)
231
+ const parseDiagnostics = (sf as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics
232
+ if (parseDiagnostics && parseDiagnostics.length > 0) return null
233
+
234
+ const refs: Array<{ start: number; end: number; name: string; key?: string }> = []
235
+ walkWithScope(sf, (n, parent, shadowed) => {
236
+ if (shadowed || !names.has(n.text)) return
237
+ if (isNonValuePosition(n, parent)) return
238
+ const start = n.getStart(sf) - prefix.length
239
+ const end = n.getEnd() - prefix.length
240
+ if (start < 0 || end > text.length) return
241
+ const shorthand = parent !== undefined && ts.isShorthandPropertyAssignment(parent) && parent.name === n
242
+ refs.push({ start, end, name: n.text, ...(shorthand && { key: n.text }) })
243
+ })
244
+
245
+ const pieces: ScopedValueRefPiece[] = []
246
+ let cursor = 0
247
+ for (const ref of refs.sort((a, b) => a.start - b.start)) {
248
+ const before = text.slice(cursor, ref.start) + (ref.key !== undefined ? `${ref.key}: ` : '')
249
+ if (before !== '') pieces.push({ kind: 'text', text: before })
250
+ pieces.push({ kind: 'ref', name: ref.name })
251
+ cursor = ref.end
252
+ }
253
+ if (cursor < text.length) pieces.push({ kind: 'text', text: text.slice(cursor) })
254
+ return pieces
255
+ }
256
+
216
257
  /**
217
258
  * `applyScopedPropRefRewrite` specializes `rewriteScopedValueRefs` for
218
259
  * the destructured-prop case: the substitution defaults to
@@ -332,7 +332,7 @@ const EMPTY_SET: ReadonlySet<string> = new Set()
332
332
  * never bound a parameter — so callers synthesize one of these instead of a
333
333
  * full `ParamInfo` (which would need a fabricated `type`/`optional`).
334
334
  */
335
- export type LivePropReadInfo = Pick<ParamInfo, 'name' | 'sourceName' | 'defaultValue' | 'defaultContainsArrow'>
335
+ export type LivePropReadInfo = Pick<ParamInfo, 'name' | 'sourceName' | 'defaultValue' | 'defaultContainsArrow' | 'defaultParts'>
336
336
 
337
337
  /** `_p.<callerKey>` — `_p` is always keyed by the caller-facing name (#2524 CSR half). */
338
338
  export function propReadBase(p: LivePropReadInfo): string {
@@ -372,12 +372,27 @@ export function propReadFallback(
372
372
  usage: PropUsage | undefined,
373
373
  usedAsCondition: boolean,
374
374
  ): string | null {
375
- if (p.defaultValue) return coalesceDefaultText(p.defaultValue, p.defaultContainsArrow)
375
+ const defaultText = propDefaultText(p)
376
+ if (defaultText) return coalesceDefaultText(defaultText, p.defaultContainsArrow)
376
377
  if (usage?.usedAsLoopArray) return '[]'
377
378
  if (propHasPropertyAccess(usage) && !usedAsCondition) return '{}'
378
379
  return null
379
380
  }
380
381
 
382
+ /**
383
+ * A prop's destructure default as client JS. A default that reads an earlier
384
+ * binding of its own pattern (`{ off = false, on = off }`, #3531) renders each
385
+ * read as that prop's own live read (`_p.off ?? false`), since the emitted
386
+ * scope binds no `off`; any other default is its source text. Undefined when
387
+ * the prop has no default.
388
+ */
389
+ export function propDefaultText(p: LivePropReadInfo): string | undefined {
390
+ if (!p.defaultParts) return p.defaultValue
391
+ return p.defaultParts
392
+ .map(part => (part.kind === 'text' ? part.text : livePropReadExpr(part.param, undefined, false)))
393
+ .join('')
394
+ }
395
+
381
396
  /**
382
397
  * The live read of a destructured prop inside init scope, in the same shape
383
398
  * props-object mode emits for `props.X`. The one formula every live-read
@@ -1,8 +1,11 @@
1
1
  import { describe, test, expect } from 'bun:test'
2
+ import ts from 'typescript'
2
3
  import {
3
4
  replaceInExprContexts,
4
5
  findInterpolationEnd,
5
6
  findTopLevelTemplateLiterals,
7
+ isTriviaKind,
8
+ iterateJsTokens,
6
9
  } from '../js-scanner'
7
10
 
8
11
  // ---------------------------------------------------------------------------
@@ -243,3 +246,37 @@ describe('findTopLevelTemplateLiterals', () => {
243
246
  expect(r).toEqual(['<a/>', '<b/>'])
244
247
  })
245
248
  })
249
+
250
+ describe('iterateJsTokens: division after a keyword used as a name (#3536)', () => {
251
+ const kinds = (text: string) =>
252
+ [...iterateJsTokens(text)].filter(t => !isTriviaKind(t.kind)).map(t => ts.SyntaxKind[t.kind])
253
+
254
+ test('a contextual-keyword binding is followed by division', () => {
255
+ expect(kinds('type / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
256
+ })
257
+
258
+ test('a keyword-named member is followed by division', () => {
259
+ expect(kinds('obj.default / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
260
+ expect(kinds('obj?.new / 2')).not.toContain('RegularExpressionLiteral')
261
+ })
262
+
263
+ test('`of` as a binding is followed by division; as the for-of separator, by a regex literal', () => {
264
+ expect(kinds('of / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
265
+ expect(kinds('for (const hit of /"/.exec(x) || []) {}')).toContain('RegularExpressionLiteral')
266
+ expect(kinds('for (const [a, b] of /x/.exec(s)) {}')).toContain('RegularExpressionLiteral')
267
+ expect(kinds('for await (const hit of /x/.exec(s)) {}')).toContain('RegularExpressionLiteral')
268
+ expect(kinds('for (const type of /"/.exec(x) || []) {}')).toContain('RegularExpressionLiteral')
269
+ expect(kinds('for (const of of /x/.exec(s)) {}')).toContain('RegularExpressionLiteral')
270
+ })
271
+
272
+ test('`of` after a binding outside a for header is a name (ASI)', () => {
273
+ expect(kinds('let of = x\nof /= step\nreturn of')).not.toContain('RegularExpressionLiteral')
274
+ expect(kinds('f(x)\nof / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
275
+ })
276
+
277
+ test('an operator keyword still starts a regex literal', () => {
278
+ expect(kinds('return /a/.test(x)')).toContain('RegularExpressionLiteral')
279
+ expect(kinds('typeof /a/')).toContain('RegularExpressionLiteral')
280
+ expect(kinds('await /a/.test(x)')).toContain('RegularExpressionLiteral')
281
+ })
282
+ })
@@ -62,9 +62,14 @@ export function* iterateJsTokens(
62
62
  // closes an object literal nested inside.
63
63
  const templateStack: { braceDepth: number }[] = []
64
64
 
65
- // Previous *significant* (non-trivia) token kind. Drives the `/`
66
- // regex-vs-division decision.
65
+ // Whether a `/` after the previous *significant* (non-trivia) token
66
+ // starts a regex literal (`regexAfter`), and that token's kind.
67
67
  let prevSignificant: ts.SyntaxKind | undefined
68
+ let regexMayStart = true
69
+ // One entry per open `(`: whether it opens a `for (…)` / `for await (…)`
70
+ // header, where `of` can be the for-of separator.
71
+ const parens: boolean[] = []
72
+ let beforePrev: ts.SyntaxKind | undefined
68
73
 
69
74
  while (true) {
70
75
  let kind = scanner.scan()
@@ -74,7 +79,7 @@ export function* iterateJsTokens(
74
79
  // significant token cannot end an expression.
75
80
  if (
76
81
  (kind === ts.SyntaxKind.SlashToken || kind === ts.SyntaxKind.SlashEqualsToken)
77
- && canRegexStartHere(prevSignificant)
82
+ && regexMayStart
78
83
  ) {
79
84
  kind = scanner.reScanSlashToken()
80
85
  }
@@ -106,10 +111,65 @@ export function* iterateJsTokens(
106
111
 
107
112
  yield { kind, pos: scanner.getTokenStart(), end: scanner.getTokenEnd() }
108
113
 
109
- if (!isTriviaKind(kind)) prevSignificant = kind
114
+ if (!isTriviaKind(kind)) {
115
+ trackForHeaderParens(parens, kind, prevSignificant, beforePrev)
116
+ regexMayStart = regexAfter(kind, prevSignificant, parens[parens.length - 1] === true)
117
+ beforePrev = prevSignificant
118
+ prevSignificant = kind
119
+ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Push / pop `parens` for an open / close paren: each entry says whether that
125
+ * `(` opens a `for (…)` or `for await (…)` header.
126
+ */
127
+ function trackForHeaderParens(
128
+ parens: boolean[],
129
+ kind: ts.SyntaxKind,
130
+ prev: ts.SyntaxKind | undefined,
131
+ beforePrev: ts.SyntaxKind | undefined,
132
+ ): void {
133
+ if (kind === ts.SyntaxKind.OpenParenToken) {
134
+ parens.push(prev === ts.SyntaxKind.ForKeyword
135
+ || (prev === ts.SyntaxKind.AwaitKeyword && beforePrev === ts.SyntaxKind.ForKeyword))
136
+ } else if (kind === ts.SyntaxKind.CloseParenToken) {
137
+ parens.pop()
110
138
  }
111
139
  }
112
140
 
141
+ /**
142
+ * Whether a `/` right after a `kind` token (itself preceded by `before`)
143
+ * starts a regex literal. A keyword used as a name ends an expression like
144
+ * an identifier does, so `/` after it is division: a member name
145
+ * (`obj.default / 2`) and a contextual keyword, which is a legal binding
146
+ * name (`type / 2`). `await` keeps its operator reading (`await /re/`), and
147
+ * so does `of` as the separator of a `for (…)` header (`inForHeader`).
148
+ */
149
+ function regexAfter(kind: ts.SyntaxKind, before: ts.SyntaxKind | undefined, inForHeader: boolean): boolean {
150
+ if (kind >= ts.SyntaxKind.FirstKeyword && kind <= ts.SyntaxKind.LastKeyword) {
151
+ if (before === ts.SyntaxKind.DotToken || before === ts.SyntaxKind.QuestionDotToken) return false
152
+ // `of` right after a binding, directly inside a `for (…)` header, is the
153
+ // for-of separator, which an expression follows:
154
+ // `for (const hit of /re/.exec(s))`. Elsewhere (`let of = x⏎of /= 2`)
155
+ // it is a name.
156
+ if (kind === ts.SyntaxKind.OfKeyword && inForHeader && endsBinding(before)) return true
157
+ if (kind > ts.SyntaxKind.LastFutureReservedWord && kind !== ts.SyntaxKind.AwaitKeyword) return false
158
+ }
159
+ return canRegexStartHere(kind)
160
+ }
161
+
162
+ /**
163
+ * Whether a `before` token can end a `for…of` binding: a name (`x`, or a
164
+ * contextual keyword used as one, `type`), `[a, b]` or `{ a }`.
165
+ */
166
+ function endsBinding(before: ts.SyntaxKind | undefined): boolean {
167
+ return before === ts.SyntaxKind.Identifier
168
+ || before === ts.SyntaxKind.CloseBracketToken
169
+ || before === ts.SyntaxKind.CloseBraceToken
170
+ || (before !== undefined && before > ts.SyntaxKind.LastFutureReservedWord && before <= ts.SyntaxKind.LastKeyword)
171
+ }
172
+
113
173
  export function isTriviaKind(kind: ts.SyntaxKind): boolean {
114
174
  return (
115
175
  kind === ts.SyntaxKind.WhitespaceTrivia
@@ -1,7 +1,8 @@
1
1
  import ts from 'typescript'
2
2
  import path from 'node:path'
3
3
  import type { AnalyzerContext } from './analyzer-context.ts'
4
- import type { ParsedExpr } from './expression-parser.ts'
4
+ import type { SourceLocation } from './types.ts'
5
+ import { localConstValuesByName, referencesOwnProp } from './ssr-defaults.ts'
5
6
 
6
7
  // TypeScript exposes these resolution-cache readers on Program at runtime
7
8
  // (its own incremental rebuild uses them), but omits them from the public
@@ -65,21 +66,47 @@ export function programWithSeparatedSource(program: ts.Program, filePath: string
65
66
  } })
66
67
  }
67
68
 
68
- function isLiteralTree(expr: ParsedExpr): boolean {
69
- switch (expr.kind) {
70
- case 'literal': return true
71
- case 'array-literal': return expr.elements.every(isLiteralTree)
72
- case 'object-literal': return expr.properties.every(p => p.kind === 'prop' && isLiteralTree(p.value))
73
- case 'unary': return ['-', '+'].includes(expr.op) && expr.argument.kind === 'literal' && expr.argument.literalType === 'number'
74
- default: return false
75
- }
69
+ /** A component-scope signal getter or memo whose binding is renamed. */
70
+ interface SeparatedBinding {
71
+ name: string
72
+ loc: SourceLocation
73
+ prefix: 'bfSignal' | 'bfMemo'
74
+ }
75
+
76
+ /**
77
+ * Signal getters and memos that share a name with a prop of a bare-props
78
+ * component (`props.label` beside `const [label] = createSignal(...)` or
79
+ * `const label = createMemo(...)`). The comparison ignores case because a
80
+ * backend may fold it (Go exports both `label` and `Label` as the field
81
+ * `Label`).
82
+ *
83
+ * A binding whose own initializer derives from that same prop
84
+ * (`createSignal(props.label ?? 'x')`) is left alone: the template-stash
85
+ * backends keep it on the prop's variable, seeded from the raw prop, and
86
+ * `extractSsrDefaults` decides that case with the same `referencesOwnProp`
87
+ * test. A raw `props.label` read beside such a binding then sees the
88
+ * derived value (limitation `signal-from-same-named-prop-raw-read`).
89
+ */
90
+ function collidingBindings(ctx: AnalyzerContext, propsObjectName: string): SeparatedBinding[] {
91
+ const propNames = new Set(ctx.propsParams.map(p => p.name.toLowerCase()))
92
+ const localConsts = localConstValuesByName(ctx)
93
+ const collides = (name: string, derivation: string): boolean =>
94
+ propNames.has(name.toLowerCase()) && !referencesOwnProp(derivation, propsObjectName, name, localConsts)
95
+ const signals: SeparatedBinding[] = ctx.signals
96
+ .filter(s => !s.isModule && !s.getterElided && !s.envReader && collides(s.getter, s.initialValue))
97
+ .map(s => ({ name: s.getter, loc: s.loc, prefix: 'bfSignal' }))
98
+ const memos: SeparatedBinding[] = ctx.memos
99
+ .filter(m => !m.isModule && collides(m.name, m.computation))
100
+ .map(m => ({ name: m.name, loc: m.loc, prefix: 'bfMemo' }))
101
+ return [...signals, ...memos]
76
102
  }
77
103
 
78
104
  /**
79
- * A bare prop and a literal-seeded getter are different JS bindings, but
80
- * scalar template backends flatten both to one variable. Give the local
81
- * getter a hygienic name before building IR, so every backend (including
82
- * the client emitter) receives one consistent binding identity.
105
+ * A prop and a signal getter or memo of the same name are different JS
106
+ * bindings (`props.label` and `label()`), but scalar template backends
107
+ * flatten both to one variable. Give the local binding a hygienic name
108
+ * before building IR, so every backend (including the client emitter)
109
+ * receives one consistent binding identity.
83
110
  *
84
111
  * Source edits are AST/symbol-based and preserve untouched source bytes.
85
112
  * Property keys, strings, and shadowing callback bindings never rename;
@@ -88,15 +115,12 @@ function isLiteralTree(expr: ParsedExpr): boolean {
88
115
  * fallback binds the already-parsed SourceFile without parsing or loading
89
116
  * dependencies: only lexical symbol identity is needed, not types.
90
117
  */
91
- export function separateLiteralSignalPropBindings(
118
+ export function separateSignalPropBindings(
92
119
  ctx: AnalyzerContext,
93
120
  isNonReference: (id: ts.Identifier) => boolean,
94
121
  ): string | null {
95
122
  if (!ctx.propsObjectName || !ctx.componentNode) return null
96
- const propNames = new Set(ctx.propsParams.map(p => p.name))
97
- const candidates = ctx.signals.filter(s =>
98
- !s.isModule && !s.getterElided && propNames.has(s.getter) && s.parsed && isLiteralTree(s.parsed),
99
- )
123
+ const candidates = collidingBindings(ctx, ctx.propsObjectName)
100
124
  if (candidates.length === 0) return null
101
125
 
102
126
  const sf = ctx.sourceFile
@@ -111,23 +135,25 @@ export function separateLiteralSignalPropBindings(
111
135
  ts.forEachChild(node, collectNames)
112
136
  }
113
137
  collectNames(sf)
138
+ // A prop typed by an imported interface has no identifier in this file.
139
+ for (const p of ctx.propsParams) occupied.add(p.name.toLowerCase())
114
140
 
115
141
  const renames = new Map<ts.Symbol, string>()
116
- const declarations = new Map(candidates.map(s => [
117
- sf.getPositionOfLineAndCharacter(s.loc.start.line - 1, s.loc.start.column), s,
142
+ const declarations = new Map(candidates.map(b => [
143
+ sf.getPositionOfLineAndCharacter(b.loc.start.line - 1, b.loc.start.column), b,
118
144
  ]))
119
145
  function collectBindings(node: ts.Node): void {
120
146
  if (ts.isVariableDeclaration(node)) {
121
- const signal = declarations.get(node.getStart(sf))
122
- if (signal) {
147
+ const binding = declarations.get(node.getStart(sf))
148
+ if (binding) {
123
149
  const names = ts.isIdentifier(node.name) ? [node.name]
124
150
  : ts.isArrayBindingPattern(node.name)
125
151
  ? node.name.elements.flatMap(e => ts.isBindingElement(e) && ts.isIdentifier(e.name) ? [e.name] : [])
126
152
  : []
127
- const id = names.find(n => n.text === signal.getter)
153
+ const id = names.find(n => n.text === binding.name)
128
154
  const symbol = id && checker.getSymbolAtLocation(id)
129
155
  if (symbol) {
130
- const base = `bfSignal_${signal.getter}`
156
+ const base = `${binding.prefix}_${binding.name}`
131
157
  let name = base
132
158
  let suffix = 0
133
159
  while (occupied.has(name.toLowerCase())) name = `${base}_${++suffix}`