@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/errors.ts CHANGED
@@ -178,6 +178,27 @@ export const ErrorCodes = {
178
178
  REACTIVE_FACTORY_MODULE_CAPTURE: 'BF112',
179
179
  REACTIVE_FACTORY_IMPORT_COLLISION: 'BF113',
180
180
  REACTIVE_FACTORY_PARAM_SHADOWED: 'BF114',
181
+ // A tuple destructure of `createSignal`/`createMemo` whose element count
182
+ // the factory doesn't return (#3159). Before this code existed, an
183
+ // over-arity destructure (`const [a, b, c] = createSignal(...)`) silently
184
+ // dropped the WHOLE declaration from the compiled output — every
185
+ // reference then fell through to an unrelated same-name prop accessor if
186
+ // one happened to exist, or threw ReferenceError at hydrate if not.
187
+ REACTIVE_FACTORY_ARITY_MISMATCH: 'BF115',
188
+ // An authored `createSignal`/`createMemo` call with more arguments than
189
+ // the primitive accepts (#3159). Before this code existed, the extra
190
+ // argument(s) were silently dropped from the emitted client JS.
191
+ REACTIVE_FACTORY_EXTRA_ARGUMENTS: 'BF116',
192
+ // An async action's accessors (`action.isPending()` / `action.error()`, from
193
+ // `createQuery` or `createMutation`), or the action itself, read in a
194
+ // template-lowered position where their seed would not render like Hono
195
+ // (#3165; #3166 seeds the positions where it does). Refused on every
196
+ // adapter including Hono. See `async-action-refusal.ts`.
197
+ ASYNC_ACTION_READ_IN_TEMPLATE: 'BF117',
198
+ // An `initial` option passed to `createMutation` (#3210). A mutation has no
199
+ // initial request to seed from (spec/async.md §7.4): its value is
200
+ // `undefined` until the action is called, and the runtime ignores the key.
201
+ MUTATION_INITIAL_OPTION: 'BF118',
181
202
  } as const
182
203
 
183
204
  export type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]
@@ -301,6 +322,24 @@ const errorMessages: Record<ErrorCode, string> = {
301
322
 
302
323
  [ErrorCodes.REACTIVE_FACTORY_PARAM_SHADOWED]:
303
324
  'Reactive factory parameter is shadowed by a nested declaration inside the factory body, so argument substitution at the inline site would be ambiguous. Rename the inner binding so it does not collide with the parameter.',
325
+
326
+ [ErrorCodes.REACTIVE_FACTORY_ARITY_MISMATCH]:
327
+ "Tuple destructure of 'createSignal'/'createMemo' does not match the number of " +
328
+ 'elements the factory returns. `createSignal` returns `[getter, setter]` (destructure ' +
329
+ '1 or 2 elements); `createMemo` returns a single getter (do not destructure it as an ' +
330
+ 'array at all).',
331
+
332
+ [ErrorCodes.REACTIVE_FACTORY_EXTRA_ARGUMENTS]:
333
+ "'createSignal'/'createMemo' call passes more arguments than the primitive accepts " +
334
+ '(`createSignal(initialValue?)`, `createMemo(computeFn)`, `createSearchParams()`). The extra argument(s) are ' +
335
+ 'silently dropped from the compiled client JS.',
336
+
337
+ [ErrorCodes.ASYNC_ACTION_READ_IN_TEMPLATE]:
338
+ "An async action's accessors (`isPending()` / `error()`) cannot be read in this template position — " +
339
+ 'the request function never runs on the server, so there is no value to render.',
340
+ [ErrorCodes.MUTATION_INITIAL_OPTION]:
341
+ '`createMutation` takes no `initial` option — a mutation has no initial request to seed its value from. ' +
342
+ 'Use `createQuery` for a value that needs an initial state.',
304
343
  }
305
344
 
306
345
  // =============================================================================
@@ -25,12 +25,8 @@
25
25
  * METHOD CALL on a host-rich-typed receiver have a catalogued lowering) and
26
26
  * short-circuits when the component has no `propsType` — a `formatDate`
27
27
  * call needs no receiver type at all and can appear in a props-free
28
- * component, so it cannot share that early return. The tree coverage below
29
- * intentionally mirrors that module's `walkNode` / `walkAttrValue` /
30
- * `walkTemplateParts` (element/component/provider attrs, loop array +
31
- * children, conditional/if-statement branches, async fallback + children)
32
- * for the same reason both checks need it: "every position a template
33
- * could render" — for two unrelated predicates.
28
+ * component, so it cannot share that early return. The positions come from
29
+ * `walkTemplatePositions` (`template-position-walk.ts`), which BF117 shares.
34
30
  */
35
31
 
