@barefootjs/jsx 0.39.7 → 0.39.9

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 (192) hide show
  1. package/dist/adapters/callback-method.d.ts +36 -7
  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 +153 -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/loop-plan.d.ts +133 -9
  12. package/dist/adapters/loop-plan.d.ts.map +1 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts +44 -0
  14. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  15. package/dist/adapters/style-object.d.ts +33 -0
  16. package/dist/adapters/style-object.d.ts.map +1 -0
  17. package/dist/analyzer.d.ts.map +1 -1
  18. package/dist/assignment-target.d.ts +26 -0
  19. package/dist/assignment-target.d.ts.map +1 -0
  20. package/dist/children-nullish.d.ts +22 -0
  21. package/dist/children-nullish.d.ts.map +1 -0
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/expression-parser.d.ts +9 -19
  25. package/dist/expression-parser.d.ts.map +1 -1
  26. package/dist/free-refs.d.ts +6 -0
  27. package/dist/free-refs.d.ts.map +1 -1
  28. package/dist/index.d.ts +17 -14
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +15040 -13899
  31. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  34. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  36. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  38. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  40. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  42. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  45. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  47. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  49. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  51. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  54. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  56. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/imports.d.ts +23 -2
  58. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/phases/props-extraction.d.ts +6 -3
  60. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  67. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  68. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  70. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  72. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  73. package/dist/ir-to-client-js/types.d.ts +3 -3
  74. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  75. package/dist/ir-to-client-js/utils.d.ts +2 -11
  76. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  77. package/dist/jsx-to-ir.d.ts.map +1 -1
  78. package/dist/nullable-signal-attr.d.ts +40 -10
  79. package/dist/nullable-signal-attr.d.ts.map +1 -1
  80. package/dist/prop-rewrite.d.ts +35 -8
  81. package/dist/prop-rewrite.d.ts.map +1 -1
  82. package/dist/props-binding.d.ts +66 -1
  83. package/dist/props-binding.d.ts.map +1 -1
  84. package/dist/scanner/js-scanner.d.ts.map +1 -1
  85. package/dist/scanner/js-scanner.js +30 -2
  86. package/dist/scope/binding-scope.d.ts +30 -2
  87. package/dist/scope/binding-scope.d.ts.map +1 -1
  88. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  89. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  90. package/dist/signal-prop-name-collision.d.ts +6 -5
  91. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  92. package/dist/ssr-defaults.d.ts +28 -0
  93. package/dist/ssr-defaults.d.ts.map +1 -1
  94. package/dist/ssr-seed-plan.d.ts +39 -14
  95. package/dist/ssr-seed-plan.d.ts.map +1 -1
  96. package/dist/types.d.ts +133 -19
  97. package/dist/types.d.ts.map +1 -1
  98. package/dist/value-references.d.ts +21 -0
  99. package/dist/value-references.d.ts.map +1 -1
  100. package/package.json +2 -2
  101. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  102. package/src/__tests__/adapter-output.test.ts +5 -3
  103. package/src/__tests__/analyzer.test.ts +33 -0
  104. package/src/__tests__/arithmetic-lowering.test.ts +48 -0
  105. package/src/__tests__/binding-scope.test.ts +29 -0
  106. package/src/__tests__/children-read.test.ts +226 -0
  107. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  108. package/src/__tests__/component-props.test.ts +68 -1
  109. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  110. package/src/__tests__/create-query.test.ts +1 -1
  111. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  112. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  113. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  114. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  115. package/src/__tests__/expression-parser.test.ts +1 -44
  116. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  117. package/src/__tests__/loop-plan.test.ts +131 -1
  118. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  119. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  120. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  121. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  122. package/src/__tests__/props-alias-const.test.ts +60 -1
  123. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  124. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  125. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  126. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  127. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  128. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  131. package/src/__tests__/style-object-plan.test.ts +54 -0
  132. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/callback-method.ts +48 -10
  135. package/src/adapters/component-props.ts +130 -12
  136. package/src/adapters/dsl-template-adapter.ts +259 -0
  137. package/src/adapters/jsx-adapter.ts +12 -6
  138. package/src/adapters/literal-value.ts +2 -2
  139. package/src/adapters/loop-plan.ts +201 -13
  140. package/src/adapters/parsed-expr-emitter.ts +67 -0
  141. package/src/adapters/style-object.ts +61 -0
  142. package/src/analyzer.ts +396 -16
  143. package/src/assignment-target.ts +79 -0
  144. package/src/children-nullish.ts +33 -0
  145. package/src/debug.ts +2 -2
  146. package/src/errors.ts +23 -0
  147. package/src/expression-parser.ts +56 -53
  148. package/src/free-refs.ts +28 -17
  149. package/src/index.ts +31 -10
  150. package/src/ir-to-client-js/compute-inlinability.ts +35 -5
  151. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  152. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  153. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  154. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  155. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  156. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  157. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  159. package/src/ir-to-client-js/csr-substitute.ts +82 -24
  160. package/src/ir-to-client-js/emit-reactive.ts +3 -3
  161. package/src/ir-to-client-js/emit-registration.ts +34 -58
  162. package/src/ir-to-client-js/generate-init.ts +17 -1
  163. package/src/ir-to-client-js/html-template.ts +48 -57
  164. package/src/ir-to-client-js/identifiers.ts +75 -24
  165. package/src/ir-to-client-js/imports.ts +56 -19
  166. package/src/ir-to-client-js/index.ts +2 -1
  167. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  168. package/src/ir-to-client-js/phases/props-extraction.ts +39 -17
  169. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  170. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  171. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  172. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  173. package/src/ir-to-client-js/reactivity.ts +2 -2
  174. package/src/ir-to-client-js/rewrite-destructured-props.ts +22 -5
  175. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  176. package/src/ir-to-client-js/safe-html.ts +29 -35
  177. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  178. package/src/ir-to-client-js/types.ts +3 -2
  179. package/src/ir-to-client-js/utils.ts +42 -122
  180. package/src/jsx-to-ir.ts +310 -90
  181. package/src/nullable-signal-attr.ts +149 -33
  182. package/src/prop-rewrite.ts +72 -72
  183. package/src/props-binding.ts +90 -3
  184. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  185. package/src/scanner/js-scanner.ts +64 -4
  186. package/src/scope/binding-scope.ts +34 -3
  187. package/src/scope/lexical-scope-walk.ts +167 -0
  188. package/src/signal-prop-name-collision.ts +50 -24
  189. package/src/ssr-defaults.ts +47 -20
  190. package/src/ssr-seed-plan.ts +103 -23
  191. package/src/types.ts +140 -20
  192. package/src/value-references.ts +132 -0
