@kayjs/kay 2.0.0-alpha.5 → 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 +400 -25
- package/src/cli/check.ts +165 -4
- package/src/cli/index.ts +2 -1
- package/src/cli/new.ts +1 -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 +25 -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 +40 -7
- package/src/server/index.ts +435 -158
- package/src/server/security.ts +81 -1
- package/src/ssr/context.ts +5 -2
- package/src/ssr/index.ts +30 -3
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kayjs/kay",
|
|
3
|
-
"version": "2.0.0-alpha.
|
|
3
|
+
"version": "2.0.0-alpha.6",
|
|
4
4
|
"description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"homepage": "https://kayjs.kaynooo.fr",
|
package/src/build/compile.ts
CHANGED
|
@@ -67,18 +67,21 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
67
67
|
embeddedPublic.push(`${JSON.stringify(rel)}: ${v}`)
|
|
68
68
|
embeddedPublicEtags.push(`${JSON.stringify(rel)}: ${JSON.stringify(etag)}`)
|
|
69
69
|
}
|
|
70
|
-
const
|
|
70
|
+
const embeddedPrerenderedFiles: string[] = []
|
|
71
|
+
let preIdx = 0
|
|
71
72
|
for (const r of manifest.routes) {
|
|
72
73
|
if (r.prerendered) {
|
|
73
74
|
for (const [, relHtml] of Object.entries(r.prerendered)) {
|
|
74
|
-
const
|
|
75
|
-
|
|
75
|
+
const abs = join(outDir, relHtml)
|
|
76
|
+
const v = `_r${preIdx++}`
|
|
77
|
+
imports.push(`import ${v} from ${JSON.stringify(abs)} with { type: "file" };`)
|
|
78
|
+
embeddedPrerenderedFiles.push(`${JSON.stringify(relHtml)}: ${v}`)
|
|
76
79
|
}
|
|
77
80
|
}
|
|
78
81
|
}
|
|
79
82
|
|
|
80
83
|
const cfgSpread = hasConfig
|
|
81
|
-
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins`
|
|
84
|
+
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress`
|
|
82
85
|
: ''
|
|
83
86
|
|
|
84
87
|
// Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
|
|
@@ -91,8 +94,9 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
91
94
|
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
92
95
|
`const publicAssets = { ${embeddedPublic.join(', ')} };`,
|
|
93
96
|
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
94
|
-
`const prerendered = {
|
|
95
|
-
`const
|
|
97
|
+
`const prerendered = {};`,
|
|
98
|
+
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
99
|
+
`const app = await createServerFromEmbedded({ manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)}${cfgSpread} });`,
|
|
96
100
|
`const port = Number(process.env.PORT ?? 3000);`,
|
|
97
101
|
`const server = app.serve(port);`,
|
|
98
102
|
`console.log(\`kay server listening on http://localhost:\${server.port}\`);`,
|
package/src/build/index.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import type { BunPlugin } from 'bun'
|
|
7
7
|
import type { IslandBinding, ModuleAnalysis } from '../compiler/index'
|
|
8
8
|
import type { BuildPluginContext, KayPlugin } from '../plugins/index'
|
|
9
|
-
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
9
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
|
10
10
|
import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
|
|
11
11
|
import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
|
|
12
12
|
import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
|
|
@@ -14,6 +14,20 @@ import { loadConfig } from '../plugins/index'
|
|
|
14
14
|
import { actionHash } from '../server/action'
|
|
15
15
|
import { compileExecutable } from './compile'
|
|
16
16
|
|
|
17
|
+
export interface BuildCache {
|
|
18
|
+
analyses: Map<string, { mtimeMs: number, size: number, code: string, analysis: ModuleAnalysis }>
|
|
19
|
+
domCompiled: Map<string, { mtimeMs: number, size: number, code: string }>
|
|
20
|
+
ssrCompiled: Map<string, { mtimeMs: number, size: number, key: string, code: string }>
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function createBuildCache(): BuildCache {
|
|
24
|
+
return {
|
|
25
|
+
analyses: new Map(),
|
|
26
|
+
domCompiled: new Map(),
|
|
27
|
+
ssrCompiled: new Map(),
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
17
31
|
export interface BuildOptions {
|
|
18
32
|
root: string
|
|
19
33
|
routesDir?: string | undefined
|
|
@@ -22,7 +36,11 @@ export interface BuildOptions {
|
|
|
22
36
|
minify?: boolean | undefined
|
|
23
37
|
assetPrefix?: string | undefined
|
|
24
38
|
plugins?: KayPlugin[] | undefined
|
|
25
|
-
/**
|
|
39
|
+
/** Reusable incremental cache for `kay dev` (skips re-parsing/re-compiling unchanged files). */
|
|
40
|
+
cache?: BuildCache | undefined
|
|
41
|
+
/** Print a per-route JS/CSS bundle weight report using Bun.build's metafile. */
|
|
42
|
+
analyze?: boolean | undefined
|
|
43
|
+
/** Export a static site directly into outDir (dist/) with no server/ folder left behind. */
|
|
26
44
|
static?: boolean | undefined
|
|
27
45
|
/** Run build-time prerendering for routes exporting `prerender = true` (default: true; disabled in `kay dev`). */
|
|
28
46
|
prerender?: boolean | undefined
|
|
@@ -49,6 +67,10 @@ export interface RouteManifestEntry {
|
|
|
49
67
|
islandHydrate?: string | undefined
|
|
50
68
|
islandChunks: string[]
|
|
51
69
|
eagerIslandChunks?: string[] | undefined
|
|
70
|
+
/** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
|
|
71
|
+
styles?: string[] | undefined
|
|
72
|
+
/** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
|
|
73
|
+
headTags?: string[] | undefined
|
|
52
74
|
usesRenderContext?: boolean | undefined
|
|
53
75
|
prerender?: boolean | undefined
|
|
54
76
|
prerendered?: Record<string, string> | undefined
|
|
@@ -57,6 +79,8 @@ export interface RouteManifestEntry {
|
|
|
57
79
|
export interface BuildManifest {
|
|
58
80
|
runtimeScript: string | undefined
|
|
59
81
|
styles: string[]
|
|
82
|
+
/** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
|
|
83
|
+
globalStyles?: string[] | undefined
|
|
60
84
|
headTags?: string[] | undefined
|
|
61
85
|
routes: RouteManifestEntry[]
|
|
62
86
|
errorFile?: string | undefined
|
|
@@ -202,13 +226,31 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
202
226
|
const fileConfig = await loadConfig(root)
|
|
203
227
|
const plugins: KayPlugin[] = options.plugins ?? fileConfig.plugins ?? []
|
|
204
228
|
const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
|
|
205
|
-
const
|
|
229
|
+
const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
230
|
+
const cacheBaseDir = join(root, '.kay-cache')
|
|
231
|
+
const cacheExisted = existsSync(cacheBaseDir)
|
|
232
|
+
const outDir = options.static
|
|
233
|
+
? join(cacheBaseDir, `.static-stage-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
|
|
234
|
+
: finalOutDir
|
|
206
235
|
const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
|
|
207
236
|
const clientDir = join(outDir, 'client')
|
|
208
237
|
const serverDir = join(outDir, 'server')
|
|
209
238
|
const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
|
|
210
239
|
const minify = options.minify ?? true
|
|
211
240
|
|
|
241
|
+
try {
|
|
242
|
+
return await buildInternal()
|
|
243
|
+
}
|
|
244
|
+
finally {
|
|
245
|
+
if (options.static) {
|
|
246
|
+
rmSync(outDir, { recursive: true, force: true })
|
|
247
|
+
if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
|
|
248
|
+
rmSync(cacheBaseDir, { recursive: true, force: true })
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function buildInternal(): Promise<BuildManifest> {
|
|
253
|
+
|
|
212
254
|
const pluginBunPlugins = plugins.flatMap((p) => {
|
|
213
255
|
const bp = p.bunPlugins
|
|
214
256
|
if (typeof bp === 'function')
|
|
@@ -246,17 +288,48 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
246
288
|
const hasErrorFile = existsSync(errorSrc)
|
|
247
289
|
const hasNotFoundFile = existsSync(notFoundSrc)
|
|
248
290
|
|
|
249
|
-
// Analyze every reachable .tsx and .ts file once
|
|
291
|
+
// Analyze every reachable .tsx and .ts file once (reusing BuildCache across `kay dev` rebuilds when mtime+size match)
|
|
292
|
+
const cache = options.cache
|
|
250
293
|
const analyses = new Map<string, ModuleAnalysis>()
|
|
251
294
|
const sources = new Map<string, string>()
|
|
295
|
+
const fileStamps = new Map<string, { mtimeMs: number, size: number }>()
|
|
296
|
+
|
|
297
|
+
function getFileStamp(file: string): { mtimeMs: number, size: number } | undefined {
|
|
298
|
+
const existing = fileStamps.get(file)
|
|
299
|
+
if (existing !== undefined)
|
|
300
|
+
return existing
|
|
301
|
+
if (cache === undefined)
|
|
302
|
+
return undefined
|
|
303
|
+
try {
|
|
304
|
+
const st = statSync(file)
|
|
305
|
+
const stamp = { mtimeMs: st.mtimeMs, size: st.size }
|
|
306
|
+
fileStamps.set(file, stamp)
|
|
307
|
+
return stamp
|
|
308
|
+
}
|
|
309
|
+
catch {
|
|
310
|
+
return undefined
|
|
311
|
+
}
|
|
312
|
+
}
|
|
252
313
|
|
|
253
314
|
function loadAnalysis(file: string): ModuleAnalysis {
|
|
254
315
|
const existing = analyses.get(file)
|
|
255
316
|
if (existing !== undefined)
|
|
256
317
|
return existing
|
|
257
|
-
const
|
|
318
|
+
const stamp = getFileStamp(file)
|
|
319
|
+
const cached = stamp !== undefined ? cache?.analyses.get(file) : undefined
|
|
320
|
+
let code: string
|
|
321
|
+
let analysis: ModuleAnalysis
|
|
322
|
+
if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
|
|
323
|
+
code = cached.code
|
|
324
|
+
analysis = cached.analysis
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
code = readFileSync(file, 'utf8')
|
|
328
|
+
analysis = analyzeModule(file, code)
|
|
329
|
+
if (cache !== undefined && stamp !== undefined)
|
|
330
|
+
cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
|
|
331
|
+
}
|
|
258
332
|
sources.set(file, code)
|
|
259
|
-
const analysis = analyzeModule(file, code)
|
|
260
333
|
analyses.set(file, analysis)
|
|
261
334
|
for (const imp of analysis.imports) {
|
|
262
335
|
const target = resolveImportPath(file, imp.source)
|
|
@@ -384,9 +457,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
384
457
|
// Step 1 & Step 2: Single-pass Client + Server Builds
|
|
385
458
|
// When there are no islands (e.g. static sites, blogs, docs), run client CSS and server builds in parallel!
|
|
386
459
|
const islandChunks = new Map<string, string>()
|
|
460
|
+
const srcCssToUrl = new Map<string, string>()
|
|
461
|
+
const islandCssUrl = new Map<string, string>()
|
|
387
462
|
const assetFiles: string[] = []
|
|
388
463
|
const styleUrls: string[] = []
|
|
389
464
|
let runtimeScript: string | undefined
|
|
465
|
+
let clientMetafile: Bun.BuildOutput['metafile']
|
|
390
466
|
|
|
391
467
|
const needsClientBuild = islandTargets.size > 0 || pluginClientEntries.length > 0 || allStandaloneCss.length > 0
|
|
392
468
|
|
|
@@ -396,6 +472,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
396
472
|
const entriesDir = join(outDir, '.entries')
|
|
397
473
|
mkdirSync(entriesDir, { recursive: true })
|
|
398
474
|
const entryPoints: string[] = []
|
|
475
|
+
const islandEntryToKey = new Map<string, string>()
|
|
399
476
|
|
|
400
477
|
const compiledDomCache = new Map<string, string>()
|
|
401
478
|
let hasDeferredHydrate = false
|
|
@@ -431,13 +508,14 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
431
508
|
for (const cssFile of allStandaloneCss)
|
|
432
509
|
entryPoints.push(cssFile)
|
|
433
510
|
|
|
434
|
-
for (const [, target] of islandTargets) {
|
|
511
|
+
for (const [key, target] of islandTargets) {
|
|
435
512
|
const entryPath = join(entriesDir, `${target.id}.ts`)
|
|
436
513
|
const exportStmt = target.exportName === 'default'
|
|
437
514
|
? `export { default } from ${JSON.stringify(target.file)};\n`
|
|
438
515
|
: `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
|
|
439
516
|
writeFileSync(entryPath, exportStmt)
|
|
440
517
|
entryPoints.push(entryPath)
|
|
518
|
+
islandEntryToKey.set(entryPath, key)
|
|
441
519
|
}
|
|
442
520
|
|
|
443
521
|
const clientPlugin: BunPlugin = {
|
|
@@ -461,8 +539,17 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
461
539
|
|
|
462
540
|
let compiled = compiledDomCache.get(args.path)
|
|
463
541
|
if (compiled === undefined) {
|
|
464
|
-
const
|
|
465
|
-
|
|
542
|
+
const stamp = getFileStamp(args.path)
|
|
543
|
+
const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
|
|
544
|
+
if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size) {
|
|
545
|
+
compiled = cachedDom.code
|
|
546
|
+
}
|
|
547
|
+
else {
|
|
548
|
+
const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
|
|
549
|
+
compiled = applyTransforms(compileDom(args.path, raw, { analysis: analyses.get(args.path) }).code, args.path, 'client')
|
|
550
|
+
if (cache !== undefined && stamp !== undefined)
|
|
551
|
+
cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, code: compiled })
|
|
552
|
+
}
|
|
466
553
|
compiledDomCache.set(args.path, compiled)
|
|
467
554
|
}
|
|
468
555
|
return { contents: compiled, loader: 'tsx' }
|
|
@@ -479,6 +566,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
479
566
|
format: 'esm',
|
|
480
567
|
splitting: true,
|
|
481
568
|
minify,
|
|
569
|
+
metafile: true,
|
|
482
570
|
naming: '[name]-[hash].[ext]',
|
|
483
571
|
define: {
|
|
484
572
|
KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
|
|
@@ -496,6 +584,39 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
496
584
|
throw new Error(`kay build (client) failed:\n${msgs}`)
|
|
497
585
|
}
|
|
498
586
|
|
|
587
|
+
clientMetafile = clientResult.metafile
|
|
588
|
+
const resolveMetaPath = (p: string): string => {
|
|
589
|
+
const fromCwd = resolve(process.cwd(), p)
|
|
590
|
+
if (existsSync(fromCwd) || islandEntryToKey.has(fromCwd))
|
|
591
|
+
return fromCwd
|
|
592
|
+
return resolve(clientDir, p)
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
if (clientMetafile !== undefined) {
|
|
596
|
+
for (const [outKey, info] of Object.entries(clientMetafile.outputs)) {
|
|
597
|
+
const relOut = outKey.replace(/^\.\//, '')
|
|
598
|
+
const url = `${assetPrefix}/${relOut}`
|
|
599
|
+
if (relOut.endsWith('.css')) {
|
|
600
|
+
if (info.entryPoint !== undefined) {
|
|
601
|
+
const absEntry = resolveMetaPath(info.entryPoint)
|
|
602
|
+
if (absEntry.endsWith('.css'))
|
|
603
|
+
srcCssToUrl.set(absEntry, url)
|
|
604
|
+
}
|
|
605
|
+
for (const inKey of Object.keys(info.inputs ?? {})) {
|
|
606
|
+
if (inKey.endsWith('.css'))
|
|
607
|
+
srcCssToUrl.set(resolveMetaPath(inKey), url)
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const cssBundle = (info as { cssBundle?: string }).cssBundle
|
|
611
|
+
if (cssBundle !== undefined && info.entryPoint !== undefined) {
|
|
612
|
+
const absEntry = resolveMetaPath(info.entryPoint)
|
|
613
|
+
const islandKey = islandEntryToKey.get(absEntry)
|
|
614
|
+
if (islandKey !== undefined)
|
|
615
|
+
islandCssUrl.set(islandKey, `${assetPrefix}/${cssBundle.replace(/^\.\//, '')}`)
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
499
620
|
for (const output of clientResult.outputs) {
|
|
500
621
|
const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
|
|
501
622
|
assetFiles.push(relFile)
|
|
@@ -575,10 +696,10 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
575
696
|
})
|
|
576
697
|
}
|
|
577
698
|
b.onLoad({ filter: /\.tsx$/ }, (args) => {
|
|
578
|
-
const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
|
|
579
699
|
const analysis = analyses.get(args.path)
|
|
580
700
|
const rawBindings = pageIslandBindings.get(args.path)
|
|
581
701
|
let islandMap: Map<string, IslandBinding> | undefined
|
|
702
|
+
let islandKey = analysis?.isInteractive ? '1' : '0'
|
|
582
703
|
if (rawBindings !== undefined) {
|
|
583
704
|
islandMap = new Map()
|
|
584
705
|
for (const [localName, target] of rawBindings) {
|
|
@@ -589,15 +710,24 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
589
710
|
chunk,
|
|
590
711
|
defaultHydrate: target.defaultHydrate,
|
|
591
712
|
})
|
|
713
|
+
islandKey += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
|
|
592
714
|
}
|
|
593
715
|
}
|
|
594
716
|
}
|
|
717
|
+
const stamp = getFileStamp(args.path)
|
|
718
|
+
const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
|
|
719
|
+
if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === islandKey)
|
|
720
|
+
return { contents: cachedSsr.code, loader: 'tsx' }
|
|
721
|
+
const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
|
|
595
722
|
const compiled = compileSsr(args.path, raw, {
|
|
596
723
|
analysis,
|
|
597
724
|
islands: islandMap,
|
|
598
725
|
isIsland: analysis?.isInteractive,
|
|
599
726
|
})
|
|
600
|
-
|
|
727
|
+
const outCode = applyTransforms(compiled.code, args.path, 'server')
|
|
728
|
+
if (cache !== undefined && stamp !== undefined)
|
|
729
|
+
cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: islandKey, code: outCode })
|
|
730
|
+
return { contents: outCode, loader: 'tsx' }
|
|
601
731
|
})
|
|
602
732
|
},
|
|
603
733
|
}
|
|
@@ -695,15 +825,68 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
695
825
|
return false
|
|
696
826
|
}
|
|
697
827
|
|
|
828
|
+
function collectRouteStyles(file: string, seen = new Set<string>(), out = new Set<string>()): void {
|
|
829
|
+
if (seen.has(file))
|
|
830
|
+
return
|
|
831
|
+
seen.add(file)
|
|
832
|
+
const analysis = analyses.get(file)
|
|
833
|
+
if (analysis === undefined)
|
|
834
|
+
return
|
|
835
|
+
if (analysis.isInteractive) {
|
|
836
|
+
const islCss = islandCssUrl.get(`${file}#default`)
|
|
837
|
+
if (islCss !== undefined)
|
|
838
|
+
out.add(islCss)
|
|
839
|
+
}
|
|
840
|
+
const bindings = pageIslandBindings.get(file)
|
|
841
|
+
if (bindings !== undefined) {
|
|
842
|
+
for (const [, target] of bindings) {
|
|
843
|
+
const islCss = islandCssUrl.get(`${target.file}#${target.exportName}`)
|
|
844
|
+
if (islCss !== undefined)
|
|
845
|
+
out.add(islCss)
|
|
846
|
+
collectRouteStyles(target.file, seen, out)
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
for (const imp of analysis.imports) {
|
|
850
|
+
const target = resolveImportPath(file, imp.source)
|
|
851
|
+
if (target === undefined)
|
|
852
|
+
continue
|
|
853
|
+
if (target.endsWith('.css')) {
|
|
854
|
+
const cssUrl = srcCssToUrl.get(target)
|
|
855
|
+
if (cssUrl !== undefined)
|
|
856
|
+
out.add(cssUrl)
|
|
857
|
+
}
|
|
858
|
+
else if (target.endsWith('.tsx') || target.endsWith('.ts')) {
|
|
859
|
+
collectRouteStyles(target, seen, out)
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
const globalPluginStyles: string[] = []
|
|
865
|
+
for (const cssFile of pluginCssFiles) {
|
|
866
|
+
const url = srcCssToUrl.get(cssFile)
|
|
867
|
+
if (url !== undefined && !globalPluginStyles.includes(url))
|
|
868
|
+
globalPluginStyles.push(url)
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
const rootLayoutSrc = join(routesDir, '_layout.tsx')
|
|
872
|
+
const globalStyleSet = new Set<string>(globalPluginStyles)
|
|
873
|
+
if (existsSync(rootLayoutSrc))
|
|
874
|
+
collectRouteStyles(rootLayoutSrc, new Set(), globalStyleSet)
|
|
875
|
+
const globalStyles = [...globalStyleSet]
|
|
876
|
+
|
|
698
877
|
const routeEntries: RouteManifestEntry[] = pageFiles.map((file) => {
|
|
699
878
|
const analysis = analyses.get(file)
|
|
700
879
|
const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
|
|
701
880
|
const middlewareSrcs = ancestorFiles(routesDir, file, ['_middleware.ts', '_middleware.tsx'])
|
|
702
881
|
const chunks = new Set<string>()
|
|
703
882
|
const eagerChunks = new Set<string>()
|
|
704
|
-
|
|
883
|
+
const routeStyles = new Set<string>(globalPluginStyles)
|
|
884
|
+
for (const lf of layoutSrcs) {
|
|
705
885
|
collectRouteIslands(lf, new Set(), chunks, eagerChunks)
|
|
886
|
+
collectRouteStyles(lf, new Set(), routeStyles)
|
|
887
|
+
}
|
|
706
888
|
collectRouteIslands(file, new Set(), chunks, eagerChunks)
|
|
889
|
+
collectRouteStyles(file, new Set(), routeStyles)
|
|
707
890
|
|
|
708
891
|
let usesRenderContext = collectUsesRenderContext(file)
|
|
709
892
|
if (!usesRenderContext) {
|
|
@@ -727,6 +910,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
727
910
|
islandHydrate: analysis?.defaultHydrate,
|
|
728
911
|
islandChunks: [...chunks],
|
|
729
912
|
eagerIslandChunks: [...eagerChunks],
|
|
913
|
+
styles: [...routeStyles],
|
|
730
914
|
usesRenderContext,
|
|
731
915
|
prerender: analysis?.hasPrerender || options.static === true,
|
|
732
916
|
}
|
|
@@ -798,11 +982,40 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
798
982
|
styleSet.add(href)
|
|
799
983
|
styleUrls.push(href)
|
|
800
984
|
}
|
|
985
|
+
if (!globalStyleSet.has(href)) {
|
|
986
|
+
globalStyleSet.add(href)
|
|
987
|
+
globalStyles.push(href)
|
|
988
|
+
}
|
|
989
|
+
for (const r of routeEntries) {
|
|
990
|
+
if (r.styles !== undefined && !r.styles.includes(href))
|
|
991
|
+
r.styles.push(href)
|
|
992
|
+
}
|
|
993
|
+
},
|
|
994
|
+
addRouteStyle(routePath, href) {
|
|
995
|
+
if (!styleSet.has(href)) {
|
|
996
|
+
styleSet.add(href)
|
|
997
|
+
styleUrls.push(href)
|
|
998
|
+
}
|
|
999
|
+
const route = routeEntries.find(r => r.path === routePath)
|
|
1000
|
+
if (route !== undefined) {
|
|
1001
|
+
route.styles ??= [...globalStyles]
|
|
1002
|
+
if (!route.styles.includes(href))
|
|
1003
|
+
route.styles.push(href)
|
|
1004
|
+
}
|
|
801
1005
|
},
|
|
802
1006
|
addHead(html) {
|
|
803
1007
|
if (html !== '')
|
|
804
1008
|
headTags.push(html)
|
|
805
1009
|
},
|
|
1010
|
+
addRouteHead(routePath, html) {
|
|
1011
|
+
if (html === '')
|
|
1012
|
+
return
|
|
1013
|
+
const route = routeEntries.find(r => r.path === routePath)
|
|
1014
|
+
if (route !== undefined) {
|
|
1015
|
+
route.headTags ??= []
|
|
1016
|
+
route.headTags.push(html)
|
|
1017
|
+
}
|
|
1018
|
+
},
|
|
806
1019
|
}
|
|
807
1020
|
|
|
808
1021
|
for (const plugin of plugins) {
|
|
@@ -813,6 +1026,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
813
1026
|
const manifest: BuildManifest = {
|
|
814
1027
|
runtimeScript,
|
|
815
1028
|
styles: styleUrls,
|
|
1029
|
+
globalStyles,
|
|
816
1030
|
...(headTags.length > 0 ? { headTags } : {}),
|
|
817
1031
|
routes: routeEntries,
|
|
818
1032
|
errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
|
|
@@ -828,10 +1042,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
828
1042
|
// Step 3: Hybrid Prerendering / Static Export (skipped in `kay dev` where routes render on-demand)
|
|
829
1043
|
const shouldPrerender = options.prerender !== false || options.static === true
|
|
830
1044
|
const prerenderRoutes = shouldPrerender ? routeEntries.filter(r => r.prerender) : []
|
|
831
|
-
if (prerenderRoutes.length > 0) {
|
|
1045
|
+
if (prerenderRoutes.length > 0 || options.static) {
|
|
832
1046
|
const { createServer } = await import('../server/index')
|
|
833
1047
|
const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
|
|
834
|
-
const prerenderDir =
|
|
1048
|
+
const prerenderDir = options.static ? finalOutDir : join(outDir, 'prerendered')
|
|
1049
|
+
if (options.static)
|
|
1050
|
+
rmSync(finalOutDir, { recursive: true, force: true })
|
|
835
1051
|
mkdirSync(prerenderDir, { recursive: true })
|
|
836
1052
|
|
|
837
1053
|
const prerenderStamp = Date.now()
|
|
@@ -865,7 +1081,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
865
1081
|
const absHtml = join(prerenderDir, relHtml)
|
|
866
1082
|
mkdirSync(dirname(absHtml), { recursive: true })
|
|
867
1083
|
writeFileSync(absHtml, html)
|
|
868
|
-
map[u] = relative(outDir, absHtml).replace(/\\/g, '/')
|
|
1084
|
+
map[u] = relative(options.static ? finalOutDir : outDir, absHtml).replace(/\\/g, '/')
|
|
869
1085
|
}
|
|
870
1086
|
}))
|
|
871
1087
|
}
|
|
@@ -877,15 +1093,17 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
877
1093
|
const notFoundRes = await app.handle(new Request('http://localhost/__kay_404__'))
|
|
878
1094
|
writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
|
|
879
1095
|
}
|
|
880
|
-
// Copy client assets into dist/
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
const
|
|
885
|
-
|
|
886
|
-
|
|
1096
|
+
// Copy client assets into dist/_kay/... and public/ files into dist/...
|
|
1097
|
+
if (nonEmptyAssets.length > 0) {
|
|
1098
|
+
const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
|
|
1099
|
+
mkdirSync(staticAssetDir, { recursive: true })
|
|
1100
|
+
for (const rel of nonEmptyAssets) {
|
|
1101
|
+
const dst = join(staticAssetDir, rel)
|
|
1102
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
1103
|
+
writeFileSync(dst, readFileSync(join(clientDir, rel)))
|
|
1104
|
+
}
|
|
887
1105
|
}
|
|
888
|
-
// Re-scan outPublicDir so any assets emitted during prerender (e.g. OG share cards) are included in --static
|
|
1106
|
+
// Re-scan outPublicDir so any assets emitted during prerender (e.g. OG share cards, optimized MD images) are included in --static
|
|
889
1107
|
if (existsSync(outPublicDir)) {
|
|
890
1108
|
for (const abs of walkAllFiles(outPublicDir)) {
|
|
891
1109
|
const rel = relative(outPublicDir, abs).replace(/\\/g, '/')
|
|
@@ -916,8 +1134,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
916
1134
|
writeFileSync(`${abs}.gz`, gz)
|
|
917
1135
|
}
|
|
918
1136
|
}
|
|
919
|
-
|
|
920
|
-
|
|
1137
|
+
else {
|
|
1138
|
+
writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
|
|
1139
|
+
}
|
|
921
1140
|
}
|
|
922
1141
|
|
|
923
1142
|
// Step 4: Single-Executable Compile (`kay build --compile [outfile]`)
|
|
@@ -935,5 +1154,161 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
|
|
|
935
1154
|
})
|
|
936
1155
|
}
|
|
937
1156
|
|
|
1157
|
+
if (options.analyze)
|
|
1158
|
+
console.log(formatBundleReport(manifest, clientDir, assetPrefix, clientMetafile))
|
|
1159
|
+
|
|
938
1160
|
return manifest
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
export interface RouteBundleMetrics {
|
|
1165
|
+
path: string
|
|
1166
|
+
jsRaw: number
|
|
1167
|
+
jsGzip: number
|
|
1168
|
+
cssRaw: number
|
|
1169
|
+
cssGzip: number
|
|
1170
|
+
jsFiles: number
|
|
1171
|
+
cssFiles: number
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
export function analyzeBundleWeights(
|
|
1175
|
+
manifest: BuildManifest,
|
|
1176
|
+
clientDir: string,
|
|
1177
|
+
assetPrefix = '/_kay',
|
|
1178
|
+
metafile?: Bun.BuildOutput['metafile'],
|
|
1179
|
+
): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
|
|
1180
|
+
const prefix = `${assetPrefix.replace(/\/$/, '')}/`
|
|
1181
|
+
const sizeCache = new Map<string, { raw: number, gzip: number }>()
|
|
1182
|
+
|
|
1183
|
+
const getSize = (url: string): { raw: number, gzip: number } => {
|
|
1184
|
+
const cached = sizeCache.get(url)
|
|
1185
|
+
if (cached !== undefined)
|
|
1186
|
+
return cached
|
|
1187
|
+
if (!url.startsWith(prefix))
|
|
1188
|
+
return { raw: 0, gzip: 0 }
|
|
1189
|
+
const abs = join(clientDir, url.slice(prefix.length))
|
|
1190
|
+
if (!existsSync(abs))
|
|
1191
|
+
return { raw: 0, gzip: 0 }
|
|
1192
|
+
const buf = readFileSync(abs)
|
|
1193
|
+
const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
|
|
1194
|
+
sizeCache.set(url, entry)
|
|
1195
|
+
return entry
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
// Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
|
|
1199
|
+
const jsDeps = new Map<string, string[]>()
|
|
1200
|
+
const moduleBytes = new Map<string, number>()
|
|
1201
|
+
if (metafile !== undefined) {
|
|
1202
|
+
for (const [outKey, info] of Object.entries(metafile.outputs)) {
|
|
1203
|
+
const rel = outKey.replace(/^\.\//, '')
|
|
1204
|
+
const url = `${prefix}${rel}`
|
|
1205
|
+
if (rel.endsWith('.js')) {
|
|
1206
|
+
const deps: string[] = []
|
|
1207
|
+
for (const imp of info.imports ?? []) {
|
|
1208
|
+
if (imp.kind === 'import-statement')
|
|
1209
|
+
deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
|
|
1210
|
+
}
|
|
1211
|
+
jsDeps.set(url, deps)
|
|
1212
|
+
}
|
|
1213
|
+
for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
|
|
1214
|
+
moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
|
|
1218
|
+
const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
|
|
1219
|
+
const seen = new Set<string>()
|
|
1220
|
+
const stack = [...urls]
|
|
1221
|
+
while (stack.length > 0) {
|
|
1222
|
+
const cur = stack.pop()!
|
|
1223
|
+
if (seen.has(cur))
|
|
1224
|
+
continue
|
|
1225
|
+
seen.add(cur)
|
|
1226
|
+
for (const dep of jsDeps.get(cur) ?? [])
|
|
1227
|
+
stack.push(dep)
|
|
1228
|
+
}
|
|
1229
|
+
return seen
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
|
|
1233
|
+
const eagerJsRoots: string[] = []
|
|
1234
|
+
if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
|
|
1235
|
+
eagerJsRoots.push(manifest.runtimeScript)
|
|
1236
|
+
for (const c of r.eagerIslandChunks ?? r.islandChunks)
|
|
1237
|
+
eagerJsRoots.push(c)
|
|
1238
|
+
|
|
1239
|
+
const jsSet = collectTransitiveJs(eagerJsRoots)
|
|
1240
|
+
let jsRaw = 0
|
|
1241
|
+
let jsGzip = 0
|
|
1242
|
+
for (const u of jsSet) {
|
|
1243
|
+
const s = getSize(u)
|
|
1244
|
+
jsRaw += s.raw
|
|
1245
|
+
jsGzip += s.gzip
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
const cssList = r.styles ?? manifest.styles
|
|
1249
|
+
let cssRaw = 0
|
|
1250
|
+
let cssGzip = 0
|
|
1251
|
+
for (const u of cssList) {
|
|
1252
|
+
const s = getSize(u)
|
|
1253
|
+
cssRaw += s.raw
|
|
1254
|
+
cssGzip += s.gzip
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
return {
|
|
1258
|
+
path: r.path,
|
|
1259
|
+
jsRaw,
|
|
1260
|
+
jsGzip,
|
|
1261
|
+
cssRaw,
|
|
1262
|
+
cssGzip,
|
|
1263
|
+
jsFiles: jsSet.size,
|
|
1264
|
+
cssFiles: cssList.length,
|
|
1265
|
+
}
|
|
1266
|
+
})
|
|
1267
|
+
|
|
1268
|
+
let totalJsGzip = 0
|
|
1269
|
+
let totalCssGzip = 0
|
|
1270
|
+
for (const rel of manifest.assets) {
|
|
1271
|
+
const s = getSize(`${prefix}${rel}`)
|
|
1272
|
+
if (rel.endsWith('.js'))
|
|
1273
|
+
totalJsGzip += s.gzip
|
|
1274
|
+
else if (rel.endsWith('.css'))
|
|
1275
|
+
totalCssGzip += s.gzip
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
const topModules = [...moduleBytes.entries()]
|
|
1279
|
+
.map(([path, bytes]) => ({ path, bytes }))
|
|
1280
|
+
.sort((a, b) => b.bytes - a.bytes)
|
|
1281
|
+
.slice(0, 10)
|
|
1282
|
+
|
|
1283
|
+
return { routes, totalJsGzip, totalCssGzip, topModules }
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
export function formatBundleReport(
|
|
1287
|
+
manifest: BuildManifest,
|
|
1288
|
+
clientDir: string,
|
|
1289
|
+
assetPrefix = '/_kay',
|
|
1290
|
+
metafile?: Bun.BuildOutput['metafile'],
|
|
1291
|
+
): string {
|
|
1292
|
+
const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
|
|
1293
|
+
const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
|
|
1294
|
+
const lines = [
|
|
1295
|
+
'\n=== KAY BUNDLE WEIGHT REPORT ===',
|
|
1296
|
+
`Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
|
|
1297
|
+
'',
|
|
1298
|
+
'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Files'.padStart(10),
|
|
1299
|
+
]
|
|
1300
|
+
for (const r of report.routes) {
|
|
1301
|
+
lines.push(
|
|
1302
|
+
r.path.padEnd(28)
|
|
1303
|
+
+ kb(r.jsGzip).padStart(16)
|
|
1304
|
+
+ kb(r.cssGzip).padStart(14)
|
|
1305
|
+
+ `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
|
|
1306
|
+
)
|
|
1307
|
+
}
|
|
1308
|
+
if (report.topModules.length > 0) {
|
|
1309
|
+
lines.push('', 'Top modules (minified output bytes):')
|
|
1310
|
+
for (const m of report.topModules.slice(0, 8))
|
|
1311
|
+
lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
|
|
1312
|
+
}
|
|
1313
|
+
return lines.join('\n')
|
|
939
1314
|
}
|