@barefootjs/jsx 0.39.2 → 0.39.4

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 (98) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -0
  2. package/dist/adapters/boolean-result.d.ts.map +1 -0
  3. package/dist/adapters/line-statement-text.d.ts +17 -0
  4. package/dist/adapters/line-statement-text.d.ts.map +1 -0
  5. package/dist/analyzer.d.ts +1 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/augment-inherited-props.d.ts +20 -0
  8. package/dist/augment-inherited-props.d.ts.map +1 -1
  9. package/dist/errors.d.ts +1 -0
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/html-types.d.ts +15 -0
  12. package/dist/html-types.d.ts.map +1 -1
  13. package/dist/index.d.ts +6 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +595 -140
  16. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +5 -0
  20. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  22. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  24. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  26. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -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/composite-loop.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +14 -0
  31. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/imports.d.ts +2 -2
  34. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  36. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  39. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/types.d.ts +12 -0
  41. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/nullable-signal-attr.d.ts +94 -0
  44. package/dist/nullable-signal-attr.d.ts.map +1 -0
  45. package/dist/profiler.d.ts +9 -1
  46. package/dist/profiler.d.ts.map +1 -1
  47. package/dist/scope/root-prop-alias.d.ts +43 -0
  48. package/dist/scope/root-prop-alias.d.ts.map +1 -0
  49. package/package.json +2 -2
  50. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  51. package/src/__tests__/attribute-fallback-wrap.test.ts +24 -0
  52. package/src/__tests__/boolean-result.test.ts +27 -0
  53. package/src/__tests__/compiler-stress-1244.test.ts +10 -13
  54. package/src/__tests__/conditional-fallback-wrap.test.ts +20 -0
  55. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  56. package/src/__tests__/html-event-handler-names.test.ts +107 -0
  57. package/src/__tests__/line-statement-text.test.ts +25 -0
  58. package/src/__tests__/lookup-literal-const.test.ts +46 -0
  59. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +66 -19
  60. package/src/__tests__/nullable-signal-attr.test.ts +124 -0
  61. package/src/__tests__/profile-binding-ids.test.ts +102 -0
  62. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  63. package/src/__tests__/profiler.test.ts +10 -9
  64. package/src/__tests__/root-prop-alias.test.ts +62 -0
  65. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  66. package/src/adapters/boolean-result.ts +89 -0
  67. package/src/adapters/line-statement-text.ts +24 -0
  68. package/src/analyzer.ts +50 -26
  69. package/src/augment-inherited-props.ts +49 -0
  70. package/src/errors.ts +11 -0
  71. package/src/html-types.ts +15 -0
  72. package/src/index.ts +16 -2
  73. package/src/ir-to-client-js/collect-elements.ts +18 -4
  74. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +2 -2
  75. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  76. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  77. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +7 -2
  78. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  79. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  80. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  81. package/src/ir-to-client-js/control-flow/shared.ts +2 -0
  82. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  83. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  84. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  85. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  86. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  87. package/src/ir-to-client-js/html-template.ts +59 -8
  88. package/src/ir-to-client-js/imports.ts +3 -1
  89. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  90. package/src/ir-to-client-js/reactivity.ts +1 -0
  91. package/src/ir-to-client-js/safe-html.ts +10 -0
  92. package/src/ir-to-client-js/stringify/declaration-emit.ts +5 -5
  93. package/src/ir-to-client-js/types.ts +12 -0
  94. package/src/ir-to-client-js/utils.ts +88 -117
  95. package/src/jsx-to-ir.ts +145 -32
  96. package/src/nullable-signal-attr.ts +202 -0
  97. package/src/profiler.ts +79 -10
  98. package/src/scope/root-prop-alias.ts +81 -0
