@kayjs/kay 2.0.0-beta.0 → 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 +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  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 +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  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 +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  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 +114 -18
  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 +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -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 +2 -1
  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.1",
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,442 @@
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 { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
9
+ import { isAbsolute, join, resolve } from 'node:path'
10
+ import { compileDom, compileSsr } from '../compiler/index'
11
+ import { readsPrivateEnv, SERVER_ONLY_FILTER } from '../compiler/server-only'
12
+ import { isOutsideRoot, isTsFile, relPosix } from './files'
13
+ import { islandKey } from './islands'
14
+ import { resolveKaySpecifier } from './resolve'
15
+
16
+ export interface BundleEnv {
17
+ root: string
18
+ outDir: string
19
+ clientDir: string
20
+ serverDir: string
21
+ assetPrefix: string
22
+ minify: boolean
23
+ isDev: boolean
24
+ graph: ModuleGraph
25
+ cache: BuildCache | undefined
26
+ plugins: KayPlugin[]
27
+ actionsByFile: ActionsByFile
28
+ islands: IslandPlan
29
+ }
30
+
31
+ const KAY_SPECIFIER_FILTER = /^(?:@kayjs\/)?kay(?:\/.*)?$/
32
+ const TS_FILTER = /\.(?:ts|tsx)$/
33
+ const KAY_SCOPE_RE = /^@kayjs\//
34
+ const LEADING_DOT_SLASH_RE = /^\.\//
35
+ const EXTERNAL_KAY_SUBPATHS = new Set(['kay/build', 'kay/compiler', 'kay/dev', 'kay/test'])
36
+
37
+ export function pluginBunPlugins(env: Pick<BundleEnv, 'plugins' | 'root' | 'assetPrefix' | 'minify'>, target: BuildPluginTarget): BunPlugin[] {
38
+ const { root, assetPrefix, minify } = env
39
+ return env.plugins.flatMap((p) => {
40
+ const bp = p.bunPlugins
41
+ return typeof bp === 'function' ? bp({ root, assetPrefix, minify, target }) : bp ?? []
42
+ })
43
+ }
44
+
45
+ /** Plugin `transform` hooks, applied in order to every module the bundles load. */
46
+ function pluginTransforms(plugins: KayPlugin[]): { active: boolean, key: string, apply: (code: string, id: string, target: 'server' | 'client') => string } {
47
+ const list = plugins.filter(p => typeof p.transform === 'function')
48
+ return {
49
+ active: list.length > 0,
50
+ key: list.map(p => p.name).join(','),
51
+ apply(code, id, target) {
52
+ let cur = code
53
+ for (const plugin of list) {
54
+ const next = plugin.transform!(cur, id, target)
55
+ if (typeof next === 'string')
56
+ cur = next
57
+ }
58
+ return cur
59
+ },
60
+ }
61
+ }
62
+
63
+ /** CSS files imported outside islands (plus the plugins' own), built as standalone stylesheets. */
64
+ export function standaloneCssFiles(graph: ModuleGraph, pluginCss: string[], islandCss: Set<string>): string[] {
65
+ const out = new Set(pluginCss)
66
+ for (const [file, analysis] of graph.analyses) {
67
+ for (const imp of analysis.imports) {
68
+ const target = graph.resolve(file, imp.source)
69
+ if (target !== undefined && target.endsWith('.css') && !islandCss.has(target))
70
+ out.add(target)
71
+ }
72
+ }
73
+ return [...out]
74
+ }
75
+
76
+ export interface ClientBuild {
77
+ /** Island key to the URL of its chunk. */
78
+ islandChunks: Map<string, string>
79
+ srcCssToUrl: Map<string, string>
80
+ /** Island key to the URL of the CSS bundled with it. */
81
+ islandCssUrl: Map<string, string>
82
+ /** Emitted files, relative to the client dir. */
83
+ assetFiles: string[]
84
+ styleUrls: string[]
85
+ runtimeScript: string | undefined
86
+ metafile: Bun.BuildOutput['metafile']
87
+ }
88
+
89
+ function clientLeakError(leaks: Set<string>): Error {
90
+ 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.`)
91
+ }
92
+
93
+ function publicEnvDefines(): Record<string, string> {
94
+ const defines: Record<string, string> = {}
95
+ for (const [key, value] of Object.entries(process.env)) {
96
+ if (key.startsWith('PUBLIC_') && value !== undefined)
97
+ defines[`process.env.${key}`] = JSON.stringify(value)
98
+ }
99
+ return defines
100
+ }
101
+
102
+ export async function buildClient(env: BundleEnv, standaloneCss: string[]): Promise<ClientBuild> {
103
+ const { root, clientDir, assetPrefix, graph, cache, actionsByFile, islands } = env
104
+ const result: ClientBuild = {
105
+ islandChunks: new Map(),
106
+ srcCssToUrl: new Map(),
107
+ islandCssUrl: new Map(),
108
+ assetFiles: [],
109
+ styleUrls: [],
110
+ runtimeScript: undefined,
111
+ metafile: undefined,
112
+ }
113
+ const pluginClientEntries = env.plugins.map(p => p.clientEntry).filter((e): e is string => Boolean(e))
114
+ if (islands.targets.size === 0 && pluginClientEntries.length === 0 && standaloneCss.length === 0)
115
+ return result
116
+
117
+ const transforms = pluginTransforms(env.plugins)
118
+ // 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.
119
+ const entriesDir = join(root, 'node_modules/.cache/kay/entries')
120
+ mkdirSync(entriesDir, { recursive: true })
121
+ // Another build of the same app (`kay build` beside `kay dev`) may be reading the file, hence the rename.
122
+ const writeEntry = (path: string, contents: string): void => {
123
+ if (existsSync(path) && readFileSync(path, 'utf8') === contents)
124
+ return
125
+ const tmpPath = `${path}.${process.pid}.tmp`
126
+ writeFileSync(tmpPath, contents)
127
+ renameSync(tmpPath, path)
128
+ }
129
+ const entryPoints: string[] = []
130
+ const islandEntryToKey = new Map<string, string>()
131
+
132
+ // A mode computed at runtime may be any of them, so it keeps both loaders.
133
+ let hasDeferredHydrate = false
134
+ let hasClientOnlyHydrate = false
135
+ for (const analysis of graph.analyses.values()) {
136
+ for (const mode of [analysis.defaultHydrate, ...analysis.hydrateModes]) {
137
+ if (mode === 'client' || mode === '*')
138
+ hasClientOnlyHydrate = true
139
+ if (mode !== undefined && mode !== 'load' && mode !== 'client')
140
+ hasDeferredHydrate = true
141
+ }
142
+ }
143
+
144
+ if (islands.targets.size > 0 || pluginClientEntries.length > 0) {
145
+ const runtimeLines: string[] = []
146
+ if (islands.targets.size > 0) {
147
+ runtimeLines.push(`import { defineIslandElement } from 'kay/island';`)
148
+ runtimeLines.push(`export { hydrate${hasClientOnlyHydrate ? ', mount' : ''} } from 'kay/dom';`)
149
+ runtimeLines.push(`defineIslandElement();`)
150
+ }
151
+ for (const pe of pluginClientEntries)
152
+ runtimeLines.push(`import ${JSON.stringify(pe)};`)
153
+ const runtimeEntryPath = join(entriesDir, 'runtime.ts')
154
+ writeEntry(runtimeEntryPath, `${runtimeLines.join('\n')}\n`)
155
+ entryPoints.push(runtimeEntryPath)
156
+ }
157
+
158
+ entryPoints.push(...standaloneCss)
159
+
160
+ for (const [key, target] of islands.targets) {
161
+ const entryPath = join(entriesDir, `${target.id}.ts`)
162
+ const exportStmt = target.exportName === 'default'
163
+ ? `export { default } from ${JSON.stringify(target.file)};\n`
164
+ : `export { ${target.exportName} as default } from ${JSON.stringify(target.file)};\n`
165
+ writeEntry(entryPath, exportStmt)
166
+ entryPoints.push(entryPath)
167
+ islandEntryToKey.set(entryPath, key)
168
+ }
169
+
170
+ const clientLeaks = new Set<string>()
171
+ const envDefines = publicEnvDefines()
172
+ const inlinedEnvKey = (key: string): boolean => key === 'NODE_ENV' || `process.env.${key}` in envDefines
173
+ const clientPlugin: BunPlugin = {
174
+ name: 'kay-v2-client',
175
+ setup(b) {
176
+ // Bun swaps node built-ins for empty shims in a browser build, so a server-only import would ship silently.
177
+ b.onResolve({ filter: SERVER_ONLY_FILTER }, (args) => {
178
+ if (!args.importer.includes('/node_modules/'))
179
+ clientLeaks.add(`${relPosix(root, args.importer)} imports server-only module "${args.path}"`)
180
+ return undefined
181
+ })
182
+ b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
183
+ const resolved = resolveKaySpecifier(args.path)
184
+ return resolved !== undefined ? { path: resolved } : undefined
185
+ })
186
+ b.onLoad({ filter: TS_FILTER }, (args) => {
187
+ const actions = actionsByFile.get(args.path)
188
+ if (actions !== undefined && !graph.analyses.get(args.path)?.isInteractive) {
189
+ const lines = [`import { actionStub } from 'kay/action';`]
190
+ for (const a of actions)
191
+ lines.push(`export const ${a.exportName} = actionStub(${JSON.stringify(a.url)});`)
192
+ return { contents: `${lines.join('\n')}\n`, loader: 'ts' }
193
+ }
194
+
195
+ if (!args.path.endsWith('.tsx')) {
196
+ if (!transforms.active || args.path.includes('/node_modules/'))
197
+ return undefined
198
+ const raw = graph.source(args.path)
199
+ const transformed = transforms.apply(raw, args.path, 'client')
200
+ return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
201
+ }
202
+
203
+ const stamp = graph.stamp(args.path)
204
+ const cachedDom = stamp !== undefined ? cache?.domCompiled.get(args.path) : undefined
205
+ if (cachedDom !== undefined && cachedDom.mtimeMs === stamp!.mtimeMs && cachedDom.size === stamp!.size && (cachedDom.key ?? '') === transforms.key)
206
+ return { contents: cachedDom.code, loader: 'tsx' }
207
+ const compiled = transforms.apply(compileDom(args.path, graph.source(args.path), { analysis: graph.analyses.get(args.path) }).code, args.path, 'client')
208
+ if (cache !== undefined && stamp !== undefined)
209
+ cache.domCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key: transforms.key, code: compiled })
210
+ return { contents: compiled, loader: 'tsx' }
211
+ })
212
+ },
213
+ }
214
+
215
+ let clientResult: Awaited<ReturnType<typeof Bun.build>>
216
+ try {
217
+ clientResult = await Bun.build({
218
+ entrypoints: entryPoints,
219
+ outdir: clientDir,
220
+ target: 'browser',
221
+ format: 'esm',
222
+ splitting: true,
223
+ minify: env.minify,
224
+ metafile: true,
225
+ naming: '[name]-[hash].[ext]',
226
+ define: {
227
+ KAY_DEFERRED: hasDeferredHydrate ? 'true' : 'false',
228
+ KAY_CLIENT_ONLY: hasClientOnlyHydrate ? 'true' : 'false',
229
+ 'process.env.NODE_ENV': JSON.stringify(env.isDev ? 'development' : 'production'),
230
+ ...envDefines,
231
+ },
232
+ plugins: [clientPlugin, ...pluginBunPlugins(env, 'client')],
233
+ })
234
+ }
235
+ catch (err) {
236
+ if (clientLeaks.size > 0)
237
+ throw clientLeakError(clientLeaks)
238
+ throw err
239
+ }
240
+
241
+ if (clientLeaks.size > 0)
242
+ throw clientLeakError(clientLeaks)
243
+ if (!clientResult.success) {
244
+ const msgs = clientResult.logs.map(l => l.message).join('\n')
245
+ throw new Error(`kay build (client) failed:\n${msgs}`)
246
+ }
247
+
248
+ const { metafile } = clientResult
249
+ result.metafile = metafile
250
+ const metaPaths = new Map<string, string>()
251
+ const resolveMetaPath = (p: string): string => {
252
+ let abs = metaPaths.get(p)
253
+ if (abs === undefined) {
254
+ const fromCwd = resolve(process.cwd(), p)
255
+ abs = existsSync(fromCwd) || islandEntryToKey.has(fromCwd) ? fromCwd : resolve(clientDir, p)
256
+ metaPaths.set(p, abs)
257
+ }
258
+ return abs
259
+ }
260
+
261
+ // 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.
262
+ for (const output of clientResult.outputs) {
263
+ if (!output.path.endsWith('.js'))
264
+ continue
265
+ const js = await output.text()
266
+ if (!js.includes('process.env') && !js.includes('Bun.env'))
267
+ continue
268
+ const relFile = relPosix(clientDir, output.path)
269
+ const info = metafile?.outputs[relFile] ?? metafile?.outputs[`./${relFile}`]
270
+ for (const [inKey, input] of Object.entries(info?.inputs ?? {})) {
271
+ if (input.bytesInOutput <= 0)
272
+ continue
273
+ const abs = resolveMetaPath(inKey)
274
+ let program = graph.analyses.get(abs)?.program
275
+ if (program === undefined && existsSync(abs) && isTsFile(abs) && !/[\\/]node_modules[\\/]/.test(abs)) {
276
+ try {
277
+ program = graph.load(abs).program
278
+ }
279
+ catch {}
280
+ }
281
+ if (program !== undefined && readsPrivateEnv(program, inlinedEnvKey))
282
+ clientLeaks.add(`${relPosix(root, abs)} reads process.env or Bun.env (only a process.env.PUBLIC_* set at build time is inlined)`)
283
+ }
284
+ }
285
+ if (clientLeaks.size > 0)
286
+ throw clientLeakError(clientLeaks)
287
+
288
+ for (const [outKey, info] of Object.entries(metafile?.outputs ?? {})) {
289
+ const relOut = outKey.replace(LEADING_DOT_SLASH_RE, '')
290
+ const url = `${assetPrefix}/${relOut}`
291
+ const entry = info.entryPoint === undefined ? undefined : resolveMetaPath(info.entryPoint)
292
+ const entryKey = entry === undefined ? undefined : islandEntryToKey.get(entry)
293
+ if (entryKey !== undefined && relOut.endsWith('.js'))
294
+ result.islandChunks.set(entryKey, url)
295
+ if (relOut.endsWith('.css')) {
296
+ if (entry?.endsWith('.css'))
297
+ result.srcCssToUrl.set(entry, url)
298
+ for (const inKey of Object.keys(info.inputs ?? {})) {
299
+ if (inKey.endsWith('.css'))
300
+ result.srcCssToUrl.set(resolveMetaPath(inKey), url)
301
+ }
302
+ }
303
+ const cssBundle = (info as { cssBundle?: string }).cssBundle
304
+ if (cssBundle !== undefined && entryKey !== undefined)
305
+ result.islandCssUrl.set(entryKey, `${assetPrefix}/${cssBundle.replace(LEADING_DOT_SLASH_RE, '')}`)
306
+ }
307
+
308
+ for (const output of clientResult.outputs) {
309
+ const relFile = relPosix(clientDir, output.path)
310
+ result.assetFiles.push(relFile)
311
+ const url = `${assetPrefix}/${relFile}`
312
+ if (relFile.endsWith('.css'))
313
+ result.styleUrls.push(url)
314
+ else if (output.kind === 'entry-point' && relFile.startsWith('runtime-'))
315
+ result.runtimeScript = url
316
+ }
317
+ return result
318
+ }
319
+
320
+ export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>): Promise<void> {
321
+ const { root, outDir, serverDir, graph, cache, islands } = env
322
+ const transforms = pluginTransforms(env.plugins)
323
+ const externalOutDir = isOutsideRoot(root, outDir)
324
+
325
+ // Whether a file renders components, directly or through what it imports: such packages are bundled so Kay's SSR compiler transforms them.
326
+ const tsxReach = new Map<string, boolean>()
327
+ const reachesTsx = (file: string, visiting = new Set<string>()): boolean => {
328
+ const known = tsxReach.get(file)
329
+ if (known !== undefined)
330
+ return known
331
+ if (file.endsWith('.tsx'))
332
+ return true
333
+ if (visiting.has(file))
334
+ return false
335
+ visiting.add(file)
336
+ const reaches = graph.localDeps(file).some(dep => reachesTsx(dep, visiting))
337
+ // Only memoize at the top-level walk (when no cycle ancestor could have truncated a branch).
338
+ if (reaches || visiting.size === 1)
339
+ tsxReach.set(file, reaches)
340
+ return reaches
341
+ }
342
+
343
+ const serverPlugin: BunPlugin = {
344
+ name: 'kay-v2-server',
345
+ setup(b) {
346
+ b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
347
+ const resolved = resolveKaySpecifier(args.path)
348
+ if (resolved === undefined)
349
+ return undefined
350
+ return EXTERNAL_KAY_SUBPATHS.has(args.path.replace(KAY_SCOPE_RE, '')) ? { path: resolved, external: true } : { path: resolved }
351
+ })
352
+ b.onResolve({ filter: KAY_SCOPE_RE }, (args) => {
353
+ try {
354
+ return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
355
+ }
356
+ catch {
357
+ return undefined
358
+ }
359
+ })
360
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
361
+ if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
362
+ return undefined
363
+ let resolved: string | undefined
364
+ try {
365
+ resolved = Bun.resolveSync(args.path, args.resolveDir || root)
366
+ }
367
+ catch {
368
+ try {
369
+ resolved = Bun.resolveSync(args.path, root)
370
+ }
371
+ catch {
372
+ return undefined
373
+ }
374
+ }
375
+ if (resolved.endsWith('.tsx') || reachesTsx(resolved))
376
+ return { path: resolved }
377
+ if (externalOutDir)
378
+ return { path: resolved, external: true }
379
+ return undefined
380
+ })
381
+ b.onLoad({ filter: TS_FILTER }, (args) => {
382
+ if (!args.path.endsWith('.tsx')) {
383
+ if (!transforms.active || args.path.includes('/node_modules/'))
384
+ return undefined
385
+ const raw = graph.source(args.path)
386
+ const transformed = transforms.apply(raw, args.path, 'server')
387
+ return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
388
+ }
389
+ const analysis = graph.analyses.get(args.path)
390
+ const rawBindings = islands.pageBindings.get(args.path)
391
+ const isInteractive = analysis?.isInteractive === true
392
+ const emitMarkers = isInteractive || islands.reach.has(args.path)
393
+ let islandMap: Map<string, IslandBinding> | undefined
394
+ let key = `${isInteractive ? '1' : '0'}:${emitMarkers ? '1' : '0'}|t=${transforms.key}`
395
+ if (rawBindings !== undefined) {
396
+ islandMap = new Map()
397
+ for (const [localName, target] of rawBindings) {
398
+ const chunk = islandChunks.get(islandKey(target))
399
+ if (chunk !== undefined) {
400
+ islandMap.set(localName, { id: target.id, chunk, defaultHydrate: target.defaultHydrate })
401
+ key += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
402
+ }
403
+ }
404
+ }
405
+ const stamp = graph.stamp(args.path)
406
+ const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
407
+ if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === key)
408
+ return { contents: cachedSsr.code, loader: 'tsx' }
409
+ const compiled = compileSsr(args.path, graph.source(args.path), {
410
+ analysis,
411
+ islands: islandMap,
412
+ isIsland: isInteractive,
413
+ emitMarkers,
414
+ } as Parameters<typeof compileSsr>[2])
415
+ const code = transforms.apply(compiled.code, args.path, 'server')
416
+ if (cache !== undefined && stamp !== undefined)
417
+ cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code })
418
+ return { contents: code, loader: 'tsx' }
419
+ })
420
+ },
421
+ }
422
+
423
+ const serverResult = await Bun.build({
424
+ entrypoints: entries,
425
+ outdir: serverDir,
426
+ root: serverRoot,
427
+ target: 'bun',
428
+ format: 'esm',
429
+ splitting: true,
430
+ packages: 'external',
431
+ minify: false,
432
+ define: {
433
+ 'process.env.NODE_ENV': 'process.env.NODE_ENV',
434
+ },
435
+ plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
436
+ })
437
+
438
+ if (!serverResult.success) {
439
+ const msgs = serverResult.logs.map(l => l.message).join('\n')
440
+ throw new Error(`kay build (server) failed:\n${msgs}`)
441
+ }
442
+ }
@@ -21,7 +21,10 @@ export interface CompileExecutableOptions {
21
21
  export async function compileExecutable(opts: CompileExecutableOptions): Promise<void> {
22
22
  const { root, outDir, clientDir, manifest, assetPrefix, outfile, kaySrcRoot, resolveKaySpecifier, bunPlugins = [] } = opts
23
23
  const entryPath = join(outDir, '__compile_entry.ts')
24
- const imports: string[] = []
24
+ const prodEnvPath = join(outDir, '__compile_prod_env.ts')
25
+ // Evaluated first via ESM static import order so `kay.config.ts` and route modules see NODE_ENV=production!
26
+ writeFileSync(prodEnvPath, `const _envKey = 'NODE_ENV';\nprocess.env[_envKey] ??= 'production';\n`)
27
+ const imports: string[] = [`import ${JSON.stringify(prodEnvPath)};`]
25
28
  const modEntries: string[] = []
26
29
  const seenFiles = new Set<string>()
27
30
  let idx = 0
@@ -93,15 +96,11 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
93
96
  }
94
97
  }
95
98
 
96
- const cfgSpread = hasConfig
97
- ? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, trustProxy: _kayConfig?.trustProxy, maxRequestBodySize: _kayConfig?.maxRequestBodySize, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
98
- : ''
99
+ const cfgSpread = hasConfig ? `...pickRuntimeConfig(_kayConfig), ` : ''
99
100
 
100
- // Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
101
101
  const code = [
102
- `import { createServerFromEmbedded } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
103
102
  ...imports,
104
- `const _envKey = 'NODE_ENV'; process.env[_envKey] ??= 'production';`,
103
+ `import { createServerFromEmbedded, pickRuntimeConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
105
104
  `const manifest = ${JSON.stringify(manifest)};`,
106
105
  `const modules = { ${modEntries.join(', ')} };`,
107
106
  `const assets = { ${embeddedAssets.join(', ')} };`,
@@ -109,10 +108,10 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
109
108
  `const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
110
109
  `const prerendered = {};`,
111
110
  `const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
112
- `const port = Number(process.env.PORT ?? ${hasConfig ? '_kayConfig?.port ?? ' : ''}3000);`,
111
+ `const port = Number(process.env.PORT || ${hasConfig ? '_kayConfig?.port || ' : ''}3000);`,
113
112
  `const hostname = process.env.HOST || undefined;`,
114
- `if (Bun.argv.includes('--health')) { const r = await fetch(\`http://\${hostname ?? '127.0.0.1'}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
115
- `const app = await createServerFromEmbedded({ manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)}${cfgSpread} });`,
113
+ `if (Bun.argv.includes('--health')) { const probeHost = !hostname || hostname === '0.0.0.0' || hostname === '::' ? '127.0.0.1' : hostname; const r = await fetch(\`http://\${probeHost}:\${port}/\`).catch(() => null); process.exit(r && r.status < 500 ? 0 : 1); }`,
114
+ `const app = await createServerFromEmbedded({ ${cfgSpread}manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)} });`,
116
115
  `const server = app.serve(port, hostname);`,
117
116
  `console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
118
117
  ].join('\n')
@@ -141,5 +140,6 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
141
140
  }
142
141
  finally {
143
142
  rmSync(entryPath, { force: true })
143
+ rmSync(prodEnvPath, { force: true })
144
144
  }
145
145
  }
@@ -0,0 +1,136 @@
1
+ // File-system helpers of the build: directory walks, the outDir safety check, and precompressed sidecars.
2
+
3
+ import type { Dirent } from 'node:fs'
4
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs'
5
+ import { tmpdir } from 'node:os'
6
+ import { dirname, extname, isAbsolute, join, relative, resolve } from 'node:path'
7
+ import { brotliCompressSync, constants as zlibConstants } from 'node:zlib'
8
+
9
+ const TEST_FILE_RE = /\.(?:test|spec)\.(?:tsx|ts)$/
10
+ const BACKSLASH_RE = /\\/g
11
+ const COMPRESSIBLE_EXTS = new Set(['.html', '.js', '.mjs', '.css', '.svg', '.xml', '.json', '.txt', '.webmanifest', '.wasm'])
12
+
13
+ /** `relative(from, to)` with forward slashes, the form manifests and messages use. */
14
+ export function relPosix(from: string, to: string): string {
15
+ return relative(from, to).replace(BACKSLASH_RE, '/')
16
+ }
17
+
18
+ export function isTsFile(file: string): boolean {
19
+ return file.endsWith('.tsx') || file.endsWith('.ts')
20
+ }
21
+
22
+ /** The size of a file in bytes, or undefined when it does not exist. */
23
+ export function fileSize(file: string): number | undefined {
24
+ try {
25
+ return statSync(file).size
26
+ }
27
+ catch {
28
+ return undefined
29
+ }
30
+ }
31
+
32
+ interface WalkOptions {
33
+ skipDir?: (name: string) => boolean
34
+ keep?: (entry: Dirent) => boolean
35
+ }
36
+
37
+ /** Every kept file under `dir`, depth first; a missing `dir` is empty. */
38
+ export function walkFiles(dir: string, options: WalkOptions = {}, out: string[] = []): string[] {
39
+ if (!existsSync(dir))
40
+ return out
41
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
42
+ const full = join(dir, entry.name)
43
+ if (entry.isDirectory()) {
44
+ if (options.skipDir?.(entry.name) !== true)
45
+ walkFiles(full, options, out)
46
+ }
47
+ else if (options.keep === undefined || options.keep(entry)) {
48
+ out.push(full)
49
+ }
50
+ }
51
+ return out
52
+ }
53
+
54
+ /** Route sources: `.ts`/`.tsx` outside `_`-prefixed folders, without declarations and tests. */
55
+ export function walkRoutes(dir: string): string[] {
56
+ return walkFiles(dir, {
57
+ skipDir: name => name.startsWith('_'),
58
+ keep: entry => isTsFile(entry.name) && !entry.name.endsWith('.d.ts') && !TEST_FILE_RE.test(entry.name),
59
+ })
60
+ }
61
+
62
+ export function walkAllFiles(dir: string): string[] {
63
+ return walkFiles(dir, { keep: entry => entry.isFile() })
64
+ }
65
+
66
+ function isOutside(base: string, target: string): boolean {
67
+ const rel = relative(base, target)
68
+ return rel === '..' || rel.startsWith('../') || rel.startsWith('..\\') || isAbsolute(rel)
69
+ }
70
+
71
+ function isStrictDescendant(base: string, target: string): boolean {
72
+ return relative(base, target) !== '' && !isOutside(base, target)
73
+ }
74
+
75
+ export function isOutsideRoot(root: string, outDir: string): boolean {
76
+ const rel = relative(root, outDir)
77
+ return rel !== '' && (rel.startsWith('..') || isAbsolute(rel))
78
+ }
79
+
80
+ export function assertSafeOutDir(root: string, outDir: string, routesDir: string, publicDir: string): void {
81
+ // Refuse filesystem root, home dir, tmpdir root, or root/ancestors of root
82
+ if (dirname(outDir) === outDir || outDir === tmpdir() || outDir === resolve(process.env.HOME ?? '\0')) {
83
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — cannot wipe a root or shared system directory.`)
84
+ }
85
+ if (!isOutside(outDir, root)) {
86
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — outDir cannot be or contain project root "${root}".`)
87
+ }
88
+ if (existsSync(outDir)) {
89
+ try {
90
+ const realRoot = realpathSync(root)
91
+ const realOut = realpathSync(outDir)
92
+ if (dirname(realOut) === realOut || !isOutside(realOut, realRoot)) {
93
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — resolved target "${realOut}" is or contains project root "${realRoot}".`)
94
+ }
95
+ }
96
+ catch (err) {
97
+ if (err instanceof Error && err.message.startsWith('kay build: refusing unsafe outDir'))
98
+ throw err
99
+ }
100
+ }
101
+ const protectedTargets: [string, string][] = [
102
+ ['src', resolve(root, 'src')],
103
+ ['routesDir', routesDir],
104
+ ['publicDir', publicDir],
105
+ ['kay.config.ts', resolve(root, 'kay.config.ts')],
106
+ ['package.json', resolve(root, 'package.json')],
107
+ ]
108
+ for (const [label, target] of protectedTargets) {
109
+ if (!isOutside(outDir, target)) {
110
+ throw new Error(`kay build: refusing unsafe outDir "${outDir}" — it equals or contains protected path ${label} ("${target}").`)
111
+ }
112
+ }
113
+ // If outDir is outside root (e.g. an external temp build dir), refuse it if it looks like another project directory.
114
+ if (!isStrictDescendant(root, outDir) && existsSync(outDir)) {
115
+ for (const marker of ['package.json', 'kay.config.ts', 'src']) {
116
+ if (existsSync(join(outDir, marker))) {
117
+ throw new Error(`kay build: refusing unsafe external outDir "${outDir}" — it contains "${marker}".`)
118
+ }
119
+ }
120
+ }
121
+ }
122
+
123
+ /** Writes `.br` and `.gz` sidecars next to a compressible file of at least `minBytes`, when they come out smaller. */
124
+ export function precompressFile(abs: string, minBytes: number): void {
125
+ if (!COMPRESSIBLE_EXTS.has(extname(abs).toLowerCase()))
126
+ return
127
+ const raw = readFileSync(abs)
128
+ if (raw.byteLength < minBytes)
129
+ return
130
+ const br = brotliCompressSync(raw, { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: 6 } })
131
+ if (br.byteLength < raw.byteLength)
132
+ writeFileSync(`${abs}.br`, br)
133
+ const gz = Bun.gzipSync(raw, { level: 9 })
134
+ if (gz.byteLength < raw.byteLength)
135
+ writeFileSync(`${abs}.gz`, gz)
136
+ }