@barefootjs/jsx 0.35.8 → 0.36.0

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.
@@ -23,9 +23,9 @@
23
23
  * Stage E.4 of issue #1021.
24
24
  */
25
25
 
26
- import type { ConstantInfo, IRNode, ReferencesGraph } from '../types.ts'
26
+ import type { ConstantInfo, DeclarationScope, IRNode, ReferencesGraph } from '../types.ts'
27
27
  import type { ClientJsContext } from './types.ts'
28
- import { graphFunctionReferences } from './build-references.ts'
28
+ import { computeDeclarationScopes } from './compute-scope.ts'
29
29
  import { extractIdentifiers, extractTemplateIdentifiers } from './identifiers.ts'
30
30
  import { isInlinableInTemplate, buildRelocateEnvFromIR } from '../relocate.ts'
31
31
  import type { RelocateEnv, RelocateDecision } from '../relocate.ts'
@@ -103,6 +103,14 @@ export type ConstantInlinability =
103
103
  * The function identity is per-instance; inlining a function
104
104
  * literal into a template would close over the wrong scope. */
105
105
  | { kind: 'arrow-literal' }
106
+ /** Module-scope arrow-valued constant that does NOT touch component
107
+ * internals (`compute-scope.ts`'s forward-reachability fixpoint
108
+ * placed it at `'module'` scope, #2988) — the mirror image of
109
+ * `FunctionInlinability`'s `'module-scope-safe'`. The template can
110
+ * reference it by bare name because the emitted client JS declares
111
+ * it at module scope too; unlike `'arrow-literal'`, this is NOT
112
+ * unsafe for template inlining. */
113
+ | { kind: 'module-scope-safe' }
106
114
  /** Initializer reads a signal/memo. Template inlining would freeze
107
115
  * the reactive value at SSR time. */
108
116
  | { kind: 'reactive-read' }
