@barefootjs/jsx 0.39.1 → 0.39.3

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 (72) hide show
  1. package/dist/adapters/line-statement-text.d.ts +17 -0
  2. package/dist/adapters/line-statement-text.d.ts.map +1 -0
  3. package/dist/adapters/parsed-expr-emitter.d.ts +2 -2
  4. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  5. package/dist/analyzer.d.ts +1 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/augment-inherited-props.d.ts +20 -0
  8. package/dist/augment-inherited-props.d.ts.map +1 -1
  9. package/dist/html-types.d.ts +15 -0
  10. package/dist/html-types.d.ts.map +1 -1
  11. package/dist/index.d.ts +6 -2
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1527 -1169
  14. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/safe-html.d.ts +1 -1
  16. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  18. package/dist/jsx-to-ir.d.ts.map +1 -1
  19. package/dist/literal-member-index.d.ts +6 -0
  20. package/dist/literal-member-index.d.ts.map +1 -0
  21. package/dist/nullable-signal-attr.d.ts +73 -0
  22. package/dist/nullable-signal-attr.d.ts.map +1 -0
  23. package/dist/scope/binding-scope.d.ts +11 -0
  24. package/dist/scope/binding-scope.d.ts.map +1 -1
  25. package/dist/scope/root-prop-alias.d.ts +43 -0
  26. package/dist/scope/root-prop-alias.d.ts.map +1 -0
  27. package/dist/signal-prop-name-collision.d.ts +20 -0
  28. package/dist/signal-prop-name-collision.d.ts.map +1 -0
  29. package/dist/ssr-defaults.d.ts.map +1 -1
  30. package/dist/ssr-seed-plan.d.ts +3 -2
  31. package/dist/ssr-seed-plan.d.ts.map +1 -1
  32. package/package.json +2 -2
  33. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  34. package/src/__tests__/attribute-fallback-wrap.test.ts +24 -0
  35. package/src/__tests__/binding-scope.test.ts +27 -0
  36. package/src/__tests__/client-template-escape-soundness.test.ts +17 -0
  37. package/src/__tests__/compiler-stress-1244.test.ts +10 -13
  38. package/src/__tests__/conditional-fallback-wrap.test.ts +20 -0
  39. package/src/__tests__/conditional-nested-loop-bindings.test.ts +41 -0
  40. package/src/__tests__/destructured-from-props-localconst-value.test.ts +3 -2
  41. package/src/__tests__/html-event-handler-names.test.ts +107 -0
  42. package/src/__tests__/line-statement-text.test.ts +25 -0
  43. package/src/__tests__/literal-member-index.test.ts +14 -0
  44. package/src/__tests__/lookup-literal-const.test.ts +46 -0
  45. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +66 -19
  46. package/src/__tests__/nullable-signal-attr.test.ts +124 -0
  47. package/src/__tests__/profile-binding-ids.test.ts +102 -0
  48. package/src/__tests__/root-prop-alias.test.ts +62 -0
  49. package/src/__tests__/signal-prop-name-collision.test.ts +171 -0
  50. package/src/__tests__/ssr-defaults.test.ts +6 -7
  51. package/src/__tests__/ssr-seed-plan.test.ts +23 -0
  52. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +1 -1
  53. package/src/__tests__/staged-ir/08-relocate-unit.test.ts +6 -3
  54. package/src/adapters/line-statement-text.ts +24 -0
  55. package/src/adapters/parsed-expr-emitter.ts +3 -3
  56. package/src/analyzer.ts +60 -26
  57. package/src/augment-inherited-props.ts +49 -0
  58. package/src/html-types.ts +15 -0
  59. package/src/index.ts +14 -2
  60. package/src/ir-to-client-js/collect-elements.ts +15 -10
  61. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +2 -2
  62. package/src/ir-to-client-js/safe-html.ts +19 -6
  63. package/src/ir-to-client-js/stringify/declaration-emit.ts +5 -5
  64. package/src/ir-to-client-js/utils.ts +88 -117
  65. package/src/jsx-to-ir.ts +21 -2
  66. package/src/literal-member-index.ts +12 -0
  67. package/src/nullable-signal-attr.ts +156 -0
  68. package/src/scope/binding-scope.ts +31 -1
  69. package/src/scope/root-prop-alias.ts +81 -0
  70. package/src/signal-prop-name-collision.ts +164 -0
  71. package/src/ssr-defaults.ts +3 -5
  72. package/src/ssr-seed-plan.ts +14 -2
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Every event handler typed on `HTMLBaseAttributes` (and the
3
+ * `BaseEventAttributes` it extends) must compile to a real DOM event name
4
+ * (#3273).
5
+ *
6
+ * The types (`html-types.ts`) and the compiler's JSX → DOM event-name
7
+ * conversion (`toDomEventName`) are two independent answers to "which events
8
+ * can a JSX element listen to". A typed prop whose lowered name is not a DOM
9
+ * event type-checks and compiles, but the listener never fires. This test
10
+ * joins the two: it reads the handler props from `html-types.ts` with a TS
11
+ * AST walk, compiles each one through `compileJSX`, and checks the emitted
12
+ * `addEventListener` name against the DOM lib's `HTMLElementEventMap`.
13
+ */
14
+
15
+ import { describe, test, expect } from 'bun:test'
16
+ import ts from 'typescript'
17
+ import { readFileSync } from 'node:fs'
18
+ import { resolve } from 'node:path'
19
+ import { compileJSX } from '..'
20
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
21
+
22
+ const HTML_TYPES_PATH = resolve(import.meta.dir, '../html-types.ts')
23
+
24
+ // Typed before this test existed, and not a DOM event: `dragexit` was
25
+ // dropped from the HTML spec and no browser fires it. Kept typed so existing
26
+ // code keeps compiling; this set may only shrink.
27
+ const NOT_A_DOM_EVENT = new Set(['onDragExit'])
28
+
29
+ function collectHandlerProps(): string[] {
30
+ const source = ts.createSourceFile(
31
+ HTML_TYPES_PATH,
32
+ readFileSync(HTML_TYPES_PATH, 'utf8'),
33
+ ts.ScriptTarget.Latest,
34
+ true,
35
+ )
36
+ const names: string[] = []
37
+ for (const stmt of source.statements) {
38
+ if (!ts.isInterfaceDeclaration(stmt)) continue
39
+ if (stmt.name.text !== 'BaseEventAttributes' && stmt.name.text !== 'HTMLBaseAttributes') continue
40
+ for (const member of stmt.members) {
41
+ if (!ts.isPropertySignature(member) || !ts.isIdentifier(member.name)) continue
42
+ if (/^on[A-Z]/.test(member.name.text)) names.push(member.name.text)
43
+ }
44
+ }
45
+ return names
46
+ }
47
+
48
+ function collectDomEventNames(): Set<string> {
49
+ const libDir = resolve(require.resolve('typescript'), '..')
50
+ const program = ts.createProgram({
51
+ rootNames: [resolve(libDir, 'lib.dom.d.ts')],
52
+ options: { noLib: true },
53
+ })
54
+ const checker = program.getTypeChecker()
55
+ const dom = program.getSourceFile(resolve(libDir, 'lib.dom.d.ts'))!
56
+ const decl = dom.statements.find(
57
+ (s): s is ts.InterfaceDeclaration =>
58
+ ts.isInterfaceDeclaration(s) && s.name.text === 'HTMLElementEventMap',
59
+ )!
60
+ const type = checker.getTypeAtLocation(decl.name)
61
+ return new Set(checker.getPropertiesOfType(type).map(p => p.name))
62
+ }
63
+
64
+ function compiledEventName(prop: string): string | undefined {
65
+ const source = `
66
+ "use client"
67
+ export function Test() {
68
+ return <div ${prop}={() => {}}>x</div>
69
+ }
70
+ `
71
+ const result = compileJSX(source, 'Test.tsx', { adapter: new HonoAdapter() })
72
+ const js = result.files.find(f => f.type === 'clientJs')?.content ?? ''
73
+ return js.match(/addEventListener\('([^']+)'/)?.[1]
74
+ }
75
+
76
+ describe('typed JSX event handlers compile to DOM events (#3273)', () => {
77
+ const props = collectHandlerProps()
78
+ const domEvents = collectDomEventNames()
79
+
80
+ test('the handler set includes the pointer events from #3273', () => {
81
+ for (const name of [
82
+ 'onPointerCancel',
83
+ 'onPointerOver',
84
+ 'onPointerOut',
85
+ 'onGotPointerCapture',
86
+ 'onLostPointerCapture',
87
+ ]) {
88
+ expect(props).toContain(name)
89
+ }
90
+ })
91
+
92
+ for (const prop of props) {
93
+ if (NOT_A_DOM_EVENT.has(prop)) continue
94
+ test(`${prop} → a DOM event`, () => {
95
+ const eventName = compiledEventName(prop)
96
+ expect(eventName).toBeDefined()
97
+ expect(domEvents.has(eventName!)).toBe(true)
98
+ })
99
+ }
100
+
101
+ test('NOT_A_DOM_EVENT only lists typed props that really are not DOM events', () => {
102
+ for (const prop of NOT_A_DOM_EVENT) {
103
+ expect(props).toContain(prop)
104
+ expect(domEvents.has(compiledEventName(prop)!)).toBe(false)
105
+ }
106
+ })
107
+ })
@@ -0,0 +1,25 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { escapeLineStatementSigil } from '../adapters/line-statement-text'
3
+
4
+ describe('escapeLineStatementSigil (#3311)', () => {
5
+ const esc = (t: string) => escapeLineStatementSigil(t, '%', "<%= '%' %>")
6
+
7
+ test('rewrites a sigil that leads the text, keeping its indentation', () => {
8
+ expect(esc('%y')).toBe("<%= '%' %>y")
9
+ expect(esc(' %y')).toBe(" <%= '%' %>y")
10
+ })
11
+
12
+ test('rewrites a sigil that leads any later line', () => {
13
+ expect(esc('a\n %b\nc')).toBe("a\n <%= '%' %>b\nc")
14
+ })
15
+
16
+ test('leaves a sigil that does not lead its line', () => {
17
+ expect(esc('50%')).toBe('50%')
18
+ expect(esc('a % b')).toBe('a % b')
19
+ })
20
+
21
+ test('rewrites only the leading sigil, once', () => {
22
+ expect(esc('%%')).toBe("<%= '%' %>%")
23
+ expect(escapeLineStatementSigil(': :x', ':', "<: ':' :>")).toBe("<: ':' :> :x")
24
+ })
25
+ })
@@ -0,0 +1,14 @@
1
+ import { expect, test } from 'bun:test'
2
+ import { literalMemberIndex } from '../literal-member-index.ts'
3
+
4
+ test('canonical array indices share the numeric index path', () => {
5
+ for (const property of ['0', '1', '4294967294']) {
6
+ expect(literalMemberIndex(property)).toEqual({ kind: 'literal', value: Number(property), literalType: 'number' })
7
+ }
8
+ })
9
+
10
+ test('non-index keys retain their exact spelling', () => {
11
+ for (const property of ['data-x', '01', '', '-1', '1.5', '1e2', '4294967295', "it's", 'a\\b']) {
12
+ expect(literalMemberIndex(property)).toEqual({ kind: 'literal', value: property, literalType: 'string' })
13
+ }
14
+ })
@@ -0,0 +1,46 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { compileJSX, lookupLiteralConst, type ComponentIR } from '../index'
3
+ import { TestAdapter } from '../adapters/test-adapter'
4
+
5
+ function constantsOf(src: string): ComponentIR['metadata']['localConstants'] {
6
+ const result = compileJSX(src.trimStart(), 'T.tsx', { adapter: new TestAdapter(), outputIR: true })
7
+ const irFile = result.files.find(f => f.type === 'ir')
8
+ if (!irFile) throw new Error('no IR')
9
+ return (JSON.parse(irFile.content) as ComponentIR).metadata.localConstants
10
+ }
11
+
12
+ describe('lookupLiteralConst (#3312)', () => {
13
+ const consts = constantsOf(`
14
+ const enabled = false
15
+ const limit = -2
16
+ const missing = null
17
+ export function C() {
18
+ const on = true
19
+ const mode = 'on'
20
+ const ratio = 1.5
21
+ const multiline = 'a\\nb'
22
+ const derived = mode + '!'
23
+ return <div data-x={on && enabled ? mode : String(limit + ratio) + derived + multiline} data-m={missing ?? 'm'}>x</div>
24
+ }
25
+ `)
26
+ const never = () => false
27
+
28
+ test('resolves boolean, number, string and null literals at module and function scope', () => {
29
+ expect(lookupLiteralConst('on', consts, never)).toEqual({ kind: 'boolean', text: 'true' })
30
+ expect(lookupLiteralConst('enabled', consts, never)).toEqual({ kind: 'boolean', text: 'false' })
31
+ expect(lookupLiteralConst('limit', consts, never)).toEqual({ kind: 'number', text: '-2' })
32
+ expect(lookupLiteralConst('ratio', consts, never)).toEqual({ kind: 'number', text: '1.5' })
33
+ expect(lookupLiteralConst('mode', consts, never)).toEqual({ kind: 'string', text: 'on' })
34
+ expect(lookupLiteralConst('multiline', consts, never)).toEqual({ kind: 'string', text: 'a\nb' })
35
+ expect(lookupLiteralConst('missing', consts, never)).toEqual({ kind: 'null', text: 'null' })
36
+ })
37
+
38
+ test('declines a non-literal initializer and an unknown name', () => {
39
+ expect(lookupLiteralConst('derived', consts, never)).toBeNull()
40
+ expect(lookupLiteralConst('unknown', consts, never)).toBeNull()
41
+ })
42
+
43
+ test('declines a name the caller reports as shadowed', () => {
44
+ expect(lookupLiteralConst('on', consts, n => n === 'on')).toBeNull()
45
+ })
46
+ })
@@ -411,35 +411,82 @@ describe('.map() row: a nested scope that shadows the loop param fails loudly in
411
411
  })
