@barefootjs/jsx 0.39.5 → 0.39.6

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 (57) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/literal-value.d.ts +22 -0
  14. package/dist/adapters/literal-value.d.ts.map +1 -0
  15. package/dist/adapters/loop-plan.d.ts +53 -0
  16. package/dist/adapters/loop-plan.d.ts.map +1 -0
  17. package/dist/adapters/prop-classes.d.ts +37 -0
  18. package/dist/adapters/prop-classes.d.ts.map +1 -0
  19. package/dist/expression-parser.d.ts +38 -0
  20. package/dist/expression-parser.d.ts.map +1 -1
  21. package/dist/index.d.ts +17 -3
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1765 -914
  24. package/dist/jsx-to-ir.d.ts +465 -1
  25. package/dist/jsx-to-ir.d.ts.map +1 -1
  26. package/dist/nullable-signal-attr.d.ts +19 -0
  27. package/dist/nullable-signal-attr.d.ts.map +1 -1
  28. package/package.json +2 -2
  29. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  30. package/src/__tests__/action-accessor.test.ts +6 -24
  31. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  32. package/src/__tests__/attr-plan.test.ts +121 -0
  33. package/src/__tests__/binding-scope-ratchet.test.ts +12 -12
  34. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  35. package/src/__tests__/boolean-result.test.ts +34 -1
  36. package/src/__tests__/callback-method.test.ts +189 -0
  37. package/src/__tests__/component-props.test.ts +148 -0
  38. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  39. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  40. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  41. package/src/__tests__/loop-plan.test.ts +104 -0
  42. package/src/__tests__/map-call-decisions.test.ts +521 -0
  43. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  44. package/src/adapters/array-method.ts +193 -0
  45. package/src/adapters/attr-plan.ts +200 -0
  46. package/src/adapters/boolean-result.ts +208 -12
  47. package/src/adapters/callback-method.ts +301 -0
  48. package/src/adapters/component-props.ts +144 -0
  49. package/src/adapters/component-tree.ts +118 -0
  50. package/src/adapters/literal-value.ts +36 -0
  51. package/src/adapters/loop-plan.ts +88 -0
  52. package/src/adapters/prop-classes.ts +73 -0
  53. package/src/expression-parser.ts +537 -374
  54. package/src/index.ts +53 -2
  55. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  56. package/src/jsx-to-ir.ts +1328 -991
  57. package/src/nullable-signal-attr.ts +78 -0
