@barefootjs/jsx 0.41.1 → 0.41.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -0
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts.map +1 -1
  4. package/dist/adapters/computed-const.d.ts +19 -0
  5. package/dist/adapters/computed-const.d.ts.map +1 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts +2 -1
  7. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  8. package/dist/adapters/inherited-const-server-read.d.ts +37 -0
  9. package/dist/adapters/inherited-const-server-read.d.ts.map +1 -0
  10. package/dist/adapters/loop-row-type.d.ts +18 -0
  11. package/dist/adapters/loop-row-type.d.ts.map +1 -1
  12. package/dist/adapters/non-primitive-equality.d.ts +8 -2
  13. package/dist/adapters/non-primitive-equality.d.ts.map +1 -1
  14. package/dist/adapters/unapplied-prop-default.d.ts +34 -0
  15. package/dist/adapters/unapplied-prop-default.d.ts.map +1 -0
  16. package/dist/adapters/uninlinable-seed-call.d.ts +29 -0
  17. package/dist/adapters/uninlinable-seed-call.d.ts.map +1 -0
  18. package/dist/analyzer.d.ts.map +1 -1
  19. package/dist/augment-inherited-props.d.ts +4 -22
  20. package/dist/augment-inherited-props.d.ts.map +1 -1
  21. package/dist/caller-value-reach.d.ts +57 -0
  22. package/dist/caller-value-reach.d.ts.map +1 -0
  23. package/dist/const-identity.d.ts +38 -0
  24. package/dist/const-identity.d.ts.map +1 -0
  25. package/dist/index.d.ts +10 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +2685 -1381
  28. package/dist/ir-to-client-js/child-props-object.d.ts +39 -41
  29. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/component-scope.d.ts +13 -2
  32. package/dist/ir-to-client-js/component-scope.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  37. package/dist/jsx-to-ir.d.ts.map +1 -1
  38. package/dist/local-call-body.d.ts +112 -0
  39. package/dist/local-call-body.d.ts.map +1 -0
  40. package/dist/nullable-signal-attr.d.ts +10 -0
  41. package/dist/nullable-signal-attr.d.ts.map +1 -1
  42. package/dist/prop-default-resolution.d.ts +52 -0
  43. package/dist/prop-default-resolution.d.ts.map +1 -0
  44. package/dist/props-binding.d.ts +15 -0
  45. package/dist/props-binding.d.ts.map +1 -1
  46. package/dist/server-read-walk.d.ts +66 -0
  47. package/dist/server-read-walk.d.ts.map +1 -0
  48. package/dist/ssr-defaults.d.ts.map +1 -1
  49. package/dist/ssr-seed-plan.d.ts +24 -1
  50. package/dist/ssr-seed-plan.d.ts.map +1 -1
  51. package/dist/static-const-member.d.ts +92 -0
  52. package/dist/static-const-member.d.ts.map +1 -0
  53. package/dist/static-literal.d.ts +21 -1
  54. package/dist/static-literal.d.ts.map +1 -1
  55. package/dist/types.d.ts +63 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/computed-const.test.ts +7 -1
  59. package/src/__tests__/const-identity-child-prop.test.ts +127 -0
  60. package/src/__tests__/inherited-const-server-read.test.ts +116 -0
  61. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +8 -3
  62. package/src/__tests__/issue-3714-open-rest-spread-child.test.ts +188 -0
  63. package/src/__tests__/local-call-body.test.ts +101 -0
  64. package/src/__tests__/loop-branch-bare-expression-reactive-text.test.ts +212 -56
  65. package/src/__tests__/nested-loop-conditional.test.ts +16 -16
  66. package/src/__tests__/prop-default-resolution.test.ts +185 -0
  67. package/src/__tests__/props-spread-shadowed.test.ts +113 -0
  68. package/src/__tests__/server-read-walk.test.ts +125 -0
  69. package/src/__tests__/ssr-defaults.test.ts +67 -7
  70. package/src/__tests__/static-literal.test.ts +47 -2
  71. package/src/__tests__/static-record-literal-array.test.ts +82 -11
  72. package/src/adapters/attr-plan.ts +12 -1
  73. package/src/adapters/component-props.ts +2 -1
  74. package/src/adapters/computed-const.ts +108 -12
  75. package/src/adapters/dsl-template-adapter.ts +17 -4
  76. package/src/adapters/inherited-const-server-read.ts +174 -0
  77. package/src/adapters/loop-row-type.ts +69 -2
  78. package/src/adapters/non-primitive-equality.ts +17 -2
  79. package/src/adapters/unapplied-prop-default.ts +83 -0
  80. package/src/adapters/uninlinable-seed-call.ts +62 -0
  81. package/src/analyzer.ts +43 -3
  82. package/src/augment-inherited-props.ts +4 -49
  83. package/src/caller-value-reach.ts +436 -0
  84. package/src/compiler.ts +4 -4
  85. package/src/const-identity.ts +189 -0
  86. package/src/index.ts +10 -5
  87. package/src/ir-to-client-js/child-props-object.ts +94 -62
  88. package/src/ir-to-client-js/collect-elements.ts +53 -68
  89. package/src/ir-to-client-js/component-scope.ts +16 -2
  90. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +1 -0
  91. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +1 -0
  92. package/src/ir-to-client-js/html-template.ts +24 -4
  93. package/src/ir-to-client-js/index.ts +2 -2
  94. package/src/ir-to-client-js/prop-handling.ts +4 -0
  95. package/src/jsx-to-ir.ts +40 -2
  96. package/src/local-call-body.ts +191 -0
  97. package/src/nullable-signal-attr.ts +39 -17
  98. package/src/prop-default-resolution.ts +195 -0
  99. package/src/props-binding.ts +16 -0
  100. package/src/server-read-walk.ts +174 -0
  101. package/src/ssr-defaults.ts +93 -10
  102. package/src/ssr-seed-plan.ts +104 -18
  103. package/src/static-const-member.ts +243 -0
  104. package/src/static-literal.ts +55 -1
  105. package/src/types.ts +63 -1
