@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.2

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.
package/src/cli/new.ts CHANGED
@@ -15,7 +15,7 @@ export function scaffoldProject(targetDir: string, options: ScaffoldOptions = {}
15
15
  const root = resolve(targetDir)
16
16
  const name = basename(root).toLowerCase().replace(/[^a-z0-9-_]/g, '-') || 'kay-app'
17
17
  const template: ScaffoldTemplate = options.template ?? 'minimal'
18
- const kayVersion = options.kayVersion ?? '^2.0.0-beta.1'
18
+ const kayVersion = options.kayVersion ?? '^2.0.0-beta.2'
19
19
 
20
20
  if (existsSync(root) && readdirSync(root).length > 0 && !options.force)
21
21
  throw new Error(`kay new: directory "${root}" is not empty (pass --force to overwrite)`)
@@ -416,14 +416,13 @@ export default defineConfig({
416
416
  ],
417
417
  })
418
418
  `
419
- files['src/routes/_layout.tsx'] = `import type { PublicUser } from '@kayjs/auth'
420
- import type { KayChild } from 'kay'
419
+ files['src/routes/_layout.tsx'] = `import type { LayoutProps } from 'kay'
421
420
  import { Button, Cluster, Toaster } from '@kayjs/ui'
422
421
  import { Head } from 'kay'
423
422
  import '../styles/app.css'
424
423
 
425
- export default function Layout({ children, locals }: { children: KayChild, locals?: { user?: PublicUser } }) {
426
- const user = locals?.user
424
+ export default function Layout({ children, locals }: LayoutProps) {
425
+ const user = locals.user
427
426
  return (
428
427
  <>
429
428
  <Head>
@@ -505,10 +504,10 @@ export default function LoginPage() {
505
504
 
506
505
  export default auth.guard({ redirectTo: '/login' })
507
506
  `
508
- files['src/routes/dashboard/index.tsx'] = `import type { PublicUser } from '@kayjs/auth'
507
+ files['src/routes/dashboard/index.tsx'] = `import type { PageProps } from 'kay'
509
508
  import { Card, CardBody, CardHeader } from '@kayjs/ui'
510
509
 
