@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.
@@ -6,14 +6,28 @@
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'
10
- import { basename, dirname, extname, join, relative, resolve } from 'node:path'
9
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
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'
13
13
  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
- /** Export a static site into dist/static (prerenders all static + paths() routes). */
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
@@ -86,10 +110,22 @@ export function resolveKaySpecifier(specifier: string): string | undefined {
86
110
  return join(KAY_SRC_ROOT, 'ssr/index.ts')
87
111
  if (specifier === 'kay/server' || specifier === '@kayjs/kay/server')
88
112
  return join(KAY_SRC_ROOT, 'server/index.ts')
113
+ if (specifier === 'kay/compiler' || specifier === '@kayjs/kay/compiler')
114
+ return join(KAY_SRC_ROOT, 'compiler/index.ts')
115
+ if (specifier === 'kay/build' || specifier === '@kayjs/kay/build')
116
+ return join(KAY_SRC_ROOT, 'build/index.ts')
117
+ if (specifier === 'kay/dev' || specifier === '@kayjs/kay/dev')
118
+ return join(KAY_SRC_ROOT, 'dev/index.ts')
89
119
  if (specifier === 'kay/test' || specifier === '@kayjs/kay/test')
90
120
  return join(KAY_SRC_ROOT, 'test/index.ts')
91
- if (specifier === 'kay/jsx-runtime' || specifier === 'kay/jsx-dev-runtime')
121
+ if (
122
+ specifier === 'kay/jsx-runtime'
123
+ || specifier === 'kay/jsx-dev-runtime'
124
+ || specifier === '@kayjs/kay/jsx-runtime'
125
+ || specifier === '@kayjs/kay/jsx-dev-runtime'
126
+ ) {
92
127
  return join(KAY_SRC_ROOT, 'jsx-runtime.ts')
128
+ }
93
129
  return undefined
94
130
  }
95
131
 
@@ -190,13 +226,31 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
190
226
  const fileConfig = await loadConfig(root)
191
227
  const plugins: KayPlugin[] = options.plugins ?? fileConfig.plugins ?? []
192
228
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
193
- const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
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
194
235
  const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
195
236
  const clientDir = join(outDir, 'client')
196
237
  const serverDir = join(outDir, 'server')
197
238
  const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
198
239
  const minify = options.minify ?? true
