@kayjs/kay 2.0.0-beta.0 → 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.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
@@ -0,0 +1,485 @@
1
+ // Shared compiler helpers & JSX child/hydration IR classification used by both `ssr.ts` and `dom.ts`.
2
+
3
+ import type {
4
+ ArrowFunctionExpression,
5
+ BlockStatement,
6
+ CallExpression,
7
+ ConditionalExpression,
8
+ Expression,
9
+ Function as OxcFunction,
10
+ JSXChild,
11
+ JSXElement,
12
+ JSXElementName,
13
+ JSXExpressionContainer,
14
+ JSXFragment,
15
+ JSXNamespacedName,
16
+ LogicalExpression,
17
+ Node,
18
+ ParamPattern,
19
+ Program,
20
+ } from 'oxc-parser'
21
+ import { walk } from './analyze'
22
+
23
+ export { DOM_PROPS, isBlockedAttr, isStringBoolAttr, isUnsafeUrlAttr } from '../attrs'
24
+
25
+ export const VOID_ELEMENTS = new Set([
26
+ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
27
+ 'link', 'meta', 'param', 'source', 'track', 'wbr',
28
+ ])
29
+
30
+ export const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
31
+ export const EVENT_ATTR = /^on([A-Z]\w*)$/
32
+
33
+ const CLOSE_STYLE_RE = /<\/(style)/gi
34
+ const SCRIPT_UNSAFE_RE = /<(\/script|script|!--)/gi
35
+ const LINE_BREAK_RE = /\r\n|\n|\r/
36
+
37
+ export function escapeRawText(str: string, tag: 'style' | 'script'): string {
38
+ if (tag === 'script') {
39
+ return str.replace(SCRIPT_UNSAFE_RE, (_, body: string) =>
40
+ body.charCodeAt(0) === 47 ? `<\\${body}` : `\\u003c${body}`)
41
+ }
42
+ return str.replace(CLOSE_STYLE_RE, '<\\/$1')
43
+ }
44
+
45
+ export function escapeStaticText(str: string): string {
46
+ return str.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
47
+ }
48
+
49
+ export function escapeStaticAttr(str: string): string {
50
+ return escapeStaticText(str).replaceAll('"', '&quot;')
51
+ }
52
+
53
+ const HTML_ENTITIES: Record<string, string> = {
54
+ // Core XML/HTML & whitespace
55
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: '\'', nbsp: '\u00A0',
56
+ ensp: '\u2002', emsp: '\u2003', thinsp: '\u2009', zwnj: '\u200C', zwj: '\u200D', lrm: '\u200E', rlm: '\u200F', shy: '\u00AD',
57
+ // Punctuation & symbols
58
+ ndash: '\u2013', mdash: '\u2014', lsquo: '\u2018', rsquo: '\u2019', sbquo: '\u201A',
59
+ ldquo: '\u201C', rdquo: '\u201D', bdquo: '\u201E', hellip: '\u2026', bull: '\u2022',
60
+ middot: '\u00B7', laquo: '\u00AB', raquo: '\u00BB', lsaquo: '\u2039', rsaquo: '\u203A',
61
+ prime: '\u2032', Prime: '\u2033', sect: '\u00A7', para: '\u00B6', dagger: '\u2020', Dagger: '\u2021', permil: '\u2030',
62
+ iexcl: '\u00A1', iquest: '\u00BF', brvbar: '\u00A6', macr: '\u00AF', acute: '\u00B4', cedil: '\u00B8', uml: '\u00A8',
63
+ ordf: '\u00AA', ordm: '\u00BA', not: '\u00AC', loz: '\u25CA',
64
+ // Suits, stars & checkmarks
65
+ spades: '\u2660', clubs: '\u2663', hearts: '\u2665', diams: '\u2666',
66
+ star: '\u2606', check: '\u2713', checkmark: '\u2713', cross: '\u2717',
67
+ // Currency & legal
68
+ copy: '\u00A9', reg: '\u00AE', trade: '\u2122', euro: '\u20AC', pound: '\u00A3', yen: '\u00A5', cent: '\u00A2', curren: '\u00A4',
69
+ // Math & arrows
70
+ deg: '\u00B0', plusmn: '\u00B1', times: '\u00D7', divide: '\u00F7',
71
+ frac12: '\u00BD', frac14: '\u00BC', frac34: '\u00BE', sup1: '\u00B9', sup2: '\u00B2', sup3: '\u00B3',
72
+ micro: '\u00B5', minus: '\u2212', ne: '\u2260', le: '\u2264', ge: '\u2265', approx: '\u2248', infin: '\u221E',
73
+ sum: '\u2211', prod: '\u220F', radic: '\u221A', int: '\u222B', part: '\u2202', empty: '\u2205', nabla: '\u2207',
74
+ isin: '\u2208', notin: '\u2209', ni: '\u220B', cap: '\u2229', cup: '\u222A', sub: '\u2282', sup: '\u2283',
75
+ nsub: '\u2284', sube: '\u2286', supe: '\u2287', oplus: '\u2295', otimes: '\u2297', perp: '\u22A5', sdot: '\u22C5',
76
+ equiv: '\u2261', cong: '\u2245', asymp: '\u2248', prop: '\u221D', and: '\u2227', or: '\u2228', forall: '\u2200', exist: '\u2203',
77
+ larr: '\u2190', uarr: '\u2191', rarr: '\u2192', darr: '\u2193', harr: '\u2194', crarr: '\u21B5',
78
+ lArr: '\u21D0', uArr: '\u21D1', rArr: '\u21D2', dArr: '\u21D3', hArr: '\u21D4',
79
+ // Greek
80
+ Alpha: '\u0391', Beta: '\u0392', Gamma: '\u0393', Delta: '\u0394', Epsilon: '\u0395', Zeta: '\u0396', Eta: '\u0397', Theta: '\u0398',
81
+ Iota: '\u0399', Kappa: '\u039A', Lambda: '\u039B', Mu: '\u039C', Nu: '\u039D', Xi: '\u039E', Omicron: '\u039F', Pi: '\u03A0',
82
+ Rho: '\u03A1', Sigma: '\u03A3', Tau: '\u03A4', Upsilon: '\u03A5', Phi: '\u03A6', Chi: '\u03A7', Psi: '\u03A8', Omega: '\u03A9',
83
+ alpha: '\u03B1', beta: '\u03B2', gamma: '\u03B3', delta: '\u03B4', epsilon: '\u03B5', zeta: '\u03B6', eta: '\u03B7', theta: '\u03B8',
84
+ iota: '\u03B9', kappa: '\u03BA', lambda: '\u03BB', mu: '\u03BC', nu: '\u03BD', xi: '\u03BE', omicron: '\u03BF', pi: '\u03C0',
85
+ rho: '\u03C1', sigmaf: '\u03C2', sigma: '\u03C3', tau: '\u03C4', upsilon: '\u03C5', phi: '\u03C6', chi: '\u03C7', psi: '\u03C8', omega: '\u03C9',
86
+ // Latin-1 & European accents
87
+ Agrave: '\u00C0', Aacute: '\u00C1', Acirc: '\u00C2', Atilde: '\u00C3', Auml: '\u00C4', Aring: '\u00C5', AElig: '\u00C6', Ccedil: '\u00C7',
88
+ Egrave: '\u00C8', Eacute: '\u00C9', Ecirc: '\u00CA', Euml: '\u00CB', Igrave: '\u00CC', Iacute: '\u00CD', Icirc: '\u00CE', Iuml: '\u00CF',
89
+ ETH: '\u00D0', Ntilde: '\u00D1', Ograve: '\u00D2', Oacute: '\u00D3', Ocirc: '\u00D4', Otilde: '\u00D5', Ouml: '\u00D6', Oslash: '\u00D8',
90
+ Ugrave: '\u00D9', Uacute: '\u00DA', Ucirc: '\u00DB', Uuml: '\u00DC', Yacute: '\u00DD', THORN: '\u00DE', szlig: '\u00DF',
91
+ agrave: '\u00E0', aacute: '\u00E1', acirc: '\u00E2', atilde: '\u00E3', auml: '\u00E4', aring: '\u00E5', aelig: '\u00E6', ccedil: '\u00E7',
92
+ egrave: '\u00E8', eacute: '\u00E9', ecirc: '\u00EA', euml: '\u00EB', igrave: '\u00EC', iacute: '\u00ED', icirc: '\u00EE', iuml: '\u00EF',
93
+ eth: '\u00F0', ntilde: '\u00F1', ograve: '\u00F2', oacute: '\u00F3', ocirc: '\u00F4', otilde: '\u00F5', ouml: '\u00F6', oslash: '\u00F8',
94
+ ugrave: '\u00F9', uacute: '\u00FA', ucirc: '\u00FB', uuml: '\u00FC', yacute: '\u00FD', thorn: '\u00FE', yuml: '\u00FF',
95
+ OElig: '\u0152', oelig: '\u0153', Scaron: '\u0160', scaron: '\u0161', Yuml: '\u0178',
96
+ }
97
+
98
+ const ENTITY_RE = /&(?:#(\d+)|#x([0-9a-fA-F]+)|([A-Za-z][A-Za-z0-9]*));/g
99
+
100
+ export function decodeHtmlEntities(str: string): string {
101
+ if (!str.includes('&'))
102
+ return str
103
+ return str.replace(ENTITY_RE, (match, dec: string | undefined, hex: string | undefined, named: string | undefined) => {
104
+ if (dec !== undefined) {
105
+ const cp = Number.parseInt(dec, 10)
106
+ return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
107
+ }
108
+ if (hex !== undefined) {
109
+ const cp = Number.parseInt(hex, 16)
110
+ return cp === 0 || cp > 0x10FFFF || (cp >= 0xD800 && cp <= 0xDFFF) ? '\uFFFD' : String.fromCodePoint(cp)
111
+ }
112
+ if (named !== undefined && Object.hasOwn(HTML_ENTITIES, named))
113
+ return HTML_ENTITIES[named]!
114
+ return match
115
+ })
116
+ }
117
+
118
+ export function offsetToLineCol(code: string, offset: number): { line: number, col: number } {
119
+ let line = 1
120
+ let col = 1
121
+ const end = Math.min(Math.max(0, offset), code.length)
122
+ for (let i = 0; i < end; i++) {
123
+ if (code.charCodeAt(i) === 10) {
124
+ line++
125
+ col = 1
126
+ }
127
+ else {
128
+ col++
129
+ }
130
+ }
131
+ return { line, col }
132
+ }
133
+
134
+ export function formatLoc(filename: string, code: string, offset?: number): string {
135
+ if (offset === undefined || offset < 0)
136
+ return filename
137
+ const { line, col } = offsetToLineCol(code, offset)
138
+ return `${filename}:${line}:${col}`
139
+ }
140
+
141
+ /** Renders a short source code frame around `offset` with 1 context line before/after and a caret underline. */
142
+ export function formatCodeFrame(code: string, offset: number, endOffset?: number): string {
143
+ if (code.length === 0)
144
+ return ''
145
+ const clamped = Math.min(Math.max(0, offset), code.length)
146
+ const { line, col } = offsetToLineCol(code, clamped)
147
+ const lines = code.split(/\r?\n/)
148
+ const lineIdx = Math.min(line - 1, lines.length - 1)
149
+ const startIdx = Math.max(0, lineIdx - 1)
150
+ const endIdx = Math.min(lines.length - 1, lineIdx + 1)
151
+ const gutterWidth = String(endIdx + 1).length
152
+ const pad = (n: number | '') => String(n).padStart(gutterWidth, ' ')
153
+ const targetLine = lines[lineIdx] ?? ''
154
+ const maxSpan = Math.max(1, targetLine.length - (col - 1))
155
+ const rawSpan = endOffset !== undefined && endOffset > clamped ? endOffset - clamped : 1
156
+ const caretLen = Math.max(1, Math.min(rawSpan, maxSpan))
157
+ const out: string[] = []
158
+ for (let i = startIdx; i <= endIdx; i++) {
159
+ const text = lines[i] ?? ''
160
+ out.push(` ${pad(i + 1)} | ${text}`)
161
+ if (i === lineIdx)
162
+ out.push(` ${pad('')} | ${' '.repeat(Math.max(0, col - 1))}${'^'.repeat(caretLen)}`)
163
+ }
164
+ return out.join('\n')
165
+ }
166
+
167
+ export const DIAGNOSTIC_PREFIX_RE = /^.+:\d+:\d+:\s+(?:error|warning):/
168
+
169
+ export function formatDiagnostic(loc: string, message: string, severity: 'error' | 'warning' = 'error'): string {
170
+ return `${loc}: ${severity}: ${message}`
171
+ }
172
+
173
+ export function cleanJsxText(raw: string): string {
174
+ if (!LINE_BREAK_RE.test(raw))
175
+ return raw
176
+ const lines = raw.split(LINE_BREAK_RE)
177
+ let out = ''
178
+ for (let i = 0; i < lines.length; i++) {
179
+ let line = lines[i]!.replace(/\t/g, ' ')
180
+ if (i > 0)
181
+ line = line.replace(/^ +/, '')
182
+ if (i < lines.length - 1)
183
+ line = line.replace(/ +$/, '')
184
+ if (line !== '') {
185
+ if (out !== '')
186
+ out += ' '
187
+ out += line
188
+ }
189
+ }
190
+ return out
191
+ }
192
+
193
+ export function jsxTagName(node: JSXElementName | JSXNamespacedName | { type: 'JSXIdentifier', name: string }): string {
194
+ if (node.type === 'JSXIdentifier')
195
+ return node.name
196
+ if (node.type === 'JSXMemberExpression')
197
+ return `${jsxTagName(node.object)}.${node.property.name}`
198
+ if (node.type === 'JSXNamespacedName')
199
+ return `${node.namespace.name}:${node.name.name}`
200
+ return ''
201
+ }
202
+
203
+ export function isComponentTag(tag: string): boolean {
204
+ const first = tag.charCodeAt(0)
205
+ return (first >= 65 && first <= 90) || tag.includes('.')
206
+ }
207
+
208
+ export function unwrapParens(node: Node): Node {
209
+ let cur = node
210
+ while (cur.type === 'ParenthesizedExpression')
211
+ cur = cur.expression
212
+ return cur
213
+ }
214
+
215
+ export function unwrapTsExpr(node: Node): Node {
216
+ let cur = node
217
+ while (
218
+ cur.type === 'ParenthesizedExpression'
219
+ || cur.type === 'TSAsExpression'
220
+ || cur.type === 'TSSatisfiesExpression'
221
+ || cur.type === 'TSNonNullExpression'
222
+ || cur.type === 'TSTypeAssertion'
223
+ ) {
224
+ cur = cur.expression
225
+ }
226
+ return cur
227
+ }
228
+
229
+ export function staticLiteral(node: Node): { ok: true, value: string | number | boolean | null } | { ok: false } {
230
+ const n = unwrapParens(node)
231
+ if (n.type === 'Literal') {
232
+ const v = n.value
233
+ if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || v === null)
234
+ return { ok: true, value: v }
235
+ }
236
+ if (n.type === 'UnaryExpression' && n.operator === '-' && n.argument.type === 'Literal' && typeof n.argument.value === 'number')
237
+ return { ok: true, value: -n.argument.value }
238
+ return { ok: false }
239
+ }
240
+
241
+ export function isJsxNode(node: Node | null | undefined): node is JSXElement | JSXFragment {
242
+ return node?.type === 'JSXElement' || node?.type === 'JSXFragment'
243
+ }
244
+
245
+ /** Whether JSX appears anywhere inside `node`, itself included. Uses O(1) lookup when precomputed `jsxNodes` is passed. */
246
+ export function containsJsx(node: Node | null | undefined, jsxNodes?: WeakSet<Node>): boolean {
247
+ if (node === null || node === undefined)
248
+ return false
249
+ if (jsxNodes !== undefined)
250
+ return jsxNodes.has(node)
251
+ let found = false
252
+ walk(node, (child) => {
253
+ if (found)
254
+ return false
255
+ if (isJsxNode(child))
256
+ found = true
257
+ return undefined
258
+ })
259
+ return found
260
+ }
261
+
262
+ /** Whether a BlockStatement directly returns JSX (ignoring nested functions). */
263
+ export function blockReturnsJsx(block: BlockStatement, jsxNodes?: WeakSet<Node>): boolean {
264
+ if (jsxNodes !== undefined && !jsxNodes.has(block))
265
+ return false
266
+ let found = false
267
+ walk(block, (child) => {
268
+ if (found)
269
+ return false
270
+ if (child !== block && (
271
+ child.type === 'ArrowFunctionExpression'
272
+ || child.type === 'FunctionExpression'
273
+ || child.type === 'FunctionDeclaration'
274
+ )) {
275
+ return false
276
+ }
277
+ if (child.type === 'ReturnStatement' && child.argument !== null && containsJsx(child.argument, jsxNodes)) {
278
+ found = true
279
+ return false
280
+ }
281
+ return undefined
282
+ })
283
+ return found
284
+ }
285
+
286
+ export function filterMeaningfulChildren(children: readonly JSXChild[]): JSXChild[] {
287
+ return children.filter((c) => {
288
+ if (c.type === 'JSXText')
289
+ return cleanJsxText(c.value) !== ''
290
+ if (c.type === 'JSXExpressionContainer' && c.expression.type === 'JSXEmptyExpression')
291
+ return false
292
+ // Empty string literal `{""}` produces zero DOM nodes on SSR and DOM alike.
293
+ if (c.type === 'JSXExpressionContainer' && c.expression.type === 'Literal' && c.expression.value === '')
294
+ return false
295
+ return true
296
+ })
297
+ }
298
+
299
+ export interface MapCallMatch {
300
+ call: CallExpression
301
+ target: Expression
302
+ cb: ArrowFunctionExpression | OxcFunction
303
+ body: JSXElement | JSXFragment | BlockStatement
304
+ isJsxBody: boolean
305
+ params: readonly ParamPattern[]
306
+ }
307
+
308
+ /** Recognizes `arr.map((item, idx?) => <jsx> | { ... return <jsx> })` identically in SSR and DOM compilers. */
309
+ export function matchJsxMapCall(expr: Node, jsxNodes?: WeakSet<Node>): MapCallMatch | undefined {
310
+ if (
311
+ expr.type !== 'CallExpression'
312
+ || expr.callee.type !== 'MemberExpression'
313
+ || expr.callee.computed
314
+ || expr.callee.property.type !== 'Identifier'
315
+ || expr.callee.property.name !== 'map'
316
+ || expr.arguments.length !== 1
317
+ ) {
318
+ return undefined
319
+ }
320
+ const arg = expr.arguments[0]
321
+ if (arg === undefined || (arg.type !== 'ArrowFunctionExpression' && arg.type !== 'FunctionExpression'))
322
+ return undefined
323
+ if (arg.async || arg.body === null)
324
+ return undefined
325
+ // 3rd `(item, idx, arr)` param or rest param cannot be mapped cleanly to `(item, idx)` loop signals.
326
+ if (arg.params.length > 2 || arg.params.some(p => p.type === 'RestElement'))
327
+ return undefined
328
+ const body = unwrapParens(arg.body)
329
+ if (isJsxNode(body))
330
+ return { call: expr, target: expr.callee.object, cb: arg, body, isJsxBody: true, params: arg.params }
331
+ if (body.type === 'BlockStatement' && blockReturnsJsx(body, jsxNodes))
332
+ return { call: expr, target: expr.callee.object, cb: arg, body, isJsxBody: false, params: arg.params }
333
+ return undefined
334
+ }
335
+
336
+ export function isStaticBranch(node: Node): boolean {
337
+ const n = unwrapParens(node)
338
+ if (isJsxNode(n))
339
+ return true
340
+ if (n.type === 'Identifier' && n.name === 'undefined')
341
+ return true
342
+ return staticLiteral(n).ok
343
+ }
344
+
345
+ export type ChildSlotKind =
346
+ | { kind: 'static-text', text: string, fromLiteral: boolean }
347
+ | { kind: 'element', node: JSXElement }
348
+ | { kind: 'component', node: JSXElement }
349
+ | { kind: 'fragment', node: JSXFragment }
350
+ | { kind: 'loop', match: MapCallMatch }
351
+ | { kind: 'and-show', expr: LogicalExpression, right: JSXElement | JSXFragment }
352
+ | { kind: 'ternary-show', expr: ConditionalExpression, cons: Node, alt: Node }
353
+ | { kind: 'expr', container: JSXExpressionContainer, expr: Expression }
354
+
355
+ /**
356
+ * Single shared child classifier for SSR & DOM codegen.
357
+ * Both emitters derive exact hydration marker placement (`<!--k[-->...<!--k]-->` vs `<!---->`) from this classification.
358
+ */
359
+ export function classifyJsxChild(child: JSXChild, jsxNodes?: WeakSet<Node>): ChildSlotKind | undefined {
360
+ if (child.type === 'JSXText') {
361
+ const text = cleanJsxText(child.value)
362
+ return text === '' ? undefined : { kind: 'static-text', text, fromLiteral: false }
363
+ }
364
+ if (child.type === 'JSXFragment')
365
+ return { kind: 'fragment', node: child }
366
+ if (child.type === 'JSXElement') {
367
+ const tag = jsxTagName(child.openingElement.name)
368
+ return isComponentTag(tag)
369
+ ? { kind: 'component', node: child }
370
+ : { kind: 'element', node: child }
371
+ }
372
+ if (child.type === 'JSXExpressionContainer') {
373
+ if (child.expression.type === 'JSXEmptyExpression')
374
+ return undefined
375
+ const expr = child.expression
376
+ if (expr.type === 'Literal' && typeof expr.value === 'string') {
377
+ return expr.value === ''
378
+ ? undefined
379
+ : { kind: 'static-text', text: expr.value, fromLiteral: true }
380
+ }
381
+ const mapMatch = matchJsxMapCall(expr, jsxNodes)
382
+ if (mapMatch !== undefined)
383
+ return { kind: 'loop', match: mapMatch }
384
+ if (expr.type === 'LogicalExpression' && expr.operator === '&&') {
385
+ const right = unwrapParens(expr.right)
386
+ if (isJsxNode(right))
387
+ return { kind: 'and-show', expr, right }
388
+ }
389
+ if (expr.type === 'ConditionalExpression') {
390
+ const cons = unwrapParens(expr.consequent)
391
+ const alt = unwrapParens(expr.alternate)
392
+ // Use `show()` only when at least one branch is JSX and the other branch is JSX or a static literal/nullish;
393
+ // mixed dynamic text (`cond ? <span/> : count.value`) goes through `expr` (`insert`) so both branches stay reactive.
394
+ if ((isJsxNode(cons) && isStaticBranch(alt)) || (isJsxNode(alt) && isStaticBranch(cons)))
395
+ return { kind: 'ternary-show', expr, cons, alt }
396
+ }
397
+ return { kind: 'expr', container: child, expr }
398
+ }
399
+ return undefined
400
+ }
401
+
402
+ /** Collects every identifier name bound by a destructuring/parameter pattern. */
403
+ export function collectPatternNames(pattern: Node | null | undefined, out: Set<string>): void {
404
+ if (pattern === null || pattern === undefined)
405
+ return
406
+ switch (pattern.type) {
407
+ case 'Identifier':
408
+ out.add(pattern.name)
409
+ return
410
+ case 'AssignmentPattern':
411
+ collectPatternNames(pattern.left, out)
412
+ return
413
+ case 'RestElement':
414
+ collectPatternNames(pattern.argument, out)
415
+ return
416
+ case 'TSParameterProperty':
417
+ collectPatternNames(pattern.parameter, out)
418
+ return
419
+ case 'ArrayPattern':
420
+ for (const el of pattern.elements) {
421
+ if (el !== null)
422
+ collectPatternNames(el, out)
423
+ }
424
+ return
425
+ case 'ObjectPattern':
426
+ for (const prop of pattern.properties) {
427
+ if (prop.type === 'RestElement')
428
+ collectPatternNames(prop.argument, out)
429
+ else
430
+ collectPatternNames(prop.value, out)
431
+ }
432
+ }
433
+ }
434
+
435
+ const PRIMITIVE_GLOBALS = new Set([
436
+ 'String', 'Number', 'Boolean', 'parseInt', 'parseFloat',
437
+ 'encodeURI', 'encodeURIComponent', 'decodeURI', 'decodeURIComponent',
438
+ ])
439
+
440
+ const PRIMITIVE_METHODS = new Set([
441
+ 'toString', 'toFixed', 'toPrecision', 'toExponential', 'toLocaleString',
442
+ 'toLocaleDateString', 'toLocaleTimeString', 'toISOString', 'toUpperCase',
443
+ 'toLowerCase', 'toLocaleUpperCase', 'toLocaleLowerCase', 'trim', 'trimStart',
444
+ 'trimEnd', 'join', 'padStart', 'padEnd', 'repeat', 'replace', 'replaceAll',
445
+ 'substring', 'substr', 'charAt', 'charCodeAt', 'codePointAt', 'indexOf',
446
+ 'lastIndexOf', 'includes', 'startsWith', 'endsWith', 'getTime', 'getFullYear',
447
+ 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds',
448
+ ])
449
+
450
+ function isKnownPrimitiveCall(node: CallExpression): boolean {
451
+ const callee = node.callee
452
+ if (callee.type === 'Identifier' && PRIMITIVE_GLOBALS.has(callee.name))
453
+ return true
454
+ if (callee.type === 'MemberExpression' && !callee.computed && callee.property.type === 'Identifier') {
455
+ const prop = callee.property.name
456
+ if (callee.object.type === 'Identifier') {
457
+ const obj = callee.object.name
458
+ if (obj === 'Math' || (obj === 'JSON' && prop === 'stringify') || (obj === 'Date' && prop === 'now'))
459
+ return true
460
+ }
461
+ if (PRIMITIVE_METHODS.has(prop))
462
+ return true
463
+ }
464
+ return false
465
+ }
466
+
467
+ export function mayReturnNode(node: Node): boolean {
468
+ const cur = unwrapTsExpr(node)
469
+ if (cur.type === 'CallExpression')
470
+ return !isKnownPrimitiveCall(cur)
471
+ if (cur.type === 'LogicalExpression')
472
+ return mayReturnNode(cur.left) || mayReturnNode(cur.right)
473
+ if (cur.type === 'ConditionalExpression')
474
+ return mayReturnNode(cur.consequent) || mayReturnNode(cur.alternate)
475
+ return false
476
+ }
477
+
478
+ /** Shared SSR/DOM check for whether a dynamic expression slot may produce DOM nodes/fragments (requiring balanced `<!--k[-->...<!--k]-->` markers). */
479
+ export function isNodeCapableExpr(expr: Expression, jsxNodes?: WeakSet<Node>): boolean {
480
+ const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
481
+ || (expr.type === 'MemberExpression' && !expr.computed && expr.property.type === 'Identifier' && expr.property.name === 'children')
482
+ return isChildrenExpr || containsJsx(expr, jsxNodes) || mayReturnNode(expr)
483
+ }
484
+
485
+ export type { Program }