511
- export default async function DashboardPage({ locals }: { locals: { user?: PublicUser } }) {
510
+ export default async function DashboardPage({ locals }: PageProps) {
512
511
  return (
513
512
  <Card>
514
513
  <CardHeader>Dashboard</CardHeader>
@@ -12,7 +12,7 @@ import type {
12
12
  } from 'oxc-parser'
13
13
  import { parseSync, visitorKeys } from 'oxc-parser'
14
14
  import { checkBareSignals, checkHydrateMode, checkMistakes, mistake } from './mistakes'
15
- import { EVENT_ATTR, formatLoc, isComponentTag, isJsxNode, jsxTagName, unwrapTsExpr } from './shared'
15
+ import { EVENT_ATTR, formatCodeFrame, formatDiagnostic, formatLoc, isComponentTag, isJsxNode, jsxTagName, unwrapTsExpr } from './shared'
16
16
 
17
17
  export type AstNode = Node
18
18
 
@@ -25,6 +25,7 @@ const REACTIVE_IMPORTS = new Set([
25
25
  'selector',
26
26
  'store',
27
27
  'island',
28
+ 'useAction',
28
29
  ])
29
30
 
30
31
  // Primitives whose result is reactive state another module can import and read.
@@ -45,6 +46,7 @@ export interface ReexportInfo {
45
46
  exported: string
46
47
  local: string
47
48
  source: string
49
+ start: number
48
50
  }
49
51
 
50
52
  export interface ModuleAnalysis {
@@ -52,9 +54,12 @@ export interface ModuleAnalysis {
52
54
  program: Program
53
55
  isInteractive: boolean
54
56
  interactiveReason: string | undefined
57
+ interactiveOffset?: number | undefined
55
58
  hasAsyncDefault: boolean
56
59
  hasLoadExport: boolean
57
60
  hasJsx: boolean
61
+ /** Precomputed set of AST nodes containing JSX (itself included), for O(1) subtree checks during codegen. */
62
+ jsxNodes: WeakSet<Node>
58
63
  hasPrerender: boolean
59
64
  hasPaths: boolean
60
65
  usesRenderContext: boolean
@@ -76,6 +81,49 @@ export interface ModuleAnalysis {
76
81
  warnings: string[]
77
82
  }
78
83
 
84
+ export function computeJsxNodes(program: Program): WeakSet<Node> {
85
+ const jsxNodes = new WeakSet<Node>()
86
+ const visit = (node: unknown): boolean => {
87
+ if (node === null || typeof node !== 'object')
88
+ return false
89
+ if (Array.isArray(node)) {
90
+ let any = false
91
+ for (let i = 0; i < node.length; i++) {
92
+ if (visit(node[i]))
93
+ any = true
94
+ }
95
+ return any
96
+ }
97
+ const ast = node as Node
98
+ const type = ast.type
99
+ if (typeof type !== 'string')
100
+ return false
101
+ let found = isJsxNode(ast)
102
+ const keys = visitorKeys[type]
103
+ if (keys !== undefined) {
104
+ const rec = ast as unknown as Record<string, unknown>
105
+ for (let i = 0; i < keys.length; i++) {
106
+ const val = rec[keys[i]!]
107
+ if (val !== null && typeof val === 'object' && visit(val))
108
+ found = true
109
+ }
110
+ }
111
+ else {
112
+ for (const [key, val] of Object.entries(ast)) {
113
+ if (key === 'start' || key === 'end' || key === 'type')
114
+ continue
115
+ if (val !== null && typeof val === 'object' && visit(val))
116
+ found = true
117
+ }
118
+ }
119
+ if (found)
120
+ jsxNodes.add(ast)
121
+ return found
122
+ }
123
+ visit(program)
124
+ return jsxNodes
125
+ }
126
+
79
127
  export function walk(node: unknown, visit: (node: Node) => boolean | void): void {
80
128
  if (node === null || typeof node !== 'object')
81
129
  return
@@ -387,9 +435,12 @@ export function parseTsx(filename: string, code: string): Program {
387
435
  const result = parseSync(filename, code, { lang, sourceType: 'module' })
388
436
  if (result.errors.length > 0) {
389
437
  const first = result.errors[0]!
390
- const offset = first.labels?.[0]?.start
438
+ const label = first.labels?.[0]
439
+ const offset = label?.start ?? 0
391
440
  const loc = formatLoc(filename, code, offset)
392
- throw new Error(`kay compiler: syntax error in ${loc}: ${first.message}`)
441
+ const frame = formatCodeFrame(code, offset, label?.end)
442
+ const header = formatDiagnostic(loc, `kay compiler: syntax error: ${first.message}`)
443
+ throw new Error(frame ? `${header}\n${frame}` : header)
393
444
  }
394
445
  return result.program
395
446
  }
@@ -468,6 +519,7 @@ function isIslandCall(node: Node, islandLocalName: string | undefined, kayNamesp
468
519
  export function analyzeModule(filename: string, code: string, program: Program = parseTsx(filename, code)): ModuleAnalysis {
469
520
  let isInteractive = false
470
521
  let interactiveReason: string | undefined
522
+ let interactiveOffset: number | undefined
471
523
  let hasAsyncDefault = false
472
524
  let hasLoadExport = false
473
525
  let hasJsx = false
@@ -496,10 +548,11 @@ export function analyzeModule(filename: string, code: string, program: Program =
496
548
  // The action() calls kay gives a URL to: the initialisers of top-level `export const`s.
497
549
  const registeredActions = new Set<Node>()
498
550
 
499
- const markInteractive = (reason: string) => {
551
+ const markInteractive = (reason: string, offset?: number) => {
500
552
  if (!isInteractive) {
501
553
  isInteractive = true
502
554
  interactiveReason = reason
555
+ interactiveOffset = offset
503
556
  }
504
557
  }
505
558
 
@@ -530,7 +583,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
530
583
  const local = spec.local.name
531
584
  specifiers.push({ local, imported })
532
585
  if (KAY_SOURCES.has(source) && REACTIVE_IMPORTS.has(imported))
533
- markInteractive(`imports ${imported} from '${source}'`)
586
+ markInteractive(`imports ${imported} from '${source}'`, spec.start)
534
587
  if (KAY_SOURCES.has(source) && imported === 'island')
535
588
  islandLocalName = local
536
589
  if (KAY_SOURCES.has(source) && STATE_PRIMITIVES.has(imported))
@@ -558,7 +611,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
558
611
  }
559
612
 
560
613
  const readIslandHydrate = (call: CallExpression): void => {
561
- markInteractive('island() wrapper')
614
+ markInteractive('island() wrapper', call.start)
562
615
  const opts = call.arguments[1]
563
616
  if (opts !== undefined && opts.type === 'ObjectExpression') {
564
617
  for (const prop of opts.properties) {
@@ -588,7 +641,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
588
641
  }
589
642
  else if (stmt.type === 'ExportAllDeclaration') {
590
643
  if (stmt.exportKind !== 'type')
591
- reexports.push({ exported: '*', local: '*', source: stmt.source.value })
644
+ reexports.push({ exported: '*', local: '*', source: stmt.source.value, start: stmt.start })
592
645
  }
593
646
  else if (stmt.type === 'ExportDefaultDeclaration') {
594
647
  exportedNames.push('default')
@@ -619,7 +672,7 @@ export function analyzeModule(filename: string, code: string, program: Program =
619
672
  const local = exportedName(spec.local)
620
673
  if (exported !== undefined && local !== undefined) {
621
674
  exportedNames.push(exported)
622
- reexports.push({ exported, local, source: src })
675
+ reexports.push({ exported, local, source: src, start: stmt.start })
623
676
  if (exported === 'load')
624
677
  hasLoadExport = true
625
678
  if (exported === 'paths')
@@ -732,13 +785,13 @@ export function analyzeModule(filename: string, code: string, program: Program =
732
785
  }
733
786
  // A handler or ref on a component tag is a prop for that component; only a DOM element binds it in the browser.
734
787
  if (!isComponent && tag !== '' && (EVENT_ATTR.test(attrName) || attrName === 'ref'))
735
- markInteractive(`uses ${attrName}`)
788
+ markInteractive(`uses ${attrName}`, attr.start)
736
789
  }
737
790
  }
738
791
  if (node.type === 'MemberExpression' && !node.computed && node.object.type === 'Identifier' && kayNamespaces.has(node.object.name) && node.property.type === 'Identifier') {
739
792
  const member = node.property.name
740
793
  if (REACTIVE_IMPORTS.has(member))
741
- markInteractive(`calls ${node.object.name}.${member}`)
794
+ markInteractive(`calls ${node.object.name}.${member}`, node.start)
742
795
  if (STATE_PRIMITIVES.has(member))
743
796
  stateCallees.add(`${node.object.name}.${member}`)
744
797
  if (member === 'signal' || member === 'computed')
@@ -795,9 +848,11 @@ export function analyzeModule(filename: string, code: string, program: Program =
795
848
  warnings,
796
849
  isInteractive,
797
850
  interactiveReason,
851
+ interactiveOffset,
798
852
  hasAsyncDefault,
799
853
  hasLoadExport: hasLoadExport || loadDeclarations(program).length > 0,
800
854
  hasJsx,
855
+ jsxNodes: hasJsx ? computeJsxNodes(program) : new WeakSet<Node>(),
801
856
  hasPrerender,
802
857
  hasPaths,
803
858
  usesRenderContext,
@@ -13,6 +13,7 @@ import type {
13
13
  Program,
14
14
  } from 'oxc-parser'
15
15
  import type { ModuleAnalysis } from './analyze'
16
+ import { visitorKeys } from 'oxc-parser'
16
17
  import { analyzeModule, loadDeclarations, parseTsx, walk } from './analyze'
17
18
  import { SourceEditor } from './patch'
18
19
  import {
@@ -116,94 +117,20 @@ function literalArrayConsts(program: Program): Set<string> {
116
117
  return literal
117
118
  }
118
119
 
119
- /** Collects free identifier references inside a node (ignoring shadowed locals and property keys). */
120
- function referencesAny(rootNode: Node, names: ReadonlySet<string>): boolean {
121
- if (names.size === 0)
122
- return false
123
- let found = false
124
- function visit(node: Node | null | undefined, shadowed: Set<string>): void {
125
- if (found || node === null || node === undefined)
126
- return
127
- switch (node.type) {
128
- case 'Identifier':
129
- if (!shadowed.has(node.name) && names.has(node.name))
130
- found = true
131
- return
132
- case 'MemberExpression':
133
- visit(node.object, shadowed)
134
- if (node.computed)
135
- visit(node.property, shadowed)
136
- return
137
- case 'Property':
138
- if (node.computed)
139
- visit(node.key, shadowed)
140
- visit(node.value, shadowed)
141
- return
142
- case 'ArrowFunctionExpression':
143
- case 'FunctionExpression':
144
- case 'FunctionDeclaration': {
145
- const next = new Set(shadowed)
146
- if (node.type !== 'ArrowFunctionExpression' && node.id !== null)
147
- next.add(node.id.name)
148
- for (const p of node.params)
149
- collectPatternNames(p, next)
150
- visit(node.body, next)
151
- return
152
- }
153
- case 'BlockStatement': {
154
- const next = new Set(shadowed)
155
- for (const stmt of node.body) {
156
- if (stmt.type === 'VariableDeclaration') {
157
- for (const d of stmt.declarations) {
158
- visit(d.init, next)
159
- collectPatternNames(d.id, next)
160
- }
161
- }
162
- else {
163
- visit(stmt, next)
164
- }
165
- }
166
- return
167
- }
168
- default: {
169
- if (node.type.startsWith('TS'))
170
- return
171
- for (const [k, v] of Object.entries(node)) {
172
- if (k === 'start' || k === 'end' || k === 'type')
173
- continue
174
- if (Array.isArray(v)) {
175
- for (const item of v) {
176
- if (item !== null && typeof item === 'object' && 'type' in item)
177
- visit(item as Node, shadowed)
178
- }
179
- }
180
- else if (v !== null && typeof v === 'object' && 'type' in v) {
181
- visit(v as Node, shadowed)
182
- }
183
- }
184
- }
185
- }
186
- }
187
- visit(rootNode, new Set())
188
- return found
120
+ interface ScopedWalkCallbacks {
121
+ shouldStop?: (() => boolean) | undefined
122
+ onIdentifier?: ((node: Extract<Node, { type: 'Identifier' }>, shadowed: ReadonlySet<string>) => void) | undefined
123
+ onShorthandProperty?: ((node: Extract<Node, { type: 'Property' }>, shadowed: ReadonlySet<string>) => boolean) | undefined
124
+ onJsx?: ((node: JSXElement | JSXFragment, shadowed: ReadonlySet<string>) => void) | undefined
125
+ onFunction?: ((node: ArrowFunctionExpression | OxcFunction, shadowed: ReadonlySet<string>) => boolean) | undefined
189
126
  }
190
127
 
191
- /** Rewrites free identifier reads inside an AST node while respecting lexical scopes, class/object keys, labels, and nested JSX/components. */
192
- function rewriteFreeIdentifiers(
193
- source: string,
194
- rootNode: Node,
195
- replacements: ReadonlyMap<string, string>,
196
- onJsx?: (node: JSXElement | JSXFragment, rewrites: ReadonlyMap<string, string>) => string,
197
- onFunction?: (fn: ArrowFunctionExpression | OxcFunction, rewrites: ReadonlyMap<string, string>) => string | undefined,
198
- ): string {
199
- if (replacements.size === 0 && (onJsx === undefined || !containsJsx(rootNode)))
200
- return source.slice(rootNode.start, rootNode.end)
201
-
202
- const offset = rootNode.start
203
- const editor = new SourceEditor(source.slice(rootNode.start, rootNode.end))
128
+ /** Single lexical-scope AST visitor shared by `referencesAny` and `rewriteFreeIdentifiers` (respects `for...of`, `catch (e)`, class members, labels, and TS nodes). */
129
+ function walkScoped(rootNode: Node, callbacks: ScopedWalkCallbacks): void {
130
+ const { shouldStop, onIdentifier, onShorthandProperty, onJsx, onFunction } = callbacks
204
131
 
205
132
  function visitPatternDefaults(pattern: Node | null | undefined, shadowed: Set<string>): void {
206
- if (pattern === null || pattern === undefined)
133
+ if (pattern === null || pattern === undefined || shouldStop?.())
207
134
  return
208
135
  switch (pattern.type) {
209
136
  case 'AssignmentPattern':
@@ -234,27 +161,19 @@ function rewriteFreeIdentifiers(
234
161
  }
235
162
  }
236
163
 
237
- function activeMap(shadowed: Set<string>): ReadonlyMap<string, string> {
238
- return shadowed.size === 0 ? replacements : new Map([...replacements].filter(([k]) => !shadowed.has(k)))
239
- }
240
-
241
164
  function visit(node: Node | null | undefined, shadowed: Set<string>): void {
242
- if (node === null || node === undefined)
165
+ if (node === null || node === undefined || shouldStop?.())
243
166
  return
244
167
 
245
168
  if (onJsx !== undefined && isJsxNode(node)) {
246
- editor.replace(node.start - offset, node.end - offset, onJsx(node, activeMap(shadowed)))
169
+ onJsx(node, shadowed)
247
170
  return
248
171
  }
249
172
 
250
173
  switch (node.type) {
251
174
  case 'Identifier': {
252
- const name = node.name
253
- if (!shadowed.has(name)) {
254
- const rep = replacements.get(name)
255
- if (rep !== undefined)
256
- editor.replace(node.start - offset, node.end - offset, rep)
257
- }
175
+ if (!shadowed.has(node.name))
176
+ onIdentifier?.(node, shadowed)
258
177
  return
259
178
  }
260
179
  case 'MemberExpression': {
@@ -274,13 +193,8 @@ function rewriteFreeIdentifiers(
274
193
  case 'Property': {
275
194
  if (node.computed)
276
195
  visit(node.key, shadowed)
277
- if (node.shorthand && node.value.type === 'Identifier') {
278
- const name = node.value.name
279
- if (!shadowed.has(name) && replacements.has(name)) {
280
- editor.replace(node.start - offset, node.end - offset, `${name}: ${replacements.get(name)}`)
281
- return
282
- }
283
- }
196
+ if (node.shorthand && node.value.type === 'Identifier' && onShorthandProperty?.(node, shadowed) === true)
197
+ return
284
198
  visit(node.value, shadowed)
285
199
  return
286
200
  }
@@ -345,13 +259,8 @@ function rewriteFreeIdentifiers(
345
259
  case 'ArrowFunctionExpression':
346
260
  case 'FunctionExpression':
347
261
  case 'FunctionDeclaration': {
348
- if (node !== rootNode && onFunction !== undefined) {
349
- const compiled = onFunction(node, activeMap(shadowed))
350
- if (compiled !== undefined) {
351
- editor.replace(node.start - offset, node.end - offset, compiled)
352
- return
353
- }
354
- }
262
+ if (node !== rootNode && onFunction?.(node, shadowed) === true)
263
+ return
355
264
  const nextShadow = new Set(shadowed)
356
265
  if (node.type !== 'ArrowFunctionExpression' && node.id !== null)
357
266
  nextShadow.add(node.id.name)
@@ -400,6 +309,24 @@ function rewriteFreeIdentifiers(
400
309
  default: {
401
310
  if (node.type.startsWith('TS'))
402
311
  return
312
+ const keys = visitorKeys[node.type]
313
+ if (keys !== undefined) {
314
+ const rec = node as unknown as Record<string, unknown>
315
+ for (let i = 0; i < keys.length; i++) {
316
+ const val = rec[keys[i]!]
317
+ if (Array.isArray(val)) {
318
+ for (let j = 0; j < val.length; j++) {
319
+ const item = val[j]
320
+ if (item !== null && typeof item === 'object' && 'type' in item)
321
+ visit(item as Node, shadowed)
322
+ }
323
+ }
324
+ else if (val !== null && typeof val === 'object' && 'type' in val) {
325
+ visit(val as Node, shadowed)
326
+ }
327
+ }
328
+ return
329
+ }
403
330
  for (const [key, val] of Object.entries(node)) {
404
331
  if (key === 'start' || key === 'end' || key === 'type')
405
332
  continue
@@ -419,9 +346,105 @@ function rewriteFreeIdentifiers(
419
346
  }
420
347
 
421
348
  visit(rootNode, new Set())
349
+ }
350
+
351
+ /** Returns true if `rootNode` contains any free identifier reference to a name in `names`. */
352
+ function referencesAny(rootNode: Node, names: ReadonlySet<string>): boolean {
353
+ if (names.size === 0)
354
+ return false
355
+ let found = false
356
+ walkScoped(rootNode, {
357
+ shouldStop: () => found,
358
+ onIdentifier(node) {
359
+ if (names.has(node.name))
360
+ found = true
361
+ },
362
+ })
363
+ return found
364
+ }
365
+
366
+ /** Rewrites free identifier reads inside an AST node while respecting lexical scopes, class/object keys, labels, and nested JSX/components. */
367
+ function rewriteFreeIdentifiers(
368
+ source: string,
369
+ rootNode: Node,
370
+ replacements: ReadonlyMap<string, string>,
371
+ jsxNodes: WeakSet<Node>,
372
+ onJsx?: (node: JSXElement | JSXFragment, rewrites: ReadonlyMap<string, string>) => string,
373
+ onFunction?: (fn: ArrowFunctionExpression | OxcFunction, rewrites: ReadonlyMap<string, string>) => string | undefined,
374
+ ): string {
375
+ if (replacements.size === 0 && (onJsx === undefined || !containsJsx(rootNode, jsxNodes)))
376
+ return source.slice(rootNode.start, rootNode.end)
377
+
378
+ const offset = rootNode.start
379
+ const editor = new SourceEditor(source.slice(rootNode.start, rootNode.end))
380
+ const activeMap = (shadowed: ReadonlySet<string>): ReadonlyMap<string, string> =>
381
+ shadowed.size === 0 ? replacements : new Map([...replacements].filter(([k]) => !shadowed.has(k)))
382
+
383
+ walkScoped(rootNode, {
384
+ onJsx: onJsx === undefined
385
+ ? undefined
386
+ : (node, shadowed) => {
387
+ editor.replace(node.start - offset, node.end - offset, onJsx(node, activeMap(shadowed)))
388
+ },
389
+ onIdentifier(node) {
390
+ const rep = replacements.get(node.name)
391
+ if (rep !== undefined)
392
+ editor.replace(node.start - offset, node.end - offset, rep)
393
+ },
394
+ onShorthandProperty(node, shadowed) {
395
+ if (node.value.type !== 'Identifier')
396
+ return false
397
+ const name = node.value.name
398
+ if (!shadowed.has(name) && replacements.has(name)) {
399
+ editor.replace(node.start - offset, node.end - offset, `${name}: ${replacements.get(name)}`)
400
+ return true
401
+ }
402
+ return false
403
+ },
404
+ onFunction: onFunction === undefined
405
+ ? undefined
406
+ : (node, shadowed) => {
407
+ const compiled = onFunction(node, activeMap(shadowed))
408
+ if (compiled !== undefined) {
409
+ editor.replace(node.start - offset, node.end - offset, compiled)
410
+ return true
411
+ }
412
+ return false
413
+ },
414
+ })
422
415
  return editor.toString()
423
416
  }
424
417
 
418
+ /** True when a JSX prop expression is statically stable (non-rewritten identifier, literal, function, or constant array/object) and needs no reactive getter. */
419
+ function isStaticPropExpr(rawNode: Node, scopeRewrites: ReadonlyMap<string, string>): boolean {
420
+ const node = unwrapTsExpr(rawNode)
421
+ switch (node.type) {
422
+ case 'Literal':
423
+ case 'ArrowFunctionExpression':
424
+ case 'FunctionExpression':
425
+ return true
426
+ case 'Identifier':
427
+ return !scopeRewrites.has(node.name)
428
+ case 'UnaryExpression':
429
+ return (node.operator === '-' || node.operator === '+' || node.operator === '!' || node.operator === '~' || node.operator === 'void')
430
+ && isStaticPropExpr(node.argument, scopeRewrites)
431
+ case 'TemplateLiteral':
432
+ return node.expressions.every(e => isStaticPropExpr(e, scopeRewrites))
433
+ case 'ArrayExpression':
434
+ return node.elements.every(el => el === null || (el.type !== 'SpreadElement' && isStaticPropExpr(el, scopeRewrites)))
435
+ case 'ObjectExpression':
436
+ return node.properties.every((prop) => {
437
+ if (prop.type !== 'Property' || prop.kind !== 'init')
438
+ return false
439
+ if (prop.computed && !isStaticPropExpr(prop.key, scopeRewrites))
440
+ return false
441
+ return isStaticPropExpr(prop.value, scopeRewrites)
442
+ })
443
+ default:
444
+ return false
445
+ }
446
+ }
447
+
425
448
  export function compileDom(filename: string, code: string, options: CompileDomOptions = {}): CompileDomResult {
426
449
  const program = options.analysis?.program ?? parseTsx(filename, code)
427
450
  const analysis = options.analysis ?? analyzeModule(filename, code, program)
@@ -431,6 +454,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
431
454
 
432
455
  const staticArrays = literalArrayConsts(program)
433
456
  const loadNodes = new Set<Node>(loadDeclarations(program))
457
+ const jsxNodes = analysis.jsxNodes
434
458
 
435
459
  const editor = new SourceEditor(code)
436
460
  const used = new Set<string>()
@@ -532,7 +556,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
532
556
  }
533
557
 
534
558
  function compileNestedComponent(fn: ArrowFunctionExpression | OxcFunction, outerRewrites: ReadonlyMap<string, string>): string | undefined {
535
- if (!containsJsx(fn.body))
559
+ if (!containsJsx(fn.body, jsxNodes))
536
560
  return undefined
537
561
  const firstParam = fn.params[0]
538
562
  const destructured = extractDestructuredParam(firstParam)
@@ -542,7 +566,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
542
566
  }
543
567
 
544
568
  function compileExpression(node: Node, scopeRewrites: ReadonlyMap<string, string>): string {
545
- return rewriteFreeIdentifiers(code, node, scopeRewrites, compileRootJsx, compileNestedComponent)
569
+ return rewriteFreeIdentifiers(code, node, scopeRewrites, jsxNodes, compileRootJsx, compileNestedComponent)
546
570
  }
547
571
 
548
572
  function compileComponentCall(node: JSXElement, scopeRewrites: ReadonlyMap<string, string>): string {
@@ -579,11 +603,8 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
579
603
  else if (attr.value.type === 'JSXExpressionContainer' && attr.value.expression.type !== 'JSXEmptyExpression') {
580
604
  const expr = attr.value.expression
581
605
  const exprCode = compileExpression(expr, scopeRewrites)
582
- // Reactive getter for dynamic expressions; plain property for literals and inline functions.
583
- const isStatic = expr.type === 'Literal'
584
- || expr.type === 'ArrowFunctionExpression'
585
- || expr.type === 'FunctionExpression'
586
- if (isStatic)
606
+ // Reactive getter for dynamic expressions; plain property for identifiers, constant literals/collections, and inline functions.
607
+ if (isStaticPropExpr(expr, scopeRewrites))
587
608
  currentObj.push(`${propKey}: ${exprCode}`)
588
609
  else
589
610
  currentObj.push(`get ${propKey}() { return ${exprCode} }`)
@@ -751,7 +772,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
751
772
  return html
752
773
 
753
774
  const meaningful = filterMeaningfulChildren(el.children)
754
- const slots = meaningful.map(c => classifyJsxChild(c)).filter(s => s !== undefined)
775
+ const slots = meaningful.map(c => classifyJsxChild(c, jsxNodes)).filter(s => s !== undefined)
755
776
  const hasSiblings = slots.length > 1
756
777
  let domIndex = 0
757
778
  let prevWasStaticText = false
@@ -944,7 +965,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
944
965
 
945
966
  // Generic expression slot
946
967
  const exprCode = compileExpression(slot.expr, scopeRewrites)
947
- if (isNodeCapableExpr(slot.expr)) {
968
+ if (isNodeCapableExpr(slot.expr, jsxNodes)) {
948
969
  if (!hasSiblings) {
949
970
  ops.push(`${use('insert')}(${elVar}, () => ${exprCode}, null, null);`)
950
971
  }
@@ -1094,7 +1115,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1094
1115
  return `document.createTextNode(${JSON.stringify(decodeHtmlEntities(cleanJsxText(child.value)))})`
1095
1116
  if (child.type === 'JSXExpressionContainer' && child.expression.type !== 'JSXEmptyExpression') {
1096
1117
  const exprCode = compileExpression(child.expression, scopeRewrites)
1097
- if (isNodeCapableExpr(child.expression))
1118
+ if (isNodeCapableExpr(child.expression, jsxNodes))
1098
1119
  return `(() => { const _f = document.createDocumentFragment(); ${use('insert')}(_f, () => (${exprCode}), null, null); return _f; })()`
1099
1120
  return `(() => { const _t = document.createTextNode(""); ${use('effect')}(() => ${use('setText')}(_t, (${exprCode}))); return _t; })()`
1100
1121
  }
@@ -1180,7 +1201,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1180
1201
 
1181
1202
  // Handle top-level component functions with destructured props + JSX compilation
1182
1203
  function processFunction(fn: ArrowFunctionExpression | OxcFunction): void {
1183
- if (fn.body === null || !containsJsx(fn.body))
1204
+ if (fn.body === null || !containsJsx(fn.body, jsxNodes))
1184
1205
  return
1185
1206
 
1186
1207
  const destructured = extractDestructuredParam(fn.params[0])
@@ -1209,7 +1230,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
1209
1230
  if (!shadowed.has(k))
1210
1231
  active.set(k, v)
1211
1232
  }
1212
- if (active.size > 0 || containsJsx(stmt))
1233
+ if (active.size > 0 || containsJsx(stmt, jsxNodes))
1213
1234
  editor.replace(stmt.start, stmt.end, compileExpression(stmt, active))
1214
1235
  if (stmt.type === 'VariableDeclaration') {
1215
1236
  for (const d of stmt.declarations)
@@ -90,13 +90,13 @@ function isEnvRoot(node: Node, shadowed: ReadonlySet<string>): 'process' | 'bun'
90
90
  return undefined
91
91
  }
92
92
 
93
- /** True when the module reads `process.env` or `Bun.env` outside its `load()` (stripped from client code) for a key the client build does not inline. */
94
- export function readsPrivateEnv(program: Program, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): boolean {
95
- let found = false
93
+ /** Byte offset of the first `process.env` or `Bun.env` read outside `load()` for a key the client build does not inline, or `undefined`. */
94
+ export function findPrivateEnvOffset(program: Program, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): number | undefined {
95
+ let foundOffset: number | undefined
96
96
  const loadCode = new Set<Node>(loadDeclarations(program))
97
97
 
98
98
  function visit(node: unknown, shadowed: Set<string>): void {
99
- if (found || node === null || typeof node !== 'object')
99
+ if (foundOffset !== undefined || node === null || typeof node !== 'object')
100
100
  return
101
101
  if (Array.isArray(node)) {
102
102
  for (let i = 0; i < node.length; i++)
@@ -112,15 +112,16 @@ export function readsPrivateEnv(program: Program, isInlined: (key: string) => bo
112
112
  if (rootKind !== undefined) {
113
113
  // Bun.env is never statically inlined in browser bundles.
114
114
  if (rootKind === 'bun') {
115
- found = true
115
+ foundOffset = n.start
116
116
  return
117
117
  }
118
118
  const key = propKeyName(n)
119
- found = key === undefined || !isInlined(key)
119
+ if (key === undefined || !isInlined(key))
120
+ foundOffset = n.start
120
121
  return
121
122
  }
122
123
  if (isEnvRoot(n, shadowed) !== undefined) {
123
- found = true
124
+ foundOffset = n.start
124
125
  return
125
126
  }
126
127
  }
@@ -201,5 +202,10 @@ export function readsPrivateEnv(program: Program, isInlined: (key: string) => bo
201
202
  }
202
203
 
203
204
  visit(program, new Set())
204
- return found
205
+ return foundOffset
206
+ }
207
+
208
+ /** True when the module reads `process.env` or `Bun.env` outside its `load()` (stripped from client code) for a key the client build does not inline. */
209
+ export function readsPrivateEnv(program: Program, isInlined: (key: string) => boolean = key => CLIENT_ENV_KEY.test(key)): boolean {
210
+ return findPrivateEnvOffset(program, isInlined) !== undefined
205
211
  }