@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.
- package/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +20 -11
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +231 -1296
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +298 -79
- package/src/cli/new.ts +67 -35
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +822 -629
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +390 -324
- package/src/context.ts +120 -0
- package/src/dev/index.ts +291 -76
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +157 -84
- package/src/dom/index.ts +154 -33
- package/src/dom/island.ts +117 -39
- package/src/dom/loop.ts +34 -21
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +120 -17
- package/src/reactivity/index.ts +250 -157
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +37 -12
- package/src/server/action.ts +217 -74
- package/src/server/compress.ts +155 -56
- package/src/server/cookies.ts +59 -22
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +201 -33
- package/src/server/index.ts +964 -737
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +27 -8
- package/src/server/security.ts +87 -39
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +96 -10
- package/src/ssr/index.ts +225 -56
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -0
- 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-
|
|
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
|
+
}
|
package/src/build/compile.ts
CHANGED
|
@@ -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
|
|
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
|
|
@@ -56,9 +59,18 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
56
59
|
const embeddedAssets: string[] = []
|
|
57
60
|
let assetIdx = 0
|
|
58
61
|
for (const rel of manifest.assets) {
|
|
62
|
+
const abs = join(clientDir, rel)
|
|
59
63
|
const v = `_a${assetIdx++}`
|
|
60
|
-
imports.push(`import ${v} from ${JSON.stringify(
|
|
64
|
+
imports.push(`import ${v} from ${JSON.stringify(abs)} with { type: "file" };`)
|
|
61
65
|
embeddedAssets.push(`${JSON.stringify(rel)}: ${v}`)
|
|
66
|
+
for (const ext of ['.br', '.gz'] as const) {
|
|
67
|
+
const sidecarAbs = `${abs}${ext}`
|
|
68
|
+
if (existsSync(sidecarAbs)) {
|
|
69
|
+
const sv = `_a${assetIdx++}`
|
|
70
|
+
imports.push(`import ${sv} from ${JSON.stringify(sidecarAbs)} with { type: "file" };`)
|
|
71
|
+
embeddedAssets.push(`${JSON.stringify(`${rel}${ext}`)}: ${sv}`)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
62
74
|
}
|
|
63
75
|
const embeddedPublic: string[] = []
|
|
64
76
|
const embeddedPublicEtags: string[] = []
|
|
@@ -84,15 +96,11 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
84
96
|
}
|
|
85
97
|
}
|
|
86
98
|
|
|
87
|
-
const cfgSpread = hasConfig
|
|
88
|
-
? `, plugins: _kayConfig?.plugins, lang: _kayConfig?.lang, security: _kayConfig?.security, trustedOrigins: _kayConfig?.trustedOrigins, compress: _kayConfig?.compress, onError: _kayConfig?.onError`
|
|
89
|
-
: ''
|
|
99
|
+
const cfgSpread = hasConfig ? `...pickRuntimeConfig(_kayConfig), ` : ''
|
|
90
100
|
|
|
91
|
-
// Default NODE_ENV to 'production' in compiled binaries (dynamic key avoids Bun.build constant-folding).
|
|
92
101
|
const code = [
|
|
93
|
-
`import { createServerFromEmbedded } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
|
|
94
102
|
...imports,
|
|
95
|
-
`
|
|
103
|
+
`import { createServerFromEmbedded, pickRuntimeConfig } from ${JSON.stringify(join(kaySrcRoot, 'server/index.ts'))};`,
|
|
96
104
|
`const manifest = ${JSON.stringify(manifest)};`,
|
|
97
105
|
`const modules = { ${modEntries.join(', ')} };`,
|
|
98
106
|
`const assets = { ${embeddedAssets.join(', ')} };`,
|
|
@@ -100,10 +108,10 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
100
108
|
`const publicEtags = { ${embeddedPublicEtags.join(', ')} };`,
|
|
101
109
|
`const prerendered = {};`,
|
|
102
110
|
`const prerenderedFiles = { ${embeddedPrerenderedFiles.join(', ')} };`,
|
|
103
|
-
`const port = Number(process.env.PORT
|
|
111
|
+
`const port = Number(process.env.PORT || ${hasConfig ? '_kayConfig?.port || ' : ''}3000);`,
|
|
104
112
|
`const hostname = process.env.HOST || undefined;`,
|
|
105
|
-
`if (Bun.argv.includes('--health')) { const
|
|
106
|
-
`const app = await createServerFromEmbedded({ manifest, modules, assets, publicAssets, publicEtags, prerendered, prerenderedFiles, assetPrefix: ${JSON.stringify(assetPrefix)}
|
|
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)} });`,
|
|
107
115
|
`const server = app.serve(port, hostname);`,
|
|
108
116
|
`console.log(\`kay server listening on http://\${hostname ?? 'localhost'}:\${server.port}\`);`,
|
|
109
117
|
].join('\n')
|
|
@@ -132,5 +140,6 @@ export async function compileExecutable(opts: CompileExecutableOptions): Promise
|
|
|
132
140
|
}
|
|
133
141
|
finally {
|
|
134
142
|
rmSync(entryPath, { force: true })
|
|
143
|
+
rmSync(prodEnvPath, { force: true })
|
|
135
144
|
}
|
|
136
145
|
}
|