@barefootjs/jsx 0.38.0 → 0.39.1

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 (105) hide show
  1. package/dist/action-accessor.d.ts +159 -0
  2. package/dist/action-accessor.d.ts.map +1 -0
  3. package/dist/adapters/interface.d.ts +19 -0
  4. package/dist/adapters/interface.d.ts.map +1 -1
  5. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  6. package/dist/analyzer.d.ts +49 -1
  7. package/dist/analyzer.d.ts.map +1 -1
  8. package/dist/async-action-refusal.d.ts +45 -0
  9. package/dist/async-action-refusal.d.ts.map +1 -0
  10. package/dist/compiler.d.ts.map +1 -1
  11. package/dist/debug.d.ts +61 -5
  12. package/dist/debug.d.ts.map +1 -1
  13. package/dist/errors.d.ts +4 -0
  14. package/dist/errors.d.ts.map +1 -1
  15. package/dist/format-date-refusal.d.ts +2 -6
  16. package/dist/format-date-refusal.d.ts.map +1 -1
  17. package/dist/html-types.d.ts +5 -0
  18. package/dist/html-types.d.ts.map +1 -1
  19. package/dist/index.d.ts +3 -2
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1261 -422
  22. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/collect-elements.d.ts +17 -1
  24. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/compute-scope.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  28. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/declaration-sort.d.ts +2 -1
  31. package/dist/ir-to-client-js/declaration-sort.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-module-level.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +7 -5
  35. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/reactivity.d.ts +10 -2
  38. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/types.d.ts +4 -0
  40. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +52 -9
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/jsx-to-ir.d.ts.map +1 -1
  44. package/dist/signal-initializer.d.ts +24 -0
  45. package/dist/signal-initializer.d.ts.map +1 -0
  46. package/dist/ssr-defaults.d.ts.map +1 -1
  47. package/dist/ssr-seed-plan.d.ts.map +1 -1
  48. package/dist/template-position-walk.d.ts +68 -0
  49. package/dist/template-position-walk.d.ts.map +1 -0
  50. package/dist/types.d.ts +95 -0
  51. package/dist/types.d.ts.map +1 -1
  52. package/package.json +2 -2
  53. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +194 -4
  54. package/src/__tests__/action-accessor.test.ts +166 -0
  55. package/src/__tests__/adapter-output.test.ts +142 -0
  56. package/src/__tests__/create-mutation.test.ts +250 -0
  57. package/src/__tests__/create-query.test.ts +696 -0
  58. package/src/__tests__/csr-fragment-root-scope-shape.test.ts +156 -0
  59. package/src/__tests__/debug.test.ts +305 -0
  60. package/src/__tests__/doc-examples.test.ts +66 -3
  61. package/src/__tests__/ir-fragment-transparency.test.ts +23 -0
  62. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +245 -0
  63. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +80 -0
  64. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +445 -0
  65. package/src/__tests__/props-destructuring.test.ts +79 -4
  66. package/src/__tests__/reactive-factory-arity.test.ts +311 -0
  67. package/src/__tests__/ssr-portal-ref-callback.test.ts +5 -3
  68. package/src/action-accessor.ts +289 -0
  69. package/src/adapters/interface.ts +19 -0
  70. package/src/adapters/jsx-adapter.ts +47 -20
  71. package/src/analyzer.ts +593 -44
  72. package/src/async-action-refusal.ts +254 -0
  73. package/src/compiler.ts +81 -46
  74. package/src/debug.ts +351 -104
  75. package/src/errors.ts +39 -0
  76. package/src/format-date-refusal.ts +6 -125
  77. package/src/html-types.ts +14 -0
  78. package/src/index.ts +3 -1
  79. package/src/ir-to-client-js/build-references.ts +6 -2
  80. package/src/ir-to-client-js/collect-elements.ts +65 -4
  81. package/src/ir-to-client-js/compute-inlinability.ts +2 -1
  82. package/src/ir-to-client-js/compute-scope.ts +3 -1
  83. package/src/ir-to-client-js/control-flow/plan/build-insert.ts +1 -0
  84. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  85. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +112 -3
  86. package/src/ir-to-client-js/control-flow/stringify/insert.ts +1 -1
  87. package/src/ir-to-client-js/csr-substitute.ts +11 -3
  88. package/src/ir-to-client-js/declaration-sort.ts +7 -3
  89. package/src/ir-to-client-js/emit-module-level.ts +7 -4
  90. package/src/ir-to-client-js/emit-registration.ts +5 -10
  91. package/src/ir-to-client-js/index.ts +7 -2
  92. package/src/ir-to-client-js/phases/ref-callbacks.ts +1 -1
  93. package/src/ir-to-client-js/plan/build-declaration-emit.ts +16 -15
  94. package/src/ir-to-client-js/plan/declaration-emit.ts +7 -5
  95. package/src/ir-to-client-js/prop-handling.ts +4 -0
  96. package/src/ir-to-client-js/reactivity.ts +32 -1
  97. package/src/ir-to-client-js/stringify/declaration-emit.ts +14 -7
  98. package/src/ir-to-client-js/types.ts +4 -0
  99. package/src/ir-to-client-js/utils.ts +184 -21
  100. package/src/jsx-to-ir.ts +111 -14
  101. package/src/signal-initializer.ts +36 -0
  102. package/src/ssr-defaults.ts +10 -0
  103. package/src/ssr-seed-plan.ts +12 -1
  104. package/src/template-position-walk.ts +203 -0
  105. package/src/types.ts +99 -0
package/src/analyzer.ts CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
  import ts from 'typescript'
10
10
  import { CLIENT_DIRECTIVE_INTERIOR_RE, USE_CLIENT_DIRECTIVE, isUseClientDirectiveText } from './directives.ts'
11
- import type { ImportSpecifier, TypeInfo, ParamInfo, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation } from './types.ts'
11
+ import type { ImportSpecifier, TypeInfo, ParamInfo, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation, SignalFactoryCall } from './types.ts'
12
12
  import { parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr } from './expression-parser.ts'
13
13
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
14
14
  import { rewriteBarePropRefs } from './prop-rewrite.ts'
@@ -31,6 +31,7 @@ import { baseTypeName } from './rich-type-evidence.ts'
31
31
  import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
32
32
  import path from 'node:path'
33
33
  import fs from 'node:fs'
34
+ import { signalSecondBinding } from './signal-initializer.ts'
34
35
 
35
36
  // =============================================================================
36
37
  // TypeScript Program Creation
@@ -46,6 +47,40 @@ const REACTIVE_BRAND_PACKAGES = [
46
47
  '@barefootjs/form',
47
48
  ]
48
49
 