@@ -0,0 +1,124 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer'
3
+ import { parseExpression } from '../expression-parser'
4
+ import {
5
+ attrValueMayBeNullish,
6
+ collectNullableSignalGetters,
7
+ collectNullishAttrContext,
8
+ nullableSignalAttrGetter,
9
+ } from '../nullable-signal-attr'
10
+ import type { ComponentIR } from '../types'
11
+
12
+ function nullableGetters(decls: string): Set<string> {
13
+ const source = `
14
+ 'use client'
15
+ import { createSignal } from '@barefootjs/client'
16
+ export function C() {
17
+ ${decls}
18
+ return <p>x</p>
19
+ }
20
+ `
21
+ const metadata = analyzeComponent(source, 'C.tsx')
22
+ return collectNullableSignalGetters({ metadata } as unknown as ComponentIR)
23
+ }
24
+
25
+ describe('collectNullableSignalGetters (#3304)', () => {
26
+ test('a zero-arg typed signal is nullable', () => {
27
+ expect([...nullableGetters('const [a] = createSignal<number>()')]).toEqual(['a'])
28
+ })
29
+
30
+ test('a type admitting undefined or null is nullable, whatever the initial value', () => {
31
+ expect([...nullableGetters(`
32
+ const [a] = createSignal<string | undefined>(undefined)
33
+ const [b] = createSignal<string | null>('x')
34
+ `)].sort()).toEqual(['a', 'b'])
35
+ })
36
+
37
+ test('an untyped literal undefined or null initial value is nullable', () => {
38
+ expect([...nullableGetters(`
39
+ const [a] = createSignal(undefined)
40
+ const [b] = createSignal(null)
41
+ `)].sort()).toEqual(['a', 'b'])
42
+ })
43
+
44
+ test('a non-nullable typed or inferred signal is not', () => {
45
+ expect([...nullableGetters(`
46
+ const [a] = createSignal('x')
47
+ const [b] = createSignal<number>(0)
48
+ `)]).toEqual([])
49
+ })
50
+ })
51
+
52
+ describe('nullableSignalAttrGetter (#3304)', () => {
53
+ const nullable = new Set(['s'])
54
+
55
+ test('matches a bare zero-arg read of a nullable signal', () => {
56
+ expect(nullableSignalAttrGetter(parseExpression('s()'), nullable)).toBe('s')
57
+ })
58
+
59
+ test('does not match any other shape', () => {
60
+ for (const expr of ['t()', 's', 's(1)', 's()?.x', "s() ?? 'a'", 'a ? s() : b']) {
61
+ expect(nullableSignalAttrGetter(parseExpression(expr), nullable)).toBeNull()
62
+ }
63
+ })
64
+ })
65
+
66
+ describe('attrValueMayBeNullish (#3322)', () => {
67
+ const source = `
68
+ 'use client'
69
+ import { createMemo, createSignal } from '@barefootjs/client'
70
+ export function C() {
71
+ const [s] = createSignal<string | undefined>(undefined)
72
+ const [t] = createSignal('x')
73
+ const [user] = createSignal<{ name?: string }>({})
74
+ const label = createMemo(() => s())
75
+ const nested = createMemo(() => label())
76
+ const plain = createMemo(() => t())
77
+ const typed = createMemo<string | undefined>(() => t())
78
+ const loop = createMemo(() => loop())
79
+ return <p>x</p>
80
+ }
81
+ `
82
+ const ctx = collectNullishAttrContext({ metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR)
83
+ const mayBe = (expr: string, shadowed: string[] = []) =>
84
+ attrValueMayBeNullish(parseExpression(expr), ctx, name => shadowed.includes(name))
85
+
86
+ test('a nullable signal or a memo over one, however deep', () => {
87
+ for (const expr of ['s()', 'label()', 'nested()', 'typed()']) expect(mayBe(expr)).toBe(true)
88
+ })
89
+
90
+ test('a memo over a present value, or a self-referencing memo, is not', () => {
91
+ for (const expr of ['t()', 'plain()', 'loop()']) expect(mayBe(expr)).toBe(false)
92
+ })
93
+
94
+ test('an optional member read, or a member of a nullable value', () => {
95
+ expect(mayBe('user()?.name')).toBe(true)
96
+ expect(mayBe('label().length')).toBe(true)
97
+ expect(mayBe('user().name')).toBe(false)
98
+ })
99
+
100
+ test('a ternary or logical operand the result can be', () => {
101
+ expect(mayBe("t() ? s() : 'a'")).toBe(true)
102
+ expect(mayBe("t() ? 'a' : label()")).toBe(true)
103
+ expect(mayBe("s() ? 'a' : 'b'")).toBe(false)
104
+ expect(mayBe("s() ?? 'a'")).toBe(false)
105
+ expect(mayBe("t() || s()")).toBe(true)
106
+ expect(mayBe("s() && 'a'")).toBe(true)
107
+ })
108
+
109
+ test('literal undefined / null, and nothing else', () => {
110
+ expect(mayBe('undefined')).toBe(true)
111
+ expect(mayBe('null')).toBe(true)
112
+ expect(mayBe("''")).toBe(false)
113
+ expect(mayBe('0')).toBe(false)
114
+ })
115
+
116
+ test('a getter a loop binding shadows is not the signal or memo', () => {
117
+ expect(mayBe('label()', ['label'])).toBe(false)
118
+ })
119
+
120
+ test("a memo's body reads its getters where the memo is declared, not where it is read", () => {
121
+ expect(mayBe('label()', ['s'])).toBe(true)
122
+ expect(mayBe('nested()', ['s', 'label'])).toBe(true)
123
+ })
124
+ })
@@ -7,9 +7,11 @@
7
7
  */
8
8
 
9
9
  import { describe, test, expect } from 'bun:test'
10
+ import ts from 'typescript'
10
11
  import { compileJSX } from '../compiler'
11
12
  import { TestAdapter } from '../adapters/test-adapter'
12
13
  import { buildIdIndex } from '../profiler'
14
+ import { analyzeComponent } from '../analyzer'
13
15
  import { buildComponentAnalysis } from '../debug'
14
16
 
15
17
  const adapter = new TestAdapter()
@@ -121,3 +123,103 @@ describe('binding-effect ids', () => {
121
123
  expect(node.loc.line).toBeGreaterThan(0)
122
124
  })
123
125
  })