199
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
+
200
254
  const pluginBunPlugins = plugins.flatMap((p) => {
201
255
  const bp = p.bunPlugins
202
256
  if (typeof bp === 'function')
@@ -234,17 +288,48 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
234
288
  const hasErrorFile = existsSync(errorSrc)
235
289
  const hasNotFoundFile = existsSync(notFoundSrc)
236
290
 
237
- // 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
238
293
  const analyses = new Map<string, ModuleAnalysis>()
239
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
+ }
240
313
 
241
314
  function loadAnalysis(file: string): ModuleAnalysis {
242
315
  const existing = analyses.get(file)
243
316
  if (existing !== undefined)
244
317
  return existing
245
- const code = readFileSync(file, 'utf8')
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
+ }
246
332
  sources.set(file, code)
247
- const analysis = analyzeModule(file, code)
248
333
  analyses.set(file, analysis)
249
334
  for (const imp of analysis.imports) {
250
335
  const target = resolveImportPath(file, imp.source)
@@ -372,9 +457,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
372
457
  // Step 1 & Step 2: Single-pass Client + Server Builds
373
458
  // When there are no islands (e.g. static sites, blogs, docs), run client CSS and server builds in parallel!
374
459
  const islandChunks = new Map<string, string>()
460
+ const srcCssToUrl = new Map<string, string>()
461
+ const islandCssUrl = new Map<string, string>()
375
462
  const assetFiles: string[] = []
376
463
  const styleUrls: string[] = []
377
464
  let runtimeScript: string | undefined
465
+ let clientMetafile: Bun.BuildOutput['metafile']
378
466
 
379
467
  const needsClientBuild = islandTargets.size > 0 || pluginClientEntries.length > 0 || allStandaloneCss.length > 0
380
468
 
@@ -384,6 +472,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
384
472
  const entriesDir = join(outDir, '.entries')
385
473
  mkdirSync(entriesDir, { recursive: true })
386
474
  const entryPoints: string[] = []
475
+ const islandEntryToKey = new Map<string, string>()
387
476
 
388
477
  const compiledDomCache = new Map<string, string>()
389
478
  let hasDeferredHydrate = false
@@ -419,13 +508,14 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
419
508
  for (const cssFile of allStandaloneCss)
420
509
  entryPoints.push(cssFile)
421
510
 
422
- for (const [, target] of islandTargets) {
511
+ for (const [key, target] of islandTargets) {
423
512
  const entryPath = join(entriesDir, `${target.id}.ts`)
424
513
  const exportStmt = target.exportName === 'default'
425
514
  ? `export { default } from ${JSON.stringify(target.file)};\n`
426
515
  : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
427
516
  writeFileSync(entryPath, exportStmt)
428
517
  entryPoints.push(entryPath)
518
+ islandEntryToKey.set(entryPath, key)
429
519
  }
430
520
 
431
521
  const clientPlugin: BunPlugin = {
@@ -449,8 +539,17 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
449
539
 
450
540
  let compiled = compiledDomCache.get(args.path)
451
541
  if (compiled === undefined) {
452
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
453
- compiled = applyTransforms(compileDom(args.path, raw, { analysis: analyses.get(args.path) }).code, args.path, 'client')
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
+ }
454
553
  compiledDomCache.set(args.path, compiled)
455
554
  }
456
555
  return { contents: compiled, loader: 'tsx' }
@@ -467,6 +566,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
467
566
  format: 'esm',
468
567
  splitting: true,
469
568
  minify,
569
+ metafile: true,
470
570
  naming: '[name]-[hash].[ext]',
471
571
  define: {
472
572
  KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
@@ -484,6 +584,39 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
484
584
  throw new Error(`kay build (client) failed:\n${msgs}`)
485
585
  }
486
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
+
487
620
  for (const output of clientResult.outputs) {
488
621
  const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
489
622
  assetFiles.push(relFile)
@@ -509,13 +642,28 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
509
642
  const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
510
643
  const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
511
644
 
645
+ const relOut = relative(root, outDir)
646
+ const outDirOutsideRoot = relOut !== '' && (relOut.startsWith('..') || isAbsolute(relOut))
647
+ const EXTERNAL_KAY_SUBPATHS = new Set([
648
+ 'kay/build',
649
+ '@kayjs/kay/build',
650
+ 'kay/compiler',
651
+ '@kayjs/kay/compiler',
652
+ 'kay/dev',
653
+ '@kayjs/kay/dev',
654
+ 'kay/test',
655
+ '@kayjs/kay/test',
656
+ ])
657
+
512
658
  const runServerBuild = async (): Promise<void> => {
513
659
  const serverPlugin: BunPlugin = {
514
660
  name: 'kay-v2-server',
515
661
  setup(b) {
516
662
  b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
517
663
  const resolved = resolveKaySpecifier(args.path)
518
- return resolved !== undefined ? { path: resolved } : undefined
664
+ if (resolved === undefined)
665
+ return undefined
666
+ return EXTERNAL_KAY_SUBPATHS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
519
667
  })
520
668
  b.onResolve({ filter: /^@kayjs\// }, (args) => {
521
669
  try {
@@ -525,11 +673,33 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
525
673
  return undefined
526
674
  }
527
675
  })
676
+ if (outDirOutsideRoot) {
677
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
678
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || isAbsolute(args.path))
679
+ return undefined
680
+ let resolved: string | undefined
681
+ try {
682
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
683
+ }
684
+ catch {
685
+ try {
686
+ resolved = Bun.resolveSync(args.path, root)
687
+ }
688
+ catch {
689
+ return undefined
690
+ }
691
+ }
692
+ const isInsideNodeModules = resolved.includes('/node_modules/') || resolved.includes('\\node_modules\\')
693
+ const relToRoot = relative(root, resolved)
694
+ const isLocalSource = !isInsideNodeModules && !relToRoot.startsWith('..') && !isAbsolute(relToRoot)
695
+ return isLocalSource ? undefined : { path: resolved, external: true }
696
+ })
697
+ }
528
698
  b.onLoad({ filter: /\.tsx$/ }, (args) => {
529
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
530
699
  const analysis = analyses.get(args.path)
531
700
  const rawBindings = pageIslandBindings.get(args.path)
532
701
  let islandMap: Map<string, IslandBinding> | undefined
702
+ let islandKey = analysis?.isInteractive ? '1' : '0'
533
703
  if (rawBindings !== undefined) {
534
704
  islandMap = new Map()
535
705
  for (const [localName, target] of rawBindings) {
@@ -540,15 +710,24 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
540
710
  chunk,
541
711
  defaultHydrate: target.defaultHydrate,
542
712
  })
713
+ islandKey += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
543
714
  }
544
715
  }
545
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')
546
722
  const compiled = compileSsr(args.path, raw, {
547
723
  analysis,
548
724
  islands: islandMap,
549
725
  isIsland: analysis?.isInteractive,
550
726
  })
551
- return { contents: applyTransforms(compiled.code, args.path, 'server'), loader: 'tsx' }
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' }
552
731
  })
553
732
  },
554
733
  }
@@ -646,15 +825,68 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
646
825
  return false
647
826
  }
