@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
@@ -0,0 +1,78 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer'
3
+ import { jsxToIR } from '../jsx-to-ir'
4
+ import type { CompilerError, IRElement, IRNode } from '../types'
5
+ import type { AttrValueEmitter } from '../adapters/attr-value-emitter'
6
+ import { renderElementShell, renderFragmentScope, type ElementShellSpelling } from '../adapters/element-shell'
7
+ import { renderDangerousInnerHtml } from '../adapters/dangerous-inner-html'
8
+
9
+ // #3475: the element every template adapter writes the same way, with the
10
+ // adapter's spelling supplied as data.
11
+ function root(source: string): IRNode {
12
+ const ir = jsxToIR(analyzeComponent(source, 'Test.tsx'))
13
+ if (!ir) throw new Error('expected IR')
14
+ return ir
15
+ }
16
+
17
+ const attrEmitter: AttrValueEmitter = {
18
+ emitLiteral: (value, name) => `${name}="${value.value}"`,
19
+ emitExpression: (value, name) => `${name}="<${value.expr}>"`,
20
+ emitBooleanAttr: (_value, name) => name,
21
+ emitBooleanShorthand: (_value, name) => name,
22
+ emitTemplate: (_value, name) => `${name}="<tpl>"`,
23
+ emitSpread: () => '',
24
+ emitJsxChildren: () => '',
25
+ }
26
+
27
+ function spelling(errors: CompilerError[] = []): ElementShellSpelling {
28
+ return {
29
+ attrEmitter,
30
+ renderDangerousInnerHtml: element =>
31
+ renderDangerousInnerHtml(element, errors, 'jinja', expr => `[raw ${expr}]`),
32
+ renderChildren: (children) => children.map(c => (c.type === 'text' ? c.value : `{${c.type}}`)).join(''),
33
+ renderScopeMarker: () => 'bf-s="SCOPE"',
34
+ renderSlotMarker: slotId => `bf="${slotId}"`,
35
+ dataKeyRelay: 'RELAY',
36
+ scopeIdValue: 'SCOPE_ID',
37
+ wrapSsrPortalElement: rendered => `[portal ${rendered}]`,
38
+ }
39
+ }
40
+
41
+ describe('renderElementShell (#3475)', () => {
42
+ test('renders attributes, the root markers, children, and the close tag', () => {
43
+ // A render root relays its caller's row key, in the adapter's spelling.
44
+ const el = root(`function Test() { return <p className="a" id="x">hi</p> }\nexport { Test }`) as IRElement
45
+ expect(renderElementShell(el, spelling())).toBe('<p class="a" id="x" bf-s="SCOPE" RELAY>hi</p>')
46
+ })
47
+
48
+ test('a void element has no children or close tag', () => {
49
+ const el = root(`function Test() { return <input type="text" /> }\nexport { Test }`) as IRElement
50
+ expect(renderElementShell(el, spelling())).toBe('<input type="text" bf-s="SCOPE" RELAY>')
51
+ })
52
+
53
+ test('a dynamic dangerouslySetInnerHTML replaces the children through the raw sink', () => {
54
+ const el = root(
55
+ `function Test({ html }: { html: string }) { return <div dangerouslySetInnerHTML={{ __html: html }}>x</div> }\nexport { Test }`,
56
+ ) as IRElement
57
+ expect(renderElementShell(el, spelling())).toContain('>[raw html]</div>')
58
+ })
59
+
60
+ test('an unlowerable dangerouslySetInnerHTML records BF101 and renders empty', () => {
61
+ const el = root(
62
+ `function Test({ v }: { v: { __html: string } }) { return <div dangerouslySetInnerHTML={v} /> }\nexport { Test }`,
63
+ ) as IRElement
64
+ const errors: CompilerError[] = []
65
+ expect(renderElementShell(el, spelling(errors))).toMatch(/><\/div>$/)
66
+ expect(errors.map(e => e.code)).toEqual(['BF101'])
67
+ })
68
+ })
69
+
70
+ describe('renderFragmentScope (#3475)', () => {
71
+ test('wraps a component-root fragment in its scope comment, else returns the children', () => {
72
+ const fragment = { type: 'fragment', children: [], needsScopeComment: true } as never
73
+ const render = () => 'kids'
74
+ expect(renderFragmentScope(fragment, render, r => `<!--s-->${r}<!--/s-->`)).toBe('<!--s-->kids<!--/s-->')
75
+ const plain = { type: 'fragment', children: [], needsScopeComment: false } as never
76
+ expect(renderFragmentScope(plain, render, r => `<!--s-->${r}<!--/s-->`)).toBe('kids')
77
+ })
78
+ })
@@ -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
  // =============================================================================