126
+
127
+ describe('a zero-arg createSignal() emits valid client JS (#3217)', () => {
128
+ const zeroArgSource = `
129
+ 'use client'
130
+ import { createSignal } from '@barefootjs/client'
131
+ export function Empty() {
132
+ const [v, setV] = createSignal<string>()
133
+ return <button onClick={() => setV('x')}>{v() ?? '-'}</button>
134
+ }
135
+ `
136
+
137
+ function emit(profile: boolean): string {
138
+ return compileJSX(zeroArgSource, 'Empty.tsx', { adapter, profile })
139
+ .files.find(f => f.type === 'clientJs')!.content
140
+ }
141
+
142
+ function parseErrors(js: string): string[] {
143
+ const diagnostics = ts.transpileModule(js, {
144
+ reportDiagnostics: true,
145
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest },
146
+ }).diagnostics ?? []
147
+ return diagnostics
148
+ .filter(d => d.category === ts.DiagnosticCategory.Error)
149
+ .map(d => ts.flattenDiagnosticMessageText(d.messageText, '\n'))
150
+ }
151
+
152
+ test('profile on: the signal id follows an explicit `undefined`, not a bare comma', () => {
153
+ const on = emit(true)
154
+ expect(on).toContain('createSignal(undefined, "Empty#signal:v")')
155
+ expect(on).not.toContain('createSignal(,')
156
+ expect(parseErrors(on)).toEqual([])
157
+ })
158
+
159
+ test('profile off: the call and the template both carry an explicit `undefined`', () => {
160
+ // The CSR template substitutes `v()` with the signal's initial value.
161
+ // An empty one used to inline as `()`, so the module failed to parse
162
+ // even without profiling.
163
+ const off = emit(false)
164
+ expect(off).toContain('createSignal(undefined)')
165
+ expect(off).toContain("escapeTextOrMarkup((undefined) ?? '-')")
166
+ expect(parseErrors(off)).toEqual([])
167
+ })
168
+ })
169
+
170
+ describe('the analyzer records `undefined` for a zero-arg createSignal() (#3215)', () => {
171
+ // One decision at the source: every emitter (SSR getter, CSR template,
172
+ // client-JS call) splices `initialValue` into an expression, so an empty
173
+ // string there is an empty operand in each of them.
174
+ const shapes: Array<[string, string]> = [
175
+ ['array destructure', 'const [v, setV] = createSignal<string>()'],
176
+ ['tuple ref + index access', 'const s = createSignal<string>(); const v = s[0]; const setV = s[1]'],
177
+ ['direct index access', 'const v = createSignal<string>()[0]; const setV = createSignal<string>()[1]'],
178
+ ]
179
+ for (const [label, decl] of shapes) {
180
+ test(label, () => {
181
+ const source = `
182
+ 'use client'
183
+ import { createSignal } from '@barefootjs/client'
184
+ export function Empty() {
185
+ ${decl}
186
+ return <button onClick={() => setV('x')}>{v() ?? '-'}</button>
187
+ }
188
+ `
189
+ const signals = analyzeComponent(source, 'Empty.tsx').signals
190
+ expect(signals.length).toBeGreaterThan(0)
191
+ for (const signal of signals) {
192
+ expect(signal.initialValue).toBe('undefined')
193
+ // The zero-arg overload's `T | undefined`, so a typed backend seeds
194
+ // nil rather than the type's zero value.
195
+ expect(signal.type.raw).toBe('string | undefined')
196
+ }
197
+ })
198
+ }
199
+
200
+ test('a type argument that already admits undefined is not widened again', () => {
201
+ const source = `
202
+ 'use client'
203
+ import { createSignal } from '@barefootjs/client'
204
+ export function Empty() {
205
+ const [v] = createSignal<'a' | 'b' | undefined>()
206
+ return <p>{v() ?? '-'}</p>
207
+ }
208
+ `
209
+ const [signal] = analyzeComponent(source, 'Empty.tsx').signals
210
+ expect(signal.type.raw).toBe("'a' | 'b' | undefined")
211
+ })
212
+
213
+ test('an explicit initial value keeps the type argument as written', () => {
214
+ const source = `
215
+ 'use client'
216
+ import { createSignal } from '@barefootjs/client'
217
+ export function Empty() {
218
+ const [v] = createSignal<string>('x')
219
+ return <p>{v()}</p>
220
+ }
221
+ `
222
+ const [signal] = analyzeComponent(source, 'Empty.tsx').signals
223
+ expect(signal.type.raw).toBe('string')
224
+ })
225
+ })
@@ -52,3 +52,25 @@ describe('profile mode on (SR3)', () => {
52
52
  expect(importLine).toContain('endTurn')
53
53
  })
