@kayjs/kay 2.0.0-alpha.4 → 2.0.0-alpha.6
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 +10 -6
- package/src/build/index.ts +452 -28
- package/src/cli/check.ts +165 -4
- package/src/cli/index.ts +2 -1
- package/src/cli/new.ts +1 -1
- package/src/compiler/dom.ts +7 -6
- package/src/compiler/ssr.ts +36 -4
- 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 +25 -2
- package/src/server/action.ts +56 -3
- package/src/server/compress.ts +241 -0
- package/src/server/cookies.ts +4 -0
- package/src/server/http.ts +40 -7
- package/src/server/index.ts +435 -155
- package/src/server/security.ts +110 -6
- package/src/ssr/context.ts +5 -2
- package/src/ssr/index.ts +51 -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,10 +60,11 @@ 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
|
}
|
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.6'
|
|
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
|
@@ -254,6 +254,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
254
254
|
hasNestedJsx = true
|
|
255
255
|
return false
|
|
256
256
|
}
|
|
257
|
+
return undefined
|
|
257
258
|
})
|
|
258
259
|
if (!hasNestedJsx)
|
|
259
260
|
return rewriteFreeIdentifiers(code, node, scopeRewrites)
|
|
@@ -268,6 +269,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
268
269
|
sub.replace(child.start - offset, child.end - offset, compileRootJsx(child, scopeRewrites))
|
|
269
270
|
return false
|
|
270
271
|
}
|
|
272
|
+
return undefined
|
|
271
273
|
})
|
|
272
274
|
|
|
273
275
|
// Also rewrite non-JSX free identifiers by applying identifier rewrites on non-JSX spans
|
|
@@ -374,12 +376,6 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
374
376
|
}
|
|
375
377
|
|
|
376
378
|
function compileElementTree(rootEl: AstNode, scopeRewrites: ReadonlyMap<string, string>): string {
|
|
377
|
-
interface NodeRef {
|
|
378
|
-
varName: string
|
|
379
|
-
parentVar: string
|
|
380
|
-
childIndex: number
|
|
381
|
-
}
|
|
382
|
-
|
|
383
379
|
const ops: string[] = []
|
|
384
380
|
const rootVar = freshVar('_e')
|
|
385
381
|
const childRefs = new Map<string, string>() // "parentVar:index" -> varName
|
|
@@ -843,6 +839,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
843
839
|
fnHasJsx = true
|
|
844
840
|
return false
|
|
845
841
|
}
|
|
842
|
+
return undefined
|
|
846
843
|
})
|
|
847
844
|
if (!fnHasJsx)
|
|
848
845
|
return
|
|
@@ -888,6 +885,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
888
885
|
stmtHasJsx = true
|
|
889
886
|
return false
|
|
890
887
|
}
|
|
888
|
+
return undefined
|
|
891
889
|
})
|
|
892
890
|
if (!stmtHasJsx) {
|
|
893
891
|
const active = new Map<string, string>()
|
|
@@ -904,6 +902,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
904
902
|
editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
|
|
905
903
|
return false
|
|
906
904
|
}
|
|
905
|
+
return undefined
|
|
907
906
|
})
|
|
908
907
|
}
|
|
909
908
|
if (stmt.type === 'VariableDeclaration') {
|
|
@@ -918,6 +917,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
918
917
|
editor.replace(child.start, child.end, compileRootJsx(child, propRewrites))
|
|
919
918
|
return false
|
|
920
919
|
}
|
|
920
|
+
return undefined
|
|
921
921
|
})
|
|
922
922
|
}
|
|
923
923
|
}
|
|
@@ -931,6 +931,7 @@ export function compileDom(filename: string, code: string, options: CompileDomOp
|
|
|
931
931
|
editor.replace(node.start, node.end, compileRootJsx(node, new Map()))
|
|
932
932
|
return false
|
|
933
933
|
}
|
|
934
|
+
return undefined
|
|
934
935
|
})
|
|
935
936
|
|
|
936
937
|
// Emit imports, hoisted templates, and delegated events
|
package/src/compiler/ssr.ts
CHANGED
|
@@ -9,6 +9,14 @@ export function escapeStaticText(str: string): string {
|
|
|
9
9
|
return str.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
10
10
|
}
|
|
11
11
|
|
|
12
|
+
const RAW_TEXT_ELEMENTS = new Set(['style', 'script'])
|
|
13
|
+
const CLOSE_STYLE_RE = /<\/(style)/gi
|
|
14
|
+
const CLOSE_SCRIPT_RE = /<\/(script)/gi
|
|
15
|
+
|
|
16
|
+
function escapeRawText(str: string, tag: 'style' | 'script'): string {
|
|
17
|
+
return str.replace(tag === 'script' ? CLOSE_SCRIPT_RE : CLOSE_STYLE_RE, '<\\/$1')
|
|
18
|
+
}
|
|
19
|
+
|
|
12
20
|
const VOID_ELEMENTS = new Set([
|
|
13
21
|
'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input',
|
|
14
22
|
'link', 'meta', 'param', 'source', 'track', 'wbr',
|
|
@@ -171,6 +179,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
171
179
|
hasNestedJsx = true
|
|
172
180
|
return false
|
|
173
181
|
}
|
|
182
|
+
return undefined
|
|
174
183
|
})
|
|
175
184
|
if (!hasNestedJsx)
|
|
176
185
|
return code.slice(node.start, node.end)
|
|
@@ -182,6 +191,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
182
191
|
sub.replace(child.start - offset, child.end - offset, compileRootJsx(child))
|
|
183
192
|
return false
|
|
184
193
|
}
|
|
194
|
+
return undefined
|
|
185
195
|
})
|
|
186
196
|
return sub.toString()
|
|
187
197
|
}
|
|
@@ -253,7 +263,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
253
263
|
if (innerHtmlExpr !== undefined)
|
|
254
264
|
parts.pushExpr(innerHtmlExpr)
|
|
255
265
|
else
|
|
256
|
-
emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt)
|
|
266
|
+
emitChildrenIntoBuffer(node.children as AstNode[], bufVar, parts, flushParts, pushStmt, RAW_TEXT_ELEMENTS.has(tag) ? tag as 'style' | 'script' : undefined)
|
|
257
267
|
parts.pushStatic(`</${tag}>`)
|
|
258
268
|
}
|
|
259
269
|
|
|
@@ -263,6 +273,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
263
273
|
parts: StringParts,
|
|
264
274
|
flushParts: () => void,
|
|
265
275
|
pushStmt: (stmt: string) => void,
|
|
276
|
+
rawTextTag?: 'style' | 'script',
|
|
266
277
|
): void {
|
|
267
278
|
const meaningful = children.filter((c) => {
|
|
268
279
|
if (c.type === 'JSXText')
|
|
@@ -277,7 +288,8 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
277
288
|
const child = meaningful[i]!
|
|
278
289
|
const isLast = i === meaningful.length - 1
|
|
279
290
|
if (child.type === 'JSXText') {
|
|
280
|
-
|
|
291
|
+
const text = cleanJsxText(child.value as string)
|
|
292
|
+
parts.pushStatic(rawTextTag !== undefined ? escapeRawText(text, rawTextTag) : text)
|
|
281
293
|
}
|
|
282
294
|
else if (child.type === 'JSXElement' || child.type === 'JSXFragment') {
|
|
283
295
|
emitIntoBuffer(child, bufVar, parts, flushParts, pushStmt)
|
|
@@ -285,9 +297,28 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
285
297
|
else if (child.type === 'JSXExpressionContainer') {
|
|
286
298
|
const expr = child.expression as AstNode
|
|
287
299
|
|
|
288
|
-
// Fold static string literal expressions like `{' '}` directly into static text
|
|
300
|
+
// Fold static string literal expressions like `{' '}` or `<style>{':root { ... }'}</style>` directly into static text
|
|
289
301
|
if (expr.type === 'Literal' && typeof expr.value === 'string') {
|
|
290
|
-
parts.pushStatic(escapeStaticText(expr.value))
|
|
302
|
+
parts.pushStatic(rawTextTag !== undefined ? escapeRawText(expr.value, rawTextTag) : escapeStaticText(expr.value))
|
|
303
|
+
continue
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Fold static no-substitution template literals inside `<style>`/`<script>` directly into raw text
|
|
307
|
+
if (
|
|
308
|
+
rawTextTag !== undefined
|
|
309
|
+
&& expr.type === 'TemplateLiteral'
|
|
310
|
+
&& (expr.expressions as AstNode[]).length === 0
|
|
311
|
+
&& (expr.quasis as AstNode[]).length === 1
|
|
312
|
+
) {
|
|
313
|
+
const cooked = expr.quasis[0]?.value?.cooked
|
|
314
|
+
if (typeof cooked === 'string') {
|
|
315
|
+
parts.pushStatic(escapeRawText(cooked, rawTextTag))
|
|
316
|
+
continue
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
if (rawTextTag !== undefined) {
|
|
321
|
+
parts.pushExpr(`${use('ssrRawText')}(${JSON.stringify(rawTextTag)}, ${compileSubExpression(expr)})`)
|
|
291
322
|
continue
|
|
292
323
|
}
|
|
293
324
|
|
|
@@ -549,6 +580,7 @@ export function compileSsr(filename: string, code: string, options: CompileSsrOp
|
|
|
549
580
|
editor.replace(node.start, node.end, compileRootJsx(node))
|
|
550
581
|
return false
|
|
551
582
|
}
|
|
583
|
+
return undefined
|
|
552
584
|
})
|
|
553
585
|
|
|
554
586
|
if (used.size > 0) {
|
package/src/dev/index.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
// kay dev:
|
|
1
|
+
// kay dev: incremental cached rebuilds, serialized rebuild queue, CSS hot-swap, SSE error push, and live config reload.
|
|
2
2
|
|
|
3
3
|
import type { FSWatcher } from 'node:fs'
|
|
4
4
|
import type { KayApp } from '../server/index'
|
|
5
|
-
import { existsSync, rmSync, watch } from 'node:fs'
|
|
5
|
+
import { existsSync, rmSync, statSync, watch } from 'node:fs'
|
|
6
6
|
import { join, resolve } from 'node:path'
|
|
7
|
-
import { build } from '../build/index'
|
|
7
|
+
import { build, createBuildCache } from '../build/index'
|
|
8
|
+
import { loadConfig } from '../plugins/index'
|
|
8
9
|
import { createServer } from '../server/index'
|
|
9
10
|
|
|
10
11
|
export interface DevServerOptions {
|
|
@@ -13,7 +14,7 @@ export interface DevServerOptions {
|
|
|
13
14
|
routesDir?: string | undefined
|
|
14
15
|
}
|
|
15
16
|
|
|
16
|
-
const DEV_RELOAD_SCRIPT = `<script>(()=>{const s=new EventSource('/_kay/dev-events');s.onmessage=()=>location.reload();})();</script>`
|
|
17
|
+
const DEV_RELOAD_SCRIPT = `<script>(()=>{const stem=u=>u.replace(/-[a-z0-9]+\\.css$/i,'');const s=new EventSource('/_kay/dev-events');s.onmessage=(e)=>{if(e.data.startsWith('css:')){const urls=JSON.parse(e.data.slice(4));const byStem=new Map(urls.map(u=>[stem(u),u]));const old=[...document.querySelectorAll('link[rel="stylesheet"][href^="/_kay/"]')];if(old.length===0){location.reload();return;}const next=[];for(const o of old){const m=byStem.get(stem(o.getAttribute('href')||''));if(m)next.push(m);}if(next.length===0){location.reload();return;}let left=next.length;for(const u of next){const l=document.createElement('link');l.rel='stylesheet';l.href=u;const done=()=>{if(--left===0)for(const o of old)o.remove();};l.onload=done;l.onerror=done;document.head.appendChild(l);}}else{location.reload();}};})();</script>`
|
|
17
18
|
|
|
18
19
|
function renderErrorOverlay(errText: string): string {
|
|
19
20
|
const escaped = errText
|
|
@@ -23,7 +24,10 @@ function renderErrorOverlay(errText: string): string {
|
|
|
23
24
|
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Kay Dev Error</title><style>body{margin:0;min-height:100vh;background:#0d1117;color:#e6edf3;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;display:grid;place-items:center;padding:2rem}main{max-width:56rem;width:100%;background:#161b22;border:1px solid #f85149;border-radius:10px;padding:1.5rem 2rem;box-shadow:0 16px 48px rgba(0,0,0,.45)}h1{margin:0 0 1rem;color:#ff7b72;font-size:1.15rem}pre{margin:0;white-space:pre-wrap;word-break:break-word;line-height:1.5;font-size:.9rem;color:#ffa198}p{margin:1rem 0 0;font-size:.8rem;color:#8b949e}</style></head><body><main><h1>Kay Dev Build Error</h1><pre>${escaped}</pre><p>Save a fix to auto-reload.</p></main>${DEV_RELOAD_SCRIPT}</body></html>`
|
|
24
25
|
}
|
|
25
26
|
|
|
26
|
-
|
|
27
|
+
type ChangeKind = 'css' | 'full' | 'config'
|
|
28
|
+
|
|
29
|
+
export async function devServer(options: DevServerOptions): Promise<{ url: string, stop: () => void, rebuild: () => Promise<void> }> {
|
|
30
|
+
const prevKayDev = process.env.KAY_DEV
|
|
27
31
|
process.env.KAY_DEV = '1'
|
|
28
32
|
const root = resolve(options.root)
|
|
29
33
|
const srcDir = resolve(root, 'src')
|
|
@@ -31,53 +35,153 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
31
35
|
const configPath = join(root, 'kay.config.ts')
|
|
32
36
|
const devRoot = join(root, '.kay-dev')
|
|
33
37
|
const port = options.port ?? 3000
|
|
38
|
+
const buildCache = createBuildCache()
|
|
39
|
+
|
|
34
40
|
let buildNum = 0
|
|
35
41
|
let currentApp: KayApp | undefined
|
|
36
42
|
let lastError: string | undefined
|
|
43
|
+
let stopped = false
|
|
44
|
+
|
|
45
|
+
// Serialized rebuild queue: rapid saves coalesce instead of racing
|
|
46
|
+
let building = false
|
|
47
|
+
let pending = false
|
|
48
|
+
let pendingCssOnly = true
|
|
49
|
+
let pendingConfigReset = false
|
|
50
|
+
let inFlight: Promise<void> | undefined
|
|
51
|
+
|
|
37
52
|
const clients = new Set<ReadableStreamDefaultController<Uint8Array>>()
|
|
38
53
|
const encoder = new TextEncoder()
|
|
39
54
|
|
|
40
|
-
|
|
55
|
+
function broadcast(payload: string): void {
|
|
56
|
+
const chunk = encoder.encode(`data: ${payload}\n\n`)
|
|
57
|
+
for (const c of clients) {
|
|
58
|
+
try {
|
|
59
|
+
c.enqueue(chunk)
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
clients.delete(c)
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function runSingleBuild(cssOnly: boolean, resetCache: boolean): Promise<void> {
|
|
68
|
+
if (stopped)
|
|
69
|
+
return
|
|
70
|
+
if (resetCache) {
|
|
71
|
+
buildCache.analyses.clear()
|
|
72
|
+
buildCache.domCompiled.clear()
|
|
73
|
+
buildCache.ssrCompiled.clear()
|
|
74
|
+
}
|
|
75
|
+
const hadError = lastError !== undefined
|
|
76
|
+
const hadApp = currentApp !== undefined
|
|
41
77
|
const n = ++buildNum
|
|
42
78
|
const outDir = `.kay-dev/b${n}`
|
|
43
79
|
const t0 = performance.now()
|
|
44
80
|
try {
|
|
45
|
-
await build({
|
|
81
|
+
const manifest = await build({
|
|
82
|
+
root,
|
|
83
|
+
routesDir: options.routesDir,
|
|
84
|
+
outDir,
|
|
85
|
+
minify: false,
|
|
86
|
+
prerender: false,
|
|
87
|
+
copyPublic: false,
|
|
88
|
+
cache: buildCache,
|
|
89
|
+
})
|
|
46
90
|
currentApp = await createServer({ root, outDir })
|
|
47
91
|
lastError = undefined
|
|
48
92
|
if (n > 2)
|
|
49
93
|
rmSync(join(devRoot, `b${n - 2}`), { recursive: true, force: true })
|
|
50
94
|
console.log(`[kay dev] rebuilt in ${(performance.now() - t0).toFixed(1)} ms`)
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
catch {
|
|
56
|
-
clients.delete(c)
|
|
57
|
-
}
|
|
58
|
-
}
|
|
95
|
+
if (cssOnly && hadApp && !hadError && manifest.styles.length > 0)
|
|
96
|
+
broadcast(`css:${JSON.stringify(manifest.styles)}`)
|
|
97
|
+
else
|
|
98
|
+
broadcast('reload')
|
|
59
99
|
}
|
|
60
100
|
catch (err) {
|
|
61
101
|
lastError = err instanceof Error ? err.stack ?? err.message : String(err)
|
|
62
102
|
console.error(`[kay dev] build error:\n${lastError}`)
|
|
103
|
+
// Push reload over SSE so open browser tabs immediately display the error overlay
|
|
104
|
+
broadcast('reload')
|
|
63
105
|
}
|
|
64
106
|
}
|
|
65
107
|
|
|
66
|
-
|
|
108
|
+
function drainRebuilds(): Promise<void> {
|
|
109
|
+
if (building) {
|
|
110
|
+
pending = true
|
|
111
|
+
return inFlight ?? Promise.resolve()
|
|
112
|
+
}
|
|
113
|
+
building = true
|
|
114
|
+
const run = (async () => {
|
|
115
|
+
try {
|
|
116
|
+
do {
|
|
117
|
+
const cssOnly = pendingCssOnly
|
|
118
|
+
const resetCache = pendingConfigReset
|
|
119
|
+
pending = false
|
|
120
|
+
pendingCssOnly = true
|
|
121
|
+
pendingConfigReset = false
|
|
122
|
+
await runSingleBuild(cssOnly, resetCache)
|
|
123
|
+
} while (pending && !stopped)
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
building = false
|
|
127
|
+
inFlight = undefined
|
|
128
|
+
}
|
|
129
|
+
})()
|
|
130
|
+
inFlight = run
|
|
131
|
+
return run
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Initial build
|
|
135
|
+
pendingCssOnly = false
|
|
136
|
+
await drainRebuilds()
|
|
67
137
|
|
|
68
138
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
69
|
-
const scheduleRebuild = () => {
|
|
139
|
+
const scheduleRebuild = (kind: ChangeKind) => {
|
|
140
|
+
if (stopped)
|
|
141
|
+
return
|
|
142
|
+
if (kind === 'config') {
|
|
143
|
+
pendingConfigReset = true
|
|
144
|
+
pendingCssOnly = false
|
|
145
|
+
}
|
|
146
|
+
else if (kind === 'full') {
|
|
147
|
+
pendingCssOnly = false
|
|
148
|
+
}
|
|
70
149
|
clearTimeout(timer)
|
|
71
|
-
timer = setTimeout(() =>
|
|
150
|
+
timer = setTimeout(() => {
|
|
151
|
+
void drainRebuilds()
|
|
152
|
+
}, 40)
|
|
72
153
|
}
|
|
73
154
|
|
|
74
155
|
const watchers: FSWatcher[] = []
|
|
75
|
-
if (existsSync(srcDir))
|
|
76
|
-
watchers.push(watch(srcDir, { recursive: true },
|
|
156
|
+
if (existsSync(srcDir)) {
|
|
157
|
+
watchers.push(watch(srcDir, { recursive: true }, (_ev, filename) => {
|
|
158
|
+
const name = typeof filename === 'string' ? filename : ''
|
|
159
|
+
const isCss = name.endsWith('.css') && !name.endsWith('.module.css')
|
|
160
|
+
scheduleRebuild(isCss ? 'css' : 'full')
|
|
161
|
+
}))
|
|
162
|
+
}
|
|
77
163
|
if (existsSync(publicDir))
|
|
78
|
-
watchers.push(watch(publicDir, { recursive: true }, scheduleRebuild))
|
|
164
|
+
watchers.push(watch(publicDir, { recursive: true }, () => scheduleRebuild('full')))
|
|
79
165
|
if (existsSync(configPath))
|
|
80
|
-
watchers.push(watch(configPath, scheduleRebuild))
|
|
166
|
+
watchers.push(watch(configPath, () => scheduleRebuild('config')))
|
|
167
|
+
|
|
168
|
+
// Watch plugin-declared extra paths (e.g. content/ or messages/ directories)
|
|
169
|
+
try {
|
|
170
|
+
const cfg = await loadConfig(root)
|
|
171
|
+
const watchedExtra = new Set<string>([srcDir, publicDir, configPath])
|
|
172
|
+
for (const plugin of cfg.plugins ?? []) {
|
|
173
|
+
const paths = typeof plugin.watchPaths === 'function' ? plugin.watchPaths(root) : (plugin.watchPaths ?? [])
|
|
174
|
+
for (const p of paths) {
|
|
175
|
+
const abs = resolve(root, p)
|
|
176
|
+
if (watchedExtra.has(abs) || !existsSync(abs))
|
|
177
|
+
continue
|
|
178
|
+
watchedExtra.add(abs)
|
|
179
|
+
const isDir = statSync(abs).isDirectory()
|
|
180
|
+
watchers.push(watch(abs, isDir ? { recursive: true } : {}, () => scheduleRebuild('full')))
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch {}
|
|
81
185
|
|
|
82
186
|
const pingChunk = encoder.encode(': ping\n\n')
|
|
83
187
|
const pingInterval = setInterval(() => {
|
|
@@ -151,13 +255,22 @@ export async function devServer(options: DevServerOptions): Promise<{ url: strin
|
|
|
151
255
|
|
|
152
256
|
return {
|
|
153
257
|
url,
|
|
258
|
+
rebuild() {
|
|
259
|
+
pendingCssOnly = false
|
|
260
|
+
return drainRebuilds()
|
|
261
|
+
},
|
|
154
262
|
stop() {
|
|
263
|
+
stopped = true
|
|
155
264
|
clearTimeout(timer)
|
|
156
265
|
clearInterval(pingInterval)
|
|
157
266
|
for (const w of watchers)
|
|
158
267
|
w.close()
|
|
159
268
|
server.stop(true)
|
|
160
269
|
rmSync(devRoot, { recursive: true, force: true })
|
|
270
|
+
if (prevKayDev === undefined)
|
|
271
|
+
delete process.env.KAY_DEV
|
|
272
|
+
else
|
|
273
|
+
process.env.KAY_DEV = prevKayDev
|
|
161
274
|
},
|
|
162
275
|
}
|
|
163
276
|
}
|