@kayjs/kay 2.0.0-alpha.5 → 2.0.0-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/build/compile.ts +18 -11
- package/src/build/index.ts +454 -43
- package/src/cli/check.ts +165 -4
- package/src/cli/index.ts +7 -4
- package/src/cli/new.ts +1 -1
- package/src/compiler/dom.ts +151 -37
- package/src/compiler/ssr.ts +16 -1
- package/src/dev/index.ts +135 -22
- package/src/dom/extras.ts +67 -11
- package/src/dom/index.ts +3 -3
- package/src/dom/island.ts +97 -75
- package/src/plugins/index.ts +35 -2
- package/src/server/action.ts +47 -0
- package/src/server/compress.ts +241 -0
- package/src/server/cookies.ts +4 -0
- package/src/server/http.ts +44 -9
- package/src/server/index.ts +510 -193
- package/src/server/security.ts +81 -1
- package/src/ssr/context.ts +5 -2
- package/src/ssr/index.ts +30 -3
package/src/cli/check.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
// `kay check [dir]`: validates routes, Kay compiler rules, config, and runs TypeScript type-checking.
|
|
1
|
+
// `kay check [dir]`: validates routes, Kay compiler & island rules, config, and runs TypeScript type-checking.
|
|
2
2
|
|
|
3
|
+
import type { AstNode, ModuleAnalysis } from '../compiler/analyze'
|
|
3
4
|
import { existsSync, readdirSync, readFileSync } from 'node:fs'
|
|
4
|
-
import { join, relative, resolve } from 'node:path'
|
|
5
|
-
import { analyzeModule } from '../compiler/
|
|
5
|
+
import { basename, dirname, join, relative, resolve } from 'node:path'
|
|
6
|
+
import { analyzeModule, walk } from '../compiler/analyze'
|
|
6
7
|
import { loadConfig } from '../plugins/index'
|
|
7
8
|
|
|
8
9
|
export interface CheckResult {
|
|
@@ -11,6 +12,35 @@ export interface CheckResult {
|
|
|
11
12
|
errors: string[]
|
|
12
13
|
}
|
|
13
14
|
|
|
15
|
+
const SERVER_ONLY_MODULES = new Set([
|
|
16
|
+
'kay/server',
|
|
17
|
+
'@kayjs/kay/server',
|
|
18
|
+
'bun:sqlite',
|
|
19
|
+
'bun:ffi',
|
|
20
|
+
'bun:dns',
|
|
21
|
+
'node:fs',
|
|
22
|
+
'node:fs/promises',
|
|
23
|
+
'node:child_process',
|
|
24
|
+
'node:net',
|
|
25
|
+
'node:http',
|
|
26
|
+
'node:https',
|
|
27
|
+
'node:http2',
|
|
28
|
+
'node:os',
|
|
29
|
+
'node:worker_threads',
|
|
30
|
+
'node:cluster',
|
|
31
|
+
'node:dgram',
|
|
32
|
+
'node:tls',
|
|
33
|
+
'node:readline',
|
|
34
|
+
'fs',
|
|
35
|
+
'fs/promises',
|
|
36
|
+
'child_process',
|
|
37
|
+
'net',
|
|
38
|
+
'http',
|
|
39
|
+
'https',
|
|
40
|
+
])
|
|
41
|
+
|
|
42
|
+
const SERIALIZABLE_NEW_CTORS = new Set(['Date', 'Map', 'Set', 'URL', 'RegExp'])
|
|
43
|
+
|
|
14
44
|
function walkTsFiles(dir: string, out: string[] = []): string[] {
|
|
15
45
|
if (!existsSync(dir))
|
|
16
46
|
return out
|
|
@@ -28,14 +58,38 @@ function walkTsFiles(dir: string, out: string[] = []): string[] {
|
|
|
28
58
|
return out
|
|
29
59
|
}
|
|
30
60
|
|
|
61
|
+
function resolveLocalModule(fromFile: string, specifier: string): string | undefined {
|
|
62
|
+
if (!specifier.startsWith('.'))
|
|
63
|
+
return undefined
|
|
64
|
+
const base = resolve(dirname(fromFile), specifier)
|
|
65
|
+
for (const c of [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]) {
|
|
66
|
+
if (existsSync(c))
|
|
67
|
+
return c
|
|
68
|
+
}
|
|
69
|
+
return undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function normalizeRouteConflictKey(routesDir: string, file: string): string {
|
|
73
|
+
const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
|
|
74
|
+
if (rel === 'index')
|
|
75
|
+
return '/'
|
|
76
|
+
const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
|
|
77
|
+
const norm = clean
|
|
78
|
+
.replace(/\[\.\.\.[^\]]+\]/g, '*')
|
|
79
|
+
.replace(/\[[^\]]+\]/g, ':')
|
|
80
|
+
return `/${norm}`
|
|
81
|
+
}
|
|
82
|
+
|
|
31
83
|
export async function checkProject(rootDir: string, options: { skipTypecheck?: boolean } = {}): Promise<CheckResult> {
|
|
32
84
|
const root = resolve(rootDir)
|
|
33
85
|
const errors: string[] = []
|
|
34
86
|
|
|
35
87
|
// 1. Validate kay.config.ts
|
|
36
88
|
let routesDir = resolve(root, 'src/routes')
|
|
89
|
+
let plugins: Awaited<ReturnType<typeof loadConfig>>['plugins'] = []
|
|
37
90
|
try {
|
|
38
91
|
const cfg = await loadConfig(root)
|
|
92
|
+
plugins = cfg.plugins ?? []
|
|
39
93
|
if (cfg.routesDir !== undefined)
|
|
40
94
|
routesDir = resolve(root, cfg.routesDir)
|
|
41
95
|
}
|
|
@@ -50,16 +104,123 @@ export async function checkProject(rootDir: string, options: { skipTypecheck?: b
|
|
|
50
104
|
// 3. Parse & run Kay static compiler analysis across src/
|
|
51
105
|
const srcDir = resolve(root, 'src')
|
|
52
106
|
const files = walkTsFiles(existsSync(srcDir) ? srcDir : routesDir)
|
|
107
|
+
const analyses = new Map<string, ModuleAnalysis>()
|
|
108
|
+
|
|
53
109
|
for (const file of files) {
|
|
54
110
|
try {
|
|
55
111
|
const code = readFileSync(file, 'utf8')
|
|
56
|
-
analyzeModule(file, code)
|
|
112
|
+
analyses.set(file, analyzeModule(file, code))
|
|
57
113
|
}
|
|
58
114
|
catch (err) {
|
|
59
115
|
errors.push(err instanceof Error ? err.message : String(err))
|
|
60
116
|
}
|
|
61
117
|
}
|
|
62
118
|
|
|
119
|
+
// 3b. Static guardrails: server-only imports in islands, non-serializable island props, route conflicts, missing paths()
|
|
120
|
+
const seenRoutes = new Map<string, string>()
|
|
121
|
+
|
|
122
|
+
for (const [file, analysis] of analyses) {
|
|
123
|
+
const rel = relative(root, file).replace(/\\/g, '/')
|
|
124
|
+
|
|
125
|
+
// Guardrail 1: server-only imports inside interactive islands
|
|
126
|
+
if (analysis.isInteractive) {
|
|
127
|
+
for (const imp of analysis.imports) {
|
|
128
|
+
if (SERVER_ONLY_MODULES.has(imp.source)) {
|
|
129
|
+
errors.push(
|
|
130
|
+
`kay check: ${rel}: interactive island imports server-only module "${imp.source}". Move server logic to a server action or async server component.`,
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Guardrail 2: non-serializable props (functions / unsupported class instances) passed from static server code into an island
|
|
137
|
+
if (!analysis.isInteractive && file.endsWith('.tsx')) {
|
|
138
|
+
const islandTags = new Set<string>()
|
|
139
|
+
for (const imp of analysis.imports) {
|
|
140
|
+
const target = resolveLocalModule(file, imp.source)
|
|
141
|
+
if (target === undefined)
|
|
142
|
+
continue
|
|
143
|
+
const targetAnalysis = analyses.get(target)
|
|
144
|
+
if (targetAnalysis?.isInteractive) {
|
|
145
|
+
for (const spec of imp.specifiers)
|
|
146
|
+
islandTags.add(spec.local)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (islandTags.size > 0) {
|
|
151
|
+
walk(analysis.program, (node: AstNode) => {
|
|
152
|
+
if (node.type !== 'JSXOpeningElement' || node.name?.type !== 'JSXIdentifier')
|
|
153
|
+
return
|
|
154
|
+
const tag = node.name.name as string
|
|
155
|
+
if (!islandTags.has(tag))
|
|
156
|
+
return
|
|
157
|
+
for (const attr of (node.attributes ?? []) as AstNode[]) {
|
|
158
|
+
if (attr.type !== 'JSXAttribute' || attr.name?.type !== 'JSXIdentifier')
|
|
159
|
+
continue
|
|
160
|
+
const attrName = attr.name.name as string
|
|
161
|
+
if (attrName === 'key' || attrName === '$hydrate')
|
|
162
|
+
continue
|
|
163
|
+
if (attr.value?.type !== 'JSXExpressionContainer')
|
|
164
|
+
continue
|
|
165
|
+
const expr = attr.value.expression as AstNode | undefined
|
|
166
|
+
if (expr === undefined)
|
|
167
|
+
continue
|
|
168
|
+
if (expr.type === 'ArrowFunctionExpression' || expr.type === 'FunctionExpression') {
|
|
169
|
+
errors.push(
|
|
170
|
+
`kay check: ${rel}: cannot pass function prop "${attrName}" from a server component into island <${tag}>. Define the handler inside the island or pass serializable data.`,
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
else if (expr.type === 'NewExpression' && expr.callee?.type === 'Identifier' && !SERIALIZABLE_NEW_CTORS.has(expr.callee.name as string)) {
|
|
174
|
+
errors.push(
|
|
175
|
+
`kay check: ${rel}: cannot pass non-serializable \`new ${expr.callee.name}()\` prop "${attrName}" into island <${tag}>.`,
|
|
176
|
+
)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Route-specific guardrails
|
|
184
|
+
const relFromRoutes = relative(routesDir, file)
|
|
185
|
+
const isRouteFile = !relFromRoutes.startsWith('..') && !basename(file).startsWith('_')
|
|
186
|
+
if (isRouteFile) {
|
|
187
|
+
const conflictKey = normalizeRouteConflictKey(routesDir, file)
|
|
188
|
+
const prev = seenRoutes.get(conflictKey)
|
|
189
|
+
if (prev !== undefined) {
|
|
190
|
+
errors.push(`kay check: conflicting routes "${prev}" and "${rel}" both match "${conflictKey}".`)
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
seenRoutes.set(conflictKey, rel)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Guardrail 4: dynamic prerender = true route missing paths()
|
|
197
|
+
if (analysis.hasPrerender && (conflictKey.includes(':') || conflictKey.includes('*')) && !analysis.hasPaths) {
|
|
198
|
+
errors.push(`kay check: ${rel}: dynamic route exports \`prerender = true\` without exporting \`paths()\`.`)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// 3c. Run plugin check(ctx) hooks
|
|
204
|
+
if (plugins && plugins.length > 0) {
|
|
205
|
+
const pluginCtx = {
|
|
206
|
+
root,
|
|
207
|
+
routesDir,
|
|
208
|
+
error(message: string) {
|
|
209
|
+
errors.push(message)
|
|
210
|
+
},
|
|
211
|
+
}
|
|
212
|
+
for (const plugin of plugins) {
|
|
213
|
+
if (plugin.check !== undefined) {
|
|
214
|
+
try {
|
|
215
|
+
await plugin.check(pluginCtx)
|
|
216
|
+
}
|
|
217
|
+
catch (err) {
|
|
218
|
+
errors.push(`${plugin.name}: ${err instanceof Error ? err.message : String(err)}`)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
63
224
|
// 4. Run TypeScript check (`tsgo` preferred, fallback to `tsc`) when tsconfig.json exists
|
|
64
225
|
const tsconfigPath = join(root, 'tsconfig.json')
|
|
65
226
|
if (!options.skipTypecheck && existsSync(tsconfigPath)) {
|
package/src/cli/index.ts
CHANGED
|
@@ -60,19 +60,22 @@ else if (cmd === 'check') {
|
|
|
60
60
|
}
|
|
61
61
|
else if (cmd === 'build') {
|
|
62
62
|
const isStatic = hasFlag('--static')
|
|
63
|
+
const analyze = hasFlag('--analyze')
|
|
63
64
|
const compileFlag = flagValue('--compile')
|
|
64
65
|
const compile = compileFlag === undefined ? undefined : (compileFlag === '' ? true : compileFlag)
|
|
65
66
|
const t0 = performance.now()
|
|
66
|
-
const manifest = await build({ root, static: isStatic, compile })
|
|
67
|
+
const manifest = await build({ root, static: isStatic, compile, analyze })
|
|
67
68
|
const ms = (performance.now() - t0).toFixed(1)
|
|
68
69
|
console.log(`kay build done in ${ms} ms (${manifest.routes.length} routes, ${manifest.assets.length} client assets, ${manifest.actions.length} actions)`)
|
|
69
70
|
}
|
|
70
71
|
else if (cmd === 'start') {
|
|
71
72
|
process.env.NODE_ENV ??= 'production'
|
|
72
|
-
const
|
|
73
|
+
const config = await loadConfig(root)
|
|
74
|
+
const port = Number(flagValue('--port') || process.env.PORT || config.port || 3000)
|
|
75
|
+
const hostname = process.env.HOST || undefined
|
|
73
76
|
const app = await createServer({ root })
|
|
74
|
-
const server = app.serve(port)
|
|
75
|
-
console.log(`kay server listening on http
|
|
77
|
+
const server = app.serve(port, hostname)
|
|
78
|
+
console.log(`kay server listening on http://${hostname ?? 'localhost'}:${server.port}`)
|
|
76
79
|
}
|
|
77
80
|
else if (cmd === 'dev') {
|
|
78
81
|
const port = Number(flagValue('--port') || process.env.PORT || 3000)
|
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-alpha.
|
|
18
|
+
const kayVersion = options.kayVersion ?? '^2.0.0-alpha.7'
|
|
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)`)
|
package/src/compiler/dom.ts
CHANGED
|
@@ -195,8 +195,16 @@ function rewriteFreeIdentifiers(
|
|
|
195
195
|
visit(attr, shadowed)
|
|
196
196
|
return
|
|
197
197
|
}
|
|
198
|
+
case 'TSAsExpression':
|
|
199
|
+
case 'TSNonNullExpression':
|
|
200
|
+
case 'TSSatisfiesExpression':
|
|
201
|
+
case 'TSTypeAssertion':
|
|
202
|
+
case 'TSInstantiationExpression': {
|
|
203
|
+
visit(node.expression, shadowed)
|
|
204
|
+
return
|
|
205
|
+
}
|
|
198
206
|
default: {
|
|
199
|
-
// Skip TypeScript type nodes
|
|
207
|
+
// Skip pure TypeScript type annotation nodes
|
|
200
208
|
if (typeof node.type === 'string' && node.type.startsWith('TS'))
|
|
201
209
|
return
|
|
202
210
|
for (const key of Object.keys(node)) {
|
|
@@ -247,48 +255,152 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
247
255
|
}
|
|
248
256
|
}
|
|
249
257
|
|
|
250
|
-
function
|
|
251
|
-
|
|
258
|
+
function hasJsxDescendant(node: AstNode | null | undefined): boolean {
|
|
259
|
+
if (!node)
|
|
260
|
+
return false
|
|
261
|
+
let found = false
|
|
252
262
|
walk(node, (child) => {
|
|
253
263
|
if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
254
|
-
|
|
264
|
+
found = true
|
|
255
265
|
return false
|
|
256
266
|
}
|
|
257
267
|
return undefined
|
|
258
268
|
})
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
// Replace nested JSX roots inside this expression
|
|
263
|
-
const subCode = code.slice(node.start, node.end)
|
|
264
|
-
const offset = node.start as number
|
|
265
|
-
const sub = new SourceEditor(subCode)
|
|
269
|
+
return found
|
|
270
|
+
}
|
|
266
271
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
272
|
+
function extractBlockKeyExpr(block: AstNode): AstNode | undefined {
|
|
273
|
+
let found: AstNode | undefined
|
|
274
|
+
walk(block, (child) => {
|
|
275
|
+
if (found !== undefined)
|
|
276
|
+
return false
|
|
277
|
+
if (child.type === 'ArrowFunctionExpression' || child.type === 'FunctionExpression' || child.type === 'FunctionDeclaration')
|
|
270
278
|
return false
|
|
279
|
+
if (child.type === 'ReturnStatement' && child.argument) {
|
|
280
|
+
const arg = unwrapParens(child.argument as AstNode)
|
|
281
|
+
const k = extractKeyExpr(arg)
|
|
282
|
+
if (k !== undefined) {
|
|
283
|
+
found = k
|
|
284
|
+
return false
|
|
285
|
+
}
|
|
271
286
|
}
|
|
272
287
|
return undefined
|
|
273
288
|
})
|
|
289
|
+
return found
|
|
290
|
+
}
|
|
274
291
|
|
|
275
|
-
|
|
276
|
-
if (
|
|
277
|
-
return
|
|
278
|
-
|
|
279
|
-
//
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
292
|
+
function compileExpression(node: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
|
|
293
|
+
if (!hasJsxDescendant(node))
|
|
294
|
+
return rewriteFreeIdentifiers(code, node, scopeRewrites)
|
|
295
|
+
|
|
296
|
+
// Replace nested JSX roots AND rewrite free identifiers in all surrounding non-JSX spans (respecting shadowing)
|
|
297
|
+
const offset = node.start as number
|
|
298
|
+
const sub = new SourceEditor(code.slice(node.start, node.end))
|
|
299
|
+
|
|
300
|
+
function visitExpr(cur: AstNode | null | undefined, shadowed: Set<string>): void {
|
|
301
|
+
if (!cur || typeof cur !== 'object')
|
|
302
|
+
return
|
|
303
|
+
|
|
304
|
+
if (cur.type === 'JSXElement' || cur.type === 'JSXFragment') {
|
|
305
|
+
const activeRewrites = shadowed.size === 0
|
|
306
|
+
? scopeRewrites
|
|
307
|
+
: new Map([...scopeRewrites].filter(([k]) => !shadowed.has(k)))
|
|
308
|
+
sub.replace(cur.start - offset, cur.end - offset, compileRootJsx(cur, activeRewrites))
|
|
309
|
+
return
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
switch (cur.type) {
|
|
313
|
+
case 'Identifier': {
|
|
314
|
+
const name = cur.name as string
|
|
315
|
+
if (!shadowed.has(name)) {
|
|
316
|
+
const rep = scopeRewrites.get(name)
|
|
317
|
+
if (rep !== undefined)
|
|
318
|
+
sub.replace(cur.start - offset, cur.end - offset, rep)
|
|
319
|
+
}
|
|
320
|
+
return
|
|
321
|
+
}
|
|
322
|
+
case 'MemberExpression': {
|
|
323
|
+
visitExpr(cur.object, shadowed)
|
|
324
|
+
if (cur.computed)
|
|
325
|
+
visitExpr(cur.property, shadowed)
|
|
326
|
+
return
|
|
327
|
+
}
|
|
328
|
+
case 'Property': {
|
|
329
|
+
if (cur.computed)
|
|
330
|
+
visitExpr(cur.key, shadowed)
|
|
331
|
+
if (cur.shorthand && cur.value?.type === 'Identifier') {
|
|
332
|
+
const name = cur.value.name as string
|
|
333
|
+
if (!shadowed.has(name) && scopeRewrites.has(name)) {
|
|
334
|
+
sub.replace(cur.start - offset, cur.end - offset, `${name}: ${scopeRewrites.get(name)}`)
|
|
335
|
+
return
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
visitExpr(cur.value, shadowed)
|
|
339
|
+
return
|
|
340
|
+
}
|
|
341
|
+
case 'ArrowFunctionExpression':
|
|
342
|
+
case 'FunctionExpression':
|
|
343
|
+
case 'FunctionDeclaration': {
|
|
344
|
+
const nextShadow = new Set(shadowed)
|
|
345
|
+
if (cur.id?.name)
|
|
346
|
+
nextShadow.add(cur.id.name as string)
|
|
347
|
+
for (const p of cur.params as AstNode[])
|
|
348
|
+
collectPatternNames(p, nextShadow)
|
|
349
|
+
visitExpr(cur.body, nextShadow)
|
|
350
|
+
return
|
|
351
|
+
}
|
|
352
|
+
case 'BlockStatement': {
|
|
353
|
+
const nextShadow = new Set(shadowed)
|
|
354
|
+
for (const stmt of cur.body as AstNode[]) {
|
|
355
|
+
if (stmt.type === 'VariableDeclaration') {
|
|
356
|
+
for (const d of stmt.declarations as AstNode[]) {
|
|
357
|
+
visitExpr(d.init, nextShadow)
|
|
358
|
+
collectPatternNames(d.id, nextShadow)
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
else if (stmt.type === 'FunctionDeclaration') {
|
|
362
|
+
if (stmt.id?.name)
|
|
363
|
+
nextShadow.add(stmt.id.name as string)
|
|
364
|
+
visitExpr(stmt, nextShadow)
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
visitExpr(stmt, nextShadow)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
case 'VariableDeclarator': {
|
|
373
|
+
visitExpr(cur.init, shadowed)
|
|
374
|
+
return
|
|
375
|
+
}
|
|
376
|
+
case 'TSAsExpression':
|
|
377
|
+
case 'TSNonNullExpression':
|
|
378
|
+
case 'TSSatisfiesExpression':
|
|
379
|
+
case 'TSTypeAssertion':
|
|
380
|
+
case 'TSInstantiationExpression': {
|
|
381
|
+
visitExpr(cur.expression, shadowed)
|
|
382
|
+
return
|
|
383
|
+
}
|
|
384
|
+
default: {
|
|
385
|
+
if (typeof cur.type === 'string' && cur.type.startsWith('TS'))
|
|
386
|
+
return
|
|
387
|
+
for (const key of Object.keys(cur)) {
|
|
388
|
+
if (key === 'start' || key === 'end' || key === 'type')
|
|
389
|
+
continue
|
|
390
|
+
const val = cur[key]
|
|
391
|
+
if (Array.isArray(val)) {
|
|
392
|
+
for (let i = 0; i < val.length; i++)
|
|
393
|
+
visitExpr(val[i] as AstNode, shadowed)
|
|
394
|
+
}
|
|
395
|
+
else if (val !== null && typeof val === 'object') {
|
|
396
|
+
visitExpr(val as AstNode, shadowed)
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
}
|
|
291
401
|
}
|
|
402
|
+
|
|
403
|
+
visitExpr(node, new Set())
|
|
292
404
|
return sub.toString()
|
|
293
405
|
}
|
|
294
406
|
|
|
@@ -563,7 +675,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
563
675
|
if (child.type === 'JSXExpressionContainer') {
|
|
564
676
|
const expr = child.expression as AstNode
|
|
565
677
|
|
|
566
|
-
// Case 1: Keyed `.map((item, idx?) => <jsx>)` → `__loop(...)`
|
|
678
|
+
// Case 1: Keyed `.map((item, idx?) => <jsx> | { ... return <jsx> })` → `__loop(...)`
|
|
567
679
|
if (
|
|
568
680
|
expr.type === 'CallExpression'
|
|
569
681
|
&& expr.callee?.type === 'MemberExpression'
|
|
@@ -573,9 +685,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
573
685
|
) {
|
|
574
686
|
const cb = expr.arguments[0] as AstNode
|
|
575
687
|
const cbBody = cb.body?.type === 'ParenthesizedExpression' ? cb.body.expression : cb.body
|
|
688
|
+
const isJsxBody = cbBody?.type === 'JSXElement' || cbBody?.type === 'JSXFragment'
|
|
689
|
+
const isBlockJsxBody = cbBody?.type === 'BlockStatement' && hasJsxDescendant(cbBody)
|
|
576
690
|
if (
|
|
577
691
|
(cb.type === 'ArrowFunctionExpression' || cb.type === 'FunctionExpression')
|
|
578
|
-
&& (
|
|
692
|
+
&& (isJsxBody || isBlockJsxBody)
|
|
579
693
|
) {
|
|
580
694
|
const loopSkip = domIndex
|
|
581
695
|
const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
|
|
@@ -601,12 +715,12 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
601
715
|
for (const n of names)
|
|
602
716
|
shadowed.delete(n)
|
|
603
717
|
}
|
|
604
|
-
const rowBody = compileRootJsx(cbBody, shadowed)
|
|
718
|
+
const rowBody = isJsxBody ? compileRootJsx(cbBody, shadowed) : compileExpression(cbBody, shadowed)
|
|
605
719
|
ops.push(`${use('eachStatic')}(${elVar}, ${anchorVar}, ${eachCode}, (${rawParams}) => ${rowBody}${skipArg});`)
|
|
606
720
|
continue
|
|
607
721
|
}
|
|
608
722
|
|
|
609
|
-
const keyAst = extractKeyExpr(cbBody)
|
|
723
|
+
const keyAst = isJsxBody ? extractKeyExpr(cbBody) : extractBlockKeyExpr(cbBody)
|
|
610
724
|
|
|
611
725
|
const rowSig = freshVar('_r')
|
|
612
726
|
const idxSig = idxParam !== undefined ? freshVar('_i') : undefined
|
|
@@ -649,7 +763,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
649
763
|
if (idxParam !== undefined && idxSig !== undefined)
|
|
650
764
|
rowRewrites.set(idxParam, `${idxSig}.value`)
|
|
651
765
|
|
|
652
|
-
const rowBody = compileRootJsx(cbBody, rowRewrites)
|
|
766
|
+
const rowBody = isJsxBody ? compileRootJsx(cbBody, rowRewrites) : compileExpression(cbBody, rowRewrites)
|
|
653
767
|
const rowParams = idxSig !== undefined ? `${rowSig}, ${idxSig}` : rowSig
|
|
654
768
|
ops.push(`${use('loop')}(${elVar}, ${anchorVar}, () => ${eachCode}, ${keyFn}, (${rowParams}) => ${rowBody}${skipArg});`)
|
|
655
769
|
continue
|
|
@@ -694,11 +808,11 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
694
808
|
}
|
|
695
809
|
}
|
|
696
810
|
|
|
697
|
-
// Case 4: Dynamic children slot / Node insertion (`{children}
|
|
811
|
+
// Case 4: Dynamic children slot / Node insertion (`{children}`, `{props.children}`, or any expression containing JSX)
|
|
698
812
|
const isChildrenExpr = (expr.type === 'Identifier' && expr.name === 'children')
|
|
699
813
|
|| (expr.type === 'MemberExpression' && !expr.computed && expr.property?.name === 'children')
|
|
700
814
|
const exprCode = compileExpression(expr, scopeRewrites)
|
|
701
|
-
if (isChildrenExpr) {
|
|
815
|
+
if (isChildrenExpr || hasJsxDescendant(expr)) {
|
|
702
816
|
const anchorVar = isLast ? 'null' : requestChild(elVar, domIndex)
|
|
703
817
|
if (!isLast) {
|
|
704
818
|
html += '<!---->'
|
package/src/compiler/ssr.ts
CHANGED
|
@@ -388,7 +388,22 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
388
388
|
if (body.type === 'JSXElement' || body.type === 'JSXFragment') {
|
|
389
389
|
const target = compileSubExpression(expr.callee.object)
|
|
390
390
|
const params = (cb.params as AstNode[]).map(p => code.slice(p.start, p.end)).join(', ')
|
|
391
|
-
|
|
391
|
+
const rendered = `${use('ssrLoop')}(${target}, (${params}) => ${compileJsxToStringExpr(body)})`
|
|
392
|
+
return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
|
|
393
|
+
}
|
|
394
|
+
if (body.type === 'BlockStatement') {
|
|
395
|
+
let blockHasJsx = false
|
|
396
|
+
walk(body, (c) => {
|
|
397
|
+
if (c.type === 'JSXElement' || c.type === 'JSXFragment') {
|
|
398
|
+
blockHasJsx = true
|
|
399
|
+
return false
|
|
400
|
+
}
|
|
401
|
+
return undefined
|
|
402
|
+
})
|
|
403
|
+
if (blockHasJsx) {
|
|
404
|
+
const rendered = `${use('esc')}(${compileSubExpression(expr)})`
|
|
405
|
+
return isIsland && !isLast ? `(${rendered}) + "<!---->"` : rendered
|
|
406
|
+
}
|
|
392
407
|
}
|
|
393
408
|
}
|
|
394
409
|
}
|