@barefootjs/jsx 0.39.6 → 0.39.7

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 (89) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -1
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +27 -0
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/computed-const.d.ts +52 -0
  6. package/dist/adapters/computed-const.d.ts.map +1 -0
  7. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  8. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  9. package/dist/adapters/element-shell.d.ts +44 -0
  10. package/dist/adapters/element-shell.d.ts.map +1 -0
  11. package/dist/adapters/interface.d.ts +2 -0
  12. package/dist/adapters/interface.d.ts.map +1 -1
  13. package/dist/analyzer.d.ts.map +1 -1
  14. package/dist/augment-inherited-props.d.ts +7 -0
  15. package/dist/augment-inherited-props.d.ts.map +1 -1
  16. package/dist/fold-render-reassignments.d.ts +43 -0
  17. package/dist/fold-render-reassignments.d.ts.map +1 -0
  18. package/dist/free-refs.d.ts +9 -0
  19. package/dist/free-refs.d.ts.map +1 -1
  20. package/dist/index.d.ts +8 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2285 -1583
  23. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  25. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/html-template.d.ts +9 -10
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  31. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  33. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/utils.d.ts +13 -0
  35. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  36. package/dist/jsx-to-ir.d.ts.map +1 -1
  37. package/dist/nullable-signal-attr.d.ts +3 -2
  38. package/dist/nullable-signal-attr.d.ts.map +1 -1
  39. package/dist/props-binding.d.ts +34 -5
  40. package/dist/props-binding.d.ts.map +1 -1
  41. package/dist/relocate.d.ts +16 -0
  42. package/dist/relocate.d.ts.map +1 -1
  43. package/dist/ssr-seed-plan.d.ts +0 -6
  44. package/dist/ssr-seed-plan.d.ts.map +1 -1
  45. package/dist/types.d.ts +54 -2
  46. package/dist/types.d.ts.map +1 -1
  47. package/package.json +2 -2
  48. package/src/__tests__/block-memo-type.test.ts +51 -0
  49. package/src/__tests__/callback-method.test.ts +75 -0
  50. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  51. package/src/__tests__/computed-const.test.ts +101 -0
  52. package/src/__tests__/element-shell.test.ts +78 -0
  53. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  54. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  55. package/src/__tests__/memo-body-expr.test.ts +120 -0
  56. package/src/__tests__/prop-handling.test.ts +35 -16
  57. package/src/__tests__/props-alias-const.test.ts +65 -0
  58. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  59. package/src/__tests__/ssr-seed-plan.test.ts +54 -1
  60. package/src/__tests__/static-template-reachability.test.ts +137 -0
  61. package/src/adapters/attr-plan.ts +29 -1
  62. package/src/adapters/callback-method.ts +62 -0
  63. package/src/adapters/computed-const.ts +185 -0
  64. package/src/adapters/dangerous-inner-html.ts +33 -0
  65. package/src/adapters/element-shell.ts +160 -0
  66. package/src/adapters/interface.ts +8 -0
  67. package/src/analyzer.ts +271 -82
  68. package/src/augment-inherited-props.ts +12 -0
  69. package/src/fold-render-reassignments.ts +314 -0
  70. package/src/free-refs.ts +49 -0
  71. package/src/index.ts +9 -2
  72. package/src/ir-to-client-js/compute-inlinability.ts +93 -17
  73. package/src/ir-to-client-js/csr-substitute.ts +13 -35
  74. package/src/ir-to-client-js/emit-registration.ts +3 -2
  75. package/src/ir-to-client-js/html-template.ts +26 -70
  76. package/src/ir-to-client-js/index.ts +3 -2
  77. package/src/ir-to-client-js/init-declarations.ts +1 -1
  78. package/src/ir-to-client-js/plan/build-declaration-emit.ts +25 -51
  79. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  80. package/src/ir-to-client-js/prop-handling.ts +13 -54
  81. package/src/ir-to-client-js/rewrite-destructured-props.ts +6 -5
  82. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  83. package/src/ir-to-client-js/utils.ts +11 -0
  84. package/src/jsx-to-ir.ts +39 -52
  85. package/src/nullable-signal-attr.ts +7 -4
  86. package/src/props-binding.ts +100 -5
  87. package/src/relocate.ts +40 -8
  88. package/src/ssr-seed-plan.ts +18 -6
  89. package/src/types.ts +50 -2
