@barefootjs/jsx 0.39.8 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/adapters/attr-plan.d.ts +1 -20
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +19 -7
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +79 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-plan.d.ts +173 -9
  8. package/dist/adapters/loop-plan.d.ts.map +1 -1
  9. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  10. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  11. package/dist/analyzer.d.ts.map +1 -1
  12. package/dist/assignment-target.d.ts +26 -0
  13. package/dist/assignment-target.d.ts.map +1 -0
  14. package/dist/augment-inherited-props.d.ts.map +1 -1
  15. package/dist/css-layer-prefixer.d.ts.map +1 -1
  16. package/dist/debug.d.ts.map +1 -1
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2566 -2007
  22. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  31. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  37. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  40. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/jsx-to-ir.d.ts.map +1 -1
  44. package/dist/module-exports.d.ts.map +1 -1
  45. package/dist/prop-rewrite.d.ts +17 -8
  46. package/dist/prop-rewrite.d.ts.map +1 -1
  47. package/dist/props-binding.d.ts +57 -0
  48. package/dist/props-binding.d.ts.map +1 -1
  49. package/dist/scope/binding-scope.d.ts +32 -2
  50. package/dist/scope/binding-scope.d.ts.map +1 -1
  51. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  52. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  53. package/dist/template-parts.d.ts +1 -1
  54. package/dist/template-parts.d.ts.map +1 -1
  55. package/dist/types.d.ts +30 -2
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  59. package/src/__tests__/attr-plan.test.ts +1 -14
  60. package/src/__tests__/binding-scope.test.ts +29 -0
  61. package/src/__tests__/client-template-escape-soundness.test.ts +17 -4
  62. package/src/__tests__/client-template-static-delimiters.test.ts +57 -0
  63. package/src/__tests__/create-query.test.ts +1 -1
  64. package/src/__tests__/dsl-template-adapter.test.ts +70 -0
  65. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  66. package/src/__tests__/extract-function-params.test.ts +37 -0
  67. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +18 -0
  68. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +11 -0
  69. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  70. package/src/__tests__/loop-plan.test.ts +196 -1
  71. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  72. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  73. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  74. package/src/__tests__/props-alias-const.test.ts +60 -1
  75. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  76. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  77. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  78. package/src/__tests__/template-parts-literal-boundary.test.ts +22 -0
  79. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  80. package/src/adapters/attr-plan.ts +2 -54
  81. package/src/adapters/callback-method.ts +25 -10
  82. package/src/adapters/dsl-template-adapter.ts +155 -2
  83. package/src/adapters/loop-plan.ts +267 -14
  84. package/src/adapters/parsed-expr-emitter.ts +37 -4
  85. package/src/analyzer.ts +283 -2
  86. package/src/assignment-target.ts +79 -0
  87. package/src/augment-inherited-props.ts +5 -9
  88. package/src/css-layer-prefixer.ts +4 -5
  89. package/src/debug.ts +1 -0
  90. package/src/errors.ts +11 -0
  91. package/src/index.ts +23 -4
  92. package/src/ir-to-client-js/compute-inlinability.ts +7 -4
  93. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  94. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  95. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  96. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  97. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  98. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  99. package/src/ir-to-client-js/emit-registration.ts +6 -1
  100. package/src/ir-to-client-js/html-template.ts +70 -52
  101. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  102. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  103. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  104. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  105. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  106. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  107. package/src/ir-to-client-js/utils.ts +41 -97
  108. package/src/jsx-to-ir.ts +65 -32
  109. package/src/loop-destructure.ts +4 -1
  110. package/src/module-exports.ts +13 -21
  111. package/src/prop-rewrite.ts +31 -72
  112. package/src/props-binding.ts +73 -1
  113. package/src/rich-type-refusal.ts +3 -1
  114. package/src/scope/binding-scope.ts +39 -3
  115. package/src/scope/lexical-scope-walk.ts +167 -0
  116. package/src/template-parts.ts +4 -2
  117. package/src/template-position-walk.ts +3 -1
  118. package/src/types.ts +27 -2
@@ -120,4 +120,94 @@ describe('rewritePropsObjectRef', () => {
120
120
  const out = rewritePropsObjectRef('const x = propsX.name', 'props')
121
121
  expect(out).toBe('const x = propsX.name')
122
122
  })