50
+ /**
51
+ * Is `id` sitting in a position where it names something rather than
52
+ * referencing a value — an object/class member key, a JSX attribute or
53
+ * intrinsic tag name, or a statement label? These positions merely SPELL an
54
+ * identifier's text without evaluating it as a variable reference, so any
55
+ * pass that resolves identifier text to a binding (a rename, an
56
+ * accessor-wrap, a free-reference scan) must leave them untouched.
57
+ *
58
+ * Shared by `classify()` below (factory-rename sites) and
59
+ * `rewriteIdentifierAsAccessor` (`ir-to-client-js/utils.ts`, #3239) — see
60
+ * CLAUDE.md's "one decision, two implementations" rule. Declaration-name
61
+ * positions (a parameter, `const`, `function`/`class` name) are
62
+ * deliberately NOT covered here: those introduce a new binding rather than
63
+ * naming an existing one, and the two callers disagree on how to handle a
64
+ * shadowing declaration (renaming wants to rename it too; accessor-wrapping
65
+ * deliberately wraps it so the shadow fails to parse), so each classifies
66
+ * those positions itself.
67
+ */
68
+ export function isNonReferenceIdentifierPosition(id: ts.Identifier): boolean {
69
+ const p = id.parent
70
+ if (ts.isPropertyAccessExpression(p) && p.name === id) return true // obj.name tail (incl. ?. chains)
71
+ if (ts.isPropertyAssignment(p) && p.name === id) return true // { name: v } key
72
+ if (ts.isBindingElement(p) && p.propertyName === id) return true // { name: local } pattern key
73
+ if ((ts.isMethodDeclaration(p) || ts.isGetAccessorDeclaration(p) ||
74
+ ts.isSetAccessorDeclaration(p) || ts.isPropertyDeclaration(p) ||
75
+ ts.isEnumMember(p)) && p.name === id) return true // member keys
76
+ if (ts.isJsxAttribute(p) && p.name === id) return true // JSX attr name
77
+ if ((ts.isLabeledStatement(p) && p.label === id)
78
+ || ((ts.isBreakStatement(p) || ts.isContinueStatement(p)) && p.label === id)) return true
79
+ if ((ts.isJsxOpeningElement(p) || ts.isJsxSelfClosingElement(p) || ts.isJsxClosingElement(p))
80
+ && p.tagName === id && /^[a-z]/.test(id.text)) return true // intrinsic tag <div>
81
+ return false
82
+ }
83
+
49
84
  /**
50
85
  * Check if a source file needs ts.TypeChecker for static analysis.
51
86
  * Reactive-brand detection requires the checker for library accessor patterns.
@@ -96,14 +131,29 @@ function findBrandPackageImportLoc(
96
131
  * imported types may resolve to `any` and the signal/memo regex fallback kicks in.
97
132
  * For full type resolution in build tools, pass a pre-built ts.Program via
98
133
  * CompileOptions.program instead.
134
+ *
135
+ * `hostOptions.currentDirectory` pins the directory a RELATIVE `filePath`
136
+ * (and the Program's own `getCurrentDirectory()`, which also roots
137
+ * `@types` discovery) resolves against, instead of `process.cwd()`. The
138
+ * Program still serves `source` at the relative name, so
139
+ * `program.getSourceFile(filePath)` resolves to it and the result can be
140
+ * handed to `compileJSX` as `CompileOptions.program` under that same
141
+ * relative `filePath`. Used by the conformance harness
142
+ * (`packages/adapter-tests/src/harness-program.ts`) to compile fixtures
143
+ * under a relative virtual name without its type resolution depending on
144
+ * where the process was started (#3220). Omitted, behaviour is unchanged.
99
145
  */