412
412
  })
413
413
 
414
- describe('destructured loop-param path (rewriteLoopBindingRefs) has the same key/member defect as the plain-param path (#3239 follow-up)', () => {
415
- // `rewriteLoopBindingRefs` (a few lines below `rewriteIdentifierAsAccessor`
416
- // in ir-to-client-js/utils.ts) rewrites a DESTRUCTURED loop param's
417
- // bindings (`({ color, label }) => ...`) with the same kind of
418
- // \bname\b-style regex the plain-param path used before this PR, and has
419
- // the identical object-literal-key defect: a binding whose name matches
420
- // an unrelated object-literal key gets that key corrupted into an
421
- // accessor call. Left out of this PR (see the PR description) because a
422
- // correct fix means touching the heavily-exercised #951/#1244
423
- // destructured-binding machinery, which is a larger, separate change.
424
- // Drop `.todo` once `rewriteLoopBindingRefs` gets the same AST-aware
425
- // treatment `rewriteIdentifierAsAccessor` got here.
426
- test.todo('an object-literal key matching a destructured binding name is left alone', () => {
427
- const source = `
414
+ describe('destructured loop-param path (rewriteLoopBindingRefs) shares the plain-param AST rewrite (#3260)', () => {
415
+ // `rewriteLoopBindingRefs` rewrites a DESTRUCTURED loop param's bindings
416
+ // (`({ color, label }) => ...`) to `__bfItem().color` etc. It used a
417
+ // \bname\b-style regex plus a shorthand-only AST pre-pass (#1244), so an
418
+ // explicit object-literal key or a member name spelling a binding name was
419
+ // corrupted the same way #3239 described for the plain param. It now runs
420
+ // the same AST walk as `rewriteIdentifierAsAccessor`.
421
+ function compileRow(row: string, item = "{ color: 'red', label: 'a', onPick: () => 1, extra: 1 }", pattern = '{ color, label }'): string {
422
+ return getClientJs(`
428
423
  'use client'
429
424
  import { createSignal } from '@barefootjs/client'
425
+ const THEME = { color: 'blue' }
430
426
  export function App() {
431
- const [items] = createSignal([{ color: 'red', label: 'a' }])
427
+ const [items] = createSignal([${item}])
432
428
  return (
433
429
  <div>
434
- {items().map(({ color, label }) => (
435
- <b key={label}>{JSON.stringify({ color: 1 })}</b>
430
+ {items().map((${pattern}) => (
431
+ ${row}
436
432
  ))}
437
433
  </div>
438
434
  )
439
435
  }
440
- `
441
- const js = getClientJs(source)
436
+ `)
437
+ }
438
+
439
+ test('an object-literal key matching a destructured binding name is left alone', () => {
440
+ const js = compileRow('<b key={label}>{JSON.stringify({ color: 1 })}</b>')
442
441
  assertParses(js)
443
442
  expect(js).toContain('JSON.stringify({ color: 1 })')
444
443
  })
444
+
445
+ test('a member name matching a destructured binding name is left alone', () => {
446
+ const js = compileRow('<b key={label}>{THEME.color}</b>')
447
+ assertParses(js)
448
+ expect(js).toContain('THEME.color')
449
+ expect(js).not.toContain('THEME.__bfItem()')
450
+ })
451
+
452
+ test('explicit key with a matching value `{ color: color }` rewrites only the value', () => {
453
+ const js = compileRow('<b key={label}>{JSON.stringify({ color: color })}</b>')
454
+ assertParses(js)
455
+ expect(js).toContain('JSON.stringify({ color: __bfItem().color })')
456
+ })
457
+
458
+ test('shorthand `{ color }` still expands to `{ color: __bfItem().color }` (#1244)', () => {
459
+ const js = compileRow('<b key={label}>{JSON.stringify({ color })}</b>')
460
+ assertParses(js)
461
+ expect(js).toContain('JSON.stringify({ color: __bfItem().color })')
462
+ })
463
+
464
+ test('a destructured binding called as a function becomes a call on the item field', () => {
465
+ // Unlike the plain param, `onPick()` is not an accessor call already —
466
+ // it calls the item's `onPick` field — so the callee is rewritten.
467
+ const js = compileRow('<b key={label}>{String(onPick())}</b>', undefined, '{ label, onPick }')
468
+ assertParses(js)
469
+ expect(js).toContain('String(__bfItem().onPick())')
470
+ })
471
+
472
+ test('a rest binding still renders through its residual form', () => {
473
+ const js = compileRow('<b key={label}>{JSON.stringify(rest)}</b>', undefined, '{ label, ...rest }')
474
+ assertParses(js)
475
+ expect(js).toContain('JSON.stringify((({ label: __bfR0, ...__bfRest }) => __bfRest)(__bfItem()))')
476
+ })
477
+
478
+ test('a named function expression shadows only its own name; other bindings inside are still rewritten', () => {
479
+ const js = compileRow('<b key={label}>{String((function color() { return label })())}</b>')
480
+ assertParses(js)
481
+ expect(js).toContain('(function color() { return __bfItem().label })()')
482
+ })
483
+
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).
489
+ const js = compileRow("<b key={label}>{(() => { function color() { return 'blue' } return color() })()}</b>")
490
+ assertDoesNotParse(js)
491
+ })
445
492
  })