@@ -0,0 +1,521 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import ts from 'typescript'
3
+ import { analyzeComponent } from '../analyzer'
4
+ import {
5
+ applyPreambleBuilderPasses,
6
+ classifyLoopArray,
7
+ createTransformContext,
8
+ refuseUnloweredJsxCallback,
9
+ resolveLoopKey,
10
+ resolveLoopRowParams,
11
+ resolveLoopSource,
12
+ transformLoopCallbackBody,
13
+ withLoopRowScope,
14
+ type TransformContext,
15
+ } from '../jsx-to-ir'
16
+ import type { IRLoop } from '../types'
17
+
18
+ // #3424: `transformMapCall` is a coordinator over one helper per decision.
19
+ // These tests pin each helper on its own, against the AST of a small
20
+ // component, so the next loop fix can be verified at the decision it
21
+ // touches. The end-to-end shapes (slot ids, adapter output) stay covered
22
+ // by the loop fixtures and the existing `*loop*` / `*map*` suites.
23
+
24
+ /** The first `.map()` / `.flatMap()` call in `source`, with a transform context. */
25
+ function mapCallOf(source: string, method: 'map' | 'flatMap' = 'map'): { node: ts.CallExpression; ctx: TransformContext } {
26
+ const analyzer = analyzeComponent(source, 'Test.tsx')
27
+ const ctx = createTransformContext(analyzer)
28
+ let found: ts.CallExpression | undefined
29
+ const visit = (n: ts.Node): void => {
30
+ if (
31
+ !found &&
32
+ ts.isCallExpression(n) &&
33
+ ts.isPropertyAccessExpression(n.expression) &&
34
+ n.expression.name.text === method
35
+ ) {
36
+ found = n
37
+ }
38
+ ts.forEachChild(n, visit)
39
+ }
40
+ visit(analyzer.sourceFile)
41
+ if (!found) throw new Error(`no .${method}() call in source`)
42
+ return { node: found, ctx }
43
+ }
44
+
45
+ const arrowOf = (node: ts.CallExpression): ts.ArrowFunction => {
46
+ const cb = node.arguments[0]
47
+ if (!ts.isArrowFunction(cb)) throw new Error('expected an arrow callback')
48
+ return cb
49
+ }
50
+
51
+ /** Lower a callback body the way the coordinator does, under the row's scope. */
52
+ function lowerBody(source: string, method: 'map' | 'flatMap' = 'map', isClientOnly = false) {
53
+ const { node, ctx } = mapCallOf(source, method)
54
+ const callback = arrowOf(node)
55
+ const src = resolveLoopSource(node, ctx, isClientOnly)
56
+ const row = resolveLoopRowParams(callback, src, ctx)
57
+ const body = withLoopRowScope(ctx, row, (savedScope) =>
58
+ transformLoopCallbackBody(callback, row, savedScope, ctx, isClientOnly, method),
59
+ )
60
+ return { node, ctx, callback, src, row, body }
61
+ }
62
+
63
+ const component = (body: string, props = '{ items }: { items: Array<{ id: number; name: string }> }') => `
64
+ function Test(${props}) {
65
+ return <ul>${body}</ul>
66
+ }
67
+ export { Test }
68
+ `
69
+
70
+ describe('resolveLoopSource — which array the loop iterates', () => {
71
+ test('a plain .map() iterates the receiver itself', () => {
72
+ const { node, ctx } = mapCallOf(component('{items.map(it => <li key={it.id}>{it.name}</li>)}'))
73
+ const src = resolveLoopSource(node, ctx, false)
74
+ expect(src.array).toBe('items')
75
+ expect(src.filterPredicate).toBeUndefined()
76
+ expect(src.sortComparator).toBeUndefined()
77
+ expect(src.chainOrder).toBeUndefined()
78
+ expect(src.iterationShape).toBeUndefined()
79
+ expect(src.objectIteration).toBeUndefined()
80
+ })
81
+
82
+ test('filter().map() lifts the predicate and iterates the inner array', () => {
83
+ const { node, ctx } = mapCallOf(component('{items.filter(it => it.id > 1).map(it => <li key={it.id}>{it.name}</li>)}'))
84
+ const src = resolveLoopSource(node, ctx, false)
85
+ expect(src.array).toBe('items')
86
+ expect(src.filterPredicate?.param).toBe('it')
87
+ expect(src.filterPredicate?.raw).toBe('it.id > 1')
88
+ expect(src.chainOrder).toBeUndefined()
89
+ })
90
+
91
+ test('filter().sort().map() records the chain order and both callbacks', () => {
92
+ const { node, ctx } = mapCallOf(
93
+ component('{items.filter(it => it.id > 1).sort((a, b) => a.id - b.id).map(it => <li key={it.id}>{it.name}</li>)}'),
94
+ )
95
+ const src = resolveLoopSource(node, ctx, false)
96
+ expect(src.array).toBe('items')
97
+ expect(src.chainOrder).toBe('filter-sort')
98
+ expect(src.filterPredicate?.raw).toBe('it.id > 1')
99
+ expect(src.sortComparator).toBeDefined()
100
+ })
101
+
102
+ test('sort().filter().map() records the other order', () => {
103
+ const { node, ctx } = mapCallOf(
104
+ component('{items.sort((a, b) => a.id - b.id).filter(it => it.id > 1).map(it => <li key={it.id}>{it.name}</li>)}'),
105
+ )
106
+ const src = resolveLoopSource(node, ctx, false)
107
+ expect(src.chainOrder).toBe('sort-filter')
108
+ expect(src.array).toBe('items')
109
+ })
110
+
111
+ test('a /* @client */ loop keeps the whole chain in the array string', () => {
112
+ const { node, ctx } = mapCallOf(component('{items.filter(it => it.id > 1).map(it => <li key={it.id}>{it.name}</li>)}'))
113
+ const src = resolveLoopSource(node, ctx, true)
114
+ expect(src.array).toBe('items.filter(it => it.id > 1)')
115
+ expect(src.filterPredicate).toBeUndefined()
116
+ expect(ctx.analyzer.errors).toHaveLength(0)
117
+ })
118
+
119
+ test('an off-subset comparator stays in the array string and is refused for a DSL target', () => {
120
+ const { node, ctx } = mapCallOf(component('{items.sort((a, b) => Math.random() - 0.5).map(it => <li key={it.id}>{it.name}</li>)}'))
121
+ const src = resolveLoopSource(node, ctx, false)
122
+ expect(src.array).toBe('items.sort((a, b) => Math.random() - 0.5)')
123
+ expect(src.sortComparator).toBeUndefined()
124
+ expect(ctx.analyzer.errors.map(e => e.code)).toEqual(['BF021'])
125
+ })
126
+
127
+ test('an off-subset comparator is accepted when the adapter runs callback bodies', () => {
128
+ const { node, ctx } = mapCallOf(component('{items.sort((a, b) => Math.random() - 0.5).map(it => <li key={it.id}>{it.name}</li>)}'))
129
+ ctx.analyzer.acceptsCallbackBody = () => true
130
+ resolveLoopSource(node, ctx, false)
131
+ expect(ctx.analyzer.errors).toHaveLength(0)
132
+ })
133
+
134
+ test('.entries() is stripped and recorded as the iteration shape', () => {
135
+ const { node, ctx } = mapCallOf(component('{items.entries().map(([i, it]) => <li key={it.id}>{i}</li>)}'))
136
+ const src = resolveLoopSource(node, ctx, false)
137
+ expect(src.array).toBe('items')
138
+ expect(src.iterationShape).toBe('entries')
139
+ })
140
+
141
+ test('.values() is a no-op: stripped but not recorded', () => {
142
+ const { node, ctx } = mapCallOf(component('{items.values().map(it => <li key={it.id}>{it.name}</li>)}'))
143
+ const src = resolveLoopSource(node, ctx, false)
144
+ expect(src.array).toBe('items')
145
+ expect(src.iterationShape).toBeUndefined()
146
+ })
147
+
148
+ test('Object.entries(x) is a separate shape, and records values too', () => {
149
+ const { node, ctx } = mapCallOf(
150
+ component('{Object.values(dict).map(v => <li key={v}>{v}</li>)}', '{ dict }: { dict: Record<string, string> }'),
151
+ )
152
+ const src = resolveLoopSource(node, ctx, false)
153
+ expect(src.array).toBe('dict')
154
+ expect(src.objectIteration).toBe('values')
155
+ expect(src.iterationShape).toBeUndefined()
156
+ })
157
+
158
+ test('templateArray carries the _p.-rewritten form of a destructured prop (#2222)', () => {
159
+ const { node, ctx } = mapCallOf(component('{items.filter(it => it.id > 1).map(it => <li key={it.id}>{it.name}</li>)}'))
160
+ const src = resolveLoopSource(node, ctx, false)
161
+ expect(src.templateArray).toBe('_p.items')
162
+ })
163
+ })
164
+
165
+ describe('resolveLoopRowParams — the names a row binds', () => {
166
+ test('item and index params, with their type text', () => {
167
+ const { node, ctx } = mapCallOf(component('{items.map((it: { id: number }, i: number) => <li key={it.id}>{i}</li>)}'))
168
+ const row = resolveLoopRowParams(arrowOf(node), resolveLoopSource(node, ctx, false), ctx)
169
+ expect(row.param).toBe('it')
170
+ expect(row.paramType).toBe('{ id: number }')
171
+ expect(row.index).toBe('i')
172
+ expect(row.indexType).toBe('number')
173
+ expect(row.paramBindings).toBeUndefined()
174
+ })
175
+
176
+ test('a callback without parameters binds the default item name', () => {
177
+ const { node, ctx } = mapCallOf(component('{items.map(() => <li>x</li>)}'))
178
+ const row = resolveLoopRowParams(arrowOf(node), resolveLoopSource(node, ctx, false), ctx)
179
+ expect(row.param).toBe('item')
180
+ expect(row.index).toBeNull()
181
+ expect(row.itemTypeNode).toBeUndefined()
182
+ })
183
+
184
+ test('a destructured param lowers to per-binding accessor paths', () => {
185
+ const { node, ctx } = mapCallOf(component('{items.map(({ id, name }) => <li key={id}>{name}</li>)}'))
186
+ const row = resolveLoopRowParams(arrowOf(node), resolveLoopSource(node, ctx, false), ctx)
187
+ expect(row.param).toBe('{ id, name }')
188
+ expect(row.paramBindings?.map(b => b.name)).toEqual(['id', 'name'])
189
+ })
190
+
191
+ test('.entries() with a 2-tuple destructure resolves into index + param, no bindings', () => {
192
+ const { node, ctx } = mapCallOf(component('{items.entries().map(([i, it]) => <li key={it.id}>{i}</li>)}'))
193
+ const row = resolveLoopRowParams(arrowOf(node), resolveLoopSource(node, ctx, false), ctx)
194
+ expect(row.index).toBe('i')
195
+ expect(row.param).toBe('it')
196
+ expect(row.paramBindings).toBeUndefined()
197
+ })
198
+
199
+ test('Object.entries(x) reuses the same 2-tuple extraction', () => {
200
+ const { node, ctx } = mapCallOf(
201
+ component('{Object.entries(dict).map(([k, v]) => <li key={k}>{v}</li>)}', '{ dict }: { dict: Record<string, string> }'),
202
+ )
203
+ const row = resolveLoopRowParams(arrowOf(node), resolveLoopSource(node, ctx, false), ctx)
204
+ expect(row.index).toBe('k')
205
+ expect(row.param).toBe('v')
206
+ })
207
+
208
+ test('.entries() with a second parameter does not take it as the index', () => {
209
+ const { node, ctx } = mapCallOf(component('{items.entries().map(([i, it], extra) => <li key={it.id}>{i}</li>)}'))
210
+ const row = resolveLoopRowParams(arrowOf(node), resolveLoopSource(node, ctx, false), ctx)
211
+ expect(row.index).toBe('i')
212
+ expect(row.indexType).toBeUndefined()
213
+ })
214
+ })
215
+
216
+ describe('transformLoopCallbackBody — what the row renders', () => {
217
+ test('a JSX expression body is the row', () => {
218
+ const { body } = lowerBody(component('{items.map(it => <li key={it.id}>{it.name}</li>)}'))
219
+ expect(body.children.map(c => c.type)).toEqual(['element'])
220
+ expect(body.preamble).toBeUndefined()
221
+ expect(body.flatMapCallback).toBeUndefined()
222
+ })
223
+
224
+ test('a parenthesized ternary body folds to a conditional', () => {
225
+ const { body } = lowerBody(component('{items.map(it => (it.id > 1 ? <li key={it.id}>a</li> : <b key={it.id}>b</b>))}'))
226
+ expect(body.children.map(c => c.type)).toEqual(['conditional'])
227
+ })
228
+
229
+ test('a renderable && body lowers through the JSX expression transformer (#1665)', () => {
230
+ const { body } = lowerBody(component('{items.map(it => it.id > 1 && <li key={it.id}>{it.name}</li>)}'))
231
+ expect(body.children).toHaveLength(1)
232
+ expect(body.children[0].type).toBe('conditional')
233
+ })
234
+
235
+ test('a scalar body produces no children', () => {
236
+ const { body, ctx } = lowerBody(component('{items.map(it => it.name)}'))
237
+ expect(body.children).toHaveLength(0)
238
+ expect(ctx.analyzer.errors).toHaveLength(0)
239
+ })
240
+
241
+ test('a single-return block body carries the value preamble', () => {
242
+ const { body } = lowerBody(
243
+ component('{items.map(it => { const label = it.name.toUpperCase(); return <li key={it.id}>{label}</li> })}'),
244
+ )
245
+ expect(body.children.map(c => c.type)).toEqual(['element'])
246
+ expect(body.preamble?.declaredNames).toEqual(['label'])
247
+ expect(body.preamble?.builderNames).toEqual([])
248
+ })
249
+
250
+ test('a multi-return block body folds to a conditional and keeps its leading preamble', () => {
251
+ const { body } = lowerBody(
252
+ component(
253
+ '{items.map(it => { const n = it.name; if (it.id > 1) return <li key={it.id}>{n}</li>; return <b key={it.id}>{n}</b> })}',
254
+ ),
255
+ )
256
+ expect(body.children.map(c => c.type)).toEqual(['conditional'])
257
+ expect(body.preamble?.declaredNames).toEqual(['n'])
258
+ })
259
+
260
+ test('a non-declaration preamble is refused for a DSL target, accepted for a JS runtime', () => {
261
+ const src = component('{items.map(it => { let n = it.name; n = n + "!"; return <li key={it.id}>{n}</li> })}')
262
+ const dsl = lowerBody(src)
263
+ expect(dsl.body.preamble?.declarations).toBeUndefined()
264
+ expect(dsl.ctx.analyzer.errors.map(e => e.code)).toEqual(['BF021'])
265
+ const { node, ctx } = mapCallOf(src)
266
+ ctx.analyzer.acceptsCallbackBody = () => true
267
+ const callback = arrowOf(node)
268
+ const row = resolveLoopRowParams(callback, resolveLoopSource(node, ctx, false), ctx)
269
+ withLoopRowScope(ctx, row, (savedScope) => transformLoopCallbackBody(callback, row, savedScope, ctx, false, 'map'))
270
+ expect(ctx.analyzer.errors).toHaveLength(0)
271
+ })
272
+
273
+ test('a JSX-building preamble needs an element root to host the built array', () => {
274
+ const { body, ctx } = lowerBody(
275
+ component('{items.map(it => { const out = []; out.push(<b>{it.name}</b>); return out })}'),
276
+ )
277
+ expect(body.children).toHaveLength(0)
278
+ expect(ctx.analyzer.errors).toHaveLength(1)
279
+ expect(ctx.analyzer.errors[0].message).toContain('no element root')
280
+ })
281
+
282
+ test('a JSX-building preamble is refused for a DSL target with the @client escape', () => {
283
+ const { body, ctx } = lowerBody(
284
+ component('{items.map(it => { const out = []; out.push(<b>{it.name}</b>); return <li key={it.id}>{out}</li> })}'),
285
+ )
286
+ expect(body.children).toHaveLength(1)
287
+ expect(body.preamble).toBeUndefined()
288
+ expect(ctx.analyzer.errors[0].message).toContain('cannot be lowered to a template on this backend')
289
+ })
290
+
291
+ test('a JSX-building preamble is carried as segments under /* @client */', () => {
292
+ const { body, ctx } = lowerBody(
293
+ component('{items.map(it => { const out = []; out.push(<b>{it.name}</b>); return <li key={it.id}>{out}</li> })}'),
294
+ 'map',
295
+ true,
296
+ )
297
+ expect(ctx.analyzer.errors).toHaveLength(0)
298
+ expect(body.preamble?.builderNames).toEqual(['out'])
299
+ })
300
+
301
+ test('a preamble local shadowing a prop is bound while the return expression is transformed', () => {
302
+ const { body } = lowerBody(
303
+ component(
304
+ '{items.map(it => { const title = it.name; return <li key={it.id}>{title}</li> })}',
305
+ '{ items, title }: { items: Array<{ id: number; name: string }>; title: string }',
306
+ ),
307
+ )
308
+ const li = body.children[0]
309
+ expect(li.type).toBe('element')
310
+ const text = li.type === 'element' ? li.children.find(c => c.type === 'expression') : undefined
311
+ expect(text?.type === 'expression' ? text.expr : null).toBe('title')
312
+ // Not the outer prop's `_p.title`: the row-local wins inside the window.
313
+ expect(text?.type === 'expression' ? text.templateExpr : null).not.toBe('_p.title')
314
+ })
315
+
316
+ test('flatMap with an array literal body renders every element as a row root', () => {
317
+ const { body } = lowerBody(component('{items.flatMap(it => [<li key={it.id}>a</li>, <li key={it.id + "b"}>b</li>])}'), 'flatMap')
318
+ expect(body.children.map(c => c.type)).toEqual(['element', 'element'])
319
+ expect(body.flatMapCallback).toBeUndefined()
320
+ })
321
+
322
+ test('flatMap with a nested projection lowers to a neutral inner loop', () => {
323
+ const { body } = lowerBody(
324
+ component(
325
+ '{items.flatMap(it => it.tags.map(tag => <li key={tag}>{tag}</li>))}',
326
+ '{ items }: { items: Array<{ id: number; tags: string[] }> }',
327
+ ),
328
+ 'flatMap',
329
+ )
330
+ expect(body.children.map(c => c.type)).toEqual(['loop'])
331
+ expect(body.flatMapCallback).toBeUndefined()
332
+ })
333
+
334
+ test('flatMap with statements rides the segments carrier and is refused for a DSL target', () => {
335
+ const { body, ctx } = lowerBody(
336
+ component(
337
+ '{items.flatMap(it => { if (it.tags.length === 0) return []; return it.tags.map(tag => <li key={tag}>{tag}</li>) })}',
338
+ '{ items }: { items: Array<{ id: number; tags: string[] }> }',
339
+ ),
340
+ 'flatMap',
341
+ )
342
+ expect(body.children).toHaveLength(0)
343
+ expect(body.flatMapCallback).toBeDefined()
344
+ expect(body.preamble).toBeUndefined()
345
+ // The single-return path's value-preamble gate fires first (the early
346
+ // `return []` is not a declaration), then the flatMap carrier's own gate.
347
+ expect(ctx.analyzer.errors.map(e => e.message)).toEqual([
348
+ expect.stringContaining('callback preamble that is not a sequence of value declarations'),
349
+ expect.stringContaining('.flatMap() callback body with statements'),
350
+ ])
351
+ })
352
+ })
353
+
354
+ describe('refuseUnloweredJsxCallback — the structural net', () => {
355
+ test('an inline JSX body no recognizer lowered is a loud diagnostic', () => {
356
+ const { node, ctx } = mapCallOf(component('{items.map(it => wrap(<li key={it.id}>{it.name}</li>))}'))
357
+ refuseUnloweredJsxCallback(node, ctx, 'map', 0)
358
+ expect(ctx.analyzer.errors).toHaveLength(1)
359
+ expect(ctx.analyzer.errors[0].message).toContain('.map() callback that builds JSX in this shape')
360
+ })
361
+
362
+ test('a JSX-helper call body carries no inline JSX and stays silent', () => {
363
+ const { node, ctx } = mapCallOf(component('{items.map(it => renderItem(it))}'))
364
+ refuseUnloweredJsxCallback(node, ctx, 'map', 0)
365
+ expect(ctx.analyzer.errors).toHaveLength(0)
366
+ })
367
+
368
+ test('a more specific refusal fired during this call is not stacked on', () => {
369
+ const { node, ctx } = mapCallOf(component('{items.map(it => wrap(<li key={it.id}>{it.name}</li>))}'))
370
+ ctx.analyzer.errors.push({ code: 'BF021', message: 'earlier', severity: 'error', loc: { file: 'Test.tsx', line: 1, column: 1 } })
371
+ refuseUnloweredJsxCallback(node, ctx, 'map', 0)
372
+ expect(ctx.analyzer.errors).toHaveLength(1)
373
+ })
374
+ })
375
+
376
+ describe('resolveLoopKey — the keyFn and the key attribute', () => {
377
+ test('the first child’s key is the keyFn and is stamped as the depth-0 key attribute', () => {
378
+ const { callback, body, ctx } = lowerBody(component('{items.map(it => <li key={it.id}>{it.name}</li>)}'))
379
+ const key = resolveLoopKey(callback, body.children, ctx, false, 0)
380
+ expect(key).toEqual({ key: 'it.id', bodyIsItemConditional: false })
381
+ const li = body.children[0]
382
+ expect(li.type === 'element' ? li.keyAttr?.name : null).toBe('data-key')
383
+ expect(ctx.analyzer.errors).toHaveLength(0)
384
+ })
385
+
386
+ test('a nested loop stamps the depth-1 key attribute', () => {
387
+ const { callback, body, ctx } = lowerBody(component('{items.map(it => <li key={it.id}>{it.name}</li>)}'))
388
+ resolveLoopKey(callback, body.children, ctx, true, 1)
389
+ const li = body.children[0]
390
+ expect(li.type === 'element' ? li.keyAttr?.name : null).toBe('data-key-1')
391
+ })
392
+
393
+ test('a missing key is BF023 at the top level and BF024 when nested', () => {
394
+ const top = lowerBody(component('{items.map(it => <li>{it.name}</li>)}'))
395
+ resolveLoopKey(top.callback, top.body.children, top.ctx, false, 0)
396
+ expect(top.ctx.analyzer.errors.map(e => e.code)).toEqual(['BF023'])
397
+ const nested = lowerBody(component('{items.map(it => <li>{it.name}</li>)}'))
398
+ resolveLoopKey(nested.callback, nested.body.children, nested.ctx, true, 1)
399
+ expect(nested.ctx.analyzer.errors.map(e => e.code)).toEqual(['BF024'])
400
+ })
401
+
402
+ test('a whole-item conditional hoists the key from its rendering branch (#1665)', () => {
403
+ const { callback, body, ctx } = lowerBody(component('{items.map(it => it.id > 1 && <li key={it.id}>{it.name}</li>)}'))
404
+ const key = resolveLoopKey(callback, body.children, ctx, false, 0)
405
+ expect(key).toEqual({ key: 'it.id', bodyIsItemConditional: true })
406
+ })
407
+
408
+ test('a ternary whose branches agree on the key lifts it (#1098)', () => {
409
+ const { callback, body, ctx } = lowerBody(component('{items.map(it => it.id > 1 ? <li key={it.id}>a</li> : <b key={it.id}>b</b>)}'))
410
+ expect(resolveLoopKey(callback, body.children, ctx, false, 0).key).toBe('it.id')
411
+ })
412
+ })
413
+
414
+ describe('applyPreambleBuilderPasses — the built element array', () => {
415
+ test('a component root fed by a JSX-building preamble is refused and the preamble dropped', () => {
416
+ const { node, body, ctx } = lowerBody(
417
+ `
418
+ function Row(props: { cells: unknown }) { return <tr>{props.cells}</tr> }
419
+ function Test({ items }: { items: Array<{ id: number; name: string }> }) {
420
+ return <table>{items.map(it => { const out = []; out.push(<td>{it.name}</td>); return <Row key={it.id} cells={out} /> })}</table>
421
+ }
422
+ export { Test }
423
+ `,
424
+ 'map',
425
+ true,
426
+ )
427
+ expect(body.children.map(c => c.type)).toEqual(['component'])
428
+ const kept = applyPreambleBuilderPasses(node, body.children, body.preamble, ctx)
429
+ expect(kept).toBeUndefined()
430
+ expect(ctx.analyzer.errors.map(e => e.message)).toEqual([expect.stringContaining('cannot return a component')])
431
+ })
432
+
433
+ test('a value-only preamble passes through untouched', () => {
434
+ const { node, body, ctx } = lowerBody(
435
+ component('{items.map(it => { const label = it.name; return <li key={it.id}>{label}</li> })}'),
436
+ )
437
+ expect(applyPreambleBuilderPasses(node, body.children, body.preamble, ctx)).toBe(body.preamble)
438
+ })
439
+ })
440
+
441
+ describe('classifyLoopArray — static vs reconciled', () => {
442
+ test('a prop array is prop-derived, not static', () => {
443
+ const { node, ctx } = mapCallOf(component('{items.map(it => <li key={it.id}>{it.name}</li>)}'))
444
+ const kind = classifyLoopArray(resolveLoopSource(node, ctx, false), 'map', ctx)
445
+ expect(kind).toEqual({ callsReactive: false, hasCalls: false, isDirectPropArray: true, isStaticArray: false })
446
+ })
447
+
448
+ test('a signal array calls a reactive getter', () => {
449
+ const { node, ctx } = mapCallOf(`
450
+ 'use client'
451
+ import { createSignal } from '@barefootjs/client'
452
+ function Test() {
453
+ const [items, setItems] = createSignal([{ id: 1, name: 'a' }])
454
+ return <ul>{items().map(it => <li key={it.id}>{it.name}</li>)}</ul>
455
+ }
456
+ export { Test }
457
+ `)
458
+ const kind = classifyLoopArray(resolveLoopSource(node, ctx, false), 'map', ctx)
459
+ expect(kind.callsReactive).toBe(true)
460
+ expect(kind.hasCalls).toBe(true)
461
+ expect(kind.isStaticArray).toBe(false)
462
+ })
463
+
464
+ test('an unrecognised call is reconciled rather than frozen (#943)', () => {
465
+ const { node, ctx } = mapCallOf(`
466
+ import { getItems } from './items'
467
+ function Test() {
468
+ return <ul>{getItems().map(it => <li key={it.id}>{it.name}</li>)}</ul>
469
+ }
470
+ export { Test }
471
+ `)
472
+ const kind = classifyLoopArray(resolveLoopSource(node, ctx, false), 'map', ctx)
473
+ expect(kind.callsReactive).toBe(false)
474
+ expect(kind.hasCalls).toBe(true)
475
+ expect(kind.isStaticArray).toBe(false)
476
+ })
477
+
478
+ test('a module-scope const array is static', () => {
479
+ const { node, ctx } = mapCallOf(`
480
+ const ITEMS = [{ id: 1, name: 'a' }]
481
+ function Test() {
482
+ return <ul>{ITEMS.map(it => <li key={it.id}>{it.name}</li>)}</ul>
483
+ }
484
+ export { Test }
485
+ `)
486
+ expect(classifyLoopArray(resolveLoopSource(node, ctx, false), 'map', ctx).isStaticArray).toBe(true)
487
+ })
488
+
489
+ test('Object.entries over a const object is never static (#2168)', () => {
490
+ const { node, ctx } = mapCallOf(`
491
+ const DICT = { a: 'x' }
492
+ function Test() {
493
+ return <ul>{Object.entries(DICT).map(([k, v]) => <li key={k}>{v}</li>)}</ul>
494
+ }
495
+ export { Test }
496
+ `)
497
+ expect(classifyLoopArray(resolveLoopSource(node, ctx, false), 'map', ctx).isStaticArray).toBe(false)
498
+ })
499
+ })
500
+
501
+ describe('transformMapCall — the coordinator', () => {
502
+ test('assembles the decisions into one IRLoop', () => {
503
+ const analyzer = analyzeComponent(
504
+ component('{items.filter(it => it.id > 1).map((it, i) => <li key={it.id}>{i}: {it.name}</li>)}'),
505
+ 'Test.tsx',
506
+ )
507
+ const { jsxToIR } = require('../jsx-to-ir') as typeof import('../jsx-to-ir')
508
+ const root = jsxToIR(analyzer)
509
+ const loop = root?.type === 'element' ? (root.children.find(c => c.type === 'loop') as IRLoop | undefined) : undefined
510
+ expect(loop).toBeDefined()
511
+ expect(loop?.array).toBe('items')
512
+ expect(loop?.filterPredicate?.raw).toBe('it.id > 1')
513
+ expect(loop?.param).toBe('it')
514
+ expect(loop?.index).toBe('i')
515
+ expect(loop?.key).toBe('it.id')
516
+ expect(loop?.depth).toBe(0)
517
+ expect(loop?.markerId).toBe('l0')
518
+ expect(loop?.isPropDerivedArray).toBe(true)
519
+ expect(loop?.isStaticArray).toBe(false)
520
+ })
521
+ })
@@ -2,6 +2,7 @@ import { describe, test, expect } from 'bun:test'
2
2
  import { analyzeComponent } from '../analyzer'
