@barefootjs/jsx 0.39.6 → 0.39.8

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 (192) 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 +44 -0
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/component-props.d.ts +80 -13
  6. package/dist/adapters/component-props.d.ts.map +1 -1
  7. package/dist/adapters/computed-const.d.ts +52 -0
  8. package/dist/adapters/computed-const.d.ts.map +1 -0
  9. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  10. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts +151 -0
  12. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  13. package/dist/adapters/element-shell.d.ts +44 -0
  14. package/dist/adapters/element-shell.d.ts.map +1 -0
  15. package/dist/adapters/interface.d.ts +2 -0
  16. package/dist/adapters/interface.d.ts.map +1 -1
  17. package/dist/adapters/jsx-adapter.d.ts +4 -0
  18. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  19. package/dist/adapters/literal-value.d.ts +2 -2
  20. package/dist/adapters/literal-value.d.ts.map +1 -1
  21. package/dist/adapters/parsed-expr-emitter.d.ts +27 -0
  22. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  23. package/dist/adapters/style-object.d.ts +33 -0
  24. package/dist/adapters/style-object.d.ts.map +1 -0
  25. package/dist/analyzer.d.ts.map +1 -1
  26. package/dist/augment-inherited-props.d.ts +7 -0
  27. package/dist/augment-inherited-props.d.ts.map +1 -1
  28. package/dist/children-nullish.d.ts +22 -0
  29. package/dist/children-nullish.d.ts.map +1 -0
  30. package/dist/errors.d.ts +1 -0
  31. package/dist/errors.d.ts.map +1 -1
  32. package/dist/expression-parser.d.ts +9 -19
  33. package/dist/expression-parser.d.ts.map +1 -1
  34. package/dist/fold-render-reassignments.d.ts +43 -0
  35. package/dist/fold-render-reassignments.d.ts.map +1 -0
  36. package/dist/free-refs.d.ts +15 -0
  37. package/dist/free-refs.d.ts.map +1 -1
  38. package/dist/index.d.ts +21 -14
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +24620 -23233
  41. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  43. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  45. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  48. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  50. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  52. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  54. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/html-template.d.ts +9 -19
  57. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  59. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/imports.d.ts +23 -2
  61. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  62. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -2
  64. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  66. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  67. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  68. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  70. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  72. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  73. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  74. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  75. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  76. package/dist/ir-to-client-js/types.d.ts +3 -3
  77. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  78. package/dist/ir-to-client-js/utils.d.ts +15 -11
  79. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  80. package/dist/jsx-to-ir.d.ts.map +1 -1
  81. package/dist/nullable-signal-attr.d.ts +43 -12
  82. package/dist/nullable-signal-attr.d.ts.map +1 -1
  83. package/dist/prop-rewrite.d.ts +18 -0
  84. package/dist/prop-rewrite.d.ts.map +1 -1
  85. package/dist/props-binding.d.ts +43 -6
  86. package/dist/props-binding.d.ts.map +1 -1
  87. package/dist/relocate.d.ts +16 -0
  88. package/dist/relocate.d.ts.map +1 -1
  89. package/dist/scanner/js-scanner.d.ts.map +1 -1
  90. package/dist/scanner/js-scanner.js +30 -2
  91. package/dist/signal-prop-name-collision.d.ts +6 -5
  92. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  93. package/dist/ssr-defaults.d.ts +28 -0
  94. package/dist/ssr-defaults.d.ts.map +1 -1
  95. package/dist/ssr-seed-plan.d.ts +37 -18
  96. package/dist/ssr-seed-plan.d.ts.map +1 -1
  97. package/dist/types.d.ts +162 -20
  98. package/dist/types.d.ts.map +1 -1
  99. package/dist/value-references.d.ts +21 -0
  100. package/dist/value-references.d.ts.map +1 -1
  101. package/package.json +2 -2
  102. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  103. package/src/__tests__/adapter-output.test.ts +5 -3
  104. package/src/__tests__/analyzer.test.ts +33 -0
  105. package/src/__tests__/arithmetic-lowering.test.ts +44 -0
  106. package/src/__tests__/block-memo-type.test.ts +51 -0
  107. package/src/__tests__/callback-method.test.ts +75 -0
  108. package/src/__tests__/children-read.test.ts +226 -0
  109. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  110. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  111. package/src/__tests__/component-props.test.ts +68 -1
  112. package/src/__tests__/computed-const.test.ts +101 -0
  113. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  114. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  115. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  116. package/src/__tests__/element-shell.test.ts +78 -0
  117. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  118. package/src/__tests__/expression-parser.test.ts +1 -44
  119. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  120. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  121. package/src/__tests__/memo-body-expr.test.ts +120 -0
  122. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  123. package/src/__tests__/prop-handling.test.ts +35 -16
  124. package/src/__tests__/props-alias-const.test.ts +65 -0
  125. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  126. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  127. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  128. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +173 -1
  131. package/src/__tests__/static-template-reachability.test.ts +137 -0
  132. package/src/__tests__/style-object-plan.test.ts +54 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/attr-plan.ts +29 -1
  135. package/src/adapters/callback-method.ts +85 -0
  136. package/src/adapters/component-props.ts +130 -12
  137. package/src/adapters/computed-const.ts +185 -0
  138. package/src/adapters/dangerous-inner-html.ts +33 -0
  139. package/src/adapters/dsl-template-adapter.ts +248 -0
  140. package/src/adapters/element-shell.ts +160 -0
  141. package/src/adapters/interface.ts +8 -0
  142. package/src/adapters/jsx-adapter.ts +12 -6
  143. package/src/adapters/literal-value.ts +2 -2
  144. package/src/adapters/parsed-expr-emitter.ts +34 -0
  145. package/src/adapters/style-object.ts +61 -0
  146. package/src/analyzer.ts +382 -94
  147. package/src/augment-inherited-props.ts +12 -0
  148. package/src/children-nullish.ts +33 -0
  149. package/src/debug.ts +2 -2
  150. package/src/errors.ts +12 -0
  151. package/src/expression-parser.ts +56 -53
  152. package/src/fold-render-reassignments.ts +314 -0
  153. package/src/free-refs.ts +77 -17
  154. package/src/index.ts +27 -10
  155. package/src/ir-to-client-js/compute-inlinability.ts +122 -19
  156. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  157. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  159. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  160. package/src/ir-to-client-js/csr-substitute.ts +25 -37
  161. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  162. package/src/ir-to-client-js/emit-registration.ts +31 -59
  163. package/src/ir-to-client-js/generate-init.ts +17 -1
  164. package/src/ir-to-client-js/html-template.ts +56 -120
  165. package/src/ir-to-client-js/identifiers.ts +75 -24
  166. package/src/ir-to-client-js/imports.ts +56 -19
  167. package/src/ir-to-client-js/index.ts +5 -3
  168. package/src/ir-to-client-js/init-declarations.ts +1 -1
  169. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  170. package/src/ir-to-client-js/phases/props-extraction.ts +16 -15
  171. package/src/ir-to-client-js/plan/build-declaration-emit.ts +26 -52
  172. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  173. package/src/ir-to-client-js/prop-handling.ts +13 -54
  174. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  175. package/src/ir-to-client-js/reactivity.ts +2 -2
  176. package/src/ir-to-client-js/rewrite-destructured-props.ts +27 -9
  177. package/src/ir-to-client-js/safe-html.ts +29 -35
  178. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  179. package/src/ir-to-client-js/types.ts +3 -2
  180. package/src/ir-to-client-js/utils.ts +13 -26
  181. package/src/jsx-to-ir.ts +318 -130
  182. package/src/nullable-signal-attr.ts +156 -37
  183. package/src/prop-rewrite.ts +41 -0
  184. package/src/props-binding.ts +117 -7
  185. package/src/relocate.ts +40 -8
  186. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  187. package/src/scanner/js-scanner.ts +64 -4
  188. package/src/signal-prop-name-collision.ts +50 -24
  189. package/src/ssr-defaults.ts +47 -20
  190. package/src/ssr-seed-plan.ts +121 -29
  191. package/src/types.ts +165 -21
  192. package/src/value-references.ts +132 -0
