@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/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
|
}
|
package/src/dom/extras.ts
CHANGED
|
@@ -120,6 +120,17 @@ function clearInserted(current: Node | Node[] | null): void {
|
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
122
|
|
|
123
|
+
function claimTextNode(claimed: Node | null, str: string): Text | undefined {
|
|
124
|
+
if (claimed === null || claimed.nodeType !== 3)
|
|
125
|
+
return undefined
|
|
126
|
+
const text = claimed as Text
|
|
127
|
+
if (text.data === str)
|
|
128
|
+
return text
|
|
129
|
+
if (str.length > 0 && text.data.endsWith(str))
|
|
130
|
+
return text.splitText(text.data.length - str.length)
|
|
131
|
+
return undefined
|
|
132
|
+
}
|
|
133
|
+
|
|
123
134
|
export function insert(parent: Node, value: () => unknown, marker: Node | null = null): void {
|
|
124
135
|
let current: Node | Node[] | null = null
|
|
125
136
|
let textNode: Text | undefined
|
|
@@ -144,8 +155,14 @@ export function insert(parent: Node, value: () => unknown, marker: Node | null =
|
|
|
144
155
|
current = null
|
|
145
156
|
}
|
|
146
157
|
if (textNode === undefined) {
|
|
147
|
-
|
|
148
|
-
|
|
158
|
+
const claimed = claimTextNode(res.claimed, str)
|
|
159
|
+
if (claimed !== undefined) {
|
|
160
|
+
textNode = claimed
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
textNode = document.createTextNode(str)
|
|
164
|
+
parent.insertBefore(textNode, marker)
|
|
165
|
+
}
|
|
149
166
|
}
|
|
150
167
|
else if (textNode.data !== str) {
|
|
151
168
|
textNode.data = str
|
|
@@ -207,8 +224,8 @@ export function show(
|
|
|
207
224
|
parent: Node,
|
|
208
225
|
marker: Node | null,
|
|
209
226
|
when: () => unknown,
|
|
210
|
-
renderTrue: () =>
|
|
211
|
-
renderFalse?: () =>
|
|
227
|
+
renderTrue: () => unknown,
|
|
228
|
+
renderFalse?: () => unknown,
|
|
212
229
|
): void {
|
|
213
230
|
const parentOwner = getOwner()
|
|
214
231
|
let branch: 0 | 1 | 2 = 0
|
|
@@ -242,17 +259,56 @@ export function show(
|
|
|
242
259
|
const res = claimInsert(parent, marker, () => untrack(() => runWithOwner(owner, fn)))
|
|
243
260
|
marker = res.marker
|
|
244
261
|
const rendered = res.result
|
|
245
|
-
if (rendered ===
|
|
262
|
+
if (rendered == null || typeof rendered === 'boolean')
|
|
246
263
|
return
|
|
247
264
|
|
|
248
|
-
if (rendered
|
|
249
|
-
|
|
250
|
-
|
|
265
|
+
if (typeof rendered === 'string' || typeof rendered === 'number') {
|
|
266
|
+
const str = String(rendered)
|
|
267
|
+
if (str === '')
|
|
268
|
+
return
|
|
269
|
+
const text = claimTextNode(res.claimed, str) ?? document.createTextNode(str)
|
|
270
|
+
if (text.parentNode !== parent)
|
|
271
|
+
parent.insertBefore(text, marker)
|
|
272
|
+
nodes = [text]
|
|
273
|
+
return
|
|
251
274
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
if (rendered.
|
|
275
|
+
|
|
276
|
+
if (rendered instanceof Node) {
|
|
277
|
+
if (rendered.nodeType === 11) {
|
|
278
|
+
nodes = Array.from(rendered.childNodes)
|
|
255
279
|
parent.insertBefore(rendered, marker)
|
|
280
|
+
}
|
|
281
|
+
else {
|
|
282
|
+
nodes = [rendered]
|
|
283
|
+
if (rendered.parentNode !== parent)
|
|
284
|
+
parent.insertBefore(rendered, marker)
|
|
285
|
+
}
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (Array.isArray(rendered)) {
|
|
290
|
+
const f = document.createDocumentFragment()
|
|
291
|
+
const list: Node[] = []
|
|
292
|
+
for (let i = 0; i < rendered.length; i++) {
|
|
293
|
+
const item = rendered[i]
|
|
294
|
+
if (item instanceof Node) {
|
|
295
|
+
if (item.nodeType === 11)
|
|
296
|
+
list.push(...Array.from(item.childNodes))
|
|
297
|
+
else
|
|
298
|
+
list.push(item)
|
|
299
|
+
f.appendChild(item)
|
|
300
|
+
}
|
|
301
|
+
else if (item != null && typeof item !== 'boolean') {
|
|
302
|
+
const str = String(item)
|
|
303
|
+
if (str !== '') {
|
|
304
|
+
const t = document.createTextNode(str)
|
|
305
|
+
list.push(t)
|
|
306
|
+
f.appendChild(t)
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
parent.insertBefore(f, marker)
|
|
311
|
+
nodes = list
|
|
256
312
|
}
|
|
257
313
|
})
|
|
258
314
|
}
|
package/src/dom/index.ts
CHANGED
|
@@ -27,9 +27,9 @@ export function claimLoop(parent: Node, fn: () => void, skip = 0): boolean {
|
|
|
27
27
|
return true
|
|
28
28
|
}
|
|
29
29
|
|
|
30
|
-
export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null } {
|
|
30
|
+
export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T): { result: T, marker: Node | null, claimed: Node | null } {
|
|
31
31
|
if (!hydrating)
|
|
32
|
-
return { result: fn(), marker }
|
|
32
|
+
return { result: fn(), marker, claimed: null }
|
|
33
33
|
|
|
34
34
|
let claimed: Node | null = marker !== null ? marker : parent.lastChild
|
|
35
35
|
let nextMarker = marker
|
|
@@ -45,7 +45,7 @@ export function claimInsert<T>(parent: Node, marker: Node | null, fn: () => T):
|
|
|
45
45
|
const prevNode = hydrateNode
|
|
46
46
|
hydrateNode = claimed
|
|
47
47
|
try {
|
|
48
|
-
return { result: fn(), marker: nextMarker }
|
|
48
|
+
return { result: fn(), marker: nextMarker, claimed }
|
|
49
49
|
}
|
|
50
50
|
finally {
|
|
51
51
|
hydrateNode = prevNode
|
package/src/dom/island.ts
CHANGED
|
@@ -5,98 +5,120 @@ import { hydrate, mount } from './index'
|
|
|
5
5
|
declare const KAY_DEFERRED: boolean | undefined
|
|
6
6
|
declare const KAY_CLIENT_ONLY: boolean | undefined
|
|
7
7
|
|
|
8
|
+
export function parseIslandProps(raw: string): Record<string, unknown> {
|
|
9
|
+
if (!raw.includes('"__k":'))
|
|
10
|
+
return JSON.parse(raw) as Record<string, unknown>
|
|
11
|
+
return JSON.parse(raw, (_k, v: unknown) => {
|
|
12
|
+
if (v !== null && typeof v === 'object' && '__k' in v && 'v' in v) {
|
|
13
|
+
const tagged = v as { __k: string, v: unknown }
|
|
14
|
+
if (tagged.__k === 'D') return new Date(tagged.v as string)
|
|
15
|
+
if (tagged.__k === 'S') return new Set(tagged.v as unknown[])
|
|
16
|
+
if (tagged.__k === 'M') return new Map(tagged.v as [unknown, unknown][])
|
|
17
|
+
if (tagged.__k === 'U') return new URL(tagged.v as string)
|
|
18
|
+
if (tagged.__k === 'R') {
|
|
19
|
+
const [src, flags] = tagged.v as [string, string]
|
|
20
|
+
return new RegExp(src, flags)
|
|
21
|
+
}
|
|
22
|
+
if (tagged.__k === 'B') return BigInt(tagged.v as string)
|
|
23
|
+
}
|
|
24
|
+
return v
|
|
25
|
+
}) as Record<string, unknown>
|
|
26
|
+
}
|
|
27
|
+
|
|
8
28
|
type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
|
|
9
29
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
30
|
+
export function defineIslandElement(): void {
|
|
31
|
+
if (typeof customElements === 'undefined' || customElements.get('kay-island'))
|
|
32
|
+
return
|
|
13
33
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
this._s = true
|
|
34
|
+
class KayIsland extends HTMLElement {
|
|
35
|
+
_d: (() => void) | undefined
|
|
36
|
+
_s = false
|
|
18
37
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (h === 'visible') {
|
|
22
|
-
const target = this.firstElementChild ?? this
|
|
23
|
-
const io = new IntersectionObserver((entries) => {
|
|
24
|
-
if (entries.some(e => e.isIntersecting)) {
|
|
25
|
-
io.disconnect()
|
|
26
|
-
void this._l(false)
|
|
27
|
-
}
|
|
28
|
-
}, { rootMargin: '200px' })
|
|
29
|
-
io.observe(target)
|
|
30
|
-
return
|
|
31
|
-
}
|
|
32
|
-
if (h === 'idle') {
|
|
33
|
-
const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
|
|
34
|
-
ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
|
|
38
|
+
connectedCallback(): void {
|
|
39
|
+
if (this._s)
|
|
35
40
|
return
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
this._s = true
|
|
42
|
+
|
|
43
|
+
const h = this.getAttribute('h')
|
|
44
|
+
if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
|
|
45
|
+
if (h === 'visible') {
|
|
46
|
+
const target = this.firstElementChild ?? this
|
|
47
|
+
const io = new IntersectionObserver((entries) => {
|
|
48
|
+
if (entries.some(e => e.isIntersecting)) {
|
|
49
|
+
io.disconnect()
|
|
50
|
+
void this._l(false)
|
|
51
|
+
}
|
|
52
|
+
}, { rootMargin: '200px' })
|
|
53
|
+
io.observe(target)
|
|
54
|
+
return
|
|
42
55
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const mq = matchMedia(h.slice(6, -1))
|
|
48
|
-
if (mq.matches) {
|
|
49
|
-
void this._l(false)
|
|
56
|
+
if (h === 'idle') {
|
|
57
|
+
const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
|
|
58
|
+
ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
|
|
59
|
+
return
|
|
50
60
|
}
|
|
51
|
-
|
|
61
|
+
if (h === 'interaction') {
|
|
62
|
+
const evs = ['pointerdown', 'focusin', 'keydown']
|
|
52
63
|
const go = () => {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
64
|
+
for (const e of evs) this.removeEventListener(e, go, true)
|
|
65
|
+
void this._l(false)
|
|
66
|
+
}
|
|
67
|
+
for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
if (h !== null && h.startsWith('media(')) {
|
|
71
|
+
const mq = matchMedia(h.slice(6, -1))
|
|
72
|
+
if (mq.matches) {
|
|
73
|
+
void this._l(false)
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
const go = () => {
|
|
77
|
+
if (mq.matches) {
|
|
78
|
+
mq.removeEventListener('change', go)
|
|
79
|
+
void this._l(false)
|
|
80
|
+
}
|
|
56
81
|
}
|
|
82
|
+
mq.addEventListener('change', go)
|
|
57
83
|
}
|
|
58
|
-
|
|
84
|
+
return
|
|
59
85
|
}
|
|
60
|
-
return
|
|
61
86
|
}
|
|
62
|
-
}
|
|
63
87
|
|
|
64
|
-
|
|
65
|
-
|
|
88
|
+
void this._l(h === 'client')
|
|
89
|
+
}
|
|
66
90
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
91
|
+
disconnectedCallback(): void {
|
|
92
|
+
// Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
|
|
93
|
+
queueMicrotask(() => {
|
|
94
|
+
if (!this.isConnected) {
|
|
95
|
+
this._d?.()
|
|
96
|
+
this._d = undefined
|
|
97
|
+
this._s = false
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
}
|
|
77
101
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
102
|
+
async _l(clientOnly: boolean): Promise<void> {
|
|
103
|
+
const chunk = this.getAttribute('c')
|
|
104
|
+
if (!chunk)
|
|
105
|
+
return
|
|
82
106
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
107
|
+
const mod = await import(chunk) as IslandModule
|
|
108
|
+
if (!this.isConnected)
|
|
109
|
+
return
|
|
86
110
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
111
|
+
const p = this.getAttribute('p')
|
|
112
|
+
const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
|
|
113
|
+
const slot = this.querySelector('kay-slot')
|
|
114
|
+
if (slot !== null)
|
|
115
|
+
props.children = slot
|
|
116
|
+
const render = () => mod.default(props)
|
|
117
|
+
this._d = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
|
|
118
|
+
? mount(this, render)
|
|
119
|
+
: hydrate(this, render)
|
|
120
|
+
}
|
|
96
121
|
}
|
|
97
|
-
}
|
|
98
122
|
|
|
99
|
-
|
|
100
|
-
if (typeof customElements !== 'undefined' && !customElements.get('kay-island'))
|
|
101
|
-
customElements.define('kay-island', KayIsland)
|
|
123
|
+
customElements.define('kay-island', KayIsland)
|
|
102
124
|
}
|
package/src/plugins/index.ts
CHANGED
|
@@ -21,8 +21,19 @@ export interface BuildPluginContext {
|
|
|
21
21
|
emitPublic(relPath: string, content: string | Uint8Array): string
|
|
22
22
|
/** Add a stylesheet URL to <head> on every page. */
|
|
23
23
|
addStyle(href: string): void
|
|
24
|
+
/** Add a stylesheet URL to <head> on a specific route path only. */
|
|
25
|
+
addRouteStyle(routePath: string, href: string): void
|
|
24
26
|
/** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
|
|
25
27
|
addHead(html: string): void
|
|
28
|
+
/** Add raw HTML to <head> on a specific route path only. */
|
|
29
|
+
addRouteHead(routePath: string, html: string): void
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CheckPluginContext {
|
|
33
|
+
readonly root: string
|
|
34
|
+
readonly routesDir: string
|
|
35
|
+
/** Report a validation error from `kay check`. */
|
|
36
|
+
error(message: string): void
|
|
26
37
|
}
|
|
27
38
|
|
|
28
39
|
export interface ServerPluginAPI {
|
|
@@ -34,10 +45,18 @@ export interface ServerPluginAPI {
|
|
|
34
45
|
rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
|
|
35
46
|
}
|
|
36
47
|
|
|
48
|
+
export interface ServerErrorInfo {
|
|
49
|
+
error: unknown
|
|
50
|
+
request: Request
|
|
51
|
+
source: 'route' | 'action' | 'plugin'
|
|
52
|
+
}
|
|
53
|
+
|
|
37
54
|
export interface KayPlugin {
|
|
38
55
|
name: string
|
|
39
56
|
/** Register server routes, global middleware, or URL rewrites. */
|
|
40
57
|
server?: (api: ServerPluginAPI) => void | Promise<void>
|
|
58
|
+
/** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
|
|
59
|
+
onError?: (info: ServerErrorInfo) => void
|
|
41
60
|
/** Build hook run after route compilation, before prerender / --static / --compile. */
|
|
42
61
|
build?: (ctx: BuildPluginContext) => void | Promise<void>
|
|
43
62
|
/** Code transform run during client & server compilation. */
|
|
@@ -52,18 +71,25 @@ export interface KayPlugin {
|
|
|
52
71
|
prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
|
|
53
72
|
/** Client bootstrap module path — bundled ONLY when this plugin is active. */
|
|
54
73
|
clientEntry?: string | undefined
|
|
74
|
+
/** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
|
|
75
|
+
check?: (ctx: CheckPluginContext) => void | Promise<void>
|
|
76
|
+
/** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
|
|
77
|
+
watchPaths?: string[] | ((root: string) => string[]) | undefined
|
|
55
78
|
/** Register custom CLI subcommands (e.g. `kay i18n check`). */
|
|
56
79
|
commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
|
|
57
80
|
}
|
|
58
81
|
|
|
59
82
|
export interface KayConfig {
|
|
60
83
|
lang?: string | undefined
|
|
84
|
+
port?: number | undefined
|
|
61
85
|
routesDir?: string | undefined
|
|
62
86
|
outDir?: string | undefined
|
|
63
87
|
publicDir?: string | undefined
|
|
64
88
|
assetPrefix?: string | undefined
|
|
65
89
|
security?: SecurityHeadersOptions | false | undefined
|
|
66
90
|
trustedOrigins?: string[] | undefined
|
|
91
|
+
compress?: boolean | undefined
|
|
92
|
+
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
67
93
|
plugins?: KayPlugin[] | undefined
|
|
68
94
|
}
|
|
69
95
|
|
|
@@ -75,11 +101,18 @@ export function definePlugin(plugin: KayPlugin): KayPlugin {
|
|
|
75
101
|
return plugin
|
|
76
102
|
}
|
|
77
103
|
|
|
78
|
-
|
|
104
|
+
const KAY_ROOT_KEY = Symbol.for('kay.root')
|
|
105
|
+
let configReloadSeq = 0
|
|
106
|
+
|
|
107
|
+
export async function loadConfig(root: string, options?: { fresh?: boolean }): Promise<KayConfig> {
|
|
79
108
|
const absRoot = resolve(root)
|
|
109
|
+
;(globalThis as Record<symbol, unknown>)[KAY_ROOT_KEY] = absRoot
|
|
80
110
|
const configPath = join(absRoot, 'kay.config.ts')
|
|
81
111
|
if (!existsSync(configPath))
|
|
82
112
|
return {}
|
|
83
|
-
const
|
|
113
|
+
const spec = options?.fresh || process.env.KAY_DEV === '1'
|
|
114
|
+
? `${configPath}?v=${++configReloadSeq}-${Date.now()}`
|
|
115
|
+
: configPath
|
|
116
|
+
const mod = await import(spec) as { default?: KayConfig }
|
|
84
117
|
return mod.default ?? {}
|
|
85
118
|
}
|