@barefootjs/jsx 0.39.7 → 0.39.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/dist/adapters/callback-method.d.ts +36 -7
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +80 -13
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +153 -0
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  7. package/dist/adapters/jsx-adapter.d.ts +4 -0
  8. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  9. package/dist/adapters/literal-value.d.ts +2 -2
  10. package/dist/adapters/literal-value.d.ts.map +1 -1
  11. package/dist/adapters/loop-plan.d.ts +133 -9
  12. package/dist/adapters/loop-plan.d.ts.map +1 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts +44 -0
  14. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  15. package/dist/adapters/style-object.d.ts +33 -0
  16. package/dist/adapters/style-object.d.ts.map +1 -0
  17. package/dist/analyzer.d.ts.map +1 -1
  18. package/dist/assignment-target.d.ts +26 -0
  19. package/dist/assignment-target.d.ts.map +1 -0
  20. package/dist/children-nullish.d.ts +22 -0
  21. package/dist/children-nullish.d.ts.map +1 -0
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/expression-parser.d.ts +9 -19
  25. package/dist/expression-parser.d.ts.map +1 -1
  26. package/dist/free-refs.d.ts +6 -0
  27. package/dist/free-refs.d.ts.map +1 -1
  28. package/dist/index.d.ts +17 -14
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +15040 -13899
  31. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  34. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  36. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  38. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  40. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  42. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  45. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  47. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  49. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  51. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  54. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  56. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/imports.d.ts +23 -2
  58. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/phases/props-extraction.d.ts +6 -3
  60. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  67. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  68. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  70. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  72. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  73. package/dist/ir-to-client-js/types.d.ts +3 -3
  74. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  75. package/dist/ir-to-client-js/utils.d.ts +2 -11
  76. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  77. package/dist/jsx-to-ir.d.ts.map +1 -1
  78. package/dist/nullable-signal-attr.d.ts +40 -10
  79. package/dist/nullable-signal-attr.d.ts.map +1 -1
  80. package/dist/prop-rewrite.d.ts +35 -8
  81. package/dist/prop-rewrite.d.ts.map +1 -1
  82. package/dist/props-binding.d.ts +66 -1
  83. package/dist/props-binding.d.ts.map +1 -1
  84. package/dist/scanner/js-scanner.d.ts.map +1 -1
  85. package/dist/scanner/js-scanner.js +30 -2
  86. package/dist/scope/binding-scope.d.ts +30 -2
  87. package/dist/scope/binding-scope.d.ts.map +1 -1
  88. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  89. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  90. package/dist/signal-prop-name-collision.d.ts +6 -5
  91. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  92. package/dist/ssr-defaults.d.ts +28 -0
  93. package/dist/ssr-defaults.d.ts.map +1 -1
  94. package/dist/ssr-seed-plan.d.ts +39 -14
  95. package/dist/ssr-seed-plan.d.ts.map +1 -1
  96. package/dist/types.d.ts +133 -19
  97. package/dist/types.d.ts.map +1 -1
  98. package/dist/value-references.d.ts +21 -0
  99. package/dist/value-references.d.ts.map +1 -1
  100. package/package.json +2 -2
  101. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  102. package/src/__tests__/adapter-output.test.ts +5 -3
  103. package/src/__tests__/analyzer.test.ts +33 -0
  104. package/src/__tests__/arithmetic-lowering.test.ts +48 -0
  105. package/src/__tests__/binding-scope.test.ts +29 -0
  106. package/src/__tests__/children-read.test.ts +226 -0
  107. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  108. package/src/__tests__/component-props.test.ts +68 -1
  109. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  110. package/src/__tests__/create-query.test.ts +1 -1
  111. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  112. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  113. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  114. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  115. package/src/__tests__/expression-parser.test.ts +1 -44
  116. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  117. package/src/__tests__/loop-plan.test.ts +131 -1
  118. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  119. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  120. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  121. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  122. package/src/__tests__/props-alias-const.test.ts +60 -1
  123. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  124. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  125. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  126. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  127. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  128. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  131. package/src/__tests__/style-object-plan.test.ts +54 -0
  132. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/callback-method.ts +48 -10
  135. package/src/adapters/component-props.ts +130 -12
  136. package/src/adapters/dsl-template-adapter.ts +259 -0
  137. package/src/adapters/jsx-adapter.ts +12 -6
  138. package/src/adapters/literal-value.ts +2 -2
  139. package/src/adapters/loop-plan.ts +201 -13
  140. package/src/adapters/parsed-expr-emitter.ts +67 -0
  141. package/src/adapters/style-object.ts +61 -0
  142. package/src/analyzer.ts +396 -16
  143. package/src/assignment-target.ts +79 -0
  144. package/src/children-nullish.ts +33 -0
  145. package/src/debug.ts +2 -2
  146. package/src/errors.ts +23 -0
  147. package/src/expression-parser.ts +56 -53
  148. package/src/free-refs.ts +28 -17
  149. package/src/index.ts +31 -10
  150. package/src/ir-to-client-js/compute-inlinability.ts +35 -5
  151. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  152. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  153. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  154. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  155. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  156. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  157. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  159. package/src/ir-to-client-js/csr-substitute.ts +82 -24
  160. package/src/ir-to-client-js/emit-reactive.ts +3 -3
  161. package/src/ir-to-client-js/emit-registration.ts +34 -58
  162. package/src/ir-to-client-js/generate-init.ts +17 -1
  163. package/src/ir-to-client-js/html-template.ts +48 -57
  164. package/src/ir-to-client-js/identifiers.ts +75 -24
  165. package/src/ir-to-client-js/imports.ts +56 -19
  166. package/src/ir-to-client-js/index.ts +2 -1
  167. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  168. package/src/ir-to-client-js/phases/props-extraction.ts +39 -17
  169. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  170. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  171. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  172. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  173. package/src/ir-to-client-js/reactivity.ts +2 -2
  174. package/src/ir-to-client-js/rewrite-destructured-props.ts +22 -5
  175. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  176. package/src/ir-to-client-js/safe-html.ts +29 -35
  177. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  178. package/src/ir-to-client-js/types.ts +3 -2
  179. package/src/ir-to-client-js/utils.ts +42 -122
  180. package/src/jsx-to-ir.ts +310 -90
  181. package/src/nullable-signal-attr.ts +149 -33
  182. package/src/prop-rewrite.ts +72 -72
  183. package/src/props-binding.ts +90 -3
  184. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  185. package/src/scanner/js-scanner.ts +64 -4
  186. package/src/scope/binding-scope.ts +34 -3
  187. package/src/scope/lexical-scope-walk.ts +167 -0
  188. package/src/signal-prop-name-collision.ts +50 -24
  189. package/src/ssr-defaults.ts +47 -20
  190. package/src/ssr-seed-plan.ts +103 -23
  191. package/src/types.ts +140 -20
  192. package/src/value-references.ts +132 -0
