@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.1

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.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +20 -11
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +231 -1296
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +298 -79
  18. package/src/cli/new.ts +67 -35
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +822 -629
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +390 -324
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +291 -76
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +157 -84
  30. package/src/dom/index.ts +154 -33
  31. package/src/dom/island.ts +117 -39
  32. package/src/dom/loop.ts +34 -21
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +120 -17
  37. package/src/reactivity/index.ts +250 -157
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +37 -12
  40. package/src/server/action.ts +217 -74
  41. package/src/server/compress.ts +155 -56
  42. package/src/server/cookies.ts +59 -22
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +201 -33
  45. package/src/server/index.ts +964 -737
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +27 -8
  48. package/src/server/security.ts +87 -39
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +96 -10
  52. package/src/ssr/index.ts +225 -56
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -0
  55. package/src/unrenderable.ts +35 -0
@@ -3,31 +3,35 @@
3
3
  // - Builds client (1 pass, minimal runtime + island chunks + action stubs) and server (1 pass)
4
4
  // - Supports hybrid prerender, --static export, and --compile single-executable builds
5
5
 
6
- import type { BunPlugin } from 'bun'
7
- import type { IslandBinding, ModuleAnalysis } from '../compiler/index'
8
- import type { BuildPluginContext, KayPlugin } from '../plugins/index'
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
- import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
12
- import { analyzeModule, compileDom, compileSsr } from '../compiler/index'
13
- import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
14
- import { loadConfig } from '../plugins/index'
6
+ import type { AppRuntimeContext } from '../plugins/context'
7
+ import type { KayPlugin } from '../plugins/index'
8
+ import type { BuildCache } from './graph'
9
+ import type { ActionsByFile } from './islands'
10
+ import type { BuildManifest } from './manifest'
11
+ import type { PublicFiles } from './plugin-host'
12
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
13
+ import { basename, dirname, join, relative, resolve } from 'node:path'
14
+ import { createAppContext, loadConfig, runWithAppContext } from '../plugins/index'
15
15
  import { actionHash } from '../server/action'
16
+ import { buildClient, buildServer, pluginBunPlugins, standaloneCssFiles } from './bundle'
16
17
  import { compileExecutable } from './compile'
17
-
18
- export interface BuildCache {
19
- analyses: Map<string, { mtimeMs: number, size: number, code: string, analysis: ModuleAnalysis }>
20
- domCompiled: Map<string, { mtimeMs: number, size: number, code: string }>
21
- ssrCompiled: Map<string, { mtimeMs: number, size: number, key: string, code: string }>
22
- }
23
-
24
- export function createBuildCache(): BuildCache {
25
- return {
26
- analyses: new Map(),
27
- domCompiled: new Map(),
28
- ssrCompiled: new Map(),
29
- }
30
- }
18
+ import { assertSafeOutDir, fileSize, relPosix, walkAllFiles, walkRoutes } from './files'
19
+ import { ModuleGraph } from './graph'
20
+ import { planIslands } from './islands'
21
+ import { buildActionEntries, buildRouteEntries } from './manifest'
22
+ import { createPluginHost, createPublicFiles } from './plugin-host'
23
+ import { prerender } from './prerender'
24
+ import { formatBundleReport } from './report'
25
+ import { KAY_SRC_ROOT, resolveKaySpecifier } from './resolve'
26
+ import { assertNoRouteConflicts, hasRouteHandlerExport, routeExportProblem, SPECIAL_ROUTE_FILES } from './routes'
27
+ import { exportStatic } from './static'
28
+
29
+ export type { BuildCache } from './graph'
30
+ export { createBuildCache } from './graph'
31
+ export type { ActionManifestEntry, BuildManifest, RouteManifestEntry } from './manifest'
32
+ export { analyzeBundleWeights, formatBundleReport } from './report'
33
+ export type { RouteBundleMetrics } from './report'
34
+ export { resolveKaySpecifier } from './resolve'
31
35
 