123
+
124
+ describe('an inner binding of the same name shadows the props object', () => {
125
+ // The client JS reads the component's props through `_p`. A callback
126
+ // parameter or local spelled like the props object belongs to its own
127
+ // binding inside its scope: renaming it too would make every `_p.<prop>`
128
+ // read the compiler emits inside that scope (a destructured prop, a
129
+ // forwarded child prop) read the parameter instead.
130
+ test('a loop row callback param keeps its name; the outer `_p` read stays outer', () => {
131
+ const code = 'mapArray(() => items(), el, (props) => String(props.id), (props) => props().label + _p.suffix)'
132
+ expect(rewritePropsObjectRef(code, null)).toBe(code)
133
+ })
134
+
135
+ test('a row accessor `const props = () => __e.item` keeps its name', () => {
136
+ const code = 'const row = (__e) => {\n const props = () => __e.item\n return props().label + _p.suffix\n}'
137
+ expect(rewritePropsObjectRef(code, null)).toBe(code)
138
+ })
139
+
140
+ test('a handler arrow param and a nested function param keep their names', () => {
141
+ const code = 'const bump = (props) => set(props.by * _p.step)\nfunction describe(props) { return props.label + _p.suffix }'
142
+ expect(rewritePropsObjectRef(code, null)).toBe(code)
143
+ })
144
+
145
+ test('references outside the shadowing scope are still rewritten', () => {
146
+ const out = rewritePropsObjectRef('const a = props.x\nconst f = (props) => props.y\nconst b = props.z', 'props')
147
+ expect(out).toBe('const a = _p.x\nconst f = (props) => props.y\nconst b = _p.z')
148
+ })
149
+
150
+ test('a rest binding name is shadowed the same way', () => {
151
+ const out = rewritePropsObjectRef('const a = rest\nconst f = (rest) => rest.y', null, 'rest')
152
+ expect(out).toBe('const a = _p\nconst f = (rest) => rest.y')
153
+ })
154
+ })
155
+
156
+ describe('`var` is function-scoped', () => {
157
+ test('a `var props` in a nested block binds for the whole enclosing function', () => {
158
+ const code = 'const f = () => { if (c) { var props = { by: 2 } } return props.by }\nconst g = props.x'
159
+ expect(rewritePropsObjectRef(code, null)).toBe('const f = () => { if (c) { var props = { by: 2 } } return props.by }\nconst g = _p.x')
160
+ })
161
+
162
+ test('a `for (var props …)` head binds after the loop, but not outside its function', () => {
163
+ const code = 'function f() { for (var props = 0; props < 3; props++) {} return props }\nconst g = props.x'
164
+ expect(rewritePropsObjectRef(code, null)).toBe('function f() { for (var props = 0; props < 3; props++) {} return props }\nconst g = _p.x')
165
+ })
166
+
167
+ test('a `var` inside a nested function does not leak into the outer one', () => {
168
+ const code = 'const f = () => { const h = () => { var props = 1; return props }; return props.x }'
169
+ expect(rewritePropsObjectRef(code, null)).toBe('const f = () => { const h = () => { var props = 1; return props }; return _p.x }')
170
+ })
171
+ })
172
+
173
+ describe('a parameter default does not see the body\'s declarations', () => {
174
+ test('a default reads the props object despite a same-named body `var`', () => {
175
+ const code = 'const f = (v = props.x) => { var props = 1; return v + props }'
176
+ expect(rewritePropsObjectRef(code, null)).toBe('const f = (v = _p.x) => { var props = 1; return v + props }')
177
+ })
178
+
179
+ test('a default reads the props object despite a same-named body `let`', () => {
180
+ const code = 'function f(v = props.x) { let props = 1; return v + props }'
181
+ expect(rewritePropsObjectRef(code, null)).toBe('function f(v = _p.x) { let props = 1; return v + props }')
182
+ })
183
+
184
+ test('a default sees an earlier parameter of the same name, not the props object', () => {
185
+ const code = 'const f = (props, v = props.x) => v'
186
+ expect(rewritePropsObjectRef(code, null)).toBe(code)
187
+ })
188
+ })
189
+
190
+ describe('a class static block owns its `var`s', () => {
191
+ test('a read inside the block is local; a read after the class is the props object', () => {
192
+ const code = 'const f = () => { class C { static { var props = 1; C.p = props } }; return props.x }'
193
+ expect(rewritePropsObjectRef(code, null)).toBe('const f = () => { class C { static { var props = 1; C.p = props } }; return _p.x }')
194
+ })
195
+
196
+ test('a `var` in a method or a field-initializer arrow does not leak into the enclosing function', () => {
197
+ const code = 'const f = () => { class C { m() { var props = 1; return props } g = () => { var props = 2; return props } }; return props.x }'
198
+ expect(rewritePropsObjectRef(code, null)).toBe('const f = () => { class C { m() { var props = 1; return props } g = () => { var props = 2; return props } }; return _p.x }')
199
+ })
200
+ })
201
+
202
+ describe('a computed method name is read in the enclosing scope', () => {
203
+ test('the key reads the props object; the body reads the parameter', () => {
204
+ const code = 'const o = { [props.k](props) { return props } }'
205
+ expect(rewritePropsObjectRef(code, null)).toBe('const o = { [_p.k](props) { return props } }')
206
+ })
207
+
208
+ test('the same holds for a class method and an accessor', () => {
209
+ const code = 'class C { [props.a](props) { return props } get [props.b]() { const props = 1; return props } }'
210
+ expect(rewritePropsObjectRef(code, null)).toBe('class C { [_p.a](props) { return props } get [_p.b]() { const props = 1; return props } }')
211
+ })
212
+ })
123
213
  })
