@barefootjs/jsx 0.40.1 → 0.40.2

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 (176) hide show
  1. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +4 -3
  2. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +1 -1
  3. package/dist/adapters/boolean-result.d.ts +32 -10
  4. package/dist/adapters/boolean-result.d.ts.map +1 -1
  5. package/dist/adapters/brace-delimiter-text.d.ts +18 -0
  6. package/dist/adapters/brace-delimiter-text.d.ts.map +1 -0
  7. package/dist/adapters/callback-method.d.ts +38 -5
  8. package/dist/adapters/callback-method.d.ts.map +1 -1
  9. package/dist/adapters/computed-const.d.ts +11 -1
  10. package/dist/adapters/computed-const.d.ts.map +1 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts +21 -0
  12. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  13. package/dist/adapters/loop-bound-names.d.ts +9 -1
  14. package/dist/adapters/loop-bound-names.d.ts.map +1 -1
  15. package/dist/adapters/loop-row-type.d.ts +52 -0
  16. package/dist/adapters/loop-row-type.d.ts.map +1 -0
  17. package/dist/adapters/nil-reading.d.ts +68 -0
  18. package/dist/adapters/nil-reading.d.ts.map +1 -0
  19. package/dist/adapters/non-primitive-equality.d.ts +33 -0
  20. package/dist/adapters/non-primitive-equality.d.ts.map +1 -0
  21. package/dist/adapters/number-value.d.ts +5 -3
  22. package/dist/adapters/number-value.d.ts.map +1 -1
  23. package/dist/adapters/operand-typing.d.ts +126 -0
  24. package/dist/adapters/operand-typing.d.ts.map +1 -0
  25. package/dist/adapters/parsed-expr-emitter.d.ts +70 -12
  26. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  27. package/dist/adapters/primitive-plan.d.ts +291 -0
  28. package/dist/adapters/primitive-plan.d.ts.map +1 -0
  29. package/dist/analyzer-context.d.ts +4 -0
  30. package/dist/analyzer-context.d.ts.map +1 -1
  31. package/dist/analyzer.d.ts.map +1 -1
  32. package/dist/augment-inherited-props.d.ts +63 -8
  33. package/dist/augment-inherited-props.d.ts.map +1 -1
  34. package/dist/compiler.d.ts.map +1 -1
  35. package/dist/event-handler-name.d.ts +12 -0
  36. package/dist/event-handler-name.d.ts.map +1 -1
  37. package/dist/expression-parser.d.ts +8 -0
  38. package/dist/expression-parser.d.ts.map +1 -1
  39. package/dist/index.d.ts +19 -9
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +4628 -2198
  42. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/child-props-object.d.ts +64 -0
  44. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -0
  45. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +4 -2
  50. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/imports.d.ts +2 -2
  53. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/index.d.ts +2 -6
  55. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +30 -18
  58. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +3 -2
  61. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  62. package/dist/jsx-to-ir.d.ts +1 -0
  63. package/dist/jsx-to-ir.d.ts.map +1 -1
  64. package/dist/nullable-signal-attr.d.ts +68 -9
  65. package/dist/nullable-signal-attr.d.ts.map +1 -1
  66. package/dist/prop-rewrite.d.ts +7 -0
  67. package/dist/prop-rewrite.d.ts.map +1 -1
  68. package/dist/props-object-whole-read.d.ts +15 -0
  69. package/dist/props-object-whole-read.d.ts.map +1 -0
  70. package/dist/rich-type-refusal.d.ts.map +1 -1
  71. package/dist/scope/binding-scope.d.ts +85 -10
  72. package/dist/scope/binding-scope.d.ts.map +1 -1
  73. package/dist/scope/lexical-scope-walk.d.ts +3 -2
  74. package/dist/scope/lexical-scope-walk.d.ts.map +1 -1
  75. package/dist/scope/root-prop-alias.d.ts +10 -7
  76. package/dist/scope/root-prop-alias.d.ts.map +1 -1
  77. package/dist/strip-types.d.ts +13 -0
  78. package/dist/strip-types.d.ts.map +1 -1
  79. package/dist/template-position-walk.d.ts +21 -3
  80. package/dist/template-position-walk.d.ts.map +1 -1
  81. package/dist/types.d.ts +90 -0
  82. package/dist/types.d.ts.map +1 -1
  83. package/package.json +2 -2
  84. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  85. package/src/__tests__/binding-scope.test.ts +89 -1
  86. package/src/__tests__/body-destructure-props-object-alias.test.ts +123 -0
  87. package/src/__tests__/boolean-result.test.ts +22 -5
  88. package/src/__tests__/brace-delimiter-text.test.ts +26 -0
  89. package/src/__tests__/callback-method.test.ts +62 -2
  90. package/src/__tests__/child-components-in-map.test.ts +1 -1
  91. package/src/__tests__/computed-const.test.ts +103 -0
  92. package/src/__tests__/emit-to-string-call.test.ts +2 -1
  93. package/src/__tests__/hydration-payload-analysis.test.ts +166 -0
  94. package/src/__tests__/issue-2724-prop-alias-loop-not-static.test.ts +7 -7
  95. package/src/__tests__/issue-2754-rest-spread-needs-slot.test.ts +5 -2
  96. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +1 -1
  97. package/src/__tests__/issue-2835-props-type-member-name-collision.test.ts +4 -4
  98. package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +1 -1
  99. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +2 -1
  100. package/src/__tests__/issue-3713-props-spread-loop-row.test.ts +65 -0
  101. package/src/__tests__/lookup-literal-const.test.ts +9 -3
  102. package/src/__tests__/loop-index-reactivity.test.ts +2 -2
  103. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +1 -1
  104. package/src/__tests__/loop-plan.test.ts +1 -1
  105. package/src/__tests__/loop-row-const-initializer-shadow.test.ts +146 -0
  106. package/src/__tests__/loop-row-type.test.ts +64 -0
  107. package/src/__tests__/lowering-value-position.test.ts +4 -0
  108. package/src/__tests__/module-const-destructure-default.test.ts +156 -0
  109. package/src/__tests__/nested-loop-index-param.test.ts +1 -1
  110. package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
  111. package/src/__tests__/nested-row-shadowing.test.ts +2 -2
  112. package/src/__tests__/nil-reading.test.ts +77 -0
  113. package/src/__tests__/nullable-signal-attr.test.ts +134 -0
  114. package/src/__tests__/primitive-plan.test.ts +416 -0
  115. package/src/__tests__/profile-loop-binding-ids.test.ts +2 -2
  116. package/src/__tests__/profile-nested-binding-ids.test.ts +2 -2
  117. package/src/__tests__/props-object-whole-read.test.ts +40 -0
  118. package/src/__tests__/reactive-attrs-in-map.test.ts +1 -1
  119. package/src/__tests__/reactive-factory-inlining.test.ts +4 -1
  120. package/src/__tests__/rest-binding-gaps.test.ts +192 -0
  121. package/src/__tests__/root-prop-alias.test.ts +53 -8
  122. package/src/__tests__/static-loop-csr-materialize.test.ts +2 -2
  123. package/src/__tests__/static-record-literal-array.test.ts +171 -0
  124. package/src/__tests__/string-concat-identifier.test.ts +40 -1
  125. package/src/adapters/ambiguous-nil-arithmetic.ts +22 -13
  126. package/src/adapters/boolean-result.ts +72 -66
  127. package/src/adapters/brace-delimiter-text.ts +25 -0
  128. package/src/adapters/callback-method.ts +151 -27
  129. package/src/adapters/computed-const.ts +238 -4
  130. package/src/adapters/dsl-template-adapter.ts +40 -2
  131. package/src/adapters/loop-bound-names.ts +9 -1
  132. package/src/adapters/loop-plan.ts +1 -1
  133. package/src/adapters/loop-row-type.ts +139 -0
  134. package/src/adapters/nil-reading.ts +297 -0
  135. package/src/adapters/non-primitive-equality.ts +92 -0
  136. package/src/adapters/number-value.ts +17 -4
  137. package/src/adapters/operand-typing.ts +522 -0
  138. package/src/adapters/parsed-expr-emitter.ts +154 -19
  139. package/src/adapters/primitive-plan.ts +696 -0
  140. package/src/analyzer-context.ts +6 -0
  141. package/src/analyzer.ts +505 -19
  142. package/src/augment-inherited-props.ts +108 -10
  143. package/src/compiler.ts +17 -0
  144. package/src/event-handler-name.ts +15 -0
  145. package/src/expression-parser.ts +70 -1
  146. package/src/index.ts +33 -7
  147. package/src/ir-to-client-js/build-references.ts +69 -0
  148. package/src/ir-to-client-js/child-props-object.ts +106 -0
  149. package/src/ir-to-client-js/collect-elements.ts +30 -55
  150. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +6 -1
  151. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +29 -28
  152. package/src/ir-to-client-js/control-flow/shared.ts +20 -22
  153. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +5 -3
  154. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +2 -2
  155. package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +1 -1
  156. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +2 -2
  157. package/src/ir-to-client-js/control-flow/stringify/loop.ts +1 -1
  158. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +3 -3
  159. package/src/ir-to-client-js/html-template.ts +25 -8
  160. package/src/ir-to-client-js/imports.ts +1 -1
  161. package/src/ir-to-client-js/index.ts +53 -11
  162. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +31 -14
  163. package/src/ir-to-client-js/plan/static-array-child-init.ts +27 -18
  164. package/src/ir-to-client-js/prop-handling.ts +22 -3
  165. package/src/ir-to-client-js/stringify/static-array-child-init.ts +26 -10
  166. package/src/jsx-to-ir.ts +446 -37
  167. package/src/nullable-signal-attr.ts +246 -29
  168. package/src/prop-rewrite.ts +30 -6
  169. package/src/props-object-whole-read.ts +87 -0
  170. package/src/rich-type-refusal.ts +2 -1
  171. package/src/scope/binding-scope.ts +182 -18
  172. package/src/scope/lexical-scope-walk.ts +4 -3
  173. package/src/scope/root-prop-alias.ts +15 -8
  174. package/src/strip-types.ts +31 -3
  175. package/src/template-position-walk.ts +57 -28
  176. package/src/types.ts +87 -0
