@barefootjs/jsx 0.35.3 → 0.35.5

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 (36) hide show
  1. package/dist/analyzer.d.ts.map +1 -1
  2. package/dist/debug.d.ts +33 -3
  3. package/dist/debug.d.ts.map +1 -1
  4. package/dist/index.js +267 -73
  5. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  6. package/dist/ir-to-client-js/compute-inlinability.d.ts +8 -0
  7. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  8. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/imports.d.ts +2 -2
  10. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  12. package/dist/ir-to-client-js/types.d.ts +25 -0
  13. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/utils.d.ts +12 -1
  15. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  16. package/dist/types.d.ts +31 -0
  17. package/dist/types.d.ts.map +1 -1
  18. package/package.json +2 -2
  19. package/src/__tests__/debug.test.ts +246 -0
  20. package/src/__tests__/issue-2897-static-loop-conditional.test.ts +340 -0
  21. package/src/__tests__/issue-2910-mutated-const-not-inlined.test.ts +118 -0
  22. package/src/__tests__/issue-2910-own-scope-id-emission.test.ts +64 -0
  23. package/src/__tests__/lazy-conditional.test.ts +1 -0
  24. package/src/analyzer.ts +157 -22
  25. package/src/debug.ts +214 -84
  26. package/src/ir-to-client-js/collect-elements.ts +83 -3
  27. package/src/ir-to-client-js/compute-inlinability.ts +8 -1
  28. package/src/ir-to-client-js/emit-registration.ts +2 -2
  29. package/src/ir-to-client-js/generate-init.ts +16 -2
  30. package/src/ir-to-client-js/imports.ts +6 -0
  31. package/src/ir-to-client-js/index.ts +6 -0
  32. package/src/ir-to-client-js/prop-handling.ts +9 -0
  33. package/src/ir-to-client-js/types.ts +37 -1
  34. package/src/ir-to-client-js/utils.ts +15 -1
  35. package/src/jsx-to-ir.ts +14 -0
  36. package/src/types.ts +31 -0
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Regression tests for #2910 (bug 2): a `const`/`let` binding mutated by a
3
+ * same-scope statement AFTER its declaration must never be inlined by its
4
+ * (now stale) declaration-time initializer text wherever the bare
5
+ * identifier is referenced as a component prop value.
6
+ *
7
+ * `const config = {}; for (const s of series) config[s.key] = {...}` is the
8
+ * `@barefootjs/chart` shape the issue reports: `expandDynamicPropValue`
9
+ * (`ir-to-client-js/prop-handling.ts`) used to look up `config` in
10
+ * `ctx.localConstants` and re-embed its initializer text (`"{}"`)
11
+ * verbatim — a snapshot from BEFORE the mutating `for` loop ran — instead
12
+ * of a live reference to the `config` binding. `markMutatedConstants`
13
+ * (analyzer.ts) now flags such bindings `mutatedAfterDeclaration`, and
14
+ * every inlining consumer checks that flag first.
15
+ */
16
+ import { describe, expect, test } from 'bun:test'
17
+ import { compileJSX } from '../index.ts'
18
+ import { TestAdapter } from '../adapters/test-adapter.ts'
19
+
20
+ function clientJsOf(source: string, path: string): string {
21
+ const result = compileJSX(source, path, { adapter: new TestAdapter() })
22
+ const errors = result.errors.filter(e => e.severity === 'error')
23
+ expect(errors).toEqual([])
24
+ const js = result.files.find(f => f.path.endsWith('.client.js'))?.content
25
+ if (!js) throw new Error(`no client JS emitted for ${path}`)
26
+ return js
27
+ }
28
+
29
+ describe('#2910 — a mutated-after-declaration const is never re-inlined', () => {
30
+ test('a for-of-loop-mutated object literal reaches the child prop as a live reference', () => {
31
+ const js = clientJsOf(
32
+ `'use client'
33
+ function Child(props: { config: Record<string, { color: string }> }) {
34
+ const handleMount = (el: HTMLElement) => {
35
+ for (const [k, v] of Object.entries(props.config)) el.style.setProperty('--color-' + k, v.color)
36
+ }
37
+ return <div ref={handleMount} />
38
+ }
39
+
40
+ export function Host() {
41
+ const config: Record<string, { color: string }> = {}
42
+ const series = [{ key: 'a', color: 'red' }, { key: 'b', color: 'blue' }]
43
+ for (const s of series) config[s.key] = { color: s.color }
44
+ return <Child config={config} />
45
+ }
46
+ `,
47
+ 'host.tsx',
48
+ )
49
+
50
+ expect(js).toContain('get config() { return config }')
51
+ expect(js).not.toContain('return {}')
52
+ // The prop can no longer be known statically at template time — the
53
+ // child render must defer to init (`upsertChild`), not an inline
54
+ // `initChild(..., { config: {} })` call.
55
+ expect(js).toContain("upsertChild(__scope, 'Child")
56
+ expect(js).not.toContain('config: ')
57
+ })
58
+
59
+ test('a reassigned let binding is treated the same as an in-place mutation', () => {
60
+ const js = clientJsOf(
61
+ `'use client'
62
+ function Child(props: { label: string }) {
63
+ return <span>{props.label}</span>
64
+ }
65
+
66
+ export function Host() {
67
+ let label = 'initial'
68
+ if (Math.random() > 0.5) label = 'changed'
69
+ return <Child label={label} />
70
+ }
71
+ `,
72
+ 'host-let.tsx',
73
+ )
74
+
75
+ expect(js).toContain('get label() { return label }')
76
+ expect(js).not.toContain("get label() { return 'initial' }")
77
+ })
78
+
79
+ test('a .push()-mutated array reaches the child prop as a live reference', () => {
80
+ const js = clientJsOf(
81
+ `'use client'
82
+ function List(props: { items: string[] }) {
83
+ return <span>{props.items.join(',')}</span>
84
+ }
85
+
86
+ export function Host() {
87
+ const items: string[] = []
88
+ items.push('a')
89
+ items.push('b')
90
+ return <List items={items} />
91
+ }
92
+ `,
93
+ 'host-push.tsx',
94
+ )
95
+
96
+ expect(js).toContain('get items() { return items }')
97
+ expect(js).not.toContain('items: []')
98
+ })
99
+
100
+ test('an untouched object-literal const is still inlined (no regression)', () => {
101
+ const js = clientJsOf(
102
+ `'use client'
103
+ function Child(props: { config: Record<string, { color: string }> }) {
104
+ return <span>{Object.keys(props.config).length}</span>
105
+ }
106
+
107
+ export function Host() {
108
+ const config: Record<string, { color: string }> = { a: { color: 'red' }, b: { color: 'blue' } }
109
+ return <Child config={config} />
110
+ }
111
+ `,
112
+ 'host-literal.tsx',
113
+ )
114
+
115
+ // Never mutated — the existing inlining behaviour is unaffected.
116
+ expect(js).toContain("config: ({ a: { color: 'red' }, b: { color: 'blue' } })")
117
+ })
118
+ })
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Regression test for #2910 (bug 1): `generateInitFunction` must emit
3
+ * `const __scopeId = ownScopeId(__scope)` for a comment-scoped root (a
4
+ * fragment root, or a root that is itself a single child-component call,
5
+ * #2649) and keep the plain `__scope.getAttribute('bf-s')` read for an
6
+ * ordinary element-scoped root. See `packages/client/src/runtime/scope.ts`'s
7
+ * `ownScopeId` for why the two differ: a comment-scoped component is
8
+ * mounted on a PROXY element whose own `bf-s` names its host/parent scope,
9
+ * not its own — reading it directly resolves every `.map()`-produced
10
+ * child lookup (`[bf-h="${__scopeId}"]`) against the wrong id.
11
+ */
12
+ import { describe, expect, test } from 'bun:test'
13
+ import { compileJSX } from '../index.ts'
14
+ import { TestAdapter } from '../adapters/test-adapter.ts'
15
+
16
+ function clientJsOf(source: string, path: string): string {
17
+ const result = compileJSX(source, path, { adapter: new TestAdapter() })
18
+ const errors = result.errors.filter(e => e.severity === 'error')
19
+ expect(errors).toEqual([])
20
+ const js = result.files.find(f => f.path.endsWith('.client.js'))?.content
21
+ if (!js) throw new Error(`no client JS emitted for ${path}`)
22
+ return js
23
+ }
24
+
25
+ describe('#2910 — __scopeId reads the comment-scope registry for a comment-scoped root', () => {
26
+ test('root is a single child-component call (#2649 shape) uses ownScopeId', () => {
27
+ const js = clientJsOf(
28
+ `'use client'
29
+ function Panel(props: { children?: unknown }) {
30
+ return <div className="panel">{props.children}</div>
31
+ }
32
+
33
+ export function Host() {
34
+ return <Panel><span>hi</span></Panel>
35
+ }
36
+ `,
37
+ 'host.tsx',
38
+ )
39
+
40
+ expect(js).toContain('function initHost')
41
+ const initHost = js.slice(js.indexOf('function initHost'))
42
+ expect(initHost).toContain('const __scopeId = ownScopeId(__scope)')
43
+ expect(initHost).not.toContain("__scope.getAttribute('bf-s')")
44
+ })
45
+
46
+ test('an ordinary element-scoped root keeps reading the bf-s attribute directly', () => {
47
+ const js = clientJsOf(
48
+ `'use client'
49
+ function Leaf(props: { label: string }) {
50
+ return <span>{props.label}</span>
51
+ }
52
+
53
+ export function Host() {
54
+ return <div className="panel"><Leaf label="hi" /></div>
55
+ }
56
+ `,
57
+ 'host-plain.tsx',
58
+ )
59
+
60
+ const initHost = js.slice(js.indexOf('function initHost'))
61
+ expect(initHost).toContain("const __scopeId = __scope.getAttribute('bf-s')")
62
+ expect(initHost).not.toContain('ownScopeId')
63
+ })
64
+ })
@@ -30,6 +30,7 @@ function cond(over: Partial<LoopChildConditional> = {}): LoopChildConditional {
30
30
  whenTrue: bare(),
31
31
  whenFalse: bare(),
32
32
  conditionFreeIdentifiers: new Set(['row']),
33
+ reactiveBeyondLoopScope: true,
33
34
  ...over,
34
35
  }
35
36
  }