648
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
+
649
877
  const routeEntries: RouteManifestEntry[] = pageFiles.map((file) => {
650
878
  const analysis = analyses.get(file)
651
879
  const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
652
880
  const middlewareSrcs = ancestorFiles(routesDir, file, ['_middleware.ts', '_middleware.tsx'])
653
881
  const chunks = new Set<string>()
654
882
  const eagerChunks = new Set<string>()
655
- for (const lf of layoutSrcs)
883
+ const routeStyles = new Set<string>(globalPluginStyles)
884
+ for (const lf of layoutSrcs) {
656
885
  collectRouteIslands(lf, new Set(), chunks, eagerChunks)
886
+ collectRouteStyles(lf, new Set(), routeStyles)
887
+ }
657
888
  collectRouteIslands(file, new Set(), chunks, eagerChunks)
889
+ collectRouteStyles(file, new Set(), routeStyles)
658
890
 
659
891
  let usesRenderContext = collectUsesRenderContext(file)
660
892
  if (!usesRenderContext) {
@@ -678,6 +910,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
678
910
  islandHydrate: analysis?.defaultHydrate,
679
911
  islandChunks: [...chunks],
680
912
  eagerIslandChunks: [...eagerChunks],
913
+ styles: [...routeStyles],
681
914
  usesRenderContext,
682
915
  prerender: analysis?.hasPrerender || options.static === true,
683
916
  }
@@ -749,11 +982,40 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
749
982
  styleSet.add(href)
750
983
  styleUrls.push(href)
751
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
+ }
752
1005
  },
753
1006
  addHead(html) {
754
1007
  if (html !== '')
755
1008
  headTags.push(html)
756
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
+ },
757
1019
  }
758
1020
 
759
1021
  for (const plugin of plugins) {
@@ -764,6 +1026,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
764
1026
  const manifest: BuildManifest = {
765
1027
  runtimeScript,
766
1028
  styles: styleUrls,
1029
+ globalStyles,
767
1030
  ...(headTags.length > 0 ? { headTags } : {}),
768
1031
  routes: routeEntries,
769
1032
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
@@ -779,10 +1042,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
779
1042
  // Step 3: Hybrid Prerendering / Static Export (skipped in `kay dev` where routes render on-demand)
780
1043
  const shouldPrerender = options.prerender !== false || options.static === true
781
1044
  const prerenderRoutes = shouldPrerender ? routeEntries.filter(r => r.prerender) : []
782
- if (prerenderRoutes.length > 0) {
1045
+ if (prerenderRoutes.length > 0 || options.static) {
783
1046
  const { createServer } = await import('../server/index')
784
1047
  const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
785
- const prerenderDir = join(outDir, options.static ? 'static' : 'prerendered')
1048
+ const prerenderDir = options.static ? finalOutDir : join(outDir, 'prerendered')
1049
+ if (options.static)
1050
+ rmSync(finalOutDir, { recursive: true, force: true })
786
1051
  mkdirSync(prerenderDir, { recursive: true })
787
1052
 
788
1053
  const prerenderStamp = Date.now()
@@ -816,7 +1081,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
816
1081
  const absHtml = join(prerenderDir, relHtml)
817
1082
  mkdirSync(dirname(absHtml), { recursive: true })
818
1083
  writeFileSync(absHtml, html)
819
- map[u] = relative(outDir, absHtml).replace(/\\/g, '/')
1084
+ map[u] = relative(options.static ? finalOutDir : outDir, absHtml).replace(/\\/g, '/')
820
1085
  }
821
1086
  }))
822
1087
  }
@@ -828,15 +1093,17 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
828
1093
  const notFoundRes = await app.handle(new Request('http://localhost/__kay_404__'))
829
1094
  writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
830
1095
  }
831
- // Copy client assets into dist/static/_kay/... and public/ files into dist/static/...
832
- const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
833
- mkdirSync(staticAssetDir, { recursive: true })
834
- for (const rel of nonEmptyAssets) {
835
- const dst = join(staticAssetDir, rel)
836
- mkdirSync(dirname(dst), { recursive: true })
837
- writeFileSync(dst, readFileSync(join(clientDir, rel)))
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
+ }
838
1105
  }
839
- // 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
840
1107
  if (existsSync(outPublicDir)) {
841
1108
  for (const abs of walkAllFiles(outPublicDir)) {
842
1109
  const rel = relative(outPublicDir, abs).replace(/\\/g, '/')
@@ -867,8 +1134,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
867
1134
  writeFileSync(`${abs}.gz`, gz)
868
1135
  }
869
1136
  }
870
-
871
- writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
1137
+ else {
1138
+ writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
1139
+ }
872
1140
  }
873
1141
 
874
1142
  // Step 4: Single-Executable Compile (`kay build --compile [outfile]`)
@@ -886,5 +1154,161 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
886
1154
  })
887
1155
  }
888
1156
 
1157
+ if (options.analyze)
1158
+ console.log(formatBundleReport(manifest, clientDir, assetPrefix, clientMetafile))
1159
+
889
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')
890
1314
  }