@@ -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'
@@ -102,6 +102,15 @@ export interface CsrEnv {
102
102
  propsObjectName: string | null
103
103
  }
104
104
 
105
+ /**
106
+ * The value positions of an object-literal `key: value` entry: the value,
107
+ * and a computed key's expression (`{ [size]: value }`, #3535). A plain key
108
+ * is a name, never a reference.
109
+ */
110
+ function propertyValueExpressions(node: ts.PropertyAssignment): ts.Expression[] {
111
+ return ts.isComputedPropertyName(node.name) ? [node.name.expression, node.initializer] : [node.initializer]
112
+ }
113
+
105
114
  /**
106
115
  * Substitute an expression for CSR template scope. Returns the rewritten
107
116
  * text plus the free identifiers of the rewritten form.
@@ -264,9 +273,10 @@ function csrSubstituteOnce(
264
273
  }
265
274
 
266
275
  // Property assignment in object literal: `{ X: value }` — `X` is a
267
- // key, not a free ref. `value` is.
276
+ // key, not a free ref. `value` is, and so is a computed key's
277
+ // expression (`{ [size]: value }`, #3535).
268
278
  if (ts.isPropertyAssignment(node)) {
269
- visit(node.initializer)
279
+ propertyValueExpressions(node).forEach(visit)
270
280
  return
271
281
  }
272
282
 
@@ -295,7 +305,7 @@ function csrSubstituteOnce(
295
305
  // Arrow function: bind params + any block-scoped locals declared
296
306
  // inside the body, recurse, unbind. Pre-collecting body locals
297
307
  // before descending matters for the IIFE shape that
298
- // `extractMemoBodyExpr` produces for non-trivial memo bodies:
308
+ // `MemoInfo.bodyExpr` carries for non-trivial memo bodies:
299
309
  //
300
310
  // (() => { const items = foo; return items.length })()
301
311
  //
@@ -457,28 +467,6 @@ export function extractFreeIdentifiersFromTemplateText(template: string): Set<st
457
467
  return ids
458
468
  }
459
469
 
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
470
  /**
483
471
  * Which local consts are bare alias-hop chains that ultimately name a
484
472
  * substitutable signal/memo getter (`isGetter`) — e.g. `const
@@ -587,7 +575,7 @@ export function buildSignalMemoEnv(
587
575
  if (s.envReader) continue
588
576
  substitutions.set(s.getter, {
589
577
  kind: 'call',
590
- replacement: normalizeSignalInitial(s, propsObjectName),
578
+ replacement: normalizeSignalInitial(s),
591
579
  freeIdentifiers: s.initialFreeIdentifiers ?? new Set(),
592
580
  })
593
581
  // A bare reference to the SETTER (`<Display update={setCount} />`,
@@ -612,12 +600,13 @@ export function buildSignalMemoEnv(
612
600
  for (const m of memos) {
613
601
  substitutions.set(m.name, {
614
602
  kind: 'call',
615
- // Destructured mode (#2468): `templateComputation` (when present) has
603
+ // Destructured mode (#2468): `templateBodyExpr` (when present) has
616
604
  // bare destructured prop refs already rewritten to `_p.X` — the
617
605
  // spliced body lands in the module-scope template arrow, which is not
618
606
  // 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),
607
+ // the signal `templateInitialValue` handling above (#2265). The body
608
+ // itself is read from the callback node by the analyzer (#3510).
609
+ replacement: m.templateBodyExpr ?? m.bodyExpr ?? 'undefined',
621
610
  freeIdentifiers: m.computationFreeIdentifiers ?? new Set(),
622
611
  })
623
612
  }
@@ -629,7 +618,8 @@ export function buildSignalMemoEnv(
629
618
 
630
619
  /**
631
620
  * 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
621
+ * the value is a bare `propsName.X` reference (`readsBareProp`, read from
622
+ * the analyzer's `SignalInfo.propSeed`, #3508). Returns the value in raw
633
623
  * (props.X) form — the `propsObjectName → _p` rewrite is deferred to
634
624
  * `rewritePropsObjectRef` at emit time so the post-substitution
635
625
  * `isInlinableInTemplate` check still sees bridged-arg shapes (#1138).
@@ -637,17 +627,15 @@ export function buildSignalMemoEnv(
637
627
  * The `??` fallback prevents literal `undefined` from leaking into the
638
628
  * SSR HTML when the prop is omitted — `inferDefaultValue` picks a
639
629
  * 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.
630
+ * Skipped when the value carries a fallback of its own (`??` / `||`) so
631
+ * user-supplied defaults aren't masked.
642
632
  */