36
32
  import type {
@@ -38,12 +34,10 @@ import type {
38
34
  IRMetadata,
39
35
  CompilerError,
40
36
  SourceLocation,
41
- AttrValue,
42
- IRTemplatePart,
43
37
  } from './types.ts'
44
38
  import type { ParsedExpr } from './expression-parser.ts'
45
- import { parseExpression } from './expression-parser.ts'
46
39
  import { ErrorCodes } from './errors.ts'
40
+ import { walkTemplatePositions } from './template-position-walk.ts'
47
41
 
48
42
  /** Entries that re-export the pure client `formatDate` helper (#2324). */
49
43
  const FORMAT_DATE_SOURCES: ReadonlySet<string> = new Set([
@@ -74,7 +68,9 @@ export function checkAuthoredFormatDateCalls(root: IRNode, metadata: IRMetadata,
74
68
  const names = collectFormatDateBoundNames(metadata)
75
69
  if (names.size === 0) return
76
70
  const seen = new Set<string>()
77
- walkNode(root, names, errors, seen)
71
+ walkTemplatePositions(root, ({ expr, loc }) => {
72
+ if (exprCallsName(expr, names)) pushDiagnostic(errors, seen, loc, anyName(names))
73
+ })
78
74
  }
79
75
 
80
76
  function pushDiagnostic(errors: CompilerError[], seen: Set<string>, loc: SourceLocation, name: string): void {
@@ -149,118 +145,3 @@ function anyName(names: ReadonlySet<string>): string {
149
145
  for (const n of names) return n
150
146
  return 'formatDate'
151
147
  }
152
-
153
- /**
154
- * `IRTemplatePart.ternary.condition` / `.lookup.key` carry no attached
155
- * parse (unlike every other position here), so parse on demand — same as
156
- * `rich-type-refusal.ts`'s `walkTemplateParts`. `ternary.whenTrue` /
157
- * `.whenFalse` are ALSO raw, unparsed text (the per-branch rendered
158
- * snippet), so they get the same on-demand treatment: this is exactly the
159
- * `format-date-ternary` shape (#2843) — a call in a ternary CONSEQUENT
160
- * inside a structured template-literal attribute.
161
- */
162
- function walkTemplateParts(
163
- parts: readonly IRTemplatePart[],
164
- loc: SourceLocation,
165
- names: ReadonlySet<string>,
166
- errors: CompilerError[],
167
- seen: Set<string>,
168
- ): void {
169
- const checkText = (text: string) => {
170
- const trimmed = text.trim()
171
- if (!trimmed) return
172
- if (exprCallsName(parseExpression(trimmed), names)) pushDiagnostic(errors, seen, loc, anyName(names))
173
- }
174
- for (const part of parts) {
175
- if (part.type === 'ternary') {
176
- checkText(part.condition)
177
- checkText(part.whenTrue)
178
- checkText(part.whenFalse)
179
- } else if (part.type === 'lookup') {
180
- checkText(part.key)
181
- }
182
- }
183
- }
184
-
185
- function walkAttrValue(
186
- value: AttrValue,
187
- clientOnly: boolean | undefined,
188
- loc: SourceLocation,
189
- names: ReadonlySet<string>,
190
- errors: CompilerError[],
191
- seen: Set<string>,
192
- ): void {
193
- if (clientOnly) return
194
- if (value.kind === 'expression') {
195
- if (value.parsed && exprCallsName(value.parsed, names)) pushDiagnostic(errors, seen, loc, anyName(names))
196
- if (value.parts) walkTemplateParts(value.parts, loc, names, errors, seen)
197
- } else if (value.kind === 'spread') {
198
- if (value.parsed && exprCallsName(value.parsed, names)) pushDiagnostic(errors, seen, loc, anyName(names))
199
- } else if (value.kind === 'template') {
200
- walkTemplateParts(value.parts, loc, names, errors, seen)
201
- }
202
- }
203
-
204
- function walkNode(node: IRNode, names: ReadonlySet<string>, errors: CompilerError[], seen: Set<string>): void {
205
- if (node.type === 'expression') {
206
- if (!node.clientOnly && node.parsed && exprCallsName(node.parsed, names)) {
207
- pushDiagnostic(errors, seen, node.loc, anyName(names))
208
- }
209
- } else if (node.type === 'conditional') {
210
- if (!node.clientOnly && node.parsedCondition && exprCallsName(node.parsedCondition, names)) {
211
- pushDiagnostic(errors, seen, node.loc, anyName(names))
212
- }
213
- } else if (node.type === 'if-statement') {
214
- if (node.parsedCondition && exprCallsName(node.parsedCondition, names)) {
215
- pushDiagnostic(errors, seen, node.loc, anyName(names))
216
- }
217
- }
218
-
219
- if (node.type === 'element') {
220
- for (const attr of node.attrs) walkAttrValue(attr.value, attr.clientOnly, attr.loc, names, errors, seen)
221
- } else if (node.type === 'component') {
222
- for (const prop of node.props) walkAttrValue(prop.value, prop.clientOnly, prop.loc, names, errors, seen)
223
- } else if (node.type === 'provider') {
224
- walkAttrValue(node.valueProp.value, node.valueProp.clientOnly, node.valueProp.loc, names, errors, seen)
225
- }
226
-
227
- switch (node.type) {
228
- case 'element':
229
- case 'component':
230
- case 'fragment':
231
- case 'provider':
232
- for (const child of node.children) walkNode(child, names, errors, seen)
233
- break
234
- case 'async':
235
- walkNode(node.fallback, names, errors, seen)
236
- for (const child of node.children) walkNode(child, names, errors, seen)
237
- break
238
- case 'loop': {
239
- if (node.clientOnly) break
240
- if (node.arrayParsed && exprCallsName(node.arrayParsed, names)) pushDiagnostic(errors, seen, node.loc, anyName(names))
241
- for (const child of node.children) walkNode(child, names, errors, seen)
242
- if (node.childComponent) {
243
- for (const child of node.childComponent.children) walkNode(child, names, errors, seen)
244
- }
245
- for (const nested of node.nestedComponents ?? []) {
246
- for (const child of nested.children) walkNode(child, names, errors, seen)
247
- }
248
- for (const seg of node.flatMapCallback?.segments ?? []) {
249
- if (seg.kind === 'jsx') walkNode(seg.ir, names, errors, seen)
250
- }
251
- for (const seg of node.preamble?.segments ?? []) {
252
- if (seg.kind === 'jsx') walkNode(seg.ir, names, errors, seen)
253
- }
254
- break
255
- }
256
- case 'conditional':
257
- if (node.clientOnly) break
258
- walkNode(node.whenTrue, names, errors, seen)
259
- walkNode(node.whenFalse, names, errors, seen)
260
- break
261
- case 'if-statement':
262
- walkNode(node.consequent, names, errors, seen)
263
- if (node.alternate) walkNode(node.alternate, names, errors, seen)
264
- break
265
- }
266
- }
package/src/html-types.ts CHANGED
@@ -93,6 +93,16 @@ export interface HTMLBaseAttributes extends BaseEventAttributes {
93
93
  lang?: string
94
94
  slot?: string
95
95
 
96
+ // Popover API (global attribute — any element can opt into being a popover).
97
+ // No `boolean` arm: `popover` isn't in BOOLEAN_ATTRS (`@barefootjs/shared`'s
98
+ // `dom-prop.ts`), so a boolean value stringifies instead of toggling the
99
+ // attribute's presence. `popover={false}` would render `popover="false"` —
100
+ // an invalid keyword the spec maps to `manual`, so the element is STILL a
101
+ // popover, not opted out — and the client runtime's `applyRestAttrs`
102
+ // disagrees by removing the attribute outright on `false`, an SSR/CSR
103
+ // mismatch. `popover={true}` renders `"true"`, also `manual`, not `auto`.
104
+ popover?: '' | 'auto' | 'manual' | 'hint'
105
+
96
106
  // Data attributes
97
107
  [key: `data-${string}`]: string | number | boolean | undefined
98
108
 
@@ -323,6 +333,8 @@ export interface ButtonHTMLAttributes extends Omit<HTMLBaseAttributes,
323
333
  name?: string
324
334
  type?: 'submit' | 'reset' | 'button'
325
335
  value?: string
336
+ popovertarget?: string
337
+ popovertargetaction?: 'toggle' | 'show' | 'hide'
326
338
 
327
339
  onClick?: MouseEventHandler<HTMLButtonElement>
328
340
  onBlur?: FocusEventHandler<HTMLButtonElement>
@@ -363,6 +375,8 @@ export interface InputHTMLAttributes extends Omit<HTMLBaseAttributes,
363
375
  name?: string
364
376
  pattern?: string
365
377
  placeholder?: string
378
+ popovertarget?: string
379
+ popovertargetaction?: 'toggle' | 'show' | 'hide'
366
380
  readonly?: boolean | null
367
381
  required?: boolean | null
368
382
  size?: number
package/src/index.ts CHANGED
@@ -87,9 +87,10 @@ export type {
87
87
  RenderDivergences,
88
88
  ImportInfo,
89
89
  } from './types.ts'
90
+ export { isElidedFactoryGetter } from './types.ts'
90
91
 
91
92
  // Analyzer
92
- export { analyzeComponent, listComponentFunctions, listComponentFunctions as listExportedComponents, scanComponentFile, createProgramForFile, needsTypeBasedDetection, resolveRelativeImportToFile, REACTIVE_PRIMITIVES, BROWSER_ONLY_CLIENT_APIS, type AnalyzerContext, type ComponentFileScan } from './analyzer.ts'
93
+ export { analyzeComponent, listComponentFunctions, listComponentFunctions as listExportedComponents, scanComponentFile, createProgramForFile, createAnchoredProgram, needsTypeBasedDetection, resolveRelativeImportToFile, REACTIVE_PRIMITIVES, BROWSER_ONLY_CLIENT_APIS, type AnalyzerContext, type ComponentFileScan } from './analyzer.ts'
93
94
  export { createProgramForCorpus, type SharedProgramOptions } from './shared-program.ts'
94
95
 
95
96
  // JSX to IR transformer
@@ -256,6 +257,7 @@ export {
256
257
  buildLoopSummary,
257
258
  buildWhyUpdate,
258
259
  traceUpdatePath,
260
+ traceableNames,
259
261
  formatComponentGraph,
260
262
  formatUpdatePath,
261
263
  formatEventSummary,
@@ -41,6 +41,7 @@ import { attrValueToString } from './utils.ts'
41
41
  import type { ClientJsContext } from './types.ts'
42
42
  import { extractIdentifiers, extractTemplateIdentifiers } from './identifiers.ts'
43
43
  import { walkIR } from './walker.ts'
44
+ import { signalSecondBinding } from '../signal-initializer.ts'
44
45
 
45
46
  // All non-declaration edge origins share a single null source — no
46
47
  // query on the graph distinguishes them on read today. Stage E
@@ -59,7 +60,8 @@ export function buildReferencesGraph(ctx: ClientJsContext, irRoot: IRNode): Refe
59
60
  for (const f of ctx.localFunctions) declaredNames.add(f.name)
60
61
  for (const s of ctx.signals) {
61
62
  declaredNames.add(s.getter)
62
- if (s.setter) declaredNames.add(s.setter)
63
+ const second = signalSecondBinding(s)
64
+ if (second) declaredNames.add(second)
63
65
  }
64
66
  for (const m of ctx.memos) declaredNames.add(m.name)
65
67
  for (const p of ctx.propsParams) {
@@ -189,7 +191,9 @@ export function buildReferencesGraph(ctx: ClientJsContext, irRoot: IRNode): Refe
189
191
 
190
192
  // identifiers.ts L137-139
191
193
  for (const signal of ctx.signals) {
192
- addExprEdges({ kind: 'signal', name: signal.getter }, signal.initialValue, 'init-body')
194
+ // An async factory's declaration is its whole call (`createQuery(fn,
195
+ // options)`, #3165): the request function's reads are dependencies too.
196
+ addExprEdges({ kind: 'signal', name: signal.getter }, signal.factory?.argsText ?? signal.initialValue, 'init-body')
193
197
  }
194
198
 
195
199
  // identifiers.ts L141-143
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { type IRNode, type IRElement, type IRComponent, type IRConditional, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
6
6
  import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
7
- import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, type LoopParamSpec } from './utils.ts'
7
+ import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, type LoopParamSpec } from './utils.ts'
8
8
  import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectConditionalBranchComponentNodes, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
9
9
  import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
10
10
  import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
@@ -196,8 +196,14 @@ export function computeLoopSiblingOffsets(root: IRNode): Map<IRLoop, IRNode[]> {
196
196
  * undecidable fall back to `legacyElementCount` (the pre-#1693 behaviour).
197
197
  * Returns `undefined` when nothing precedes the loop (or only non-element
198
198
  * nodes do), so the loop keeps bare `children[idx]`.
199
+ *
200
+ * Exported for `collectLoopChildEventsWithNesting` (`reactivity.ts`), which
201
+ * builds its own `NestedLoop` chain for delegated-event metadata and needs
202
+ * the same static-sibling-count resolution the hydration side
203
+ * (`collectInnerLoops`, below) already applies — see that call site's
204
+ * comment (#3240 follow-up).
199
205
  */
200
- function resolveLoopOffset(preceding: IRNode[] | undefined): LoopOffset | undefined {
206
+ export function resolveLoopOffset(preceding: IRNode[] | undefined): LoopOffset | undefined {
201
207
  if (!preceding || preceding.length === 0) return undefined
202
208
  let staticCount = 0
203
209
  const dynamicTerms: string[] = []
@@ -411,7 +417,7 @@ export function collectInnerLoops(
411
417
  }
412
418
 
413
419
  for (const child of n.children) {
414
- bindings.events.push(...collectLoopChildEventsWithNesting(child))
420
+ bindings.events.push(...collectLoopChildEventsWithNesting(child, [], siblingOffsets))
415
421
  }
416
422
  }
417
423
 
@@ -1077,6 +1083,7 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1077
1083
  ctx.refElements.push({
1078
1084
  slotId: element.slotId,
1079
1085
  callback: element.ref,
1086
+ ...(element.ssrPortalOwnerScope && { ssrPortalOwner: true }),
1080
1087
  })
1081
1088
  }
1082
1089
 
@@ -1131,6 +1138,60 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1131
1138
  const valueStr = attrValueToString(attr.value)
1132
1139
  if (!valueStr) continue
1133
1140
 
1141
+ // #3057: a statically expanded rest-key attribute (`{...rest}` onto
1142
+ // this element, unrolled per-key by `expandSpreadAttribute` because
1143
+ // the rest type is closed) reads the destructured rest OBJECT
1144
+ // (`rest.tag`) — a snapshot taken once when the component
1145
+ // initializes, never a live prop read. The string-level heuristics
1146
+ // below (`needsEffectWrapper`/`decideWrapForAttr`) don't recognize
1147
+ // `rest`/the expanded key as a tracked prop name, so this would
1148
+ // otherwise be classified static and never get a `createEffect` —
1149
+ // exactly the bug this issue reports. Bind it straight to a live
1150
+ // `_p.<key>` read instead, unconditionally: forwarding a prop via
1151
+ // `{...rest}` means it tracks the caller's current value by
1152
+ // definition, so it can never be "static" the way an ordinary
1153
+ // attribute expression can. `insideConditional` below just skips
1154
+ // this element the same way the generic path does (#1071) — unlike
1155
+ // the generic path, `collectBranchReactiveAttrs` does not read
1156
+ // `restExpandedKey`, so a rest key inside a conditional branch gets
1157
+ // no binding at all; that gap is intentionally out of scope for
1158
+ // #3057 (see the PR description). Two cases
1159
+ // fall back to the pre-#3057 classification below instead of this
1160
+ // fast path (both found by review on #3252):
1161
+ // - `attr.name` is an explicit JSX attribute's HTML name too
1162
+ // (e.g. a closed `id` rest key alongside a literal `id="fixed"`
1163
+ // on the same element). An unconditional `_p.id` write would
1164
+ // `removeAttribute` the SSR value whenever the caller doesn't
1165
+ // pass `id`, clobbering the explicit attribute.
1166
+ // - `classifyDOMProp` says this key doesn't reach the DOM as a
1167
+ // plain attribute at all (`ref` / `event` / `skip`, e.g.
1168
+ // `onPing` or `children`). `applyRestAttrs` already excludes
1169
+ // these from its own attribute set for the same reason; an
1170
+ // unconditional `setAttribute` here would stringify a function
1171
+ // or children value onto the element, which the pre-#3057
1172
+ // path never did.
1173
+ const restKeyHtmlName = toHtmlAttrName(attr.name)
1174
+ const collidesWithExplicitAttr = element.attrs.some(
1175
+ other => other !== attr && other.name !== '...' && toHtmlAttrName(other.name) === restKeyHtmlName,
1176
+ )
1177
+ const restKeyDomKind = classifyDOMProp(attr.name).kind
1178
+ if (
1179
+ attr.restExpandedKey &&
1180
+ !collidesWithExplicitAttr &&
1181
+ restKeyDomKind !== 'ref' &&
1182
+ restKeyDomKind !== 'event' &&
1183
+ restKeyDomKind !== 'skip'
1184
+ ) {
1185
+ if (insideConditional) continue
1186
+ ctx.reactiveAttrs.push({
1187
+ slotId: element.slotId,
1188
+ attrName: attr.name,
1189
+ expression: `${PROPS_PARAM}.${attr.name}`,
1190
+ ...pickAttrMetaFromIR(attr),
1191
+ })
1192
+ continue
1193
+ }
1194
+
1134
1195
  // Expand local constant references to detect transitive prop dependencies.
1135
1196
  // e.g., `classes` → `` `${baseClasses} ${variantClasses[variant]} ${className}` ``
1136
1197
  const expandedResult = expandConstantForReactivity(valueStr, ctx, attr.freeIdentifiers)
@@ -1543,7 +1604,7 @@ export function collectLoopChildBindings(
1543
1604
  ): LoopChildBindings {
1544
1605
  const bindings = emptyLoopChildBindings()
1545
1606
  for (const child of children) {
1546
- bindings.events.push(...collectLoopChildEventsWithNesting(child))
1607
+ bindings.events.push(...collectLoopChildEventsWithNesting(child, [], siblingOffsets))
1547
1608
  // stopAtReactiveConditionals=true (#2347): this function always also
1548
1609
  // collects nested reactive conditionals below via
1549
1610
  // `collectLoopChildConditionals`, which gives each its own insert() +
@@ -33,6 +33,7 @@ import { createError, ErrorCodes } from '../errors.ts'
33
33
  import { attrValueToString } from './utils.ts'
34
34
  import { walkIR, type IRVisitor } from './walker.ts'
35
35
  import { buildSignalMemoEnv, csrSubstitute, resolveGetterAliases, type CsrEnv, type CsrSubstitution } from './csr-substitute.ts'
36
+ import { signalSecondBinding } from '../signal-initializer.ts'
36
37
 
37
38
  /**
38
39
  * Build a `RelocateEnv` from a live `ClientJsContext`. The IR-keyed env
@@ -266,7 +267,7 @@ export function computeInlinability(
266
267
 
267
268
  // --- Constants (initial classification) ---
268
269
  const signalGetters = new Set(ctx.signals.map(s => s.getter))
269
- const signalSetters = new Set(ctx.signals.filter(s => s.setter).map(s => s.setter!))
270
+ const signalSetters = new Set(ctx.signals.flatMap(s => signalSecondBinding(s) ?? []))
270
271
  const memoNames = new Set(ctx.memos.map(m => m.name))
271
272
  // A bare alias-hop chain that ultimately names a signal/memo getter
272
273
  // (`const items__alias = items`, #2778) is `reactive-read` the same as
@@ -21,6 +21,7 @@ import {
21
21
  graphFunctionReferences,
22
22
  graphUsedIdentifiers,
23
23
  } from './build-references.ts'
24
+ import { signalSecondBinding } from '../signal-initializer.ts'
24
25
 
25
26
  export interface DeclarationScopes {
26
27
  constantScope: Map<string, DeclarationScope>
@@ -104,7 +105,8 @@ export function computeDeclarationScopes(
104
105
  const initRequired = new Set<string>()
105
106
  for (const s of ctx.signals) {
106
107
  initRequired.add(s.getter)
107
- if (s.setter) initRequired.add(s.setter)
108
+ const second = signalSecondBinding(s)
109
+ if (second) initRequired.add(second)
108
110
  }
109
111
  for (const m of ctx.memos) initRequired.add(m.name)
110
112
  for (const p of ctx.propsParams) initRequired.add(p.name)
@@ -79,6 +79,7 @@ function buildArmBody(branch: BranchSummary, options: BuildInsertOptions): ArmBo
79
79
  refs: branch.refs.map(r => ({
80
80
  slotId: r.slotId,
81
81
  callback: r.callback,
82
+ ...(r.ssrPortalOwner && { ssrPortalOwner: true }),
82
83
  })),
83
84
  childComponents: branch.childComponents.map(c => ({
84
85
  name: c.name,
@@ -92,6 +92,8 @@ export interface ArmEventBind {
92
92
  export interface ArmRefBind {
93
93
  slotId: string
94
94
  callback: string
95
+ /** The element's `IRElement.ssrPortalOwnerScope` — see `emitRefCall`. */
96
+ ssrPortalOwner?: boolean
95
97
  }
96
98
 
97
99
  export interface ArmChildComponentInit {
@@ -324,9 +324,118 @@ function emitStaticIndexLookup(
324
324
  // Preamble and idx binding run INSIDE the item null guard (BUG-4) — an
325
325
  // out-of-range index (stale-DOM race) must short-circuit first.
326
326
  ls.push(` if (${param}) {`)
327
- if (preambleLine) ls.push(` ${preambleLine}`)
328
- if (idxLine) ls.push(` ${idxLine}`)
329
- ls.push(` ;${handlerCall}`)
327
+ // Nested static `.map()` params (#3240): static arrays carry no
328
+ // data-key markers, so — unlike `emitKeyedLookup`'s nested branch, which
329
+ // resolves each level via `closest('[data-key-N]')` — each nested level's
330
+ // item is recovered positionally, the same way hydration wires up a
331
+ // nested static loop's own bindings (`stringify/static-array-child-init.ts`'s
332
+ // `__ic`/`indexOf` shape, #2798): scope a `containerSlotId` lookup inside
333
+ // the previously-resolved row, walk the ORIGINAL event target up to that
334
+ // container's direct child, and read its position. The positional lookups
335
+ // run inside this guard (not above) because a nested `array` expression
336
+ // may read the outer `param` (e.g. `CHOICES[group]`), which must exist
337
+ // first; the params themselves are declared just below, once every
338
+ // level's index has resolved (see `emitNestedIndexParams`'s docstring on
339
+ // why the guard is on the indices, not the params).
340
+ const { guardNames: nestedGuardNames, paramLines: nestedParamLines } = emitNestedIndexParams(ls, ev, '__el', ' ')
341
+ const guarded = nestedGuardNames.length > 0
342
+ if (guarded) ls.push(` if (${nestedGuardNames.join(' && ')}) {`)
343
+ const bodyIndent = guarded ? ' ' : ' '
344
+ for (const line of nestedParamLines) ls.push(`${bodyIndent}${line}`)
345
+ if (preambleLine) ls.push(`${bodyIndent}${preambleLine}`)
346
+ if (idxLine) ls.push(`${bodyIndent}${idxLine}`)
347
+ ls.push(`${bodyIndent};${handlerCall}`)
348
+ if (guarded) ls.push(` }`)
330
349
  ls.push(` }`)
331
350
  ls.push(` }`)
332
351
  }
352
+
353
+ /**
354
+ * Resolve each nested (inner) `.map()`'s item for an index-based item lookup
355
+ * (#3240). `ev.nestedLoops` is ordered outermost-first (depth 1, 2, …); each
356
+ * entry's `containerSlotId` (the slot id of the element enclosing that
357
+ * level's loop, or `null` when the loop's items are direct children of the
358
+ * previous level's row) is looked up scoped to the previously-resolved row
359
+ * element — never document-wide — so a same-id container in a sibling row
360
+ * never collides. `baseScopeVar` is the already-resolved OUTERMOST row
361
+ * element (`__el`, `static-index`'s own resolved row); the walk-up at every
362
+ * level still starts from the actual event-target slot element
363
+ * (`<childSlotId>El`), since that is the only DOM reference this dispatcher
364
+ * holds — walking it up to become a direct child of each level's container
365
+ * recovers that level's row regardless of how many levels are nested
366
+ * beneath it.
367
+ *
368
+ * Emits the positional index resolution (`__icN`/`__irN`/`__iidxN`) for
369
+ * every level up front, and returns it split into two pieces the caller
370
+ * assembles around the rest of the handler body:
371
+ *
372
+ * - `guardNames`: one `<idxVar> >= 0` condition per level, meant to be
373
+ * `&&`-joined into the guard that wraps the param declarations and the
374
+ * handler call.
375
+ * - `paramLines`: one `const <nested.param> = <array>[<idxVar>]` per
376
+ * level, in depth order, meant to be pushed INSIDE that guard.
377
+ *
378
+ * The guard checks the resolved INDEX, not the item's truthiness — unlike
379
+ * an earlier version of this function, which declared `const <param> =
380
+ * <idx> >= 0 ? <array>[<idx>] : undefined` and left the caller to guard on
381
+ * `<param>` directly. That silently dropped a click on a falsy item
382
+ * (`NUMS = [0, 1, 2]`, clicking `0`) since `if (0)` is false, and threw a
383
+ * `TypeError` for a destructured `nested.param` (`({ id, label }) => ...`
384
+ * destructuring `undefined` on a miss) since `if ({ id, label })` is always
385
+ * true regardless of whether the lookup actually resolved. Guarding on the
386
+ * index and declaring the (possibly-destructured) param only once every
387
+ * level's index is known to be `>= 0` fixes both: a `0` item still passes
388
+ * `__iidxN >= 0`, and a destructured param is never handed `undefined`.
389
+ *
390
+ * Declaring the params in depth order (rather than each next to its own
391
+ * index computation) still lets a nested `array` expression read an outer
392
+ * level's param (e.g. `CHOICES[group]`) — the container/row/index
393
+ * computations for every level never depend on any level's param, only on
394
+ * DOM structure, so they can all run first regardless of param order; only
395
+ * the actual item lookups (`paramLines`) need the depth ordering, and the
396
+ * caller pushes them in the order this function returns them.
397
+ *
398
+ * Returns `{ guardNames: [], paramLines: [] }` (emitting nothing) when
399
+ * `ev.nestedLoops` is empty, so a non-nested event's emitted lines are
400
+ * unchanged.
401
+ *
402
+ * Only `emitStaticIndexLookup` calls this today. `emitDynamicIndexLookup`
403
+ * (the other unkeyed item-lookup shape) never sees a non-empty
404
+ * `ev.nestedLoops`: a dynamic (non-static-array) loop with a nested `.map()`
405
+ * always sets `useElementReconciliation`
406
+ * (`collect-elements.ts`'s `decideLoopRendering`), which routes it to the
407
+ * composite/element-reconciliation emission path — a direct
408
+ * `addEventListener` on each row at creation, not this delegated dispatcher
409
+ * — regardless of whether the outer loop has a key (verified by compiling
410
+ * both a keyed and an unkeyed reactive outer array with a nested static
411
+ * `.map()`: both emit `mapArray` + a direct per-row listener, never
412
+ * `static-index`/`dynamic-index`/`keyed` delegation for the inner event).
413
+ */
414
+ function emitNestedIndexParams(
415
+ ls: string[],
416
+ ev: LoopChildEvent,
417
+ baseScopeVar: string,
418
+ indent: string,
419
+ ): { guardNames: string[]; paramLines: string[] } {
420
+ const evVar = varSlotId(ev.childSlotId)
421
+ const guardNames: string[] = []
422
+ const paramLines: string[] = []
423
+ let scopeVar = baseScopeVar
424
+ for (const nested of ev.nestedLoops) {
425
+ const containerVarName = `__ic${nested.depth}`
426
+ const rowVarName = `__ir${nested.depth}`
427
+ const idxVarName = `__iidx${nested.depth}`
428
+ const containerExpr = nested.containerSlotId
429
+ ? `${scopeVar}.querySelector('[bf="${nested.containerSlotId}"]') || ${scopeVar}`
430
+ : scopeVar
431
+ ls.push(`${indent}const ${containerVarName} = ${containerExpr}`)
432
+ ls.push(`${indent}let ${rowVarName} = ${evVar}El`)
433
+ ls.push(`${indent}while (${rowVarName}.parentElement && ${rowVarName}.parentElement !== ${containerVarName}) ${rowVarName} = ${rowVarName}.parentElement`)
434
+ const offsetSuffix = buildLoopChildIndexSubtraction(nested.offset)
435
+ ls.push(`${indent}const ${idxVarName} = ${rowVarName}.parentElement === ${containerVarName} ? Array.from(${containerVarName}.children).indexOf(${rowVarName})${offsetSuffix} : -1`)
436
+ guardNames.push(`${idxVarName} >= 0`)
437
+ paramLines.push(`const ${nested.param} = ${nested.array}[${idxVarName}]`)
438
+ scopeVar = rowVarName
439
+ }
440
+ return { guardNames, paramLines }
441
+ }
@@ -124,7 +124,7 @@ function emitArmBody(
124
124
 
125
125
  for (const ref of body.refs) {
126
126
  const v = varSlotId(ref.slotId)
127
- lines.push(`${indent}if (_${v}) ${emitRefCall(ref.callback, `_${v}`)}`)
127
+ lines.push(`${indent}if (_${v}) ${emitRefCall(ref.callback, `_${v}`, ref.ssrPortalOwner)}`)
128
128
  }
129
129
 
130
130
  // 3. Child component initializations from the branch swap.
@@ -31,6 +31,7 @@ import { extractFreeIdentifiersFromNode } from '../analyzer.ts'
31
31
  import type { ConstantInfo, MemoInfo, SignalInfo } from '../types.ts'
32
32
  import type { BindingScope } from '../scope/binding-scope.ts'
33
33
  import { resolveAliasOrigin } from '../props-binding.ts'
34
+ import { signalSecondBinding } from '../signal-initializer.ts'
34
35
 
35
36
  /**
36
37
  * CSR-substituted const value: the const's initializer with every
@@ -600,8 +601,12 @@ export function buildSignalMemoEnv(
600
601
  // that shim directly, with no thunk-wrapping needed. `s.setter` is
601
602
  // null for the setter-elided declaration form (`const [count] =
602
603
  // createSignal(...)`), which has no name to register.
603
- if (s.setter) {
604
- substitutions.set(s.setter, { kind: 'identifier', replacement: '() => {}', freeIdentifiers: new Set() })
604
+ // An async factory's action (#3165) gets the same no-op: forwarding it as
605
+ // a value (`<Retry run={fetchItems} />`) is allowed, and every read of
606
+ // its accessors in a template position is refused before emit (BF117).
607
+ const second = signalSecondBinding(s)
608
+ if (second) {
609
+ substitutions.set(second, { kind: 'identifier', replacement: '() => {}', freeIdentifiers: new Set() })
605
610
  }
606
611
  }
607
612
  for (const m of memos) {
@@ -639,7 +644,10 @@ function normalizeSignalInitial(signal: SignalInfo, propsObjectName: string | nu
639
644
  const initialValue = signal.initialValue
640
645
  const propsName = propsObjectName ?? 'props'
641
646
  const propsPrefix = `${propsName}.`
642
- if (initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
647
+ // An async factory's `initial` (#3165) renders exactly as given: an absent
648
+ // prop means no obtained result, so the value is `undefined` on the server
649
+ // too, never a type default.
650
+ if (!signal.factory && initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
643
651
  return `${initialValue} ?? ${inferDefaultValue(signal.type)}`
644
652
  }
645
653
  // Destructured mode (#2265): `templateInitialValue` (when present) has