@@ -0,0 +1,430 @@
1
+ /**
2
+ * No substitution rewrites a written binding.
3
+ *
4
+ * The client JS replaces reads of component bindings with expressions that
5
+ * produce their value: a destructured prop with its live read
6
+ * `(_p.start ?? 0)`, an inlinable local with its declared value `(0)` in the
7
+ * client template. A write position cannot take such a replacement:
8
+ * `++start` became `++(_p.start ?? 0)` and `{++nextId}` became `++(0)`, a
9
+ * SyntaxError that broke the whole client module.
10
+ *
11
+ * - A destructured prop the component writes anywhere (`ParamInfo.reassigned`)
12
+ * is a local: init declares `let start = _p.start ?? 0` once and keeps
13
+ * every reference to it.
14
+ * - A client component's markup that writes a binding while it renders
15
+ * (`{++nextId}`) is refused with BF065: no client path could keep the
16
+ * written value. A write in an event handler leaves the declared value
17
+ * inlinable, since render sees that value.
18
+ * - A client-template expression that writes a binding (a memo body, a
19
+ * const whose initializer writes) is left to init, on every template
20
+ * path: a component that writes a binding never takes the static one.
21
+ */
22
+
23
+ import { describe, test, expect } from 'bun:test'
24
+ import ts from 'typescript'
25
+ import { compileJSX } from '../compiler'
26
+ import { TestAdapter } from '../adapters/test-adapter'
27
+ import { isAssignmentTargetIdentifier } from '../assignment-target'
28
+ import { analyzeComponent } from '../analyzer'
29
+ import { keepsDeclaredValue } from '../props-binding'
30
+
31
+ const adapter = new TestAdapter()
32
+ const transpiler = new Bun.Transpiler({ loader: 'js' })
33
+
34
+ function clientJs(body: string, params = '', extra = ''): string {
35
+ const source = `
36
+ 'use client'
37
+ import { createSignal, createMemo } from '@barefootjs/client'
38
+ ${extra}
39
+ export function C(${params}) {
40
+ ${body}
41
+ }
42
+ `
43
+ const result = compileJSX(source, 'C.tsx', { adapter })
44
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
45
+ const js = result.files.find(f => f.type === 'clientJs')!.content
46
+ expect(() => transpiler.transformSync(js)).not.toThrow()
47
+ return js
48
+ }
49
+
50
+ function templateOf(js: string): string {
51
+ const line = js.split('\n').find(l => l.includes("hydrate('C'"))
52
+ expect(line).toBeDefined()
53
+ return line!
54
+ }
55
+
56
+
57
+ /** The diagnostics' codes for `body` compiled as component `C`. */
58
+ function codesOf(body: string, params = '', extra = '', directive = "'use client'"): string[] {
59
+ const source = `
60
+ ${directive}
61
+ import { createSignal } from '@barefootjs/client'
62
+ ${extra}
63
+ export function C(${params}) {
64
+ ${body}
65
+ }
66
+ `
67
+ return compileJSX(source, 'C.tsx', { adapter }).errors.map(e => e.code)
68
+ }
69
+
70
+ /**
71
+ * Run the registration template of `C` (`template: (_p) => \`…\``) with
72
+ * `props`, the runtime's escape helpers stubbed as plain string coercion.
73
+ */
74
+ function runTemplate(js: string, props: Record<string, unknown>): string {
75
+ const line = templateOf(js)
76
+ const start = line.indexOf('template: ') + 'template: '.length
77
+ const end = line.lastIndexOf(' })')
78
+ const helperNames = (js.match(/^import \{ ([^}]+) \} from '@barefootjs\/client\/runtime'/m)?.[1] ?? '')
79
+ .split(',').map(n => n.trim()).filter(Boolean)
80
+ const stub = (v: unknown) => (v == null ? '' : String(v))
81
+ const template = new Function(...helperNames, `return ${line.slice(start, end)}`)(...helperNames.map(() => stub))
82
+ return template(props)
83
+ }
84
+
85
+ describe('a destructured prop the component writes is an init local', () => {
86
+ const P = '{ start = 0 }: { start?: number }'
87
+
88
+ test('a prefix update in an inline handler', () => {
89
+ const js = clientJs(
90
+ `const [items, setItems] = createSignal<number[]>([])
91
+ return <div><button onClick={() => setItems([...items(), ++start])}>add</button><p>{items().join(',')}</p></div>`,
92
+ P,
93
+ )
94
+ expect(js).toContain('let start = _p.start ?? 0')
95
+ expect(js).toContain('++start')
96
+ expect(js).not.toContain('++(_p.start')
97
+ })
98
+
99
+ test('a compound assignment in a handler const, with the prop also read in markup', () => {
100
+ const js = clientJs(
101
+ `const [items, setItems] = createSignal<number[]>([])
102
+ const add = () => { start += 1; setItems([...items(), start]) }
103
+ return <div><button onClick={add}>add</button><p>{start}</p><p>{items().join(',')}</p></div>`,
104
+ P,
105
+ )
106
+ expect(js).toContain('const add = () => { start += 1; setItems([...items(), start]) }')
107
+ // Until a handler runs, the binding holds the prop: the template reads it.
108
+ expect(templateOf(js)).toContain('(_p.start ?? 0)')
109
+ })
110
+
111
+ test('a top-level reassignment', () => {
112
+ const js = clientJs(`start = start + 1\n return <p>{start}</p>`, P)
113
+ expect(js).toContain('let start = _p.start ?? 0')
114
+ expect(js).toContain('start = start + 1')
115
+ })
116
+
117
+ test('a destructuring assignment and a for-in head', () => {
118
+ const js = clientJs(
119
+ `const [n, setN] = createSignal(0)
120
+ return <div><button onClick={() => { [a, b] = [b, a]; for (k in { x: 1 }) {} setN(a) }}>go</button><p>{n()}</p></div>`,
121
+ '{ a = 1, b = 2, k = "" }: { a?: number; b?: number; k?: string }',
122
+ )
123
+ expect(js).toContain('[a, b] = [b, a]')
124
+ expect(js).toContain('for (k in')
125
+ expect(js).toContain('let a = _p.a ?? 1')
126
+ })
127
+
128
+ test('a prop without a default no longer writes the props object', () => {
129
+ const js = clientJs(
130
+ `const [items, setItems] = createSignal<number[]>([])
131
+ return <div><button onClick={() => setItems([...items(), ++start])}>add</button><p>{items().join(',')}</p></div>`,
132
+ '{ start }: { start: number }',
133
+ )
134
+ expect(js).toContain('let start = _p.start')
135
+ expect(js).not.toContain('++_p.start')
136
+ })
137
+
138
+ test('a renamed prop declares its local from the caller-facing key', () => {
139
+ const js = clientJs(
140
+ `const [items, setItems] = createSignal<number[]>([])
141
+ return <div><button onClick={() => setItems([...items(), ++s])}>add</button><p>{items().join(',')}</p></div>`,
142
+ '{ start: s = 0 }: { start?: number }',
143
+ )
144
+ expect(js).toContain('let s = _p.start ?? 0')
145
+ expect(js).toContain('++s')
146
+ })
147
+
148
+ test('a handler-local binding of the same name is not the prop', () => {
149
+ const js = clientJs(
150
+ `const [n, setN] = createSignal(0)
151
+ const add = () => { let start = 1; start++; setN(start) }
152
+ return <div><button onClick={add}>{start}</button><p>{n()}</p></div>`,
153
+ P,
154
+ )
155
+ expect(js).not.toContain('let start = _p.start')
156
+ expect(js).toContain('let start = 1; start++')
157
+ })
158
+
159
+ })
160
+
161
+ describe('a `for (let …)` head shadows a prop of the same name', () => {
162
+ test('the loop variable is not rewritten to the prop', () => {
163
+ const js = clientJs(
164
+ `const [n, setN] = createSignal(0)
165
+ const add = () => { let t = 0; for (let i = 0; i < 3; i++) t += i; setN(t + i) }
166
+ return <div><button onClick={add}>go</button><p>{n()}</p></div>`,
167
+ '{ i = 5 }: { i?: number }',
168
+ )
169
+ expect(js).toContain('for (let i = 0; i < 3; i++) t += i; setN(t + (_p.i ?? 5))')
170
+ })
171
+ })
172
+
173
+ describe('a written local in the client template', () => {
174
+ test('a write in an event handler keeps the declared value inlined', () => {
175
+ const js = clientJs(
176
+ `const [items, setItems] = createSignal<number[]>([])
177
+ let nextId = 0
178
+ const add = () => setItems([...items(), ++nextId])
179
+ return <div><button onClick={add}>add</button><p>{nextId}</p><p>{items().join(',')}</p></div>`,
180
+ )
181
+ expect(js).toContain('const add = () => setItems([...items(), ++nextId])')
182
+ expect(templateOf(js)).toContain('<p>${escapeText((0))}</p>')
183
+ })
184
+
185
+ test("a memo body's own loop variable and block locals are not binding writes", () => {
186
+ const js = clientJs(
187
+ `const [n, setN] = createSignal(3)
188
+ const total = createMemo(() => { let t = 0; for (let i = 0; i < n(); i++) { let d = i; d++; t += d } return t })
189
+ return <div><button onClick={() => setN(n() + 1)}>add</button><p>{total()}</p></div>`,
190
+ )
191
+ expect(templateOf(js)).toContain('for (let i = 0; i < (3); i++)')
192
+ })
193
+
194
+ test('a memo body that writes a local is left to init', () => {
195
+ const js = clientJs(
196
+ `const [n, setN] = createSignal(0)
197
+ let calls = 0
198
+ const doubled = createMemo(() => { calls++; return n() * 2 })
199
+ return <div><button onClick={() => setN(n() + 1)}>add</button><p>{doubled()}</p></div>`,
200
+ )
201
+ expect(js).toContain('calls++')
202
+ expect(templateOf(js)).not.toContain('(0)++')
203
+ })
204
+
205
+ })
206
+
207
+ describe('every template path leaves a write to init', () => {
208
+ test('a stateless component writing a prop in a handler renders the prop from its template', () => {
209
+ const js = clientJs(`return <button onClick={() => start++}>{start}</button>`, '{ start = 0 }: { start?: number }')
210
+ expect(js).toContain('let start = _p.start ?? 0')
211
+ expect(runTemplate(js, { start: 5 })).toContain('5')
212
+ expect(runTemplate(js, {})).toContain('0')
213
+ })
214
+
215
+ test('a const whose initializer writes a prop is not inlined into a stateless template', () => {
216
+ const js = clientJs(`const label = ++start\n return <p>{label}:{start}</p>`, '{ start = 0 }: { start?: number }')
217
+ expect(js).toContain('const label = ++start')
218
+ expect(templateOf(js)).not.toContain('++start')
219
+ expect(() => runTemplate(js, { start: 5 })).not.toThrow()
220
+ // init runs the write once and repaints the slot.
221
+ expect(js).toContain('const __val = label')
222
+ })
223
+ })
224
+
225
+ describe('BF065: a client component markup that writes a binding while it renders', () => {
226
+ const CHILD = 'function Show(props: { get: () => number }) { return <i>{props.get()}</i> }'
227
+
228
+ test('is refused for a local, a prop and a counter a `.map()` row increments', () => {
229
+ expect(codesOf(`let id = 0\n return <p>{++id}</p>`)).toContain('BF065')
230
+ expect(codesOf(`let id = 0\n return <p>{id++}</p>`)).toContain('BF065')
231
+ expect(codesOf(`return <p>{++start}</p>`, '{ start = 0 }: { start?: number }')).toContain('BF065')
232
+ expect(codesOf(`let count = 0\n return <ul>{['a', 'b'].map(i => <li key={i}>{++count}</li>)}</ul>`)).toContain('BF065')
233
+ expect(codesOf(`let count = 0\n return <ul>{['a', 'b'].map(i => { count++; return <li key={i}>{count}</li> })}</ul>`)).toContain('BF065')
234
+ expect(codesOf(`let id = 0\n return <p>{(() => ++id)()}</p>`)).toContain('BF065')
235
+ })
236
+
237
+ test('is not raised for a callback the markup hands on, or a top-level statement', () => {
238
+ expect(codesOf(`let id = 0\n return <button onClick={() => { id++ }}>{id}</button>`)).not.toContain('BF065')
239
+ expect(codesOf(`let id = 0\n return <div><Show get={() => ++id} /></div>`, '', CHILD)).not.toContain('BF065')
240
+ expect(codesOf(
241
+ `let api = null\n return <Ctx.Provider value={{ setApi: (a: unknown) => { api = a } }}><i /></Ctx.Provider>`,
242
+ '',
243
+ "import { createContext } from '@barefootjs/client'\n const Ctx = createContext<unknown>(null)",
244
+ )).not.toContain('BF065')
245
+ expect(codesOf(`let id = 0\n id++\n return <p>{id}</p>`)).not.toContain('BF065')
246
+ })
247
+
248
+ test('is refused for a callback any call in markup may run in place', () => {
249
+ // `Array.from`'s mapper runs while the markup renders: `<b>{id}</b>` reads 2, not 0.
250
+ expect(codesOf(`let id = 0\n return <div><p>{Array.from([1, 2], () => ++id).join(',')}</p><b>{id}</b></div>`)).toContain('BF065')
251
+ expect(codesOf(`let id = 0\n return <p>{'a-b'.replace(/-/g, () => String(++id))}</p>`)).toContain('BF065')
252
+ // A computed child-prop value is evaluated while rendering too.
253
+ expect(codesOf(
254
+ `let id = 0\n return <div><List items={Array.from([1, 2], () => ++id)} /></div>`,
255
+ '',
256
+ 'function List(props: { items: number[] }) { return <i>{props.items.length}</i> }',
257
+ )).toContain('BF065')
258
+ expect(codesOf(`let id = 0\n return <p>{(() => ++id)()}</p>`)).toContain('BF065')
259
+ })
260
+
261
+ test('is refused for a write an event attribute evaluates eagerly', () => {
262
+ // The IIFE and the comma operand run while the attribute renders, not on click.
263
+ expect(codesOf(`let id = 0\n return <div><button onClick={(() => { ++id; return () => {} })()}>x</button><b>{id}</b></div>`)).toContain('BF065')
264
+ expect(codesOf(`let id = 0\n return <div><button onClick={(++id, () => {})}>x</button><b>{id}</b></div>`)).toContain('BF065')
265
+ expect(codesOf(`let id = 0\n return <div><button onClick={((f: () => void) => f)(() => { ++id })}>{id}</button></div>`)).not.toContain('BF065')
266
+ })
267
+
268
+ test('is refused for a getter or an iterator a spread runs while the markup renders, not for what a spread copies', () => {
269
+ const SHOW_VALUE = 'function Show(props: { value: { x: number } }) { return <i>{props.value.x}</i> }'
270
+ const NEXT = 'function Show(props: { value: object }) { return <i>{String(Object.keys(props.value).length)}</i> }'
271
+ // The object spread runs the getter while rendering: `<b>{id}</b>` reads 1.
272
+ expect(codesOf(`let id = 0\n return <div><Show value={{ ...{ get x() { return ++id } } }} /><b>{id}</b></div>`, '', SHOW_VALUE)).toContain('BF065')
273
+ expect(codesOf(`let id = 0\n return <p>{[...{ *[Symbol.iterator]() { yield ++id } }].join(',')}</p>`)).toContain('BF065')
274
+ // A spread copies a data callback, a method and an array literal's elements: handed on.
275
+ expect(codesOf(`let id = 0\n return <div><Show value={{ ...{ next: () => ++id } }} /></div>`, '', NEXT)).not.toContain('BF065')
276
+ expect(codesOf(`let id = 0\n return <div><Show value={{ ...{ next() { return ++id } } }} /></div>`, '', NEXT)).not.toContain('BF065')
277
+ expect(codesOf(`let id = 0\n return <div><Show value={{ ...{ set x(v: number) { id = v } } }} /></div>`, '', NEXT)).not.toContain('BF065')
278
+ expect(codesOf(
279
+ `let id = 0\n return <div><Fns fns={[...[() => ++id]]} /></div>`,
280
+ '',
281
+ 'function Fns(props: { fns: Array<() => number> }) { return <i>{props.fns.length}</i> }',
282
+ )).not.toContain('BF065')
283
+ // An object literal with a getter or a method passed directly is handed on.
284
+ expect(codesOf(`let id = 0\n return <div><Show value={{ get x() { return ++id } }} /></div>`, '', SHOW_VALUE)).not.toContain('BF065')
285
+ expect(codesOf(
286
+ `let api = null\n return <Ctx.Provider value={{ setApi(a: unknown) { api = a }, set current(a: unknown) { api = a } }}><i /></Ctx.Provider>`,
287
+ '',
288
+ "import { createContext } from '@barefootjs/client'\n const Ctx = createContext<unknown>(null)",
289
+ )).not.toContain('BF065')
290
+ })
291
+
292
+ test('is not raised for a callback a conditional selects as a child prop, and the closure keeps working', () => {
293
+ const CHILD_GET = 'function Show(props: { get: () => number }) { return <i>{props.get()}</i> }'
294
+ const body = `const [n, setN] = createSignal(0)
295
+ const enabled = true
296
+ let id = 0
297
+ return <div><button onClick={() => setN(n() + 1)}>add</button><p>{n()}</p><Show get={enabled ? () => ++id : () => id} /></div>`
298
+ expect(codesOf(body, '', CHILD_GET)).not.toContain('BF065')
299
+ const js = clientJs(body, '', CHILD_GET)
300
+ expect(js).toContain('let id = 0')
301
+ expect(templateOf(js)).toContain('data-bf-ph')
302
+ const getter = js.split('\n').find(l => l.includes('get get() { return '))!
303
+ const getterText = getter.slice(getter.indexOf('get get() { return ') + 'get get() { return '.length, getter.indexOf(' }', getter.indexOf('get get()')))
304
+ const calls = new Function(`const enabled = true; let id = 0; const g = ${getterText}; return [g(), g(), id]`)()
305
+ expect(calls).toEqual([1, 2, 2])
306
+ })
307
+
308
+ test('is not raised for a handler wrapped by another call, which may run it later', () => {
309
+ const wrap = 'const wrap = (fn: () => void) => fn'
310
+ const body = (handler: string) =>
311
+ `const [n, setN] = createSignal(0)
312
+ let count = 0
313
+ return <div><button onClick={${handler}}>add</button><p>{n()}</p></div>`
314
+ const wrapped = body('wrap(() => { ++count; setN(count) })')
315
+ expect(codesOf(wrapped, '', wrap)).not.toContain('BF065')
316
+ expect(codesOf(body('() => { ++count; setN(count) }'), '', wrap)).not.toContain('BF065')
317
+ const debounce = 'declare function debounce(fn: () => void, ms: number): () => void'
318
+ expect(codesOf(body('debounce(() => { count++ }, 100)'), '', debounce)).not.toContain('BF065')
319
+ expect(codesOf(
320
+ `let count = 0\n return <input onInput={debounce(() => { count++ }, 100)} />`,
321
+ '',
322
+ debounce,
323
+ )).not.toContain('BF065')
324
+ // The control: a `.map()` callback runs in place, so its write is still refused.
325
+ expect(codesOf(`let count = 0\n return <ul>{['a'].map(i => { count++; return <li key={i}>{count}</li> })}</ul>`)).toContain('BF065')
326
+
327
+ // The wrapped listener keeps the init local and increments it.
328
+ const js = clientJs(body('wrap(() => { ++count; setN(count) })'), '', wrap)
329
+ expect(js).toContain('let count = 0')
330
+ const listener = js.split('\n').find(l => l.includes("addEventListener('click', "))!
331
+ const handlerText = listener.slice(listener.indexOf("'click', ") + "'click', ".length, listener.lastIndexOf(')'))
332
+ expect(handlerText).toBe('wrap(() => { ++count; setN(count) })')
333
+ // Run the emitted listener expression against an init-scope `count`.
334
+ const calls: number[] = []
335
+ const count = new Function('wrap', 'setN', `let count = 0; const h = ${handlerText}; h(); h(); return count`)(
336
+ (fn: () => void) => fn,
337
+ (v: number) => calls.push(v),
338
+ )
339
+ expect(count).toBe(2)
340
+ expect(calls).toEqual([1, 2])
341
+ })
342
+
343
+ test('a child prop that writes a local renders the child from init, not the template', () => {
344
+ const js = clientJs(
345
+ `const [n, setN] = createSignal(0)
346
+ let nextId = 0
347
+ return <div><button onClick={() => setN(n() + 1)}>add</button><p>{n()}</p><Show get={() => ++nextId} /></div>`,
348
+ '',
349
+ CHILD,
350
+ )
351
+ expect(templateOf(js)).toContain('data-bf-ph')
352
+ expect(templateOf(js)).not.toContain('++')
353
+ expect(js).toContain('return () => ++nextId')
354
+ })
355
+
356
+ test('a child prop that writes a prop renders the child from init, not the template', () => {
357
+ const js = clientJs(
358
+ `const [n, setN] = createSignal(0)
359
+ return <div><button onClick={() => setN(n() + 1)}>add</button><p>{n()}</p><Show get={() => ++start} /></div>`,
360
+ '{ start = 0 }: { start?: number }',
361
+ CHILD,
362
+ )
363
+ expect(templateOf(js)).toContain('data-bf-ph')
364
+ expect(js).toContain('let start = _p.start ?? 0')
365
+ expect(js).toContain('return () => ++start')
366
+ })
367
+
368
+ test('is not raised for a server-only component, which has no client template', () => {
369
+ expect(codesOf(`let id = 0\n return <p>{++id}</p>`, '', '', '')).not.toContain('BF065')
370
+ })
371
+ })
372
+
373
+ describe('isAssignmentTargetIdentifier', () => {
374
+ function targets(code: string, name: string): boolean[] {
375
+ const sf = ts.createSourceFile('x.ts', code, ts.ScriptTarget.Latest, true)
376
+ const out: boolean[] = []
377
+ const visit = (n: ts.Node): void => {
378
+ if (ts.isIdentifier(n) && n.text === name) out.push(isAssignmentTargetIdentifier(n))
379
+ ts.forEachChild(n, visit)
380
+ }
381
+ visit(sf)
382
+ return out
383
+ }
384
+
385
+ test('writes', () => {
386
+ for (const code of [
387
+ 'x = 1', 'x += 1', 'x ??= 1', '++x', 'x--', '(x) = 1', 'x! = 1', '(x as number) = 1',
388
+ '[x] = a', '[y, ...x] = a', '({ x } = o)', '({ k: x } = o)', '({ ...x } = o)', '[x = 1] = a',
389
+ 'for (x of a) {}', 'for (x in o) {}',
390
+ ]) {
391
+ expect({ code, t: targets(code, 'x') }).toEqual({ code, t: [true] })
392
+ }
393
+ })
394
+
395
+ test('reads', () => {
396
+ for (const code of [
397
+ 'y = x', 'x.a = 1', 'x[0]++', 'f([x])', 'y = [x]', '({ k: x })', '[y = x] = a',
398
+ '({ y = x } = o)', 'for (const x of a) {}', 'x + 1', '-x', '!x',
399
+ ]) {
400
+ expect({ code, t: targets(code, 'x').every(t => !t) }).toEqual({ code, t: true })
401
+ }
402
+ })
403
+ })
404
+
405
+ describe('one notion of a written binding', () => {
406
+ test('a binding the analyzer marks written fails keepsDeclaredValue, a prop and a body binding alike', () => {
407
+ const ctx = analyzeComponent(
408
+ `'use client'
409
+ import { createSignal } from '@barefootjs/client'
410
+ export function C({ start = 0, step = 1 }: { start?: number; step?: number }) {
411
+ const [n, setN] = createSignal(0)
412
+ let nextId = 0
413
+ const label = 'x'
414
+ const add = () => { start += step; setN(++nextId) }
415
+ return <div><button onClick={add}>{label}</button><p>{n()}</p></div>
416
+ }`,
417
+ 'C.tsx',
418
+ )
419
+ const param = (name: string) => ctx.propsParams.find(p => p.name === name)!
420
+ const local = (name: string) => ctx.localConstants.find(c => c.name === name)!
421
+ expect(param('start').reassigned).toBe(true)
422
+ expect(keepsDeclaredValue(param('start'))).toBe(false)
423
+ expect(keepsDeclaredValue(param('step'))).toBe(true)
424
+ expect(local('nextId').reassigned).toBe(true)
425
+ expect(keepsDeclaredValue(local('nextId'))).toBe(false)
426
+ // A handler's write leaves the declared value for render.
427
+ expect(local('nextId').mutatedAfterDeclaration).toBeUndefined()
428
+ expect(keepsDeclaredValue(local('label'))).toBe(true)
429
+ })
430
+ })
@@ -0,0 +1,57 @@
1
+ /**
2
+ * #3562: the CSR template substitutes a zero-param local helper
3
+ * (`const isWide = () => props.mode === 'wide'`) like any other const, so a
4
+ * template call `isWide()` reads its body instead of falling back to empty.
5
+ * A helper that is not a synchronous, pure value (a body that mutates state,
6
+ * an async arrow, a generator) is left alone: splicing `() => ({ id:
7
+ * ++nextId })` produced `++(0)`, a SyntaxError in the client bundle.
8
+ */
9
+
10
+ import { describe, test, expect } from 'bun:test'
11
+ import { compileJSX } from '../compiler'
12
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
13
+
14
+ const PRELUDE = "'use client'\nimport { createSignal } from '@barefootjs/client'\n"
15
+
16
+ function compile(body: string, jsx: string) {
17
+ const source = `${PRELUDE}export function S(props: { mode?: string; flag?: boolean }) {\n${body}\nreturn ${jsx}\n}`
18
+ const result = compileJSX(source, 'S.tsx', { adapter: new HonoAdapter() })
19
+ const clientJs = result.files.find((f) => f.path.endsWith('.client.js'))?.content ?? ''
20
+ const template = clientJs.split('\n').find((l) => l.includes('hydrate(')) ?? ''
21
+ return { clientJs, template }
22
+ }
23
+
24
+ /** Evaluate the registered `template:` lambda against `props`. */
25
+ function render(template: string, props: Record<string, unknown>): string {
26
+ const lambda = template.match(/template: (\(_p\) => `.*`) \}\)/)?.[1]
27
+ expect(lambda).toBeDefined()
28
+ return new Function('escapeAttr', 'escapeTextOrMarkup', `return ${lambda}`)(String, String)(props)
29
+ }
30
+
31
+ describe('zero-param helper in the CSR template (#3562)', () => {
32
+ test('a pure helper call reads its body', () => {
33
+ const { template } = compile(
34
+ "const isWide = () => props.mode === 'wide'\nconst [shown] = createSignal(isWide() ? 'wide' : 'narrow')",
35
+ '<p data-shown={shown()}>x</p>',
36
+ )
37
+ expect(render(template, { mode: 'wide' })).toContain('data-shown="wide"')
38
+ expect(render(template, { mode: 'tall' })).toContain('data-shown="narrow"')
39
+ })
40
+
41
+ test('a helper that mutates state is not spliced, and the bundle still parses', () => {
42
+ const { clientJs } = compile(
43
+ "let nextId = 0\nconst createField = () => ({ id: ++nextId, value: '' })\nconst [fields] = createSignal([createField()])",
44
+ '<ul>{fields().map((f) => <li key={f.id}>{f.value}</li>)}</ul>',
45
+ )
46
+ expect(clientJs).not.toContain('++(')
47
+ expect(() => new Bun.Transpiler({ loader: 'js' }).transformSync(clientJs)).not.toThrow()
48
+ })
49
+
50
+ test.each([
51
+ ['an async arrow', 'const helper = async () => props.flag'],
52
+ ['a generator function', 'const helper = function* () { return props.flag }'],
53
+ ])('%s is not spliced', (_label, decl) => {
54
+ const { template } = compile(`${decl}\nconst [shown] = createSignal(helper() ? 'yes' : 'no')`, '<p data-shown={shown()}>x</p>')
55
+ expect(template).not.toContain('_p.flag')
56
+ })
57
+ })
@@ -86,14 +86,22 @@ export interface CallbackEvalPlan {
86
86
  captured: string[]
87
87
  }