@@ -0,0 +1,22 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { templatePartsToJsExpr } from '../template-parts'
3
+ import { parseExpression } from '../expression-parser'
4
+
5
+ for (const text of ['${notCode}', '`', '\\', '\\${notCode}', '"\'\n\r\t', '']) {
6
+ test(`template text stays literal: ${JSON.stringify(text)}`, () => {
7
+ const source = templatePartsToJsExpr([
8
+ { type: 'string', value: text },
9
+ { type: 'expression', expr: 'value', templateExpr: '_p.value', parsed: parseExpression('value') },
10
+ { type: 'string', value: text },
11
+ ])
12
+ expect(new Function('value', `return ${source}`)('}')).toBe(`${text}}${text}`)
13
+ })
14
+ }
15
+
16
+ test('template expression projection rewrites only the expression part', () => {
17
+ const source = templatePartsToJsExpr([
18
+ { type: 'string', value: '${value} ' },
19
+ { type: 'expression', expr: 'value', templateExpr: '_p.value', parsed: parseExpression('value') },
20
+ ], { useTemplate: true })
21
+ expect(new Function('_p', `return ${source}`)({ value: 'tail' })).toBe('${value} tail')
22
+ })
@@ -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
+ })
@@ -10,65 +10,13 @@
10
10
  * hash literal.
11
11
  */
12
12
 
13
- import { exprToString, isSupported, parseExpression, type ParsedExpr } from '../expression-parser.ts'
14
- import type { LoweringMatcher } from '../lowering-registry.ts'
13
+ import { exprToString, parseExpression, type ParsedExpr } from '../expression-parser.ts'
15
14
  import { attrValueMayBeNullish, nullableSignalAttrGetter, type NullishAttrContext } from '../nullable-signal-attr.ts'
16
- import type { CompilerError, ConstantInfo, ExpressionAttr, SpreadAttr } from '../types.ts'
15
+ import type { ConstantInfo, ExpressionAttr, SpreadAttr } from '../types.ts'
17
16
  import { isBooleanAttr } from '../html-constants.ts'
18
17
 
19
18
  const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
20
19
 
21
- /**
22
- * Whether an attribute value is a shape no template lowers: a JS object
23
- * literal (`style={{…}}` aside, which the adapter lowers first) or a
24
- * tagged template literal (`cn\`base ${tone()}\``). Returns the refusal, with
25
- * the support gate's reason when it gives one, or `null` when the value
26
- * goes on to {@link planAttrExpression}. The adapter reports BF101 in its own
27
- * words. A value starting with neither shape is never parsed here.
28
- */
29
- export function unsupportedAttrExpression(
30
- expr: string,
31
- loweringMatchers: readonly LoweringMatcher[],
32
- ): { reason: string | undefined } | null {
33
- let probe = expr.trim()
34
- while (probe.startsWith('(')) probe = probe.slice(1).trimStart()
35
- const startsAsObjectLiteral = probe.startsWith('{')
36
- const hasTaggedTemplate = /[A-Za-z_$][\w$]*\s*`/.test(probe)
37
- if (!startsAsObjectLiteral && !hasTaggedTemplate) return null
38
- const parsed = parseExpression(expr.trim())
39
- const support = isSupported(parsed, { loweringMatchers })
40
- if (parsed.kind !== 'unsupported' && support.supported) return null
41
- return { reason: support.reason ?? (parsed.kind === 'unsupported' ? parsed.reason : undefined) }
42
- }
43
-
44
- /**
45
- * The BF101 for an attribute value {@link unsupportedAttrExpression}
46
- * refuses, worded for one adapter (`adapterLabel`, e.g. `Mojo`) and its
47
- * template language (`languageLabel`, e.g. `Embedded Perl`); `null` when the
48
- * value goes on to {@link planAttrExpression}.
49
- */
50
- export function unsupportedAttrExpressionError(
51
- expr: string,
52
- attrName: string,
53
- loweringMatchers: readonly LoweringMatcher[],
54
- componentName: string,
55
- adapterLabel: string,
56
- languageLabel: string,
57
- ): CompilerError | null {
58
- const refusal = unsupportedAttrExpression(expr, loweringMatchers)
59
- if (!refusal) return null
60
- const reasonLine = refusal.reason ? `\n${refusal.reason}` : ''
61
- return {
62
- code: 'BF101',
63
- severity: 'error',
64
- message: `Expression not supported on attribute '${attrName}': ${expr.trim()}${reasonLine}`,
65
- loc: { file: componentName + '.tsx', start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
66
- suggestion: {
67
- message: `The ${adapterLabel} adapter cannot lower JS object literals or tagged-template-literal expressions into ${languageLabel}. Move the expression into a \`'use client'\` component (so hydration computes it), or expand it into discrete attributes whose values are values the adapter can lower.`,
68
- },
69
- }
70
- }
71
-
72
20
  /**
73
21
  * The emission of an `{expr}` attribute value.
74
22
  *