@@ -0,0 +1,124 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer'
3
+ import { parseExpression } from '../expression-parser'
4
+ import {
5
+ attrValueMayBeNullish,
6
+ collectNullableSignalGetters,
7
+ collectNullishAttrContext,
8
+ nullableSignalAttrGetter,
9
+ } from '../nullable-signal-attr'
10
+ import type { ComponentIR } from '../types'
11
+
12
+ function nullableGetters(decls: string): Set<string> {
13
+ const source = `
14
+ 'use client'
15
+ import { createSignal } from '@barefootjs/client'
16
+ export function C() {
17
+ ${decls}
18
+ return <p>x</p>
19
+ }
20
+ `
21
+ const metadata = analyzeComponent(source, 'C.tsx')
22
+ return collectNullableSignalGetters({ metadata } as unknown as ComponentIR)
23
+ }
24
+
25
+ describe('collectNullableSignalGetters (#3304)', () => {
26
+ test('a zero-arg typed signal is nullable', () => {
27
+ expect([...nullableGetters('const [a] = createSignal<number>()')]).toEqual(['a'])
28
+ })
29
+
30
+ test('a type admitting undefined or null is nullable, whatever the initial value', () => {
31
+ expect([...nullableGetters(`
32
+ const [a] = createSignal<string | undefined>(undefined)
33
+ const [b] = createSignal<string | null>('x')
34
+ `)].sort()).toEqual(['a', 'b'])
35
+ })
36
+
37
+ test('an untyped literal undefined or null initial value is nullable', () => {
38
+ expect([...nullableGetters(`
39
+ const [a] = createSignal(undefined)
40
+ const [b] = createSignal(null)
41
+ `)].sort()).toEqual(['a', 'b'])
42
+ })
43
+
44
+ test('a non-nullable typed or inferred signal is not', () => {
45
+ expect([...nullableGetters(`
46
+ const [a] = createSignal('x')
47
+ const [b] = createSignal<number>(0)
48
+ `)]).toEqual([])
49
+ })
50
+ })
51
+
52
+ describe('nullableSignalAttrGetter (#3304)', () => {
53
+ const nullable = new Set(['s'])
54
+
55
+ test('matches a bare zero-arg read of a nullable signal', () => {
56
+ expect(nullableSignalAttrGetter(parseExpression('s()'), nullable)).toBe('s')
57
+ })
58
+
59
+ test('does not match any other shape', () => {
60
+ for (const expr of ['t()', 's', 's(1)', 's()?.x', "s() ?? 'a'", 'a ? s() : b']) {
61
+ expect(nullableSignalAttrGetter(parseExpression(expr), nullable)).toBeNull()
62
+ }
63
+ })
64
+ })
65
+
66
+ describe('attrValueMayBeNullish (#3322)', () => {
67
+ const source = `
68
+ 'use client'
69
+ import { createMemo, createSignal } from '@barefootjs/client'
70
+ export function C() {
71
+ const [s] = createSignal<string | undefined>(undefined)
72
+ const [t] = createSignal('x')
73
+ const [user] = createSignal<{ name?: string }>({})
74
+ const label = createMemo(() => s())
75
+ const nested = createMemo(() => label())
76
+ const plain = createMemo(() => t())
77
+ const typed = createMemo<string | undefined>(() => t())
78
+ const loop = createMemo(() => loop())
79
+ return <p>x</p>
80
+ }
81
+ `
82
+ const ctx = collectNullishAttrContext({ metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR)
83
+ const mayBe = (expr: string, shadowed: string[] = []) =>
84
+ attrValueMayBeNullish(parseExpression(expr), ctx, name => shadowed.includes(name))
85
+
86
+ test('a nullable signal or a memo over one, however deep', () => {
87
+ for (const expr of ['s()', 'label()', 'nested()', 'typed()']) expect(mayBe(expr)).toBe(true)
88
+ })
89
+
90
+ test('a memo over a present value, or a self-referencing memo, is not', () => {
91
+ for (const expr of ['t()', 'plain()', 'loop()']) expect(mayBe(expr)).toBe(false)
92
+ })
93
+
94
+ test('an optional member read, or a member of a nullable value', () => {
95
+ expect(mayBe('user()?.name')).toBe(true)
96
+ expect(mayBe('label().length')).toBe(true)
97
+ expect(mayBe('user().name')).toBe(false)
98
+ })
99
+
100
+ test('a ternary or logical operand the result can be', () => {
101
+ expect(mayBe("t() ? s() : 'a'")).toBe(true)
102
+ expect(mayBe("t() ? 'a' : label()")).toBe(true)
103
+ expect(mayBe("s() ? 'a' : 'b'")).toBe(false)
104
+ expect(mayBe("s() ?? 'a'")).toBe(false)
105
+ expect(mayBe("t() || s()")).toBe(true)
106
+ expect(mayBe("s() && 'a'")).toBe(true)
107
+ })
108
+
109
+ test('literal undefined / null, and nothing else', () => {
110
+ expect(mayBe('undefined')).toBe(true)
111
+ expect(mayBe('null')).toBe(true)
112
+ expect(mayBe("''")).toBe(false)
113
+ expect(mayBe('0')).toBe(false)
114
+ })
115
+
116
+ test('a getter a loop binding shadows is not the signal or memo', () => {
117
+ expect(mayBe('label()', ['label'])).toBe(false)
118
+ })
119
+
120
+ test("a memo's body reads its getters where the memo is declared, not where it is read", () => {
121
+ expect(mayBe('label()', ['s'])).toBe(true)
122
+ expect(mayBe('nested()', ['s', 'label'])).toBe(true)
123
+ })
124
+ })
@@ -7,9 +7,11 @@
7
7
  */
8
8
 
9
9
  import { describe, test, expect } from 'bun:test'
10
+ import ts from 'typescript'
10
11
  import { compileJSX } from '../compiler'
11
12
  import { TestAdapter } from '../adapters/test-adapter'
12
13
  import { buildIdIndex } from '../profiler'
14
+ import { analyzeComponent } from '../analyzer'
13
15
  import { buildComponentAnalysis } from '../debug'
14
16
 
15
17
  const adapter = new TestAdapter()
@@ -121,3 +123,103 @@ describe('binding-effect ids', () => {
121
123
  expect(node.loc.line).toBeGreaterThan(0)
122
124
  })
123
125
  })
