@barefootjs/jsx 0.39.6 → 0.39.8

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/attr-plan.d.ts +8 -1
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +44 -0
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/component-props.d.ts +80 -13
  6. package/dist/adapters/component-props.d.ts.map +1 -1
  7. package/dist/adapters/computed-const.d.ts +52 -0
  8. package/dist/adapters/computed-const.d.ts.map +1 -0
  9. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  10. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts +151 -0
  12. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  13. package/dist/adapters/element-shell.d.ts +44 -0
  14. package/dist/adapters/element-shell.d.ts.map +1 -0
  15. package/dist/adapters/interface.d.ts +2 -0
  16. package/dist/adapters/interface.d.ts.map +1 -1
  17. package/dist/adapters/jsx-adapter.d.ts +4 -0
  18. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  19. package/dist/adapters/literal-value.d.ts +2 -2
  20. package/dist/adapters/literal-value.d.ts.map +1 -1
  21. package/dist/adapters/parsed-expr-emitter.d.ts +27 -0
  22. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  23. package/dist/adapters/style-object.d.ts +33 -0
  24. package/dist/adapters/style-object.d.ts.map +1 -0
  25. package/dist/analyzer.d.ts.map +1 -1
  26. package/dist/augment-inherited-props.d.ts +7 -0
  27. package/dist/augment-inherited-props.d.ts.map +1 -1
  28. package/dist/children-nullish.d.ts +22 -0
  29. package/dist/children-nullish.d.ts.map +1 -0
  30. package/dist/errors.d.ts +1 -0
  31. package/dist/errors.d.ts.map +1 -1
  32. package/dist/expression-parser.d.ts +9 -19
  33. package/dist/expression-parser.d.ts.map +1 -1
  34. package/dist/fold-render-reassignments.d.ts +43 -0
  35. package/dist/fold-render-reassignments.d.ts.map +1 -0
  36. package/dist/free-refs.d.ts +15 -0
  37. package/dist/free-refs.d.ts.map +1 -1
  38. package/dist/index.d.ts +21 -14
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +24620 -23233
  41. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  43. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  45. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  48. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  50. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  52. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  54. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/html-template.d.ts +9 -19
  57. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  59. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/imports.d.ts +23 -2
  61. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  62. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -2
  64. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  66. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  67. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  68. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  70. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  72. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  73. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  74. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  75. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  76. package/dist/ir-to-client-js/types.d.ts +3 -3
  77. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  78. package/dist/ir-to-client-js/utils.d.ts +15 -11
  79. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  80. package/dist/jsx-to-ir.d.ts.map +1 -1
  81. package/dist/nullable-signal-attr.d.ts +43 -12
  82. package/dist/nullable-signal-attr.d.ts.map +1 -1
  83. package/dist/prop-rewrite.d.ts +18 -0
  84. package/dist/prop-rewrite.d.ts.map +1 -1
  85. package/dist/props-binding.d.ts +43 -6
  86. package/dist/props-binding.d.ts.map +1 -1
  87. package/dist/relocate.d.ts +16 -0
  88. package/dist/relocate.d.ts.map +1 -1
  89. package/dist/scanner/js-scanner.d.ts.map +1 -1
  90. package/dist/scanner/js-scanner.js +30 -2
  91. package/dist/signal-prop-name-collision.d.ts +6 -5
  92. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  93. package/dist/ssr-defaults.d.ts +28 -0
  94. package/dist/ssr-defaults.d.ts.map +1 -1
  95. package/dist/ssr-seed-plan.d.ts +37 -18
  96. package/dist/ssr-seed-plan.d.ts.map +1 -1
  97. package/dist/types.d.ts +162 -20
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/value-references.d.ts +21 -0
  100. package/dist/value-references.d.ts.map +1 -1
  101. package/package.json +2 -2
  102. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  103. package/src/__tests__/adapter-output.test.ts +5 -3
  104. package/src/__tests__/analyzer.test.ts +33 -0
  105. package/src/__tests__/arithmetic-lowering.test.ts +44 -0
  106. package/src/__tests__/block-memo-type.test.ts +51 -0
  107. package/src/__tests__/callback-method.test.ts +75 -0
  108. package/src/__tests__/children-read.test.ts +226 -0
  109. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  110. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  111. package/src/__tests__/component-props.test.ts +68 -1
  112. package/src/__tests__/computed-const.test.ts +101 -0
  113. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  114. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  115. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  116. package/src/__tests__/element-shell.test.ts +78 -0
  117. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  118. package/src/__tests__/expression-parser.test.ts +1 -44
  119. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  120. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  121. package/src/__tests__/memo-body-expr.test.ts +120 -0
  122. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  123. package/src/__tests__/prop-handling.test.ts +35 -16
  124. package/src/__tests__/props-alias-const.test.ts +65 -0
  125. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  126. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  127. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  128. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +173 -1
  131. package/src/__tests__/static-template-reachability.test.ts +137 -0
  132. package/src/__tests__/style-object-plan.test.ts +54 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/attr-plan.ts +29 -1
  135. package/src/adapters/callback-method.ts +85 -0
  136. package/src/adapters/component-props.ts +130 -12
  137. package/src/adapters/computed-const.ts +185 -0
  138. package/src/adapters/dangerous-inner-html.ts +33 -0
  139. package/src/adapters/dsl-template-adapter.ts +248 -0
  140. package/src/adapters/element-shell.ts +160 -0
  141. package/src/adapters/interface.ts +8 -0
  142. package/src/adapters/jsx-adapter.ts +12 -6
  143. package/src/adapters/literal-value.ts +2 -2
  144. package/src/adapters/parsed-expr-emitter.ts +34 -0
  145. package/src/adapters/style-object.ts +61 -0
  146. package/src/analyzer.ts +382 -94
  147. package/src/augment-inherited-props.ts +12 -0
  148. package/src/children-nullish.ts +33 -0
  149. package/src/debug.ts +2 -2
  150. package/src/errors.ts +12 -0
  151. package/src/expression-parser.ts +56 -53
  152. package/src/fold-render-reassignments.ts +314 -0
  153. package/src/free-refs.ts +77 -17
  154. package/src/index.ts +27 -10
  155. package/src/ir-to-client-js/compute-inlinability.ts +122 -19
  156. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  157. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  159. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  160. package/src/ir-to-client-js/csr-substitute.ts +25 -37
  161. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  162. package/src/ir-to-client-js/emit-registration.ts +31 -59
  163. package/src/ir-to-client-js/generate-init.ts +17 -1
  164. package/src/ir-to-client-js/html-template.ts +56 -120
  165. package/src/ir-to-client-js/identifiers.ts +75 -24
  166. package/src/ir-to-client-js/imports.ts +56 -19
  167. package/src/ir-to-client-js/index.ts +5 -3
  168. package/src/ir-to-client-js/init-declarations.ts +1 -1
  169. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  170. package/src/ir-to-client-js/phases/props-extraction.ts +16 -15
  171. package/src/ir-to-client-js/plan/build-declaration-emit.ts +26 -52
  172. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  173. package/src/ir-to-client-js/prop-handling.ts +13 -54
  174. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  175. package/src/ir-to-client-js/reactivity.ts +2 -2
  176. package/src/ir-to-client-js/rewrite-destructured-props.ts +27 -9
  177. package/src/ir-to-client-js/safe-html.ts +29 -35
  178. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  179. package/src/ir-to-client-js/types.ts +3 -2
  180. package/src/ir-to-client-js/utils.ts +13 -26
  181. package/src/jsx-to-ir.ts +318 -130
  182. package/src/nullable-signal-attr.ts +156 -37
  183. package/src/prop-rewrite.ts +41 -0
  184. package/src/props-binding.ts +117 -7
  185. package/src/relocate.ts +40 -8
  186. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  187. package/src/scanner/js-scanner.ts +64 -4
  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 +121 -29
  191. package/src/types.ts +165 -21
  192. package/src/value-references.ts +132 -0
