@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.
@@ -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
- /** 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
@@ -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 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
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 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
+ }
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 raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
465
- 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
+ }
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)
@@ -534,6 +655,41 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
534
655
  '@kayjs/kay/test',
535
656
  ])
536
657
 
658
+ const reachesTsxCache = new Map<string, boolean>()
659
+ function reachesTsx(file: string, stack = new Set<string>()): boolean {
660
+ const cached = reachesTsxCache.get(file)
661
+ if (cached !== undefined)
662
+ return cached
663
+ if (file.endsWith('.tsx')) {
664
+ reachesTsxCache.set(file, true)
665
+ return true
666
+ }
667
+ if (stack.has(file))
668
+ return false
669
+ stack.add(file)
670
+ const analysis = analyses.get(file)
671
+ if (analysis === undefined) {
672
+ reachesTsxCache.set(file, false)
673
+ return false
674
+ }
675
+ for (const imp of analysis.imports) {
676
+ const target = resolveImportPath(file, imp.source)
677
+ if (target !== undefined && reachesTsx(target, stack)) {
678
+ reachesTsxCache.set(file, true)
679
+ return true
680
+ }
681
+ }
682
+ for (const re of analysis.reexports) {
683
+ const target = resolveImportPath(file, re.source)
684
+ if (target !== undefined && reachesTsx(target, stack)) {
685
+ reachesTsxCache.set(file, true)
686
+ return true
687
+ }
688
+ }
689
+ reachesTsxCache.set(file, false)
690
+ return false
691
+ }
692
+
537
693
  const runServerBuild = async (): Promise<void> => {
538
694
  const serverPlugin: BunPlugin = {
539
695
  name: 'kay-v2-server',
@@ -552,33 +708,33 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
552
708
  return undefined
553
709
  }
554
710
  })
555
- if (outDirOutsideRoot) {
556
- b.onResolve({ filter: /^[^./]/ }, (args) => {
557
- if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || isAbsolute(args.path))
558
- return undefined
559
- let resolved: string | undefined
711
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
712
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
713
+ return undefined
714
+ let resolved: string | undefined
715
+ try {
716
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
717
+ }
718
+ catch {
560
719
  try {
561
- resolved = Bun.resolveSync(args.path, args.resolveDir || root)
720
+ resolved = Bun.resolveSync(args.path, root)
562
721
  }
563
722
  catch {
564
- try {
565
- resolved = Bun.resolveSync(args.path, root)
566
- }
567
- catch {
568
- return undefined
569
- }
723
+ return undefined
570
724
  }
571
- const isInsideNodeModules = resolved.includes('/node_modules/') || resolved.includes('\\node_modules\\')
572
- const relToRoot = relative(root, resolved)
573
- const isLocalSource = !isInsideNodeModules && !relToRoot.startsWith('..') && !isAbsolute(relToRoot)
574
- return isLocalSource ? undefined : { path: resolved, external: true }
575
- })
576
- }
725
+ }
726
+ // Bundle any package that exports/re-exports .tsx components so Kay's SSR compiler transforms them.
727
+ if (resolved.endsWith('.tsx') || reachesTsx(resolved))
728
+ return { path: resolved }
729
+ if (outDirOutsideRoot)
730
+ return { path: resolved, external: true }
731
+ return undefined
732
+ })
577
733
  b.onLoad({ filter: /\.tsx$/ }, (args) => {
578
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
579
734
  const analysis = analyses.get(args.path)
580
735
  const rawBindings = pageIslandBindings.get(args.path)
581
736
  let islandMap: Map<string, IslandBinding> | undefined
737
+ let islandKey = analysis?.isInteractive ? '1' : '0'
582
738
  if (rawBindings !== undefined) {
583
739
  islandMap = new Map()
584
740
  for (const [localName, target] of rawBindings) {
@@ -589,15 +745,24 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
589
745
  chunk,
590
746
  defaultHydrate: target.defaultHydrate,
591
747
  })
748
+ islandKey += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
592
749
  }
593
750
  }
594
751
  }
752
+ const stamp = getFileStamp(args.path)
753
+ const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
754
+ if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === islandKey)
755
+ return { contents: cachedSsr.code, loader: 'tsx' }
756
+ const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
595
757
  const compiled = compileSsr(args.path, raw, {
596
758
  analysis,
597
759
  islands: islandMap,
598
760
  isIsland: analysis?.isInteractive,
599
761
  })
600
- return { contents: applyTransforms(compiled.code, args.path, 'server'), loader: 'tsx' }
762
+ const outCode = applyTransforms(compiled.code, args.path, 'server')
763
+ if (cache !== undefined && stamp !== undefined)
764
+ cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: islandKey, code: outCode })
765
+ return { contents: outCode, loader: 'tsx' }
601
766
  })
602
767
  },
603
768
  }
@@ -695,15 +860,68 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
695
860
  return false
696
861
  }
697
862
 
863
+ function collectRouteStyles(file: string, seen = new Set<string>(), out = new Set<string>()): void {
864
+ if (seen.has(file))
865
+ return
866
+ seen.add(file)
867
+ const analysis = analyses.get(file)
868
+ if (analysis === undefined)
869
+ return
870
+ if (analysis.isInteractive) {
871
+ const islCss = islandCssUrl.get(`${file}#default`)
872
+ if (islCss !== undefined)
873
+ out.add(islCss)
874
+ }
875
+ const bindings = pageIslandBindings.get(file)
876
+ if (bindings !== undefined) {
877
+ for (const [, target] of bindings) {
878
+ const islCss = islandCssUrl.get(`${target.file}#${target.exportName}`)
879
+ if (islCss !== undefined)
880
+ out.add(islCss)
881
+ collectRouteStyles(target.file, seen, out)
882
+ }
883
+ }
884
+ for (const imp of analysis.imports) {
885
+ const target = resolveImportPath(file, imp.source)
886
+ if (target === undefined)
887
+ continue
888
+ if (target.endsWith('.css')) {
889
+ const cssUrl = srcCssToUrl.get(target)
890
+ if (cssUrl !== undefined)
891
+ out.add(cssUrl)
892
+ }
893
+ else if (target.endsWith('.tsx') || target.endsWith('.ts')) {
894
+ collectRouteStyles(target, seen, out)
895
+ }
896
+ }
897
+ }
898
+
899
+ const globalPluginStyles: string[] = []
900
+ for (const cssFile of pluginCssFiles) {
901
+ const url = srcCssToUrl.get(cssFile)
902
+ if (url !== undefined && !globalPluginStyles.includes(url))
903
+ globalPluginStyles.push(url)
904
+ }
905
+
906
+ const rootLayoutSrc = join(routesDir, '_layout.tsx')
907
+ const globalStyleSet = new Set<string>(globalPluginStyles)
908
+ if (existsSync(rootLayoutSrc))
909
+ collectRouteStyles(rootLayoutSrc, new Set(), globalStyleSet)
910
+ const globalStyles = [...globalStyleSet]
911
+
698
912
  const routeEntries: RouteManifestEntry[] = pageFiles.map((file) => {
699
913
  const analysis = analyses.get(file)
700
914
  const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
701
915
  const middlewareSrcs = ancestorFiles(routesDir, file, ['_middleware.ts', '_middleware.tsx'])
702
916
  const chunks = new Set<string>()
703
917
  const eagerChunks = new Set<string>()
704
- for (const lf of layoutSrcs)
918
+ const routeStyles = new Set<string>(globalPluginStyles)
919
+ for (const lf of layoutSrcs) {
705
920
  collectRouteIslands(lf, new Set(), chunks, eagerChunks)
921
+ collectRouteStyles(lf, new Set(), routeStyles)
922
+ }
706
923
  collectRouteIslands(file, new Set(), chunks, eagerChunks)
924
+ collectRouteStyles(file, new Set(), routeStyles)
707
925
 
708
926
  let usesRenderContext = collectUsesRenderContext(file)
709
927
  if (!usesRenderContext) {
@@ -727,6 +945,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
727
945
  islandHydrate: analysis?.defaultHydrate,
728
946
  islandChunks: [...chunks],
729
947
  eagerIslandChunks: [...eagerChunks],
948
+ styles: [...routeStyles],
730
949
  usesRenderContext,
731
950
  prerender: analysis?.hasPrerender || options.static === true,
732
951
  }
@@ -798,11 +1017,40 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
798
1017
  styleSet.add(href)
799
1018
  styleUrls.push(href)
800
1019
  }
1020
+ if (!globalStyleSet.has(href)) {
1021
+ globalStyleSet.add(href)
1022
+ globalStyles.push(href)
1023
+ }
1024
+ for (const r of routeEntries) {
1025
+ if (r.styles !== undefined && !r.styles.includes(href))
1026
+ r.styles.push(href)
1027
+ }
1028
+ },
1029
+ addRouteStyle(routePath, href) {
1030
+ if (!styleSet.has(href)) {
1031
+ styleSet.add(href)
1032
+ styleUrls.push(href)
1033
+ }
1034
+ const route = routeEntries.find(r => r.path === routePath)
1035
+ if (route !== undefined) {
1036
+ route.styles ??= [...globalStyles]
1037
+ if (!route.styles.includes(href))
1038
+ route.styles.push(href)
1039
+ }
801
1040
  },
802
1041
  addHead(html) {
803
1042
  if (html !== '')
804
1043
  headTags.push(html)
805
1044
  },
1045
+ addRouteHead(routePath, html) {
1046
+ if (html === '')
1047
+ return
1048
+ const route = routeEntries.find(r => r.path === routePath)
1049
+ if (route !== undefined) {
1050
+ route.headTags ??= []
1051
+ route.headTags.push(html)
1052
+ }
1053
+ },
806
1054
  }
807
1055
 
808
1056
  for (const plugin of plugins) {
@@ -813,6 +1061,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
813
1061
  const manifest: BuildManifest = {
814
1062
  runtimeScript,
815
1063
  styles: styleUrls,
1064
+ globalStyles,
816
1065
  ...(headTags.length > 0 ? { headTags } : {}),
817
1066
  routes: routeEntries,
818
1067
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
@@ -828,10 +1077,12 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
828
1077
  // Step 3: Hybrid Prerendering / Static Export (skipped in `kay dev` where routes render on-demand)
829
1078
  const shouldPrerender = options.prerender !== false || options.static === true
830
1079
  const prerenderRoutes = shouldPrerender ? routeEntries.filter(r => r.prerender) : []
831
- if (prerenderRoutes.length > 0) {
1080
+ if (prerenderRoutes.length > 0 || options.static) {
832
1081
  const { createServer } = await import('../server/index')
833
1082
  const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
834
- const prerenderDir = join(outDir, options.static ? 'static' : 'prerendered')
1083
+ const prerenderDir = options.static ? finalOutDir : join(outDir, 'prerendered')
1084
+ if (options.static)
1085
+ rmSync(finalOutDir, { recursive: true, force: true })
835
1086
  mkdirSync(prerenderDir, { recursive: true })
836
1087
 
837
1088
  const prerenderStamp = Date.now()
@@ -865,7 +1116,7 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
865
1116
  const absHtml = join(prerenderDir, relHtml)
866
1117
  mkdirSync(dirname(absHtml), { recursive: true })
867
1118
  writeFileSync(absHtml, html)
868
- map[u] = relative(outDir, absHtml).replace(/\\/g, '/')
1119
+ map[u] = relative(options.static ? finalOutDir : outDir, absHtml).replace(/\\/g, '/')
869
1120
  }
870
1121
  }))
871
1122
  }
@@ -877,15 +1128,17 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
877
1128
  const notFoundRes = await app.handle(new Request('http://localhost/__kay_404__'))
878
1129
  writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
879
1130
  }
880
- // Copy client assets into dist/static/_kay/... and public/ files into dist/static/...
881
- const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
882
- mkdirSync(staticAssetDir, { recursive: true })
883
- for (const rel of nonEmptyAssets) {
884
- const dst = join(staticAssetDir, rel)
885
- mkdirSync(dirname(dst), { recursive: true })
886
- writeFileSync(dst, readFileSync(join(clientDir, rel)))
1131
+ // Copy client assets into dist/_kay/... and public/ files into dist/...
1132
+ if (nonEmptyAssets.length > 0) {
1133
+ const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
1134
+ mkdirSync(staticAssetDir, { recursive: true })
1135
+ for (const rel of nonEmptyAssets) {
1136
+ const dst = join(staticAssetDir, rel)
1137
+ mkdirSync(dirname(dst), { recursive: true })
1138
+ writeFileSync(dst, readFileSync(join(clientDir, rel)))
1139
+ }
887
1140
  }
888
- // Re-scan outPublicDir so any assets emitted during prerender (e.g. OG share cards) are included in --static
1141
+ // Re-scan outPublicDir so any assets emitted during prerender (e.g. OG share cards, optimized MD images) are included in --static
889
1142
  if (existsSync(outPublicDir)) {
890
1143
  for (const abs of walkAllFiles(outPublicDir)) {
891
1144
  const rel = relative(outPublicDir, abs).replace(/\\/g, '/')
@@ -916,8 +1169,9 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
916
1169
  writeFileSync(`${abs}.gz`, gz)
917
1170
  }
918
1171
  }
919
-
920
- writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
1172
+ else {
1173
+ writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
1174
+ }
921
1175
  }
922
1176
 
923
1177
  // Step 4: Single-Executable Compile (`kay build --compile [outfile]`)
@@ -932,8 +1186,165 @@ export async function build(options: BuildOptions): Promise<BuildManifest> {
932
1186
  outfile,
933
1187
  kaySrcRoot: KAY_SRC_ROOT,
934
1188
  resolveKaySpecifier,
1189
+ bunPlugins: pluginBunPlugins,
935
1190
  })
936
1191
  }
937
1192
 
1193
+ if (options.analyze)
1194
+ console.log(formatBundleReport(manifest, clientDir, assetPrefix, clientMetafile))
1195
+
938
1196
  return manifest
1197
+ }
1198
+ }
1199
+
1200
+ export interface RouteBundleMetrics {
1201
+ path: string
1202
+ jsRaw: number
1203
+ jsGzip: number
1204
+ cssRaw: number
1205
+ cssGzip: number
1206
+ jsFiles: number
1207
+ cssFiles: number
1208
+ }
1209
+
1210
+ export function analyzeBundleWeights(
1211
+ manifest: BuildManifest,
1212
+ clientDir: string,
1213
+ assetPrefix = '/_kay',
1214
+ metafile?: Bun.BuildOutput['metafile'],
1215
+ ): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
1216
+ const prefix = `${assetPrefix.replace(/\/$/, '')}/`
1217
+ const sizeCache = new Map<string, { raw: number, gzip: number }>()
1218
+
1219
+ const getSize = (url: string): { raw: number, gzip: number } => {
1220
+ const cached = sizeCache.get(url)
1221
+ if (cached !== undefined)
1222
+ return cached
1223
+ if (!url.startsWith(prefix))
1224
+ return { raw: 0, gzip: 0 }
1225
+ const abs = join(clientDir, url.slice(prefix.length))
1226
+ if (!existsSync(abs))
1227
+ return { raw: 0, gzip: 0 }
1228
+ const buf = readFileSync(abs)
1229
+ const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
1230
+ sizeCache.set(url, entry)
1231
+ return entry
1232
+ }
1233
+
1234
+ // Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
1235
+ const jsDeps = new Map<string, string[]>()
1236
+ const moduleBytes = new Map<string, number>()
1237
+ if (metafile !== undefined) {
1238
+ for (const [outKey, info] of Object.entries(metafile.outputs)) {
1239
+ const rel = outKey.replace(/^\.\//, '')
1240
+ const url = `${prefix}${rel}`
1241
+ if (rel.endsWith('.js')) {
1242
+ const deps: string[] = []
1243
+ for (const imp of info.imports ?? []) {
1244
+ if (imp.kind === 'import-statement')
1245
+ deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
1246
+ }
1247
+ jsDeps.set(url, deps)
1248
+ }
1249
+ for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
1250
+ moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
1251
+ }
1252
+ }
1253
+
1254
+ const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
1255
+ const seen = new Set<string>()
1256
+ const stack = [...urls]
1257
+ while (stack.length > 0) {
1258
+ const cur = stack.pop()!
1259
+ if (seen.has(cur))
1260
+ continue
1261
+ seen.add(cur)
1262
+ for (const dep of jsDeps.get(cur) ?? [])
1263
+ stack.push(dep)
1264
+ }
1265
+ return seen
1266
+ }
1267
+
1268
+ const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
1269
+ const eagerJsRoots: string[] = []
1270
+ if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
1271
+ eagerJsRoots.push(manifest.runtimeScript)
1272
+ for (const c of r.eagerIslandChunks ?? r.islandChunks)
1273
+ eagerJsRoots.push(c)
1274
+
1275
+ const jsSet = collectTransitiveJs(eagerJsRoots)
1276
+ let jsRaw = 0
1277
+ let jsGzip = 0
1278
+ for (const u of jsSet) {
1279
+ const s = getSize(u)
1280
+ jsRaw += s.raw
1281
+ jsGzip += s.gzip
1282
+ }
1283
+
1284
+ const cssList = r.styles ?? manifest.styles
1285
+ let cssRaw = 0
1286
+ let cssGzip = 0
1287
+ for (const u of cssList) {
1288
+ const s = getSize(u)
1289
+ cssRaw += s.raw
1290
+ cssGzip += s.gzip
1291
+ }
1292
+
1293
+ return {
1294
+ path: r.path,
1295
+ jsRaw,
1296
+ jsGzip,
1297
+ cssRaw,
1298
+ cssGzip,
1299
+ jsFiles: jsSet.size,
1300
+ cssFiles: cssList.length,
1301
+ }
1302
+ })
1303
+
1304
+ let totalJsGzip = 0
1305
+ let totalCssGzip = 0
1306
+ for (const rel of manifest.assets) {
1307
+ const s = getSize(`${prefix}${rel}`)
1308
+ if (rel.endsWith('.js'))
1309
+ totalJsGzip += s.gzip
1310
+ else if (rel.endsWith('.css'))
1311
+ totalCssGzip += s.gzip
1312
+ }
1313
+
1314
+ const topModules = [...moduleBytes.entries()]
1315
+ .map(([path, bytes]) => ({ path, bytes }))
1316
+ .sort((a, b) => b.bytes - a.bytes)
1317
+ .slice(0, 10)
1318
+
1319
+ return { routes, totalJsGzip, totalCssGzip, topModules }
1320
+ }
1321
+
1322
+ export function formatBundleReport(
1323
+ manifest: BuildManifest,
1324
+ clientDir: string,
1325
+ assetPrefix = '/_kay',
1326
+ metafile?: Bun.BuildOutput['metafile'],
1327
+ ): string {
1328
+ const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
1329
+ const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
1330
+ const lines = [
1331
+ '\n=== KAY BUNDLE WEIGHT REPORT ===',
1332
+ `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
1333
+ '',
1334
+ 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Files'.padStart(10),
1335
+ ]
1336
+ for (const r of report.routes) {
1337
+ lines.push(
1338
+ r.path.padEnd(28)
1339
+ + kb(r.jsGzip).padStart(16)
1340
+ + kb(r.cssGzip).padStart(14)
1341
+ + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
1342
+ )
1343
+ }
1344
+ if (report.topModules.length > 0) {
1345
+ lines.push('', 'Top modules (minified output bytes):')
1346
+ for (const m of report.topModules.slice(0, 8))
1347
+ lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
1348
+ }
1349
+ return lines.join('\n')
939
1350
  }