126
+
127
+ describe('a zero-arg createSignal() emits valid client JS (#3217)', () => {
128
+ const zeroArgSource = `
129
+ 'use client'
130
+ import { createSignal } from '@barefootjs/client'
131
+ export function Empty() {
132
+ const [v, setV] = createSignal<string>()
133
+ return <button onClick={() => setV('x')}>{v() ?? '-'}</button>
134
+ }
135
+ `
136
+
137
+ function emit(profile: boolean): string {
138
+ return compileJSX(zeroArgSource, 'Empty.tsx', { adapter, profile })
139
+ .files.find(f => f.type === 'clientJs')!.content
140
+ }
141
+
142
+ function parseErrors(js: string): string[] {
143
+ const diagnostics = ts.transpileModule(js, {
144
+ reportDiagnostics: true,
145
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest },
146
+ }).diagnostics ?? []
147
+ return diagnostics
148
+ .filter(d => d.category === ts.DiagnosticCategory.Error)
149
+ .map(d => ts.flattenDiagnosticMessageText(d.messageText, '\n'))
150
+ }
151
+
152
+ test('profile on: the signal id follows an explicit `undefined`, not a bare comma', () => {
153
+ const on = emit(true)
154
+ expect(on).toContain('createSignal(undefined, "Empty#signal:v")')
155
+ expect(on).not.toContain('createSignal(,')
156
+ expect(parseErrors(on)).toEqual([])
157
+ })
158
+
159
+ test('profile off: the call and the template both carry an explicit `undefined`', () => {
160
+ // The CSR template substitutes `v()` with the signal's initial value.
161
+ // An empty one used to inline as `()`, so the module failed to parse
162
+ // even without profiling.
163
+ const off = emit(false)
164
+ expect(off).toContain('createSignal(undefined)')
165
+ expect(off).toContain("escapeTextOrMarkup((undefined) ?? '-')")
166
+ expect(parseErrors(off)).toEqual([])
167
+ })
168
+ })
169
+
170
+ describe('the analyzer records `undefined` for a zero-arg createSignal() (#3215)', () => {
171
+ // One decision at the source: every emitter (SSR getter, CSR template,
172
+ // client-JS call) splices `initialValue` into an expression, so an empty
173
+ // string there is an empty operand in each of them.
174
+ const shapes: Array<[string, string]> = [
175
+ ['array destructure', 'const [v, setV] = createSignal<string>()'],
176
+ ['tuple ref + index access', 'const s = createSignal<string>(); const v = s[0]; const setV = s[1]'],
177
+ ['direct index access', 'const v = createSignal<string>()[0]; const setV = createSignal<string>()[1]'],
178
+ ]
179
+ for (const [label, decl] of shapes) {
180
+ test(label, () => {
181
+ const source = `
182
+ 'use client'
183
+ import { createSignal } from '@barefootjs/client'
184
+ export function Empty() {
185
+ ${decl}
186
+ return <button onClick={() => setV('x')}>{v() ?? '-'}</button>
187
+ }
188
+ `
189
+ const signals = analyzeComponent(source, 'Empty.tsx').signals
190
+ expect(signals.length).toBeGreaterThan(0)
191
+ for (const signal of signals) {
192
+ expect(signal.initialValue).toBe('undefined')
193
+ // The zero-arg overload's `T | undefined`, so a typed backend seeds
194
+ // nil rather than the type's zero value.
195
+ expect(signal.type.raw).toBe('string | undefined')
196
+ }
197
+ })
198
+ }
199
+
200
+ test('a type argument that already admits undefined is not widened again', () => {
201
+ const source = `
202
+ 'use client'
203
+ import { createSignal } from '@barefootjs/client'
204
+ export function Empty() {
205
+ const [v] = createSignal<'a' | 'b' | undefined>()
206
+ return <p>{v() ?? '-'}</p>
207
+ }
208
+ `
209
+ const [signal] = analyzeComponent(source, 'Empty.tsx').signals
210
+ expect(signal.type.raw).toBe("'a' | 'b' | undefined")
211
+ })
212
+
213
+ test('an explicit initial value keeps the type argument as written', () => {
214
+ const source = `
215
+ 'use client'
216
+ import { createSignal } from '@barefootjs/client'
217
+ export function Empty() {
218
+ const [v] = createSignal<string>('x')
219
+ return <p>{v()}</p>
220
+ }
221
+ `
222
+ const [signal] = analyzeComponent(source, 'Empty.tsx').signals
223
+ expect(signal.type.raw).toBe('string')
224
+ })
225
+ })
@@ -0,0 +1,62 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { BindingScope } from '../scope/binding-scope'
3
+ import { rootPropAliasNames, rootPropAliasesForLoop, rootPropReadName } from '../scope/root-prop-alias'
4
+ import type { ComponentIR } from '../types'
5
+
6
+ function irWith(opts: { localConstants?: string[]; loopParam?: string } = {}): ComponentIR {
7
+ const root = opts.loopParam
8
+ ? { type: 'loop', param: opts.loopParam, children: [] }
9
+ : { type: 'element', children: [] }
10
+ return {
11
+ root,
12
+ metadata: {
13
+ localConstants: (opts.localConstants ?? []).map(name => ({ name })),
14
+ localFunctions: [],
15
+ signals: [],
16
+ memos: [],
17
+ },
18
+ } as unknown as ComponentIR
19
+ }
20
+
21
+ describe('root-prop aliases (#3314)', () => {
22
+ const props = new Set(['value', 'index', 'values'])
23
+ const aliases = rootPropAliasNames(irWith(), props)
24
+ const outer = BindingScope.EMPTY
25
+ const row = outer.enterLoopRow({ param: 'value', index: 'index' })
26
+ const inner = row.enterLoopRow({ param: 'value' })
27
+
28
+ test('a loop row aliases exactly the props it newly shadows', () => {
29
+ expect(rootPropAliasesForLoop(outer, row, aliases)).toEqual([
30
+ { name: 'value', alias: '__bf_root_value' },
31
+ { name: 'index', alias: '__bf_root_index' },
32
+ ])
33
+ })
34
+
35
+ test('a nested loop re-binding an already shadowed name adds no alias', () => {
36
+ expect(rootPropAliasesForLoop(row, inner, aliases)).toEqual([])
37
+ })
38
+
39
+ test('a binding that is not a prop needs no alias', () => {
40
+ expect(rootPropAliasesForLoop(outer, outer.enterLoopRow({ param: 'item' }), aliases)).toEqual([])
41
+ })
42
+
43
+ test('props.X reads the alias only while X is shadowed', () => {
44
+ expect(rootPropReadName('value', outer, aliases)).toBe('value')
45
+ expect(rootPropReadName('value', row, aliases)).toBe('__bf_root_value')
46
+ expect(rootPropReadName('value', inner, aliases)).toBe('__bf_root_value')
47
+ expect(rootPropReadName('values', row, aliases)).toBe('values')
48
+ })
49
+
50
+ test('an alias never takes a name the component already uses', () => {
51
+ expect(rootPropAliasNames(irWith(), ['value', '__bf_root_value']).get('value')).toBe('__bf_root_value_')
52
+ expect(rootPropAliasNames(irWith({ localConstants: ['__bf_root_value'] }), ['value']).get('value')).toBe(
53
+ '__bf_root_value_',
54
+ )
55
+ expect(rootPropAliasNames(irWith({ loopParam: '__bf_root_value' }), ['value']).get('value')).toBe(
56
+ '__bf_root_value_',
57
+ )
58
+ // `value` (bumped past the prop) and `value_` would otherwise share `__bf_root_value_`.
59
+ const both = rootPropAliasNames(irWith(), ['value', '__bf_root_value', 'value_'])
60
+ expect(new Set(both.values()).size).toBe(3)
61
+ })
62
+ })