643
- function normalizeSignalInitial(signal: SignalInfo, propsObjectName: string | null): string {
633
+ function normalizeSignalInitial(signal: SignalInfo): string {
644
634
  const initialValue = signal.initialValue
645
- const propsName = propsObjectName ?? 'props'
646
- const propsPrefix = `${propsName}.`
647
635
  // An async factory's `initial` (#3165) renders exactly as given: an absent
648
636
  // prop means no obtained result, so the value is `undefined` on the server
649
637
  // too, never a type default.
650
- if (!signal.factory && initialValue.startsWith(propsPrefix) && !initialValue.includes('??')) {
638
+ if (!signal.factory && readsBareProp(signal)) {
651
639
  return `${initialValue} ?? ${inferDefaultValue(signal.type)}`
652
640
  }
653
641
  // Destructured mode (#2265): `templateInitialValue` (when present) has
@@ -5,7 +5,7 @@
5
5
  */
6
6
 
7
7
  import ts from 'typescript'
8
- import type { AttrMeta, IRMetadata } from '../types.ts'
8
+ import { type AttrMeta, type IRMetadata, isChildrenPropParam } from '../types.ts'
9
9
  import { isBooleanAttr } from '../html-constants.ts'
10
10
  import type { ClientJsContext } from './types.ts'
11
11
  import { toHtmlAttrName, varSlotId, PROPS_PARAM } from './utils.ts'
@@ -327,7 +327,7 @@ export function rewriteDestructuredPropsInExpr(expr: string, ctx: ClientJsContex
327
327
  const propAliases = new Map<string, string>()
328
328
  const propsByName = new Map<string, ClientJsContext['propsParams'][number]>()
329
329
  for (const prop of ctx.propsParams) {
330
- if (prop.name === 'children') continue
330
+ if (isChildrenPropParam(prop)) continue
331
331
  propNames.add(prop.name)
332
332
  propsByName.set(prop.name, prop)
333
333
  // `_p` is always keyed by the caller-facing name (#2524 CSR half).
@@ -7,73 +7,45 @@
7
7
  import type { ComponentIR, IRNode, ReferencesGraph, SignalInfo } from '../types.ts'
8
8
  import type { ClientJsContext } from './types.ts'
9
9
  import { PROPS_PARAM, componentDefScopeFlags, initFunctionName } from './utils.ts'
10
+ import { collectReactiveGetterNames } from '../analyzer-context.ts'
10
11
  import { computeInlinability, toLegacyInlinability } from './compute-inlinability.ts'
11
- import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate, createStringProtector } from './html-template.ts'
12
+ import { canGenerateStaticTemplate, irToComponentTemplate, generateCsrTemplate } from './html-template.ts'
13
+ import { csrSubstitute, type CsrEnv } from './csr-substitute.ts'
12
14
  import { markupSlotIdsOf } from './markup-slots.ts'
13
15
  import { nameForRegistryRef } from './component-scope.ts'
14
16
  import { resolveRestSpreadNames } from './prop-handling.ts'
15
17
 
16
18
  /**
17
19
  * Resolve chained references within a constants map.
18
- * If constant A references constant B, replace B's name in A's value with B's resolved value.
19
- * Uses pre-computed freeIdentifiers to skip unnecessary regex replacements.
20
+ * If constant A references constant B, replace B's name in A's value with
21
+ * B's resolved value. The substitution runs on the expression tree
22
+ * (`csrSubstitute`), so a constant's name inside a string or template
23
+ * literal, a member name, or a binding that shadows it is never replaced,
24
+ * and an object-literal shorthand expands to `name: (value)` (#3535).
20
25
  *
21
- * When `freeIdsMap` is supplied, it is updated in place: each substitution
22
- * removes the substituted name from the resolving constant's free-id set
23
- * and unions in the substituted constant's own free ids. The result is a
24
- * transitively-closed free-id map that downstream callers
25
- * (`toLegacyInlinability` unsafe-ref check, #1267) can read without
26
- * re-scanning the resolved string.
26
+ * When `freeIdsMap` is supplied, it is updated in place to the free
27
+ * identifiers of each resolved value, so downstream callers
28
+ * (`toLegacyInlinability` unsafe-ref check, #1267) can read a
29
+ * transitively-closed free-id map without re-scanning the resolved string.
30
+ * A constant whose recorded free ids name no other constant is skipped.
27
31
  */
28
32
  export function resolveChainedRefs(constants: Map<string, string>, freeIdsMap?: Map<string, Set<string>>): void {
29
- let changed = true
30
- const maxIterations = constants.size + 1
31
- let iteration = 0
32
- while (changed && iteration < maxIterations) {
33
- changed = false
34
- iteration++
35
- for (const [constName, constValue] of constants) {
36
- // String literal values (single/double quoted) cannot contain variable references.
37
- // Skip them to avoid corrupting CSS class names like "size-4" when a constant
38
- // named "size" exists (the regex would falsely match "size" in "size-4").
39
- const trimmed = constValue.trim()
40
- if ((trimmed.startsWith("'") && trimmed.endsWith("'")) ||
41
- (trimmed.startsWith('"') && trimmed.endsWith('"'))) {
42
- continue
43
- }
44
-
45
- // Protect string literals within compound values (e.g., Record objects
46
- // containing 'size-4') from regex-based identifier replacement
47
- const { protect, restore } = createStringProtector()
48
- let newValue = protect(constValue)
49
- const freeIds = freeIdsMap?.get(constName)
50
- for (const [otherName, otherValue] of constants) {
51
- if (otherName === constName) continue
52
- // Use freeIdentifiers to skip constants that are definitely not referenced.
53
- // On subsequent iterations the value may have been expanded beyond what
54
- // freeIdentifiers tracks, so fall through to regex when freeIds is unavailable
55
- // or when the iteration is > 1 (values have been mutated).
56
- if (freeIds && iteration === 1 && !freeIds.has(otherName)) continue
57
- const replaced = newValue.replace(new RegExp(`(?<![-.])\\b${otherName}\\b`, 'g'), `(${protect(otherValue)})`)
58
- if (replaced !== newValue) {
59
- newValue = replaced
60
- changed = true
61
- // Maintain a transitively-closed free-id set on the resolving
62
- // constant: drop the substituted name, union in the substituted
63
- // constant's own free ids.
64
- if (freeIds) {
65
- freeIds.delete(otherName)
66
- const otherFreeIds = freeIdsMap?.get(otherName)
67
- if (otherFreeIds) {
68
- for (const id of otherFreeIds) freeIds.add(id)
69
- }
70
- }
71
- }
72
- }
73
- newValue = restore(newValue)
74
- if (newValue !== constValue) {
75
- constants.set(constName, newValue)
76
- }
33
+ for (const [constName, constValue] of constants) {
34
+ const freeIds = freeIdsMap?.get(constName)
35
+ if (freeIds && ![...freeIds].some(id => id !== constName && constants.has(id))) continue
36
+ // Every other constant, not only the recorded free ids: a substituted
37
+ // value can bring in a name the original value did not mention.
38
+ const env: CsrEnv = { substitutions: new Map(), propsObjectName: null }
39
+ for (const [otherName, otherValue] of constants) {
40
+ if (otherName === constName) continue
41
+ env.substitutions.set(otherName, { kind: 'identifier', replacement: otherValue, freeIdentifiers: new Set() })
42
+ }
43
+ const { rewritten, freeIdentifiers } = csrSubstitute(constValue, env)
44
+ if (rewritten === constValue) continue
45
+ constants.set(constName, rewritten)
46
+ if (freeIds) {
47
+ freeIds.clear()
48
+ for (const id of freeIdentifiers) freeIds.add(id)
77
49
  }
78
50
  }
79
51
  }
@@ -190,7 +162,7 @@ export function emitRegistrationAndHydration(
190
162
  lines.push(`}`)
191
163
  lines.push('')
192
164
 
193
- const propNamesForStaticCheck = new Set(ctx.propsParams.map((p) => p.name))
165
+ const reactiveGetterNames = collectReactiveGetterNames(ctx.signals, ctx.memos)
194
166
  const { inlinableConstants, unsafeLocalNames } = inlinability ?? buildInlinableConstants(ctx, graph, _ir.root)
195
167
 
196
168
  // Build rest spread names: these are rest/props spreads handled by
@@ -219,7 +191,7 @@ export function emitRegistrationAndHydration(
219
191
 
220
192
  // Build ComponentDef object for hydrate()
221
193
  const defParts: string[] = [`init: ${initFunctionName(name)}`]
222
- if (canGenerateStaticTemplate(_ir.root, propNamesForStaticCheck, inlinableConstants, unsafeLocalNames)) {
194
+ if (canGenerateStaticTemplate(_ir.root, reactiveGetterNames, inlinableConstants, unsafeLocalNames)) {
223
195
  const markupSlotIds = markupSlotIdsOf(ctx)
224
196
  const templateHtml = irToComponentTemplate(_ir.root, inlinableConstants, restSpreadNames, ctx.propsObjectName, markupSlotIds, ctx.restPropsName)
225
197
  if (templateHtml) {
@@ -13,7 +13,8 @@ import type { ClientJsContext } from './types.ts'
13
13
  import { PROPS_PARAM, isCommentScopedRoot, initFunctionName } from './utils.ts'
14
14
  import { buildReferencesGraph } from './build-references.ts'
15
15
  import { computePropUsage } from './compute-prop-usage.ts'
16
- import { IMPORT_PLACEHOLDER, MODULE_CONSTANTS_PLACEHOLDER } from './imports.ts'
16
+ import { IMPORT_PLACEHOLDER, MODULE_CONSTANTS_PLACEHOLDER, runtimeNameCollisions } from './imports.ts'
17
+ import { signalSecondBinding } from '../signal-initializer.ts'
17
18
  import { emitRegistrationAndHydration, csrInlinableConstantsFromCtx } from './emit-registration.ts'
18
19
  import { computeDeferredChildSlots } from './html-template.ts'
19
20
  import { emitChildComponentImports } from './child-components.ts'
@@ -137,6 +138,21 @@ export function generateInitFunction(
137
138
  const codeWithModuleConstants = pruneUnusedPropExtractions(
138
139
  generatedCode.replace(MODULE_CONSTANTS_PLACEHOLDER, () => moduleConstantsCode),
139
140
  )
141
+ ctx.warnings.push(
142
+ ...runtimeNameCollisions(
143
+ [
144
+ ...classification.moduleLevelConstants,
145
+ ...classification.moduleLevelFunctions,
146
+ ...classification.moduleLevelSignals.flatMap(s => {
147
+ const second = signalSecondBinding(s)
148
+ return [{ name: s.getter, loc: s.loc }, ...(second ? [{ name: second, loc: s.loc }] : [])]
149
+ }),
150
+ ...classification.moduleLevelMemos,
151
+ ],
152
+ ir.metadata.imports,
153
+ codeWithModuleConstants,
154
+ ),
155
+ )
140
156
  const allImportLines = resolveFinalImports(codeWithModuleConstants, ir, localImportPrefixes)
141
157
 
142
158
  return codeWithModuleConstants.replace(IMPORT_PLACEHOLDER, () => allImportLines)
@@ -2,7 +2,7 @@
2
2
  * IR → HTML template string generation and validation.
3
3
  */
4
4
 
5
- import type { AttrValue, FlatMapCallback, IRAttribute, IRElement, IRExpression, IRNode, IRProp, MapCallbackPreamble } from '../types.ts'
5
+ import type { AttrValue, FlatMapCallback, IRAttribute, IRElement, IRExpression, IRNode, IRProp, MapCallbackPreamble, JsSourceText } from '../types.ts'
6
6
  import { isBooleanAttr } from '../html-constants.ts'
7
7
  import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_PH, keyAttrName, loopStartMarker, loopEndMarker, loopItemMarker, freeIdsFromRefs, setIntersects, wrapExprWithLoopParams, specsInsideRow } from './utils.ts'
8
8
  import type { LoopParamSpec } from './utils.ts'
@@ -19,29 +19,6 @@ import { interp, spliceChildValue, conditionalMarkup, renderChildCall, mappedRow
19
19
  import { markupSlotIdsOf } from './markup-slots.ts'
20
20
  import { isEventHandlerName } from '../event-handler-name.ts'
21
21
 
22
- /**
23
- * Protect string literals from regex-based replacements.
24
- * Returns protect/restore functions that extract string literals before
25
- * regex replacements and restore them after.
26
- */
27
- export function createStringProtector(): {
28
- protect: (s: string) => string
29
- restore: (s: string) => string
30
- } {
31
- const strings: string[] = []
32
- const protect = (s: string): string => {
33
- return s.replace(/'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g, (match) => {
34
- const idx = strings.length
35
- strings.push(match)
36
- return `__STRLIT_${idx}__`
37
- })
38
- }
39
- const restore = (s: string): string => {
40
- return s.replace(/__STRLIT_(\d+)__/g, (_, idx) => strings[Number(idx)])
41
- }
42
- return { protect, restore }
43
- }
44
-
45
22
  /**
46
23
  * Split a template literal body into static segments and `${...}` interpolations,
47
24
  * correctly handling nested braces (e.g. object literals inside interpolations).
@@ -327,7 +304,7 @@ function escapeAttrValueExpr(valExpr: string): string {
327
304
  */
328
305
  function dangerouslyHtmlChildren(
329
306
  attrs: ReadonlyArray<IRAttribute>,
330
- toExpr: (v: { expr: string; templateExpr?: string }) => string,
307
+ toExpr: (v: { expr: JsSourceText; templateExpr?: JsSourceText }) => string,
331
308
  ): string | null {
332
309
  const attr = attrs.find(a => a.name === 'dangerouslySetInnerHTML')
333
310
  if (!attr || attr.value.kind !== 'expression') return null
@@ -341,7 +318,7 @@ function dangerouslyHtmlChildren(
341
318
  * template path; for non-`expression`/`spread`/`template` variants we
342
319
  * delegate to the canonical projection.
343
320
  */
344
- function transformKeyValue(value: AttrValue, transformExpr: (expr: string, templateExpr?: string) => string): string {
321
+ function transformKeyValue(value: AttrValue, transformExpr: (expr: JsSourceText, templateExpr?: JsSourceText) => string): string {
345
322
  switch (value.kind) {
346
323
  case 'expression':
347
324
  case 'spread':
@@ -1838,8 +1815,22 @@ export function irToComponentTemplate(
1838
1815
  return irToComponentTemplateWithOpts(node, { inlinableConstants, restSpreadNames, propsObjectName, loopDepth: -1, markupSlotIds, restPropsName })
1839
1816
  }
1840
1817
 
1818
+ /**
1819
+ * The `csrSubstitute` environment that inlines each template constant by
1820
+ * name (#3535), or null when there is none to inline.
1821
+ */
1822
+ function inlinableConstantEnv(inlinableConstants: ReadonlyMap<string, string> | undefined): CsrEnv | null {
1823
+ if (!inlinableConstants || inlinableConstants.size === 0) return null
1824
+ const substitutions = new Map<string, CsrSubstitution>()
1825
+ for (const [name, value] of inlinableConstants) {
1826
+ substitutions.set(name, { kind: 'identifier', replacement: value, freeIdentifiers: new Set() })
1827
+ }
1828
+ return { substitutions, propsObjectName: null }
1829
+ }
1830
+
1841
1831
  function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): string {
1842
1832
  const { inlinableConstants, restSpreadNames, propsObjectName, restPropsName, loopDepth = 0 } = opts
1833
+ const constantEnv = inlinableConstantEnv(inlinableConstants)
1843
1834
  // `recurse` preserves `inHoistedChildren` for structural pass-through
1844
1835
  // (fragment / conditional); `childrenRecurse` clears it so element
1845
1836
  // descendants don't re-emit the placeholder. (#1320)
@@ -1849,29 +1840,19 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1849
1840
  // Bare prop name prefixing (org → _p.org) is handled by templateExpr
1850
1841
  // from Phase 1 AST rewrite. Only constant inlining and props object
1851
1842
  // normalization are done here. (#807)
1852
- const transformExpr = (expr: string, templateExpr?: string): string => {
1853
- const { protect, restore } = createStringProtector()
1854
- let result = protect(templateExpr ?? expr)
1855
-
1856
- // Inline constant references with their resolved values (#343)
1857
- if (inlinableConstants && inlinableConstants.size > 0) {
1858
- for (const [constName, constValue] of inlinableConstants) {
1859
- result = result.replace(new RegExp(`(?<![-.])\\b${constName}\\b`, 'g'), `(${protect(constValue)})`)
1860
- }
1861
- }
1843
+ const transformExpr = (expr: JsSourceText, templateExpr?: JsSourceText): string => {
1844
+ // Inline constant references with their resolved values (#343), on the
1845
+ // expression tree: a constant's name inside a string or template
1846
+ // literal, a member name, or a binding that shadows it is never
1847
+ // replaced, and a shorthand `{ size }` expands to `size: (value)`
1848
+ // (#3535).
1849
+ const source = templateExpr ?? expr
1850
+ const restored = constantEnv ? csrSubstitute(source, constantEnv, opts.scope).rewritten : source
1862
1851
 
1863
- // Normalize source-level props object access (e.g., props.xxx → _p.xxx).
1864
- // Restore FIRST: `rewritePropsObjectRef` parses `result` as real
1865
- // TypeScript, and a still-protected string/template-literal span would
1866
- // parse as an opaque placeholder token instead of the source text it
1867
- // stands for (harmless for the placeholder itself, but it must not be
1868
- // mistaken for unparsed leftover input by a caller reading `result`
1869
- // before this point). Regex-based `\b${propsObjectName}\.` (removed
1870
- // here) required the name to be immediately followed by `.`, so a
1871
- // parenthesised receiver — `(props).label`, produced by this same
1872
- // function's own constant-inlining step just above when the inlined
1873
- // value is itself `props` (a local alias of the whole props object) —
1874
- // silently kept the pre-rewrite name instead of `_p`.
1852
+ // Normalize source-level props object access (e.g., props.xxx → _p.xxx),
1853
+ // also on the tree: a parenthesised receiver — `(props).label`, produced
1854
+ // by the constant inlining just above when the inlined value is itself
1855
+ // `props` (a local alias of the whole props object) — resolves too.
1875
1856
  //
1876
1857
  // The gate stays keyed on `propsObjectName` for the destructured-prop
1877
1858
  // case (unconditionally rewriting here would also change static-path
@@ -1881,7 +1862,6 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1881
1862
  // param), so `rest.header` resolves to `_p.header` here the same way
1882
1863
  // it already does in the init body (`generate-init.ts`, #2723) instead
1883
1864
  // of reaching the template as a bare, undeclared `rest` (#2806).
1884
- const restored = restore(result)
1885
1865
  return (propsObjectName && propsObjectName !== PROPS_PARAM) || restPropsName
1886
1866
  ? rewritePropsObjectRef(restored, propsObjectName ?? null, restPropsName ?? null, { enclosingScope: opts.scope })
1887
1867
  : restored
@@ -2124,26 +2104,32 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
2124
2104
  * Returns false if the component has:
2125
2105
  * - Loops (which use dynamic signal arrays)
2126
2106
  * - Child components (which can't be fully represented in templates)
2127
- * - Signal calls in expressions (like todos().length)
2128
- * - References to local variables not available at module scope (#343)
2107
+ * - A free reference that the module-scope template lambda cannot reach:
2108
+ * a signal getter or memo (`todos().length`, `label + count()`), or a local
2109
+ * variable not available at module scope (#343)
2129
2110
  *
2130
2111
  * Components that fail this check should not have registerTemplate() generated
2131
2112
  * as the template would reference undefined variables at module scope.
2132
2113
  *
2114
+ * The decision reads only the IR's free identifiers (`origin.freeRefs` for
2115
+ * expressions and conditions, `freeIdentifiers` for attributes), never the
2116
+ * expression text, so it does not depend on operand order (#3509).
2117
+ *
2133
2118
  * @param node - IR node to check
2134
- * @param propNames - Set of prop names (safe to reference via props parameter)
2119
+ * @param reactiveGetterNames - Signal getter and memo names (not callable in the template lambda)
2135
2120
  * @param inlinableConstants - Constants that can be substituted with their values
2136
2121
  * @param unsafeLocalNames - Local names that cannot be used in module-scope templates
2137
2122
  */
2138
2123
  export function canGenerateStaticTemplate(
2139
2124
  node: IRNode,
2140
- propNames: Set<string>,
2125
+ reactiveGetterNames: ReadonlySet<string>,
2141
2126
  inlinableConstants?: Map<string, string>,
2142
2127
  unsafeLocalNames?: Set<string>
2143
2128
  ): boolean {
2144
- const hasUnsafeRef = (freeIds: ReadonlySet<string> | undefined): boolean => {
2145
- return !!(unsafeLocalNames && unsafeLocalNames.size > 0 && setIntersects(freeIds, unsafeLocalNames))
2146
- }
2129
+ const recurse = (child: IRNode): boolean =>
2130
+ canGenerateStaticTemplate(child, reactiveGetterNames, inlinableConstants, unsafeLocalNames)
2131
+ const hasUnreachableRef = (freeIds: ReadonlySet<string> | undefined): boolean =>
2132
+ setIntersects(freeIds, reactiveGetterNames) || setIntersects(freeIds, unsafeLocalNames)
2147
2133
 
2148
2134
  switch (node.type) {
2149
2135
  case 'loop':
@@ -2153,59 +2139,32 @@ export function canGenerateStaticTemplate(
2153
2139
  return false
2154
2140
 
2155
2141
  case 'expression':
2156
- if (hasUnsafeRef(freeIdsFromRefs(node.origin?.freeRefs))) return false
2157
- // Use AST-derived flag when available, fall back to string check for older IR
2158
- if ((node.hasFunctionCalls ?? node.expr.includes('()')) && !isSimplePropExpression(node.expr, propNames)) {
2159
- return false
2160
- }
2161
- return true
2142
+ return !hasUnreachableRef(freeIdsFromRefs(node.origin?.freeRefs))
2162
2143
 
2163
2144
  case 'element':
2164
2145
  for (const attr of node.attrs) {
2165
- if (attr.name === '...') {
2166
- // Computed local spreads are now handled by spreadAttrs() at runtime.
2167
- // Only check for unsafe references that would fail at module scope.
2168
- const valueStr = attrValueToString(attr.value)
2169
- if (valueStr && hasUnsafeRef(attr.freeIdentifiers)) return false
2170
- if (valueStr && valueStr.includes('()') && !isSimplePropExpression(valueStr, propNames)) return false
2171
- continue
2172
- }
2173
- // Only `expression` / `template` carry runtime references worth probing.
2174
- if (attr.value.kind === 'expression' || attr.value.kind === 'template' || attr.value.kind === 'spread') {
2175
- const valueStr = attrValueToString(attr.value)
2176
- if (valueStr) {
2177
- if (hasUnsafeRef(attr.freeIdentifiers)) return false
2178
- if (valueStr.includes('()') && !isSimplePropExpression(valueStr, propNames)) {
2179
- return false
2180
- }
2181
- }
2182
- }
2146
+ // Only `expression` / `template` / `spread` carry runtime references
2147
+ // worth probing. A spread (`{...rest}`) of a computed local is handled
2148
+ // by spreadAttrs() at runtime, so the same reachability check applies.
2149
+ const probes = attr.name === '...' || attr.value.kind === 'expression' ||
2150
+ attr.value.kind === 'template' || attr.value.kind === 'spread'
2151
+ if (probes && attrValueToString(attr.value) && hasUnreachableRef(attr.freeIdentifiers)) return false
2183
2152
  }
2184
- return node.children.every((c) => canGenerateStaticTemplate(c, propNames, inlinableConstants, unsafeLocalNames))
2153
+ return node.children.every(recurse)
2185
2154
 
2186
2155
  case 'conditional':
2187
- if (hasUnsafeRef(freeIdsFromRefs(node.origin?.freeRefs))) return false
2188
- if (node.condition.includes('()') && !isSimplePropExpression(node.condition, propNames)) {
2189
- return false
2190
- }
2191
- return canGenerateStaticTemplate(node.whenTrue, propNames, inlinableConstants, unsafeLocalNames) &&
2192
- canGenerateStaticTemplate(node.whenFalse, propNames, inlinableConstants, unsafeLocalNames)
2156
+ if (hasUnreachableRef(freeIdsFromRefs(node.origin?.freeRefs))) return false
2157
+ return recurse(node.whenTrue) && recurse(node.whenFalse)
2193
2158
 
2194
2159
  case 'fragment':
2195
- return node.children.every((c) => canGenerateStaticTemplate(c, propNames, inlinableConstants, unsafeLocalNames))
2160
+ return node.children.every(recurse)
2196
2161
 
2197
2162
  case 'if-statement':
2198
- if (!canGenerateStaticTemplate(node.consequent, propNames, inlinableConstants, unsafeLocalNames)) {
2199
- return false
2200
- }
2201
- if (node.alternate && !canGenerateStaticTemplate(node.alternate, propNames, inlinableConstants, unsafeLocalNames)) {
2202
- return false
2203
- }
2204
- return true
2163
+ return recurse(node.consequent) && (!node.alternate || recurse(node.alternate))
2205
2164
 
2206
2165
  case 'provider':
2207
2166
  case 'async':
2208
- return node.children.every((c) => canGenerateStaticTemplate(c, propNames, inlinableConstants, unsafeLocalNames))
2167
+ return node.children.every(recurse)
2209
2168
 
2210
2169
  case 'text':
2211
2170
  return true
@@ -2499,7 +2458,7 @@ export function computeDeferredChildSlots(
2499
2458
  function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): string {
2500
2459
  const { restSpreadNames, propsObjectName, restPropsName, csrEnv, unsafeLocalNames, loopDepth = 0 } = opts
2501
2460
  const env: CsrEnv = csrEnv ?? { substitutions: new Map(), propsObjectName: propsObjectName ?? null }
2502
- const transformExpr = (expr: string, templateExpr?: string): string => {
2461
+ const transformExpr = (expr: JsSourceText, templateExpr?: JsSourceText): string => {
2503
2462
  // Single AST substitution pass: replaces signal getter calls
2504
2463
  // (`count()` → `(initialValue)`), memo calls (`bars()` → `(body)`),
2505
2464
  // and inlinable-const refs (`label` → `(rewrittenValue)`) in one
@@ -2903,26 +2862,3 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2903
2862
  }
2904
2863
  }
2905
2864
 
2906
- /**
2907
- * Check if an expression is a simple prop-based expression.
2908
- * Simple prop expressions access props only: todo.done, todo.text, props.name
2909
- * Non-prop expressions call signals: todos(), todos().length, todos().filter(...)
2910
- */
2911
- export function isSimplePropExpression(expr: string, propNames: Set<string>): boolean {
2912
- const match = expr.match(/^([a-zA-Z_$][a-zA-Z0-9_$]*)/)
2913
- if (!match) {
2914
- // No identifier at start (e.g., template literal `${...}`) — check for signal calls
2915
- return !expr.includes('()')
2916
- }
2917
-
2918
- const rootIdent = match[1]
2919
- if (propNames.has(rootIdent)) {
2920
- // Even if root is a prop name, calling it as a function means it's a signal getter
2921
- const rest = expr.slice(rootIdent.length)
2922
- if (rest.startsWith('(')) return false
2923
- return true
2924
- }
2925
- if (expr.includes('()')) return false
2926
-
2927
- return true
2928
- }