@@ -0,0 +1,138 @@
1
+ /**
2
+ * A props destructure default that reads an earlier binding of its own
3
+ * pattern (`{ off = false, on = off }`, #3531). The analyzer splits the
4
+ * default at those reads (`ParamInfo.defaultParts`), and the client JS
5
+ * renders each as the earlier prop's own live read, so no emitted scope
6
+ * names a binding it lacks.
7
+ */
8
+
9
+ import { describe, test, expect } from 'bun:test'
10
+ import { analyzeComponent } from '../analyzer'
11
+ import { compileJSX } from '../compiler'
12
+ import { TestAdapter } from '../adapters/test-adapter'
13
+ import { splitScopedValueRefs } from '../prop-rewrite'
14
+
15
+ const adapter = new TestAdapter()
16
+
17
+ function clientJs(source: string): string {
18
+ const result = compileJSX(source, 'Component.tsx', { adapter })
19
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
20
+ const file = result.files.find(f => f.type === 'clientJs')
21
+ expect(file).toBeDefined()
22
+ return file!.content
23
+ }
24
+
25
+ function propsParams(source: string) {
26
+ return analyzeComponent(source, 'Component.tsx').propsParams
27
+ }
28
+
29
+ describe('ParamInfo.defaultParts', () => {
30
+ test('records each read of an earlier binding, carrying its own read for a chain', () => {
31
+ const params = propsParams(`
32
+ function C({ a = 'x', b = a, c = b }: { a?: string; b?: string; c?: string }) {
33
+ return <p>{c}</p>
34
+ }
35
+ `)
36
+ const byName = new Map(params.map(p => [p.name, p]))
37
+ expect(byName.get('a')!.defaultParts).toBeUndefined()
38
+ expect(byName.get('b')!.defaultParts).toEqual([
39
+ { kind: 'param', param: { name: 'a', defaultValue: "'x'" } },
40
+ ])
41
+ const cParts = byName.get('c')!.defaultParts!
42
+ expect(cParts).toHaveLength(1)
43
+ expect(cParts[0]).toEqual({ kind: 'param', param: { name: 'b', defaultValue: 'a', defaultParts: byName.get('b')!.defaultParts } })
44
+ })
45
+
46
+ test('leaves a later binding (TDZ), an outer name and a shadowing callback param alone', () => {
47
+ const params = propsParams(`
48
+ const off = true
49
+ function C({ first = later, x = 1, y = [1].map((x) => x + 1), later = 2 }: { first?: number; x?: number; y?: number[]; later?: number }) {
50
+ return <p>{first}{y}</p>
51
+ }
52
+ `)
53
+ for (const p of params) expect(p.defaultParts).toBeUndefined()
54
+ })
55
+
56
+ test('keeps a shorthand property key as text', () => {
57
+ expect(splitScopedValueRefs('{ off, n: off }', new Set(['off']))).toEqual([
58
+ { kind: 'text', text: '{ off: ' },
59
+ { kind: 'ref', name: 'off' },
60
+ { kind: 'text', text: ', n: ' },
61
+ { kind: 'ref', name: 'off' },
62
+ { kind: 'text', text: ' }' },
63
+ ])
64
+ })
65
+ })
66
+
67
+ describe('client JS reads the earlier prop live', () => {
68
+ test('parameter form: the default reads the earlier prop with its own default', () => {
69
+ const js = clientJs(`
70
+ 'use client'
71
+ export function C({ off = false, on = off }: { off?: boolean; on?: boolean }) {
72
+ return <p>{String(on && true)}</p>
73
+ }
74
+ `)
75
+ expect(js).toContain('(_p.on ?? (_p.off ?? false))')
76
+ expect(js).not.toContain('_p.on ?? off)')
77
+ })
78
+
79
+ test('a chain nests each earlier read, and an expression default keeps its operator', () => {
80
+ const js = clientJs(`
81
+ 'use client'
82
+ export function C({ a = 'x', b = a, c = b, off = false, on = !off }: { a?: string; b?: string; c?: string; off?: boolean; on?: boolean }) {
83
+ return <p>{c}{String(on)}</p>
84
+ }
85
+ `)
86
+ expect(js).toContain(`(_p.c ?? (_p.b ?? (_p.a ?? 'x')))`)
87
+ expect(js).toContain('(_p.on ?? !(_p.off ?? false))')
88
+ })
89
+
90
+ test('a renamed earlier binding reads its caller-facing key', () => {
91
+ const js = clientJs(`
92
+ 'use client'
93
+ export function C({ off: o = false, on = o }: { off?: boolean; on?: boolean }) {
94
+ return <p>{String(on)}</p>
95
+ }
96
+ `)
97
+ expect(js).toContain('(_p.on ?? (_p.off ?? false))')
98
+ })
99
+
100
+ test('body form: the init body reads the earlier prop live too', () => {
101
+ const js = clientJs(`
102
+ 'use client'
103
+ export function C(props: { off?: boolean; on?: boolean }) {
104
+ const { off = false, on = off } = props
105
+ return <p>{String(on)}</p>
106
+ }
107
+ `)
108
+ expect(js).not.toMatch(/_p\.on \?\? off\b/)
109
+ expect(js).toContain('(_p.on ?? (_p.off ?? false))')
110
+ })
111
+
112
+ test('the CSR template reads a signal seed and a memo over the prop with its default', () => {
113
+ const js = clientJs(`
114
+ 'use client'
115
+ import { createSignal, createMemo } from '@barefootjs/client'
116
+ export function C({ off = false, on = off }: { off?: boolean; on?: boolean }) {
117
+ const [v, setV] = createSignal(on)
118
+ const flipped = createMemo(() => !on)
119
+ return <p onClick={() => setV(!v())}>{String(v())}|{String(flipped())}</p>
120
+ }
121
+ `)
122
+ const template = js.slice(js.indexOf('template: (_p) =>'))
123
+ expect(template).toContain('String(((_p.on ?? (_p.off ?? false))))')
124
+ expect(template).toContain('String((!(_p.on ?? (_p.off ?? false))))')
125
+ })
126
+
127
+ test('a controlled signal seeded by the prop reads the earlier prop live', () => {
128
+ const js = clientJs(`
129
+ 'use client'
130
+ import { createSignal } from '@barefootjs/client'
131
+ export function C({ off = false, on = off }: { off?: boolean; on?: boolean }) {
132
+ const [v, setV] = createSignal(on)
133
+ return <button onClick={() => setV(!v())}>{String(v())}</button>
134
+ }
135
+ `)
136
+ expect(js).not.toMatch(/_p\.on \?\? off\b/)
137
+ })
138
+ })
@@ -0,0 +1,173 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer'
3
+ import { jsxToIR } from '../jsx-to-ir'
4
+ import { buildMetadata } from '../compiler'
5
+ import { DslTemplateAdapter, type TemplateIdentifierSpelling } from '../adapters/dsl-template-adapter'
6
+ import type {
7
+ ComponentIR,
8
+ IRComponent,
9
+ IRConditional,
10
+ IRElement,
11
+ IRExpression,
12
+ IRIfStatement,
13
+ IRLoop,
14
+ IRNode,
15
+ } from '../types'
16
+
17
+ // #3475: the `generate()` the eight DSL template adapters share. A minimal
18
+ // adapter stands in for one; each hook records what it saw.
19
+ function componentIR(source: string): ComponentIR {
20
+ const ctx = analyzeComponent(source, 'Test.tsx')
21
+ const root = jsxToIR(ctx)
22
+ if (!root) throw new Error('expected IR')
23
+ return { version: '0.1', metadata: buildMetadata(ctx), root, errors: [] }
24
+ }
25
+
26
+ class StubAdapter extends DslTemplateAdapter {
27
+ name = 'stub'
28
+ extension = '.stub'
29
+ protected readonly loopChildDiagnosticName = 'Stub'
30
+ protected override readonly templateIdentifierSpelling: TemplateIdentifierSpelling | null
31
+ /** What `resetAdapterState` saw of the shared state. */
32
+ seenAtReset: { propNames: string[]; errors: number; counter: number } | null = null
33
+ scriptCalls: unknown[][] = []
34
+
35
+ constructor(spelling: TemplateIdentifierSpelling | null = null) {
36
+ super()
37
+ this.templateIdentifierSpelling = spelling
38
+ }
39
+
40
+ protected stringValueNamesFor(): Set<string> {
41
+ return new Set()
42
+ }
43
+ protected override resetAdapterState(): void {
44
+ this.seenAtReset = {
45
+ propNames: this.propsParams.map(p => p.name),
46
+ errors: this.errors.length,
47
+ counter: this.childrenCaptureCounter,
48
+ }
49
+ }
50
+ protected renderIfStatement(ifStmt: IRIfStatement): string {
51
+ return `[if ${ifStmt.condition}]`
52
+ }
53
+ protected generateScriptRegistrations(...args: unknown[]): string {
54
+ this.scriptCalls.push(args.slice(1))
55
+ return '[scripts]'
56
+ }
57
+ protected contextConsumerSeed(): string {
58
+ return '[ctx]'
59
+ }
60
+ protected derivedMemoSeed(): string {
61
+ return '[memo]'
62
+ }
63
+
64
+ renderNode(node: IRNode): string {
65
+ if (node.type === 'component') {
66
+ // A rendering diagnostic, and a use of the per-compile counter.
67
+ this.errors.push({
68
+ code: 'BF999',
69
+ severity: 'error',
70
+ message: `rendered ${(node as IRComponent).name}`,
71
+ loc: { file: 'Test.tsx', start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
72
+ })
73
+ return `[child ${this.childrenCaptureCounter++}]`
74
+ }
75
+ if (node.type === 'element') return `<${(node as IRElement).tag}>${this.renderChildren((node as IRElement).children)}`
76
+ if (node.type === 'loop') return this.renderChildren((node as IRLoop).children)
77
+ return `{${node.type}}`
78
+ }
79
+ renderElement(element: IRElement): string {
80
+ return this.renderNode(element)
81
+ }
82
+ renderExpression(expr: IRExpression): string {
83
+ return this.renderNode(expr)
84
+ }
85
+ renderConditional(cond: IRConditional): string {
86
+ return this.renderNode(cond)
87
+ }
88
+ renderLoop(loop: IRLoop): string {
89
+ return this.renderNode(loop)
90
+ }
91
+ renderComponent(comp: IRComponent): string {
92
+ return this.renderNode(comp)
93
+ }
94
+ renderScopeMarker(): string {
95
+ return ''
96
+ }
97
+ renderSlotMarker(): string {
98
+ return ''
99
+ }
100
+ renderCondMarker(): string {
101
+ return ''
102
+ }
103
+ }
104
+
105
+ const LOOP_CHILD = `
106
+ import Child from './child'
107
+ export function Test({ items }: { items: string[] }) {
108
+ return <ul>{items.map(i => <Child key={i} />)}</ul>
109
+ }
110
+ `
111
+
112
+ describe('DslTemplateAdapter.generate (#3475)', () => {
113
+ test('the template is the script registrations, the two seeds and the body, in that order', () => {
114
+ const out = new StubAdapter().generate(componentIR(`export function Test() { return <p>hi</p> }`))
115
+ expect(out.template).toBe('[scripts][ctx][memo]<p>{text}\n')
116
+ expect(out.sections).toEqual({ imports: '', types: '', component: out.template, defaultExport: '' })
117
+ expect(out.extension).toBe('.stub')
118
+ })
119
+
120
+ test('skipScriptRegistration drops the registrations; the script options reach the adapter', () => {
121
+ const ir = componentIR(`export function Test() { return <p>hi</p> }`)
122
+ const adapter = new StubAdapter()
123
+ expect(adapter.generate(ir, { skipScriptRegistration: true }).template).toBe('[ctx][memo]<p>{text}\n')
124
+ adapter.generate(ir, { scriptBaseName: 'Base', scriptAssets: ['/a.js'], preloadAssets: ['/p.js'] })
125
+ expect(adapter.scriptCalls).toEqual([['Base', ['/a.js'], ['/p.js']]])
126
+ })
127
+
128
+ test('a root if statement renders through renderIfStatement', () => {
129
+ const ir = componentIR(`
130
+ export function Test({ on }: { on: boolean }) {
131
+ if (on) return <p>on</p>
132
+ return <p>off</p>
133
+ }
134
+ `)
135
+ expect(ir.root.type).toBe('if-statement')
136
+ expect(new StubAdapter().generate(ir, { skipScriptRegistration: true }).template).toBe('[ctx][memo][if on]\n')
137
+ })
138
+
139
+ test('the adapter hook runs after the shared state is reset', () => {
140
+ const adapter = new StubAdapter()
141
+ adapter.generate(componentIR(LOOP_CHILD))
142
+ adapter.generate(componentIR(`export function Test({ label }: { label: string }) { return <p>{label}</p> }`))
143
+ expect(adapter.seenAtReset).toEqual({ propNames: ['label'], errors: 0, counter: 0 })
144
+ })
145
+
146
+ test('BF103 names the adapter, comes before rendering diagnostics, and is suppressed for registered siblings', () => {
147
+ const ir = componentIR(LOOP_CHILD)
148
+ const out = new StubAdapter().generate(ir)
149
+ expect(out.template).toContain('[child 0]')
150
+ expect(ir.errors.map(e => e.code)).toEqual(['BF103', 'BF999'])
151
+ expect(ir.errors[0]!.message).toContain('The Stub adapter emits')
152
+
153
+ const registered = componentIR(LOOP_CHILD)
154
+ new StubAdapter().generate(registered, { siblingTemplatesRegistered: true })
155
+ expect(registered.errors.map(e => e.code)).toEqual(['BF999'])
156
+ })
157
+
158
+ test('the reserved-name collision check runs only for an adapter that renames names', () => {
159
+ const source = `
160
+ export function Test(props: { loop: string; __bf_loop: string }) {
161
+ return <div>{props.loop}{props.__bf_loop}</div>
162
+ }
163
+ `
164
+ const spelling = { ident: (name: string) => (name === 'loop' ? '__bf_loop' : name), label: 'Stub' }
165
+ const renamed = componentIR(source)
166
+ new StubAdapter(spelling).generate(renamed)
167
+ expect(renamed.errors.map(e => e.code)).toEqual(['BF105'])
168
+
169
+ const plain = componentIR(source)
170
+ new StubAdapter().generate(plain)
171
+ expect(plain.errors).toEqual([])
172
+ })
173
+ })
@@ -0,0 +1,58 @@
1
+ /**
2
+ * `recv.toString()` reaches an adapter's `call()` as `String(recv)` (#3621).
3
+ * Every template adapter registers the `String` primitive; a zero-arg method
4
+ * call otherwise falls to `call()`'s getter fallback, which reads the callee
5
+ * `recv.toString` as a property and drops the call.
6
+ */
7
+
8
+ import { describe, test, expect } from 'bun:test'
9
+ import { emitParsedExpr, parseExpression, type ParsedExpr, type ParsedExprEmitter } from '../index'
10
+
11
+ // Spells every node as a JS-like string so the dispatched shape is visible.
12
+ function makeEmitter(): ParsedExprEmitter {
13
+ const callName = (callee: ParsedExpr, emit: (e: ParsedExpr) => string) =>
14
+ callee.kind === 'identifier' ? callee.name : emit(callee)
15
+ return {
16
+ identifier: name => name,
17
+ literal: value => JSON.stringify(value),
18
+ call: (callee, args, emit) => `${callName(callee, emit)}(${args.map(emit).join(', ')})`,
19
+ member: (object, property, _computed, optional, emit) => `${emit(object)}${optional ? '?.' : '.'}${property}`,
20
+ indexAccess: (object, index, emit) => `${emit(object)}[${emit(index)}]`,
21
+ binary: (op, l, r, emit) => `${emit(l)} ${op} ${emit(r)}`,
22
+ unary: (op, a, emit) => `${op}${emit(a)}`,
23
+ logical: (op, l, r, emit) => `${emit(l)} ${op} ${emit(r)}`,
24
+ conditional: () => 'COND',
25
+ templateLiteral: () => 'TPL',
26
+ arrow: () => 'ARROW',
27
+ regex: raw => raw,
28
+ arrayLiteral: (els, emit) => `[${els.map(emit).join(', ')}]`,
29
+ objectLiteral: (_p, raw) => raw,
30
+ callbackMethod: (method, object, _arrow, _rest, emit) => `${emit(object)}.${method}(CB)`,
31
+ arrayMethod: (method, object, args, emit) => `${emit(object)}.${method}(${args.map(emit).join(', ')})`,
32
+ flatMethod: (object, _depth, emit) => `${emit(object)}.flat()`,
33
+ unsupported: raw => `UNSUPPORTED(${raw})`,
34
+ }
35
+ }
36
+
37
+ const emit = (src: string) => emitParsedExpr(parseExpression(src), makeEmitter())
38
+
39
+ describe('recv.toString() dispatches as String(recv)', () => {
40
+ test('a row value, an index and a getter result', () => {
41
+ expect(emit('x.toString()')).toBe('String(x)')
42
+ expect(emit('i.toString()')).toBe('String(i)')
43
+ expect(emit('count().toString()')).toBe('String(count())')
44
+ expect(emit('row.meta.id.toString()')).toBe('String(row.meta.id)')
45
+ })
46
+
47
+ test('nested inside another expression', () => {
48
+ expect(emit("'#' + n.toString()")).toBe("\"#\" + String(n)")
49
+ })
50
+
51
+ test('other shapes keep the generic call dispatch', () => {
52
+ // A radix argument changes the result; `String` takes none.
53
+ expect(emit('n.toString(16)')).toBe('n.toString(16)')
54
+ // `x?.toString()` is `undefined` for a nullish receiver, `String` is not.
55
+ expect(emit('x?.toString()')).not.toContain('String(')
56
+ expect(emit('x.valueOf()')).toBe('x.valueOf()')
57
+ })
58
+ })
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Event handlers reach `addEventListener` verbatim (#3538).
3
+ *
4
+ * The emitters used to rewrite an arrow handler into block form by splitting
5
+ * its text at the first `=>`, which broke any handler whose first `=>` is not
6
+ * the outer arrow's (a conditional choosing between arrows, a default
7
+ * parameter holding an arrow). `addEventListener` ignores a listener's return
8
+ * value, so the handler is now passed through as written, in every position
9
+ * a listener is emitted from.
10
+ */
11
+
12
+ import { describe, test, expect } from 'bun:test'
13
+ import { compileJSX } from '../compiler'
14
+ import { TestAdapter } from '../adapters/test-adapter'
15
+
16
+ const adapter = new TestAdapter()
17
+ const transpiler = new Bun.Transpiler({ loader: 'js' })
18
+
19
+ const HANDLERS: Record<string, string> = {
20
+ 'conditional between arrows': '(n() > 5 ? () => setN(0) : () => setN(n() + 1))',
21
+ 'default parameter holding an arrow': '(e = { step: () => 2 }) => setN(n() + e.step())',
22
+ 'comma sequence': 'setN(1), () => setN(n() + 1)',
23
+ 'destructured parameter': '({ currentTarget }) => setN(currentTarget ? n() + 1 : 0)',
24
+ 'expression-bodied arrow': '() => setN(n() + 1)',
25
+ }
26
+
27
+ /** Wraps one handler in each position a listener is emitted from. */
28
+ function positions(handler: string): Record<string, string> {
29
+ return {
30
+ 'top-level element': `<button onClick={${handler}}>{n()}</button>`,
31
+ 'conditional branch': `<div>{n() > 0 ? <button onClick={${handler}}>a</button> : <span>none</span>}</div>`,
32
+ 'loop row': `<ul>{items().map(item => <li key={item}><button onClick={${handler}}>{item}</button></li>)}</ul>`,
33
+ }
34
+ }
35
+
36
+ function compile(body: string): string {
37
+ const source = `
38
+ 'use client'
39
+ import { createSignal } from '@barefootjs/client'
40
+ export function T() {
41
+ const [n, setN] = createSignal(0)
42
+ const [items] = createSignal(['a', 'b'])
43
+ return ${body}
44
+ }
45
+ `
46
+ const result = compileJSX(source, 'T.tsx', { adapter })
47
+ expect(result.errors).toHaveLength(0)
48
+ const clientJs = result.files.find(f => f.type === 'clientJs')
49
+ expect(clientJs).toBeDefined()
50
+ return clientJs!.content
51
+ }
52
+
53
+ describe('event handlers are emitted verbatim (#3538)', () => {
54
+ for (const [shape, handler] of Object.entries(HANDLERS)) {
55
+ for (const [position, body] of Object.entries(positions(handler))) {
56
+ test(`${shape} in a ${position} compiles to valid JS`, () => {
57
+ const js = compile(body)
58
+ expect(() => transpiler.transformSync(js)).not.toThrow()
59
+ })
60
+ }
61
+ }
62
+
63
+ test('a top-level handler appears unchanged as the listener argument', () => {
64
+ const handler = HANDLERS['conditional between arrows']
65
+ const js = compile(positions(handler)['top-level element'])
66
+ expect(js).toContain(`.addEventListener('click', ${handler})`)
67
+ })
68
+
69
+ test('a comma sequence stays one listener argument', () => {
70
+ const js = compile(positions(HANDLERS['comma sequence'])['top-level element'])
71
+ expect(js).toContain(`.addEventListener('click', (setN(1), () => setN(n() + 1)))`)
72
+ })
73
+ })
@@ -1,6 +1,6 @@
1
1
  import { describe, test, expect } from 'bun:test'
2
2
  import ts from 'typescript'
3
- import { parseExpression, isSupported, isSupportedValue, exprToString, stringifyParsedExpr, parseBlockBody, foldBlockToExpr, extractArrowBodyExpression, parseStyleObjectEntries, parseProviderObjectLiteral, asCallbackMethodCall, containsHigherOrder } from '../expression-parser'
3
+ import { parseExpression, isSupported, isSupportedValue, exprToString, stringifyParsedExpr, parseBlockBody, foldBlockToExpr, extractArrowBodyExpression, parseProviderObjectLiteral, asCallbackMethodCall, containsHigherOrder } from '../expression-parser'
4
4
  import { collectAllTypeRanges, reconstructWithoutTypes } from '../strip-types'
5
5
 
6
6
  describe('expression-parser', () => {
@@ -2036,49 +2036,6 @@ describe('parseProviderObjectLiteral', () => {
2036
2036
  })
2037
2037
  })
2038
2038
 
2039
- describe('parseStyleObjectEntries', () => {
2040
- test('kebab-cases keys and splits literal vs expression values', () => {
2041
- expect(parseStyleObjectEntries("{ backgroundColor: color, padding: '8px' }")).toEqual([
2042
- { cssKey: 'background-color', kind: 'expr', expr: 'color' },
2043
- { cssKey: 'padding', kind: 'literal', value: '8px' },
2044
- ])
2045
- })
2046
-
2047
- test('handles signal-getter call values as expressions', () => {
2048
- expect(parseStyleObjectEntries('{ background: bg(), color: fg() }')).toEqual([
2049
- { cssKey: 'background', kind: 'expr', expr: 'bg()' },
2050
- { cssKey: 'color', kind: 'expr', expr: 'fg()' },
2051
- ])
2052
- })
2053
-
2054
- test('quoted keys are honoured', () => {
2055
- expect(parseStyleObjectEntries("{ 'z-index': '1' }")).toEqual([
2056
- { cssKey: 'z-index', kind: 'literal', value: '1' },
2057
- ])
2058
- })
2059
-
2060
- test('vendor-prefixed keys keep the leading dash', () => {
2061
- expect(parseStyleObjectEntries("{ WebkitTransform: 'none' }")).toEqual([
2062
- { cssKey: '-webkit-transform', kind: 'literal', value: 'none' },
2063
- ])
2064
- // The `ms` prefix is lowercase in React style keys but the CSS property
2065
- // carries a leading dash (`-ms-transform`), unlike `Webkit`/`Moz`.
2066
- expect(parseStyleObjectEntries("{ msTransform: 'none' }")).toEqual([
2067
- { cssKey: '-ms-transform', kind: 'literal', value: 'none' },
2068
- ])
2069
- })
2070
-
2071
- test('returns null for unsupported shapes (spread / shorthand / computed)', () => {
2072
- expect(parseStyleObjectEntries('{ ...rest }')).toBeNull()
2073
- expect(parseStyleObjectEntries('{ color }')).toBeNull()
2074
- expect(parseStyleObjectEntries('{ [k]: v }')).toBeNull()
2075
- })
2076
-
2077
- test('returns null for a non-object source', () => {
2078
- expect(parseStyleObjectEntries('color')).toBeNull()
2079
- })
2080
- })
2081
-
2082
2039
  // =============================================================================
2083
2040
  // Block → Expression Normalization (#2040)
2084
2041
  // =============================================================================
@@ -65,16 +65,6 @@ function assertParses(clientJs: string): void {
65
65
  expect(syntaxErrorsOf(clientJs)).toHaveLength(0)
66
66
  }
67
67
 
68
- /**
69
- * The counterpart to `assertParses`: a nested declaration that shadows the
70
- * loop param (see the `rewriteIdentifierAsAccessor` docstring in
71
- * `ir-to-client-js/utils.ts`) is expected to fail loudly at this
72
- * parse-check rather than silently emit a value that's wrong at runtime.
73
- */
74
- function assertDoesNotParse(clientJs: string): void {
75
- expect(syntaxErrorsOf(clientJs).length).toBeGreaterThan(0)
76
- }
77
-
78
68
  describe('.map() row: object-literal key / shorthand / member positions vs. the loop param (#3239)', () => {
79
69
  test('shorthand property `{ choice }` expands to `{ choice: choice() }`, not `{ choice() }`', () => {
80
70
  const source = `
@@ -361,18 +351,14 @@ describe('.map() row: declaration/member positions the old regex skipped via its
361
351
  })
362
352
  })
363
353
 
364
- describe('.map() row: a nested scope that shadows the loop param fails loudly instead of silently misrewriting', () => {
365
- // `rewriteIdentifierAsAccessor` has no scope tracking (see its docstring
366
- // in ir-to-client-js/utils.ts): once a nested scope re-binds the loop
367
- // param's name, the rewrite can no longer tell a reference to the outer
368
- // item from a reference to the shadowing local, so it deliberately wraps
369
- // the shadowing declaration's own name too. That's always a syntax break
370
- // at the declaration site, so the module fails a syntax check instead of
371
- // silently compiling into a runtime `TypeError` against the wrong value
372
- // — matching what the pre-#3239 regex already did for this shape (it had
373
- // no shadow-awareness either).
374
-
375
- test('a nested `.map(choice => ...)` that reuses the outer loop param name fails to parse', () => {
354
+ describe('.map() row: a nested scope that shadows the loop param keeps its own binding (#3595)', () => {
355
+ // The accessor rewrite walks the text with the shared lexical-scope model
356
+ // (`walkWithScope`): an inner binding of the loop param's name — its binder
357
+ // and every reference it shadows — is the inner binding's, so neither is
358
+ // wrapped. Before #3595 the rewrite had no scope tracking and wrapped the
359
+ // binder too (`(choice()) =>`, `const choice() = 1`), a syntax error.
360
+
361
+ test('a nested `.map(choice => ...)` that reuses the outer loop param name reads the inner param', () => {
376
362
  const source = `
377
363
  'use client'
378
364
  import { createSignal } from '@barefootjs/client'
@@ -388,10 +374,11 @@ describe('.map() row: a nested scope that shadows the loop param fails loudly in
388
374
  }
389
375
  `
390
376
  const js = getClientJs(source)
391
- assertDoesNotParse(js)
377
+ assertParses(js)
378
+ expect(js).toContain("choice().split('').map(choice => choice.toUpperCase())")
392
379
  })
393
380
 
394
- test('a nested `const choice = ...` that reuses the outer loop param name fails to parse', () => {
381
+ test('a nested `const choice = ...` that reuses the outer loop param name reads the local', () => {
395
382
  const source = `
396
383
  'use client'
397
384
  import { createSignal } from '@barefootjs/client'
@@ -407,7 +394,73 @@ describe('.map() row: a nested scope that shadows the loop param fails loudly in
407
394
  }
408
395
  `
409
396
  const js = getClientJs(source)
410
- assertDoesNotParse(js)
397
+ assertParses(js)
398
+ expect(js).toContain('const choice = 1; return choice })()')
399
+ })
400
+
401
+ test('an inner callback that reuses the index name reads its own index', () => {
402
+ const source = `
403
+ 'use client'
404
+ import { createSignal } from '@barefootjs/client'
405
+ export function App() {
406
+ const [items] = createSignal(['ab', 'cd'])
407
+ return (
408
+ <div>
409
+ {items().map((choice, i) => (
410
+ <b key={choice}>{String(i) + choice.split('').map((c, i) => c + i).join('')}</b>
411
+ ))}
412
+ </div>
413
+ )
414
+ }
415
+ `
416
+ const js = getClientJs(source)
417
+ assertParses(js)
418
+ // A lazy row hands the index as a plain number (`const i = __e.index`);
419
+ // the inner `(c, i)` keeps its binder either way.
420
+ expect(js).toContain("String(i) + choice().split('').map((c, i) => c + i)")
421
+ expect(js).not.toContain('(c, i())')
422
+ })
423
+
424
+ test('a named class expression binds its own name inside the class body', () => {
425
+ const source = `
426
+ 'use client'
427
+ import { createSignal } from '@barefootjs/client'
428
+ export function App() {
429
+ const [items] = createSignal(['a', 'b'])
430
+ return (
431
+ <div>
432
+ {items().map(choice => (
433
+ <b key={choice}>{String((class choice { static n = choice.name }).n)}</b>
434
+ ))}
435
+ </div>
436
+ )
437
+ }
438
+ `
439
+ const js = getClientJs(source)
440
+ assertParses(js)
441
+ expect(js).toContain('class choice { static n = choice.name }')
442
+ })
443
+
444
+ test('a computed method key reads the outer item; the method body reads its own param', () => {
445
+ // The key is evaluated in the enclosing scope, before the method's
446
+ // parameters exist, so only the body's `choice` is the inner binding.
447
+ const source = `
448
+ 'use client'
449
+ import { createSignal } from '@barefootjs/client'
450
+ export function App() {
451
+ const [items] = createSignal(['a', 'b'])
452
+ return (
453
+ <div>
454
+ {items().map(choice => (
455
+ <b key={choice}>{Object.keys({ [choice](choice) { return choice } }).join('')}</b>
456
+ ))}
457
+ </div>
458
+ )
459
+ }
460
+ `
461
+ const js = getClientJs(source)
462
+ assertParses(js)
463
+ expect(js).toContain('{ [choice()](choice) { return choice } }')
411
464
  })
412
465
  })
413
466
 
@@ -481,12 +534,18 @@ describe('destructured loop-param path (rewriteLoopBindingRefs) shares the plain
481
534
  expect(js).toContain('(function color() { return __bfItem().label })()')
482
535
  })
483
536
 
484
- test('a nested function declaration shadowing a binding fails to parse instead of calling the item field', () => {
485
- // Keeping `function color() {}` while rewriting its call to
486
- // `__bfItem().color()` would compile and then call the wrong value at
487
- // hydration. Rewriting the declaration name too breaks it loudly, as the
488
- // old destructured regex did (#3260 review).
537
+ test('a nested function declaration shadowing a binding is called as the local function', () => {
538
+ // `function color() {}` binds `color` for its block, so both the
539
+ // declaration and its call stay local (#3595); before, the rewrite had no
540
+ // scope tracking and broke the declaration name to fail loudly (#3260).
489
541
  const js = compileRow("<b key={label}>{(() => { function color() { return 'blue' } return color() })()}</b>")
490
- assertDoesNotParse(js)
542
+ assertParses(js)
543
+ expect(js).toContain("function color() { return 'blue' } return color() })()")
544
+ })
545
+
546
+ test('a nested callback rebinding a destructured name reads the inner param (#3595)', () => {
547
+ const js = compileRow("<b key={label}>{[1, 2].map((label) => label * 2).join(label)}</b>")
548
+ assertParses(js)
549
+ expect(js).toContain('[1, 2].map((label) => label * 2).join(__bfItem().label)')
491
550
  })
492
551
  })