3
3
  import { parseExpression } from '../expression-parser'
4
4
  import {
5
+ arithmeticOperandCoercion,
5
6
  attrValueMayBeNullish,
6
7
  collectNullableSignalGetters,
7
8
  collectNullishAttrContext,
@@ -122,3 +123,47 @@ describe('attrValueMayBeNullish (#3322)', () => {
122
123
  expect(mayBe('nested()', ['s', 'label'])).toBe(true)
123
124
  })
124
125
  })
126
+
127
+ describe('arithmeticOperandCoercion (#3474)', () => {
128
+ function ctxOf(signature: string, decls = ''): ReturnType<typeof collectNullishAttrContext> {
129
+ const source = `
130
+ 'use client'
131
+ import { createSignal } from '@barefootjs/client'
132
+ export function C(${signature}) {
133
+ ${decls}
134
+ return <p>x</p>
135
+ }
136
+ `
137
+ const metadata = analyzeComponent(source, 'C.tsx')
138
+ return collectNullishAttrContext({ metadata } as unknown as ComponentIR)
139
+ }
140
+ const coercion = (ctx: ReturnType<typeof collectNullishAttrContext>, op: string, operand: string, other: string) =>
141
+ arithmeticOperandCoercion(op, parseExpression(operand), parseExpression(other), ctx)
142
+
143
+ test('a nullable number prop reads as null under every arithmetic operator, + with a number included', () => {
144
+ const ctx = ctxOf('props: { a: number | null; b?: number; c: number; d: string | null }')
145
+ for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.a', 'x')).toBe('null')
146
+ expect(coercion(ctx, '+', 'props.a', '1')).toBe('null')
147
+ expect(coercion(ctx, '+', 'props.b', '-2')).toBe('null')
148
+ expect(coercion(ctx, '*', 'props.c', '2')).toBeNull()
149
+ expect(coercion(ctx, '*', 'props.d', '2')).toBeNull()
150
+ })
151
+
152
+ test('+ is left alone unless the other operand is a number: it may concatenate', () => {
153
+ const ctx = ctxOf('props: { a: number | null }', 'const [n] = createSignal<number | null>(null)')
154
+ expect(coercion(ctx, '+', 'props.a', 'label')).toBeNull()
155
+ expect(coercion(ctx, '+', "props.a", "'px'")).toBeNull()
156
+ expect(coercion(ctx, '+', 'n()', '1')).toBe('null')
157
+ })
158
+
159
+ test('a destructured nullable number prop, and a shadowed one', () => {
160
+ const ctx = ctxOf('{ a }: { a?: number }')
161
+ expect(coercion(ctx, '*', 'a', '2')).toBe('null')
162
+ expect(arithmeticOperandCoercion('*', parseExpression('a'), parseExpression('2'), ctx, n => n === 'a')).toBeNull()
163
+ })
164
+
165
+ test('a defaulted prop is not nullable; an undefined-seeded signal keeps its NaN coercion', () => {
166
+ expect(coercion(ctxOf('{ a = 1 }: { a?: number }'), '*', 'a', '2')).toBeNull()
167
+ expect(coercion(ctxOf('', 'const [t] = createSignal<number>()'), '+', 't()', '1')).toBe('undefined')
168
+ })
169
+ })