@barefootjs/jsx 0.39.8 → 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.
- package/dist/adapters/callback-method.d.ts +19 -7
- package/dist/adapters/callback-method.d.ts.map +1 -1
- package/dist/adapters/dsl-template-adapter.d.ts +2 -0
- package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
- package/dist/adapters/loop-plan.d.ts +133 -9
- package/dist/adapters/loop-plan.d.ts.map +1 -1
- package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
- package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/assignment-target.d.ts +26 -0
- package/dist/assignment-target.d.ts.map +1 -0
- package/dist/errors.d.ts +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1913 -1457
- package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
- package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
- package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
- package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
- package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
- package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
- package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
- package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
- package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
- package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
- package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
- package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
- package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
- package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/prop-rewrite.d.ts +17 -8
- package/dist/prop-rewrite.d.ts.map +1 -1
- package/dist/props-binding.d.ts +57 -0
- package/dist/props-binding.d.ts.map +1 -1
- package/dist/scope/binding-scope.d.ts +30 -2
- package/dist/scope/binding-scope.d.ts.map +1 -1
- package/dist/scope/lexical-scope-walk.d.ts +26 -0
- package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
- package/dist/types.d.ts +25 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/arithmetic-lowering.test.ts +5 -1
- package/src/__tests__/binding-scope.test.ts +29 -0
- package/src/__tests__/create-query.test.ts +1 -1
- package/src/__tests__/emit-to-string-call.test.ts +58 -0
- package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
- package/src/__tests__/loop-plan.test.ts +131 -1
- package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
- package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
- package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
- package/src/__tests__/props-alias-const.test.ts +60 -1
- package/src/__tests__/props-named-callback-param.test.ts +256 -0
- package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
- package/src/__tests__/rewrite-props-object.test.ts +90 -0
- package/src/__tests__/written-binding-substitution.test.ts +430 -0
- package/src/adapters/callback-method.ts +25 -10
- package/src/adapters/dsl-template-adapter.ts +11 -0
- package/src/adapters/loop-plan.ts +201 -13
- package/src/adapters/parsed-expr-emitter.ts +37 -4
- package/src/analyzer.ts +283 -2
- package/src/assignment-target.ts +79 -0
- package/src/errors.ts +11 -0
- package/src/index.ts +13 -2
- package/src/ir-to-client-js/compute-inlinability.ts +6 -3
- package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
- package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
- package/src/ir-to-client-js/control-flow/shared.ts +41 -3
- package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
- package/src/ir-to-client-js/csr-substitute.ts +70 -22
- package/src/ir-to-client-js/emit-reactive.ts +2 -2
- package/src/ir-to-client-js/emit-registration.ts +6 -1
- package/src/ir-to-client-js/html-template.ts +18 -7
- package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
- package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
- package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
- package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
- package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
- package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
- package/src/ir-to-client-js/utils.ts +40 -96
- package/src/jsx-to-ir.ts +31 -12
- package/src/prop-rewrite.ts +31 -72
- package/src/props-binding.ts +73 -1
- package/src/scope/binding-scope.ts +34 -3
- package/src/scope/lexical-scope-walk.ts +167 -0
- package/src/types.ts +25 -1
|
@@ -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
|
+
})
|
|
@@ -86,14 +86,22 @@ export interface CallbackEvalPlan {
|
|
|
86
86
|
captured: string[]
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
-
/**
|
|
90
|
-
|
|
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
|
|
@@ -147,6 +147,17 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
|
|
|
147
147
|
* above and before any diagnostic or rendering.
|
|
148
148
|
*/
|
|
149
149
|
protected resetAdapterState(_ir: ComponentIR): void {}
|
|
150
|
+
|
|
151
|
+
/** `render()` under `scope`, the current scope restored afterwards. */
|
|
152
|
+
protected renderInScope<T>(scope: BindingScope, render: () => T): T {
|
|
153
|
+
const outer = this.scope
|
|
154
|
+
this.scope = scope
|
|
155
|
+
try {
|
|
156
|
+
return render()
|
|
157
|
+
} finally {
|
|
158
|
+
this.scope = outer
|
|
159
|
+
}
|
|
160
|
+
}
|
|
150
161
|
/** The root `if` statement of a component with conditional returns. */
|
|
151
162
|
protected abstract renderIfStatement(ifStmt: IRIfStatement): string
|
|
152
163
|
/** The script registrations the template starts with. */
|