88
88
 
89
- /** A lowered callback method call, as data. */
90
- export type CallbackPlan =
89
+ /**
90
+ * A lowered `.sort` / `.toSorted` comparator: the evaluator call, the
91
+ * structured `{keys: …}` descriptor for a comparator the evaluator cannot
92
+ * model, or BF101.
93
+ */
94
+ export type SortPlan =
91
95
  | CallbackEvalPlan
92
96
  /** A comparator the evaluator cannot model but the `{keys: …}` descriptor can. */
93
97
  | { kind: 'structured-sort'; comparator: SortComparator }
98
+ | { kind: 'refuse'; message: string; suggestion: string }
99
+
100
+ /** A lowered callback method call, as data. */
101
+ export type CallbackPlan =
102
+ | SortPlan
94
103
  /** A predicate for the adapter's own native form (see `nativePredicate`). */
95
104
  | { kind: 'native-predicate'; method: PredicateMethod; param: string; predicate: ParsedExpr }
96
- | { kind: 'refuse'; message: string; suggestion: string }
97
105
  /** A method outside `CALLBACK_METHODS`; unreachable, as the parser recognises only those. */
98
106
  | { kind: 'receiver' }
99
107
 
@@ -119,13 +127,7 @@ export function lowerCallbackMethod(
119
127
  const { adapterName } = options
120
128
  const { body, params } = arrow
121
129
  if (isPredicateMethod(method)) return lowerPredicate(method, arrow, options)
122
- if (method === 'sort' || method === 'toSorted') {
123
- const plan = sortEvalPlan(body, params)
124
- if (plan) return plan
125
- const comparator = sortComparatorFromArrow(arrow)
126
- if (comparator) return { kind: 'structured-sort', comparator }
127
- return sortRefusal(method, adapterName)
128
- }
130
+ if (method === 'sort' || method === 'toSorted') return lowerSortComparator(method, arrow, adapterName)
129
131
  if (method === 'reduce' || method === 'reduceRight') {
130
132
  const init = restArgs[0]
131
133
  const plan = init ? reduceEvalPlan(body, params, init, method === 'reduceRight' ? 'right' : 'left') : null
@@ -178,6 +180,19 @@ function lowerPredicate(method: PredicateMethod, arrow: Arrow, options: Callback
178
180
  }
179
181
  }
180
182
 
183
+ /**
184
+ * Lower a `.sort` / `.toSorted` comparator: the evaluator first, then the
185
+ * structured `{keys: …}` descriptor, otherwise BF101. A loop source's sort
186
+ * (`planLoop`) and `.sort(cmp)` at an expression position decide the same.
187
+ */
188
+ export function lowerSortComparator(method: 'sort' | 'toSorted', arrow: Arrow, adapterName: string): SortPlan {
189
+ const plan = sortEvalPlan(arrow.body, arrow.params)
190
+ if (plan) return plan
191
+ const comparator = sortComparatorFromArrow(arrow)
192
+ if (comparator) return { kind: 'structured-sort', comparator }
193
+ return sortRefusal(method, adapterName)
194
+ }
195
+
181
196
  /**
182
197
  * The evaluator plan for a sort comparator, or `null` when the body is
183
198
  * outside the evaluator surface (a `localeCompare` comparator) or the arrow
@@ -351,6 +366,29 @@ export function unloweredCallRefusal(
351
366
  }
352
367
  }
353
368
 
369
+ /**
370
+ * BF101 for a `.filter(...).map(...)` predicate shape a DSL adapter's filter
371
+ * emitter has no form for: a conditional, a template literal, an object
372
+ * literal, a standalone arrow or regex, or an unsupported node (#3534). The
373
+ * emitters used to stand a truthy constant in for these, so every row
374
+ * rendered; the same predicate outside a loop is evaluated or refused, never
375
+ * guessed.
376
+ */
377
+ export function filterPredicateShapeRefusal(shape: string, adapterName: string): { message: string; suggestion: string } {
378
+ return {
379
+ message: `Filter predicate contains ${shape}, which has no ${adapterName} loop-filter form`,
380
+ suggestion: `Rewrite the predicate as comparisons joined with && / || / !, or add /* @client */ for client-only evaluation (no SSR).`,
381
+ }
382
+ }
383
+
384
+ /** BF101 for a loop filter whose predicate never reached the IR (#3534). */
385
+ export function missingFilterPredicateRefusal(raw: string, adapterName: string): { message: string; suggestion: string } {
386
+ return {
387
+ message: `Filter predicate '${raw}' has no ${adapterName} loop-filter form`,
388
+ suggestion: `Rewrite the predicate as an expression-body arrow, or add /* @client */ for client-only evaluation (no SSR).`,
389
+ }
390
+ }
391
+
354
392
  /**
355
393
  * The BF101 for a callback method nested inside a filter predicate, which a
356
394
  * predicate emitter has no scalar form for.