@@ -96,7 +96,7 @@ export function generateClientJsWithSourceMap(
96
96
  // harness (`csr-render.ts`) and `analyzeClientNeeds` both do. Cleared
97
97
  // in `finally` so a thrown error never leaks the alias map into an
98
98
  // unrelated later compile.
99
- setActiveImportAliases(buildImportAliasMap(ir.metadata.imports))
99
+ const outerAliases = setActiveImportAliases(buildImportAliasMap(ir.metadata.imports))
100
100
  try {
101
101
  const ctx = createContext(ir, scope, adapterCapabilities, profile)
102
102
  const siblingOffsets = computeLoopSiblingOffsets(ir.root)
@@ -125,7 +125,7 @@ export function generateClientJsWithSourceMap(
125
125
 
126
126
  return { code }
127
127
  } finally {
128
- setActiveImportAliases(null)
128
+ setActiveImportAliases(outerAliases)
129
129
  }
130
130
  }
131
131
 
@@ -118,6 +118,10 @@ export function expandDynamicPropValue(value: string, ctx: ClientJsContext, scop
118
118
  // Re-embedding it here would silently drop the mutation; keep the bare
119
119
  // reference instead so the emitted getter reads the LIVE binding.
120
120
  if (constant?.mutatedAfterDeclaration) return value
121
+ // An initializer that allocates and reads nothing reactive (#3868) would
122
+ // hand every prop read a new object; the getter returns the one value the
123
+ // declaration created instead (init declares the binding).
124
+ if (constant?.identityBound) return value
121
125
  if (constant && constant.value && !initializerCapturedBy(constant, scope)) {
122
126
  return constant.value
123
127
  }
package/src/jsx-to-ir.ts CHANGED
@@ -59,7 +59,7 @@ import {
59
59
  collectAstPropRefs,
60
60
  rewriteScopedValueRefs,
61
61
  } from './prop-rewrite.ts'
62
- import { boundPropLocalNames, buildPropAliasMap, templatePropReadParams, resolveAliasOrigin, resolveRestSpreadOriginCore, livePropReadExpr } from './props-binding.ts'
62
+ import { boundPropLocalNames, buildPropAliasMap, templatePropReadParams, resolveAliasOrigin, resolveRestSpreadOriginCore, restBagOmittedKeys, livePropReadExpr } from './props-binding.ts'
63
63
  import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
64
64
  import { walkIR } from './ir-to-client-js/walker.ts'
65
65
  import { resolveFreeRefs, rebindHelperParamRefs, isNameBound as isNameBoundInEnv, type BindingEnvironment } from './free-refs.ts'
@@ -75,6 +75,7 @@ import { reconstructAsSegments, reconstructWithoutTypes } from './strip-types.ts
75
75
  import { templatePartsToJsExpr } from './template-parts.ts'
76
76
  import { toHTMLAttrName, decodeEntities, BF_KEY, keyAttrName } from '@barefootjs/shared'
77
77
  import { BindingScope } from './scope/binding-scope.ts'
78
+ import { readsCallerValue } from './caller-value-reach.ts'
78
79
  import { identifierPattern, identifierCallPattern } from './identifier-pattern.ts'
79
80
  import { isEventHandlerName } from './event-handler-name.ts'
80
81
  import { seedActionAccessorReads } from './action-accessor.ts'
@@ -1226,6 +1227,20 @@ function isLoopRowPropRead(parsed: ParsedExpr, analyzer: AnalyzerContext, scope:
1226
1227
  )
1227
1228
  }
1228
1229
 
1230
+ /**
1231
+ * Whether a conditional branch reads a value the caller supplied that may
1232
+ * be or build a live element (`IRExpression.readsCallerValue`). A loop row's
1233
+ * item, index and destructured names are the row's own data; any other name
1234
+ * a row or callback binds (a `.map()` preamble local) is not known safe.
1235
+ */
1236
+ function branchReadsCallerValue(node: ts.Expression, ctx: TransformContext): boolean {
1237
+ return readsCallerValue(node, ctx.analyzer, name => {
1238
+ const source = ctx.scope.lookup(name)?.binding.source
1239
+ if (source === undefined) return undefined
1240
+ return source === 'item' || source === 'index' || source === 'destructure'
1241
+ })
1242
+ }
1243
+
1229
1244
  /** Set `childrenRead` and `loopRowPropRead` on an expression child from its parse. */
1230
1245
  function attachPropReadFlags(node: IRExpression, parsed: ParsedExpr, analyzer: AnalyzerContext, scope: BindingScope): void {
1231
1246
  const childrenRead = childrenReadOf(parsed, analyzer, scope)
@@ -1250,6 +1265,7 @@ function attachParsedAttrValues(
1250
1265
  if (value.kind === 'template' || value.kind === 'expression') {
1251
1266
  for (const part of value.parts ?? []) {
1252
1267
  if (part.type === 'expression') part.parsed = resolve(part.parsed)
1268
+ else if (part.type === 'ternary' && part.condition.trim()) part.parsedCondition = parse(part.condition.trim())
1253
1269
  }
1254
1270
  }
1255
1271
  if (value.kind === 'expression' || (spreads && value.kind === 'spread')) {
@@ -3639,6 +3655,7 @@ function transformConditionalBranch(
3639
3655
  slotId,
3640
3656
  callsReactiveGetters: callsReactive || undefined,
3641
3657
  hasFunctionCalls: hasCalls || undefined,
3658
+ ...(hasCalls && branchReadsCallerValue(node, ctx) && { readsCallerValue: true as const }),
3642
3659
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
3643
3660
  origin: branchOrigin,
3644
3661
  }
@@ -7368,9 +7385,17 @@ function expandSpreadAttribute(
7368
7385
  const slotId = generateSpreadSlotId(ctx)
7369
7386
  const value = AttrValueOf.spread(spreadExpr, ctx.getTemplateJS(attr.expression), slotId)
7370
7387
  const callerBag = callerBagOfSpread(value, ctx)
7388
+ const shadowsPropsObject = spreadShadowsPropsObject(attr, ctx)
7371
7389
  return [{
7372
7390
  name: '...',
7373
- value: callerBag ? { ...value, callerBag } : value,
7391
+ value: callerBag || shadowsPropsObject
7392
+ ? {
7393
+ ...value,
7394
+ ...(callerBag && { callerBag }),
7395
+ ...(callerBag === 'rest' && { restOmittedKeys: restBagOmittedKeys(ctx.analyzer) }),
7396
+ ...(shadowsPropsObject && { shadowsPropsObject: true as const }),
7397
+ }
7398
+ : value,
7374
7399
  loc,
7375
7400
  freeIdentifiers: spreadFreeIdentifiers,
7376
7401
  }]
@@ -7727,6 +7752,19 @@ function staticObjectSpreadEntries(init: ts.ObjectLiteralExpression): Array<{ ke
7727
7752
  return [...entries].map(([key, text]) => ({ key, text }))
7728
7753
  }
7729
7754
 
7755
+ /**
7756
+ * Whether `{...name}` spreads a binding spelled like the component's props
7757
+ * object (`SpreadAttr.shadowsPropsObject`): a loop row or callback parameter
7758
+ * of that name hides the props object at the spread (#3727).
7759
+ */
7760
+ function spreadShadowsPropsObject(attr: ts.JsxSpreadAttribute, ctx: TransformContext): boolean {
7761
+ const propsName = ctx.analyzer.propsObjectName
7762
+ if (propsName === null) return false
7763
+ let expr: ts.Expression = attr.expression
7764
+ while (ts.isParenthesizedExpression(expr)) expr = expr.expression
7765
+ return ts.isIdentifier(expr) && expr.text === propsName && ctx.scope.isBound(propsName)
7766
+ }
7767
+
7730
7768
  /**
7731
7769
  * Which caller prop bag a spread forwards whole (`SpreadAttr.callerBag`):
7732
7770
  * its `expr` / `templateExpr` resolved through any alias hop
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Zero-argument calls a template resolves to what the called function
3
+ * returns (#3721).
4
+ *
5
+ * A template has no binding for a component's or module's functions: the
6
+ * backend receives the props, not the JS scope. Every template adapter reads
7
+ * a zero-argument identifier call as a signal or memo getter (`count()` →
8
+ * `count`), so a call to a function (`function value() { return 1 }` called
9
+ * as `value()`) read a template variable of the function's name — nothing,
10
+ * or a prop of the same name, which a `(props)`-arg component flattens into
11
+ * the same template namespace.
12
+ *
13
+ * This is the one decision of what such a call reads, made in two steps.
14
+ * First the declaration the name denotes where the call is written
15
+ * ({@link localBindings}): a component-scope declaration of a name hides
16
+ * the module one, whatever either is, and a function body's names resolve
17
+ * in the scope the function is declared in. A prop counts as a component
18
+ * binding only where its bare name is in scope (`templatePropReadParams`):
19
+ * a destructured parameter, or a body binding that holds the prop. A typed
20
+ * prop the body never binds does not hide a function of its name, as in JS.
21
+ * Then what a call of that declaration is ({@link localCall}): inlined, for
22
+ * a function taking no parameters whose body is a single `return <expr>` (a
23
+ * `function` declaration's `FunctionInfo.returnParsed`, or a zero-param
24
+ * arrow `const`); refused, for any other function; neither, for a binding
25
+ * that is not a function. The consumers resolve the call through this
26
+ * table: the SSR seed plan (signal seeds, memo bodies), the static SSR
27
+ * defaults, the template adapters' shared inlining of markup expressions
28
+ * (`inlineComputedConsts`), and the walk of what a server-rendered position
29
+ * reads (`walkServerReads`).
30
+ */
31
+
32
+ import { freeIdentifiers, mapParsedExpr, zeroArgCallBody, type ParsedExpr } from './expression-parser.ts'
33
+ import { templatePropReadParams, type TemplatePropReadBindings } from './props-binding.ts'
34
+ import type { ConstantInfo, FunctionInfo, MemoInfo, SignalInfo } from './types.ts'
35
+
36
+ /** A scope a name is declared in, and a function body's names are read in. */
37
+ export type LocalScope = 'component' | 'module'
38
+
39
+ /** What a zero-argument call of a function returns, and where its body's names resolve. */
40
+ export interface LocalCallBody {
41
+ /** The returned expression. */
42
+ body: ParsedExpr
43
+ /** The scope the function is declared in, which the body's free names are read in. */
44
+ scope: LocalScope
45
+ }
46
+
47
+ /** The component bindings {@link localBindings} reads. */
48
+ export interface LocalCallBindings extends TemplatePropReadBindings {
49
+ localFunctions: readonly FunctionInfo[]
50
+ restPropsName?: string | null
51
+ signals: readonly SignalInfo[]
52
+ memos: readonly MemoInfo[]
53
+ }
54
+
55
+ /**
56
+ * What a name denotes in the scope it is declared in. `opaque` is a binding
57
+ * with no declaration to read: a prop in scope by its bare name, the props
58
+ * object, the rest props, a signal setter.
59
+ */
60
+ export type LocalBinding =
61
+ | { kind: 'signal'; scope: LocalScope; info: SignalInfo }
62
+ | { kind: 'memo'; scope: LocalScope; info: MemoInfo }
63
+ | { kind: 'const'; scope: LocalScope; info: ConstantInfo }
64
+ | { kind: 'function'; scope: LocalScope; info: FunctionInfo }
65
+ | { kind: 'opaque'; scope: LocalScope }
66
+
67
+ /** The declaration `name` denotes, read from `from`: `null` for a name neither scope declares. */
68
+ export type LocalBindingResolver = (name: string, from: LocalScope) => LocalBinding | null
69
+
70
+ /**
71
+ * The lexical resolution of a component's and its module's names. Read from
72
+ * the component scope, a component declaration of the name is the binding,
73
+ * and only a name the component does not declare reaches the module's; read
74
+ * from the module scope (a module function's body), only the module's is.
75
+ */
76
+ export function localBindings(b: LocalCallBindings): LocalBindingResolver {
77
+ const scopes = { component: new Map<string, LocalBinding>(), module: new Map<string, LocalBinding>() }
78
+ const bind = (name: string, binding: LocalBinding): void => {
79
+ scopes[binding.scope].set(name, binding)
80
+ }
81
+ for (const info of b.localFunctions) {
82
+ bind(info.name, { kind: 'function', scope: info.inComponentBody ? 'component' : 'module', info })
83
+ }
84
+ for (const info of b.localConstants) bind(info.name, { kind: 'const', scope: info.isModule ? 'module' : 'component', info })
85
+ for (const info of b.memos) bind(info.name, { kind: 'memo', scope: info.isModule ? 'module' : 'component', info })
86
+ for (const info of b.signals) {
87
+ const scope = info.isModule ? 'module' : 'component'
88
+ bind(info.getter, { kind: 'signal', scope, info })
89
+ if (info.setter) bind(info.setter, { kind: 'opaque', scope })
90
+ }
91
+ const props = [b.propsObjectName, b.restPropsName, ...templatePropReadParams(b).map(p => p.name)]
92
+ for (const name of props) if (name) bind(name, { kind: 'opaque', scope: 'component' })
93
+ return (name, from) => (from === 'component' ? scopes.component.get(name) : undefined) ?? scopes.module.get(name) ?? null
94
+ }
95
+
96
+ /**
97
+ * What a zero-argument call of `binding` is to a template: `inline` with the
98
+ * expression the function returns, `refuse` for a function a template
99
+ * cannot inline (one with parameters, a body other than a single `return`,
100
+ * an `async` / generator one, a reassigned arrow `const`), or `null` for a
101
+ * binding that is not such a function. A function returning JSX is inlined
102
+ * into the markup before any template reads it, and is `null` too.
103
+ */
104
+ export function localCall(binding: LocalBinding | null): { kind: 'inline'; body: ParsedExpr } | { kind: 'refuse' } | null {
105
+ if (binding?.kind === 'function') {
106
+ const f = binding.info
107
+ if (f.isJsxFunction || f.containsJsx || f.isMultiReturnJsxHelper) return null
108
+ return f.returnParsed ? { kind: 'inline', body: f.returnParsed } : { kind: 'refuse' }
109
+ }
110
+ if (binding?.kind !== 'const') return null
111
+ const c = binding.info
112
+ const body = arrowConstBody(c)
113
+ if (body) return { kind: 'inline', body }
114
+ if (c.declarationKind !== 'const' || c.parsed?.kind !== 'arrow' || c.isJsxFunction || c.isJsx) return null
115
+ return { kind: 'refuse' }
116
+ }
117
+
118
+ /**
119
+ * Each function name a zero-argument call written in `from` reads as a
120
+ * function whose returned expression a template can inline, with that
121
+ * expression ({@link inlinedBody}).
122
+ */
123
+ export function localCallBodies(b: LocalCallBindings, from: LocalScope = 'component'): ReadonlyMap<string, LocalCallBody> {
124
+ const resolve = localBindings(b)
125
+ const out = new Map<string, LocalCallBody>()
126
+ for (const name of callableNames(b)) {
127
+ const binding = resolve(name, from)
128
+ const body = binding && inlinedBody(binding, resolve, new Set())
129
+ if (binding && body) out.set(name, { body, scope: binding.scope })
130
+ }
131
+ return out
132
+ }
133
+
134
+ /**
135
+ * Each function name a zero-argument call written in `from` reads as a
136
+ * function a template cannot inline: {@link localCall}'s `refuse`, or a
137
+ * module function whose returned expression calls one. Read as a getter,
138
+ * such a call would render an unbound name or a prop of that name, so a
139
+ * template refuses it.
140
+ */
141
+ export function uninlinableLocalCalls(b: LocalCallBindings, from: LocalScope = 'component'): ReadonlySet<string> {
142
+ const resolve = localBindings(b)
143
+ const out = new Set<string>()
144
+ for (const name of callableNames(b)) {
145
+ const binding = resolve(name, from)
146
+ if (binding && localCall(binding) && !inlinedBody(binding, resolve, new Set())) out.add(name)
147
+ }
148
+ return out
149
+ }
150
+
151
+ /**
152
+ * The expression a zero-argument call of `binding` is inlined as, or `null`
153
+ * when a template cannot inline it.
154
+ *
155
+ * A component function's returned expression is read where the call is
156
+ * written (these tables serve the component scope), so it stands as it is.
157
+ * A module function's is not: each local function it calls is the module's,
158
+ * which a component declaration of the same name would replace once the
159
+ * expression sits in the component scope. Those calls are inlined here, in
160
+ * module scope, and one a template cannot inline (or a function calling
161
+ * itself) makes the caller uninlinable too.
162
+ */
163
+ function inlinedBody(binding: LocalBinding, resolve: LocalBindingResolver, running: ReadonlySet<LocalBinding>): ParsedExpr | null {
164
+ const call = localCall(binding)
165
+ if (call?.kind !== 'inline' || running.has(binding)) return null
166
+ if (binding.scope === 'component') return call.body
167
+ const inner = new Set(running).add(binding)
168
+ let inlinable = true
169
+ const body = mapParsedExpr(call.body, (e, enclosing) => {
170
+ if (e.kind !== 'call' || e.args.length > 0 || e.callee.kind !== 'identifier' || enclosing.has(e.callee.name)) return null
171
+ const callee = resolve(e.callee.name, 'module')
172
+ if (!callee || !localCall(callee)) return null
173
+ const inlined = inlinedBody(callee, resolve, inner)
174
+ // Inlined under a callback param of one of its names, the expression would read the param.
175
+ const free = inlined && freeIdentifiers(inlined)
176
+ if (!inlined || !free || [...free].some(name => enclosing.has(name))) inlinable = false
177
+ return inlined
178
+ })
179
+ return inlinable ? body : null
180
+ }
181
+
182
+ /** Every name a function declaration or a const binds, in either scope. */
183
+ function callableNames(b: LocalCallBindings): Set<string> {
184
+ return new Set([...b.localFunctions.map(f => f.name), ...b.localConstants.map(c => c.name)])
185
+ }
186
+
187
+ /** The body of a zero-param arrow `const` that is never reassigned, or `null`. */
188
+ function arrowConstBody(c: ConstantInfo): ParsedExpr | null {
189
+ if (c.declarationKind !== 'const' || c.mutatedAfterDeclaration || !c.parsed) return null
190
+ return zeroArgCallBody(c.parsed)
191
+ }
@@ -242,6 +242,16 @@ export interface NullishAttrContext {
242
242
  * ToNumber unless both sides are strings, so its nil's reading decides the
243
243
  * comparison (`undefined < 1` is false, `null < 1` is true). */
244
244
  readonly nullableScalarProps?: ReadonlyMap<string, NullableScalarProp>
245
+ /**
246
+ * Whether the value a read names at the attribute site is declared to
247
+ * admit `undefined` / `null` (#3728): a loop row's optional member
248
+ * (`r.tone` where the element type has `tone?: string`, a destructured
249
+ * `tone`, `r.meta.tone`). The adapter answers it from the declared types
250
+ * through its live `BindingScope` (`declaredValueMayBeNil`). Consulted for
251
+ * the attribute's own reads only, never inside a memo body, whose names
252
+ * resolve where the memo is declared.
253
+ */
254
+ readonly declaredNil?: (expr: ParsedExpr) => boolean
245
255
  }
246
256
 
247
257
  /** A string or boolean prop's nil reading ({@link NullishAttrContext.nullableScalarProps}). */
@@ -360,44 +370,56 @@ export function attrValueMayBeNullish(
360
370
  // `shadowed` is the scope the expression is read in: the attribute site's
361
371
  // loop bindings at the top level, none inside a memo body — its getters
362
372
  // resolve where the memo is declared, not where it is read.
363
- const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): boolean => {
373
+ // `atSite`: the expression is the attribute's own, read in the attribute
374
+ // site's scope, where the declared-type answer (`declaredNil`) applies.
375
+ const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean, atSite = true): boolean => {
364
376
  if (readsUndefinedLeaf(expr, ctx, shadowed)) return true
377
+ if (atSite && ctx.declaredNil !== undefined && isPlainRead(expr) && ctx.declaredNil(expr)) return true
365
378
  switch (expr.kind) {
366
379
  case 'identifier':
367
380
  return expr.name === 'undefined'
368
381
  case 'literal':
369
382
  return expr.literalType === 'null'
370
- case 'call': {
371
- const getter = bareGetterCallName(expr)
372
- if (getter === null || shadowed(getter)) return false
373
- if (ctx.nullableSignals.has(getter)) return true
374
- const memo = ctx.memos.get(getter)
375
- if (!memo || visiting.has(getter)) return false
376
- if (admitsNullish(memo.type)) return true
377
- visiting.add(getter)
378
- const result = memo.parsed !== undefined && walk(memo.parsed, () => false)
379
- visiting.delete(getter)
380
- return result
381
- }
383
+ case 'call':
384
+ return getterMayBeNullish(expr, shadowed)
382
385
  // A computed key or an index (`pair[1]`, `row[key]`) reads `undefined`
383
386
  // when it is out of range or absent (#3497).
384
387
  case 'member':
385
- return expr.optional || expr.computed || walk(expr.object, shadowed)
388
+ return expr.optional || expr.computed || walk(expr.object, shadowed, atSite)
386
389
  case 'index-access':
387
390
  return true
388
391
  case 'conditional':
389
- return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed)
392
+ return walk(expr.consequent, shadowed, atSite) || walk(expr.alternate, shadowed, atSite)
390
393
  case 'logical':
391
394
  return expr.op === '&&'
392
- ? walk(expr.left, shadowed) || walk(expr.right, shadowed)
393
- : walk(expr.right, shadowed)
395
+ ? walk(expr.left, shadowed, atSite) || walk(expr.right, shadowed, atSite)
396
+ : walk(expr.right, shadowed, atSite)
394
397
  default:
395
398
  return false
396
399
  }
397
400
  }
401
+ // A nullable signal's getter, or a memo whose type or body can be nullish.
402
+ const getterMayBeNullish = (expr: ParsedExpr, shadowed: (name: string) => boolean): boolean => {
403
+ const getter = bareGetterCallName(expr)
404
+ if (getter === null || shadowed(getter)) return false
405
+ if (ctx.nullableSignals.has(getter)) return true
406
+ const memo = ctx.memos.get(getter)
407
+ if (!memo || visiting.has(getter)) return false
408
+ if (admitsNullish(memo.type)) return true
409
+ visiting.add(getter)
410
+ const result = memo.parsed !== undefined && walk(memo.parsed, () => false, false)
411
+ visiting.delete(getter)
412
+ return result
413
+ }
398
414
  return parsed !== undefined && walk(parsed, isShadowed)
399
415
  }
400
416
 
417
+ /** A bare name or a non-computed member path over one (`tone`, `r.tone`, `r.meta.tone`). */
418
+ function isPlainRead(expr: ParsedExpr): boolean {
419
+ if (expr.kind === 'identifier') return true
420
+ return expr.kind === 'member' && !expr.computed && isPlainRead(expr.object)
421
+ }
422
+
401
423
  /** A method call that can miss (`methodMayReturnUndefined`), or a read of a prop that can be absent. */
402
424
  function readsUndefinedLeaf(expr: ParsedExpr, ctx: NullishAttrContext, shadowed: (name: string) => boolean): boolean {
403
425
  return methodMayReturnUndefined(expr) || readsNullableProp(expr, ctx, shadowed)
@@ -0,0 +1,195 @@
1
+ /**
2
+ * What a computed destructure default evaluates, once the declarations it
3
+ * reads are resolved (#3725, #3791).
4
+ *
5
+ * A backend applies a computed default when it renders (the SSR seed plan's
6
+ * prop steps, Go's props constructor), and it receives the props, not the JS
7
+ * scope: a default naming a const (`const DEF = 'z'`, `{ b =
8
+ * DEF.toUpperCase() }`) or calling a function has nothing to read there.
9
+ * This is the one resolution of those names into the expression the default
10
+ * stands for, each name read lexically (`localBindings`):
11
+ *
12
+ * - A body destructure (`const { b = DEF } = props`) reads the component
13
+ * scope, where a component const hides a module const of its name.
14
+ * - A parameter destructure (`function C({ b = DEF })`) reads the module
15
+ * scope: a parameter default cannot see the body's declarations.
16
+ *
17
+ * A `const` is replaced by its own value resolved in the scope it is
18
+ * declared in, and a zero-argument call of a function a template inlines
19
+ * (`localCall`) by the expression it returns. A module value is taken only
20
+ * when nothing is left to read in it, so no name it reads can meet a
21
+ * component binding where it lands. What stays free is a prop, the props
22
+ * object, a global, or a module name no backend computes.
23
+ *
24
+ * A component-scope declaration that has no such value (a signal, a memo, a
25
+ * `let`, a mutated const, a function with parameters or statements, a const
26
+ * declared after the destructure, which JS has not initialized when the
27
+ * default runs) leaves the default with nothing a template can compute: it
28
+ * is `blocked`, and the adapters refuse it where the server render reads the
29
+ * prop (`refuseUnappliedPropDefaults`).
30
+ */
31
+
32
+ import { freeIdentifiers, mapParsedExpr, type ParsedExpr } from './expression-parser.ts'
33
+ import { localBindings, localCall, type LocalBinding, type LocalBindingResolver, type LocalScope } from './local-call-body.ts'
34
+ import { templatePropReadParams } from './props-binding.ts'
35
+ import type { IRMetadata, ParamInfo, Position, SourceLocation } from './types.ts'
36
+
37
+ /** A computed destructure default with the declarations it reads resolved. */
38
+ export interface ResolvedPropDefault {
39
+ /** The default as the expression it stands for. */
40
+ expr: ParsedExpr
41
+ /** Whether a declaration the default reads was resolved into `expr`. */
42
+ readsDeclaration: boolean
43
+ /** Where a body destructure binds the prop; unset for a parameter default. */
44
+ loc: SourceLocation | undefined
45
+ /** The component declarations it reads that have no value a template can compute. */
46
+ blocked: readonly string[]
47
+ }
48
+
49
+ /** The metadata {@link propDefaultResolver} reads. */
50
+ export type PropDefaultBindings = Pick<
51
+ IRMetadata,
52
+ 'propsParams' | 'propsObjectName' | 'restPropsName' | 'signals' | 'memos' | 'localFunctions' | 'localConstants'
53
+ >
54
+
55
+ /** One expression resolved in one scope. */
56
+ interface Resolution {
57
+ expr: ParsedExpr
58
+ blocked: Set<string>
59
+ /** Whether a declaration was resolved into `expr`. */
60
+ replaced: boolean
61
+ }
62
+
63
+ /** What a free name of an expression is replaced by. */
64
+ type Replacement =
65
+ | { kind: 'keep' }
66
+ | { kind: 'blocked' }
67
+ /** Every free read of the name. */
68
+ | { kind: 'value'; value: Resolution }
69
+ /** Only a call of the name with no arguments; any other read of it is `otherwise`. */
70
+ | { kind: 'call'; value: Resolution; otherwise: 'keep' | 'blocked' }
71
+
72
+ /**
73
+ * The resolver of a component's destructure defaults: `p`'s default as the
74
+ * expression it stands for ({@link ResolvedPropDefault}), or `null` for a
75
+ * prop with no parsed default.
76
+ */
77
+ export function propDefaultResolver(metadata: PropDefaultBindings): (p: ParamInfo) => ResolvedPropDefault | null {
78
+ const bindings = { ...metadata, localConstants: metadata.localConstants ?? [] }
79
+ const resolve = localBindings(bindings)
80
+ const props = new Set<string>(templatePropReadParams(bindings).map(p => p.name))
81
+ if (metadata.propsObjectName) props.add(metadata.propsObjectName)
82
+ if (metadata.restPropsName) props.add(metadata.restPropsName)
83
+ const bodyBound = new Map<string, SourceLocation>()
84
+ for (const c of bindings.localConstants) if (!c.isModule && c.propsDestructure) bodyBound.set(c.name, c.loc)
85
+ return (p) => {
86
+ if (p.isRest || !p.parsed) return null
87
+ const loc = bodyBound.get(p.name)
88
+ const resolver = new DeclarationResolver(resolve, props, loc?.start)
89
+ const { expr, blocked, replaced } = resolver.resolveExpr(p.parsed, loc ? 'component' : 'module', true)
90
+ return { expr, blocked: [...blocked], readsDeclaration: replaced, loc }
91
+ }
92
+ }
93
+
94
+ /** Resolves one default through the declarations it reads, each declaration once. */
95
+ class DeclarationResolver {
96
+ private readonly values = new Map<LocalBinding['scope'], Map<string, Resolution | null>>([
97
+ ['component', new Map()],
98
+ ['module', new Map()],
99
+ ])
100
+
101
+ constructor(
102
+ private readonly resolve: LocalBindingResolver,
103
+ /** The names a template reads as props, which hide a module declaration of the name. */
104
+ private readonly props: ReadonlySet<string>,
105
+ /** Where the body destructure holding the default starts: a component const declared from there on is not initialized yet. */
106
+ private readonly runsAt: Position | undefined,
107
+ ) {}
108
+
109
+ /**
110
+ * `expr` with each free name read from `scope` replaced by what it
111
+ * denotes. `propsInScope` is whether the expression sits where the props
112
+ * are bound (a default, a component declaration), not in a module one.
113
+ */
114
+ resolveExpr(expr: ParsedExpr, scope: LocalScope, propsInScope: boolean): Resolution {
115
+ const blocked = new Set<string>()
116
+ const free = freeIdentifiers(expr)
117
+ if (!free) return { expr, blocked, replaced: false }
118
+ const replacements = new Map<string, Replacement>()
119
+ for (const name of free) {
120
+ const replacement = propsInScope && this.props.has(name) ? KEEP : this.replacementOf(name, scope)
121
+ if (replacement.kind !== 'keep') replacements.set(name, replacement)
122
+ }
123
+ if (replacements.size === 0) return { expr, blocked, replaced: false }
124
+ let replaced = false
125
+ // A value landing under a callback param of one of its own names would read the param.
126
+ const take = (name: string, value: Resolution, enclosing: ReadonlySet<string>): ParsedExpr | null => {
127
+ const reads = freeIdentifiers(value.expr)
128
+ if (!reads || [...reads].some(read => enclosing.has(read))) {
129
+ blocked.add(name)
130
+ return null
131
+ }
132
+ for (const b of value.blocked) blocked.add(b)
133
+ replaced = true
134
+ return value.expr
135
+ }
136
+ const resolved = mapParsedExpr(expr, (e, enclosing) => {
137
+ if (e.kind === 'call' && e.args.length === 0 && e.callee.kind === 'identifier' && !enclosing.has(e.callee.name)) {
138
+ const r = replacements.get(e.callee.name)
139
+ if (r?.kind === 'call') return take(e.callee.name, r.value, enclosing)
140
+ }
141
+ if (e.kind !== 'identifier' || enclosing.has(e.name)) return null
142
+ const r = replacements.get(e.name)
143
+ if (r?.kind === 'value') return take(e.name, r.value, enclosing)
144
+ if (r?.kind === 'blocked' || (r?.kind === 'call' && r.otherwise === 'blocked')) blocked.add(e.name)
145
+ return null
146
+ })
147
+ return { expr: replaced ? resolved : expr, blocked, replaced }
148
+ }
149
+
150
+ /** What a free read of `name` from `scope` is replaced by. */
151
+ private replacementOf(name: string, scope: LocalScope): Replacement {
152
+ const binding = this.resolve(name, scope)
153
+ if (!binding || binding.kind === 'opaque') return KEEP
154
+ // A module declaration no backend computes stays a name, as before.
155
+ const otherwise = binding.scope === 'component' ? 'blocked' : 'keep'
156
+ if (binding.kind === 'const' && binding.scope === 'component' && !this.isInitialized(binding.info.loc?.start)) return { kind: 'blocked' }
157
+ const call = localCall(binding)
158
+ if (call) {
159
+ const value = call.kind === 'inline' ? this.valueOf(name, binding, call.body) : null
160
+ return value ? { kind: 'call', value, otherwise } : { kind: otherwise }
161
+ }
162
+ const value = binding.kind === 'const' && isStableConst(binding) ? this.valueOf(name, binding, binding.info.parsed!) : null
163
+ return value ? { kind: 'value', value } : { kind: otherwise }
164
+ }
165
+
166
+ /** Whether a component const declared at `declared` holds its value when the default runs. */
167
+ private isInitialized(declared: Position | undefined): boolean {
168
+ const at = this.runsAt
169
+ return !at || !declared || declared.line < at.line || (declared.line === at.line && declared.column < at.column)
170
+ }
171
+
172
+ /**
173
+ * The value `binding` (declared as `name`) holds, resolved in its own
174
+ * scope: `null` for a module value that still reads something, or one
175
+ * that reads itself.
176
+ */
177
+ private valueOf(name: string, binding: LocalBinding, expr: ParsedExpr): Resolution | null {
178
+ const known = this.values.get(binding.scope)!
179
+ if (known.has(name)) return known.get(name) ?? null
180
+ known.set(name, null)
181
+ const value = this.resolveExpr(expr, binding.scope, binding.scope === 'component')
182
+ const closed = binding.scope === 'component' || freeIdentifiers(value.expr)?.size === 0
183
+ const result = closed ? value : null
184
+ known.set(name, result)
185
+ return result
186
+ }
187
+ }
188
+
189
+ const KEEP: Replacement = { kind: 'keep' }
190
+
191
+ /** A `const` holding the one value its initializer gives it, which a template can read in its place. */
192
+ function isStableConst(binding: Extract<LocalBinding, { kind: 'const' }>): boolean {
193
+ const c = binding.info
194
+ return c.declarationKind === 'const' && !c.mutatedAfterDeclaration && c.parsed !== undefined && !c.isJsx && !c.isJsxFunction
195
+ }
@@ -619,6 +619,22 @@ export interface RestSpreadBindings {
619
619
  propsObjectName: string | null
620
620
  }
621
621
 
622
+ /**
623
+ * The caller keys the component's rest bag (`...rest`) leaves out: the keys
624
+ * its destructure takes before the rest element, spelled as the caller
625
+ * passes them. A body destructure of the props object (`const { a, ...rest }
626
+ * = props`) records them itself (`restPropsOmittedKeys`); a signature rest
627
+ * takes every destructured param, by its source key (`{ value: v }` takes
628
+ * `value`). The one definition `SpreadAttr.restOmittedKeys` is built from.
629
+ */
630
+ export function restBagOmittedKeys(bindings: {
631
+ propsParams: ReadonlyArray<{ name: string; sourceName?: string }>
632
+ restPropsOmittedKeys?: readonly string[] | null
633
+ }): string[] {
634
+ if (bindings.restPropsOmittedKeys) return [...bindings.restPropsOmittedKeys]
635
+ return bindings.propsParams.map(p => p.sourceName ?? p.name)
636
+ }
637
+
622
638
  /**
623
639
  * Walks a bare `const x__alias = <name>` hop chain recorded in
624
640
  * `constantValues` (name → initializer text) until `terminal` recognizes