@@ -27,6 +27,9 @@ import {
27
27
  isSupported,
28
28
  isSupportedValue,
29
29
  emitParsedExpr,
30
+ primitivesAt,
31
+ EMPTY_OPERAND_TYPING,
32
+ BindingScope,
30
33
  type LoweringPlugin,
31
34
  type LoweringEmitter,
32
35
  type ParsedExprEmitter,
@@ -174,6 +177,7 @@ describe('emitParsedExpr dispatch with an emitter.lowering seam (#2843)', () =>
174
177
  throw new Error(`unexpected emitter.${name} call in this test`)
175
178
  }
176
179
  return {
180
+ primitives: primitivesAt(EMPTY_OPERAND_TYPING, BindingScope.EMPTY, {}),
177
181
  identifier: (name: string) => `ID(${name})`,
178
182
  literal: (v) => `LIT(${JSON.stringify(v)})`,
179
183
  call: (callee, args, emit) => `CALL(${emit(callee)}, ${args.map(emit).join(', ')})`,
@@ -0,0 +1,156 @@
1
+ /**
2
+ * A destructured prop's client read is `_p.m ?? <default>`, so a module
3
+ * declaration the default names (`{ m = DEFAULT }`) is a client read even
4
+ * when nothing else in the component names it. The reference graph used to
5
+ * miss it, and the emitted client module read an undeclared name — a
6
+ * `ReferenceError` whenever the prop was absent (a client-side mount).
7
+ *
8
+ * Declarations are read from the emitted client JS with the TypeScript AST.
9
+ */
10
+
11
+ import { describe, test, expect } from 'bun:test'
12
+ import ts from 'typescript'
13
+ import { compileJSX } from '../compiler'
14
+ import { TestAdapter } from '../adapters/test-adapter'
15
+
16
+ function clientJs(source: string): string {
17
+ const result = compileJSX(source, 'C.tsx', { adapter: new TestAdapter() })
18
+ expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
19
+ return result.files.find(f => f.type === 'clientJs')!.content
20
+ }
21
+
22
+ /** Every name the client module declares (variables and functions, any depth), in order. */
23
+ function declarations(js: string): string[] {
24
+ const sf = ts.createSourceFile('c.js', js, ts.ScriptTarget.Latest, true, ts.ScriptKind.JS)
25
+ const names: string[] = []
26
+ const visit = (node: ts.Node): void => {
27
+ if ((ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node)) && node.name && ts.isIdentifier(node.name)) {
28
+ names.push(node.name.text)
29
+ }
30
+ ts.forEachChild(node, visit)
31
+ }
32
+ visit(sf)
33
+ return names
34
+ }
35
+
36
+ const declaredNames = (js: string): Set<string> => new Set(declarations(js))
37
+ const declarationCount = (js: string, name: string): number => declarations(js).filter(n => n === name).length
38
+
39
+ describe('module declarations read only by a destructure default are emitted', () => {
40
+ test('a module const default read as text', () => {
41
+ const js = clientJs(`'use client'
42
+ const DEFAULT = 'm'
43
+ export function C({ m = DEFAULT }: { m?: string }) {
44
+ return <p>{m}</p>
45
+ }`)
46
+ expect(declaredNames(js).has('DEFAULT')).toBe(true)
47
+ })
48
+
49
+ test('a chain: the later prop reads the earlier one, whose default reads the const', () => {
50
+ const js = clientJs(`'use client'
51
+ const DEFAULT = 'm'
52
+ export function C({ a = DEFAULT, b = a }: { a?: string; b?: string }) {
53
+ return <p>{b}</p>
54
+ }`)
55
+ expect(declaredNames(js).has('DEFAULT')).toBe(true)
56
+ })
57
+
58
+ test('a member read of a module object const', () => {
59
+ const js = clientJs(`'use client'
60
+ const D = { label: 'm' }
61
+ export function C({ m = D.label }: { m?: string }) {
62
+ return <p title={m}>{m}</p>
63
+ }`)
64
+ expect(declaredNames(js).has('D')).toBe(true)
65
+ })
66
+
67
+ test('a module helper function called by the default', () => {
68
+ const js = clientJs(`'use client'
69
+ function fmt(s: string) { return s + '!' }
70
+ export function C({ m = fmt('x') }: { m?: string }) {
71
+ return <p>{m}</p>
72
+ }`)
73
+ expect(declaredNames(js).has('fmt')).toBe(true)
74
+ })
75
+
76
+ test('a signal seeded from the defaulted prop', () => {
77
+ const js = clientJs(`'use client'
78
+ import { createSignal } from '@barefootjs/client'
79
+ const START = 2
80
+ export function C({ start = START }: { start?: number }) {
81
+ const [c, setC] = createSignal(start)
82
+ return <button onClick={() => setC(c() + 1)}>{c()}</button>
83
+ }`)
84
+ expect(declaredNames(js).has('START')).toBe(true)
85
+ })
86
+
87
+ test('a body local of the same name does not get a second declaration', () => {
88
+ const js = clientJs(`'use client'
89
+ const LABEL = 'a'
90
+ export function C({ m = LABEL }: { m?: string }) {
91
+ const LABEL = 'b'
92
+ return <p title={LABEL}>{m}</p>
93
+ }`)
94
+ // Two `const LABEL` in one init body would be a SyntaxError for the module.
95
+ expect(declarationCount(js, 'LABEL')).toBeLessThanOrEqual(1)
96
+ })
97
+
98
+ test('the default of a prop the client never reads adds nothing', () => {
99
+ const js = clientJs(`'use client'
100
+ import { createSignal } from '@barefootjs/client'
101
+ const UNUSED = 'u'
102
+ export function C({ m = UNUSED }: { m?: string }) {
103
+ const [c, setC] = createSignal(0)
104
+ return <button onClick={() => setC(c() + 1)}>{c()}</button>
105
+ }`)
106
+ expect(declaredNames(js).has('UNUSED')).toBe(false)
107
+ })
108
+ })
109
+
110
+ describe('a destructure default names only its free references (#3792 review)', () => {
111
+ // A property key, a member name and a callback parameter inside the
112
+ // default are not reads of an outer binding; tracing them kept an
113
+ // unrelated module declaration in `initC` (here one reading `process`,
114
+ // which the browser lacks — a `ReferenceError` at mount).
115
+ test('an object literal key and a member name of the default', () => {
116
+ const js = clientJs(`'use client'
117
+ const label = process.env.SERVER_ONLY
118
+ export function C({ m = ({ label: 'm' }).label }: { m?: string }) {
119
+ return <p>{m}</p>
120
+ }`)
121
+ expect(declaredNames(js).has('label')).toBe(false)
122
+ expect(js).not.toContain('process')
123
+ })
124
+
125
+ test('a callback parameter of the default', () => {
126
+ const js = clientJs(`'use client'
127
+ const label = process.env.SERVER_ONLY
128
+ export function C({ m = ['m'].map(label => label)[0] }: { m?: string }) {
129
+ return <p>{m}</p>
130
+ }`)
131
+ expect(declaredNames(js).has('label')).toBe(false)
132
+ expect(js).not.toContain('process')
133
+ })
134
+
135
+ test('a genuine outer read beside a colliding key is still traced', () => {
136
+ const js = clientJs(`'use client'
137
+ const label = process.env.SERVER_ONLY
138
+ const D = { text: 'm' }
139
+ export function C({ m = ({ label: D.text }).label }: { m?: string }) {
140
+ return <p>{m}</p>
141
+ }`)
142
+ expect(declaredNames(js).has('D')).toBe(true)
143
+ expect(declaredNames(js).has('label')).toBe(false)
144
+ })
145
+
146
+ test('a chain through an earlier prop whose default has a colliding key', () => {
147
+ const js = clientJs(`'use client'
148
+ const label = process.env.SERVER_ONLY
149
+ const DEFAULT = 'm'
150
+ export function C({ a = ({ label: DEFAULT }).label, b = a }: { a?: string; b?: string }) {
151
+ return <p>{b}</p>
152
+ }`)
153
+ expect(declaredNames(js).has('DEFAULT')).toBe(true)
154
+ expect(declaredNames(js).has('label')).toBe(false)
155
+ })
156
+ })
@@ -115,7 +115,7 @@ describe('nested .map() index param referenced in key/text/attr (#2218)', () =>
115
115
  // `loop-index` source fixes this: the index is wired through the same
116
116
  // accessor `mapArray` already hands every row (#2859/#2860), and the
117
117
  // slot now gets a real update effect.
118
- expect(content).toContain(`createEffect(() => { __bfw_s0('s0', String(i())) })`)
118
+ expect(content).toContain(`createEffect(() => { __bfw_s0('s0', textOrNode(i())) })`)
119
119
  })
