@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2

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 +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kayjs/kay",
3
- "version": "2.0.0-beta.0",
3
+ "version": "2.0.0-beta.2",
4
4
  "description": "Bun-native TSX web framework with zero-directive automatic islands, fine-grained signals, and single-binary deploys",
5
5
  "license": "MIT",
6
6
  "homepage": "https://kayjs.kaynooo.fr",
package/src/attrs.ts ADDED
@@ -0,0 +1,35 @@
1
+ // Shared HTML attribute safety & classification rules used identically by compiler, SSR, and DOM runtimes.
2
+
3
+ export const VALID_ATTR_NAME = /^[A-Za-z_:][-\w:.]*$/
4
+ export const URL_ATTRS = new Set(['href', 'src', 'action', 'formaction', 'xlink:href', 'data'])
5
+ const UNSAFE_URL_RE = /^(?:javascript|vbscript):/i
6
+ const UNSAFE_DATA_URL_RE = /^data:(?!image\/(?:png|jpe?g|gif|webp|avif|bmp|ico);)/i
7
+ const STRING_BOOL_ATTRS = new Set(['draggable', 'spellcheck', 'contenteditable'])
8
+
9
+ export const DOM_PROPS = new Set(['value', 'checked', 'selected', 'muted', 'indeterminate'])
10
+
11
+ export function isBlockedAttr(name: string): boolean {
12
+ if (!VALID_ATTR_NAME.test(name))
13
+ return true
14
+ const lower = name.toLowerCase()
15
+ return lower.startsWith('on') || lower === 'innerhtml' || lower === 'srcdoc'
16
+ }
17
+
18
+ export function isStringBoolAttr(name: string): boolean {
19
+ const lower = name.toLowerCase()
20
+ return lower.startsWith('aria-') || STRING_BOOL_ATTRS.has(lower)
21
+ }
22
+
23
+ export function isUnsafeUrlAttr(name: string, value: unknown): boolean {
24
+ const lower = name.toLowerCase()
25
+ if (!URL_ATTRS.has(lower))
26
+ return false
27
+ const cleaned = String(value).replace(/[\u0000-\u0020]+/g, '')
28
+ if (UNSAFE_URL_RE.test(cleaned))
29
+ return true
30
+ if (lower !== 'src' && /^data:/i.test(cleaned))
31
+ return true
32
+ if (lower === 'src' && UNSAFE_DATA_URL_RE.test(cleaned))
33
+ return true
34
+ return false
35
+ }
@@ -0,0 +1,615 @@
1
+ // The two Bun.build passes: the client (runtime + island chunks + standalone CSS) and the server (routes compiled for SSR).
2
+
3
+ import type { BunPlugin } from 'bun'
4
+ import type { IslandBinding } from '../compiler/index'
5
+ import type { BuildPluginTarget, KayPlugin } from '../plugins/index'
6
+ import type { BuildCache, ModuleGraph } from './graph'
7
+ import type { ActionsByFile, IslandPlan } from './islands'
8
+ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
9
+ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
10
+ import { compileDom, compileSsr } from '../compiler/index'
11
+ import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
12
+ import { formatBunBuildLogs, isOutsideRoot, isTsFile, relPosix } from './files'
13
+ import { stampFiles, stampsMatch } from './graph'
14
+ import { islandKey } from './islands'
15
+ import { resolveKaySpecifier } from './resolve'
16
+
17
+ export interface BundleEnv {
18
+ root: string
19
+ outDir: string
20
+ clientDir: string
21
+ serverDir: string
22
+ assetPrefix: string
23
+ minify: boolean
24
+ isDev: boolean
25
+ analyze?: boolean | undefined
26
+ graph: ModuleGraph
27
+ cache: BuildCache | undefined
28
+ plugins: KayPlugin[]
29
+ actionsByFile: ActionsByFile
30
+ islands: IslandPlan
31
+ }
32
+
33
+ function linkOrCopyFile(src: string, dst: string): void {
34
+ mkdirSync(dirname(dst), { recursive: true })
35
+ try {
36
+ linkSync(src, dst)
37
+ }
38
+ catch {
39
+ copyFileSync(src, dst)
40
+ }
41
+ }
42
+
43
+ function reuseDirFiles(srcDir: string, dstDir: string, relFiles?: readonly string[]): boolean {
44
+ if (!existsSync(srcDir))
45
+ return false
46
+ if (relFiles !== undefined) {
47
+ for (const rel of relFiles) {
48
+ const from = join(srcDir, rel)
49
+ if (!existsSync(from))
50
+ return false
51
+ linkOrCopyFile(from, join(dstDir, rel))
52
+ }
53
+ return true
54
+ }
55
+ let count = 0
56
+ for (const ent of readdirSync(srcDir, { recursive: true, withFileTypes: true })) {
57
+ if (!ent.isFile())
58
+ continue
59
+ const from = join(ent.parentPath, ent.name)
60
+ const rel = relative(srcDir, from)
61
+ linkOrCopyFile(from, join(dstDir, rel))
62
+ count++
63
+ }
64
+ return count > 0
65
+ }
66
+
67
+ const KAY_SPECIFIER_FILTER = /^(?:@kayjs\/)?kay(?:\/.*)?$/
68
+ const TS_FILTER = /\.(?:ts|tsx)$/
69
+ const KAY_SCOPE_RE = /^@kayjs\//
70
+ const LEADING_DOT_SLASH_RE = /^\.\//
71
+ const EXTERNAL_KAY_SUBPATHS = new Set(['kay/build', 'kay/compiler', 'kay/dev', 'kay/test'])
72
+
73
+ export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify'>, target: BuildPluginTarget): BunPlugin[] {
74
+ const { root, assetPrefix, minify } = env
75
+ return env.plugins.flatMap((p) => {
76
+ const bp = p.bunPlugins
77
+ return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target }) : bp ?? []
78
+ })
79
+ }
80
+
81
+ /** Plugin `transform` hooks, applied in order to every module the bundles load. */
82
+ function pluginTransforms(plugins: KayPlugin[]): { active: boolean, key: string, apply: (code: string, id: string, target: 'server' | 'client') => string } {
83
+ const list = plugins.filter(p => typeof p.transform === 'function')
84
+ return {
85
+ active: list.length > 0,
86
+ key: list.map(p => p.name).join(','),
87
+ apply(code, id, target) {
88
+ let cur = code
89
+ for (const plugin of list) {
90
+ const next = plugin.transform!(cur, id, target)
91
+ if (typeof next === 'string')
92
+ cur = next
93
+ }
94
+ return cur
95
+ },
96
+ }
97
+ }
98
+
99
+ /** CSS files imported outside islands (plus the plugins' own), built as standalone stylesheets. */
100
+ export function standaloneCssFiles(graph: ModuleGraph, pluginCss: string[], islandCss: Set<string>): string[] {
101
+ const out = new Set(pluginCss)
102
+ for (const [file, analysis] of graph.analyses) {
103
+ for (const imp of analysis.imports) {
104
+ const target = graph.resolve(file, imp.source)
105
+ if (target !== undefined && target.endsWith('.css') && !islandCss.has(target))
106
+ out.add(target)
107
+ }
108
+ }
109
+ return [...out]
110
+ }
111
+
112
+ export interface ClientBuild {
113
+ /** Island key to the URL of its chunk. */
114
+ islandChunks: Map<string, string>
115
+ srcCssToUrl: Map<string, string>
116
+ /** Island key to the URL of the CSS bundled with it. */
117
+ islandCssUrl: Map<string, string>
118
+ /** Emitted files, relative to the client dir. */
119
+ assetFiles: string[]
120
+ styleUrls: string[]
121
+ runtimeScript: string | undefined
122
+ metafile: Bun.BuildOutput['metafile']
123
+ }
124
+
125
+ function clientLeakError(leaks: Set<string>): Error {
126
+ 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.`)
127
+ }
128
+
129
+ function publicEnvDefines(): Record<string, string> {
130
+ const defines: Record<string, string> = {}
131
+ for (const [key, value] of Object.entries(process.env)) {
132
+ if (key.startsWith('PUBLIC_') && value !== undefined)
133
+ defines[`process.env.${key}`] = JSON.stringify(value)
134
+ }
135
+ return defines
136
+ }
137
+
138
+ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
139
+ const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
140
+ const result: ClientBuild = {
141
+ islandChunks: new Map(),
142
+ srcCssToUrl: new Map(),
143
+ islandCssUrl: new Map(),
144
+ assetFiles: [],
145
+ styleUrls: [],
146
+ runtimeScript: undefined,
147
+ metafile: undefined,
148
+ }
149
+ const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
150
+ if (islands.targets.size === 0 && pluginClientEntries.length === 0 && standaloneCss.length === 0) {
151
+ if (cache !== undefined)
152
+ cache.lastClient = undefined
153
+ return result
154
+ }
155
+
156
+ const transforms = pluginTransforms(env.plugins)
157
+ // A mode computed at runtime may be any of them, so it keeps both loaders.
158
+ let hasDeferredHydrate = false
159
+ let hasClientOnlyHydrate = false
160
+ for (const analysis of graph.analyses.values()) {
161
+ for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
162
+ if (mode === 'client' || mode === '*')
163
+ hasClientOnlyHydrate = true
164
+ if (mode !== undefined && mode !== 'load' && mode !== 'client')
165
+ hasDeferredHydrate = true
166
+ }
167
+ }
168
+
169
+ const envDefines = publicEnvDefines()
170
+ const clientSignature = cache !== undefined
171
+ ? JSON.stringify({
172
+ minify: env.minify,
173
+ assetPrefix,
174
+ isDev: env.isDev,
175
+ transforms: transforms.key,
176
+ hasDeferredHydrate,
177
+ hasClientOnlyHydrate,
178
+ pluginClientEntries,
179
+ standaloneCss: [...standaloneCss].sort(),
180
+ islands: [...islands.targets.entries()]
181
+ .sort(([a], [b]) => a.localeCompare(b))
182
+ .map(([k, t]) => [k, t.id, t.file, t.exportName, t.defaultHydrate ?? '']),
183
+ actions: [...actionsByFile.entries()]
184
+ .sort(([a], [b]) => a.localeCompare(b))
185
+ .map(([f, list]) => [f, list.map(a => `${a.exportName}=${a.url}`)]),
186
+ envDefines: Object.entries(envDefines).sort(([a], [b]) => a.localeCompare(b)),
187
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
188
+ })
189
+ : ''
190
+
191
+ if (
192
+ cache !== undefined
193
+ && !env.analyze
194
+ && cache.lastClient !== undefined
195
+ && cache.lastClient.signature === clientSignature
196
+ && stampsMatch(cache.lastClient.inputStamps)
197
+ && reuseDirFiles(cache.lastClient.clientDir, clientDir, cache.lastClient.assetFiles)
198
+ ) {
199
+ cache.stats.clientSkips++
200
+ cache.lastClient.clientDir = clientDir
201
+ return {
202
+ islandChunks: new Map(cache.lastClient.islandChunks),
203
+ srcCssToUrl: new Map(cache.lastClient.srcCssToUrl),
204
+ islandCssUrl: new Map(cache.lastClient.islandCssUrl),
205
+ assetFiles: [...cache.lastClient.assetFiles],
206
+ styleUrls: [...cache.lastClient.styleUrls],
207
+ runtimeScript: cache.lastClient.runtimeScript,
208
+ metafile: undefined,
209
+ }
210
+ }
211
+
212
+ // Bun hashes an entry's path into its chunk name, so the entries sit at one path per app: a dev rebuild or a static stage then keeps every unchanged chunk name.
213
+ const entriesDir = join(root, 'node_modules/.cache/kay/entries')
214
+ mkdirSync(entriesDir, { recursive: true })
215
+ // Another build of the same app (`kay build` beside `kay dev`) may be reading the file, hence the rename.
216
+ const writeEntry = (path: string, contents: string): void => {
217
+ if (existsSync(path) && readFileSync(path, 'utf8') === contents)
218
+ return
219
+ const tmpPath = `${path}.${process.pid}.tmp`
220
+ writeFileSync(tmpPath, contents)
221
+ renameSync(tmpPath, path)
222
+ }
223
+ const entryPoints: string[] = []
224
+ const islandEntryToKey = new Map<string, string>()
225
+
226
+ if (islands.targets.size > 0 || pluginClientEntries.length > 0) {
227
+ const runtimeLines: string[] = []
228
+ if (islands.targets.size > 0) {
229
+ runtimeLines.push(`import { defineIslandElement } from 'kay/island';`)
230
+ runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'kay/dom';`)
231
+ runtimeLines.push(`defineIslandElement();`)
232
+ }
233
+ for (const pe of pluginClientEntries)
234
+ runtimeLines.push(`import ${JSON.stringify(pe)};`)
235
+ const runtimeEntryPath = join(entriesDir, 'runtime.ts')
236
+ writeEntry(runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
237
+ entryPoints.push(runtimeEntryPath)
238
+ }
239
+
240
+ entryPoints.push(...standaloneCss)
241
+
242
+ for (const [key, target] of islands.targets) {
243
+ const entryPath = join(entriesDir, `${target.id}.ts`)
244
+ const exportStmt = target.exportName === 'default'
245
+ ? `export { default } from ${JSON.stringify(target.file)};\n`
246
+ : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
247
+ writeEntry(entryPath, exportStmt)
248
+ entryPoints.push(entryPath)
249
+ islandEntryToKey.set(entryPath, key)
250
+ }
251
+
252
+ const clientLeaks = new Set<string>()
253
+ const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
254
+ const clientPlugin: BunPlugin = {
255
+ name: 'kay-v2-client',
256
+ setup(b) {
257
+ // Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
258
+ b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
259
+ if (!args.importer.includes('/node_modules/'))
260
+ clientLeaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
261
+ return undefined
262
+ })
263
+ b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
264
+ const resolved = resolveKaySpecifier(args.path)
265
+ return resolved !== undefined ? { path: resolved } : undefined
266
+ })
267
+ b.onLoad({ filter: TS_FILTER }, (args) => {
268
+ const actions = actionsByFile.get(args.path)
269
+ if (actions !== undefined && !graph.analyses.get(args.path)?.isInteractive) {
270
+ const lines = [`import { actionStub } from 'kay/action';`]
271
+ for (const a of actions)
272
+ lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
273
+ return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
274
+ }
275
+
276
+ if (!args.path.endsWith('.tsx')) {
277
+ if (!transforms.active || args.path.includes('/node_modules/'))
278
+ return undefined
279
+ const raw = graph.source(args.path)
280
+ const transformed = transforms.apply(raw, args.path, 'client')
281
+ return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
282
+ }
283
+
284
+ const stamp = graph.stamp(args.path)
285
+ const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
286
+ if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === transforms.key)
287
+ return { contents: cachedDom.code, loader: 'tsx' }
288
+ const compiled = transforms.apply(compileDom(args.path, graph.source(args.path), { analysis: graph.analyses.get(args.path) }).code, args.path, 'client')
289
+ if (cache !== undefined && stamp !== undefined)
290
+ cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: transforms.key, code: compiled })
291
+ return { contents: compiled, loader: 'tsx' }
292
+ })
293
+ },
294
+ }
295
+
296
+ let clientResult: Awaited<ReturnType<typeof Bun.build>>
297
+ try {
298
+ clientResult = await Bun.build({
299
+ entrypoints: entryPoints,
300
+ outdir: clientDir,
301
+ target: 'browser',
302
+ format: 'esm',
303
+ splitting: true,
304
+ minify: env.minify,
305
+ metafile: true,
306
+ naming: '[name]-[hash].[ext]',
307
+ define: {
308
+ KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
309
+ KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
310
+ 'process.env.NODE_ENV': JSON.stringify(env.isDev ? 'development' : 'production'),
311
+ ...envDefines,
312
+ },
313
+ plugins: [clientPlugin, ...pluginBunPlugins(env, 'client')],
314
+ })
315
+ }
316
+ catch (err) {
317
+ if (clientLeaks.size > 0)
318
+ throw clientLeakError(clientLeaks)
319
+ if (err instanceof AggregateError && err.errors.length > 0)
320
+ throw new Error(`kay build (client) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
321
+ throw err
322
+ }
323
+
324
+ if (clientLeaks.size > 0)
325
+ throw clientLeakError(clientLeaks)
326
+ if (!clientResult.success) {
327
+ const msgs = formatBunBuildLogs(clientResult.logs, env.root)
328
+ throw new Error(`kay build (client) failed:\n${msgs}`)
329
+ }
330
+
331
+ const { metafile } = clientResult
332
+ result.metafile = metafile
333
+ const metaPaths = new Map<string, string>()
334
+ const resolveMetaPath = (p: string): string => {
335
+ let abs = metaPaths.get(p)
336
+ if (abs === undefined) {
337
+ const fromCwd = resolve(process.cwd(), p)
338
+ abs = existsSync(fromCwd) || islandEntryToKey.has(fromCwd) ? fromCwd : resolve(clientDir, p)
339
+ metaPaths.set(p, abs)
340
+ }
341
+ return abs
342
+ }
343
+
344
+ // A process.env or Bun.env left in a chunk is a key the build did not inline: name the app module that put it there.
345
+ for (const output of clientResult.outputs) {
346
+ if (!output.path.endsWith('.js'))
347
+ continue
348
+ const js = await output.text()
349
+ if (!js.includes('process.env') && !js.includes('Bun.env'))
350
+ continue
351
+ const relFile = relPosix(clientDir, output.path)
352
+ const info = metafile?.outputs[relFile] ?? metafile?.outputs[`./${relFile}`]
353
+ for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
354
+ if (input.bytesInOutput <= 0)
355
+ continue
356
+ const abs = resolveMetaPath(inKey)
357
+ let program = graph.analyses.get(abs)?.program
358
+ if (program === undefined && existsSync(abs) && isTsFile(abs) && !/[\\/]node_modules[\\/]/.test(abs)) {
359
+ try {
360
+ program = graph.load(abs).program
361
+ }
362
+ catch {}
363
+ }
364
+ if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
365
+ clientLeaks.add(`${relPosix(root, abs)} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
366
+ }
367
+ }
368
+ if (clientLeaks.size > 0)
369
+ throw clientLeakError(clientLeaks)
370
+
371
+ for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
372
+ const relOut = outKey.replace(LEADING_DOT_SLASH_RE, '')
373
+ const url = `${assetPrefix}/${relOut}`
374
+ const entry = info.entryPoint === undefined ? undefined : resolveMetaPath(info.entryPoint)
375
+ const entryKey = entry === undefined ? undefined : islandEntryToKey.get(entry)
376
+ if (entryKey !== undefined && relOut.endsWith('.js'))
377
+ result.islandChunks.set(entryKey, url)
378
+ if (relOut.endsWith('.css')) {
379
+ if (entry?.endsWith('.css'))
380
+ result.srcCssToUrl.set(entry, url)
381
+ for (const inKey of Object.keys(info.inputs ?? {})) {
382
+ if (inKey.endsWith('.css'))
383
+ result.srcCssToUrl.set(resolveMetaPath(inKey), url)
384
+ }
385
+ }
386
+ const cssBundle = (info as { cssBundle?: string }).cssBundle
387
+ if (cssBundle !== undefined && entryKey !== undefined)
388
+ result.islandCssUrl.set(entryKey, `${assetPrefix}/${cssBundle.replace(LEADING_DOT_SLASH_RE, '')}`)
389
+ }
390
+
391
+ for (const output of clientResult.outputs) {
392
+ const relFile = relPosix(clientDir, output.path)
393
+ result.assetFiles.push(relFile)
394
+ const url = `${assetPrefix}/${relFile}`
395
+ if (relFile.endsWith('.css'))
396
+ result.styleUrls.push(url)
397
+ else if (output.kind === 'entry-point' && relFile.startsWith('runtime-'))
398
+ result.runtimeScript = url
399
+ }
400
+
401
+ if (cache !== undefined) {
402
+ cache.stats.clientBuilds++
403
+ const inputFiles = new Set<string>([...standaloneCss, ...pluginClientEntries])
404
+ for (const inKey of Object.keys(metafile?.inputs ?? {})) {
405
+ const abs = resolveMetaPath(inKey)
406
+ // Skip generated entry shims and stubbed action files (whose signature tracks exported action names/URLs, not server body).
407
+ if (abs.startsWith(entriesDir))
408
+ continue
409
+ if (actionsByFile.has(abs) && !graph.analyses.get(abs)?.isInteractive)
410
+ continue
411
+ inputFiles.add(abs)
412
+ }
413
+ cache.lastClient = {
414
+ signature: clientSignature,
415
+ clientDir,
416
+ inputStamps: stampFiles(inputFiles),
417
+ islandChunks: new Map(result.islandChunks),
418
+ srcCssToUrl: new Map(result.srcCssToUrl),
419
+ islandCssUrl: new Map(result.islandCssUrl),
420
+ assetFiles: [...result.assetFiles],
421
+ styleUrls: [...result.styleUrls],
422
+ runtimeScript: result.runtimeScript,
423
+ }
424
+ }
425
+ return result
426
+ }
427
+
428
+ export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>): Promise<void> {
429
+ const { root, outDir, serverDir, graph, cache, islands } = env
430
+ const transforms = pluginTransforms(env.plugins)
431
+ const externalOutDir = isOutsideRoot(root, outDir)
432
+
433
+ const serverSignature = cache !== undefined
434
+ ? JSON.stringify({
435
+ serverRoot,
436
+ assetPrefix: env.assetPrefix,
437
+ isDev: env.isDev,
438
+ transforms: transforms.key,
439
+ entries: [...entries].sort(),
440
+ islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
441
+ reach: [...islands.reach].sort(),
442
+ bindings: [...islands.pageBindings.entries()]
443
+ .sort(([a], [b]) => a.localeCompare(b))
444
+ .map(([f, map]) => [f, [...map.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, t]) => [l, t.id, t.defaultHydrate ?? ''])]),
445
+ bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
446
+ })
447
+ : ''
448
+
449
+ if (
450
+ cache !== undefined
451
+ && cache.lastServer !== undefined
452
+ && cache.lastServer.signature === serverSignature
453
+ && stampsMatch(cache.lastServer.inputStamps)
454
+ && reuseDirFiles(cache.lastServer.serverDir, serverDir)
455
+ ) {
456
+ cache.stats.serverSkips++
457
+ cache.lastServer.serverDir = serverDir
458
+ return
459
+ }
460
+
461
+ // Whether a file renders components, directly or through what it imports: such packages are bundled so Kay's SSR compiler transforms them.
462
+ const tsxReach = new Map<string, boolean>()
463
+ const reachesTsx = (file: string, visiting = new Set<string>()): boolean => {
464
+ const known = tsxReach.get(file)
465
+ if (known !== undefined)
466
+ return known
467
+ if (file.endsWith('.tsx'))
468
+ return true
469
+ if (visiting.has(file))
470
+ return false
471
+ visiting.add(file)
472
+ const reaches = graph.localDeps(file).some(dep => reachesTsx(dep, visiting))
473
+ // Only memoize at the top-level walk (when no cycle ancestor could have truncated a branch).
474
+ if (reaches || visiting.size === 1)
475
+ tsxReach.set(file, reaches)
476
+ return reaches
477
+ }
478
+
479
+ const serverPlugin: BunPlugin = {
480
+ name: 'kay-v2-server',
481
+ setup(b) {
482
+ b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
483
+ const resolved = resolveKaySpecifier(args.path)
484
+ if (resolved === undefined)
485
+ return undefined
486
+ return EXTERNAL_KAY_SUBPATHS.has(args.path.replace(KAY_SCOPE_RE, '')) ? { path: resolved, external: true } : { path: resolved }
487
+ })
488
+ b.onResolve({ filter: KAY_SCOPE_RE }, (args) => {
489
+ try {
490
+ return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
491
+ }
492
+ catch {
493
+ return undefined
494
+ }
495
+ })
496
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
497
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
498
+ return undefined
499
+ let resolved: string | undefined
500
+ try {
501
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
502
+ }
503
+ catch {
504
+ try {
505
+ resolved = Bun.resolveSync(args.path, root)
506
+ }
507
+ catch {
508
+ return undefined
509
+ }
510
+ }
511
+ if (resolved.endsWith('.tsx') || reachesTsx(resolved))
512
+ return { path: resolved }
513
+ if (env.isDev && isTsFile(resolved)) {
514
+ try {
515
+ const real = realpathSync(resolved)
516
+ if (!real.includes('/node_modules/') && !real.includes('\\node_modules\\'))
517
+ return { path: resolved }
518
+ }
519
+ catch {}
520
+ }
521
+ if (externalOutDir)
522
+ return { path: resolved, external: true }
523
+ return undefined
524
+ })
525
+ b.onLoad({ filter: TS_FILTER }, (args) => {
526
+ if (!args.path.endsWith('.tsx')) {
527
+ if (!transforms.active || args.path.includes('/node_modules/'))
528
+ return undefined
529
+ const raw = graph.source(args.path)
530
+ const transformed = transforms.apply(raw, args.path, 'server')
531
+ return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
532
+ }
533
+ const analysis = graph.analyses.get(args.path)
534
+ const rawBindings = islands.pageBindings.get(args.path)
535
+ const isInteractive = analysis?.isInteractive === true
536
+ const emitMarkers = isInteractive || islands.reach.has(args.path)
537
+ let islandMap: Map<string, IslandBinding> | undefined
538
+ let key = `${isInteractive ? '1' : '0'}:${emitMarkers ? '1' : '0'}|t=${transforms.key}`
539
+ if (rawBindings !== undefined) {
540
+ islandMap = new Map()
541
+ for (const [localName, target] of rawBindings) {
542
+ const chunk = islandChunks.get(islandKey(target))
543
+ if (chunk !== undefined) {
544
+ islandMap.set(localName, { id: target.id, chunk, defaultHydrate: target.defaultHydrate })
545
+ key += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
546
+ }
547
+ }
548
+ }
549
+ const stamp = graph.stamp(args.path)
550
+ const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
551
+ if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === key)
552
+ return { contents: cachedSsr.code, loader: 'tsx' }
553
+ const compiled = compileSsr(args.path, graph.source(args.path), {
554
+ analysis,
555
+ islands: islandMap,
556
+ isIsland: isInteractive,
557
+ emitMarkers,
558
+ } as Parameters<typeof compileSsr>[2])
559
+ const code = transforms.apply(compiled.code, args.path, 'server')
560
+ if (cache !== undefined && stamp !== undefined)
561
+ cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code })
562
+ return { contents: code, loader: 'tsx' }
563
+ })
564
+ },
565
+ }
566
+
567
+ let serverResult: Awaited<ReturnType<typeof Bun.build>>
568
+ try {
569
+ serverResult = await Bun.build({
570
+ entrypoints: entries,
571
+ outdir: serverDir,
572
+ root: serverRoot,
573
+ target: 'bun',
574
+ format: 'esm',
575
+ splitting: true,
576
+ packages: 'external',
577
+ minify: false,
578
+ metafile: cache !== undefined,
579
+ define: {
580
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
581
+ },
582
+ plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
583
+ })
584
+ }
585
+ catch (err) {
586
+ if (err instanceof AggregateError && err.errors.length > 0)
587
+ throw new Error(`kay build (server) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
588
+ throw err
589
+ }
590
+
591
+ if (!serverResult.success) {
592
+ const msgs = formatBunBuildLogs(serverResult.logs, env.root)
593
+ throw new Error(`kay build (server) failed:\n${msgs}`)
594
+ }
595
+
596
+ if (cache !== undefined) {
597
+ cache.stats.serverBuilds++
598
+ const inputFiles = new Set<string>(entries)
599
+ for (const inKey of Object.keys(serverResult.metafile?.inputs ?? {})) {
600
+ const fromCwd = resolve(process.cwd(), inKey)
601
+ const abs = existsSync(fromCwd) ? fromCwd : resolve(serverDir, inKey)
602
+ if (!existsSync(abs))
603
+ continue
604
+ // Plain `.css` stylesheets are bundled exclusively by `buildClient`; CSS edits must not trigger a server rebuild.
605
+ if (abs.endsWith('.css') && !abs.endsWith('.module.css'))
606
+ continue
607
+ inputFiles.add(abs)
608
+ }
609
+ cache.lastServer = {
610
+ signature: serverSignature,
611
+ serverDir,
612
+ inputStamps: stampFiles(inputFiles),
613
+ }
614
+ }
615
+ }