@@ -232,9 +240,26 @@ export function computeInlinability(
232
240
  const constants = new Map<string, ConstantInlinability>()
233
241
  const functions = new Map<string, FunctionInlinability>()
234
242
 
243
+ // #3000: single producer for "is this module-level function safe to
244
+ // reference by bare name from the CSR template lambda" — reuses
245
+ // `compute-scope.ts`'s forward-reachability fixpoint (already the sole
246
+ // producer for constants as of #2998) instead of the independent, more
247
+ // conservative `functionReferencesDeclaredName`, which flagged a
248
+ // module-scope function unsafe on a reference to ANY name in
249
+ // `graph.declaredNames` — including another module-scope-SAFE helper —
250
+ // rather than only names that are themselves unsafe. A module-scope
251
+ // function calling another module-scope pure helper (`fmt(s) { return
252
+ // inner(s) }`) is exactly the shape `compute-scope.ts`'s own fixpoint
253
+ // already gets right for both functions transitively (it demotes a
254
+ // candidate only when it transitively references something actually
255
+ // `init`-scoped) — computing the shared scopes once here, before both
256
+ // the function loop and the constant classification below, makes
257
+ // functions and constants resolve through the same producer.
258
+ const { constantScope, functionScope } = computeDeclarationScopes(ctx, graph)
259
+
235
260
  // --- Functions ---
236
261
  for (const fn of ctx.localFunctions) {
237
- functions.set(fn.name, fn.isModule && !functionReferencesDeclaredName(graph, fn.name)
262
+ functions.set(fn.name, functionScope.get(fn.name) === 'module'
238
263
  ? { kind: 'module-scope-safe' }
239
264
  : { kind: 'references-component-scope' })
240
265
  }
@@ -257,6 +282,18 @@ export function computeInlinability(
257
282
  // rejections during classification.
258
283
  const env = buildEnvFromCtx(ctx)
259
284
 
285
+ // #2988: single producer for "is this module-level constant safe to
286
+ // reference by bare name from the template lambda" — reuses
287
+ // `compute-scope.ts`'s forward-reachability fixpoint, the SAME
288
+ // decision `classifyLocalDeclarations` (init-declarations.ts) uses to
289
+ // place a constant's own `var` declaration at module vs init scope in
290
+ // the compiled bundle, instead of `classifyConstantInitial` re-deriving
291
+ // an independent (and, pre-#2988, unconditional) `arrow-literal`
292
+ // verdict for every arrow-valued constant. `constantScope` was already
293
+ // computed above (#3000) alongside `functionScope`, from the same
294
+ // `(ctx, graph)` pair with nothing mutating either in between — reused
295
+ // here rather than calling `computeDeclarationScopes` a second time.
296
+
260
297
  const decisionsByName = new Map<string, RelocateDecision[]>()
261
298
  for (const c of ctx.localConstants) {
262
299
  const { status, decisions } = classifyConstantInitial(
@@ -267,6 +304,7 @@ export function computeInlinability(
267
304
  memoNames,
268
305
  env,
269
306
  getterAliases,
307
+ constantScope,
270
308
  )
271
309
  constants.set(c.name, status)
272
310
  decisionsByName.set(c.name, decisions)
@@ -281,7 +319,7 @@ export function computeInlinability(
281
319
  // transformation. The map lives on `ClientJsContext` — not on the
282
320
  // cross-adapter `ConstantInfo` IR — so SSR adapters don't see CSR
283
321
  // substitution semantics they have no use for.
284
- populateCsrInlinable(ctx, env, getterAliases)
322
+ populateCsrInlinable(ctx, env, getterAliases, constantScope)
285
323
 
286
324
  return { constants, functions, decisionsByName, templateRiskyNames }
287
325
  }
@@ -300,14 +338,26 @@ export function computeInlinability(
300
338
  *
301
339
  * A const ends with `ctx.csrInlinable.get(name) === null` when:
302
340
  * - it has no `value` (placeholder-let)
303
- * - the value contains an arrow / function expression (identity per render)
341
+ * - the value contains an arrow / function expression (identity per
342
+ * render) — UNLESS `constantScope` places it at module scope
343
+ * (#2988: the arrow closes over nothing but its own params, same
344
+ * shape a module-scope `function` declaration already gets right),
345
+ * in which case it gets an identity entry (`rewrittenValue: name`)
346
+ * instead of `null` — the compiled bundle declares the const at
347
+ * module scope too, so referencing it by its own bare name from the
348
+ * CSR template is exactly as safe as a `module-scope-safe` function
304
349
  * - it's a system construct (`createContext`, `new WeakMap`)
305
350
  * - it's a JSX literal (handled by jsx-inline routing)
306
351
  * - it's a bare alias-hop chain naming a signal/memo getter (`getterAliases`)
307
352
  * - the substituted form fails `isInlinableInTemplate` (would re-execute
308
353
  * a non-pure call at template-eval time — #1138)
309
354
  */
310
- function populateCsrInlinable(ctx: ClientJsContext, relocateEnv: RelocateEnv, getterAliases: ReadonlyMap<string, string>): void {
355
+ function populateCsrInlinable(
356
+ ctx: ClientJsContext,
357
+ relocateEnv: RelocateEnv,
358
+ getterAliases: ReadonlyMap<string, string>,
359
+ constantScope: ReadonlyMap<string, DeclarationScope>,
360
+ ): void {
311
361
  if (ctx.localConstants.length === 0) return
312
362
 
313
363
  // Base env: signal getters + memo calls in raw (props.X) form, PLUS
@@ -345,6 +395,24 @@ function populateCsrInlinable(ctx: ClientJsContext, relocateEnv: RelocateEnv, ge
345
395
  // call-kind entry (`buildEnvWithConsts`'s Map spread puts `constSubs`
346
396
  // last) — the literal `(undefined)()` this issue is about (#2778).
347
397
  for (const c of ctx.localConstants) {
398
+ // `mutatedAfterDeclaration` takes precedence, matching
399
+ // `classifyConstantInitial`'s order exactly (checked before
400
+ // `containsArrow` there too) — a same-scope mutation after
401
+ // declaration means `c.name`'s bare reference no longer reflects
402
+ // the value this identity substitution would imply, even if
403
+ // `compute-scope.ts` still placed the declaration at module scope.
404
+ if (c.containsArrow && !c.mutatedAfterDeclaration && constantScope.get(c.name) === 'module') {
405
+ // #2988: module-scope-safe arrow helper — CSR substitution is
406
+ // identity. The compiled bundle declares `c.name` at module
407
+ // scope (same `computeDeclarationScopes` answer that placed it
408
+ // there), so the template lambda — itself module scope — can
409
+ // reference it by its own bare name with no rewrite needed, the
410
+ // same principle a `module-scope-safe` function already gets via
411
+ // `functionScope` (#3000) above.
412
+ ctx.csrInlinable.set(c.name, { rewrittenValue: c.name, freeIdentifiers: new Set() })
413
+ finalised.add(c.name)
414
+ continue
415
+ }
348
416
  if (c.isJsx || !c.value || c.containsArrow || c.systemConstructKind || c.mutatedAfterDeclaration || getterAliases.has(c.name)) {
349
417
  ctx.csrInlinable.set(c.name, null)
350
418
  finalised.add(c.name)
@@ -629,11 +697,23 @@ function classifyConstantInitial(
629
697
  memoNames: Set<string>,
630
698
  env: RelocateEnv,
631
699
  getterAliases: ReadonlyMap<string, string>,
700
+ constantScope: ReadonlyMap<string, DeclarationScope>,
632
701
  ): { status: ConstantInlinability; decisions: RelocateDecision[] } {
633
702
  if (c.isJsx) return { status: { kind: 'jsx-inline' }, decisions: [] }
634
703
  if (!c.value) return { status: { kind: 'placeholder-let' }, decisions: [] }
635
704
  if (c.mutatedAfterDeclaration) return { status: { kind: 'mutated-after-declaration' }, decisions: [] }
636
- if (c.containsArrow) return { status: { kind: 'arrow-literal' }, decisions: [] }
705
+ if (c.containsArrow) {
706
+ // #2988: `compute-scope.ts`'s fixpoint already answered "is this
707
+ // safe to reference by bare name at module scope" for arrow-valued
708
+ // module constants — read it instead of unconditionally treating
709
+ // every arrow value as per-instance/unsafe. A non-module arrow (or
710
+ // one that transitively touches component internals) still lands
711
+ // in `'init'`/`'skip'` there, so this stays `arrow-literal` for
712
+ // every case the pre-#2988 cascade already got right.
713
+ return constantScope.get(c.name) === 'module'
714
+ ? { status: { kind: 'module-scope-safe' }, decisions: [] }
715
+ : { status: { kind: 'arrow-literal' }, decisions: [] }
716
+ }
637
717
  if (c.systemConstructKind) return { status: { kind: 'system-construct' }, decisions: [] }
638
718
  // A multi-hop alias chain to a getter (`const a = items; const b = a`)
639
719
  // has `b`'s OWN free id as `a` — an `init-local`, not a getter — so the
@@ -694,14 +774,6 @@ function classifyConstantInitial(
694
774
  }
695
775
  }
696
776
 
697
- function functionReferencesDeclaredName(graph: ReferencesGraph, fnName: string): boolean {
698
- const refs = graphFunctionReferences(graph, fnName)
699
- for (const r of refs) {
700
- if (graph.declaredNames.has(r)) return true
701
- }
702
- return false
703
- }
704
-
705
777
  /**
706
778
  * Convert the tagged-union analysis back into the legacy shape the
707
779
  * rest of the template pipeline expects: a map of inlinable constants
@@ -729,8 +801,12 @@ export function toLegacyInlinability(
729
801
  for (const [name, status] of analysis.constants) {
730
802
  if (status.kind === 'inlinable') {
731
803
  inlinableConstants.set(name, status.value)
732
- } else if (status.kind === 'jsx-inline' || status.kind === 'system-construct') {
804
+ } else if (status.kind === 'jsx-inline' || status.kind === 'system-construct' || status.kind === 'module-scope-safe') {
733
805
  // Not inlinable AND not unsafe — they have their own routing.
806
+ // `module-scope-safe` (#2988) is referenced by bare name via
807
+ // `ctx.csrInlinable`'s identity entry (`populateCsrInlinable`),
808
+ // the same "own routing" shape `jsx-inline`/`system-construct`
809
+ // already use here.
734
810
  } else {
735
811
  unsafeLocalNames.add(name)
736
812
  }
@@ -38,7 +38,7 @@ export function computeDeclarationScopes(
38
38
  const initStmtAssigned = graphAssignedIdentifiers(graph)
39
39
 
40
40
  // ============================================================================
41
- // Constants
41
+ // Constants — immediate classification
42
42
  //
43
43
  // Cascade order mirrors generate-init.ts L114-151 (pre-Stage C):
44
44
  //
@@ -50,26 +50,55 @@ export function computeDeclarationScopes(
50
50
  // 3. no value (bare `let x`) → init (emitted as `let X` placeholder)
51
51
  // 4. systemConstructKind → module (unique identity)
52
52
  // 5. isModule + assignment target → module (#933 ReferenceError avoidance)
53
- // 6. otherwise → init
53
+ // 6. isModule + arrow-valued → deferred to the fixpoint below (#2988)
54
+ // 7. otherwise → init
55
+ //
56
+ // Step 6 is new (#2988): an arrow-valued module-level const closing
57
+ // over nothing but its own params (`const fmt = (s) => s.toUpperCase()`)
58
+ // is exactly the shape a `function fmt(s) { ... }` declaration already
59
+ // gets right via the forward-reachability fixpoint just below — the
60
+ // pre-#2988 cascade had no fixpoint-reachability equivalent for
61
+ // constants and fell straight to `init`, which silently disagreed with
62
+ // `compute-inlinability.ts`'s independent (and, for constants,
63
+ // unconditional) `arrow-literal` verdict and produced an empty CSR
64
+ // template seed. Scoped to arrow-valued constants specifically, not
65
+ // every value-bearing module constant — widening the fixpoint to cover
66
+ // every module constant shape is a larger, separately-scoped change.
54
67
  // ============================================================================
55
68
 
56
69
  const providerContextNames = new Set<string>()
57
70
  for (const p of ctx.providerSetups) providerContextNames.add(p.contextName)
58
71
 
72
+ const pendingConstants: ConstantInfo[] = []
59
73
  for (const c of ctx.localConstants) {
60
- constantScope.set(c.name, classifyConstant(c, usedIdentifiers, initStmtAssigned, providerContextNames))
74
+ const immediate = classifyConstantImmediate(c, usedIdentifiers, initStmtAssigned, providerContextNames)
75
+ if (immediate === 'pending-fixpoint') {
76
+ pendingConstants.push(c)
77
+ } else {
78
+ constantScope.set(c.name, immediate)
79
+ }
61
80
  }
62
81
 
63
82
  // ============================================================================
64
- // Functions — forward-reachability fixpoint
83
+ // Functions + deferred constants — forward-reachability fixpoint
65
84
  //
66
85
  // Seed `initRequired` with anything that must live inside the init
67
86
  // function (reactive roots, props, and every constant classified as
68
- // `init` above). Then walk every module-level candidate: if its body
69
- // references any name in the set, demote it to init scope and add its
70
- // own name so transitive callers demote in the next iteration. Loop
71
- // until stable. Functions that survive the fixpoint are `module`.
72
- // Mirrors generate-init.ts L218-280 (pre-Stage C).
87
+ // `init` above). Then walk every module-level candidate — functions
88
+ // AND, as of #2988, the arrow-valued constants deferred above: if its
89
+ // body/value references any name in the set, demote it to init scope
90
+ // and add its own name so transitive callers demote in the next
91
+ // iteration. Loop until stable. Survivors are `module`. Mirrors
92
+ // generate-init.ts L218-280 (pre-Stage C) for functions; constants
93
+ // join the same fixpoint rather than getting a second, independent
94
+ // implementation of the same reachability question.
95
+ //
96
+ // Functions read their reference set from the graph's (regex-derived,
97
+ // not scope-aware) `graphFunctionReferences`, so `fn.params` must be
98
+ // stripped explicitly. Constants use `c.freeIdentifiers` instead — the
99
+ // analyzer's TS-AST walk (`extractFreeIdentifiersFromNode`) already
100
+ // excludes an arrow's own bound parameter names, so no equivalent
101
+ // stripping is needed here.
73
102
  // ============================================================================
74
103
 
75
104
  const initRequired = new Set<string>()
@@ -84,20 +113,22 @@ export function computeDeclarationScopes(
84
113
  if (constantScope.get(c.name) === 'init') initRequired.add(c.name)
85
114
  }
86
115
 
87
- let pending: FunctionInfo[] = []
116
+ let pendingFns: FunctionInfo[] = []
88
117
  for (const fn of ctx.localFunctions) {
89
118
  if (fn.isJsxFunction) { functionScope.set(fn.name, 'skip'); continue }
90
119
  if (fn.isMultiReturnJsxHelper) { functionScope.set(fn.name, 'skip'); continue }
91
120
  if (!usedIdentifiers.has(fn.name)) { functionScope.set(fn.name, 'skip'); continue }
92
121
  if (!fn.isModule) { functionScope.set(fn.name, 'init'); continue }
93
- pending.push(fn)
122
+ pendingFns.push(fn)
94
123
  }
124
+ let pendingConsts = pendingConstants
95
125
 
96
126
  let changed = true
97
127
  while (changed) {
98
128
  changed = false
99
- const stillPending: FunctionInfo[] = []
100
- for (const fn of pending) {
129
+
130
+ const stillPendingFns: FunctionInfo[] = []
131
+ for (const fn of pendingFns) {
101
132
  const refs = graphFunctionReferences(graph, fn.name)
102
133
  // Parameters shadow outer names inside the function body.
103
134
  for (const p of fn.params) refs.delete(p.name)
@@ -107,22 +138,44 @@ export function computeDeclarationScopes(
107
138
  initRequired.add(fn.name)
108
139
  changed = true
109
140
  } else {
110
- stillPending.push(fn)
141
+ stillPendingFns.push(fn)
111
142
  }
112
143
  }
113
- pending = stillPending
144
+ pendingFns = stillPendingFns
145
+
146
+ const stillPendingConsts: ConstantInfo[] = []
147
+ for (const c of pendingConsts) {
148
+ const refs = c.freeIdentifiers ?? new Set<string>()
149
+ const referencesInit = [...refs].some(r => initRequired.has(r))
150
+ if (referencesInit) {
151
+ constantScope.set(c.name, 'init')
152
+ initRequired.add(c.name)
153
+ changed = true
154
+ } else {
155
+ stillPendingConsts.push(c)
156
+ }
157
+ }
158
+ pendingConsts = stillPendingConsts
114
159
  }
115
- for (const fn of pending) functionScope.set(fn.name, 'module')
160
+ for (const fn of pendingFns) functionScope.set(fn.name, 'module')
161
+ for (const c of pendingConsts) constantScope.set(c.name, 'module')
116
162
 
117
163
  return { constantScope, functionScope }
118
164
  }
119
165
 
120
- function classifyConstant(
166
+ /**
167
+ * Immediate (non-fixpoint) constant classification. Returns
168
+ * `'pending-fixpoint'` for the one case (#2988) that can't be decided
169
+ * without the reachability walk `computeDeclarationScopes` runs after
170
+ * this — the caller collects those into `pendingConstants` instead of
171
+ * setting a scope here.
172
+ */
173
+ function classifyConstantImmediate(
121
174
  c: ConstantInfo,
122
175
  usedIdentifiers: Set<string>,
123
176
  initStmtAssigned: Set<string>,
124
177
  providerContextNames: Set<string>,
125
- ): DeclarationScope {
178
+ ): DeclarationScope | 'pending-fixpoint' {
126
179
  if (c.isJsx) return 'skip' // Inlined at IR level (#547)
127
180
  if (c.isJsxFunction) return 'skip' // Inlined at call sites (#569)
128
181
 
@@ -140,5 +193,6 @@ function classifyConstant(
140
193
  if (!c.value) return 'init' // `let x` placeholder
141
194
  if (c.systemConstructKind) return 'module'
142
195
  if (c.isModule && initStmtAssigned.has(c.name)) return 'module'
196
+ if (c.isModule && c.containsArrow) return 'pending-fixpoint' // #2988
143
197
  return 'init'
144
198
  }
@@ -47,7 +47,16 @@ export function emitModuleLevelDeclarations(
47
47
  const lines: string[] = []
48
48
  for (const constant of moduleLevelConstants) {
49
49
  if (!constant.value) continue
50
- lines.push(`var ${constant.name} = ${constant.name} ?? ${constant.value}`)
50
+ // An arrow-valued initializer needs parenthesising on the right of
51
+ // `??` — `x ?? (s) => …` is a SyntaxError because `??`'s operand
52
+ // grammar (BitwiseORExpression) is higher-precedence than an arrow
53
+ // function (AssignmentExpression); only an already-parenthesised
54
+ // value (an object literal, `(a, b) => …`) survives unwrapped, and
55
+ // wrapping those again is a harmless no-op (#2988). Gated on
56
+ // `containsArrow` specifically so existing fixtures with
57
+ // parenthesised object-literal module consts don't churn.
58
+ const value = constant.containsArrow ? `(${constant.value})` : constant.value
59
+ lines.push(`var ${constant.name} = ${constant.name} ?? ${value}`)
51
60
  }
52
61
  for (const fn of moduleLevelFunctions) {
53
62
  const paramStr = fn.params.map(p => {
package/src/jsx-to-ir.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
 
7
7
  import ts from 'typescript'
8
+ import { CLIENT_DIRECTIVE_INTERIOR_RE } from './directives.ts'
8
9
  import {
9
10
  type IRNode,
10
11
  type IRElement,
@@ -272,7 +273,6 @@ interface TransformContext {
272
273
  * specially), so we read the trivia text directly and parse block
273
274
  * comments out of it.
274
275
  */
275
- const CLIENT_DIRECTIVE_INTERIOR_RE = /^\s*@client\s*$/
276
276
  const BLOCK_COMMENT_RE = /\/\*([\s\S]*?)\*\//g
277
277
  function hasLeadingClientDirective(expr: ts.Expression, sourceFile: ts.SourceFile): boolean {
278
278
  const trivia = sourceFile.text.slice(expr.pos, expr.getStart(sourceFile))
@@ -31,6 +31,7 @@
31
31
  */
32
32
 
33
33
  import ts from 'typescript'
34
+ import { isUseClientDirectiveText } from './directives.ts'
34
35
  import type { CompilerError, SourceLocation } from './types.ts'
35
36
  import { ErrorCodes, createError } from './errors.ts'
36
37
 
@@ -97,7 +98,7 @@ function runSinglePass(
97
98
  const hasUseClient = sourceFile.statements.some(stmt =>
98
99
  ts.isExpressionStatement(stmt) &&
99
100
  ts.isStringLiteral(stmt.expression) &&
100
- (stmt.expression.text === 'use client' || stmt.expression.text === "'use client'")
101
+ isUseClientDirectiveText(stmt.expression.text)
101
102
  )
102
103
 
103
104
  // Without `'use client'` the synthesized component has nowhere to