120
120
 
121
121
  test('index referenced in a reactive attribute expression is bound', () => {
@@ -347,7 +347,7 @@ describe('reactive attributes inside a nested .map() body (#135)', () => {
347
347
  // The innermost loop's per-item renderItem must emit BOTH a
348
348
  // reactive-text effect for `panel.text` and a reactive-attr effect
349
349
  // for `panel.cls` — the bug dropped only the former.
350
- expect(content).toMatch(/createEffect\(\(\) => \{[\s\S]*?__bfw_\w+\('s\d+', String\(panel\(\)\.text\)\)/)
350
+ expect(content).toMatch(/createEffect\(\(\) => \{[\s\S]*?__bfw_\w+\('s\d+', textOrNode\(panel\(\)\.text\)\)/)
351
351
  expect(content).toContain("setAttribute('class'")
352
352
  })
353
353
 
@@ -405,7 +405,7 @@ describe('reactive attributes inside a nested .map() body (#135)', () => {
405
405
  // effect missing (the exact regression here). `pi` reads the row's
406
406
  // live index accessor (#2859), so `labelAt(pi())` also stays correct
407
407
  // if this innermost loop's rows ever survive a same-key reorder.
408
- expect(content).toMatch(/createEffect\(\(\) => \{[\s\S]*?__bfw_\w+\('s\d+', String\(labelAt\(pi\(\)\)\)\)/)
408
+ expect(content).toMatch(/createEffect\(\(\) => \{[\s\S]*?__bfw_\w+\('s\d+', textOrNode\(labelAt\(pi\(\)\)\)\)/)
409
409
  expect(content).toContain("setAttribute('class'")
410
410
  })
411
411
  })
@@ -30,7 +30,7 @@ export function N(props: { groups: { name: string; tags: string[] }[] }) {
30
30
  expect(js).not.toContain('const __bfItem().name')
31
31
  expect(js).toContain("const name = t() + '!'")
32
32
  expect(js).toContain('String(name)')
33
- expect(js).toContain('String(__bfItem().name)')
33
+ expect(js).toContain('textOrNode(__bfItem().name)')
34
34
  })
35
35
 
36
36
  test('a row two loops deep still reads the outermost item through its accessor', () => {
@@ -51,7 +51,7 @@ export function Feed() {
51
51
  </article>)}</main>
52
52
  }
53
53
  `)
54
- expect(js).toContain('String(post().text + reply().text)')
54
+ expect(js).toContain('textOrNode(post().text + reply().text)')
55
55
  expect(js).not.toContain('String(post.text + reply().text)')
56
56
  })
57
57
  })
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The nil-reading rewrite (#3824 step 4a, `spec/js-primitive-semantics.md`
3
+ * "Nil reading is a tree rewrite"): an operand whose nil Phase 1 can read is
4
+ * made non-nil before the plan, by its consumer's coercion.
5
+ */
6
+ import { describe, test, expect } from 'bun:test'
7
+ import {
8
+ analyzeComponent,
9
+ buildMetadata,
10
+ collectOperandTyping,
11
+ rewriteNilReadings,
12
+ rewriteNilReadingsDeep,
13
+ parseExpression,
14
+ serializeParsedExpr,
15
+ stringifyParsedExpr,
16
+ BindingScope,
17
+ type ParsedExpr,
18
+ } from '../index'
19
+
20
+ const SRC = `export function C(props: { n?: number; nn: number | null; e?: number | null; s?: string; sn: string | null; c?: string | null; m: number; t: string; x: any }) { return <p>{props.m}</p> }`
21
+
22
+ function typing() {
23
+ const metadata = buildMetadata(analyzeComponent(SRC, 'c.tsx'))
24
+ return collectOperandTyping(metadata).at(BindingScope.forComponent(metadata.propsObjectName))
25
+ }
26
+
27
+ /** `e` with every operator node parenthesised, so the tests read the tree's grouping. */
28
+ function show(e: ParsedExpr): string {
29
+ switch (e.kind) {
30
+ case 'binary':
31
+ case 'logical':
32
+ return `(${show(e.left)} ${e.op} ${show(e.right)})`
33
+ case 'unary':
34
+ return `${e.op}${show(e.argument)}`
35
+ case 'literal':
36
+ return e.literalType === 'string' ? `'${e.value}'` : String(e.value)
37
+ case 'template-literal':
38
+ return '`' + e.parts.map(p => (p.type === 'string' ? p.value : `\${${show(p.expr)}}`)).join('') + '`'
39
+ default:
40
+ return stringifyParsedExpr(e)
41
+ }
42
+ }
43
+
44
+ const rewrite = (src: string): string => show(rewriteNilReadings(parseExpression(src), typing()))
45
+
46
+ describe('rewriteNilReadings', () => {
47
+ test('a numeric consumer reads an undefined nil as NaN and a null one as 0', () => {
48
+ expect(rewrite('props.n * 2')).toBe('((props.n ?? NaN) * 2)')
49
+ expect(rewrite('props.nn - props.m')).toBe('((props.nn ?? 0) - props.m)')
50
+ expect(rewrite('-props.n')).toBe('-(props.n ?? NaN)')
51
+ expect(rewrite('props.s < props.t')).toBe('((props.s ?? NaN) < props.t)')
52
+ })
53
+
54
+ test('a string consumer reads it as "undefined" / "null"', () => {
55
+ expect(rewrite("props.s + '!'")).toBe("((props.s ?? 'undefined') + '!')")
56
+ expect(rewrite("props.t + props.sn")).toBe("(props.t + (props.sn ?? 'null'))")
57
+ expect(rewrite('`${props.n}`')).toBe("`${(props.n ?? 'undefined')}`")
58
+ expect(rewrite("null + 'x'")).toBe("('null' + 'x')")
59
+ })
60
+
61
+ test('a string operand under + number is split on nil by the numeric row', () => {
62
+ expect(rewrite('props.s + 1')).toBe('((props.s ?? NaN) + 1)')
63
+ })
64
+
65
+ test('an either nil keeps the display reading, and a dynamic + is left alone', () => {
66
+ expect(rewrite('(props.e * 2)')).toBe('(props.e * 2)')
67
+ expect(rewrite("'btn ' + props.c")).toBe("('btn ' + (props.c ?? ''))")
68
+ expect(rewrite('(props.n + props.x)')).toBe('(props.n + props.x)')
69
+ })
70
+
71
+ test('the deep form enters callbacks and serializes NaN through Number', () => {
72
+ const deep = rewriteNilReadingsDeep(parseExpression('props.items.filter(i => i > props.n)'), typing())
73
+ const arrow = deep.kind === 'call' ? deep.args[0] : undefined
74
+ expect(arrow?.kind === 'arrow' ? show(arrow.body) : null).toBe('(i > (props.n ?? NaN))')
75
+ expect(serializeParsedExpr(rewriteNilReadings(parseExpression('props.n * 2'), typing()))).toContain('"name":"Number"')
76
+ })
77
+ })
@@ -1,4 +1,5 @@
1
1
  import { describe, test, expect } from 'bun:test'
2
+ import { arithmeticCoercionOrRefuse, refuseAmbiguousNilArithmetic } from '../adapters/ambiguous-nil-arithmetic'
2
3
  import { analyzeComponent } from '../analyzer'
3
4
  import { exprToString, parseExpression } from '../expression-parser'
4
5
  import {
@@ -11,6 +12,8 @@ import {
11
12
  collectAbsentPropSeedReads,
12
13
  collectNullableSignalGetters,
13
14
  collectNullishAttrContext,
15
+ isNeverNullishOperand,
16
+ nullablePropsYieldedBy,
14
17
  nullableSignalAttrGetter,
15
18
  } from '../nullable-signal-attr'
16
19
  import { BindingScope } from '../scope/binding-scope'
@@ -228,6 +231,30 @@ describe('arithmeticOperandCoercion (#3474)', () => {
228
231
  expect(unary('props.c')).toBeNull()
229
232
  })
230
233
 
234
+ test('unary plus passes no other operand and coerces like unary minus (#3824 step 3)', () => {
235
+ const ctx = ctxOf('props: { a: number | null; b?: number; c: number }')
236
+ const unary = (operand: string) => arithmeticOperandCoercion('+', parseExpression(operand), undefined, ctx)
237
+ expect(unary('props.a')).toBe('null')
238
+ expect(unary('props.b')).toBe('undefined')
239
+ expect(unary('props.c')).toBeNull()
240
+ })
241
+
242
+ test('a string or boolean relational operand that may only be absent reads NaN and keeps a present value (#3824 step 3)', () => {
243
+ const ctx = ctxOf('props: { s?: string; b?: boolean; t: string | null; c: string; u: string | undefined }')
244
+ for (const op of ['<', '<=', '>', '>=']) {
245
+ expect(coercion(ctx, op, 'props.s', '1')).toBe('undefined-keep')
246
+ expect(coercion(ctx, op, 'props.s', "'a'")).toBe('undefined-keep')
247
+ expect(coercion(ctx, op, 'props.b', '1')).toBe('undefined-keep')
248
+ expect(coercion(ctx, op, 'props.u', '1')).toBe('undefined-keep')
249
+ // A `null` reading is the helper's own; a required prop has no nil.
250
+ expect(coercion(ctx, op, 'props.t', '1')).toBeNull()
251
+ expect(coercion(ctx, op, 'props.c', '1')).toBeNull()
252
+ }
253
+ // Arithmetic over a string prop is not a relational: left as it is.
254
+ expect(coercion(ctx, '*', 'props.s', '2')).toBeNull()
255
+ expect(arithmeticOperandCoercion('<', parseExpression('props.s'), parseExpression('1'), ctx, n => n === 'props')).toBeNull()
256
+ })
257
+
231
258
  test('an absent-only prop is not certainly undefined: arithmeticOperandIsUndefined stays false', () => {
232
259
  const ctx = ctxOf('props: { b?: number }')
233
260
  expect(arithmeticOperandIsUndefined(parseExpression('props.b'), ctx)).toBe(false)
@@ -273,6 +300,7 @@ describe('arithmeticOperandNilIsAmbiguous (#3700)', () => {
273
300
  for (const op of ['-', '*', '/', '%', '**']) expect(ambiguous(ctx, op, 'props.n', 'x')).toBe(true)
274
301
  expect(ambiguous(ctx, '+', 'props.n', '1')).toBe(true)
275
302
  expect(ambiguous(ctx, '-', 'props.n')).toBe(true)
303
+ expect(ambiguous(ctx, '+', 'props.n')).toBe(true)
276
304
  // `+` against a non-number may concatenate: no `ToNumber`, no ambiguity.
277
305
  expect(ambiguous(ctx, '+', 'props.n', "'px'")).toBe(false)
278
306
  }
@@ -281,6 +309,34 @@ describe('arithmeticOperandNilIsAmbiguous (#3700)', () => {
281
309
  expect(ambiguous(destructured, '*', 'alias', '2')).toBe(true)
282
310
  })
283
311
 
312
+ test('a relational operand is a numeric consumer too (#3824 step 3)', () => {
313
+ const ctx = ctxOf('props: { n?: number | null; a: number | null; b?: number }')
314
+ for (const op of ['<', '<=', '>', '>=']) {
315
+ expect(ambiguous(ctx, op, 'props.n', '1')).toBe(true)
316
+ expect(ambiguous(ctx, op, 'props.n', "'x'")).toBe(true)
317
+ expect(ambiguous(ctx, op, 'props.a', '1')).toBe(false)
318
+ expect(ambiguous(ctx, op, 'props.b', '1')).toBe(false)
319
+ }
320
+ // The spelling keeps the helper's null reading for the refused operand.
321
+ expect(arithmeticOperandCoercion('<', parseExpression('props.n'), parseExpression('1'), ctx)).toBeNull()
322
+ expect(arithmeticOperandCoercion('<', parseExpression('props.b'), parseExpression('1'), ctx)).toBe('undefined')
323
+ expect(arithmeticOperandCoercion('<', parseExpression('props.a'), parseExpression('1'), ctx)).toBeNull()
324
+ })
325
+
326
+ test('a string or boolean prop admitting both nils is ambiguous under a comparison only (#3824 step 3)', () => {
327
+ const ctx = ctxOf('props: { s?: string | null; b?: boolean | null; t?: string; m: string | null }', 'const id = createMemo(() => props.s)')
328
+ for (const op of ['<', '<=', '>', '>=']) {
329
+ expect(ambiguous(ctx, op, 'props.s', '1')).toBe(true)
330
+ expect(ambiguous(ctx, op, 'props.s', "'a'")).toBe(true)
331
+ expect(ambiguous(ctx, op, 'props.b', '1')).toBe(true)
332
+ expect(ambiguous(ctx, op, 'id()', '1')).toBe(true)
333
+ expect(ambiguous(ctx, op, 'props.t', '1')).toBe(false)
334
+ expect(ambiguous(ctx, op, 'props.m', '1')).toBe(false)
335
+ }
336
+ expect(ambiguous(ctx, '*', 'props.s', '2')).toBe(false)
337
+ expect(ambiguous(ctx, '+', 'props.s')).toBe(false)
338
+ })
339
+
284
340
  test('a prop with one nil reading, a defaulted one and a shadowed one are not ambiguous', () => {
285
341
  const ctx = ctxOf('props: { a: number | null; b?: number; c: number }')
286
342
  for (const operand of ['props.a', 'props.b', 'props.c']) expect(ambiguous(ctx, '*', operand, '2')).toBe(false)
@@ -318,6 +374,17 @@ describe('ambiguousNilArithmeticOperands (#3700)', () => {
318
374
  expect(found("(-n > 1 ? `a${n + 1}` : 'b')")).toEqual(['n', 'n'])
319
375
  })
320
376
 
377
+ test('finds a unary plus operand (#3824 step 3)', () => {
378
+ expect(found('+n')).toEqual(['n'])
379
+ expect(found('+n > 1 ? 1 : 0')).toEqual(['n'])
380
+ })
381
+
382
+ test('finds a relational operand, in a predicate and at the top level', () => {
383
+ expect(found('items.filter(i => i < n).length')).toEqual(['n'])
384
+ expect(found('n >= 1')).toEqual(['n'])
385
+ expect(found('items.filter(n => n < 1).length')).toEqual([])
386
+ })
387
+
321
388
  test('an arrow param or an enclosing binding of the same name shadows the prop', () => {
322
389
  expect(found("items.filter(n => n * 2 > 1).length")).toEqual([])
323
390
  expect(found("items.map(i => items.filter(n => n > i).length * n)")).toEqual(['n'])
@@ -326,3 +393,70 @@ describe('ambiguousNilArithmeticOperands (#3700)', () => {
326
393
  expect(found('items.filter(n => n > 1).length * n')).toEqual(['n'])
327
394
  })
328
395
  })
396
+
397
+ describe('a prop that can be absent, and an operand that is never nullish', () => {
398
+ function irOf(signature: string): ComponentIR {
399
+ const source = `
400
+ export function C(${signature}) {
401
+ return <p>x</p>
402
+ }
403
+ `
404
+ return { metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR
405
+ }
406
+ const mayBeNullish = (ir: ComponentIR, src: string, shadowed: (n: string) => boolean = () => false) =>
407
+ attrValueMayBeNullish(parseExpression(src), collectNullishAttrContext(ir), shadowed)
408
+
409
+ test('an && / ternary over an absent-able prop may be nullish, in both props forms', () => {
410
+ const object = irOf('props: { on?: boolean; label: string | undefined; n: number; d?: string }')
411
+ expect(mayBeNullish(object, "props.on && 'y'")).toBe(true)
412
+ expect(mayBeNullish(object, "props.n > 0 ? props.label : 'x'")).toBe(true)
413
+ expect(mayBeNullish(object, "props.n && 'y'")).toBe(false)
414
+ expect(mayBeNullish(object, "props.on ?? 'y'")).toBe(false)
415
+ expect(mayBeNullish(object, "props.on && 'y'", n => n === 'props')).toBe(false)
416
+ const destructured = irOf("{ on, d = 'z' }: { on?: boolean; d?: string }")
417
+ expect(mayBeNullish(destructured, "on && 'y'")).toBe(true)
418
+ expect(mayBeNullish(destructured, "on && 'y'", n => n === 'on')).toBe(false)
419
+ expect(mayBeNullish(destructured, "d && 'y'")).toBe(false)
420
+ })
421
+
422
+ test('nullablePropsYieldedBy names the props a value can be read whole from', () => {
423
+ const ir = irOf('props: { on?: boolean; label?: string; n?: number }')
424
+ const nullable = collectNullishAttrContext(ir).nullableProps!
425
+ expect([...nullablePropsYieldedBy(parseExpression("props.on && (props.n > 0 ? props.label : 'x')"), nullable)].sort()).toEqual(['label', 'on'])
426
+ expect([...nullablePropsYieldedBy(parseExpression("props.on ?? props.label"), nullable)]).toEqual(['label'])
427
+ })
428
+
429
+ test('isNeverNullishOperand: a comparison and a required scalar prop, not an optional or shadowed one', () => {
430
+ const object = irOf("props: { flag: boolean; s: string; n: number; tone: 'a' | 'b'; opt?: boolean; u: string | undefined; list: string[] }").metadata
431
+ const never = (src: string, isBound: (n: string) => boolean = () => false) =>
432
+ isNeverNullishOperand(parseExpression(src)!, object, isBound)
433
+ for (const src of ['props.flag', 'props.s', 'props.n', 'props.tone', 'props.n > 1', '!props.opt']) expect(never(src)).toBe(true)
434
+ for (const src of ['props.opt', 'props.u', 'props.list', 'flag']) expect(never(src)).toBe(false)
435
+ expect(never('props.flag', n => n === 'props')).toBe(false)
436
+ const destructured = irOf('{ flag, opt }: { flag: boolean; opt?: boolean }').metadata
437
+ expect(isNeverNullishOperand(parseExpression('flag')!, destructured, () => false)).toBe(true)
438
+ expect(isNeverNullishOperand(parseExpression('flag')!, destructured, n => n === 'flag')).toBe(false)
439
+ expect(isNeverNullishOperand(parseExpression('opt')!, destructured, () => false)).toBe(false)
440
+ })
441
+ })
442
+
443
+ describe('the BF101 of an ambiguous nil names the prop family (#3824 step 3)', () => {
444
+ const ctx = collectNullishAttrContext({
445
+ metadata: analyzeComponent(
446
+ `export function C(props: { n?: number | null; s?: string | null; b?: boolean | null }) { return <p>x</p> }`,
447
+ 'C.tsx',
448
+ ),
449
+ } as unknown as ComponentIR)
450
+
451
+ test('a numeric operand keeps the arithmetic message; a string or boolean one names its type', () => {
452
+ const sink = { errors: [] as import('../types').CompilerError[], componentName: 'C' }
453
+ arithmeticCoercionOrRefuse('*', parseExpression('props.n'), parseExpression('2'), ctx, () => false, sink)
454
+ arithmeticCoercionOrRefuse('<', parseExpression('props.s'), parseExpression('1'), ctx, () => false, sink)
455
+ refuseAmbiguousNilArithmetic(parseExpression('props.b >= 1'), ctx, BindingScope.EMPTY, sink)
456
+ expect(sink.errors.map(e => e.code)).toEqual(['BF101', 'BF101', 'BF101'])
457
+ expect(sink.errors[0]!.message).toStartWith('Arithmetic over `props.n` reads a number prop declared both optional and nullable (`?: number | null`).')
458
+ expect(sink.errors[1]!.message).toStartWith('A comparison over `props.s` reads a string prop declared both optional and nullable (`?: string | null`).')
459
+ expect(sink.errors[2]!.message).toStartWith('A comparison over `props.b` reads a boolean prop')
460
+ expect(sink.errors[1]!.suggestion?.message).toContain('`?: string`')
461
+ })
462
+ })