package/src/analyzer.ts CHANGED
@@ -1806,6 +1806,7 @@ function collectInitStatement(node: ts.Statement, ctx: AnalyzerContext): void {
1806
1806
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
1807
1807
  freeIdentifiers: extractFreeIdentifiersFromNode(node),
1808
1808
  assignedIdentifiers: extractAssignedIdentifiersFromNode(node),
1809
+ mutatedIdentifiers: extractMutatedIdentifiersFromNode(node),
1809
1810
  // Init statements run inside the component's init function, so they
1810
1811
  // belong to `init` scope. Phase is conservatively `hydrate` (run-once
1811
1812
  // at hydration). relocate() can refine this when consuming the field.
@@ -1896,28 +1897,8 @@ function extractAssignedIdentifiersFromNode(node: ts.Node): Set<string> {
1896
1897
  ) {
1897
1898
  return
1898
1899
  }
1899
- if (ts.isBinaryExpression(n)) {
1900
- const op = n.operatorToken.kind
1901
- if (
1902
- op === ts.SyntaxKind.EqualsToken ||
1903
- op === ts.SyntaxKind.PlusEqualsToken ||
1904
- op === ts.SyntaxKind.MinusEqualsToken ||
1905
- op === ts.SyntaxKind.AsteriskEqualsToken ||
1906
- op === ts.SyntaxKind.SlashEqualsToken ||
1907
- op === ts.SyntaxKind.PercentEqualsToken ||
1908
- op === ts.SyntaxKind.AsteriskAsteriskEqualsToken ||
1909
- op === ts.SyntaxKind.AmpersandEqualsToken ||
1910
- op === ts.SyntaxKind.BarEqualsToken ||
1911
- op === ts.SyntaxKind.CaretEqualsToken ||
1912
- op === ts.SyntaxKind.LessThanLessThanEqualsToken ||
1913
- op === ts.SyntaxKind.GreaterThanGreaterThanEqualsToken ||
1914
- op === ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken ||
1915
- op === ts.SyntaxKind.AmpersandAmpersandEqualsToken ||
1916
- op === ts.SyntaxKind.BarBarEqualsToken ||
1917
- op === ts.SyntaxKind.QuestionQuestionEqualsToken
1918
- ) {
1919
- addFromTarget(n.left)
1920
- }
1900
+ if (ts.isBinaryExpression(n) && isAssignmentOperator(n.operatorToken.kind)) {
1901
+ addFromTarget(n.left)
1921
1902
  }
1922
1903
  if (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) {
1923
1904
  if (
@@ -1940,6 +1921,126 @@ function extractAssignedIdentifiersFromNode(node: ts.Node): Set<string> {
1940
1921
  return ids
1941
1922
  }
1942
1923
 
1924
+ /**
1925
+ * Method names that mutate their receiver in place. Used only to recognise
1926
+ * `<root>.<method>(...)` calls as mutating the root identifier (#2910) —
1927
+ * NOT to model array/collection semantics generally, so this stays a small,
1928
+ * explicit catalogue rather than a heuristic over every possible method.
1929
+ */
1930
+ const MUTATING_METHOD_NAMES: ReadonlySet<string> = new Set([
1931
+ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin',
1932
+ 'set', 'add', 'delete', 'clear',
1933
+ ])
1934
+
1935
+ /**
1936
+ * Collect identifiers mutated IN PLACE by a statement — a property/element
1937
+ * write (`config[k] = …`, `config.a.b += 1`), an `Object.assign(config, …)`
1938
+ * call, or a call to a known mutating method on the receiver
1939
+ * (`items.push(...)`) — as opposed to `extractAssignedIdentifiersFromNode`,
1940
+ * which only tracks reassignment of the BINDING itself (#2910).
1941
+ *
1942
+ * This distinction matters because `expandDynamicPropValue` /
1943
+ * `expandConstantForReactivity` (`ir-to-client-js/prop-handling.ts`) inline
1944
+ * a `localConstants` entry's DECLARATION-TIME initializer text wherever the
1945
+ * bare identifier is referenced. A `const config = {}` later populated by
1946
+ * `for (const s of series) config[s.key] = {...}` never reassigns `config`
1947
+ * itself — `extractAssignedIdentifiersFromNode` (correctly) reports no
1948
+ * assigned identifiers, since `config[s.key] = …` doesn't create an
1949
+ * implicit global — but the compiler must still know `config`'s value is
1950
+ * no longer just `{}` by the time this statement has run, so a consumer
1951
+ * that inlines the stale literal (instead of referencing the live `config`
1952
+ * binding) silently drops everything the mutation was supposed to do. See
1953
+ * `ConstantInfo.mutatedAfterDeclaration` for where this is consumed.
1954
+ */
1955
+ function extractMutatedIdentifiersFromNode(node: ts.Node): Set<string> {
1956
+ const ids = new Set<string>()
1957
+
1958
+ function rootIdentifierOf(expr: ts.Expression): string | null {
1959
+ let current: ts.Expression = expr
1960
+ while (true) {
1961
+ if (ts.isIdentifier(current)) return current.text
1962
+ if (ts.isParenthesizedExpression(current)) { current = current.expression; continue }
1963
+ if (ts.isNonNullExpression(current)) { current = current.expression; continue }
1964
+ if (ts.isPropertyAccessExpression(current)) { current = current.expression; continue }
1965
+ if (ts.isElementAccessExpression(current)) { current = current.expression; continue }
1966
+ return null
1967
+ }
1968
+ }
1969
+
1970
+ function visit(n: ts.Node): void {
1971
+ // Same init/sub-init boundary as `extractAssignedIdentifiersFromNode`:
1972
+ // a mutation inside a nested function literal doesn't run at init time.
1973
+ if (
1974
+ ts.isArrowFunction(n) ||
1975
+ ts.isFunctionExpression(n) ||
1976
+ ts.isFunctionDeclaration(n) ||
1977
+ ts.isMethodDeclaration(n) ||
1978
+ ts.isGetAccessorDeclaration(n) ||
1979
+ ts.isSetAccessorDeclaration(n) ||
1980
+ ts.isConstructorDeclaration(n)
1981
+ ) {
1982
+ return
1983
+ }
1984
+
1985
+ if (ts.isBinaryExpression(n) && isAssignmentOperator(n.operatorToken.kind)) {
1986
+ if (ts.isPropertyAccessExpression(n.left) || ts.isElementAccessExpression(n.left)) {
1987
+ const root = rootIdentifierOf(n.left)
1988
+ if (root) ids.add(root)
1989
+ }
1990
+ } else if (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) {
1991
+ const isIncDec = n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken
1992
+ if (isIncDec && (ts.isPropertyAccessExpression(n.operand) || ts.isElementAccessExpression(n.operand))) {
1993
+ const root = rootIdentifierOf(n.operand)
1994
+ if (root) ids.add(root)
1995
+ }
1996
+ } else if (ts.isCallExpression(n)) {
1997
+ const callee = n.expression
1998
+ if (ts.isPropertyAccessExpression(callee)) {
1999
+ const methodName = callee.name.text
2000
+ if (MUTATING_METHOD_NAMES.has(methodName)) {
2001
+ const root = rootIdentifierOf(callee.expression)
2002
+ if (root) ids.add(root)
2003
+ } else if (
2004
+ methodName === 'assign' &&
2005
+ ts.isIdentifier(callee.expression) &&
2006
+ callee.expression.text === 'Object' &&
2007
+ n.arguments.length > 0
2008
+ ) {
2009
+ // `Object.assign(target, ...)` mutates `target` in place.
2010
+ const root = rootIdentifierOf(n.arguments[0])
2011
+ if (root) ids.add(root)
2012
+ }
2013
+ }
2014
+ }
2015
+
2016
+ ts.forEachChild(n, visit)
2017
+ }
2018
+
2019
+ visit(node)
2020
+ return ids
2021
+ }
2022
+
2023
+ function isAssignmentOperator(kind: ts.SyntaxKind): boolean {
2024
+ return (
2025
+ kind === ts.SyntaxKind.EqualsToken ||
2026
+ kind === ts.SyntaxKind.PlusEqualsToken ||
2027
+ kind === ts.SyntaxKind.MinusEqualsToken ||
2028
+ kind === ts.SyntaxKind.AsteriskEqualsToken ||
2029
+ kind === ts.SyntaxKind.SlashEqualsToken ||
2030
+ kind === ts.SyntaxKind.PercentEqualsToken ||
2031
+ kind === ts.SyntaxKind.AsteriskAsteriskEqualsToken ||
2032
+ kind === ts.SyntaxKind.AmpersandEqualsToken ||
2033
+ kind === ts.SyntaxKind.BarEqualsToken ||
2034
+ kind === ts.SyntaxKind.CaretEqualsToken ||
2035
+ kind === ts.SyntaxKind.LessThanLessThanEqualsToken ||
2036
+ kind === ts.SyntaxKind.GreaterThanGreaterThanEqualsToken ||
2037
+ kind === ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken ||
2038
+ kind === ts.SyntaxKind.AmpersandAmpersandEqualsToken ||
2039
+ kind === ts.SyntaxKind.BarBarEqualsToken ||
2040
+ kind === ts.SyntaxKind.QuestionQuestionEqualsToken
2041
+ )
2042
+ }
2043
+
1943
2044
  /**
1944
2045
  * Collect all variable names declared within a statement tree (for-loop
1945
2046
  * initializers, for-in/of bindings, nested `let`/`const`/`var` blocks).
@@ -3899,6 +4000,11 @@ function validateContext(ctx: AnalyzerContext): void {
3899
4000
  }
3900
4001
  }
3901
4002
 
4003
+ // A same-scope statement (typically a `for`/`while` loop) may mutate a
4004
+ // `localConstants` binding after its declaration — flag those bindings so
4005
+ // downstream inlining never re-embeds their stale initializer text (#2910).
4006
+ markMutatedConstants(ctx)
4007
+
3902
4008
  // BF052: init statements that write to an identifier with no visible
3903
4009
  // declaration cause a ReferenceError in ESM strict mode. Flag them
3904
4010
  // at compile time instead of shipping broken client JS. (#933)
@@ -4162,6 +4268,35 @@ function fileHasUseClientDirective(filePath: string): boolean {
4162
4268
  return found
4163
4269
  }
4164
4270
 
4271
+ /**
4272
+ * Flag every `localConstants` entry a same-scope init statement mutates
4273
+ * after its declaration (#2910) — see `ConstantInfo.mutatedAfterDeclaration`
4274
+ * for why this matters and who reads it. Runs once, after the whole
4275
+ * component (and module-level) body has been walked, since the mutating
4276
+ * statement is a SEPARATE statement from the declaration and may follow it
4277
+ * by any number of lines.
4278
+ *
4279
+ * Deliberately keyed off BOTH `mutatedIdentifiers` (in-place writes) and
4280
+ * `assignedIdentifiers` (whole-binding reassignment, e.g. a `let` later
4281
+ * written to): both leave `ConstantInfo.value` stale, and
4282
+ * `expandDynamicPropValue` inlines `value` for `let` bindings exactly the
4283
+ * same way it does for `const`.
4284
+ */
4285
+ function markMutatedConstants(ctx: AnalyzerContext): void {
4286
+ if (ctx.initStatements.length === 0 || ctx.localConstants.length === 0) return
4287
+
4288
+ const mutatedNames = new Set<string>()
4289
+ for (const stmt of ctx.initStatements) {
4290
+ if (stmt.mutatedIdentifiers) for (const name of stmt.mutatedIdentifiers) mutatedNames.add(name)
4291
+ if (stmt.assignedIdentifiers) for (const name of stmt.assignedIdentifiers) mutatedNames.add(name)
4292
+ }
4293
+ if (mutatedNames.size === 0) return
4294
+
4295
+ for (const constant of ctx.localConstants) {
4296
+ if (mutatedNames.has(constant.name)) constant.mutatedAfterDeclaration = true
4297
+ }
4298
+ }
4299
+
4165
4300
  function validateInitStatementReferences(ctx: AnalyzerContext): void {
4166
4301
  if (ctx.initStatements.length === 0) return
4167
4302