100
146
  export function createProgramForFile(
101
147
  source: string,
102
- filePath: string
148
+ filePath: string,
149
+ hostOptions: { currentDirectory?: string } = {}
103
150
  ): { program: ts.Program; sourceFile: ts.SourceFile; checker: ts.TypeChecker } | null {
104
151
  incrementCounter('programCreations')
105
152
  try {
106
- const normalizedPath = path.resolve(filePath)
153
+ const { currentDirectory } = hostOptions
154
+ const resolveFrom = (fileName: string): string =>
155
+ currentDirectory === undefined ? path.resolve(fileName) : path.resolve(currentDirectory, fileName)
156
+ const normalizedPath = resolveFrom(filePath)
107
157
 
108
158
  const compilerOptions: ts.CompilerOptions = {
109
159
  target: ts.ScriptTarget.Latest,
@@ -120,18 +170,19 @@ export function createProgramForFile(
120
170
 
121
171
  const virtualHost: ts.CompilerHost = {
122
172
  ...defaultHost,
173
+ ...(currentDirectory === undefined ? {} : { getCurrentDirectory: () => currentDirectory }),
123
174
  getSourceFile(fileName, languageVersion) {
124
- if (path.resolve(fileName) === normalizedPath) {
175
+ if (resolveFrom(fileName) === normalizedPath) {
125
176
  return ts.createSourceFile(fileName, source, languageVersion, true, ts.ScriptKind.TSX)
126
177
  }
127
178
  return defaultHost.getSourceFile(fileName, languageVersion)
128
179
  },
129
180
  fileExists(fileName) {
130
- if (path.resolve(fileName) === normalizedPath) return true
181
+ if (resolveFrom(fileName) === normalizedPath) return true
131
182
  return defaultHost.fileExists(fileName)
132
183
  },
133
184
  readFile(fileName) {
134
- if (path.resolve(fileName) === normalizedPath) return source
185
+ if (resolveFrom(fileName) === normalizedPath) return source
135
186
  return defaultHost.readFile(fileName)
136
187
  },
137
188
  }
@@ -148,6 +199,26 @@ export function createProgramForFile(
148
199
  }
149
200
  }
150
201
 
202
+ /**
203
+ * The Program to pass as `compileJSX`'s `program` when a test harness
204
+ * compiles `source` under the relative virtual `filename`, with type
205
+ * resolution anchored at `anchorDir` instead of `process.cwd()` — or
206
+ * `undefined` when the compiler would not build a checker for this source.
207
+ *
208
+ * Without it, a harness compile resolves `@barefootjs/*` relative to the
209
+ * directory `bun test` was started from, so a `Reactive<T>` accessor read
210
+ * such as `fetchPosts.isPending()` is typed `any` from the repo root and
211
+ * its real type from a package (#3220). `anchorDir` need not exist: module
212
+ * resolution only probes its ancestors for `node_modules`. The one
213
+ * implementation for every harness that compiles under relative names:
214
+ * the conformance harness (`packages/adapter-tests/src/harness-program.ts`)
215
+ * and the docs-example suite (`doc-examples.test.ts`).
216
+ */
217
+ export function createAnchoredProgram(source: string, filename: string, anchorDir: string): ts.Program | undefined {
218
+ if (!needsTypeBasedDetection(source)) return undefined
219
+ return createProgramForFile(source, filename, { currentDirectory: anchorDir })?.program
220
+ }
221
+
151
222
  // =============================================================================
152
223
  // Main Entry Point
153
224
  // =============================================================================
@@ -1142,6 +1213,22 @@ const PRIMITIVE_CANONICAL_NAMES: Record<string, 'signal' | 'memo' | 'effect' | '
1142
1213
  // is recorded separately on the collected signal so adapters can lower the
1143
1214
  // reader value; the reactivity kind itself is just `signal`.
1144
1215
  createSearchParams: 'signal',
1216
+ // Async reactive factories (#3165) return a `[value, action]` tuple whose
1217
+ // value half is a signal getter, so they resolve to the `signal` kind too;
1218
+ // SIGNAL_FACTORY_KINDS below records which factory it was.
1219
+ createQuery: 'signal',
1220
+ createMutation: 'signal',
1221
+ }
1222
+
1223
+ /**
1224
+ * Async reactive factories → their `SignalFactoryCall` kind (#3165). The value
1225
+ * half of the tuple is collected as a signal seeded from `options.initial`;
1226
+ * the kind tells every backend that re-emits the declaration to call the
1227
+ * factory instead of `createSignal`.
1228
+ */
1229
+ const SIGNAL_FACTORY_KINDS: Record<string, SignalFactoryCall['kind']> = {
1230
+ createQuery: 'query',
1231
+ createMutation: 'mutation',
1145
1232
  }
1146
1233
 
1147
1234
  /**
@@ -1271,15 +1358,41 @@ function resolveEnvSignalKey(
1271
1358
  callExpr: ts.CallExpression,
1272
1359
  ctx: AnalyzerContext
1273
1360
  ): string | null {
1361
+ return resolveClientFactoryEntry(callExpr, ENV_SIGNAL_FACTORIES, ctx)
1362
+ }
1363
+
1364
+ /**
1365
+ * Resolve a call expression to the {@link SIGNAL_FACTORY_KINDS} kind of the
1366
+ * async reactive factory it calls (`createQuery(...)` → `'query'`), or null.
1367
+ * Same fast/slow paths as {@link resolveEnvSignalKey}.
1368
+ */
1369
+ function resolveSignalFactoryKind(
1370
+ callExpr: ts.CallExpression,
1371
+ ctx: AnalyzerContext
1372
+ ): SignalFactoryCall['kind'] | null {
1373
+ return resolveClientFactoryEntry(callExpr, SIGNAL_FACTORY_KINDS, ctx)
1374
+ }
1375
+
1376
+ /**
1377
+ * Look a call's callee up in a table keyed by `@barefootjs/client` export
1378
+ * names: the direct name, an alias resolved through the checker, or a
1379
+ * `bf.<name>` namespace access. Shared by the env-signal and async-factory
1380
+ * resolvers above.
1381
+ */
1382
+ function resolveClientFactoryEntry<T>(
1383
+ callExpr: ts.CallExpression,
1384
+ table: Record<string, T>,
1385
+ ctx: AnalyzerContext
1386
+ ): T | null {
1274
1387
  if (ts.isIdentifier(callExpr.expression)) {
1275
- const key = ENV_SIGNAL_FACTORIES[callExpr.expression.text]
1276
- if (key) return key
1388
+ const hit = table[callExpr.expression.text]
1389
+ if (hit) return hit
1277
1390
  const canonical = resolveCanonicalClientExportName(callExpr.expression, ctx)
1278
- return canonical ? (ENV_SIGNAL_FACTORIES[canonical] ?? null) : null
1391
+ return canonical ? (table[canonical] ?? null) : null
1279
1392
  }
1280
1393
  if (ts.isPropertyAccessExpression(callExpr.expression)) {
1281
- const key = ENV_SIGNAL_FACTORIES[callExpr.expression.name.text]
1282
- if (key && isBarefootClientNamespace(callExpr.expression.expression, ctx)) return key
1394
+ const hit = table[callExpr.expression.name.text]
1395
+ if (hit && isBarefootClientNamespace(callExpr.expression.expression, ctx)) return hit
1283
1396
  }
1284
1397
  return null
1285
1398
  }
@@ -1323,6 +1436,11 @@ function isSignalDeclaration(node: ts.VariableDeclaration, ctx: AnalyzerContext)
1323
1436
  function collectSignal(node: ts.VariableDeclaration, ctx: AnalyzerContext): void {
1324
1437
  const pattern = node.name as ts.ArrayBindingPattern
1325
1438
  const callExpr = node.initializer as ts.CallExpression
1439
+ const factoryKind = resolveSignalFactoryKind(callExpr, ctx)
1440
+ if (factoryKind) {
1441
+ collectFactorySignal(node, pattern, callExpr, factoryKind, ctx)
1442
+ return
1443
+ }
1326
1444
 
1327
1445
  const elements = pattern.elements
1328
1446
  // Getter-elided form: `const [, setActive] = createSignal(0)`. The first
@@ -1408,6 +1526,137 @@ function collectSignal(node: ts.VariableDeclaration, ctx: AnalyzerContext): void
1408
1526
  })
1409
1527
  }
1410
1528
 
1529
+ /**
1530
+ * Collect `const [value, action] = createQuery(fn, options)` (#3165) or
1531
+ * `createMutation(fn, options)` (#3210) as a signal whose getter is the value
1532
+ * and whose initial value is `options.initial` (a query) or `undefined` (a
1533
+ * mutation, which has no `initial`: spec/async.md §7.4). The action is
1534
+ * recorded on `factory`, never as a setter, so setter-keyed logic
1535
+ * (controlled-prop sync, handler→setter wiring, SSR setter stubs) leaves it
1536
+ * alone.
1537
+ *
1538
+ * `initial` is read structurally from an object-literal `options` with no
1539
+ * spread: its value expression when the key is present, the literal
1540
+ * `undefined` when it isn't. Any other `options`
1541
+ * shape seeds from the member read `(<options>).initial`, which each backend
1542
+ * lowers or refuses like any other expression — never a guess.
1543
+ */
1544
+ function collectFactorySignal(
1545
+ node: ts.VariableDeclaration,
1546
+ pattern: ts.ArrayBindingPattern,
1547
+ callExpr: ts.CallExpression,
1548
+ kind: SignalFactoryCall['kind'],
1549
+ ctx: AnalyzerContext,
1550
+ ): void {
1551
+ const elements = pattern.elements
1552
+ const bindingName = (el: ts.ArrayBindingElement | undefined): string | null =>
1553
+ el && ts.isBindingElement(el) && ts.isIdentifier(el.name) ? el.name.text : null
1554
+ // BF115 reports any other destructure shape; nothing is collected for it.
1555
+ if (elements.length < 1 || elements.length > 2) return
1556
+ const getterElided = ts.isOmittedExpression(elements[0])
1557
+ const valueName = getterElided ? null : bindingName(elements[0])
1558
+ if (!getterElided && valueName === null) return
1559
+ const action = elements.length === 2 ? bindingName(elements[1]) : null
1560
+ if (elements.length === 2 && action === null) return
1561
+ if (getterElided && action === null) return
1562
+
1563
+ // A mutation's value is `undefined` until its action is called; an
1564
+ // `initial` it was given anyway is refused (BF118), never read.
1565
+ const initialNode: FactoryInitialNode = kind === 'mutation'
1566
+ ? { kind: 'absent' }
1567
+ : factoryInitialNode(callExpr.arguments[1])
1568
+ const initialValue = initialNode.kind === 'expression'
1569
+ ? ctx.getJS(initialNode.node)
1570
+ : initialNode.kind === 'member-read'
1571
+ ? `(${ctx.getJS(initialNode.options)}).initial`
1572
+ : 'undefined'
1573
+ const typedInitialValue = initialNode.kind === 'expression'
1574
+ ? initialNode.node.getText(ctx.sourceFile)
1575
+ : initialNode.kind === 'member-read'
1576
+ ? `(${initialNode.options.getText(ctx.sourceFile)}).initial`
1577
+ : undefined
1578
+ const initialFreeIdentifiers = initialNode.kind === 'expression'
1579
+ ? extractFreeIdentifiersFromNode(initialNode.node)
1580
+ : initialNode.kind === 'member-read'
1581
+ ? extractFreeIdentifiersFromNode(initialNode.options)
1582
+ : new Set<string>()
1583
+
1584
+ let type: TypeInfo = { kind: 'unknown', raw: 'unknown' }
1585
+ if (callExpr.typeArguments && callExpr.typeArguments.length > 0) {
1586
+ type = typeNodeToTypeInfo(callExpr.typeArguments[0], ctx.sourceFile) ?? type
1587
+ } else if (initialNode.kind !== 'absent') {
1588
+ type = inferTypeFromValue(initialValue)
1589
+ }
1590
+
1591
+ // Destructured-arg components (#2265): the CSR `template:` arrow's
1592
+ // module-scope fallback needs `_p.<name>` for a bare destructured prop in
1593
+ // `initial`, same as a `createSignal` initial value.
1594
+ let templateInitialValue: string | undefined
1595
+ if (!ctx.propsObjectName && initialNode.kind === 'expression') {
1596
+ const propNames = new Set(ctx.propsParams.map(p => p.name))
1597
+ if (propNames.size > 0) {
1598
+ const propAliases = buildPropAliasMap(ctx.propsParams)
1599
+ templateInitialValue = rewriteBarePropRefs(initialValue, initialNode.node, propNames, undefined, propAliases)
1600
+ }
1601
+ }
1602
+
1603
+ const argTexts = callExpr.arguments.map(arg => ctx.getJS(arg))
1604
+ const requestArg = callExpr.arguments[0]
1605
+
1606
+ ctx.signals.push({
1607
+ getter: valueName ?? `__bfGet_${action}`,
1608
+ setter: null,
1609
+ getterElided: getterElided || undefined,
1610
+ initialValue,
1611
+ typedInitialValue: typedInitialValue !== undefined && typedInitialValue !== initialValue ? typedInitialValue : undefined,
1612
+ templateInitialValue,
1613
+ type,
1614
+ loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
1615
+ initialFreeIdentifiers,
1616
+ factory: {
1617
+ kind,
1618
+ callee: callExpr.expression.getText(ctx.sourceFile),
1619
+ argsText: argTexts.join(', '),
1620
+ requestText: argTexts[0] ?? '',
1621
+ requestFreeIdentifiers: requestArg ? extractFreeIdentifiersFromNode(requestArg) : new Set(),
1622
+ action,
1623
+ },
1624
+ })
1625
+ }
1626
+
1627
+ /**
1628
+ * Where an async factory's `initial` comes from (#3165): the `initial`
1629
+ * property's value in an object-literal `options` (`expression`), nothing
1630
+ * (`absent` — no `options`, or a literal without the key), or a member read
1631
+ * of `options` itself when the literal can't be read structurally (spread,
1632
+ * computed key, accessor) or `options` isn't a literal at all (`member-read`).
1633
+ */
1634
+ type FactoryInitialNode =
1635
+ | { kind: 'expression'; node: ts.Expression }
1636
+ | { kind: 'absent' }
1637
+ | { kind: 'member-read'; options: ts.Expression }
1638
+
1639
+ function factoryInitialNode(options: ts.Expression | undefined): FactoryInitialNode {
1640
+ if (!options) return { kind: 'absent' }
1641
+ let unwrapped: ts.Expression = options
1642
+ while (ts.isParenthesizedExpression(unwrapped) || ts.isAsExpression(unwrapped) || ts.isSatisfiesExpression(unwrapped)) {
1643
+ unwrapped = unwrapped.expression
1644
+ }
1645
+ if (!ts.isObjectLiteralExpression(unwrapped)) return { kind: 'member-read', options }
1646
+ let found: ts.Expression | null = null
1647
+ for (const prop of unwrapped.properties) {
1648
+ if (ts.isSpreadAssignment(prop)) return { kind: 'member-read', options }
1649
+ const name = prop.name
1650
+ if (name === undefined || ts.isComputedPropertyName(name)) return { kind: 'member-read', options }
1651
+ const key = ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name) ? name.text : null
1652
+ if (key !== 'initial') continue
1653
+ if (ts.isPropertyAssignment(prop)) found = prop.initializer
1654
+ else if (ts.isShorthandPropertyAssignment(prop)) found = prop.name
1655
+ else return { kind: 'member-read', options }
1656
+ }
1657
+ return found ? { kind: 'expression', node: found } : { kind: 'absent' }
1658
+ }
1659
+
1411
1660
  /**
1412
1661
  * Detects `const s = createSignal(...)` — the tuple is stored in an
1413
1662
  * Identifier rather than destructured. The accessor(s) appear in later
@@ -2138,6 +2387,10 @@ const CLIENT_EXPORTS = new Set([
2138
2387
  // getter; the compiler lowers the reader value per adapter via the signal's
2139
2388
  // `envReader` key, with no `searchParams`-name allow-list.
2140
2389
  'createSearchParams',
2390
+ // Async layer 0 (spec/async.md §7): `http` descriptors and `HttpError`
2391
+ // (#3161), and `createQuery` (#3165) / `createMutation` (#3210),
2392
+ // recognised structurally as factory signals.
2393
+ 'http', 'HttpError', 'createQuery', 'createMutation',
2141
2394
  // Pure URL-query builder (#2042) — the functional counterpart to
2142
2395
  // `searchParams`. Runs natively on the client; SSR adapters lower a
2143
2396
  // `queryHref(base, { … })` call to their query helper (go-template: `bf_query`).
@@ -2875,6 +3128,7 @@ function collectFunction(
2875
3128
  declarationKind: 'function',
2876
3129
  isModule: _isModule || undefined,
2877
3130
  isJsxFunction: isJsxFunction || undefined,
3131
+ freeIdentifiers: extractFreeIdentifiersFromNode(node),
2878
3132
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
2879
3133
  })
2880
3134
  }
@@ -3428,6 +3682,12 @@ function collectConstant(
3428
3682
 
3429
3683
  // Compute AST-derived flags for Phase 2 optimization
3430
3684
  const containsArrow = node.initializer ? nodeContainsArrow(node.initializer) : false
3685
+ let unwrappedInitializer: ts.Expression | undefined = node.initializer
3686
+ while (unwrappedInitializer && (ts.isParenthesizedExpression(unwrappedInitializer) || ts.isAsExpression(unwrappedInitializer) || ts.isSatisfiesExpression(unwrappedInitializer))) {
3687
+ unwrappedInitializer = unwrappedInitializer.expression
3688
+ }
3689
+ const isFunctionValue = unwrappedInitializer !== undefined &&
3690
+ (ts.isArrowFunction(unwrappedInitializer) || ts.isFunctionExpression(unwrappedInitializer))
3431
3691
  const systemConstructKind = node.initializer ? getSystemConstructKind(node.initializer) : undefined
3432
3692
 
3433
3693
  // Pre-transform bare prop refs for template inlining (#807). Two
@@ -3472,7 +3732,8 @@ function collectConstant(
3472
3732
  const shadowedByNonAlias = new Set<string>()
3473
3733
  for (const s of ctx.signals) {
3474
3734
  shadowedByNonAlias.add(s.getter)
3475
- if (s.setter) shadowedByNonAlias.add(s.setter)
3735
+ const second = signalSecondBinding(s)
3736
+ if (second) shadowedByNonAlias.add(second)
3476
3737
  }
3477
3738
  for (const m of ctx.memos) shadowedByNonAlias.add(m.name)
3478
3739
  const aliases = new Set<string>()
@@ -3536,6 +3797,7 @@ function collectConstant(
3536
3797
  isJsx,
3537
3798
  isJsxFunction: isJsxFunction || undefined,
3538
3799
  containsArrow: containsArrow || undefined,
3800
+ isFunctionValue: isFunctionValue || undefined,
3539
3801
  systemConstructKind,
3540
3802
  templateValue,
3541
3803
  origin: {
@@ -3703,7 +3965,10 @@ function collectKeysFromMembers(
3703
3965
  *
3704
3966
  * `array`/`object` admit only when EVERY reachable leaf resolves — an
3705
3967
  * array's element type and an object's every property type must pass this
3706
- * same check, recursively. A union, a function, or an un-catalogued named
3968
+ * same check, recursively. A same-file object type referenced by name
3969
+ * (`Item` in `items: Item[]`) is checked through its declaration's members
3970
+ * (`LocalObjectMemberTypes`) the same way an inline object literal's are.
3971
+ * A union, a function, or any other named
3707
3972
  * type reachable ANYWHERE inside the shape declines the WHOLE member (not
3708
3973
  * just that one leaf): `collectMemberTypes` is an all-or-nothing gate per
3709
3974
  * member, so a partially-resolvable structural type must still decline —
@@ -3728,22 +3993,91 @@ function collectKeysFromMembers(
3728
3993
  * synthesized struct is exactly as faithful a representation as the type
3729
3994
  * itself claims, nothing is being guessed.
3730
3995
  */