@@ -0,0 +1,96 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { foldRenderReassignmentsInSource } from '../fold-render-reassignments.ts'
3
+
4
+ /**
5
+ * A `let`'s render-time reassignments fold into its initializer (#3501), so
6
+ * every stage reads the one value the binding holds when the component
7
+ * returns. Only side-effect-free reassignments that directly follow the
8
+ * declaration fold; anything else is left as written.
9
+ */
10
+ function fold(body: string): string | null {
11
+ const out = foldRenderReassignmentsInSource(`export function S(props: { label?: string }) {\n${body}\n return <p>{label}</p>\n}\n`, 'S.tsx')
12
+ return out === null ? null : out.split('\n').slice(1, -3).join('\n')
13
+ }
14
+
15
+ describe('foldRenderReassignmentsInSource', () => {
16
+ test('an `if` reassignment becomes a conditional over the value so far', () => {
17
+ const [decl, removed] = fold(" let label = props.label ?? 'Default'\n if (!label) label = 'Fallback'")!.split('\n')
18
+ expect(decl).toBe(" const label_1 = props.label ?? 'Default'; let label = ((!(label_1)) ? ('Fallback') : (label_1))")
19
+ expect(removed!.trim()).toBe('')
20
+ })
21
+
22
+ test('`if`/`else`, blocks and compound assignments fold in order', () => {
23
+ const out = fold(" let label = 'a'\n if (props.label) { label = props.label } else { label += '!' }\n label ??= 'z'")
24
+ expect(out?.split('\n')[0]).toBe(
25
+ " const label_1 = ((props.label) ? (props.label) : ((('a') + ('!')))); let label = ((label_1) ?? ('z'))",
26
+ )
27
+ })
28
+
29
+ test('removed statements keep their lines, so later locations stay valid', () => {
30
+ const body = " let label = 'a'\n if (props.label) {\n label = 'b'\n }"
31
+ expect(fold(body)?.split('\n').length).toBe(body.split('\n').length)
32
+ })
33
+
34
+ test('a computed value inside a statement that would be repeated, reordered or dropped is not folded', () => {
35
+ expect(fold(" let label = 'a'\n if (props.label) { label = props.label; label = label + label }")).toBeNull()
36
+ expect(fold(" let label = 'a'\n if (props.label) { label = props.label; label = props.b + label }")).toBeNull()
37
+ expect(fold(' let label = 0\n { label = props.label; label = 7 }')).toBeNull()
38
+ expect(fold(" let label = 'a'\n { label = props.label; if (props.b) label = 1 }")).toBeNull()
39
+ })
40
+
41
+ test('a reassignment with a side effect is not folded', () => {
42
+ expect(fold(" let label = 'a'\n if (check()) label = 'b'")).toBeNull()
43
+ expect(fold(" let label = 'a'\n label = make()")).toBeNull()
44
+ })
45
+
46
+ test('a reassignment after an unrelated statement is not folded', () => {
47
+ expect(fold(" let label = 'a'\n console.log(label)\n label = 'b'")).toBeNull()
48
+ })
49
+
50
+ test('a reassignment in a loop is not folded', () => {
51
+ expect(fold(" let label = 'a'\n for (const t of [1]) label = 'b'")).toBeNull()
52
+ })
53
+
54
+ test('a `const` and a `let` with no reassignment are left as written', () => {
55
+ expect(fold(" const label = 'a'")).toBeNull()
56
+ expect(fold(" let label = 'a'")).toBeNull()
57
+ })
58
+ })
59
+
60
+ /**
61
+ * The folded source evaluates every expression as often, and in the same
62
+ * order, as the original: a getter on the props object observes the same
63
+ * reads and the binding ends with the same value.
64
+ */
65
+ describe('folding preserves evaluation', () => {
66
+ const bodies = [
67
+ "let label = props.label ?? 'Default'\n if (!label) label = 'Fallback'",
68
+ 'let label = props.label\n if (label) label = 0',
69
+ "let label = props.label\n if (props.label) { label = props.label } else { label += '!' }\n label ??= 'z'",
70
+ "let label = 'a'\n if (props.label) { label = props.label; label += '!' }",
71
+ "let label = 0\n label = props.label\n label = 7",
72
+ ]
73
+ const run = (source: string, values: unknown[]) => {
74
+ const log: unknown[] = []
75
+ let k = 0
76
+ const props = {
77
+ get label() {
78
+ const v = values[k++ % values.length]
79
+ log.push(v)
80
+ return v
81
+ },
82
+ }
83
+ const fn = new Function('props', source.slice(source.indexOf('{') + 1, source.lastIndexOf('}')))
84
+ return { value: fn(props), log }
85
+ }
86
+ for (const body of bodies) {
87
+ for (const values of [[undefined], [''], ['x'], [0, 1, 2]]) {
88
+ test(`${JSON.stringify(body)} with label reads ${JSON.stringify(values)}`, () => {
89
+ const original = `function S(props) {\n ${body}\n return label\n}\n`
90
+ const folded = foldRenderReassignmentsInSource(original, 'S.js')
91
+ expect(folded).not.toBeNull()
92
+ expect(run(folded!, values)).toEqual(run(original, values))
93
+ })
94
+ }
95
+ }
96
+ })
@@ -0,0 +1,81 @@
1
+ /**
2
+ * #3513: a const read through a method call on another const that is itself
3
+ * inlinable into the CSR template (`const text = props.label ?? 'd'; const
4
+ * upper = text.toUpperCase()`) inlines as the call on that value, as the
5
+ * same chain without a call (`label + '!'`) already did. Before, the
6
+ * init-local receiver failed the adapter's call acceptance, `upper` reported
7
+ * BF061 and the template slot fell back to `undefined`.
8
+ *
9
+ * Both template paths are covered: the static template (no signal) and the
10
+ * CSR template a component with a signal registers, which reads
11
+ * `ctx.csrInlinable`. A receiver that is classified inlinable but gets no
12
+ * CSR form (`(choices).includes(name)`) withdraws the acceptance, so the call
13
+ * reports BF061 again instead of rendering `undefined.toUpperCase()`.
14
+ */
15
+
16
+ import { describe, test, expect } from 'bun:test'
17
+ import { compileJSX } from '../compiler'
18
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
19
+
20
+ const SIGNAL_PRELUDE = "'use client'\nimport { createSignal } from '@barefootjs/client'\n"
21
+
22
+ function compile(body: string, { prelude = '', signal = false } = {}) {
23
+ const head = signal ? `${SIGNAL_PRELUDE}${prelude}` : prelude
24
+ const signalDecl = signal ? 'const [count] = createSignal(0)\n' : ''
25
+ const source = `${head}export function S(props: { label?: string }) {\n${signalDecl}${body}\n}`
26
+ const result = compileJSX(source, 'S.tsx', { adapter: new HonoAdapter() })
27
+ const clientJs = result.files.find((f) => f.path.endsWith('.client.js'))?.content ?? ''
28
+ const line = clientJs.split('\n').find((l) => l.includes('hydrate(')) ?? ''
29
+ return { errors: result.errors.map((e) => e.code), template: line }
30
+ }
31
+
32
+ /** Evaluate the registered `template:` lambda against `props`. */
33
+ function render(template: string, props: Record<string, unknown>): string {
34
+ const lambda = template.match(/template: (\(_p\) => `.*`) \}\)/)?.[1]
35
+ expect(lambda).toBeDefined()
36
+ return new Function('escapeAttr', 'escapeTextOrMarkup', `return ${lambda}`)(String, String)(props)
37
+ }
38
+
39
+ const CHAINS: [string, string, string][] = [
40
+ ["const text = props.label ?? 'd'\nconst upper = text.toUpperCase()", 'upper', 'ABC'],
41
+ ["const label = props.label ?? 'd'\nconst upper = label.toUpperCase()", 'upper', 'ABC'],
42
+ ["const text = props.label ?? 'd'\nconst upper = text.toUpperCase()\nconst lower = upper.toLowerCase()", 'lower', 'abc'],
43
+ ]
44
+
45
+ describe('a method call on an inlinable local inlines (#3513)', () => {
46
+ test.each(CHAINS)('static template: %s', (decls, read, rendered) => {
47
+ const { errors, template } = compile(`${decls}\nreturn <p title={${read}}>{${read}}</p>`)
48
+ expect(errors).not.toContain('BF061')
49
+ expect(template).toContain("(_p.label ?? 'd').toUpperCase()")
50
+ expect(template).not.toContain('escapeAttr(undefined)')
51
+ expect(render(template, { label: 'aBc' })).toContain(`title="${rendered}"`)
52
+ })
53
+
54
+ test.each(CHAINS)('CSR template: %s', (decls, read, rendered) => {
55
+ const { errors, template } = compile(`${decls}\nreturn <p title={${read}}>{count()}</p>`, { signal: true })
56
+ expect(errors).not.toContain('BF061')
57
+ expect(template).toContain("(_p.label ?? 'd').toUpperCase()")
58
+ expect(render(template, { label: 'aBc' })).toContain(`title="${rendered}"`)
59
+ })
60
+
61
+ test('a method call on a local that does not inline still reports BF061', () => {
62
+ const { errors, template } = compile(
63
+ 'function readItems() { return [props.label] }\nconst items = readItems()\nconst first = items.join()\nreturn <p title={first}>{first}</p>',
64
+ )
65
+ expect(errors).toContain('BF061')
66
+ expect(template).not.toContain('items.join()')
67
+ })
68
+
69
+ test.each([
70
+ ['const upper = text.toUpperCase()', 'upper'],
71
+ ['const upper = text.toUpperCase()\nconst lower = upper.toLowerCase()', 'lower'],
72
+ ])('a receiver refused after classification withdraws the call: %s', (decls, read) => {
73
+ const { errors, template } = compile(
74
+ `const text = (choices).includes(props.label) ? 'yes' : 'no'\n${decls}\nreturn <p title={${read}}>{count()}</p>`,
75
+ { prelude: "const choices = ['a']\n", signal: true },
76
+ )
77
+ expect(errors).toContain('BF061')
78
+ expect(template).not.toContain('undefined.')
79
+ expect(() => render(template, { label: 'a' })).not.toThrow()
80
+ })
81
+ })
@@ -0,0 +1,120 @@
1
+ /**
2
+ * #3510: a memo's value expression is read from the callback node
3
+ * (`MemoInfo.bodyExpr`), not by matching `() =>` in `computation`.
4
+ * Consumers substitute it for `memo()`, so every callback shape must yield
5
+ * an expression that evaluates to the memo's value — never the uncalled
6
+ * function.
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
+
14
+ function memoOf(callback: string, props = '') {
15
+ const source = `
16
+ 'use client'
17
+ import { createSignal, createMemo } from '@barefootjs/client'
18
+ export function C(${props}) {
19
+ const [count] = createSignal(2)
20
+ const m = createMemo(${callback})
21
+ return <p>{m()}</p>
22
+ }
23
+ `
24
+ const memo = analyzeComponent(source, 'C.tsx').memos.find((x) => x.name === 'm')
25
+ if (!memo) throw new Error('memo not collected')
26
+ return memo
27
+ }
28
+
29
+ describe('MemoInfo.bodyExpr (#3510)', () => {
30
+ test.each([
31
+ ['() => count() * 2', 'count() * 2'],
32
+ ['(): number => count() * 2', 'count() * 2'],
33
+ ['() => { return count() * 2 }', 'count() * 2'],
34
+ ['function () { return count() * 2 }', 'count() * 2'],
35
+ ['(() => count() * 2)', 'count() * 2'],
36
+ ['(function () { return count() * 2 })', 'count() * 2'],
37
+ ])('%s yields its returned expression', (callback, expected) => {
38
+ expect(memoOf(callback).bodyExpr).toBe(expected)
39
+ })
40
+
41
+ test('a multi-statement body yields a call of the whole callback', () => {
42
+ expect(memoOf('() => { const k = count(); return k * 3 }').bodyExpr)
43
+ .toBe('(() => { const k = count(); return k * 3 })()')
44
+ expect(memoOf('function () { const k = count(); return k * 3 }').bodyExpr)
45
+ .toBe('(function () { const k = count(); return k * 3 })()')
46
+ })
47
+
48
+ test('a callback that is not a plain zero-parameter function is called as written', () => {
49
+ expect(memoOf('async () => count()').bodyExpr).toBe('(async () => count())()')
50
+ expect(memoOf('count').bodyExpr).toBe('(count)()')
51
+ })
52
+
53
+ test('templateBodyExpr rewrites a destructured prop read in the body', () => {
54
+ const memo = memoOf('function () { return count() + base }', '{ base }: { base: number }')
55
+ expect(memo.bodyExpr).toBe('count() + base')
56
+ expect(memo.templateBodyExpr).toBe('count() + _p.base')
57
+ })
58
+
59
+ test('a function expression carries the same structured parse as a block arrow', () => {
60
+ const fn = memoOf('function () { return count() * 2 }')
61
+ const arrow = memoOf('() => { return count() * 2 }')
62
+ expect(fn.parsedBlock).toEqual(arrow.parsedBlock)
63
+ expect(fn.parsedBlockComplete).toBe(true)
64
+ })
65
+
66
+ test('a function expression that needs its own scope is called as a whole', () => {
67
+ for (const callback of [
68
+ 'function base() { return typeof base }',
69
+ 'function () { return arguments.length }',
70
+ 'function () { return this }',
71
+ 'function () { return Object.keys({ [arguments.length]() {} })[0] }',
72
+ 'function () { return class extends (this ? Object : Object) {} }',
73
+ ]) {
74
+ const memo = memoOf(callback, '{ base }: { base: number }')
75
+ expect(memo.bodyExprIsCall).toBe(true)
76
+ expect(memo.bodyExpr).toBe(`(${callback})()`)
77
+ expect(memo.parsedBlock).toBeUndefined()
78
+ }
79
+ })
80
+
81
+ test('the CSR template evaluates a scope-bound callback to its own value', () => {
82
+ const source = `
83
+ 'use client'
84
+ import { createMemo } from '@barefootjs/client'
85
+ export function C({ base }: { base: number }) {
86
+ const named = createMemo(function base() { return typeof base })
87
+ const args = createMemo(function () { return arguments.length })
88
+ return <p>{named()}|{args()}</p>
89
+ }
90
+ `
91
+ const result = compileJSX(source, 'C.tsx', { adapter: new TestAdapter() })
92
+ const line = result.files.find((f) => f.type === 'clientJs')!.content.split('\n').find((l) => l.includes('hydrate('))!
93
+ const lambda = line.match(/template: (\(_p\) => `.*`) \}\)$/)![1]
94
+ const template = new Function('escapeTextOrMarkup', 'escapeText', 'escapeAttr', `return ${lambda}`)(String, String, String)
95
+ const html = template({ base: 7 })
96
+ expect(html).toContain('-->function<!--')
97
+ expect(html).toContain('-->0<!--')
98
+ })
99
+
100
+ test('a callback whose nested function only binds its own scope is still extracted', () => {
101
+ const memo = memoOf('function () { return [1].map(function () { return arguments.length })[0] }')
102
+ expect(memo.bodyExprIsCall).toBeUndefined()
103
+ })
104
+
105
+ test('a computed method name reading the callback\'s arguments renders its own value', () => {
106
+ const source = `
107
+ 'use client'
108
+ import { createMemo } from '@barefootjs/client'
109
+ export function C() {
110
+ const key = createMemo(function () { return Object.keys({ [arguments.length]() {} })[0] })
111
+ return <p>{key()}</p>
112
+ }
113
+ `
114
+ const result = compileJSX(source, 'C.tsx', { adapter: new TestAdapter() })
115
+ const line = result.files.find((f) => f.type === 'clientJs')!.content.split('\n').find((l) => l.includes('hydrate('))!
116
+ const lambda = line.match(/template: (\(_p\) => `.*`) \}\)$/)![1]
117
+ const template = new Function('escapeTextOrMarkup', 'escapeText', 'escapeAttr', `return ${lambda}`)(String, String, String)
118
+ expect(template({})).toContain('-->0<!--')
119
+ })
120
+ })
@@ -3,7 +3,9 @@ import { analyzeComponent } from '../analyzer'
3
3
  import { parseExpression } from '../expression-parser'
4
4
  import {
5
5
  arithmeticOperandCoercion,
6
+ arithmeticOperandIsUndefined,
6
7
  attrValueMayBeNullish,
8
+ collectAbsentPropSeedReads,
7
9
  collectNullableSignalGetters,
8
10
  collectNullishAttrContext,
9
11
  nullableSignalAttrGetter,
@@ -50,6 +52,47 @@ describe('collectNullableSignalGetters (#3304)', () => {
50
52
  })
51
53
  })
52
54
 
55
+ function componentIR(params: string, decls: string): ComponentIR {
56
+ const source = `
57
+ 'use client'
58
+ import { createSignal } from '@barefootjs/client'
59
+ export function C(${params}) {
60
+ ${decls}
61
+ return <p>x</p>
62
+ }
63
+ `
64
+ return { metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR
65
+ }
66
+
67
+ describe('signals seeded from an absent optional prop (#3567)', () => {
68
+ test('a bare read, a ternary branch and a `??` right operand are nullable', () => {
69
+ const ir = componentIR('props: { a?: string; b?: string; c?: string }', `
70
+ const [bare] = createSignal(props.a)
71
+ const [branch] = createSignal(props.a === 'x' ? props.b : 'y')
72
+ const [fallback] = createSignal(props.a ?? props.c)
73
+ `)
74
+ expect([...collectNullableSignalGetters(ir)].sort()).toEqual(['bare', 'branch', 'fallback'])
75
+ expect(collectAbsentPropSeedReads(ir).get('branch')).toEqual(new Set(['b']))
76
+ expect(collectAbsentPropSeedReads(ir).get('fallback')).toEqual(new Set(['c']))
77
+ })
78
+
79
+ test('destructured params are read by their binding name', () => {
80
+ const ir = componentIR('{ label }: { label?: string }', 'const [shown] = createSignal(label)')
81
+ expect([...collectNullableSignalGetters(ir)]).toEqual(['shown'])
82
+ })
83
+
84
+ test('a required prop, a defaulted prop, a `??` left operand or a value built from the prop is not', () => {
85
+ const ir = componentIR("{ req, def = 'd', opt }: { req: string; def?: string; opt?: string }", `
86
+ const [a] = createSignal(req)
87
+ const [b] = createSignal(def)
88
+ const [c] = createSignal(opt ?? 'x')
89
+ const [d] = createSignal(opt === 'x')
90
+ const [e] = createSignal(\`\${opt}\`)
91
+ `)
92
+ expect([...collectNullableSignalGetters(ir)]).toEqual([])
93
+ })
94
+ })
95
+
53
96
  describe('nullableSignalAttrGetter (#3304)', () => {
54
97
  const nullable = new Set(['s'])
55
98
 
@@ -141,14 +184,35 @@ describe('arithmeticOperandCoercion (#3474)', () => {
141
184
  arithmeticOperandCoercion(op, parseExpression(operand), parseExpression(other), ctx)
142
185
 
143
186
  test('a nullable number prop reads as null under every arithmetic operator, + with a number included', () => {
144
- const ctx = ctxOf('props: { a: number | null; b?: number; c: number; d: string | null }')
187
+ const ctx = ctxOf('props: { a: number | null; c: number; d: string | null }')
145
188
  for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.a', 'x')).toBe('null')
146
189
  expect(coercion(ctx, '+', 'props.a', '1')).toBe('null')
147
- expect(coercion(ctx, '+', 'props.b', '-2')).toBe('null')
148
190
  expect(coercion(ctx, '*', 'props.c', '2')).toBeNull()
149
191
  expect(coercion(ctx, '*', 'props.d', '2')).toBeNull()
150
192
  })
151
193
 
194
+ test('a number prop that can only be absent reads its nil as undefined (#3533)', () => {
195
+ const ctx = ctxOf('props: { b?: number; u: number | undefined; both?: number | null }')
196
+ for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.b', 'x')).toBe('undefined')
197
+ expect(coercion(ctx, '+', 'props.b', '-2')).toBe('undefined')
198
+ expect(coercion(ctx, '*', 'props.u', '2')).toBe('undefined')
199
+ // A type that admits both keeps the null reading: its nil can be either.
200
+ expect(coercion(ctx, '*', 'props.both', '2')).toBe('null')
201
+ })
202
+
203
+ test('unary minus passes no other operand and coerces like binary minus (#3533)', () => {
204
+ const ctx = ctxOf('props: { a: number | null; b?: number; c: number }')
205
+ const unary = (operand: string) => arithmeticOperandCoercion('-', parseExpression(operand), undefined, ctx)
206
+ expect(unary('props.a')).toBe('null')
207
+ expect(unary('props.b')).toBe('undefined')
208
+ expect(unary('props.c')).toBeNull()
209
+ })
210
+
211
+ test('an absent-only prop is not certainly undefined: arithmeticOperandIsUndefined stays false', () => {
212
+ const ctx = ctxOf('props: { b?: number }')
213
+ expect(arithmeticOperandIsUndefined(parseExpression('props.b'), ctx)).toBe(false)
214
+ })
215
+
152
216
  test('+ is left alone unless the other operand is a number: it may concatenate', () => {
153
217
  const ctx = ctxOf('props: { a: number | null }', 'const [n] = createSignal<number | null>(null)')
154
218
  expect(coercion(ctx, '+', 'props.a', 'label')).toBeNull()
@@ -158,7 +222,7 @@ describe('arithmeticOperandCoercion (#3474)', () => {
158
222
 
159
223
  test('a destructured nullable number prop, and a shadowed one', () => {
160
224
  const ctx = ctxOf('{ a }: { a?: number }')
161
- expect(coercion(ctx, '*', 'a', '2')).toBe('null')
225
+ expect(coercion(ctx, '*', 'a', '2')).toBe('undefined')
162
226
  expect(arithmeticOperandCoercion('*', parseExpression('a'), parseExpression('2'), ctx, n => n === 'a')).toBeNull()
163
227
  })
164
228