@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.3
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 +617 -0
- package/src/build/compile.ts +27 -51
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +272 -1466
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +229 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +102 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +339 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +61 -0
- package/src/plugins/index.ts +10 -123
- package/src/plugins/load.ts +38 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/services.ts +23 -0
- package/src/plugins/types.ts +197 -0
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action-registry.ts +72 -0
- package/src/server/action.ts +157 -79
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/document.ts +192 -0
- package/src/server/env.ts +18 -13
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +203 -77
- package/src/server/index.ts +420 -973
- package/src/server/loader.ts +113 -0
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +90 -59
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +163 -0
- package/src/server/stream.ts +94 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +24 -18
- 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.
|
|
3
|
+
"version": "2.0.0-beta.3",
|
|
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,617 @@
|
|
|
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
|
+
/** `entry` is the generated `_entry.js`, an in-memory file bundled beside `entries` so it shares their chunks. */
|
|
429
|
+
export async function buildServer(env: BundleEnv, entries: string[], serverRoot: string, islandChunks: Map<string, string>, entry: { file: string, source: string }): Promise<void> {
|
|
430
|
+
const { root, outDir, serverDir, graph, cache, islands } = env
|
|
431
|
+
const transforms = pluginTransforms(env.plugins)
|
|
432
|
+
const externalOutDir = isOutsideRoot(root, outDir)
|
|
433
|
+
|
|
434
|
+
const serverSignature = cache !== undefined
|
|
435
|
+
? JSON.stringify({
|
|
436
|
+
serverRoot,
|
|
437
|
+
assetPrefix: env.assetPrefix,
|
|
438
|
+
isDev: env.isDev,
|
|
439
|
+
transforms: transforms.key,
|
|
440
|
+
entries: [...entries].sort(),
|
|
441
|
+
islandChunks: [...islandChunks.entries()].sort(([a], [b]) => a.localeCompare(b)),
|
|
442
|
+
reach: [...islands.reach].sort(),
|
|
443
|
+
bindings: [...islands.pageBindings.entries()]
|
|
444
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
445
|
+
.map(([f, map]) => [f, [...map.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([l, t]) => [l, t.id, t.defaultHydrate ?? ''])]),
|
|
446
|
+
bunPlugins: env.plugins.filter(p => p.bunPlugins !== undefined).map(p => p.name),
|
|
447
|
+
})
|
|
448
|
+
: ''
|
|
449
|
+
|
|
450
|
+
if (
|
|
451
|
+
cache !== undefined
|
|
452
|
+
&& cache.lastServer !== undefined
|
|
453
|
+
&& cache.lastServer.signature === serverSignature
|
|
454
|
+
&& stampsMatch(cache.lastServer.inputStamps)
|
|
455
|
+
&& reuseDirFiles(cache.lastServer.serverDir, serverDir)
|
|
456
|
+
) {
|
|
457
|
+
cache.stats.serverSkips++
|
|
458
|
+
cache.lastServer.serverDir = serverDir
|
|
459
|
+
return
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
// Whether a file renders components, directly or through what it imports: such packages are bundled so Kay's SSR compiler transforms them.
|
|
463
|
+
const tsxReach = new Map<string, boolean>()
|
|
464
|
+
const reachesTsx = (file: string, visiting = new Set<string>()): boolean => {
|
|
465
|
+
const known = tsxReach.get(file)
|
|
466
|
+
if (known !== undefined)
|
|
467
|
+
return known
|
|
468
|
+
if (file.endsWith('.tsx'))
|
|
469
|
+
return true
|
|
470
|
+
if (visiting.has(file))
|
|
471
|
+
return false
|
|
472
|
+
visiting.add(file)
|
|
473
|
+
const reaches = graph.localDeps(file).some(dep => reachesTsx(dep, visiting))
|
|
474
|
+
// Only memoize at the top-level walk (when no cycle ancestor could have truncated a branch).
|
|
475
|
+
if (reaches || visiting.size === 1)
|
|
476
|
+
tsxReach.set(file, reaches)
|
|
477
|
+
return reaches
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const serverPlugin: BunPlugin = {
|
|
481
|
+
name: 'kay-v2-server',
|
|
482
|
+
setup(b) {
|
|
483
|
+
b.onResolve({ filter: KAY_SPECIFIER_FILTER }, (args) => {
|
|
484
|
+
const resolved = resolveKaySpecifier(args.path)
|
|
485
|
+
if (resolved === undefined)
|
|
486
|
+
return undefined
|
|
487
|
+
return EXTERNAL_KAY_SUBPATHS.has(args.path.replace(KAY_SCOPE_RE, '')) ? { path: resolved, external: true } : { path: resolved }
|
|
488
|
+
})
|
|
489
|
+
b.onResolve({ filter: KAY_SCOPE_RE }, (args) => {
|
|
490
|
+
try {
|
|
491
|
+
return { path: Bun.resolveSync(args.path, args.resolveDir || root) }
|
|
492
|
+
}
|
|
493
|
+
catch {
|
|
494
|
+
return undefined
|
|
495
|
+
}
|
|
496
|
+
})
|
|
497
|
+
b.onResolve({ filter: /^[^./]/ }, (args) => {
|
|
498
|
+
if (args.path === 'bun' || args.path.startsWith('bun:') || args.path.startsWith('node:') || args.path.startsWith('~') || isAbsolute(args.path))
|
|
499
|
+
return undefined
|
|
500
|
+
let resolved: string | undefined
|
|
501
|
+
try {
|
|
502
|
+
resolved = Bun.resolveSync(args.path, args.resolveDir || root)
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
try {
|
|
506
|
+
resolved = Bun.resolveSync(args.path, root)
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
return undefined
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (resolved.endsWith('.tsx') || reachesTsx(resolved))
|
|
513
|
+
return { path: resolved }
|
|
514
|
+
if (env.isDev && isTsFile(resolved)) {
|
|
515
|
+
try {
|
|
516
|
+
const real = realpathSync(resolved)
|
|
517
|
+
if (!real.includes('/node_modules/') && !real.includes('\\node_modules\\'))
|
|
518
|
+
return { path: resolved }
|
|
519
|
+
}
|
|
520
|
+
catch {}
|
|
521
|
+
}
|
|
522
|
+
if (externalOutDir)
|
|
523
|
+
return { path: resolved, external: true }
|
|
524
|
+
return undefined
|
|
525
|
+
})
|
|
526
|
+
b.onLoad({ filter: TS_FILTER }, (args) => {
|
|
527
|
+
if (!args.path.endsWith('.tsx')) {
|
|
528
|
+
if (!transforms.active || args.path.includes('/node_modules/'))
|
|
529
|
+
return undefined
|
|
530
|
+
const raw = graph.source(args.path)
|
|
531
|
+
const transformed = transforms.apply(raw, args.path, 'server')
|
|
532
|
+
return transformed !== raw ? { contents: transformed, loader: 'ts' } : undefined
|
|
533
|
+
}
|
|
534
|
+
const analysis = graph.analyses.get(args.path)
|
|
535
|
+
const rawBindings = islands.pageBindings.get(args.path)
|
|
536
|
+
const isInteractive = analysis?.isInteractive === true
|
|
537
|
+
const emitMarkers = isInteractive || islands.reach.has(args.path)
|
|
538
|
+
let islandMap: Map<string, IslandBinding> | undefined
|
|
539
|
+
let key = `${isInteractive ? '1' : '0'}:${emitMarkers ? '1' : '0'}|t=${transforms.key}`
|
|
540
|
+
if (rawBindings !== undefined) {
|
|
541
|
+
islandMap = new Map()
|
|
542
|
+
for (const [localName, target] of rawBindings) {
|
|
543
|
+
const chunk = islandChunks.get(islandKey(target))
|
|
544
|
+
if (chunk !== undefined) {
|
|
545
|
+
islandMap.set(localName, { id: target.id, chunk, defaultHydrate: target.defaultHydrate })
|
|
546
|
+
key += `|${localName}=${chunk}:${target.defaultHydrate ?? ''}`
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const stamp = graph.stamp(args.path)
|
|
551
|
+
const cachedSsr = stamp !== undefined ? cache?.ssrCompiled.get(args.path) : undefined
|
|
552
|
+
if (cachedSsr !== undefined && cachedSsr.mtimeMs === stamp!.mtimeMs && cachedSsr.size === stamp!.size && cachedSsr.key === key)
|
|
553
|
+
return { contents: cachedSsr.code, loader: 'tsx' }
|
|
554
|
+
const compiled = compileSsr(args.path, graph.source(args.path), {
|
|
555
|
+
analysis,
|
|
556
|
+
islands: islandMap,
|
|
557
|
+
isIsland: isInteractive,
|
|
558
|
+
emitMarkers,
|
|
559
|
+
} as Parameters<typeof compileSsr>[2])
|
|
560
|
+
const code = transforms.apply(compiled.code, args.path, 'server')
|
|
561
|
+
if (cache !== undefined && stamp !== undefined)
|
|
562
|
+
cache.ssrCompiled.set(args.path, { mtimeMs: stamp.mtimeMs, size: stamp.size, key, code })
|
|
563
|
+
return { contents: code, loader: 'tsx' }
|
|
564
|
+
})
|
|
565
|
+
},
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
let serverResult: Awaited<ReturnType<typeof Bun.build>>
|
|
569
|
+
try {
|
|
570
|
+
serverResult = await Bun.build({
|
|
571
|
+
entrypoints: [...entries, entry.file],
|
|
572
|
+
files: { [entry.file]: entry.source },
|
|
573
|
+
outdir: serverDir,
|
|
574
|
+
root: serverRoot,
|
|
575
|
+
target: 'bun',
|
|
576
|
+
format: 'esm',
|
|
577
|
+
splitting: true,
|
|
578
|
+
packages: 'external',
|
|
579
|
+
minify: false,
|
|
580
|
+
metafile: cache !== undefined,
|
|
581
|
+
define: {
|
|
582
|
+
'process.env.NODE_ENV': 'process.env.NODE_ENV',
|
|
583
|
+
},
|
|
584
|
+
plugins: [serverPlugin, ...pluginBunPlugins(env, 'server')],
|
|
585
|
+
})
|
|
586
|
+
}
|
|
587
|
+
catch (err) {
|
|
588
|
+
if (err instanceof AggregateError && err.errors.length > 0)
|
|
589
|
+
throw new Error(`kay build (server) failed:\n${formatBunBuildLogs(err.errors, env.root)}`)
|
|
590
|
+
throw err
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (!serverResult.success) {
|
|
594
|
+
const msgs = formatBunBuildLogs(serverResult.logs, env.root)
|
|
595
|
+
throw new Error(`kay build (server) failed:\n${msgs}`)
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
if (cache !== undefined) {
|
|
599
|
+
cache.stats.serverBuilds++
|
|
600
|
+
const inputFiles = new Set<string>(entries)
|
|
601
|
+
for (const inKey of Object.keys(serverResult.metafile?.inputs ?? {})) {
|
|
602
|
+
const fromCwd = resolve(process.cwd(), inKey)
|
|
603
|
+
const abs = existsSync(fromCwd) ? fromCwd : resolve(serverDir, inKey)
|
|
604
|
+
if (!existsSync(abs))
|
|
605
|
+
continue
|
|
606
|
+
// Plain `.css` stylesheets are bundled exclusively by `buildClient`; CSS edits must not trigger a server rebuild.
|
|
607
|
+
if (abs.endsWith('.css') && !abs.endsWith('.module.css'))
|
|
608
|
+
continue
|
|
609
|
+
inputFiles.add(abs)
|
|
610
|
+
}
|
|
611
|
+
cache.lastServer = {
|
|
612
|
+
signature: serverSignature,
|
|
613
|
+
serverDir,
|
|
614
|
+
inputStamps: stampFiles(inputFiles),
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|