3731
- function isResolvableMemberType(info: TypeInfo): boolean {
3996
+ function isResolvableMemberType(
3997
+ info: TypeInfo,
3998
+ localObjectMembers?: LocalObjectMemberTypes,
3999
+ visiting: ReadonlySet<string> = new Set(),
4000
+ ): boolean {
4001
+ const recurse = (t: TypeInfo): boolean => isResolvableMemberType(t, localObjectMembers, visiting)
3732
4002
  switch (info.kind) {
3733
4003
  case 'primitive':
3734
4004
  return info.primitive === 'string' || info.primitive === 'number' || info.primitive === 'boolean'
3735
- case 'interface':
3736
- return CATALOGUED_RICH_TYPE_NAMES.has(baseTypeName(info.raw))
4005
+ case 'interface': {
4006
+ if (CATALOGUED_RICH_TYPE_NAMES.has(baseTypeName(info.raw))) return true
4007
+ // A same-file object type referenced BY NAME (`initial: State`,
4008
+ // `items: Item[]`) is the same structural shape as its inline
4009
+ // spelling — see `LocalObjectMemberTypes`. A name already on the
4010
+ // resolution stack (a recursive type) declines rather than loop.
4011
+ if (!localObjectMembers || visiting.has(info.raw)) return false
4012
+ const members = localObjectMembers(info.raw)
4013
+ if (!members) return false
4014
+ const inner = new Set(visiting).add(info.raw)
4015
+ return members.every(t => isResolvableMemberType(t, localObjectMembers, inner))
4016
+ }
3737
4017
  case 'array':
3738
- return !!info.elementType && isResolvableMemberType(info.elementType)
4018
+ return !!info.elementType && recurse(info.elementType)
3739
4019
  case 'object':
3740
- return info.properties !== undefined && info.properties.every(prop => isResolvableMemberType(prop.type))
4020
+ return info.properties !== undefined && info.properties.every(prop => recurse(prop.type))
3741
4021
  // Unions, functions, and `unknown` all decline — see docstring.
3742
4022
  default:
3743
4023
  return false
3744
4024
  }
3745
4025
  }
3746
4026
 
4027
+ /**
4028
+ * Member types of a same-file, non-generic object type declared by name —
4029
+ * an `interface` with no `extends` clause, or a `type X = { … }` alias —
4030
+ * or `null` when `name` isn't one (an import, a generic, a union alias, an
4031
+ * interface with heritage, or a declaration with a non-property member such
4032
+ * as a method or index signature). #3142 follow-up: `{ initial }: {
4033
+ * initial: State }` declined to `unknown` while the `props`-object form
4034
+ * (`props: { initial: State }`, `extractPropsFromTypeMembers`) resolved
4035
+ * `State` — the same destructured-vs-props-object asymmetry #2677 closed
4036
+ * for INLINE object shapes, left open for NAMED ones. A named same-file
4037
+ * object type is exactly as representable as its inline spelling: it lands
4038
+ * in `ir.metadata.typeDefinitions`, and typed adapters already emit a
4039
+ * struct for it (go-template's `typeDefinitionToGo`), so admitting it
4040
+ * resurrects neither #2150 concern.
4041
+ */
4042
+ type LocalObjectMemberTypes = (name: string) => TypeInfo[] | null
4043
+
4044
+ function localObjectMemberTypesFor(ctx: AnalyzerContext): LocalObjectMemberTypes {
4045
+ // Each lookup walks the whole source file, and one props annotation can
4046
+ // reach the same name many times (`Item` from several `Item[]` members),
4047
+ // so answer each name once per annotation.
4048
+ const cache = new Map<string, TypeInfo[] | null>()
4049
+ const lookup = (name: string): TypeInfo[] | null => {
4050
+ // Exactly one declaration, or decline: two `interface State` blocks
4051
+ // merge into one type, and checking either half alone could admit a
4052
+ // shape whose other half carries a member this gate would refuse.
4053
+ const decls = findTypeDeclarations(name, ctx.sourceFile)
4054
+ if (decls.length !== 1) return null
4055
+ const decl = decls[0]
4056
+ if (decl.typeParameters?.length) return null
4057
+ let members: ts.NodeArray<ts.TypeElement>
4058
+ if (ts.isInterfaceDeclaration(decl)) {
4059
+ if (decl.heritageClauses?.length) return null
4060
+ members = decl.members
4061
+ } else if (ts.isTypeLiteralNode(decl.type)) {
4062
+ members = decl.type.members
4063
+ } else {
4064
+ return null
4065
+ }
4066
+ const types: TypeInfo[] = []
4067
+ for (const member of members) {
4068
+ if (!ts.isPropertySignature(member) || !member.type) return null
4069
+ const info = typeNodeToTypeInfo(member.type, ctx.sourceFile)
4070
+ if (!info) return null
4071
+ types.push(info)
4072
+ }
4073
+ return types
4074
+ }
4075
+ return (name) => {
4076
+ if (!cache.has(name)) cache.set(name, lookup(name))
4077
+ return cache.get(name) ?? null
4078
+ }
4079
+ }
4080
+
3747
4081
  /**
3748
4082
  * Build a property-name -> { type, optional } map from a props type
3749
4083
  * annotation, for destructured params (`{ value }: Props`) so they carry the
@@ -3759,9 +4093,10 @@ function isResolvableMemberType(info: TypeInfo): boolean {
3759
4093
  * #2252's nullish-flip machinery supplies the nillable representation
3760
4094
  * exactly where absence is semantically observable (#2259).
3761
4095
  * - A member resolves a type when it is a PRIMITIVE (string/number/boolean),
3762
- * a CATALOGUED rich type (`Date`), or a STRUCTURAL shape (array/object)
3763
- * built entirely out of those, recursively (#2677). Unions, functions, and
3764
- * un-catalogued named types (`Map`, `Set`, …) are left as `unknown` — see
4096
+ * a CATALOGUED rich type (`Date`), or a STRUCTURAL shape (array/object,
4097
+ * inline or a same-file object type referenced by name) built entirely
4098
+ * out of those, recursively (#2677). Unions, functions, and other named
4099
+ * types (imports, generics, `Map`, `Set`, …) are left as `unknown` — see
3765
4100
  * `isResolvableMemberType`'s own docstring for why the structural cases
3766
4101
  * are safe to admit and why those three still are not.
3767
4102
  */
@@ -3769,6 +4104,7 @@ function collectMemberTypes(
3769
4104
  typeNode: ts.TypeNode,
3770
4105
  ctx: AnalyzerContext
3771
4106
  ): Map<string, { type: TypeInfo | null; optional: boolean }> | null {
4107
+ const localObjectMembers = localObjectMemberTypesFor(ctx)
3772
4108
  const fromMembers = (
3773
4109
  members: ts.NodeArray<ts.TypeElement>
3774
4110
  ): Map<string, { type: TypeInfo | null; optional: boolean }> => {
@@ -3777,7 +4113,7 @@ function collectMemberTypes(
3777
4113
  if (ts.isPropertySignature(member) && member.name) {
3778
4114
  const info = member.type ? typeNodeToTypeInfo(member.type, ctx.sourceFile) : null
3779
4115
  map.set(member.name.getText(ctx.sourceFile), {
3780
- type: info && isResolvableMemberType(info) ? info : null,
4116
+ type: info && isResolvableMemberType(info, localObjectMembers) ? info : null,
3781
4117
  optional: !!member.questionToken,
3782
4118
  })
3783
4119
  }
@@ -3857,21 +4193,19 @@ function extractPropsFromTypeMembers(
3857
4193
  }
3858
4194
 
3859
4195
  /**
3860
- * Find a type declaration (interface or type alias) by name in the source file.
4196
+ * Every type declaration (interface or type alias) named `typeName` in the
4197
+ * source file, in source order. More than one means interface declaration
4198
+ * merging (or a name reused in nested scopes).
3861
4199
  */
3862
- function findTypeDeclaration(
4200
+ function findTypeDeclarations(
3863
4201
  typeName: string,
3864
4202
  sourceFile: ts.SourceFile
3865
- ): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined {
3866
- let result: ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined
4203
+ ): Array<ts.InterfaceDeclaration | ts.TypeAliasDeclaration> {
4204
+ const result: Array<ts.InterfaceDeclaration | ts.TypeAliasDeclaration> = []
3867
4205
 
3868
4206
  function visit(node: ts.Node): void {
3869
- if (ts.isInterfaceDeclaration(node) && node.name.text === typeName) {
3870
- result = node
3871
- return
3872
- }
3873
- if (ts.isTypeAliasDeclaration(node) && node.name.text === typeName) {
3874
- result = node
4207
+ if ((ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) && node.name.text === typeName) {
4208
+ result.push(node)
3875
4209
  return
3876
4210
  }
3877
4211
  ts.forEachChild(node, visit)
@@ -3881,6 +4215,17 @@ function findTypeDeclaration(
3881
4215
  return result
3882
4216
  }
3883
4217
 
4218
+ /**
4219
+ * Find a type declaration (interface or type alias) by name in the source
4220
+ * file — the LAST one when the name is declared more than once.
4221
+ */
4222
+ function findTypeDeclaration(
4223
+ typeName: string,
4224
+ sourceFile: ts.SourceFile
4225
+ ): ts.InterfaceDeclaration | ts.TypeAliasDeclaration | undefined {
4226
+ return findTypeDeclarations(typeName, sourceFile).at(-1)
4227
+ }
4228
+
3884
4229
  // =============================================================================
3885
4230
  // Helpers
3886
4231
  // =============================================================================
@@ -4048,6 +4393,13 @@ function validateContext(ctx: AnalyzerContext): void {
4048
4393
  // failures before factory inlining landed (#931).
4049
4394
  validateReactiveFactoryCalls(ctx)
4050
4395
 
4396
+ // BF115/BF116: flag a RECOGNISED createSignal/createMemo call used with a
4397
+ // destructure arity or argument count it doesn't support — the gap
4398
+ // validateReactiveFactoryCalls above doesn't cover, since it exists to
4399
+ // validate an unrecognised callee and skips createSignal/createMemo
4400
+ // unconditionally (#3159).
4401
+ validateReactiveFactoryArity(ctx)
4402
+
4051
4403
  // BF013: flag a reactive primitive invoked through a namespace import
4052
4404
  // that the analyzer could not resolve (#2771) — same "silently dropped,
4053
4405
  // ReferenceError at hydrate" failure shape as BF011.
@@ -4370,7 +4722,8 @@ function collectResolvedNames(ctx: AnalyzerContext): Set<string> {
4370
4722
  for (const f of ctx.localFunctions) names.add(f.name)
4371
4723
  for (const s of ctx.signals) {
4372
4724
  names.add(s.getter)
4373
- if (s.setter) names.add(s.setter)
4725
+ const second = signalSecondBinding(s)
4726
+ if (second) names.add(second)
4374
4727
  }
4375
4728
  for (const m of ctx.memos) names.add(m.name)
4376
4729
  for (const p of ctx.propsParams) names.add(p.name)
@@ -5485,17 +5838,7 @@ function detectReactiveFactory(
5485
5838
  if (!relevantNames.has(id.text)) return
5486
5839
  const p = id.parent
5487
5840
  // Pure-key / non-reference positions — never rename:
5488
- if (ts.isPropertyAccessExpression(p) && p.name === id) return // obj.name tail (incl. ?. chains)
5489
- if (ts.isPropertyAssignment(p) && p.name === id) return // { name: v } key
5490
- if (ts.isBindingElement(p) && p.propertyName === id) return // { name: local } pattern key
5491
- if ((ts.isMethodDeclaration(p) || ts.isGetAccessorDeclaration(p) ||
5492
- ts.isSetAccessorDeclaration(p) || ts.isPropertyDeclaration(p) ||
5493
- ts.isEnumMember(p)) && p.name === id) return // member keys
5494
- if (ts.isJsxAttribute(p) && p.name === id) return // JSX attr name
5495
- if ((ts.isLabeledStatement(p) && p.label === id) ||
5496
- ((ts.isBreakStatement(p) || ts.isContinueStatement(p)) && p.label === id)) return
5497
- if ((ts.isJsxOpeningElement(p) || ts.isJsxSelfClosingElement(p) || ts.isJsxClosingElement(p)) &&
5498
- p.tagName === id && /^[a-z]/.test(id.text)) return // intrinsic tag <div>
5841
+ if (isNonReferenceIdentifierPosition(id)) return
5499
5842
 
5500
5843
  // Shorthand dual-role positions → expansion form (renaming must
5501
5844
  // preserve the implied key): `{ name }` object literal / pattern.
@@ -6009,6 +6352,9 @@ export function validateReactiveFactoryCalls(ctx: AnalyzerContext): void {
6009
6352
  // import (`import { createSearchParams as csp }`) is accepted here too,
6010
6353
  // rather than falling through to a spurious BF110.
6011
6354
  if (resolveEnvSignalKey(decl.initializer, ctx)) continue
6355
+ // Async reactive factories (`createQuery`, #3165) return a
6356
+ // `[value, action]` tuple and are collected by `collectFactorySignal`.
6357
+ if (resolveSignalFactoryKind(decl.initializer, ctx)) continue
6012
6358
 
6013
6359
  const declinedEntry = ctx.declinedReactiveFactories.get(callee)
6014
6360
  if (declinedEntry) {
@@ -6064,6 +6410,209 @@ export function validateReactiveFactoryCalls(ctx: AnalyzerContext): void {
6064
6410
  }
6065
6411
  }
6066
6412
 
6413
+ /**
6414
+ * BF115 / BF116 (#3159): two `createSignal`/`createMemo` shapes that
6415
+ * mis-compiled silently before this pass existed, because
6416
+ * `validateReactiveFactoryCalls` above unconditionally `continue`s past any
6417
+ * array-pattern destructure whose callee is `createSignal`/`createMemo` —
6418
+ * it exists to validate an UNRECOGNISED callee, and never checked whether a
6419
+ * RECOGNISED one was actually called with a shape it supports.
6420
+ *
6421
+ * - **BF115 — tuple arity.** `createSignal(...)` returns `[getter, setter]`:
6422
+ * a 1-element destructure keeps just the getter (`setter: null`,
6423
+ * supported), but `collectSignal`'s `elements.length > 2` guard silently
6424
+ * returns with NOTHING pushed to `ctx.signals` for anything wider — the
6425
+ * whole declaration vanishes from the compiled output, and a same-name
6426
+ * prop (`const [user, setUser, extra] = createSignal(props.user)` next to
6427
+ * a `user` prop) silently mis-seeds `user` as the raw prop accessor
6428
+ * instead of the signal. `createMemo(...)` returns a single getter, not a
6429
+ * tuple, so ANY array-pattern destructure of it is a mismatch (it isn't
6430
+ * even reachable through `collectMemo`, which requires an identifier
6431
+ * binding — so today it silently produces nothing at all, not even an
6432
+ * opaque local).
6433
+ * - **BF116 — extra arguments.** `createSignal(initialValue?)` takes 0 or 1
6434
+ * argument; `createMemo(computeFn)` takes exactly 1; an env-signal factory
6435
+ * (`createSearchParams()`) takes none. `collectSignal`/
6436
+ * `collectMemo` only ever read `arguments[0]`, so any argument beyond it
6437
+ * (`createSignal(props.user, { from: 'router' })`) is silently dropped
6438
+ * from the emitted client JS with no diagnostic.
6439
+ *
6440
+ * Recognises the callee via `resolvePrimitiveKind` — the same
6441
+ * TypeChecker-backed, alias/namespace-import-safe resolution
6442
+ * `isSignalDeclaration`/`isMemoDeclaration` use — rather than the bare
6443
+ * identifier-text match `validateReactiveFactoryCalls` uses for BF110, so
6444
+ * an aliased import (`import { createSignal as sig }`) is still caught.
6445
+ *
6446
+ * This walks the analyzer's own parse of the ORIGINAL source AST (Phase 1),
6447
+ * which runs strictly before Phase 2 client-JS emission — the compiler's
6448
+ * own profile-mode `__bfId` argument (`ir-to-client-js/stringify/
6449
+ * declaration-emit.ts`, `profiler.ts`) is inserted later, during emission,
6450
+ * so it can never appear in a call this pass inspects and needs no
6451
+ * special-casing here.
6452
+ */
6453
+ function validateReactiveFactoryArity(ctx: AnalyzerContext): void {
6454
+ if (!ctx.componentNode) return
6455
+ const body = ts.isFunctionDeclaration(ctx.componentNode)
6456
+ ? ctx.componentNode.body
6457
+ : (ts.isBlock(ctx.componentNode.body) ? ctx.componentNode.body : null)
6458
+ if (!body) return
6459
+
6460
+ checkStatementsForReactiveFactoryArity(body.statements, ctx)
6461
+
6462
+ // Conditional early-return branches get their own signal collection path
6463
+ // (#1414 cell #8 — `collectBranchSignals`, called from the "if statement
6464
+ // with JSX return" case in `visitComponentBody` above): a top-level `if`
6465
+ // whose then-branch returns JSX has its *direct* statements scanned for
6466
+ // `createSignal` declarations too, so a bad-arity call there mis-compiles
6467
+ // exactly like a top-level one would, and needs the same diagnostic — not
6468
+ // just the top-level scan above, which the branch's statements are never
6469
+ // members of.
6470
+ for (const stmt of body.statements) {
6471
+ if (!ts.isIfStatement(stmt)) continue
6472
+ if (!findJsxReturnInBlock(stmt.thenStatement)) continue
6473
+ if (!ts.isBlock(stmt.thenStatement)) continue
6474
+ checkStatementsForReactiveFactoryArity(stmt.thenStatement.statements, ctx)
6475
+ }
6476
+ }
6477
+
6478
+ /**
6479
+ * BF115/BF116 over one flat list of statements — shared by the component
6480
+ * body's top-level scan and the conditional-branch scan above, both of
6481
+ * which only ever look at direct variable-statement children (never
6482
+ * recursing further), matching exactly what `collectSignal`/`collectMemo`
6483
+ * are reachable from in each case.
6484
+ */
6485
+ function checkStatementsForReactiveFactoryArity(statements: readonly ts.Statement[], ctx: AnalyzerContext): void {
6486
+ for (const stmt of statements) {
6487
+ if (!ts.isVariableStatement(stmt)) continue
6488
+ for (const decl of stmt.declarationList.declarations) {
6489
+ if (!decl.initializer || !ts.isCallExpression(decl.initializer)) continue
6490
+ const callExpr = decl.initializer
6491
+ const kind = resolvePrimitiveKind(callExpr, ctx)
6492
+ if (kind !== 'signal' && kind !== 'memo') continue
6493
+
6494
+ const loc = getSourceLocation(stmt, ctx.sourceFile, ctx.filePath)
6495
+ const calleeText = callExpr.expression.getText(ctx.sourceFile)
6496
+
6497
+ // Async reactive factories (`createQuery(fn, options?)`, #3165) return
6498
+ // `[value, action]` and take a request function plus options.
6499
+ const factoryKind = kind === 'signal' ? resolveSignalFactoryKind(callExpr, ctx) : null
6500
+ if (factoryKind !== null) {
6501
+ checkAsyncFactoryArity(decl, callExpr, calleeText, loc, ctx)
6502
+ if (factoryKind === 'mutation') checkMutationInitialOption(callExpr, calleeText, ctx)
6503
+ continue
6504
+ }
6505
+
6506
+ // BF115: tuple-destructure arity. `createMemo` never returns a tuple
6507
+ // (maxArity 0 — any array-pattern destructure of it is a mismatch);
6508
+ // `createSignal` returns 1-2 elements.
6509
+ if (ts.isArrayBindingPattern(decl.name)) {
6510
+ const elementCount = decl.name.elements.length
6511
+ const maxArity = kind === 'signal' ? 2 : 0
6512
+ if (elementCount < 1 || elementCount > maxArity) {
6513
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_ARITY_MISMATCH, loc, {
6514
+ severity: 'error',
6515
+ message: kind === 'signal'
6516
+ ? (elementCount === 0
6517
+ ? `'${calleeText}(...)' returns a 2-element tuple '[getter, setter]' — this ` +
6518
+ `destructure binds 0 elements, so neither the getter nor the setter is ` +
6519
+ `reachable. Use 'const [get, set] = ${calleeText}(...)' or ` +
6520
+ `'const [get] = ${calleeText}(...)'.`
6521
+ : `'${calleeText}(...)' returns a 2-element tuple '[getter, setter]' (a ` +
6522
+ `1-element destructure keeps just the getter) — this destructure has ` +
6523
+ `${elementCount} elements. The extra binding(s) are silently dropped from ` +
6524
+ `the compiled output today. Use 'const [get, set] = ${calleeText}(...)' or ` +
6525
+ `'const [get] = ${calleeText}(...)'.`)
6526
+ : `'${calleeText}(...)' returns a single getter function, not a tuple — this ` +
6527
+ `destructures ${elementCount} element${elementCount === 1 ? '' : 's'} from it. ` +
6528
+ `Use 'const value = ${calleeText}(...)' instead.`,
6529
+ }))
6530
+ // Already flagged for this shape; the argument-count check below
6531
+ // would be redundant noise on a declaration already rejected.
6532
+ continue
6533
+ }
6534
+ }
6535
+
6536
+ // BF116: extra call arguments. `createSignal`/`createMemo` accept at
6537
+ // most 1; an env-signal factory (`createSearchParams()`, which also
6538
+ // resolves to kind `'signal'`) takes none — its value comes from the
6539
+ // request env, so any argument is dropped just the same.
6540
+ const isEnvSignal = kind === 'signal' && resolveEnvSignalKey(callExpr, ctx) !== null
6541
+ const maxArgs = isEnvSignal ? 0 : 1
6542
+ if (callExpr.arguments.length > maxArgs) {
6543
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_EXTRA_ARGUMENTS, loc, {
6544
+ severity: 'error',
6545
+ message: isEnvSignal
6546
+ ? `'${calleeText}()' takes no arguments (its value is read from the request ` +
6547
+ `environment), but this call passes ${callExpr.arguments.length}. The ` +
6548
+ `argument(s) are silently dropped from the compiled client JS today; remove them.`
6549
+ : `'${calleeText}(...)' accepts at most 1 argument (${kind === 'signal' ? 'the initial value' : 'the compute function'}), ` +
6550
+ `but this call passes ${callExpr.arguments.length}. The extra argument(s) are ` +
6551
+ `silently dropped from the compiled client JS today; remove them, or fold ` +
6552
+ `whatever they configure into the ${kind === 'signal' ? 'initial value expression' : 'compute function body'}.`,
6553
+ }))
6554
+ }
6555
+ }
6556
+ }
6557
+ }
6558
+
6559
+ /**
6560
+ * BF115 / BF116 for an async reactive factory (`createQuery(fn, options?)`,
6561
+ * #3165): it returns `[value, action]` (a 1-element destructure keeps just
6562
+ * the value; `[, action]` keeps just the action) and takes the request
6563
+ * function plus an optional options object. `collectFactorySignal` only
6564
+ * reads those two arguments, so a third would be dropped from the client JS.
6565
+ */
6566
+ function checkAsyncFactoryArity(
6567
+ decl: ts.VariableDeclaration,
6568
+ callExpr: ts.CallExpression,
6569
+ calleeText: string,
6570
+ loc: SourceLocation,
6571
+ ctx: AnalyzerContext,
6572
+ ): void {
6573
+ if (ts.isArrayBindingPattern(decl.name)) {
6574
+ const elementCount = decl.name.elements.length
6575
+ if (elementCount < 1 || elementCount > 2) {
6576
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_ARITY_MISMATCH, loc, {
6577
+ severity: 'error',
6578
+ message:
6579
+ `'${calleeText}(...)' returns a 2-element tuple '[value, action]' — this destructure has ` +
6580
+ `${elementCount} elements. Use 'const [value, action] = ${calleeText}(...)', ` +
6581
+ `'const [value] = ${calleeText}(...)' or 'const [, action] = ${calleeText}(...)'.`,
6582
+ }))
6583
+ return
6584
+ }
6585
+ }
6586
+ if (callExpr.arguments.length > 2) {
6587
+ ctx.errors.push(createError(ErrorCodes.REACTIVE_FACTORY_EXTRA_ARGUMENTS, loc, {
6588
+ severity: 'error',
6589
+ message:
6590
+ `'${calleeText}(...)' accepts at most 2 arguments (the request function and the options), ` +
6591
+ `but this call passes ${callExpr.arguments.length}. The extra argument(s) are dropped from the ` +
6592
+ `compiled client JS; remove them.`,
6593
+ }))
6594
+ }
6595
+ }
6596
+
6597
+ /**
6598
+ * BF118 (#3210): an `initial` key in `createMutation`'s options. A mutation's
6599
+ * value is `undefined` until its action is called (spec/async.md §7.4), and
6600
+ * the runtime ignores the key, so an author who writes it expects a seed
6601
+ * that never happens. Only an object-literal `options` is read, the same
6602
+ * structural read `createQuery`'s `initial` goes through; any other shape
6603
+ * carries no key the compiler can see.
6604
+ */
6605
+ function checkMutationInitialOption(callExpr: ts.CallExpression, calleeText: string, ctx: AnalyzerContext): void {
6606
+ const initialNode = factoryInitialNode(callExpr.arguments[1])
6607
+ if (initialNode.kind !== 'expression') return
6608
+ ctx.errors.push(createError(ErrorCodes.MUTATION_INITIAL_OPTION, getSourceLocation(initialNode.node, ctx.sourceFile, ctx.filePath), {
6609
+ severity: 'error',
6610
+ message:
6611
+ `'${calleeText}(...)' takes no 'initial' option: a mutation's value is undefined until its action is ` +
6612
+ `called, so this value would never be used. Use 'createQuery' for a value that needs an initial state.`,
6613
+ }))
6614
+ }
6615
+
6067
6616
  /**
6068
6617
  * BF013 (#2771): a reactive primitive called through a namespace import
6069
6618
  * (`import * as bf from '@barefootjs/client'`, `bf.createSignal(...)`)