32
36
  export interface BuildOptions {
33
37
  root: string
@@ -49,1363 +53,294 @@ export interface BuildOptions {
49
53
  copyPublic?: boolean | undefined
50
54
  /** Compile into a single standalone executable at this path (or true -> dist/server-bin). */
51
55
  compile?: string | boolean | undefined
56
+ /** Run in development mode (keeps NODE_ENV as development and skips production client asset precompression; auto-detected via KAY_DEV=1). */
57
+ dev?: boolean | undefined
52
58
  }
53
59
 
54
- export interface ActionManifestEntry {
55
- url: string
56
- file: string
57
- exportName: string
58
- /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
59
- middlewares: string[]
60
- }
61
-
62
- export interface RouteManifestEntry {
63
- path: string
64
- file: string
65
- layouts: string[]
66
- middlewares: string[]
67
- hasLoad?: boolean | undefined
68
- isIsland?: boolean | undefined
69
- islandChunk?: string | undefined
70
- islandHydrate?: string | undefined
71
- islandChunks: string[]
72
- eagerIslandChunks?: string[] | undefined
73
- /** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
74
- styles?: string[] | undefined
75
- /** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
76
- headTags?: string[] | undefined
77
- usesRenderContext?: boolean | undefined
78
- prerender?: boolean | undefined
79
- prerendered?: Record<string, string> | undefined
80
- }
81
-
82
- export interface BuildManifest {
83
- runtimeScript: string | undefined
84
- styles: string[]
85
- /** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
86
- globalStyles?: string[] | undefined
87
- headTags?: string[] | undefined
88
- routes: RouteManifestEntry[]
89
- errorFile?: string | undefined
90
- notFoundFile?: string | undefined
91
- actions: ActionManifestEntry[]
92
- islands: Record<string, string>
93
- assets: string[]
94
- publicFiles: string[]
95
- }
96
-
97
- const KAY_SRC_ROOT = resolve(import.meta.dir, '..')
98
-
99
- export function resolveKaySpecifier(specifier: string): string | undefined {
100
- if (specifier === 'kay' || specifier === '@kayjs/kay')
101
- return join(KAY_SRC_ROOT, 'index.ts')
102
- if (specifier === 'kay/dom' || specifier === '@kayjs/kay/dom')
103
- return join(KAY_SRC_ROOT, 'dom/index.ts')
104
- if (specifier === 'kay/dom-extras' || specifier === '@kayjs/kay/dom-extras')
105
- return join(KAY_SRC_ROOT, 'dom/extras.ts')
106
- if (specifier === 'kay/dom-loop' || specifier === '@kayjs/kay/dom-loop')
107
- return join(KAY_SRC_ROOT, 'dom/loop.ts')
108
- if (specifier === 'kay/action' || specifier === '@kayjs/kay/action')
109
- return join(KAY_SRC_ROOT, 'dom/action.ts')
110
- if (specifier === 'kay/island' || specifier === '@kayjs/kay/island')
111
- return join(KAY_SRC_ROOT, 'dom/island.ts')
112
- if (specifier === 'kay/ssr' || specifier === '@kayjs/kay/ssr')
113
- return join(KAY_SRC_ROOT, 'ssr/index.ts')
114
- if (specifier === 'kay/server' || specifier === '@kayjs/kay/server')
115
- return join(KAY_SRC_ROOT, 'server/index.ts')
116
- if (specifier === 'kay/compiler' || specifier === '@kayjs/kay/compiler')
117
- return join(KAY_SRC_ROOT, 'compiler/index.ts')
118
- if (specifier === 'kay/build' || specifier === '@kayjs/kay/build')
119
- return join(KAY_SRC_ROOT, 'build/index.ts')
120
- if (specifier === 'kay/dev' || specifier === '@kayjs/kay/dev')
121
- return join(KAY_SRC_ROOT, 'dev/index.ts')
122
- if (specifier === 'kay/test' || specifier === '@kayjs/kay/test')
123
- return join(KAY_SRC_ROOT, 'test/index.ts')
124
- if (
125
- specifier === 'kay/jsx-runtime'
126
- || specifier === 'kay/jsx-dev-runtime'
127
- || specifier === '@kayjs/kay/jsx-runtime'
128
- || specifier === '@kayjs/kay/jsx-dev-runtime'
129
- ) {
130
- return join(KAY_SRC_ROOT, 'jsx-runtime.ts')
131
- }
132
- return undefined
133
- }
134
-
135
- function resolveImportPath(fromFile: string, specifier: string): string | undefined {
136
- if (specifier.startsWith('.')) {
137
- const base = resolve(dirname(fromFile), specifier)
138
- const candidates = [base, `${base}.tsx`, `${base}.ts`, join(base, 'index.tsx'), join(base, 'index.ts')]
139
- for (const c of candidates) {
140
- if (existsSync(c))
141
- return c
142
- }
143
- return undefined
144
- }
145
- if (
146
- specifier === 'kay'
147
- || specifier.startsWith('kay/')
148
- || specifier.startsWith('@kayjs/kay')
149
- || specifier.startsWith('node:')
150
- || specifier.startsWith('bun')
151
- || specifier.startsWith('~')
152
- ) {
153
- return undefined
154
- }
155
- try {
156
- const resolved = Bun.resolveSync(specifier, dirname(fromFile))
157
- return resolved.endsWith('.tsx') || resolved.endsWith('.ts') ? resolved : undefined
158
- }
159
- catch {
160
- return undefined
161
- }
162
- }
163
-
164
- function walkRoutes(dir: string, out: string[] = []): string[] {
165
- if (!existsSync(dir))
166
- return out
167
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
168
- const full = join(dir, entry.name)
169
- if (entry.isDirectory())
170
- walkRoutes(full, out)
171
- else if (entry.name.endsWith('.tsx') || entry.name.endsWith('.ts'))
172
- out.push(full)
173
- }
174
- return out
175
- }
176
-
177
- function walkAllFiles(dir: string, out: string[] = []): string[] {
178
- if (!existsSync(dir))
179
- return out
180
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
181
- const full = join(dir, entry.name)
182
- if (entry.isDirectory())
183
- walkAllFiles(full, out)
184
- else if (entry.isFile())
185
- out.push(full)
186
- }
187
- return out
188
- }
189
-
190
- function fileToRoutePath(routesDir: string, file: string): string {
191
- const rel = relative(routesDir, file).replace(/\\/g, '/').replace(/\.(tsx|ts)$/, '')
192
- if (rel === 'index')
193
- return '/'
194
- const clean = rel.endsWith('/index') ? rel.slice(0, -'/index'.length) : rel
195
- const pattern = clean
196
- .replace(/\[\.\.\.([^\]]+)\]/g, '*$1')
197
- .replace(/\[([^\]]+)\]/g, ':$1')
198
- return `/${pattern}`
60
+ /** Everything one build run needs, resolved once from the options and `kay.config.ts`. */
61
+ interface BuildRun {
62
+ options: BuildOptions
63
+ root: string
64
+ plugins: KayPlugin[]
65
+ routesDir: string
66
+ publicDir: string
67
+ finalOutDir: string
68
+ /** Where the build writes: `finalOutDir`, or a stage folder for a static export. */
69
+ outDir: string
70
+ staticStageDir: string | undefined
71
+ stageSuffix: string
72
+ assetPrefix: string
73
+ minify: boolean
74
+ isDev: boolean
75
+ appCtx: AppRuntimeContext
76
+ publicFiles: PublicFiles
199
77
  }
200
78
 
201
- /** Finds all ancestor files named `specialName` from routesDir down to dirname(routeFile), outermost first. */
202
- function ancestorFiles(routesDir: string, routeFile: string, specialNames: string[]): string[] {
203
- const result: string[] = []
204
- const relDir = relative(routesDir, dirname(routeFile))
205
- const parts = relDir === '' ? [] : relDir.split(/[/\\]/)
206
- let cur = routesDir
207
-
208
- for (let i = 0; i <= parts.length; i++) {
209
- if (i > 0)
210
- cur = join(cur, parts[i - 1]!)
211
- for (const name of specialNames) {
212
- const candidate = join(cur, name)
213
- if (existsSync(candidate))
214
- result.push(candidate)
215
- }
79
+ export async function build(options: BuildOptions): Promise<BuildManifest> {
80
+ if (options.static && options.compile) {
81
+ throw new Error('kay build: --static and --compile cannot be used together (static export produces HTML/assets without a server binary).')
216
82
  }
217
- return result
218
- }
219
-
220
- interface IslandTarget {
221
- id: string
222
- file: string
223
- exportName: string
224
- defaultHydrate: string | undefined
225
- }
226
-
227
- function clientLeakError(leaks: Set<string>): Error {
228
- return new Error(`kay build (client): server code is reachable from an island:\n${[...leaks].map(l => ` ${l}`).join('\n')}\nMove server logic to a server action or async server component.`)
229
- }
230
83
 
231
- export async function build(options: BuildOptions): Promise<BuildManifest> {
232
84
  const root = resolve(options.root)
233
85
  const fileConfig = await loadConfig(root)
234
- const plugins: KayPlugin[] = options.plugins ?? fileConfig.plugins ?? []
235
86
  const routesDir = resolve(root, options.routesDir ?? fileConfig.routesDir ?? 'src/routes')
236
87
  const finalOutDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
88
+ const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
89
+
90
+ assertSafeOutDir(root, finalOutDir, routesDir, publicDir)
91
+
92
+ const isDev = options.dev ?? (process.env.KAY_DEV === '1')
237
93
  const cacheBaseDir = join(root, '.kay-cache')
238
94
  const cacheExisted = existsSync(cacheBaseDir)
239
- const outDir = options.static
240
- ? join(cacheBaseDir, `.static-stage-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
241
- : finalOutDir
242
- const publicDir = resolve(root, options.publicDir ?? fileConfig.publicDir ?? 'public')
243
- const clientDir = join(outDir, 'client')
244
- const serverDir = join(outDir, 'server')
95
+ const stageSuffix = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
96
+ const outDir = options.static ? join(cacheBaseDir, `.static-stage-${stageSuffix}`) : finalOutDir
97
+ const staticStageDir = options.static ? join(dirname(finalOutDir), `.${basename(finalOutDir)}.stage-${stageSuffix}`) : undefined
245
98
  const assetPrefix = (options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay').replace(/\/$/, '')
246
- const minify = options.minify ?? true
99
+ const publicFiles = createPublicFiles()
100
+ const appCtx = createAppContext({
101
+ root,
102
+ outDir,
103
+ publicDir: join(outDir, 'public'),
104
+ assetPrefix,
105
+ dev: isDev,
106
+ onRegisterPublicFile: publicFiles.register,
107
+ })
108
+
109
+ const prevNodeEnv = process.env.NODE_ENV
110
+ if (!isDev)
111
+ process.env.NODE_ENV ??= 'production'
247
112
 
248
113
  try {
249
- return await buildInternal()
114
+ return await runWithAppContext(appCtx, () => runBuild({
115
+ options,
116
+ root,
117
+ plugins: options.plugins ?? fileConfig.plugins ?? [],
118
+ routesDir,
119
+ publicDir,
120
+ finalOutDir,
121
+ outDir,
122
+ staticStageDir,
123
+ stageSuffix,
124
+ assetPrefix,
125
+ minify: options.minify ?? true,
126
+ isDev,
127
+ appCtx,
128
+ publicFiles,
129
+ }))
250
130
  }
251
131
  finally {
132
+ if (!isDev) {
133
+ if (prevNodeEnv !== undefined)
134
+ process.env.NODE_ENV = prevNodeEnv
135
+ else
136
+ delete process.env.NODE_ENV
137
+ }
252
138
  if (options.static) {
139
+ if (staticStageDir !== undefined)
140
+ rmSync(staticStageDir, { recursive: true, force: true })
253
141
  rmSync(outDir, { recursive: true, force: true })
254
142
  if (!cacheExisted && existsSync(cacheBaseDir) && readdirSync(cacheBaseDir).length === 0)
255
143
  rmSync(cacheBaseDir, { recursive: true, force: true })
256
144
  }
257
145
  }
146
+ }
258
147
 
259
- async function buildInternal(): Promise<BuildManifest> {
260
-
261
- const pluginBunPlugins = plugins.flatMap((p) => {
262
- const bp = p.bunPlugins
263
- if (typeof bp === 'function')
264
- return bp({ root, assetPrefix, minify })
265
- return bp ?? []
266
- })
267
- const pluginClientEntries = plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
268
- const pluginCssFiles = plugins
269
- .flatMap(p => p.css ?? [])
270
- .map(c => resolve(root, c))
271
- .filter(c => existsSync(c))
272
-
273
- function applyTransforms(code: string, id: string, target: 'server' | 'client'): string {
274
- let cur = code
275
- for (let i = 0; i < plugins.length; i++) {
276
- const fn = plugins[i]!.transform
277
- if (fn !== undefined) {
278
- const next = fn(cur, id, target)
279
- if (typeof next === 'string')
280
- cur = next
281
- }
282
- }
283
- return cur
284
- }
285
-
286
- rmSync(outDir, { recursive: true, force: true })
287
- mkdirSync(clientDir, { recursive: true })
288
- mkdirSync(serverDir, { recursive: true })
148
+ async function runBuild(run: BuildRun): Promise<BuildManifest> {
149
+ const { options, root, plugins, routesDir, outDir, assetPrefix, isDev, publicFiles } = run
150
+ const clientDir = join(outDir, 'client')
151
+ const serverDir = join(outDir, 'server')
152
+ const isStatic = options.static === true
289
153
 
290
154
  const allRouteFiles = walkRoutes(routesDir).sort()
291
- const specialFiles = allRouteFiles.filter(f => basename(f).startsWith('_'))
292
- const pageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
155
+ const specialFiles = allRouteFiles.filter(f => SPECIAL_ROUTE_FILES.has(basename(f)))
156
+ const candidatePageFiles = allRouteFiles.filter(f => !basename(f).startsWith('_'))
293
157
  const errorSrc = join(routesDir, '_error.tsx')
294
158
  const notFoundSrc = join(routesDir, '_404.tsx')
295
159
  const hasErrorFile = existsSync(errorSrc)
296
160
  const hasNotFoundFile = existsSync(notFoundSrc)
297
161
 
298
- // Analyze every reachable .tsx and .ts file once (reusing BuildCache across `kay dev` rebuilds when mtime+size match)
299
- const cache = options.cache
300
- const analyses = new Map<string, ModuleAnalysis>()
301
- const sources = new Map<string, string>()
302
- const fileStamps = new Map<string, { mtimeMs: number, size: number }>()
303
-
304
- function getFileStamp(file: string): { mtimeMs: number, size: number } | undefined {
305
- const existing = fileStamps.get(file)
306
- if (existing !== undefined)
307
- return existing
308
- if (cache === undefined)
309
- return undefined
310
- try {
311
- const st = statSync(file)
312
- const stamp = { mtimeMs: st.mtimeMs, size: st.size }
313
- fileStamps.set(file, stamp)
314
- return stamp
315
- }
316
- catch {
317
- return undefined
318
- }
319
- }
320
-
321
- function loadAnalysis(file: string): ModuleAnalysis {
322
- const existing = analyses.get(file)
323
- if (existing !== undefined)
324
- return existing
325
- const stamp = getFileStamp(file)
326
- const cached = stamp !== undefined ? cache?.analyses.get(file) : undefined
327
- let code: string
328
- let analysis: ModuleAnalysis
329
- if (cached !== undefined && cached.mtimeMs === stamp!.mtimeMs && cached.size === stamp!.size) {
330
- code = cached.code
331
- analysis = cached.analysis
332
- }
333
- else {
334
- code = readFileSync(file, 'utf8')
335
- analysis = analyzeModule(file, code)
336
- if (cache !== undefined && stamp !== undefined)
337
- cache.analyses.set(file, { mtimeMs: stamp.mtimeMs, size: stamp.size, code, analysis })
338
- }
339
- sources.set(file, code)
340
- analyses.set(file, analysis)
341
- for (const imp of analysis.imports) {
342
- const target = resolveImportPath(file, imp.source)
343
- if (target !== undefined && (target.endsWith('.tsx') || target.endsWith('.ts')))
344
- loadAnalysis(target)
345
- }
346
- for (const re of analysis.reexports) {
347
- const target = resolveImportPath(file, re.source)
348
- if (target !== undefined && (target.endsWith('.tsx') || target.endsWith('.ts')))
349
- loadAnalysis(target)
350
- }
351
- return analysis
162
+ // Every reachable .ts/.tsx file is analyzed & validated BEFORE wiping outDir, so build errors keep the last working dist/.
163
+ const graph = new ModuleGraph(options.cache)
164
+ for (const f of [...specialFiles, ...candidatePageFiles])
165
+ graph.load(f)
166
+ for (const analysis of graph.analyses.values()) {
167
+ for (const warning of analysis.warnings)
168
+ console.warn(warning)
352
169
  }
353
170
 
354
- function resolveExportTarget(file: string, exportName: string, depth = 0): { file: string, exportName: string } {
355
- if (depth > 8)
356
- return { file, exportName }
357
- const analysis = loadAnalysis(file)
358
- const re = analysis.reexports.find(r => r.exported === exportName)
359
- if (re !== undefined) {
360
- const next = resolveImportPath(file, re.source)
361
- if (next !== undefined)
362
- return resolveExportTarget(next, re.local, depth + 1)
363
- }
364
- return { file, exportName }
171
+ // Skip helper files inside routes/ that export neither a default component nor an HTTP method handler
172
+ for (const f of candidatePageFiles) {
173
+ const problem = routeExportProblem(graph.analyses.get(f)!, relPosix(root, f))
174
+ if (problem !== undefined)
175
+ throw new Error(`kay build: ${problem}`)
365
176
  }
177
+ const pageFiles = candidatePageFiles.filter(f => hasRouteHandlerExport(graph.analyses.get(f)!))
178
+ assertNoRouteConflicts(root, routesDir, pageFiles)
366
179
 
367
- for (const f of allRouteFiles)
368
- loadAnalysis(f)
369
-
370
- // Discover all server actions (keyed by source file -> exportName -> action URL)
371
- const actionsByFile = new Map<string, { exportName: string, url: string }[]>()
372
- for (const [file, analysis] of analyses) {
180
+ // Server actions, keyed by source file
181
+ const actionsByFile: ActionsByFile = new Map()
182
+ for (const [file, analysis] of graph.analyses) {
373
183
  if (analysis.exportedActions.length > 0) {
374
- const rel = relative(root, file).replace(/\\/g, '/')
375
- actionsByFile.set(
376
- file,
377
- analysis.exportedActions.map(exportName => ({
378
- exportName,
379
- url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
380
- })),
381
- )
184
+ const rel = relPosix(root, file)
185
+ actionsByFile.set(file, analysis.exportedActions.map(exportName => ({
186
+ exportName,
187
+ url: `${assetPrefix}/action/${actionHash(rel, exportName)}`,
188
+ })))
382
189
  }
383
190
  }
384
191
 
385
- // Discover all island roots referenced from static pages/layouts/errors (or sync interactive pages themselves)
386
- const islandTargets = new Map<string, IslandTarget>()
387
- const islandIds = new Set<string>()
388
- const pageIslandBindings = new Map<string, Map<string, IslandTarget>>()
389
-
390
- function registerIsland(file: string, exportName: string): IslandTarget {
391
- const key = `${file}#${exportName}`
392
- const existing = islandTargets.get(key)
393
- if (existing !== undefined)
394
- return existing
395
- const analysis = loadAnalysis(file)
396
- const baseName = basename(file, extname(file)).toLowerCase()
397
- const expLower = exportName.toLowerCase()
398
- let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
399
- // The id names the entry file and the chunk: two islands sharing a basename keep it readable and add a hash of their path.
400
- if (islandIds.has(id))
401
- id = `${id}-${Bun.hash(relative(root, key)).toString(36).slice(0, 6)}`
402
- islandIds.add(id)
403
- const target: IslandTarget = { id, file, exportName, defaultHydrate: analysis.defaultHydrate }
404
- islandTargets.set(key, target)
405
- return target
406
- }
407
-
408
- for (const [file, analysis] of analyses) {
409
- if (!file.endsWith('.tsx'))
410
- continue
411
- if (analysis.isInteractive) {
412
- if (pageFiles.includes(file))
413
- registerIsland(file, 'default')
414
- continue
415
- }
416
-
417
- const bindings = new Map<string, IslandTarget>()
418
- for (const imp of analysis.imports) {
419
- const resolved = resolveImportPath(file, imp.source)
420
- if (resolved === undefined || (!resolved.endsWith('.tsx') && !resolved.endsWith('.ts')))
421
- continue
422
- for (const spec of imp.specifiers) {
423
- if (spec.imported === '*')
424
- continue
425
- const target = resolveExportTarget(resolved, spec.imported)
426
- if (!target.file.endsWith('.tsx'))
427
- continue
428
- const targetAnalysis = loadAnalysis(target.file)
429
- if (targetAnalysis.isInteractive)
430
- bindings.set(spec.local, registerIsland(target.file, target.exportName))
431
- }
432
- }
433
- if (bindings.size > 0)
434
- pageIslandBindings.set(file, bindings)
435
- }
436
-
437
- // Collect component/page CSS & CSS Module imports from static modules (island CSS is bundled via island entrypoints)
438
- const islandCssFiles = new Set<string>()
439
- const collectIslandCss = (file: string, seen = new Set<string>()) => {
440
- if (seen.has(file))
441
- return
442
- seen.add(file)
443
- const analysis = analyses.get(file)
444
- if (analysis === undefined)
445
- return
446
- for (const imp of analysis.imports) {
447
- const target = resolveImportPath(file, imp.source)
448
- if (target === undefined)
449
- continue
450
- if (target.endsWith('.css'))
451
- islandCssFiles.add(target)
452
- else if (target.endsWith('.tsx') || target.endsWith('.ts'))
453
- collectIslandCss(target, seen)
454
- }
455
- }
456
- for (const [, target] of islandTargets)
457
- collectIslandCss(target.file)
458
-
459
- // The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
460
- const islandReach = new Set<string>()
461
- const reachStack = [...islandTargets.values()].map(t => t.file)
462
- while (reachStack.length > 0) {
463
- const file = reachStack.pop()!
464
- if (islandReach.has(file))
465
- continue
466
- islandReach.add(file)
467
- for (const imp of analyses.get(file)?.imports ?? []) {
468
- const target = resolveImportPath(file, imp.source)
469
- if (target !== undefined && target.endsWith('.tsx'))
470
- reachStack.push(target)
471
- }
472
- }
473
-
474
- const standaloneCssSet = new Set<string>(pluginCssFiles)
475
- for (const [file, analysis] of analyses) {
476
- for (const imp of analysis.imports) {
477
- const target = resolveImportPath(file, imp.source)
478
- if (target !== undefined && target.endsWith('.css') && !islandCssFiles.has(target))
479
- standaloneCssSet.add(target)
480
- }
481
- }
482
- const allStandaloneCss = [...standaloneCssSet]
483
-
484
- // Step 1 & Step 2: Single-pass Client + Server Builds
485
- // When there are no islands (e.g. static sites, blogs, docs), run client CSS and server builds in parallel!
486
- const islandChunks = new Map<string, string>()
487
- const srcCssToUrl = new Map<string, string>()
488
- const islandCssUrl = new Map<string, string>()
489
- const assetFiles: string[] = []
490
- const styleUrls: string[] = []
491
- let runtimeScript: string | undefined
492
- let clientMetafile: Bun.BuildOutput['metafile']
493
-
494
- const needsClientBuild = islandTargets.size > 0 || pluginClientEntries.length > 0 || allStandaloneCss.length > 0
495
-
496
- const runClientBuild = async (): Promise<void> => {
497
- if (!needsClientBuild)
498
- return
499
- const entriesDir = join(outDir, '.entries')
500
- mkdirSync(entriesDir, { recursive: true })
501
- const entryPoints: string[] = []
502
- const islandEntryToKey = new Map<string, string>()
503
-
504
- const compiledDomCache = new Map<string, string>()
505
- let hasDeferredHydrate = false
506
- let hasClientOnlyHydrate = false
507
-
508
- for (const [, analysis] of analyses) {
509
- if (analysis.defaultHydrate === 'client')
510
- hasClientOnlyHydrate = true
511
- else if (analysis.defaultHydrate !== undefined && analysis.defaultHydrate !== 'load')
512
- hasDeferredHydrate = true
513
- }
514
- for (const [, raw] of sources) {
515
- if (/\$hydrate\s*=\s*["'](?:visible|idle|interaction|media\()/.test(raw))
516
- hasDeferredHydrate = true
517
- if (/\$hydrate\s*=\s*["']client["']/.test(raw))
518
- hasClientOnlyHydrate = true
519
- }
520
-
521
- const runtimeEntryPath = join(entriesDir, 'runtime.ts')
522
- if (islandTargets.size > 0 || pluginClientEntries.length > 0) {
523
- const runtimeLines: string[] = []
524
- if (islandTargets.size > 0) {
525
- runtimeLines.push(`import { defineIslandElement } from 'kay/island';`)
526
- runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'kay/dom';`)
527
- runtimeLines.push(`defineIslandElement();`)
528
- }
529
- for (const pe of pluginClientEntries)
530
- runtimeLines.push(`import ${JSON.stringify(pe)};`)
531
- writeFileSync(runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
532
- entryPoints.push(runtimeEntryPath)
533
- }
534
-
535
- for (const cssFile of allStandaloneCss)
536
- entryPoints.push(cssFile)
537
-
538
- for (const [key, target] of islandTargets) {
539
- const entryPath = join(entriesDir, `${target.id}.ts`)
540
- const exportStmt = target.exportName === 'default'
541
- ? `export { default } from ${JSON.stringify(target.file)};\n`
542
- : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
543
- writeFileSync(entryPath, exportStmt)
544
- entryPoints.push(entryPath)
545
- islandEntryToKey.set(entryPath, key)
546
- }
547
-
548
- const clientLeaks = new Set<string>()
549
- const publicEnvDefines: Record<string, string> = {}
550
- for (const [key, value] of Object.entries(process.env)) {
551
- if (key.startsWith('PUBLIC_') && value !== undefined)
552
- publicEnvDefines[`process.env.${key}`] = JSON.stringify(value)
553
- }
554
- const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in publicEnvDefines
555
- const clientPlugin: BunPlugin = {
556
- name: 'kay-v2-client',
557
- setup(b) {
558
- // Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
559
- b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
560
- if (!args.importer.includes('/node_modules/'))
561
- clientLeaks.add(`${relative(root, args.importer).replace(/\\/g, '/')} imports server-only module "${args.path}"`)
562
- return undefined
563
- })
564
- b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
565
- const resolved = resolveKaySpecifier(args.path)
566
- return resolved !== undefined ? { path: resolved } : undefined
567
- })
568
- b.onLoad({ filter: /\.(?:ts|tsx)$/ }, (args) => {
569
- const actions = actionsByFile.get(args.path)
570
- if (actions !== undefined && !analyses.get(args.path)?.isInteractive) {
571
- const lines = [`import { actionStub } from 'kay/action';`]
572
- for (const a of actions)
573
- lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
574
- return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
575
- }
576
-
577
- if (!args.path.endsWith('.tsx'))
578
- return undefined
579
-
580
- let compiled = compiledDomCache.get(args.path)
581
- if (compiled === undefined) {
582
- const stamp = getFileStamp(args.path)
583
- const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
584
- if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size) {
585
- compiled = cachedDom.code
586
- }
587
- else {
588
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
589
- compiled = applyTransforms(compileDom(args.path, raw, { analysis: analyses.get(args.path) }).code, args.path, 'client')
590
- if (cache !== undefined && stamp !== undefined)
591
- cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, code: compiled })
592
- }
593
- compiledDomCache.set(args.path, compiled)
594
- }
595
- return { contents: compiled, loader: 'tsx' }
596
- })
597
- },
598
- }
599
-
600
- let clientResult: Awaited<ReturnType<typeof Bun.build>>
601
- try {
602
- clientResult = await Bun.build({
603
- entrypoints: entryPoints,
604
- outdir: clientDir,
605
- target: 'browser',
606
- format: 'esm',
607
- splitting: true,
608
- minify,
609
- metafile: true,
610
- naming: '[name]-[hash].[ext]',
611
- define: {
612
- KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
613
- KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
614
- ...publicEnvDefines,
615
- },
616
- plugins: [clientPlugin, ...pluginBunPlugins],
617
- })
618
- }
619
- catch (err) {
620
- if (clientLeaks.size > 0)
621
- throw clientLeakError(clientLeaks)
622
- throw err
623
- }
624
- finally {
625
- rmSync(entriesDir, { recursive: true, force: true })
626
- }
627
-
628
- if (clientLeaks.size > 0)
629
- throw clientLeakError(clientLeaks)
630
- if (!clientResult.success) {
631
- const msgs = clientResult.logs.map(l => l.message).join('\n')
632
- throw new Error(`kay build (client) failed:\n${msgs}`)
633
- }
192
+ const islands = planIslands(graph, root, pageFiles, specialFiles, actionsByFile)
634
193
 
635
- clientMetafile = clientResult.metafile
636
- const resolveMetaPath = (p: string): string => {
637
- const fromCwd = resolve(process.cwd(), p)
638
- if (existsSync(fromCwd) || islandEntryToKey.has(fromCwd))
639
- return fromCwd
640
- return resolve(clientDir, p)
641
- }
642
-
643
- // A process.env left in a chunk is a key the build did not inline: name the app module that put it there.
644
- for (const output of clientResult.outputs) {
645
- if (!output.path.endsWith('.js') || !(await output.text()).includes('process.env'))
646
- continue
647
- const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
648
- const info = clientMetafile?.outputs[relFile] ?? clientMetafile?.outputs[`./${relFile}`]
649
- for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
650
- const program = input.bytesInOutput > 0 ? analyses.get(resolveMetaPath(inKey))?.program : undefined
651
- if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
652
- clientLeaks.add(`${relative(root, resolveMetaPath(inKey)).replace(/\\/g, '/')} reads process.env (only a process.env.PUBLIC_* set at build time is inlined)`)
653
- }
654
- }
655
- if (clientLeaks.size > 0)
656
- throw clientLeakError(clientLeaks)
657
-
658
- if (clientMetafile !== undefined) {
659
- for (const [outKey, info] of Object.entries(clientMetafile.outputs)) {
660
- const relOut = outKey.replace(/^\.\//, '')
661
- const url = `${assetPrefix}/${relOut}`
662
- const islandKey = info.entryPoint !== undefined && relOut.endsWith('.js') ? islandEntryToKey.get(resolveMetaPath(info.entryPoint)) : undefined
663
- if (islandKey !== undefined)
664
- islandChunks.set(islandKey, url)
665
- if (relOut.endsWith('.css')) {
666
- if (info.entryPoint !== undefined) {
667
- const absEntry = resolveMetaPath(info.entryPoint)
668
- if (absEntry.endsWith('.css'))
669
- srcCssToUrl.set(absEntry, url)
670
- }
671
- for (const inKey of Object.keys(info.inputs ?? {})) {
672
- if (inKey.endsWith('.css'))
673
- srcCssToUrl.set(resolveMetaPath(inKey), url)
674
- }
675
- }
676
- const cssBundle = (info as { cssBundle?: string }).cssBundle
677
- if (cssBundle !== undefined && info.entryPoint !== undefined) {
678
- const absEntry = resolveMetaPath(info.entryPoint)
679
- const islandKey = islandEntryToKey.get(absEntry)
680
- if (islandKey !== undefined)
681
- islandCssUrl.set(islandKey, `${assetPrefix}/${cssBundle.replace(/^\.\//, '')}`)
682
- }
683
- }
684
- }
685
-
686
- for (const output of clientResult.outputs) {
687
- const relFile = relative(clientDir, output.path).replace(/\\/g, '/')
688
- assetFiles.push(relFile)
689
- const url = `${assetPrefix}/${relFile}`
690
- if (relFile.endsWith('.css')) {
691
- styleUrls.push(url)
692
- }
693
- else if (output.kind === 'entry-point' && relFile.startsWith('runtime-')) {
694
- runtimeScript = url
695
- }
696
- }
697
- }
194
+ rmSync(outDir, { recursive: true, force: true })
195
+ mkdirSync(clientDir, { recursive: true })
196
+ mkdirSync(serverDir, { recursive: true })
197
+ const pluginCssFiles = plugins
198
+ .flatMap(p => p.css ?? [])
199
+ .map(c => resolve(root, c))
200
+ .filter(c => existsSync(c))
201
+ const env = { root, outDir, clientDir, serverDir, assetPrefix, minify: run.minify, isDev, graph, cache: options.cache, plugins, actionsByFile, islands }
698
202
 
699
- const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !allRouteFiles.includes(f))
203
+ const routeEntryFiles = new Set([...specialFiles, ...pageFiles])
204
+ const standaloneActionFiles = [...actionsByFile.keys()].filter(f => !routeEntryFiles.has(f))
700
205
  const serverEntries = [...specialFiles, ...pageFiles, ...standaloneActionFiles]
701
206
  const serverRoot = standaloneActionFiles.length > 0 ? root : routesDir
702
207
 
703
- const relOut = relative(root, outDir)
704
- const outDirOutsideRoot = relOut !== '' && (relOut.startsWith('..') || isAbsolute(relOut))
705
- const EXTERNAL_KAY_SUBPATHS = new Set([
706
- 'kay/build',
707
- '@kayjs/kay/build',
708
- 'kay/compiler',
709
- '@kayjs/kay/compiler',
710
- 'kay/dev',
711
- '@kayjs/kay/dev',
712
- 'kay/test',
713
- '@kayjs/kay/test',
714
- ])
715
-
716
- const reachesTsxCache = new Map<string, boolean>()
717
- function reachesTsx(file: string, stack = new Set<string>()): boolean {
718
- const cached = reachesTsxCache.get(file)
719
- if (cached !== undefined)
720
- return cached
721
- if (file.endsWith('.tsx')) {
722
- reachesTsxCache.set(file, true)
723
- return true
724
- }
725
- if (stack.has(file))
726
- return false
727
- stack.add(file)
728
- const analysis = analyses.get(file)
729
- if (analysis === undefined) {
730
- reachesTsxCache.set(file, false)
731
- return false
732
- }
733
- for (const imp of analysis.imports) {
734
- const target = resolveImportPath(file, imp.source)
735
- if (target !== undefined && reachesTsx(target, stack)) {
736
- reachesTsxCache.set(file, true)
737
- return true
738
- }
739
- }
740
- for (const re of analysis.reexports) {
741
- const target = resolveImportPath(file, re.source)
742
- if (target !== undefined && reachesTsx(target, stack)) {
743
- reachesTsxCache.set(file, true)
744
- return true
745
- }
746
- }
747
- reachesTsxCache.set(file, false)
748
- return false
749
- }
750
-
751
- const runServerBuild = async (): Promise<void> => {
752
- const serverPlugin: BunPlugin = {
753
- name: 'kay-v2-server',
754
- setup(b) {
755
- b.onResolve({ filter: /^(?:@kayjs\/)?kay(?:\/.*)?$/ }, (args) => {
756
- const resolved = resolveKaySpecifier(args.path)
757
- if (resolved === undefined)
758
- return undefined
759
- return EXTERNAL_KAY_SUBPATHS.has(args.path) ? { path: resolved, external: true } : { path: resolved }
760
- })
761
- b.onResolve({ filter: /^@kayjs\// }, (args) => {
762
- try {
763
- return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
764
- }
765
- catch {
766
- return undefined
767
- }
768
- })
769
- b.onResolve({ filter: /^[^./]/ }, (args) => {
770
- if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
771
- return undefined
772
- let resolved: string | undefined
773
- try {
774
- resolved = Bun.resolveSync(args.path, args.resolveDir || root)
775
- }
776
- catch {
777
- try {
778
- resolved = Bun.resolveSync(args.path, root)
779
- }
780
- catch {
781
- return undefined
782
- }
783
- }
784
- // Bundle any package that exports/re-exports .tsx components so Kay's SSR compiler transforms them.
785
- if (resolved.endsWith('.tsx') || reachesTsx(resolved))
786
- return { path: resolved }
787
- if (outDirOutsideRoot)
788
- return { path: resolved, external: true }
789
- return undefined
790
- })
791
- b.onLoad({ filter: /\.tsx$/ }, (args) => {
792
- const analysis = analyses.get(args.path)
793
- const rawBindings = pageIslandBindings.get(args.path)
794
- let islandMap: Map<string, IslandBinding> | undefined
795
- const inIsland = analysis?.isInteractive === true || islandReach.has(args.path)
796
- let islandKey = inIsland ? '1' : '0'
797
- if (rawBindings !== undefined) {
798
- islandMap = new Map()
799
- for (const [localName, target] of rawBindings) {
800
- const chunk = islandChunks.get(`${target.file}#${target.exportName}`)
801
- if (chunk !== undefined) {
802
- islandMap.set(localName, {
803
- id: target.id,
804
- chunk,
805
- defaultHydrate: target.defaultHydrate,
806
- })
807
- islandKey += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
808
- }
809
- }
810
- }
811
- const stamp = getFileStamp(args.path)
812
- const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
813
- if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === islandKey)
814
- return { contents: cachedSsr.code, loader: 'tsx' }
815
- const raw = sources.get(args.path) ?? readFileSync(args.path, 'utf8')
816
- const compiled = compileSsr(args.path, raw, {
817
- analysis,
818
- islands: islandMap,
819
- isIsland: inIsland,
820
- })
821
- const outCode = applyTransforms(compiled.code, args.path, 'server')
822
- if (cache !== undefined && stamp !== undefined)
823
- cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: islandKey, code: outCode })
824
- return { contents: outCode, loader: 'tsx' }
825
- })
826
- },
827
- }
828
-
829
- const serverResult = await Bun.build({
830
- entrypoints: serverEntries,
831
- outdir: serverDir,
832
- root: serverRoot,
833
- target: 'bun',
834
- format: 'esm',
835
- splitting: true,
836
- packages: 'external',
837
- minify: false,
838
- plugins: [serverPlugin, ...pluginBunPlugins],
839
- })
840
-
841
- if (!serverResult.success) {
842
- const msgs = serverResult.logs.map(l => l.message).join('\n')
843
- throw new Error(`kay build (server) failed:\n${msgs}`)
844
- }
845
- }
846
-
847
- if (islandTargets.size === 0) {
848
- await Promise.all([runClientBuild(), runServerBuild()])
208
+ // The server compiles against the island chunk URLs, so islands build first; without islands both passes run in parallel.
209
+ const clientPass = () => buildClient(env, standaloneCssFiles(graph, pluginCssFiles, islands.cssFiles))
210
+ let client: Awaited<ReturnType<typeof clientPass>>
211
+ if (islands.targets.size === 0) {
212
+ const [built] = await Promise.all([clientPass(), buildServer(env, serverEntries, serverRoot, new Map())])
213
+ client = built
849
214
  }
850
215
  else {
851
- await runClientBuild()
852
- await runServerBuild()
216
+ client = await clientPass()
217
+ await buildServer(env, serverEntries, serverRoot, client.islandChunks)
853
218
  }
854
219
 
855
220
  const toOutRel = (srcFile: string): string =>
856
- relative(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js'))).replace(/\\/g, '/')
221
+ relPosix(outDir, join(serverDir, relative(serverRoot, srcFile).replace(/\.(tsx|ts)$/, '.js')))
857
222
 
858
- const nonEmptyAssets = assetFiles.filter((rel) => {
223
+ const assets: string[] = []
224
+ for (const rel of client.assetFiles) {
859
225
  const abs = join(clientDir, rel)
860
- if (!existsSync(abs))
861
- return false
862
- if (readFileSync(abs).length === 0) {
226
+ const size = fileSize(abs)
227
+ if (size === 0)
863
228
  rmSync(abs, { force: true })
864
- return false
865
- }
866
- return true
867
- })
868
-
869
- function collectRouteIslands(file: string, seen = new Set<string>(), all = new Set<string>(), eager = new Set<string>()): void {
870
- if (seen.has(file))
871
- return
872
- seen.add(file)
873
- const analysis = analyses.get(file)
874
- if (analysis === undefined)
875
- return
876
- if (analysis.isInteractive) {
877
- const chunk = islandChunks.get(`${file}#default`)
878
- if (chunk !== undefined) {
879
- all.add(chunk)
880
- if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
881
- eager.add(chunk)
882
- }
883
- return
884
- }
885
- const bindings = pageIslandBindings.get(file)
886
- if (bindings !== undefined) {
887
- for (const [localName, target] of bindings) {
888
- const chunk = islandChunks.get(`${target.file}#${target.exportName}`)
889
- if (chunk !== undefined) {
890
- all.add(chunk)
891
- const isDeferred = analysis.deferredIslandTags.has(localName)
892
- || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
893
- if (!isDeferred)
894
- eager.add(chunk)
895
- }
896
- }
897
- }
898
- for (const imp of analysis.imports) {
899
- const target = resolveImportPath(file, imp.source)
900
- if (target !== undefined && target.endsWith('.tsx'))
901
- collectRouteIslands(target, seen, all, eager)
902
- }
903
- }
904
-
905
- function collectUsesRenderContext(file: string, seen = new Set<string>()): boolean {
906
- if (seen.has(file))
907
- return false
908
- seen.add(file)
909
- const analysis = analyses.get(file)
910
- if (analysis === undefined)
911
- return false
912
- if (analysis.usesRenderContext)
913
- return true
914
- for (const imp of analysis.imports) {
915
- const target = resolveImportPath(file, imp.source)
916
- if (target !== undefined && target.endsWith('.tsx') && collectUsesRenderContext(target, seen))
917
- return true
918
- }
919
- return false
920
- }
921
-
922
- function collectRouteStyles(file: string, seen = new Set<string>(), out = new Set<string>()): void {
923
- if (seen.has(file))
924
- return
925
- seen.add(file)
926
- const analysis = analyses.get(file)
927
- if (analysis === undefined)
928
- return
929
- if (analysis.isInteractive) {
930
- const islCss = islandCssUrl.get(`${file}#default`)
931
- if (islCss !== undefined)
932
- out.add(islCss)
933
- }
934
- const bindings = pageIslandBindings.get(file)
935
- if (bindings !== undefined) {
936
- for (const [, target] of bindings) {
937
- const islCss = islandCssUrl.get(`${target.file}#${target.exportName}`)
938
- if (islCss !== undefined)
939
- out.add(islCss)
940
- collectRouteStyles(target.file, seen, out)
941
- }
942
- }
943
- for (const imp of analysis.imports) {
944
- const target = resolveImportPath(file, imp.source)
945
- if (target === undefined)
946
- continue
947
- if (target.endsWith('.css')) {
948
- const cssUrl = srcCssToUrl.get(target)
949
- if (cssUrl !== undefined)
950
- out.add(cssUrl)
951
- }
952
- else if (target.endsWith('.tsx') || target.endsWith('.ts')) {
953
- collectRouteStyles(target, seen, out)
954
- }
955
- }
956
- }
957
-
958
- const globalPluginStyles: string[] = []
959
- for (const cssFile of pluginCssFiles) {
960
- const url = srcCssToUrl.get(cssFile)
961
- if (url !== undefined && !globalPluginStyles.includes(url))
962
- globalPluginStyles.push(url)
963
- }
964
-
965
- const rootLayoutSrc = join(routesDir, '_layout.tsx')
966
- const globalStyleSet = new Set<string>(globalPluginStyles)
967
- if (existsSync(rootLayoutSrc))
968
- collectRouteStyles(rootLayoutSrc, new Set(), globalStyleSet)
969
- const globalStyles = [...globalStyleSet]
970
-
971
- const routeEntries: RouteManifestEntry[] = pageFiles.map((file) => {
972
- const analysis = analyses.get(file)
973
- const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
974
- const middlewareSrcs = ancestorFiles(routesDir, file, ['_middleware.ts', '_middleware.tsx'])
975
- const chunks = new Set<string>()
976
- const eagerChunks = new Set<string>()
977
- const routeStyles = new Set<string>(globalPluginStyles)
978
- for (const lf of layoutSrcs) {
979
- collectRouteIslands(lf, new Set(), chunks, eagerChunks)
980
- collectRouteStyles(lf, new Set(), routeStyles)
981
- }
982
- collectRouteIslands(file, new Set(), chunks, eagerChunks)
983
- collectRouteStyles(file, new Set(), routeStyles)
984
-
985
- let usesRenderContext = collectUsesRenderContext(file)
986
- if (!usesRenderContext) {
987
- for (const lf of layoutSrcs) {
988
- if (collectUsesRenderContext(lf)) {
989
- usesRenderContext = true
990
- break
991
- }
992
- }
993
- }
994
-
995
- const islandKey = `${file}#default`
996
- return {
997
- path: fileToRoutePath(routesDir, file),
998
- file: toOutRel(file),
999
- layouts: layoutSrcs.map(toOutRel),
1000
- middlewares: middlewareSrcs.map(toOutRel),
1001
- hasLoad: analysis?.hasLoadExport,
1002
- isIsland: analysis?.isInteractive,
1003
- islandChunk: islandChunks.get(islandKey),
1004
- islandHydrate: analysis?.defaultHydrate,
1005
- islandChunks: [...chunks],
1006
- eagerIslandChunks: [...eagerChunks],
1007
- styles: [...routeStyles],
1008
- usesRenderContext,
1009
- prerender: analysis?.hasPrerender || options.static === true,
1010
- }
229
+ else if (size !== undefined)
230
+ assets.push(rel)
231
+ }
232
+
233
+ const { routes, globalStyles } = buildRouteEntries({
234
+ graph,
235
+ islands,
236
+ islandChunks: client.islandChunks,
237
+ srcCssToUrl: client.srcCssToUrl,
238
+ islandCssUrl: client.islandCssUrl,
239
+ routesDir,
240
+ pageFiles,
241
+ pluginCssFiles,
242
+ isStatic,
243
+ toOutRel,
1011
244
  })
1012
245
 
1013
- const actionEntries: ActionManifestEntry[] = []
1014
- for (const [srcFile, list] of actionsByFile) {
1015
- const outFile = toOutRel(srcFile)
1016
- const inRoutes = !relative(routesDir, srcFile).startsWith('..')
1017
- const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, ['_middleware.ts', '_middleware.tsx']).map(toOutRel) : []
1018
- for (const a of list)
1019
- actionEntries.push({ url: a.url, file: outFile, exportName: a.exportName, middlewares })
1020
- }
1021
-
1022
- const islandsRecord: Record<string, string> = {}
1023
- for (const [k, v] of islandChunks)
1024
- islandsRecord[k] = v
1025
-
1026
- // Copy public/ static files into dist/public (skipped in `kay dev`, where createServer streams directly from public/)
1027
- const publicFiles: string[] = []
246
+ // public/ files are listed in the manifest and copied into outDir/public (`kay dev` serves public/ directly instead)
1028
247
  const outPublicDir = join(outDir, 'public')
1029
- const shouldCopyPublic = options.copyPublic !== false
1030
- if (existsSync(publicDir)) {
1031
- for (const abs of walkAllFiles(publicDir).sort()) {
1032
- const rel = relative(publicDir, abs).replace(/\\/g, '/')
1033
- publicFiles.push(rel)
1034
- if (shouldCopyPublic) {
1035
- const dst = join(outPublicDir, rel)
1036
- mkdirSync(dirname(dst), { recursive: true })
1037
- writeFileSync(dst, readFileSync(abs))
1038
- }
248
+ for (const abs of walkAllFiles(run.publicDir).sort()) {
249
+ const rel = publicFiles.register(relative(run.publicDir, abs))
250
+ if (options.copyPublic !== false) {
251
+ mkdirSync(dirname(join(outPublicDir, rel)), { recursive: true })
252
+ copyFileSync(abs, join(outPublicDir, rel))
1039
253
  }
1040
254
  }
1041
255
 
1042
- // Run plugin build(ctx) hooks so plugins can emit hashed assets, public files, styles, or <head> tags
1043
- const headTags: string[] = []
1044
- const assetSet = new Set(nonEmptyAssets)
1045
- const publicSet = new Set(publicFiles)
1046
- const styleSet = new Set(styleUrls)
1047
-
1048
- const buildPluginCtx: BuildPluginContext = {
256
+ const host = createPluginHost({
257
+ plugins,
258
+ appCtx: run.appCtx,
1049
259
  root,
1050
260
  outDir,
261
+ clientDir,
262
+ outPublicDir,
1051
263
  assetPrefix,
1052
- minify,
1053
- routes: routeEntries,
1054
- emitAsset(relPath, content) {
1055
- const clean = relPath.replace(/^\/+/, '').replace(/\\/g, '/')
1056
- const dst = join(clientDir, clean)
1057
- mkdirSync(dirname(dst), { recursive: true })
1058
- writeFileSync(dst, content)
1059
- if (!assetSet.has(clean)) {
1060
- assetSet.add(clean)
1061
- nonEmptyAssets.push(clean)
1062
- }
1063
- return `${assetPrefix}/${clean}`
1064
- },
1065
- emitPublic(relPath, content) {
1066
- const clean = relPath.replace(/^\/+/, '').replace(/\\/g, '/')
1067
- const dst = join(outPublicDir, clean)
1068
- mkdirSync(dirname(dst), { recursive: true })
1069
- writeFileSync(dst, content)
1070
- if (!publicSet.has(clean)) {
1071
- publicSet.add(clean)
1072
- publicFiles.push(clean)
1073
- }
1074
- return `/${clean}`
1075
- },
1076
- addStyle(href) {
1077
- if (!styleSet.has(href)) {
1078
- styleSet.add(href)
1079
- styleUrls.push(href)
1080
- }
1081
- if (!globalStyleSet.has(href)) {
1082
- globalStyleSet.add(href)
1083
- globalStyles.push(href)
1084
- }
1085
- for (const r of routeEntries) {
1086
- if (r.styles !== undefined && !r.styles.includes(href))
1087
- r.styles.push(href)
1088
- }
1089
- },
1090
- addRouteStyle(routePath, href) {
1091
- if (!styleSet.has(href)) {
1092
- styleSet.add(href)
1093
- styleUrls.push(href)
1094
- }
1095
- const route = routeEntries.find(r => r.path === routePath)
1096
- if (route !== undefined) {
1097
- route.styles ??= [...globalStyles]
1098
- if (!route.styles.includes(href))
1099
- route.styles.push(href)
1100
- }
1101
- },
1102
- addHead(html) {
1103
- if (html !== '')
1104
- headTags.push(html)
1105
- },
1106
- addRouteHead(routePath, html) {
1107
- if (html === '')
1108
- return
1109
- const route = routeEntries.find(r => r.path === routePath)
1110
- if (route !== undefined) {
1111
- route.headTags ??= []
1112
- route.headTags.push(html)
1113
- }
1114
- },
1115
- }
1116
-
1117
- for (const plugin of plugins) {
1118
- if (plugin.build !== undefined)
1119
- await plugin.build(buildPluginCtx)
1120
- }
264
+ minify: run.minify,
265
+ isStatic,
266
+ isDev,
267
+ routes,
268
+ publicFiles,
269
+ assets,
270
+ styleUrls: client.styleUrls,
271
+ globalStyles,
272
+ })
273
+ await host.runBuild()
274
+ host.precompressAssets()
1121
275
 
1122
276
  const manifest: BuildManifest = {
1123
- runtimeScript,
1124
- styles: styleUrls,
277
+ runtimeScript: client.runtimeScript,
278
+ styles: client.styleUrls,
1125
279
  globalStyles,
1126
- ...(headTags.length > 0 ? { headTags } : {}),
1127
- routes: routeEntries,
280
+ ...(host.headTags.length > 0 ? { headTags: host.headTags } : {}),
281
+ routes,
1128
282
  errorFile: hasErrorFile ? toOutRel(errorSrc) : undefined,
1129
283
  notFoundFile: hasNotFoundFile ? toOutRel(notFoundSrc) : undefined,
1130
- actions: actionEntries,
1131
- islands: islandsRecord,
1132
- assets: nonEmptyAssets,
1133
- publicFiles,
1134
- }
1135
-
1136
- writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
1137
-
1138
- // Step 3: Hybrid Prerendering / Static Export (skipped in `kay dev` where routes render on-demand)
1139
- const shouldPrerender = options.prerender !== false || options.static === true
1140
- const prerenderRoutes = shouldPrerender ? routeEntries.filter(r => r.prerender) : []
1141
- if (prerenderRoutes.length > 0 || options.static) {
1142
- const { createServer } = await import('../server/index')
1143
- const app = await createServer({ root, outDir: relative(root, outDir), assetPrefix, plugins })
1144
- const prerenderDir = options.static ? finalOutDir : join(outDir, 'prerendered')
1145
- if (options.static)
1146
- rmSync(finalOutDir, { recursive: true, force: true })
1147
- mkdirSync(prerenderDir, { recursive: true })
1148
-
1149
- const prerenderStamp = Date.now()
1150
- for (const route of prerenderRoutes) {
1151
- const mod = await import(`${join(outDir, route.file)}?v=${prerenderStamp}`) as { paths?: () => Promise<string[]> | string[] }
1152
- let urls: string[] = []
1153
- if (!route.path.includes(':') && !route.path.includes('*')) {
1154
- urls = [route.path]
1155
- }
1156
- else if (typeof mod.paths === 'function') {
1157
- urls = await mod.paths()
1158
- }
1159
-
1160
- if (urls.length === 0)
1161
- continue
1162
-
1163
- for (const plugin of plugins) {
1164
- if (plugin.prerenderPaths !== undefined)
1165
- urls = await plugin.prerenderPaths(urls, route)
1166
- }
1167
-
1168
- const map: Record<string, string> = {}
1169
- const CONCURRENCY = 8
1170
- for (let i = 0; i < urls.length; i += CONCURRENCY) {
1171
- const batch = urls.slice(i, i + CONCURRENCY)
1172
- await Promise.all(batch.map(async (u) => {
1173
- const res = await app.handle(new Request(`http://localhost${u}`))
1174
- if (res.status === 200) {
1175
- const html = await res.text()
1176
- const relHtml = u === '/' ? 'index.html' : `${u.replace(/^\//, '').replace(/\/$/, '')}/index.html`
1177
- const absHtml = join(prerenderDir, relHtml)
1178
- mkdirSync(dirname(absHtml), { recursive: true })
1179
- writeFileSync(absHtml, html)
1180
- map[u] = relative(options.static ? finalOutDir : outDir, absHtml).replace(/\\/g, '/')
1181
- }
1182
- }))
1183
- }
1184
- route.prerendered = map
1185
- }
284
+ actions: buildActionEntries(actionsByFile, routesDir, toOutRel),
285
+ islands: Object.fromEntries(client.islandChunks),
286
+ assets,
287
+ publicFiles: publicFiles.files,
288
+ ...(Object.keys(host.pluginData).length > 0 ? { pluginData: host.pluginData } : {}),
289
+ }
290
+ const writeManifest = (): void => writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
291
+ writeManifest()
292
+
293
+ // Hybrid prerendering / static export (skipped in `kay dev`, where routes render on-demand)
294
+ const prerenderRoutes = options.prerender !== false || isStatic ? routes.filter(r => r.prerender) : []
295
+ const prerenderDir = isStatic ? run.staticStageDir! : join(outDir, 'prerendered')
296
+ const app = prerenderRoutes.length > 0 || isStatic
297
+ ? await prerender({ root, outDir, assetPrefix, plugins, isDev, isStatic, prerenderDir, routes: prerenderRoutes })
298
+ : undefined
1186
299
 
1187
- if (options.static) {
1188
- if (hasNotFoundFile) {
1189
- const notFoundRes = await app.handle(new Request('http://localhost/__kay_404__'))
1190
- writeFileSync(join(prerenderDir, '404.html'), await notFoundRes.text())
1191
- }
1192
- // Copy client assets into dist/_kay/... and public/ files into dist/...
1193
- if (nonEmptyAssets.length > 0) {
1194
- const staticAssetDir = join(prerenderDir, assetPrefix.replace(/^\//, ''))
1195
- mkdirSync(staticAssetDir, { recursive: true })
1196
- for (const rel of nonEmptyAssets) {
1197
- const dst = join(staticAssetDir, rel)
1198
- mkdirSync(dirname(dst), { recursive: true })
1199
- writeFileSync(dst, readFileSync(join(clientDir, rel)))
1200
- }
1201
- }
1202
- // Re-scan outPublicDir so any assets emitted during prerender (e.g. OG share cards, optimized MD images) are included in --static
1203
- if (existsSync(outPublicDir)) {
1204
- for (const abs of walkAllFiles(outPublicDir)) {
1205
- const rel = relative(outPublicDir, abs).replace(/\\/g, '/')
1206
- if (!publicSet.has(rel)) {
1207
- publicSet.add(rel)
1208
- publicFiles.push(rel)
1209
- }
1210
- }
1211
- }
1212
- for (const rel of publicFiles) {
1213
- const dst = join(prerenderDir, rel)
1214
- mkdirSync(dirname(dst), { recursive: true })
1215
- writeFileSync(dst, readFileSync(join(outDir, 'public', rel)))
1216
- }
1217
- // Emit precompressed .br and .gz sidecars for compressible static files (>= 128 B)
1218
- const COMPRESSIBLE = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest'])
1219
- for (const abs of walkAllFiles(prerenderDir)) {
1220
- if (!COMPRESSIBLE.has(extname(abs).toLowerCase()))
1221
- continue
1222
- const raw = readFileSync(abs)
1223
- if (raw.byteLength < 128)
1224
- continue
1225
- const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
1226
- if (br.byteLength < raw.byteLength)
1227
- writeFileSync(`${abs}.br`, br)
1228
- const gz = Bun.gzipSync(raw, { level: 9 })
1229
- if (gz.byteLength < raw.byteLength)
1230
- writeFileSync(`${abs}.gz`, gz)
1231
- }
300
+ try {
301
+ const ranAfterPrerender = await host.runAfterPrerender()
302
+ host.precompressAssets()
303
+ if (Object.keys(host.pluginData).length > 0)
304
+ manifest.pluginData = host.pluginData
305
+
306
+ if (isStatic) {
307
+ await exportStatic({
308
+ stageDir: prerenderDir,
309
+ finalOutDir: run.finalOutDir,
310
+ outDir,
311
+ clientDir,
312
+ assetPrefix,
313
+ assets,
314
+ publicFiles,
315
+ app,
316
+ hasNotFoundFile,
317
+ stageSuffix: run.stageSuffix,
318
+ })
1232
319
  }
1233
- else {
1234
- writeFileSync(join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2))
320
+ else if (prerenderRoutes.length > 0 || ranAfterPrerender) {
321
+ writeManifest()
1235
322
  }
1236
323
  }
324
+ finally {
325
+ await app?.dispose?.()
326
+ }
1237
327
 
1238
- // Step 4: Single-Executable Compile (`kay build --compile [outfile]`)
1239
328
  if (options.compile) {
1240
- const outfile = typeof options.compile === 'string' ? resolve(root, options.compile) : join(outDir, 'server-bin')
1241
329
  await compileExecutable({
1242
330
  root,
1243
331
  outDir,
1244
332
  clientDir,
1245
333
  manifest,
1246
334
  assetPrefix,
1247
- outfile,
335
+ outfile: typeof options.compile === 'string' ? resolve(root, options.compile) : join(outDir, 'server-bin'),
1248
336
  kaySrcRoot: KAY_SRC_ROOT,
1249
337
  resolveKaySpecifier,
1250
- bunPlugins: pluginBunPlugins,
338
+ bunPlugins: pluginBunPlugins(env, 'compile'),
1251
339
  })
1252
340
  }
1253
341
 
1254
342
  if (options.analyze)
1255
- console.log(formatBundleReport(manifest, clientDir, assetPrefix, clientMetafile))
343
+ console.log(formatBundleReport(manifest, clientDir, assetPrefix, client.metafile))
1256
344
 
1257
345
  return manifest
1258
- }
1259
- }
1260
-
1261
- export interface RouteBundleMetrics {
1262
- path: string
1263
- jsRaw: number
1264
- jsGzip: number
1265
- cssRaw: number
1266
- cssGzip: number
1267
- jsFiles: number
1268
- cssFiles: number
1269
- }
1270
-
1271
- export function analyzeBundleWeights(
1272
- manifest: BuildManifest,
1273
- clientDir: string,
1274
- assetPrefix = '/_kay',
1275
- metafile?: Bun.BuildOutput['metafile'],
1276
- ): { routes: RouteBundleMetrics[], totalJsGzip: number, totalCssGzip: number, topModules: { path: string, bytes: number }[] } {
1277
- const prefix = `${assetPrefix.replace(/\/$/, '')}/`
1278
- const sizeCache = new Map<string, { raw: number, gzip: number }>()
1279
-
1280
- const getSize = (url: string): { raw: number, gzip: number } => {
1281
- const cached = sizeCache.get(url)
1282
- if (cached !== undefined)
1283
- return cached
1284
- if (!url.startsWith(prefix))
1285
- return { raw: 0, gzip: 0 }
1286
- const abs = join(clientDir, url.slice(prefix.length))
1287
- if (!existsSync(abs))
1288
- return { raw: 0, gzip: 0 }
1289
- const buf = readFileSync(abs)
1290
- const entry = { raw: buf.byteLength, gzip: Bun.gzipSync(buf, { level: 9 }).byteLength }
1291
- sizeCache.set(url, entry)
1292
- return entry
1293
- }
1294
-
1295
- // Collect transitive JS chunk imports from metafile so eager JS includes shared runtime chunks!
1296
- const jsDeps = new Map<string, string[]>()
1297
- const moduleBytes = new Map<string, number>()
1298
- if (metafile !== undefined) {
1299
- for (const [outKey, info] of Object.entries(metafile.outputs)) {
1300
- const rel = outKey.replace(/^\.\//, '')
1301
- const url = `${prefix}${rel}`
1302
- if (rel.endsWith('.js')) {
1303
- const deps: string[] = []
1304
- for (const imp of info.imports ?? []) {
1305
- if (imp.kind === 'import-statement')
1306
- deps.push(`${prefix}${imp.path.replace(/^\.\//, '')}`)
1307
- }
1308
- jsDeps.set(url, deps)
1309
- }
1310
- for (const [inPath, inInfo] of Object.entries(info.inputs ?? {}))
1311
- moduleBytes.set(inPath, (moduleBytes.get(inPath) ?? 0) + inInfo.bytesInOutput)
1312
- }
1313
- }
1314
-
1315
- const collectTransitiveJs = (urls: readonly string[]): Set<string> => {
1316
- const seen = new Set<string>()
1317
- const stack = [...urls]
1318
- while (stack.length > 0) {
1319
- const cur = stack.pop()!
1320
- if (seen.has(cur))
1321
- continue
1322
- seen.add(cur)
1323
- for (const dep of jsDeps.get(cur) ?? [])
1324
- stack.push(dep)
1325
- }
1326
- return seen
1327
- }
1328
-
1329
- const routes: RouteBundleMetrics[] = manifest.routes.map((r) => {
1330
- const eagerJsRoots: string[] = []
1331
- if (r.islandChunks.length > 0 && manifest.runtimeScript !== undefined)
1332
- eagerJsRoots.push(manifest.runtimeScript)
1333
- for (const c of r.eagerIslandChunks ?? r.islandChunks)
1334
- eagerJsRoots.push(c)
1335
-
1336
- const jsSet = collectTransitiveJs(eagerJsRoots)
1337
- let jsRaw = 0
1338
- let jsGzip = 0
1339
- for (const u of jsSet) {
1340
- const s = getSize(u)
1341
- jsRaw += s.raw
1342
- jsGzip += s.gzip
1343
- }
1344
-
1345
- const cssList = r.styles ?? manifest.styles
1346
- let cssRaw = 0
1347
- let cssGzip = 0
1348
- for (const u of cssList) {
1349
- const s = getSize(u)
1350
- cssRaw += s.raw
1351
- cssGzip += s.gzip
1352
- }
1353
-
1354
- return {
1355
- path: r.path,
1356
- jsRaw,
1357
- jsGzip,
1358
- cssRaw,
1359
- cssGzip,
1360
- jsFiles: jsSet.size,
1361
- cssFiles: cssList.length,
1362
- }
1363
- })
1364
-
1365
- let totalJsGzip = 0
1366
- let totalCssGzip = 0
1367
- for (const rel of manifest.assets) {
1368
- const s = getSize(`${prefix}${rel}`)
1369
- if (rel.endsWith('.js'))
1370
- totalJsGzip += s.gzip
1371
- else if (rel.endsWith('.css'))
1372
- totalCssGzip += s.gzip
1373
- }
1374
-
1375
- const topModules = [...moduleBytes.entries()]
1376
- .map(([path, bytes]) => ({ path, bytes }))
1377
- .sort((a, b) => b.bytes - a.bytes)
1378
- .slice(0, 10)
1379
-
1380
- return { routes, totalJsGzip, totalCssGzip, topModules }
1381
- }
1382
-
1383
- export function formatBundleReport(
1384
- manifest: BuildManifest,
1385
- clientDir: string,
1386
- assetPrefix = '/_kay',
1387
- metafile?: Bun.BuildOutput['metafile'],
1388
- ): string {
1389
- const report = analyzeBundleWeights(manifest, clientDir, assetPrefix, metafile)
1390
- const kb = (b: number) => `${(b / 1024).toFixed(2)} KB`
1391
- const lines = [
1392
- '\n=== KAY BUNDLE WEIGHT REPORT ===',
1393
- `Total emitted: JS ${kb(report.totalJsGzip)} gz | CSS ${kb(report.totalCssGzip)} gz`,
1394
- '',
1395
- 'Route'.padEnd(28) + 'Eager JS (gz)'.padStart(16) + 'CSS (gz)'.padStart(14) + 'Files'.padStart(10),
1396
- ]
1397
- for (const r of report.routes) {
1398
- lines.push(
1399
- r.path.padEnd(28)
1400
- + kb(r.jsGzip).padStart(16)
1401
- + kb(r.cssGzip).padStart(14)
1402
- + `${r.jsFiles}j/${r.cssFiles}c`.padStart(10),
1403
- )
1404
- }
1405
- if (report.topModules.length > 0) {
1406
- lines.push('', 'Top modules (minified output bytes):')
1407
- for (const m of report.topModules.slice(0, 8))
1408
- lines.push(` ${kb(m.bytes).padStart(9)} ${m.path}`)
1409
- }
1410
- return lines.join('\n')
1411
346
  }