@@ -8,6 +8,8 @@ import { describe, test, expect } from 'bun:test'
8
8
  import {
9
9
  isEmptyComponentProps,
10
10
  planComponentProps,
11
+ propsSpreadParam,
12
+ resolveComponentPropKeys,
11
13
  spellComponentProps,
12
14
  type ComponentPropEntry,
13
15
  type ComponentPropsOptions,
@@ -64,6 +66,7 @@ function spell(comp: IRComponent, options = noProps): string[] {
64
66
  return spellComponentProps(planComponentProps(comp, options), {
65
67
  entry: describe,
66
68
  spread: (value) => value.expr,
69
+ presentParam: (name) => `${name}?=$${name}`,
67
70
  }).map((segment) => (segment.kind === 'spread' ? `...${segment.expr}` : `{${segment.parts.join(', ')}}`))
68
71
  }
69
72
 
@@ -101,8 +104,30 @@ describe('planComponentProps', () => {
101
104
  test('a repeated key keeps its first position and takes the later value', () => {
102
105
  const later = component([prop('', spread('props')), prop('tone', literal('explicit'))])
103
106
  expect(spell(later, withProps)).toEqual([`{tone='explicit', size=$size, _bf_slot='s0'}`])
107
+ })
108
+
109
+ test('{...props} after an explicit prop carries that key only when the caller passed it', () => {
104
110
  const earlier = component([prop('tone', literal('first')), prop('', spread('props'))])
105
- expect(spell(earlier, withProps)).toEqual([`{tone=$tone, size=$size, _bf_slot='s0'}`])
111
+ expect(spell(earlier, withProps)).toEqual([`{tone='first'}`, '...tone?=$tone', `{size=$size, _bf_slot='s0'}`])
112
+ })
113
+
114
+ test('{...props} after a spread of unknown keys carries every key only when passed', () => {
115
+ const comp = component([prop('', spread('rest')), prop('', spread('props'))], { slotId: null })
116
+ expect(spell(comp, withProps)).toEqual(['{}', '...rest', '...tone?=$tone', '...size?=$size'])
117
+ })
118
+
119
+ test('a required param always wins: the caller always passes it', () => {
120
+ const required: ComponentPropsOptions = {
121
+ propsObjectName: 'props',
122
+ propsParams: [{ name: 'tone', optional: false }, { name: 'size', optional: true }],
123
+ }
124
+ const comp = component([prop('tone', literal('first')), prop('size', literal('s')), prop('', spread('props'))])
125
+ expect(spell(comp, required)).toEqual([`{tone=$tone, size='s'}`, '...size?=$size', `{_bf_slot='s0'}`])
126
+ })
127
+
128
+ test('an explicit prop after the spread replaces a passed-only key', () => {
129
+ const comp = component([prop('tone', literal('a')), prop('', spread('props')), prop('tone', literal('z'))])
130
+ expect(spell(comp, withProps)).toEqual([`{tone='a'}`, '...tone?=$tone', `{size=$size, tone='z', _bf_slot='s0'}`])
106
131
  })
107
132
 
108
133
  test('a key repeated across a spread stays twice: the spread may set it in between', () => {
@@ -124,6 +149,47 @@ describe('planComponentProps', () => {
124
149
  })
125
150
  })
126
151
 
152
+ describe('propsSpreadParam', () => {
153
+ const none = { keys: new Set<string>(), spread: false }
154
+ test('nothing earlier sets the key: an ordinary entry', () => {
155
+ expect(propsSpreadParam({ name: 'tone' }, none)).toBe('entry')
156
+ })
157
+ test('an earlier entry or an earlier spread may set the key: only when passed', () => {
158
+ expect(propsSpreadParam({ name: 'tone' }, { keys: new Set(['tone']), spread: false })).toBe('present')
159
+ expect(propsSpreadParam({ name: 'tone', optional: true }, { keys: new Set(), spread: true })).toBe('present')
160
+ })
161
+ test('a required param is always passed, so it always wins', () => {
162
+ expect(propsSpreadParam({ name: 'tone', optional: false }, { keys: new Set(['tone']), spread: true })).toBe('entry')
163
+ })
164
+ })
165
+
166
+ describe('resolveComponentPropKeys', () => {
167
+ test('per key, in first-set order: the passed param over the latest unconditional entry', () => {
168
+ const comp = component([prop('tone', literal('first')), prop('size', literal('s')), prop('', spread('props'))], {
169
+ slotId: null,
170
+ })
171
+ const resolved = resolveComponentPropKeys(planComponentProps(comp, withProps))!
172
+ expect(resolved.map((r) => [r.key, r.base?.kind, r.presentParams])).toEqual([
173
+ ['tone', 'value', ['tone']],
174
+ ['size', 'value', ['size']],
175
+ ])
176
+ })
177
+
178
+ test('a later entry clears the passed-only params before it', () => {
179
+ const comp = component([prop('tone', literal('a')), prop('', spread('props')), prop('tone', literal('z'))], {
180
+ slotId: null,
181
+ })
182
+ const tone = resolveComponentPropKeys(planComponentProps(comp, withProps))!.find((r) => r.key === 'tone')!
183
+ expect(tone.presentParams).toEqual([])
184
+ expect(tone.base).toEqual({ kind: 'value', name: 'tone', value: literal('z') })
185
+ })
186
+
187
+ test('a spread of unknown keys cannot be resolved at compile time', () => {
188
+ const comp = component([prop('', spread('rest')), prop('', spread('props'))])
189
+ expect(resolveComponentPropKeys(planComponentProps(comp, withProps))).toBeNull()
190
+ })
191
+ })
192
+
127
193
  describe('spellComponentProps', () => {
128
194
  test('spells entries in source order and drops an empty part', () => {
129
195
  const order: string[] = []
@@ -136,6 +202,7 @@ describe('spellComponentProps', () => {
136
202
  return entry.kind === 'value' ? '' : 'part'
137
203
  },
138
204
  spread: () => '',
205
+ presentParam: () => '',
139
206
  })
140
207
  expect(order).toEqual(['a', 'b', 'c', 'slot-id', 'children'])
141
208
  expect(segments).toEqual([{ kind: 'entries', parts: ['part', 'part', 'part', 'part'] }])
@@ -0,0 +1,101 @@
1
+ // A template reads a computed const as its initializer (#3494): the shared
2
+ // substitution every template adapter applies before lowering an
3
+ // expression, against metadata built by the real pipeline.
4
+
5
+ import { describe, test, expect } from 'bun:test'
6
+ import { analyzeComponent } from '../analyzer'
7
+ import { buildMetadata } from '../compiler'
8
+ import { parseExpression, stringifyParsedExpr } from '../expression-parser'
9
+ import { computedConstContext, inlineComputedConsts } from '../adapters/computed-const'
10
+
11
+ function inliner(source: string, shadowed: readonly string[] = [], adapterBound: readonly string[] = []) {
12
+ const metadata = buildMetadata(analyzeComponent(source, 'test.tsx'))
13
+ const ctx = computedConstContext(metadata, name => shadowed.includes(name), name => adapterBound.includes(name))
14
+ return (expr: string) => stringifyParsedExpr(inlineComputedConsts(parseExpression(expr), ctx))
15
+ }
16
+
17
+ describe('inlineComputedConsts (#3494)', () => {
18
+ const source = `
19
+ 'use client'
20
+ import { createSignal, useContext, createContext } from '@barefootjs/client'
21
+ const Theme = createContext('light')
22
+ function makeLabel() { return 'x' }
23
+ export function C(props: { v: string; n: number; label?: string; labels: Record<string, string> }) {
24
+ const [count] = createSignal(1)
25
+ const cls = 'btn ' + props.v
26
+ const wide = cls + ' w-full'
27
+ const twice = props.n * 2
28
+ const doubled = count() * 2
29
+ const fallback = props.label ?? 'Default'
30
+ const keys = Object.keys(props.labels)
31
+ const total = 5
32
+ const opaque = makeLabel()
33
+ const theme = useContext(Theme)
34
+ const format = (s: string) => s.trim()
35
+ return <p class={wide}>{twice}{doubled}{fallback}{keys.length}{total}{opaque}{theme}{format('a')}</p>
36
+ }
37
+ `
38
+
39
+ test('a const computed from props reads as its initializer, through a const of a const', () => {
40
+ const inline = inliner(source)
41
+ expect(inline('twice')).toBe('props.n * 2')
42
+ expect(inline('wide')).toBe('"btn " + props.v + " w-full"')
43
+ expect(inline('fallback')).toBe('props.label ?? "Default"')
44
+ })
45
+
46
+ test('a signal read stays a getter call inside the initializer', () => {
47
+ expect(inliner(source)('doubled')).toBe('count() * 2')
48
+ })
49
+
50
+ test('an initializer no template lowers is still substituted, for the adapter to refuse', () => {
51
+ expect(inliner(source)('keys.length')).toBe('Object.keys(props.labels).length')
52
+ })
53
+
54
+ test('a literal const, an opaque accessor, a context consumer and a function stay as read', () => {
55
+ const inline = inliner(source)
56
+ for (const name of ['total', 'opaque', 'theme']) expect(inline(name)).toBe(name)
57
+ expect(inline("format('a')")).toBe('format("a")')
58
+ })
59
+
60
+ test('a name a loop row binds at the read site is the row, not the const', () => {
61
+ expect(inliner(source, ['twice'])('twice')).toBe('twice')
62
+ })
63
+
64
+ test('an initializer whose free name the read site rebinds is left alone', () => {
65
+ expect(inliner(source, ['props'])('twice')).toBe('twice')
66
+ })
67
+
68
+ test('a const the adapter binds itself stays as read, also inside another initializer', () => {
69
+ const inline = inliner(source, [], ['cls'])
70
+ expect(inline('cls')).toBe('cls')
71
+ expect(inline('wide')).toBe('cls + " w-full"')
72
+ })
73
+
74
+ test('a callback param shadowing the name keeps the param', () => {
75
+ expect(inliner(source)('rows.map(twice => twice + 1)')).toBe('rows.map(twice => twice + 1)')
76
+ })
77
+
78
+ test('a props destructure binding stays as read: the adapter binds it as a props param', () => {
79
+ const inline = inliner(`
80
+ function A(props: { value: number; label?: string }) {
81
+ const { value, label: text = 'none' } = props
82
+ const shown = text + '!'
83
+ return <div>{value}{text}{shown}</div>
84
+ }
85
+ export { A }
86
+ `)
87
+ expect(inline('text')).toBe('text')
88
+ expect(inline('value')).toBe('value')
89
+ expect(inline('shown')).toBe('text + "!"')
90
+ })
91
+
92
+ test('a const named like a prop with no default of its own still reads as its initializer', () => {
93
+ const inline = inliner(`
94
+ export function B(props: { label?: string }) {
95
+ const label = props.label ?? 'Default'
96
+ return <p>{label}</p>
97
+ }
98
+ `)
99
+ expect(inline('label')).toBe('props.label ?? "Default"')
100
+ })
101
+ })
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Constant inlining in the client JS runs on the expression tree (#3535).
3
+ *
4
+ * The component template used to inline a constant with
5
+ * ``text.replace(new RegExp(`(?<![-.])\\b${name}\\b`), `(${value})`)`` behind
6
+ * a quoted-string protector. The static segments of a template literal and an
7
+ * object-literal shorthand were exposed, so `` `btn size-${size}` `` rendered
8
+ * `btn ('lg')-lg` and `{ size }` became the SyntaxError `{ ('lg') }`.
9
+ */
10
+
11
+ import { describe, test, expect } from 'bun:test'
12
+ import { compileJSX } from '../compiler'
13
+ import { TestAdapter } from '../adapters/test-adapter'
14
+ import { resolveChainedRefs } from '../ir-to-client-js/emit-registration'
15
+
16
+ const adapter = new TestAdapter()
17
+ const transpiler = new Bun.Transpiler({ loader: 'js' })
18
+
19
+ function clientJs(locals: string, jsx: string): string {
20
+ const source = `
21
+ 'use client'
22
+ import { createSignal } from '@barefootjs/client'
23
+ export function T(props: { label: string; items: string[] }) {
24
+ const [on, setOn] = createSignal(false)
25
+ ${locals}
26
+ return ${jsx}
27
+ }
28
+ `
29
+ const result = compileJSX(source, 'T.tsx', { adapter })
30
+ expect(result.errors).toHaveLength(0)
31
+ const js = result.files.find(f => f.type === 'clientJs')!.content
32
+ expect(() => transpiler.transformSync(js)).not.toThrow()
33
+ return js
34
+ }
35
+
36
+ /** The `template: (_p) => …` lambda the client registers for CSR. */
37
+ function templateOf(js: string): string {
38
+ const line = js.split('\n').find(l => l.includes('template: (_p) =>'))
39
+ expect(line).toBeDefined()
40
+ return line!
41
+ }
42
+
43
+ const button = (attrs: string) => `<button ${attrs} onClick={() => setOn(!on())}>{props.label}</button>`
44
+
45
+ describe('constant inlining on the tree (#3535)', () => {
46
+ test('a template-literal static segment that spells the constant is kept', () => {
47
+ const tpl = templateOf(clientJs("const size = 'lg'", button('className={`btn size-${size}`}')))
48
+ expect(tpl).not.toContain("('lg')-")
49
+ expect(tpl).toContain("size-${('lg')}")
50
+ })
51
+
52
+ test('an object-literal shorthand expands to a key-value pair', () => {
53
+ const tpl = templateOf(clientJs("const size = 'lg'", button('data-o={JSON.stringify({ size })}')))
54
+ expect(tpl).toContain("size: ('lg')")
55
+ })
56
+
57
+ test('a member name and a string spelling the constant are kept', () => {
58
+ const tpl = templateOf(clientJs("const size = 'lg'", button("data-o={props.label.size + 'size'}")))
59
+ expect(tpl).toContain('.size')
60
+ expect(tpl).toContain("'size'")
61
+ })
62
+
63
+ test('a $-named constant is inlined', () => {
64
+ const tpl = templateOf(clientJs("const size$ = 'lg'", button('data-size={size$}')))
65
+ expect(tpl).not.toMatch(/\bsize\$/)
66
+ expect(tpl).toContain('lg')
67
+ })
68
+
69
+ test('a loop row binding that shadows the constant is not replaced', () => {
70
+ const js = clientJs(
71
+ "const item = 'outer'",
72
+ "<ul data-x={item}>{props.items.map(item => <li key={item}>{item}</li>)}</ul>",
73
+ )
74
+ expect(js).not.toContain("key={('outer')}")
75
+ })
76
+ })
77
+
78
+ /** Runs the registered template lambda against `props`, as a CSR mount would. */
79
+ function renderTemplate(js: string, props: Record<string, unknown>): string {
80
+ const line = templateOf(js)
81
+ const lambda = line.slice(line.indexOf('template: (_p) =>') + 'template: '.length).replace(/ \}\)\s*$/, '')
82
+ const escape = (v: unknown) => String(v ?? '')
83
+ const run = new Function('escapeAttr', 'escapeText', 'escapeTextOrMarkup', 'markupOrEmpty', `return (${lambda})`)
84
+ return run(escape, escape, escape, escape)(props)
85
+ }
86
+
87
+ describe('computed object keys (#3535 review)', () => {
88
+ test('a constant in a computed key is inlined, so the template runs', () => {
89
+ const js = clientJs("const size = 'lg'", button('data-o={JSON.stringify({ [size]: props.label })}'))
90
+ expect(templateOf(js)).toContain("[('lg')]")
91
+ expect(() => renderTemplate(js, { label: 'hello' })).not.toThrow()
92
+ })
93
+
94
+ test('a compound computed key is inlined too', () => {
95
+ const js = clientJs("const size = 'lg'", button("data-o={JSON.stringify({ [size + '!']: props.label })}"))
96
+ expect(() => renderTemplate(js, { label: 'hello' })).not.toThrow()
97
+ })
98
+ })
99
+
100
+ describe('resolveChainedRefs', () => {
101
+ test('resolves a chain on the tree, leaving strings and member names alone', () => {
102
+ const constants = new Map([
103
+ ['base', "'lg'"],
104
+ ['cls', '`btn base-${base}`'],
105
+ ['opts', '({ base, other: o.base })'],
106
+ ])
107
+ resolveChainedRefs(constants)
108
+ expect(constants.get('cls')).toBe("`btn base-${('lg')}`")
109
+ expect(constants.get('opts')).toBe("({ base: ('lg'), other: o.base })")
110
+ })
111
+
112
+ test('a computed key in a chained constant is resolved', () => {
113
+ const constants = new Map([
114
+ ['size', "'lg'"],
115
+ ['obj', '({ [size]: 1 })'],
116
+ ])
117
+ resolveChainedRefs(constants)
118
+ expect(constants.get('obj')).toBe("({ [('lg')]: 1 })")
119
+ })
120
+
121
+ test('a value brought in by a substitution is resolved too', () => {
122
+ const constants = new Map([
123
+ ['a', 'b + 1'],
124
+ ['b', 'c * 2'],
125
+ ['c', '3'],
126
+ ])
127
+ const freeIds = new Map([
128
+ ['a', new Set(['b'])],
129
+ ['b', new Set(['c'])],
130
+ ['c', new Set<string>()],
131
+ ])
132
+ resolveChainedRefs(constants, freeIds)
133
+ expect(constants.get('a')).toBe('((3) * 2) + 1')
134
+ expect([...freeIds.get('a')!]).toEqual([])
135
+ })
136
+ })
@@ -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
+ })