@@ -0,0 +1,314 @@
1
+ /**
2
+ * Fold render-time reassignments of a component-scope `let` into its
3
+ * initializer (#3501).
4
+ *
5
+ * A template evaluates a binding's value, never the statements that follow
6
+ * its declaration, so a `let` reassigned before the component returns had
7
+ * no value a template could read:
8
+ *
9
+ * let label = props.label ?? 'Default'
10
+ * if (!label) label = 'Fallback'
11
+ *
12
+ * This pre-pass rewrites that to the single value the binding holds at
13
+ * render time, binding each intermediate value once, and removes the
14
+ * reassigning statements:
15
+ *
16
+ * const label_1 = props.label ?? 'Default'; let label = ((!(label_1)) ? ('Fallback') : (label_1))
17
+ *
18
+ * Every later stage (the analyzer, the CSR template, the template adapters,
19
+ * the client init body) then sees ordinary bindings with one value each, so
20
+ * they agree by construction.
21
+ *
22
+ * The rewrite only applies where it cannot change behaviour:
23
+ * - the reassigning statements directly follow the declaration, and each
24
+ * is an assignment to the binding (`x = e`, `x += e`, `x ??= e`, …), an
25
+ * `if`/`else` whose branches are such assignments, or a block of them;
26
+ * - the initializer, every assigned value and every condition is free of
27
+ * side effects (no calls, no assignments, no functions);
28
+ * - every expression is evaluated exactly as often, and in the same order,
29
+ * as the original statements evaluate it, since a member read may run a
30
+ * getter. Each statement's incoming value is a binding (a read of it is
31
+ * unobservable) or a literal, a conditional evaluates only the branch it
32
+ * takes, and inside a statement a computed value may only flow into a
33
+ * compound assignment (see `foldStatement`).
34
+ * Anything else leaves the binding as it is (and `markMutatedConstants`
35
+ * flags it as before).
36
+ */
37
+
38
+ import ts from 'typescript'
39
+
40
+ /** Folded values longer than this are left unfolded. */
41
+ const MAX_FOLDED_LENGTH = 4000
42
+
43
+ interface Edit {
44
+ start: number
45
+ end: number
46
+ text: string
47
+ }
48
+
49
+ /**
50
+ * The source with each foldable `let` folded, or `null` when nothing was
51
+ * folded. Line count is preserved where possible (removed statements are
52
+ * blanked rather than deleted), so later source locations stay valid.
53
+ */
54
+ export function foldRenderReassignmentsInSource(source: string, filePath: string): string | null {
55
+ if (!source.includes('let ')) return null
56
+ const sf = ts.createSourceFile(filePath, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
57
+ const edits: Edit[] = []
58
+ const names = new FreshNames(sf)
59
+ for (const body of topLevelFunctionBodies(sf)) foldBlock(body.statements, sf, names, edits)
60
+ if (edits.length === 0) return null
61
+ edits.sort((a, b) => b.start - a.start)
62
+ let out = source
63
+ for (const e of edits) out = out.slice(0, e.start) + e.text + out.slice(e.end)
64
+ return out
65
+ }
66
+
67
+ function topLevelFunctionBodies(sf: ts.SourceFile): ts.Block[] {
68
+ const bodies: ts.Block[] = []
69
+ const add = (fn: ts.Node | undefined) => {
70
+ if (fn && (ts.isArrowFunction(fn) || ts.isFunctionExpression(fn)) && fn.body && ts.isBlock(fn.body)) bodies.push(fn.body)
71
+ }
72
+ for (const stmt of sf.statements) {
73
+ if (ts.isFunctionDeclaration(stmt) && stmt.body) bodies.push(stmt.body)
74
+ else if (ts.isVariableStatement(stmt)) for (const d of stmt.declarationList.declarations) add(d.initializer)
75
+ else if (ts.isExportAssignment(stmt)) add(stmt.expression)
76
+ }
77
+ return bodies
78
+ }
79
+
80
+ /** Identifiers not yet used anywhere in the file, for the intermediate bindings. */
81
+ class FreshNames {
82
+ private readonly used = new Set<string>()
83
+ constructor(sf: ts.SourceFile) {
84
+ const visit = (node: ts.Node): void => {
85
+ if (ts.isIdentifier(node)) this.used.add(node.text)
86
+ ts.forEachChild(node, visit)
87
+ }
88
+ visit(sf)
89
+ }
90
+ next(base: string): string {
91
+ let k = 1
92
+ while (this.used.has(`${base}_${k}`)) k++
93
+ const name = `${base}_${k}`
94
+ this.used.add(name)
95
+ return name
96
+ }
97
+ }
98
+
99
+ /** A value: its source text, and whether it is a literal or a plain identifier, which may be repeated freely. */
100
+ interface Value {
101
+ text: string
102
+ trivial: boolean
103
+ }
104
+
105
+ function foldBlock(statements: ts.NodeArray<ts.Statement>, sf: ts.SourceFile, names: FreshNames, edits: Edit[]): void {
106
+ for (let i = 0; i < statements.length; i++) {
107
+ const decl = foldableLet(statements[i]!)
108
+ if (!decl) continue
109
+ const name = decl.name.text
110
+ // `value` is the binding's value so far. Each statement reads it through
111
+ // a binding of its own (or directly, when it is a literal or identifier),
112
+ // so its expression is evaluated once, where the original evaluated it.
113
+ let value: Value = { text: decl.initializer.getText(sf), trivial: isTrivial(decl.initializer) }
114
+ const bindings: string[] = []
115
+ let last = i
116
+ for (let j = i + 1; j < statements.length; j++) {
117
+ const ref = value.trivial ? value.text : names.next(name)
118
+ const next = foldStatement(statements[j]!, name, { text: ref, trivial: true }, sf)
119
+ if (next === null || next.text.length > MAX_FOLDED_LENGTH) break
120
+ if (!value.trivial) bindings.push(`const ${ref} = ${value.text}; `)
121
+ value = next
122
+ last = j
123
+ }
124
+ if (last === i) continue
125
+ const stmt = statements[i]!
126
+ const initText = decl.initializer.getText(sf)
127
+ const prefix = bindings.join('')
128
+ edits.push({ start: stmt.getStart(sf), end: stmt.getStart(sf), text: prefix })
129
+ edits.push({ start: decl.initializer.getStart(sf), end: decl.initializer.getEnd(), text: value.text })
130
+ const surplus = countNewlines(prefix) + countNewlines(value.text) - countNewlines(initText)
131
+ edits.push(...blankStatements(statements.slice(i + 1, last + 1), sf, surplus))
132
+ i = last
133
+ }
134
+ }
135
+
136
+ function isTrivial(expr: ts.Expression): boolean {
137
+ return PURE_LEAF_KINDS.has(skipParens(expr).kind)
138
+ }
139
+
140
+ /** `let x = <pure initializer>` with a single identifier binding. */
141
+ function foldableLet(stmt: ts.Statement): (ts.VariableDeclaration & { name: ts.Identifier; initializer: ts.Expression }) | null {
142
+ if (!ts.isVariableStatement(stmt)) return null
143
+ const list = stmt.declarationList
144
+ if (!(list.flags & ts.NodeFlags.Let) || list.declarations.length !== 1) return null
145
+ const d = list.declarations[0]!
146
+ if (!ts.isIdentifier(d.name) || !d.initializer || !isPure(d.initializer)) return null
147
+ return d as ts.VariableDeclaration & { name: ts.Identifier; initializer: ts.Expression }
148
+ }
149
+
150
+ const COMPOUND_OPERATORS = new Map<ts.SyntaxKind, string>([
151
+ [ts.SyntaxKind.PlusEqualsToken, '+'],
152
+ [ts.SyntaxKind.MinusEqualsToken, '-'],
153
+ [ts.SyntaxKind.AsteriskEqualsToken, '*'],
154
+ [ts.SyntaxKind.SlashEqualsToken, '/'],
155
+ [ts.SyntaxKind.PercentEqualsToken, '%'],
156
+ [ts.SyntaxKind.QuestionQuestionEqualsToken, '??'],
157
+ [ts.SyntaxKind.BarBarEqualsToken, '||'],
158
+ [ts.SyntaxKind.AmpersandAmpersandEqualsToken, '&&'],
159
+ ])
160
+
161
+ /**
162
+ * The binding's value after `stmt`, given its value `current` before; `null`
163
+ * when `stmt` is not foldable.
164
+ *
165
+ * A trivial `current` (a binding, a literal) may be read any number of times,
166
+ * or not at all. A computed one (left by an earlier assignment inside the
167
+ * same statement) must be evaluated exactly once and before anything else, as
168
+ * the original evaluated it, so only a compound assignment (`x += e`, whose
169
+ * `e` does not read `x`) or an empty statement may follow it: an overwrite
170
+ * would drop its evaluation, and any other read could repeat or reorder it.
171
+ */
172
+ function foldStatement(stmt: ts.Statement, name: string, current: Value, sf: ts.SourceFile): Value | null {
173
+ if (ts.isEmptyStatement(stmt)) return current
174
+ if (ts.isBlock(stmt)) return foldSequence(stmt.statements, name, current, sf)
175
+ if (ts.isIfStatement(stmt)) return current.trivial ? foldIf(stmt, name, current, sf) : null
176
+ const assignment = reassignment(stmt, name)
177
+ if (!assignment) return null
178
+ const value = substitute(assignment.right, name, current.text, sf)
179
+ if (assignment.operatorToken.kind === ts.SyntaxKind.EqualsToken) {
180
+ return current.trivial ? { text: value.text, trivial: value.reads === 0 && isTrivial(assignment.right) } : null
181
+ }
182
+ const op = COMPOUND_OPERATORS.get(assignment.operatorToken.kind)
183
+ if (op === undefined || (!current.trivial && value.reads > 0)) return null
184
+ return { text: `((${current.text}) ${op} (${value.text}))`, trivial: false }
185
+ }
186
+
187
+ /** `name = e` / `name op= e` with a side-effect-free `e`, as an expression statement. */
188
+ function reassignment(stmt: ts.Statement, name: string): ts.BinaryExpression | null {
189
+ if (!ts.isExpressionStatement(stmt)) return null
190
+ const expr = skipParens(stmt.expression)
191
+ if (!ts.isBinaryExpression(expr)) return null
192
+ const target = skipParens(expr.left)
193
+ return ts.isIdentifier(target) && target.text === name && isPure(expr.right) ? expr : null
194
+ }
195
+
196
+ /** Statements in order: each reads the value the previous one left. */
197
+ function foldSequence(stmts: readonly ts.Statement[], name: string, current: Value, sf: ts.SourceFile): Value | null {
198
+ let value = current
199
+ for (const s of stmts) {
200
+ const next = foldStatement(s, name, value, sf)
201
+ if (next === null) return null
202
+ value = next
203
+ }
204
+ return value
205
+ }
206
+
207
+ /** A conditional evaluates its test, then only the branch it takes. `current` is trivial here. */
208
+ function foldIf(stmt: ts.IfStatement, name: string, current: Value, sf: ts.SourceFile): Value | null {
209
+ if (!isPure(stmt.expression)) return null
210
+ const whenTrue = foldStatement(stmt.thenStatement, name, current, sf)
211
+ if (whenTrue === null) return null
212
+ const whenFalse = stmt.elseStatement ? foldStatement(stmt.elseStatement, name, current, sf) : current
213
+ if (whenFalse === null) return null
214
+ const test = substitute(stmt.expression, name, current.text, sf)
215
+ return { text: `((${test.text}) ? (${whenTrue.text}) : (${whenFalse.text}))`, trivial: false }
216
+ }
217
+
218
+ /** `expr`'s source text with every read of `name` replaced by `(current)`, and how many reads there were. */
219
+ function substitute(expr: ts.Expression, name: string, current: string, sf: ts.SourceFile): { text: string; reads: number } {
220
+ const start = expr.getStart(sf)
221
+ const reads: ts.Identifier[] = []
222
+ const visit = (node: ts.Node): void => {
223
+ if (ts.isTypeNode(node)) return
224
+ if (ts.isIdentifier(node) && node.text === name && !isPropertyName(node)) reads.push(node)
225
+ ts.forEachChild(node, visit)
226
+ }
227
+ visit(expr)
228
+ let out = expr.getText(sf)
229
+ for (const id of [...reads].reverse()) {
230
+ const at = id.getStart(sf) - start
231
+ out = `${out.slice(0, at)}(${current})${out.slice(at + id.text.length)}`
232
+ }
233
+ return { text: out, reads: reads.length }
234
+ }
235
+
236
+ function isPropertyName(id: ts.Identifier): boolean {
237
+ const p = id.parent
238
+ return ts.isPropertyAccessExpression(p) && p.name === id
239
+ }
240
+
241
+ const PURE_LEAF_KINDS: ReadonlySet<ts.SyntaxKind> = new Set([
242
+ ts.SyntaxKind.Identifier,
243
+ ts.SyntaxKind.StringLiteral,
244
+ ts.SyntaxKind.NumericLiteral,
245
+ ts.SyntaxKind.BigIntLiteral,
246
+ ts.SyntaxKind.NoSubstitutionTemplateLiteral,
247
+ ts.SyntaxKind.TrueKeyword,
248
+ ts.SyntaxKind.FalseKeyword,
249
+ ts.SyntaxKind.NullKeyword,
250
+ ])
251
+
252
+ /**
253
+ * Whether evaluating `expr` has no side effects and reads nothing a
254
+ * statement between the declaration and the reassignment could change:
255
+ * identifiers, literals, member reads and operators only.
256
+ */
257
+ function isPure(expr: ts.Expression): boolean {
258
+ const e = skipParens(expr)
259
+ if (PURE_LEAF_KINDS.has(e.kind)) return true
260
+ const operands = pureOperands(e)
261
+ return operands !== null && operands.every(isPure)
262
+ }
263
+
264
+ /** The sub-expressions of a side-effect-free form, or `null` for any other form. */
265
+ function pureOperands(e: ts.Expression): readonly ts.Expression[] | null {
266
+ if (ts.isPropertyAccessExpression(e) || ts.isTypeOfExpression(e)) return [e.expression]
267
+ if (ts.isAsExpression(e) || ts.isNonNullExpression(e) || ts.isSatisfiesExpression(e)) return [e.expression]
268
+ if (ts.isElementAccessExpression(e)) return [e.expression, e.argumentExpression]
269
+ if (ts.isConditionalExpression(e)) return [e.condition, e.whenTrue, e.whenFalse]
270
+ if (ts.isTemplateExpression(e)) return e.templateSpans.map(s => s.expression)
271
+ if (ts.isPrefixUnaryExpression(e)) {
272
+ const sideEffect = e.operator === ts.SyntaxKind.PlusPlusToken || e.operator === ts.SyntaxKind.MinusMinusToken
273
+ return sideEffect ? null : [e.operand]
274
+ }
275
+ if (ts.isBinaryExpression(e)) return isPureOperator(e.operatorToken.kind) ? [e.left, e.right] : null
276
+ return null
277
+ }
278
+
279
+ /** A binary operator that neither assigns nor sequences. */
280
+ function isPureOperator(op: ts.SyntaxKind): boolean {
281
+ const isAssignment = op >= ts.SyntaxKind.FirstAssignment && op <= ts.SyntaxKind.LastAssignment
282
+ return !isAssignment && op !== ts.SyntaxKind.CommaToken
283
+ }
284
+
285
+ function skipParens(expr: ts.Expression): ts.Expression {
286
+ let e = expr
287
+ while (ts.isParenthesizedExpression(e)) e = e.expression
288
+ return e
289
+ }
290
+
291
+ function countNewlines(text: string): number {
292
+ let n = 0
293
+ for (const ch of text) if (ch === '\n') n++
294
+ return n
295
+ }
296
+
297
+ /**
298
+ * Blank each removed statement to spaces, keeping its newlines so later
299
+ * lines keep their numbers. `surplus` newlines the folded initializer added
300
+ * are taken back out of the blanked text (or, when negative, added to it).
301
+ */
302
+ function blankStatements(stmts: readonly ts.Statement[], sf: ts.SourceFile, surplus: number): Edit[] {
303
+ let pending = surplus
304
+ return stmts.map((s, k) => {
305
+ let text = ''
306
+ for (const ch of s.getText(sf)) {
307
+ if (ch !== '\n') text += ' '
308
+ else if (pending > 0) pending--
309
+ else text += '\n'
310
+ }
311
+ if (k === stmts.length - 1 && pending < 0) text += '\n'.repeat(-pending)
312
+ return { start: s.getStart(sf), end: s.getEnd(), text }
313
+ })
314
+ }
package/src/free-refs.ts CHANGED
@@ -425,3 +425,52 @@ export function resolveFreeRefs(
425
425
  ): FreeReference[] {
426
426
  return resolveFreeRefsInternal(node, env, new Set<string>())
427
427
  }
428
+
429
+ /**
430
+ * Replace the free references to a helper's parameters, inside the IR built
431
+ * from its inlined body, with the references of the call's arguments
432
+ * (#3509). `argRefs` maps each parameter name to its argument's resolved
433
+ * references. Rewrites `origin.freeRefs` (expressions, conditions, and any
434
+ * other node carrying an origin) and attribute `freeIdentifiers` in place,
435
+ * anywhere in the subtree.
436
+ */
437
+ export function rebindHelperParamRefs(root: unknown, argRefs: ReadonlyMap<string, readonly FreeReference[]>): void {
438
+ if (argRefs.size === 0) return
439
+ const seen = new WeakSet<object>()
440
+ const visit = (value: unknown): void => {
441
+ if (typeof value !== 'object' || value === null || seen.has(value)) return
442
+ seen.add(value)
443
+ if (Array.isArray(value)) {
444
+ for (const item of value) visit(item)
445
+ return
446
+ }
447
+ if (value instanceof Set || value instanceof Map) return
448
+ const node = value as { origin?: { freeRefs?: FreeReference[] }; freeIdentifiers?: ReadonlySet<string> }
449
+ if (node.origin?.freeRefs) node.origin.freeRefs = rebindRefs(node.origin.freeRefs, argRefs)
450
+ if (node.freeIdentifiers instanceof Set) node.freeIdentifiers = rebindIds(node.freeIdentifiers, argRefs)
451
+ for (const child of Object.values(value)) visit(child)
452
+ }
453
+ visit(root)
454
+ }
455
+
456
+ function rebindRefs(refs: FreeReference[], argRefs: ReadonlyMap<string, readonly FreeReference[]>): FreeReference[] {
457
+ if (!refs.some(r => argRefs.has(r.name))) return refs
458
+ const out: FreeReference[] = []
459
+ for (const ref of refs) {
460
+ const replacement = argRefs.get(ref.name)
461
+ if (!replacement) out.push(ref)
462
+ else for (const r of replacement) if (!out.some(o => o.name === r.name && o.kind === r.kind)) out.push(r)
463
+ }
464
+ return out
465
+ }
466
+
467
+ function rebindIds(ids: ReadonlySet<string>, argRefs: ReadonlyMap<string, readonly FreeReference[]>): ReadonlySet<string> {
468
+ if (![...ids].some(id => argRefs.has(id))) return ids
469
+ const out = new Set<string>()
470
+ for (const id of ids) {
471
+ const replacement = argRefs.get(id)
472
+ if (!replacement) out.add(id)
473
+ else for (const r of replacement) if (r.kind !== 'reactive-brand') out.add(r.name)
474
+ }
475
+ return out
476
+ }
package/src/index.ts CHANGED
@@ -145,6 +145,8 @@ export {
145
145
  isPredicateMethod,
146
146
  lowerCallbackMethod,
147
147
  nestedCallbackRefusal,
148
+ isUnloweredCall,
149
+ unloweredCallRefusal,
148
150
  sortEvalPlan,
149
151
  sortRefusal,
150
152
  } from './adapters/callback-method.ts'
@@ -169,9 +171,11 @@ export type {
169
171
  export { derivesScopeFromSlot } from './adapters/child-scope.ts'
170
172
  export { childTemplateName, componentPropKey, isEmptyComponentProps, planComponentProps, spellComponentProps } from './adapters/component-props.ts'
171
173
  export type { ComponentPropEntry, ComponentPropSegment, ComponentPropSpelling, ComponentPropsOptions, SpelledComponentPropSegment } from './adapters/component-props.ts'
172
- export { parseUndefinedAlternateTernary, planAttrExpression, planSpreadAttr, unsupportedAttrExpression } from './adapters/attr-plan.ts'
174
+ export { parseUndefinedAlternateTernary, planAttrExpression, planSpreadAttr, unsupportedAttrExpression, unsupportedAttrExpressionError } from './adapters/attr-plan.ts'
173
175
  export type { AttrExpressionPlan, AttrPlanContext, SpreadAttrPlan, SpreadPlanContext, UndefinedAlternateTernary } from './adapters/attr-plan.ts'
174
176
  export { planLoop } from './adapters/loop-plan.ts'
177
+ export { computedConstContext, inlineComputedConstAttr, inlineComputedConsts } from './adapters/computed-const.ts'
178
+ export type { ComputedConstContext } from './adapters/computed-const.ts'
175
179
  export type { LoopPlan, LoopPlanContext } from './adapters/loop-plan.ts'
176
180
  export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
177
181
  export {
@@ -225,7 +229,10 @@ export {
225
229
  resolveDangerousInnerHtml,
226
230
  dangerousInnerHtmlMetacharViolation,
227
231
  dangerousInnerHtmlDiagnostic,
232
+ renderDangerousInnerHtml,
228
233
  } from './adapters/dangerous-inner-html.ts'
234
+ export { renderElementAttributes, renderElementShell, renderFragmentScope } from './adapters/element-shell.ts'
235
+ export type { ElementShellSpelling } from './adapters/element-shell.ts'
229
236
  export type { DangerousInnerHtmlResolution } from './adapters/dangerous-inner-html.ts'
230
237
 
231
238
  // Client JS Generator
@@ -431,7 +438,7 @@ export { BOOLEAN_ATTRS, isBooleanAttr } from './html-constants.ts'
431
438
  export { USE_CLIENT_DIRECTIVE, CLIENT_EXPRESSION_DIRECTIVE } from './directives.ts'
432
439
 
433
440
  // Shared props-object-pattern helpers for the Go / Mojo template adapters
434
- export { augmentInheritedPropAccesses, parseRecordIndexAccess, evalStringArrayJoin, collectModuleStringConsts, lookupStaticRecordLiteral, lookupLiteralConst, collectContextConsumers } from './augment-inherited-props.ts'
441
+ export { augmentInheritedPropAccesses, parseRecordIndexAccess, evalStringArrayJoin, collectModuleStringConsts, lookupStaticRecordLiteral, lookupLiteralConst, collectContextConsumers, contextConsumerSeed } from './augment-inherited-props.ts'
435
442
  export type { RecordIndexAccess, RecordIndexEntry, ContextConsumer } from './augment-inherited-props.ts'
436
443
 
437
444
  // HTML element attribute types
@@ -296,19 +296,27 @@ export function computeInlinability(
296
296
  // here rather than calling `computeDeclarationScopes` a second time.
297
297
 
298
298
  const decisionsByName = new Map<string, RelocateDecision[]>()
299
- for (const c of ctx.localConstants) {
300
- const { status, decisions } = classifyConstantInitial(
301
- c,
302
- graph.declaredNames,
303
- signalGetters,
304
- signalSetters,
305
- memoNames,
306
- env,
307
- getterAliases,
308
- constantScope,
309
- )
310
- constants.set(c.name, status)
311
- decisionsByName.set(c.name, decisions)
299
+ // Constants are classified in declaration order, so a later const can see
300
+ // which earlier ones inline (#3513) and accept a method call on them.
301
+ const inlinableLocals = new Set<string>()
302
+ env.inlinableLocals = inlinableLocals
303
+ const classifyAll = (refused: ReadonlySet<string>) => {
304
+ inlinableLocals.clear()
305
+ for (const c of ctx.localConstants) {
306
+ const { status, decisions } = classifyConstantInitial(
307
+ c,
308
+ graph.declaredNames,
309
+ signalGetters,
310
+ signalSetters,
311
+ memoNames,
312
+ env,
313
+ getterAliases,
314
+ constantScope,
315
+ )
316
+ constants.set(c.name, status)
317
+ decisionsByName.set(c.name, decisions)
318
+ if (status.kind === 'inlinable' && !refused.has(c.name)) inlinableLocals.add(c.name)
319
+ }
312
320
  }
313
321
 
314
322
  const templateRiskyNames = collectTemplateRiskyNames(irRoot)
@@ -320,7 +328,21 @@ export function computeInlinability(
320
328
  // transformation. The map lives on `ClientJsContext` — not on the
321
329
  // cross-adapter `ConstantInfo` IR — so SSR adapters don't see CSR
322
330
  // substitution semantics they have no use for.
323
- populateCsrInlinable(ctx, env, getterAliases, constantScope)
331
+ //
332
+ // A const classified inlinable can still end with no CSR form here
333
+ // (`(choices).includes(name)` fails the post-substitution check). A
334
+ // method call on it was accepted on the provisional verdict, so it would
335
+ // read as `undefined.m()`: withdraw the receiver and classify again
336
+ // until no accepted receiver is refused. Each round removes at least one
337
+ // name, so this stops within `localConstants.length` rounds.
338
+ const refused = new Set<string>()
339
+ for (;;) {
340
+ classifyAll(refused)
341
+ populateCsrInlinable(ctx, env, getterAliases, constantScope)
342
+ const withdrawn = [...inlinableLocals].filter(name => ctx.csrInlinable.get(name) === null)
343
+ if (withdrawn.length === 0) break
344
+ for (const name of withdrawn) refused.add(name)
345
+ }
324
346
 
325
347
  return { constants, functions, decisionsByName, templateRiskyNames }
326
348
  }
@@ -381,6 +403,7 @@ function populateCsrInlinable(
381
403
  substitutions: new Map([...baseEnv.substitutions, ...constSubs]),
382
404
  propsObjectName: baseEnv.propsObjectName,
383
405
  })
406
+ const receivers = inlinedReceiverCheck(relocateEnv)
384
407
 
385
408
  // Pre-mark consts that are structurally ineligible — they record
386
409
  // `null` in `ctx.csrInlinable`. Mirrors `classifyConstantInitial`
@@ -473,11 +496,10 @@ function populateCsrInlinable(
473
496
  // `rewritePropsObjectRef` doesn't need to redo the AST work. The
474
497
  // free identifiers are re-extracted from the bridged form so
475
498
  // the post-substitution unsafe-name check stays exact.
476
- const inlineResult = isInlinableInTemplate(rewritten, relocateEnv)
477
- if (!inlineResult.ok) {
499
+ const bridgedRewritten = bridgedCsrForm(rewritten, source, env, relocateEnv, receivers)
500
+ if (bridgedRewritten === null) {
478
501
  ctx.csrInlinable.set(c.name, null)
479
502
  } else {
480
- const bridgedRewritten = inlineResult.rewrittenValue
481
503
  const bridgedFreeIdentifiers = recomputeFreeIdentifiers(bridgedRewritten, freeIdentifiers)
482
504
  ctx.csrInlinable.set(c.name, { rewrittenValue: bridgedRewritten, freeIdentifiers: bridgedFreeIdentifiers })
483
505
  constSubs.set(c.name, {
@@ -485,6 +507,7 @@ function populateCsrInlinable(
485
507
  replacement: bridgedRewritten,
486
508
  freeIdentifiers: bridgedFreeIdentifiers,
487
509
  })
510
+ receivers.add(c.name, bridgedRewritten)
488
511
  }
489
512
  finalised.add(c.name)
490
513
  progressed = true
@@ -500,6 +523,59 @@ function populateCsrInlinable(
500
523
  }
501
524
  }
502
525
 
526
+ /**
527
+ * The bridged CSR form of a const whose substituted text is `rewritten`, or
528
+ * null when it isn't safe in template scope.
529
+ */
530
+ function bridgedCsrForm(
531
+ rewritten: string,
532
+ source: string,
533
+ env: CsrEnv,
534
+ relocateEnv: RelocateEnv,
535
+ receivers: ReturnType<typeof inlinedReceiverCheck>,
536
+ ): string | null {
537
+ const inlineResult = isInlinableInTemplate(rewritten, relocateEnv)
538
+ return inlineResult.ok ? inlineResult.rewrittenValue : receivers.check(source, env)
539
+ }
540
+
541
+ /**
542
+ * The post-substitution check refuses a method call on an inlinable local
543
+ * (`text.toUpperCase()`, #3513): once `text` is substituted, the receiver
544
+ * is a parenthesized expression the adapter can't vouch for. `check`
545
+ * re-runs it with the receivers that already have a CSR form left as
546
+ * identifiers, so relocate's receiver rule decides the call and inlines
547
+ * each one as its `inline` form (an `inline` read inside a call argument
548
+ * still counts as bridged, #1138). A receiver whose own CSR form was
549
+ * refused is never added, so a call on it stays refused.
550
+ */
551
+ function inlinedReceiverCheck(relocateEnv: RelocateEnv): {
552
+ add: (name: string, bridged: string) => void
553
+ check: (source: string, env: CsrEnv) => string | null
554
+ } {
555
+ const inlined = new Map<string, string>()
556
+ const vetted = new Set<string>()
557
+ const receiverEnv: RelocateEnv = { ...relocateEnv, inlinable: inlined, inlinableLocals: vetted }
558
+ return {
559
+ add(name, bridged) {
560
+ // Only an init-local reaches relocate's receiver rule; a module
561
+ // const keeps the post-substitution verdict (#2106).
562
+ const kind = relocateEnv.bindings.get(name)
563
+ if (kind !== 'init-local' && kind !== 'sub-init-local') return
564
+ if (relocateEnv.inlinableLocals?.has(name) !== true) return
565
+ vetted.add(name)
566
+ inlined.set(name, `(${bridged})`)
567
+ },
568
+ check(source, env) {
569
+ if (vetted.size === 0) return null
570
+ const substitutions = new Map(env.substitutions)
571
+ for (const name of vetted) substitutions.delete(name)
572
+ const partial = csrSubstitute(source, { substitutions, propsObjectName: env.propsObjectName }).rewritten
573
+ const result = isInlinableInTemplate(partial, receiverEnv)
574
+ return result.ok ? result.rewrittenValue : null
575
+ },
576
+ }
577
+ }
578
+
503
579
  /**
504
580
  * Recompute free identifiers after `relocate` has rewritten bare prop
505
581
  * refs to `_p.X`. The pre-rewrite free-id set may still mention the
@@ -26,7 +26,7 @@
26
26
  */
27
27
 
28
28
  import ts from 'typescript'
29
- import { inferDefaultValue } from './utils.ts'
29
+ import { inferDefaultValue, readsBareProp } from './utils.ts'
30
30
  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'
@@ -295,7 +295,7 @@ function csrSubstituteOnce(
295
295
  // Arrow function: bind params + any block-scoped locals declared
296
296
  // inside the body, recurse, unbind. Pre-collecting body locals
297
297
  // before descending matters for the IIFE shape that
298
- // `extractMemoBodyExpr` produces for non-trivial memo bodies:
298
+ // `MemoInfo.bodyExpr` carries for non-trivial memo bodies:
299
299
  //
300
300
  // (() => { const items = foo; return items.length })()
301
301
  //
@@ -457,28 +457,6 @@ export function extractFreeIdentifiersFromTemplateText(template: string): Set<st
457
457
  return ids
458
458
  }
459
459
 
460
- /**
461
- * Reduce a memo's `() => expr` source to the expression that should be
462
- * substituted in for `memoName()`. Matches the extraction done by the
463
- * legacy `buildSignalAndMemoMaps` in `emit-registration.ts`:
464
- *
465
- * - `() => expr` → `expr`
466
- * - `() => { return e; }` → `e`
467
- * - `() => { ...complex... }` → `(() => { ...complex... })()`
468
- *
469
- * The IIFE form for non-trivial blocks keeps intermediate `const`/`let`
470
- * bindings in scope; inlining the block bare would dangle them.
471
- */
472
- export function extractMemoBodyExpr(computation: string): string {
473
- const arrowMatch = computation.match(/^\(\)\s*=>\s*(.+)$/s)
474
- if (!arrowMatch) return computation
475
- const body = arrowMatch[1].trim()
476
- if (!body.startsWith('{')) return body
477
- const simpleReturn = body.match(/^\{\s*return\s+([\s\S]+?)\s*;?\s*\}$/)
478
- if (simpleReturn) return simpleReturn[1]
479
- return `(() => ${body})()`
480
- }
481
-
482
460
  /**
483
461
  * Which local consts are bare alias-hop chains that ultimately name a
484
462
  * substitutable signal/memo getter (`isGetter`) — e.g. `const
@@ -587,7 +565,7 @@ export function buildSignalMemoEnv(
587
565
  if (s.envReader) continue
588
566
  substitutions.set(s.getter, {
589
567
  kind: 'call',
590
- replacement: normalizeSignalInitial(s, propsObjectName),
568
+ replacement: normalizeSignalInitial(s),
591
569
  freeIdentifiers: s.initialFreeIdentifiers ?? new Set(),
592
570
  })
593
571
  // A bare reference to the SETTER (`<Display update={setCount} />`,
@@ -612,12 +590,13 @@ export function buildSignalMemoEnv(
612
590
  for (const m of memos) {
613
591
  substitutions.set(m.name, {
614
592
  kind: 'call',
615
- // Destructured mode (#2468): `templateComputation` (when present) has
593
+ // Destructured mode (#2468): `templateBodyExpr` (when present) has
616
594
  // bare destructured prop refs already rewritten to `_p.X` — the
617
595
  // spliced body lands in the module-scope template arrow, which is not
618
596
  // a closure over init's `const value = _p.value` extraction. Mirrors
619
- // the signal `templateInitialValue` handling above (#2265).
620
- replacement: extractMemoBodyExpr(m.templateComputation ?? m.computation),
597
+ // the signal `templateInitialValue` handling above (#2265). The body
598
+ // itself is read from the callback node by the analyzer (#3510).
599
+ replacement: m.templateBodyExpr ?? m.bodyExpr ?? 'undefined',
621
600
  freeIdentifiers: m.computationFreeIdentifiers ?? new Set(),
622
601
  })
623
602
  }
@@ -629,7 +608,8 @@ export function buildSignalMemoEnv(
629
608
 
630
609
  /**
631
610
  * Add the `?? <default>` SSR fallback to a signal's initial value when
632
- * the value is a bare `propsName.X` reference. Returns the value in raw
611
+ * the value is a bare `propsName.X` reference (`readsBareProp`, read from
612
+ * the analyzer's `SignalInfo.propSeed`, #3508). Returns the value in raw
633
613
  * (props.X) form — the `propsObjectName → _p` rewrite is deferred to
634
614
  * `rewritePropsObjectRef` at emit time so the post-substitution
635
615
  * `isInlinableInTemplate` check still sees bridged-arg shapes (#1138).
@@ -637,17 +617,15 @@ export function buildSignalMemoEnv(
637
617
  * The `??` fallback prevents literal `undefined` from leaking into the
638
618
  * SSR HTML when the prop is omitted — `inferDefaultValue` picks a
639
619
  * type-appropriate sentinel (`0` for number, `''` for string, etc.).
640
- * Skipped when the value already carries its own `??` so user-supplied
641
- * defaults aren't masked.
620
+ * Skipped when the value carries a fallback of its own (`??` / `||`) so
621
+ * user-supplied defaults aren't masked.
642
622
  */
643
- function normalizeSignalInitial(signal: SignalInfo, propsObjectName: string | null): string {
623
+ function normalizeSignalInitial(signal: SignalInfo): string {
644
624
  const initialValue = signal.initialValue
645
- const propsName = propsObjectName ?? 'props'
646
- const propsPrefix = `${propsName}.`
647
625
  // An async factory's `initial` (#3165) renders exactly as given: an absent
648
626
  // prop means no obtained result, so the value is `undefined` on the server
649
627
  // too, never a type default.
650
- if (!signal.factory && initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
628
+ if (!signal.factory && readsBareProp(signal)) {
651
629
  return `${initialValue} ?? ${inferDefaultValue(signal.type)}`
652
630
  }
653
631
  // Destructured mode (#2265): `templateInitialValue` (when present) has