54
54
  })
55
+
56
+ describe('rest-spread event forwarding (#3376)', () => {
57
+ const spread = `
58
+ 'use client'
59
+ interface Props { onClick?: () => void }
60
+ export function SpreadButton(props: Props) {
61
+ return <button {...props}>Increment</button>
62
+ }
63
+ `
64
+ const compile = (profile: boolean) =>
65
+ compileJSX(spread, 'SpreadButton.tsx', { adapter, profile }).files.find(f => f.type === 'clientJs')!.content
66
+
67
+ test('profile mode names the spread site so the runtime can open a turn per handler', () => {
68
+ expect(compile(true)).toContain('applyRestAttrs(_s0, _p, [], "SpreadButton#handler:s0")')
69
+ })
70
+
71
+ test('profile mode off passes no site (zero instrumentation in production)', () => {
72
+ const off = compile(false)
73
+ expect(off).toContain('applyRestAttrs(_s0, _p, [])')
74
+ expect(off).not.toContain('#handler:')
75
+ })
76
+ })
@@ -564,8 +564,9 @@ describe('agent contract: status, findings, guidance (#1841)', () => {
564
564
 
565
565
  test('a clean run is status ok with no findings', () => {
566
566
  n = 0
567
- // One memo run in a turn → runsPerTurn 1 → not hot, nothing flagged.
568
- const turn = 'Calc#handler:s0:click'
567
+ // One memo run in a turn → runsPerTurn 1 → not hot, nothing flagged. The
568
+ // turn id is the button's real handler id, so coverage reads 1/1.
569
+ const turn = 'Calc#handler:s1:click'
569
570
  const events: ProfilerEvent[] = [
570
571
  ev('turnBegin', { handlerId: turn }),
571
572
  ev('effectEnter', { subscriber: 'Calc#memo:a', turn }),
@@ -614,18 +615,18 @@ describe('agent contract: status, findings, guidance (#1841)', () => {
614
615
  expect(gap.nextCommands.every(c => !c.includes('graph Calc'))).toBe(true)
615
616
  })
616
617
 
617
- test('coverage.ratio is clamped to 1 when the stream over-counts handlers', () => {
618
+ test('a turn id the IR does not list joins the inventory, so the ratio stays within 1', () => {
618
619
  n = 0
619
- // Calc exposes a single handler (handlersTotal 1), but a malformed stream
620
- // reports two distinct turn ids — without clamping the ratio would be 2.0
621
- // and silently pass a `--min-coverage` gate it shouldn't.
620
+ // Calc lists a single handler, but the stream reports a second distinct
621
+ // turn id (#3377). It is a handler site that ran, so it counts on both
622
+ // sides: 2/2, never 2/1 — the ratio can't pass a `--min-coverage` gate it
623
+ // shouldn't.
622
624
  const events: ProfilerEvent[] = [
623
- ev('effectEnter', { subscriber: 'Calc#memo:a', turn: 'Calc#handler:s0:click' }),
625
+ ev('effectEnter', { subscriber: 'Calc#memo:a', turn: 'Calc#handler:s1:click' }),
624
626
  ev('effectEnter', { subscriber: 'Calc#memo:a', turn: 'Calc#handler:s9:click' }),
625
627
  ]
626
628
  const r = buildProfileReport({ source: src, filePath: 'Calc.tsx', scenario: 'auto', events })
627
- expect(r.coverage.ratio).toBe(1)
628
- expect(r.coverage.ratio).toBeLessThanOrEqual(1)
629
+ expect(r.coverage).toMatchObject({ handlersFired: 2, handlersTotal: 2, ratio: 1 })
629
630
  })
630
631
 
631
632
  test('a zero-turn run emits guidance pointing at a story file', () => {
@@ -0,0 +1,62 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { BindingScope } from '../scope/binding-scope'
3
+ import { rootPropAliasNames, rootPropAliasesForLoop, rootPropReadName } from '../scope/root-prop-alias'
4
+ import type { ComponentIR } from '../types'
5
+
6
+ function irWith(opts: { localConstants?: string[]; loopParam?: string } = {}): ComponentIR {
7
+ const root = opts.loopParam
8
+ ? { type: 'loop', param: opts.loopParam, children: [] }
9
+ : { type: 'element', children: [] }
10
+ return {
11
+ root,
12
+ metadata: {
13
+ localConstants: (opts.localConstants ?? []).map(name => ({ name })),
14
+ localFunctions: [],
15
+ signals: [],
16
+ memos: [],
17
+ },
18
+ } as unknown as ComponentIR
19
+ }
20
+
21
+ describe('root-prop aliases (#3314)', () => {
22
+ const props = new Set(['value', 'index', 'values'])
23
+ const aliases = rootPropAliasNames(irWith(), props)
24
+ const outer = BindingScope.EMPTY
25
+ const row = outer.enterLoopRow({ param: 'value', index: 'index' })
26
+ const inner = row.enterLoopRow({ param: 'value' })
27
+
28
+ test('a loop row aliases exactly the props it newly shadows', () => {
29
+ expect(rootPropAliasesForLoop(outer, row, aliases)).toEqual([
30
+ { name: 'value', alias: '__bf_root_value' },
31
+ { name: 'index', alias: '__bf_root_index' },
32
+ ])
33
+ })
34
+
35
+ test('a nested loop re-binding an already shadowed name adds no alias', () => {
36
+ expect(rootPropAliasesForLoop(row, inner, aliases)).toEqual([])
37
+ })
38
+
39
+ test('a binding that is not a prop needs no alias', () => {
40
+ expect(rootPropAliasesForLoop(outer, outer.enterLoopRow({ param: 'item' }), aliases)).toEqual([])
41
+ })
42
+
43
+ test('props.X reads the alias only while X is shadowed', () => {
44
+ expect(rootPropReadName('value', outer, aliases)).toBe('value')
45
+ expect(rootPropReadName('value', row, aliases)).toBe('__bf_root_value')
46
+ expect(rootPropReadName('value', inner, aliases)).toBe('__bf_root_value')
47
+ expect(rootPropReadName('values', row, aliases)).toBe('values')
48
+ })
49
+
50
+ test('an alias never takes a name the component already uses', () => {
51
+ expect(rootPropAliasNames(irWith(), ['value', '__bf_root_value']).get('value')).toBe('__bf_root_value_')
52
+ expect(rootPropAliasNames(irWith({ localConstants: ['__bf_root_value'] }), ['value']).get('value')).toBe(
53
+ '__bf_root_value_',
54
+ )
55
+ expect(rootPropAliasNames(irWith({ loopParam: '__bf_root_value' }), ['value']).get('value')).toBe(
56
+ '__bf_root_value_',
57
+ )
58
+ // `value` (bumped past the prop) and `value_` would otherwise share `__bf_root_value_`.
59
+ const both = rootPropAliasNames(irWith(), ['value', '__bf_root_value', 'value_'])
60
+ expect(new Set(both.values()).size).toBe(3)
61
+ })
62
+ })
@@ -28,6 +28,25 @@ function rootFor(src: string, componentName: string): IRNode {
28
28
  return node
29
29
  }
30
30
 
31
+ /** `keyAttr` of every flagged element, in document order. */
32
+ function portalKeyAttrs(node: IRNode): Array<IRElement['keyAttr']> {
33
+ const out: Array<IRElement['keyAttr']> = []
34
+ const visit = (n: IRNode): void => {
35
+ if (n.type === 'element' && (n as IRElement).ssrPortalOwnerScope) out.push((n as IRElement).keyAttr)
36
+ if ('children' in n && Array.isArray((n as { children?: IRNode[] }).children)) {
37
+ for (const c of (n as { children: IRNode[] }).children) visit(c)
38
+ }
39
+ }
40
+ visit(node)
41
+ return out
42
+ }
43
+
44
+ /** Error codes `compileJSX` reports for `src`. */
45
+ function errorCodes(src: string): string[] {
46
+ const result = compileJSX(src.trimStart(), 'T.tsx', { adapter: new TestAdapter() })
47
+ return result.errors.map(e => e.code)
48
+ }
49
+
31
50
  function flaggedRefs(node: IRNode): string[] {
32
51
  const out: string[] = []
33
52
  const visit = (n: IRNode): void => {
@@ -176,18 +195,12 @@ export function Overlay() {
176
195
  expect(flaggedRefs(rootFor(src, 'Overlay'))).toEqual(['handleMount'])
177
196
  })
178
197
 
179
- // BF063 resolves a `ref` name outward through every enclosing function
180
- // scope; the portal recognition keeps the pre-BF063 limit (the callback
181
- // must be declared in the ref's innermost function scope) so sharing the
182
- // resolution does not widen what is recognized. These two tests pin that
183
- // scope limit only. A portal element inside a `.map()` row is broken
184
- // either way — the second test's row-declared callback is still
185
- // recognized and still breaks the row's hydration — which is the
186
- // registered known limitation `loop-row-ref-portal`
187
- // (`packages/adapter-tests/limitations/loop-row-ref-portal.ts`, fixture
188
- // `row-portal-ref`): the control pins today's behaviour as a known gap,
189
- // not as intended behaviour.
190
- test('does not flag a .map() row ref naming a portal callback declared in the component body', () => {
198
+ // The portal recognition shares BF063's resolution, which walks outward
199
+ // through every enclosing function scope (#3318): a `.map()` row ref
200
+ // naming a component-body portal callback is recognized like a
201
+ // row-declared one, and the flagged element carries the row key so
202
+ // hydration can pair it with its row.
203
+ test('flags a .map() row ref naming a portal callback declared in the component body', () => {
191
204
  const ir = root(`
192
205
  'use client'
193
206
  import { createPortal } from '@barefootjs/client'
@@ -196,7 +209,8 @@ export function List(props: { rows: string[] }) {
196
209
  return <ul>{props.rows.map(r => (<li key={r}><div ref={mountContent}>{r}</div></li>))}</ul>
197
210
  }
198
211
  `)
199
- expect(flaggedRefs(ir)).toEqual([])
212
+ expect(flaggedRefs(ir)).toEqual(['mountContent'])
213
+ expect(portalKeyAttrs(ir)).toEqual([{ name: 'data-key', value: 'r' }])
200
214
  })
201
215
 
202
216
  test('still flags a .map() row ref naming a portal callback declared in the row callback itself', () => {
@@ -216,4 +230,65 @@ export function List(props: { rows: string[] }) {
216
230
  `)
217
231
  expect(flaggedRefs(ir)).toEqual(['mountContent'])
218
232
  })
233
+
234
+ describe('row portals (#3318)', () => {
235
+ const portalRow = (loop: string) => `
236
+ 'use client'
237
+ import { createPortal, createSignal } from '@barefootjs/client'
238
+ export function List(props: { rows: string[]; groups: string[][] }) {
239
+ const [open] = createSignal(true)
240
+ const mountContent = (el: HTMLElement) => { createPortal(el, document.body, { ownerScope: 'x' }) }
241
+ return <ul>{${loop}}</ul>
242
+ }
243
+ `
244
+
245
+ test('keys the portaled element of a keyed top-level row without an error', () => {
246
+ expect(errorCodes(portalRow(`props.rows.map(r => <li key={r}><button ref={mountContent}>{r}</button></li>)`))).toEqual([])
247
+ })
248
+
249
+ test('refuses an unkeyed row (BF064)', () => {
250
+ expect(errorCodes(portalRow(`props.rows.map(r => <li><button ref={mountContent}>{r}</button></li>)`))).toContain('BF064')
251
+ })
252
+
253
+ test('refuses a nested row (BF064)', () => {
254
+ expect(
255
+ errorCodes(portalRow(
256
+ `props.groups.map((g, i) => <li key={i}><ol>{g.map(r => <li key={r}><button ref={mountContent}>{r}</button></li>)}</ol></li>)`,
257
+ )),
258
+ ).toContain('BF064')
259
+ })
260
+
261
+ test('refuses a portaled row root (BF064)', () => {
262
+ expect(errorCodes(portalRow(`props.rows.map(r => <button key={r} ref={mountContent}>{r}</button>)`))).toContain('BF064')
263
+ })
264
+
265
+ test('refuses a portaled row root of a nested loop (BF064)', () => {
266
+ expect(
267
+ errorCodes(portalRow(
268
+ `props.groups.map((g, i) => <li key={i}>{g.map(r => <button key={r} ref={mountContent}>{r}</button>)}</li>)`,
269
+ )),
270
+ ).toContain('BF064')
271
+ })
272
+
273
+ test('refuses a portal inside a reactive conditional in the row (BF064)', () => {
274
+ expect(
275
+ errorCodes(portalRow(
276
+ `props.rows.map(r => <li key={r}>{open() ? <button ref={mountContent}>{r}</button> : null}</li>)`,
277
+ )),
278
+ ).toContain('BF064')
279
+ })
280
+
281
+ test('does not touch a portal element outside any loop', () => {
282
+ const ir = root(`
283
+ 'use client'
284
+ import { createPortal } from '@barefootjs/client'
285
+ export function P() {
286
+ const mountContent = (el: HTMLElement) => { createPortal(el, document.body, { ownerScope: 'x' }) }
287
+ return <div><div ref={mountContent} /></div>
288
+ }
289
+ `)
290
+ expect(flaggedRefs(ir)).toEqual(['mountContent'])
291
+ expect(portalKeyAttrs(ir)).toEqual([undefined])
292
+ })
293
+ })
219
294
  })
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Backend-neutral boolean-result classification shared by the adapters whose
3
+ * host language has no boolean type (Mojolicious, Xslate: Perl renders a
4
+ * comparison as `''` / `1` and the literal `false` as `0`). Both adapters
5
+ * route a boolean-shaped attribute value through their `bool_str` runtime
6
+ * helper; this module decides which `ParsedExpr` shapes are boolean-shaped
7
+ * and rewrites a ternary that only PARTLY is (#3349).
8
+ *
9
+ * Detected boolean-result shapes:
10
+ * - `binary` with a comparison operator (`<`, `>`, `<=`, `>=`, `==`,
11
+ * `===`, `!=`, `!==`)
12
+ * - `unary` with logical `!`
13
+ * - `literal` with `literalType: 'boolean'`
14
+ * - `logical` (`&&` / `||` / `??`) when both sides are boolean-result
15
+ * - `conditional` (`?:`) when both branches are boolean-result
16
+ */
17
+
18
+ import type { ParsedExpr } from '../expression-parser.ts'
19
+
20
+ const COMPARISON_OPS = new Set([
21
+ '<',
22
+ '>',
23
+ '<=',
24
+ '>=',
25
+ '==',
26
+ '===',
27
+ '!=',
28
+ '!==',
29
+ ])
30
+
31
+ /** Whether `node` structurally evaluates to a JS boolean. */
32
+ export function isBooleanResultParsed(node: ParsedExpr): boolean {
33
+ switch (node.kind) {
34
+ case 'literal':
35
+ return node.literalType === 'boolean'
36
+ case 'binary':
37
+ return COMPARISON_OPS.has(node.op)
38
+ case 'unary':
39
+ return node.op === '!'
40
+ case 'logical':
41
+ // `x > 0 && y < 10` is boolean; `x() || 'fallback'` is not.
42
+ // Only both-sides-boolean qualifies.
43
+ return (
44
+ isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right)
45
+ )
46
+ case 'conditional':
47
+ // `cond ? bool : bool` is boolean; `cond ? 'a' : 'b'` is not.
48
+ return (
49
+ isBooleanResultParsed(node.consequent) &&
50
+ isBooleanResultParsed(node.alternate)
51
+ )
52
+ default:
53
+ return false
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Rewrites the boolean-result branches of a ternary whose OTHER branch is
59
+ * not boolean (`yes() ? false : s()`), so a taken boolean branch carries
60
+ * JS `String(boolean)` instead of Perl's `0` / `''` / `1` (#3349). The whole
61
+ * value isn't boolean-shaped, so `bool_str` can't wrap it; instead a literal
62
+ * `true` / `false` branch becomes the string literal `'true'` / `'false'`,
63
+ * and any other boolean-result branch `b` becomes `b ? 'true' : 'false'`.
64
+ * The existing ternary lowering then renders the rewritten tree unchanged.
65
+ * Nested ternary branches are rewritten recursively; anything that is not
66
+ * a mixed ternary is returned as is.
67
+ */
68
+ export function stringifyBooleanTernaryBranches(node: ParsedExpr): ParsedExpr {
69
+ if (node.kind !== 'conditional' || isBooleanResultParsed(node)) return node
70
+ return {
71
+ ...node,
72
+ consequent: stringifyBooleanBranch(node.consequent),
73
+ alternate: stringifyBooleanBranch(node.alternate),
74
+ }
75
+ }
76
+
77
+ function stringifyBooleanBranch(branch: ParsedExpr): ParsedExpr {
78
+ if (!isBooleanResultParsed(branch)) return stringifyBooleanTernaryBranches(branch)
79
+ if (branch.kind === 'literal') {
80
+ return { kind: 'literal', value: String(branch.value), literalType: 'string' }
81
+ }
82
+ return {
83
+ kind: 'conditional',
84
+ test: branch,
85
+ consequent: { kind: 'literal', value: 'true', literalType: 'string' },
86
+ alternate: { kind: 'literal', value: 'false', literalType: 'string' },
87
+ }
88
+ }
89
+
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Static text in a template engine with LINE statements — Mojolicious
3
+ * (`% if (…) {`) and Xslate Kolon (`: if (…) {`) — must never begin a
4
+ * template line with the statement sigil: the engine reads such a line as
5
+ * code, so `{c ? 'on' : 'off'} :y` (whose text lands on its own line right
6
+ * after the conditional's closing `: }`) fails to parse, or vanishes when the
7
+ * line happens to parse (#3311).
8
+ *
9
+ * Every sigil that is the first non-blank character of the text or of a line
10
+ * inside it is emitted through `literal` instead — an output expression for
11
+ * the sigil character itself (`<%= '%' %>`, `<: ':' :>`). The text cannot know
12
+ * whether it starts a template line (that depends on what precedes it), so a
13
+ * line-leading sigil is always rewritten; the expression renders the same
14
+ * character either way.
15
+ */
16
+ export function escapeLineStatementSigil(text: string, sigil: string, literal: string): string {
17
+ return text
18
+ .split('\n')
19
+ .map(line => {
20
+ const indent = line.length - line.trimStart().length
21
+ return line.startsWith(sigil, indent) ? line.slice(0, indent) + literal + line.slice(indent + sigil.length) : line
22
+ })
23
+ .join('\n')
24
+ }