@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.
Files changed (69) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +617 -0
  4. package/src/build/compile.ts +27 -51
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +272 -1466
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +229 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +102 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/server-entry.ts +38 -0
  16. package/src/build/static.ts +73 -0
  17. package/src/cli/check.ts +300 -129
  18. package/src/cli/index.ts +297 -94
  19. package/src/cli/new.ts +58 -38
  20. package/src/compiler/analyze.ts +723 -93
  21. package/src/compiler/dom.ts +848 -762
  22. package/src/compiler/mistakes.ts +354 -0
  23. package/src/compiler/patch.ts +1 -1
  24. package/src/compiler/server-only.ts +172 -23
  25. package/src/compiler/shared.ts +485 -0
  26. package/src/compiler/ssr.ts +331 -342
  27. package/src/context.ts +120 -0
  28. package/src/dev/index.ts +339 -76
  29. package/src/dom/action.ts +114 -14
  30. package/src/dom/extras.ts +121 -83
  31. package/src/dom/index.ts +122 -80
  32. package/src/dom/island.ts +71 -36
  33. package/src/dom/loop.ts +28 -20
  34. package/src/index.ts +5 -1
  35. package/src/jsx-runtime.ts +432 -93
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +61 -0
  38. package/src/plugins/index.ts +10 -123
  39. package/src/plugins/load.ts +38 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/services.ts +23 -0
  42. package/src/plugins/types.ts +197 -0
  43. package/src/reactivity/index.ts +237 -213
  44. package/src/reactivity/selector.ts +11 -9
  45. package/src/reactivity/store.ts +36 -11
  46. package/src/server/action-registry.ts +72 -0
  47. package/src/server/action.ts +157 -79
  48. package/src/server/app-entry.ts +23 -0
  49. package/src/server/assets.ts +182 -0
  50. package/src/server/compress.ts +197 -104
  51. package/src/server/cookies.ts +46 -16
  52. package/src/server/document.ts +192 -0
  53. package/src/server/env.ts +18 -13
  54. package/src/server/errors.ts +123 -0
  55. package/src/server/http.ts +203 -77
  56. package/src/server/index.ts +420 -973
  57. package/src/server/loader.ts +113 -0
  58. package/src/server/page.ts +107 -0
  59. package/src/server/plugin-host.ts +167 -0
  60. package/src/server/router.ts +69 -26
  61. package/src/server/security.ts +90 -59
  62. package/src/server/standard-schema.ts +42 -11
  63. package/src/server/static-dir.ts +163 -0
  64. package/src/server/stream.ts +94 -0
  65. package/src/ssr/context.ts +95 -10
  66. package/src/ssr/index.ts +167 -66
  67. package/src/style.ts +33 -0
  68. package/src/test/index.ts +24 -18
  69. package/src/unrenderable.ts +35 -0
@@ -0,0 +1,177 @@
1
+ // Island discovery: which exports run in the browser, which modules render them, and the checks that keep server code out of them.
2
+
3
+ import type { ModuleGraph } from './graph'
4
+ import { basename, extname } from 'node:path'
5
+ import { asyncInteractiveError } from '../compiler/analyze'
6
+ import { isTsFile, relPosix } from './files'
7
+
8
+ export interface IslandTarget {
9
+ id: string
10
+ file: string
11
+ exportName: string
12
+ defaultHydrate: string | undefined
13
+ }
14
+
15
+ export type ActionsByFile = Map<string, { exportName: string, url: string }[]>
16
+
17
+ export interface IslandPlan {
18
+ /** Island roots keyed `file#exportName`. */
19
+ targets: Map<string, IslandTarget>
20
+ /** Per static module, the island each rendered tag stands for. */
21
+ pageBindings: Map<string, Map<string, IslandTarget>>
22
+ /** CSS files imported (transitively) by an island: bundled with it, not as standalone styles. */
23
+ cssFiles: Set<string>
24
+ /** Modules the client compiles for an island, whose SSR must emit hydration markers too. */
25
+ reach: Set<string>
26
+ }
27
+
28
+ export function islandKey(target: { file: string, exportName: string }): string {
29
+ return `${target.file}#${target.exportName}`
30
+ }
31
+
32
+ export function planIslands(graph: ModuleGraph, root: string, pageFiles: string[], specialFiles: string[], actionsByFile: ActionsByFile): IslandPlan {
33
+ const { analyses } = graph
34
+ const targets = new Map<string, IslandTarget>()
35
+ const usedIds = new Set<string>()
36
+ const pageBindings = new Map<string, Map<string, IslandTarget>>()
37
+ const pageSet = new Set(pageFiles)
38
+
39
+ function registerIsland(file: string, exportName: string): IslandTarget {
40
+ const key = islandKey({ file, exportName })
41
+ const existing = targets.get(key)
42
+ if (existing !== undefined)
43
+ return existing
44
+ const baseName = basename(file, extname(file)).toLowerCase()
45
+ const expLower = exportName.toLowerCase()
46
+ let id = exportName === 'default' || expLower === baseName ? baseName : `${baseName}-${expLower}`
47
+ // The id names the entry file and the chunk: two islands sharing a basename keep it readable and add a hash of their path.
48
+ if (usedIds.has(id))
49
+ id = `${id}-${Bun.hash(relPosix(root, key)).toString(36).slice(0, 6)}`
50
+ usedIds.add(id)
51
+ const target: IslandTarget = { id, file, exportName, defaultHydrate: graph.load(file).defaultHydrate }
52
+ targets.set(key, target)
53
+ return target
54
+ }
55
+
56
+ // A component reading reactive state another module exports runs in the browser too. The promoted analysis lives in this build's map only, so the cached one still reflects the file alone.
57
+ for (const [file, analysis] of analyses) {
58
+ if (!file.endsWith('.tsx') || analysis.isInteractive)
59
+ continue
60
+ for (const imp of analysis.imports) {
61
+ const resolved = graph.resolve(file, imp.source)
62
+ const state = resolved === undefined || !isTsFile(resolved)
63
+ ? undefined
64
+ : imp.specifiers.find((spec) => {
65
+ if (analysis.jsxTags.has(spec.local))
66
+ return false
67
+ if (spec.imported === '*')
68
+ return graph.load(resolved).stateExports.length > 0
69
+ const target = graph.exportTarget(resolved, spec.imported)
70
+ return graph.load(target.file).stateExports.includes(target.exportName)
71
+ })
72
+ if (state !== undefined) {
73
+ const reason = `reads ${state.local} from '${imp.source}'`
74
+ if (analysis.hasAsyncDefault)
75
+ throw asyncInteractiveError(file, reason)
76
+ analyses.set(file, { ...analysis, isInteractive: true, interactiveReason: reason })
77
+ break
78
+ }
79
+ }
80
+ }
81
+
82
+ for (const [file, analysis] of analyses) {
83
+ if (!file.endsWith('.tsx'))
84
+ continue
85
+ if (analysis.isInteractive) {
86
+ if (pageSet.has(file))
87
+ registerIsland(file, 'default')
88
+ continue
89
+ }
90
+
91
+ // Only names rendered as tags become islands: `<Counter />`, or `<UI.Counter />` through a namespace import.
92
+ const bindings = new Map<string, IslandTarget>()
93
+ for (const imp of analysis.imports) {
94
+ const resolved = graph.resolve(file, imp.source)
95
+ if (resolved === undefined || !isTsFile(resolved))
96
+ continue
97
+ for (const spec of imp.specifiers) {
98
+ const tags = spec.imported === '*'
99
+ ? [...analysis.jsxTags].filter(tag => tag.startsWith(`${spec.local}.`) && !tag.slice(spec.local.length + 1).includes('.')).map(tag => [tag, tag.slice(spec.local.length + 1)] as const)
100
+ : analysis.jsxTags.has(spec.local) ? [[spec.local, spec.imported] as const] : []
101
+ for (const [tag, exportName] of tags) {
102
+ const target = graph.exportTarget(resolved, exportName)
103
+ if (target.file.endsWith('.tsx') && graph.load(target.file).isInteractive)
104
+ bindings.set(tag, registerIsland(target.file, target.exportName))
105
+ }
106
+ }
107
+ }
108
+ if (bindings.size > 0)
109
+ pageBindings.set(file, bindings)
110
+ }
111
+
112
+ const isStubbedActionFile = (file: string): boolean =>
113
+ !analyses.get(file)?.isInteractive && actionsByFile.has(file)
114
+
115
+ // Component/page CSS & CSS Module imports reached from islands are bundled via island entrypoints.
116
+ const cssFiles = new Set<string>()
117
+ const cssSeen = new Set<string>()
118
+ const cssStack = [...targets.values()].map(t => t.file)
119
+ while (cssStack.length > 0) {
120
+ const file = cssStack.pop()!
121
+ if (cssSeen.has(file))
122
+ continue
123
+ cssSeen.add(file)
124
+ for (const imp of analyses.get(file)?.imports ?? []) {
125
+ const target = graph.resolve(file, imp.source)
126
+ if (target === undefined)
127
+ continue
128
+ if (target.endsWith('.css'))
129
+ cssFiles.add(target)
130
+ else if (isTsFile(target) && !isStubbedActionFile(target))
131
+ cssStack.push(target)
132
+ }
133
+ }
134
+
135
+ // A layout, error or 404 page renders on the server only, so interactivity written in it would never run.
136
+ for (const file of specialFiles) {
137
+ const analysis = analyses.get(file)
138
+ if (analysis?.isInteractive === true) {
139
+ const rel = relPosix(root, file)
140
+ throw new Error(`kay build: ${rel} uses browser interactivity (${analysis.interactiveReason}), but it renders on the server only. Move the interactive part into a component and render that component from ${rel}.`)
141
+ }
142
+ }
143
+
144
+ // The client compiles every module an island imports to hydrate against SSR markers, so their SSR must emit them too.
145
+ const reach = new Set<string>()
146
+ const reachSeen = new Set<string>()
147
+ const reachStack = [...targets.values()].map(t => t.file)
148
+ while (reachStack.length > 0) {
149
+ const file = reachStack.pop()!
150
+ if (reachSeen.has(file))
151
+ continue
152
+ reachSeen.add(file)
153
+ if (file.endsWith('.tsx'))
154
+ reach.add(file)
155
+ for (const dep of graph.localDeps(file)) {
156
+ if (!isStubbedActionFile(dep))
157
+ reachStack.push(dep)
158
+ }
159
+ const analysis = analyses.get(file)
160
+ for (const imp of analysis?.imports ?? []) {
161
+ // The client build swaps an action file for stubs of its actions, so any other export it has is missing there.
162
+ const target = graph.resolve(file, imp.source)
163
+ const actions = target !== undefined && isStubbedActionFile(target) ? actionsByFile.get(target) : undefined
164
+ const missing = actions !== undefined ? imp.specifiers.find(s => s.imported !== '*' && !actions.some(a => a.exportName === s.imported)) : undefined
165
+ if (missing !== undefined)
166
+ throw new Error(`kay build: ${relPosix(root, file)} runs in the browser and imports ${missing.imported} from ${relPosix(root, target!)}, a file of server actions: the browser only gets its actions. Move ${missing.imported} into a module without actions.`)
167
+ }
168
+ for (const re of analysis?.reexports ?? []) {
169
+ const target = graph.resolve(file, re.source)
170
+ const actions = target !== undefined && isStubbedActionFile(target) ? actionsByFile.get(target) : undefined
171
+ if (actions !== undefined && re.local !== '*' && !actions.some(a => a.exportName === re.local))
172
+ throw new Error(`kay build: ${relPosix(root, file)} runs in the browser and re-exports ${re.local} from ${relPosix(root, target!)}, a file of server actions: the browser only gets its actions. Move ${re.local} into a module without actions.`)
173
+ }
174
+ }
175
+
176
+ return { targets, pageBindings, cssFiles, reach }
177
+ }
@@ -0,0 +1,229 @@
1
+ // The build manifest: its shape, and the per-route entries (islands, styles, layouts, middlewares) computed from the module graph.
2
+
3
+ import type { ModuleGraph } from './graph'
4
+ import type { IslandPlan } from './islands'
5
+ import { join, relative } from 'node:path'
6
+ import { islandKey } from './islands'
7
+ import { ancestorFiles, fileToRoutePath, MIDDLEWARE_NAMES } from './routes'
8
+
9
+ export interface ActionManifestEntry {
10
+ url: string
11
+ file: string
12
+ exportName: string
13
+ /** `_middleware.ts` chain of the folder declaring the action, outermost first. */
14
+ middlewares: string[]
15
+ }
16
+
17
+ export interface RouteManifestEntry {
18
+ path: string
19
+ file: string
20
+ layouts: string[]
21
+ middlewares: string[]
22
+ hasLoad?: boolean | undefined
23
+ isIsland?: boolean | undefined
24
+ islandChunk?: string | undefined
25
+ islandHydrate?: string | undefined
26
+ /** Top-level keys of `load()` data statically read by a page island (`undefined` when `data` escapes). */
27
+ islandDataKeys?: string[] | undefined
28
+ islandChunks: string[]
29
+ eagerIslandChunks?: string[] | undefined
30
+ /** Per-route stylesheets (global plugin styles + CSS imported by this route, its layouts, and its islands). */
31
+ styles?: string[] | undefined
32
+ /** Per-route raw <head> HTML tags injected by plugins via `ctx.addRouteHead()`. */
33
+ headTags?: string[] | undefined
34
+ usesRenderContext?: boolean | undefined
35
+ prerender?: boolean | undefined
36
+ prerendered?: Record<string, string> | undefined
37
+ /** CSP hashes of the app's `<style>` blocks per prerendered URL, for the pages that have any. */
38
+ prerenderedStyleHashes?: Record<string, string[]> | undefined
39
+ }
40
+
41
+ export interface BuildManifest {
42
+ runtimeScript: string | undefined
43
+ styles: string[]
44
+ /** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
45
+ globalStyles?: string[] | undefined
46
+ headTags?: string[] | undefined
47
+ routes: RouteManifestEntry[]
48
+
49
+ /** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
50
+ rootLayoutFile?: string | undefined
51
+ errorFile?: string | undefined
52
+ notFoundFile?: string | undefined
53
+ actions: ActionManifestEntry[]
54
+ islands: Record<string, string>
55
+ assets: string[]
56
+ publicFiles: string[]
57
+ /** Serializable build-time metadata persisted by plugins via `ctx.setData()`, read via `api.getBuildData()`. */
58
+ pluginData?: Record<string, Record<string, unknown>> | undefined
59
+ }
60
+
61
+ interface FileReach {
62
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
63
+ chunks: Set<string>
64
+ eager: Set<string>
65
+ styles: Set<string>
66
+ usesRenderContext: boolean
67
+ }
68
+
69
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
70
+ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
71
+ const { analyses } = graph
72
+
73
+ function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
74
+ if (seen.has(file))
75
+ return
76
+ seen.add(file)
77
+ const analysis = analyses.get(file)
78
+ if (analysis === undefined)
79
+ return
80
+ if (analysis.isInteractive) {
81
+ const chunk = islandChunks.get(`${file}#default`)
82
+ if (chunk !== undefined) {
83
+ reach.chunks.add(chunk)
84
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
85
+ reach.eager.add(chunk)
86
+ }
87
+ return
88
+ }
89
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
90
+ const chunk = islandChunks.get(islandKey(target))
91
+ if (chunk === undefined)
92
+ continue
93
+ reach.chunks.add(chunk)
94
+ const isDeferred = analysis.deferredIslandTags.has(localName)
95
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
96
+ if (!isDeferred)
97
+ reach.eager.add(chunk)
98
+ }
99
+ for (const dep of graph.localDeps(file))
100
+ walkIslands(dep, seen, reach)
101
+ }
102
+
103
+ function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
104
+ if (seen.has(file))
105
+ return
106
+ seen.add(file)
107
+ const analysis = analyses.get(file)
108
+ if (analysis === undefined)
109
+ return
110
+ if (analysis.isInteractive) {
111
+ const islCss = islandCssUrl.get(`${file}#default`)
112
+ if (islCss !== undefined)
113
+ out.add(islCss)
114
+ }
115
+ for (const target of islands.pageBindings.get(file)?.values() ?? []) {
116
+ const islCss = islandCssUrl.get(islandKey(target))
117
+ if (islCss !== undefined)
118
+ out.add(islCss)
119
+ walkStyles(target.file, seen, out)
120
+ }
121
+ for (const imp of analysis.imports) {
122
+ const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
123
+ if (cssUrl !== undefined)
124
+ out.add(cssUrl)
125
+ }
126
+ for (const dep of graph.localDeps(file))
127
+ walkStyles(dep, seen, out)
128
+ }
129
+
130
+ function walkRenderContext(file: string, seen: Set<string>): boolean {
131
+ if (seen.has(file))
132
+ return false
133
+ seen.add(file)
134
+ const analysis = analyses.get(file)
135
+ if (analysis === undefined)
136
+ return false
137
+ return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
138
+ }
139
+
140
+ // Layouts are shared by many routes, so each file is walked once.
141
+ const memo = new Map<string, FileReach>()
142
+ return (file: string): FileReach => {
143
+ let reach = memo.get(file)
144
+ if (reach === undefined) {
145
+ reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false }
146
+ walkIslands(file, new Set(), reach)
147
+ walkStyles(file, new Set(), reach.styles)
148
+ reach.usesRenderContext = walkRenderContext(file, new Set())
149
+ memo.set(file, reach)
150
+ }
151
+ return reach
152
+ }
153
+ }
154
+
155
+ export interface RouteEntries {
156
+ routes: RouteManifestEntry[]
157
+ /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
158
+ globalStyles: string[]
159
+ /** The plugins' CSS alone. */
160
+ globalPluginStyles: string[]
161
+ }
162
+
163
+ export function buildRouteEntries(options: {
164
+ graph: ModuleGraph
165
+ islands: IslandPlan
166
+ islandChunks: Map<string, string>
167
+ srcCssToUrl: Map<string, string>
168
+ islandCssUrl: Map<string, string>
169
+ routesDir: string
170
+ pageFiles: string[]
171
+ pluginCssFiles: string[]
172
+ isStatic: boolean
173
+ /** Maps a source file to its compiled module, relative to the out dir. */
174
+ toOutRel: (srcFile: string) => string
175
+ }): RouteEntries {
176
+ const { graph, islands, islandChunks, routesDir, toOutRel } = options
177
+ const reachOf = createReachWalker(graph, islands, islandChunks, options.srcCssToUrl, options.islandCssUrl)
178
+
179
+ const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
180
+ const rootLayout = join(routesDir, '_layout.tsx')
181
+ const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
182
+
183
+ const routes = options.pageFiles.map((file): RouteManifestEntry => {
184
+ const analysis = graph.analyses.get(file)
185
+ const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
186
+ const chunks = new Set<string>()
187
+ const eagerChunks = new Set<string>()
188
+ const styles = new Set<string>(globalPluginStyles)
189
+ let usesRenderContext = false
190
+ for (const src of [...layoutSrcs, file]) {
191
+ const reach = reachOf(src)
192
+ for (const chunk of reach.chunks)
193
+ chunks.add(chunk)
194
+ for (const chunk of reach.eager)
195
+ eagerChunks.add(chunk)
196
+ for (const style of reach.styles)
197
+ styles.add(style)
198
+ usesRenderContext ||= reach.usesRenderContext
199
+ }
200
+ return {
201
+ path: fileToRoutePath(routesDir, file),
202
+ file: toOutRel(file),
203
+ layouts: layoutSrcs.map(toOutRel),
204
+ middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
205
+ hasLoad: analysis?.hasLoadExport,
206
+ isIsland: analysis?.isInteractive,
207
+ islandChunk: islandChunks.get(`${file}#default`),
208
+ islandHydrate: analysis?.defaultHydrate,
209
+ islandDataKeys: analysis?.isInteractive && analysis.hasLoadExport ? analysis.defaultDataKeys : undefined,
210
+ islandChunks: [...chunks],
211
+ eagerIslandChunks: [...eagerChunks],
212
+ styles: [...styles],
213
+ usesRenderContext,
214
+ prerender: analysis?.hasPrerender || options.isStatic,
215
+ }
216
+ })
217
+ return { routes, globalStyles, globalPluginStyles }
218
+ }
219
+
220
+ export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
221
+ const entries: ActionManifestEntry[] = []
222
+ for (const [srcFile, list] of actionsByFile) {
223
+ const inRoutes = !relative(routesDir, srcFile).startsWith('..')
224
+ const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, MIDDLEWARE_NAMES).map(toOutRel) : []
225
+ for (const a of list)
226
+ entries.push({ url: a.url, file: toOutRel(srcFile), exportName: a.exportName, middlewares })
227
+ }
228
+ return entries
229
+ }
@@ -0,0 +1,186 @@
1
+ // What plugins see of a build: the `build(ctx)` and `afterPrerender(ctx)` hooks, and the shared lists (assets, styles, head tags, public files) those hooks add to.
2
+
3
+ import type { AppRuntimeContext } from '../plugins/context'
4
+ import type { BuildPluginContext, FinalizeBuildContext, KayPlugin } from '../plugins/index'
5
+ import type { RouteManifestEntry } from './manifest'
6
+ import { mkdirSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join } from 'node:path'
8
+ import { precompressFile } from './files'
9
+
10
+ const LEADING_SLASHES_RE = /^\/+/
11
+ const BACKSLASH_RE = /\\/g
12
+
13
+ function cleanRel(relPath: string): string {
14
+ return relPath.replace(LEADING_SLASHES_RE, '').replace(BACKSLASH_RE, '/')
15
+ }
16
+
17
+ export interface PublicFiles {
18
+ /** Public files known so far, as relative paths in registration order. */
19
+ files: string[]
20
+ /** Records a public file and returns its normalized relative path. */
21
+ register: (relPath: string) => string
22
+ }
23
+
24
+ export function createPublicFiles(): PublicFiles {
25
+ const files: string[] = []
26
+ const seen = new Set<string>()
27
+ return {
28
+ files,
29
+ register(relPath) {
30
+ const clean = cleanRel(relPath)
31
+ if (clean !== '' && !seen.has(clean)) {
32
+ seen.add(clean)
33
+ files.push(clean)
34
+ }
35
+ return clean
36
+ },
37
+ }
38
+ }
39
+
40
+ export interface PluginHostOptions {
41
+ plugins: KayPlugin[]
42
+ appCtx: AppRuntimeContext
43
+ root: string
44
+ outDir: string
45
+ clientDir: string
46
+ outPublicDir: string
47
+ assetPrefix: string
48
+ site?: string | undefined
49
+ minify: boolean
50
+ isStatic: boolean
51
+ isDev: boolean
52
+ routes: RouteManifestEntry[]
53
+ publicFiles: PublicFiles
54
+ /** Client files already emitted, relative to the client dir. */
55
+ assets: string[]
56
+ styleUrls: string[]
57
+ globalStyles: string[]
58
+ }
59
+
60
+ export function createPluginHost(options: PluginHostOptions) {
61
+ const { plugins, appCtx, outDir, clientDir, outPublicDir, assetPrefix, routes, assets, styleUrls, globalStyles } = options
62
+ const assetSet = new Set(assets)
63
+ const styleSet = new Set(styleUrls)
64
+ const globalStyleSet = new Set(globalStyles)
65
+ const headTags: string[] = []
66
+ const pluginData: Record<string, Record<string, unknown>> = {}
67
+ const precompressed = new Set<string>()
68
+
69
+ function emitAsset(relPath: string, content: string | Uint8Array): string {
70
+ const clean = cleanRel(relPath)
71
+ const dst = join(clientDir, clean)
72
+ mkdirSync(dirname(dst), { recursive: true })
73
+ writeFileSync(dst, content)
74
+ if (!assetSet.has(clean)) {
75
+ assetSet.add(clean)
76
+ assets.push(clean)
77
+ }
78
+ return `${assetPrefix}/${clean}`
79
+ }
80
+
81
+ function emitPublic(relPath: string, content: string | Uint8Array): string {
82
+ const clean = options.publicFiles.register(relPath)
83
+ const dst = join(outPublicDir, clean)
84
+ mkdirSync(dirname(dst), { recursive: true })
85
+ writeFileSync(dst, content)
86
+ return `/${clean}`
87
+ }
88
+
89
+ function addStyleUrl(href: string): void {
90
+ if (!styleSet.has(href)) {
91
+ styleSet.add(href)
92
+ styleUrls.push(href)
93
+ }
94
+ }
95
+
96
+ const setDataFor = (pluginName: string) => (data: Record<string, unknown>): void => {
97
+ pluginData[pluginName] = { ...pluginData[pluginName], ...data }
98
+ }
99
+
100
+ const shared = {
101
+ root: options.root,
102
+ outDir,
103
+ assetPrefix,
104
+ ...(options.site !== undefined ? { site: options.site } : {}),
105
+ minify: options.minify,
106
+ isStatic: options.isStatic,
107
+ dev: options.isDev,
108
+ routes,
109
+ emitAsset,
110
+ emitPublic,
111
+ provide: appCtx.provide,
112
+ inject: appCtx.inject,
113
+ }
114
+
115
+ const buildCtx = {
116
+ ...shared,
117
+ addStyle(href: string) {
118
+ addStyleUrl(href)
119
+ if (!globalStyleSet.has(href)) {
120
+ globalStyleSet.add(href)
121
+ globalStyles.push(href)
122
+ }
123
+ for (const r of routes) {
124
+ if (r.styles !== undefined && !r.styles.includes(href))
125
+ r.styles.push(href)
126
+ }
127
+ },
128
+ addRouteStyle(routePath: string, href: string) {
129
+ addStyleUrl(href)
130
+ const route = routes.find(r => r.path === routePath)
131
+ if (route !== undefined) {
132
+ route.styles ??= [...globalStyles]
133
+ if (!route.styles.includes(href))
134
+ route.styles.push(href)
135
+ }
136
+ },
137
+ addHead(html: string) {
138
+ if (html !== '')
139
+ headTags.push(html)
140
+ },
141
+ addRouteHead(routePath: string, html: string) {
142
+ const route = html === '' ? undefined : routes.find(r => r.path === routePath)
143
+ if (route !== undefined)
144
+ (route.headTags ??= []).push(html)
145
+ },
146
+ }
147
+
148
+ return {
149
+ headTags,
150
+ pluginData,
151
+ /** Runs every plugin's `build(ctx)`, so plugins can emit hashed assets, public files, styles, <head> tags, or services. */
152
+ async runBuild(): Promise<void> {
153
+ for (const plugin of plugins) {
154
+ if (plugin.build !== undefined) {
155
+ const ctx: BuildPluginContext = { ...buildCtx, setData: setDataFor(plugin.name) }
156
+ await plugin.build(ctx)
157
+ }
158
+ }
159
+ },
160
+
161
+ /** Runs every plugin's `afterPrerender(ctx)`, once `route.prerendered` and prerender-emitted public files are known. */
162
+ async runAfterPrerender(): Promise<boolean> {
163
+ let ran = false
164
+ for (const plugin of plugins) {
165
+ if (plugin.afterPrerender !== undefined) {
166
+ ran = true
167
+ const ctx: FinalizeBuildContext = { ...shared, publicFiles: options.publicFiles.files, setData: setDataFor(plugin.name) }
168
+ await plugin.afterPrerender(ctx)
169
+ }
170
+ }
171
+ return ran
172
+ },
173
+
174
+ /** Writes `.br`/`.gz` sidecars for client assets not compressed yet (production server builds only: `--static` compresses its own output). */
175
+ precompressAssets(): void {
176
+ if (options.isDev || options.isStatic)
177
+ return
178
+ for (const rel of assets) {
179
+ if (!precompressed.has(rel)) {
180
+ precompressed.add(rel)
181
+ precompressFile(join(clientDir, rel), 256)
182
+ }
183
+ }
184
+ },
185
+ }
186
+ }
@@ -0,0 +1,102 @@
1
+ // Build-time rendering: routes exporting `prerender = true` (and every route in a static export) are rendered through the real server and written as HTML.
2
+
3
+ import type { KayPlugin } from '../plugins/index'
4
+ import type { RouteManifestEntry } from './manifest'
5
+ import { mkdirSync, writeFileSync } from 'node:fs'
6
+ import { dirname, resolve } from 'node:path'
7
+ import { inlineStyleHashes } from '../server/security'
8
+ import { relPosix } from './files'
9
+ import { assertPathUrls } from './routes'
10
+
11
+ const CONCURRENCY = 8
12
+ const SLASH_EDGES_RE = /^\/|\/$/g
13
+
14
+
15
+ function resolvePrerenderHtmlPath(prerenderDir: string, urlStr: string, isStatic: boolean): string {
16
+ const pathname = new URL(urlStr, 'http://localhost').pathname
17
+ const rel = pathname === '/'
18
+ ? 'index.html'
19
+ : (isStatic && pathname === '/404')
20
+ ? '404.html'
21
+ : `${pathname.replace(SLASH_EDGES_RE, '')}/index.html`
22
+ const absRoot = resolve(prerenderDir)
23
+ const abs = resolve(absRoot, rel)
24
+ if (!abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
25
+ throw new Error(`kay build: prerender path "${urlStr}" escapes output directory.`)
26
+ return abs
27
+ }
28
+
29
+ export interface PrerenderOptions {
30
+ root: string
31
+ outDir: string
32
+ assetPrefix: string
33
+ site?: string | undefined
34
+ plugins: KayPlugin[]
35
+ /** Plugins passed to `build()` itself, which the app runs with in place of its bundled config's. */
36
+ pluginOverride?: KayPlugin[] | undefined
37
+ isDev: boolean
38
+ isStatic: boolean
39
+ /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
40
+ prerenderDir: string
41
+ routes: RouteManifestEntry[]
42
+ }
43
+
44
+ /** Renders every route to HTML, records `route.prerendered`, and returns the server the pages were rendered with. */
45
+ export async function prerender(options: PrerenderOptions) {
46
+ const { root, outDir, prerenderDir, isStatic } = options
47
+ // Pages render with the runtime's own plugin instances, from the bundled config; `options.plugins` are the build's native ones.
48
+ const { startBuiltApp } = await import('../server/loader')
49
+ const { app, entry } = await startBuiltApp({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.pluginOverride, dev: options.isDev })
50
+ mkdirSync(prerenderDir, { recursive: true })
51
+
52
+ for (const route of options.routes) {
53
+ let urls: string[] = []
54
+ if (!route.path.includes(':') && !route.path.includes('*')) {
55
+ urls = [route.path]
56
+ }
57
+ else {
58
+ const mod = entry?.modules[route.file] as { paths?: () => Promise<string[]> | string[] } | undefined ?? {}
59
+ if (typeof mod.paths === 'function') {
60
+ const returned: unknown = await mod.paths()
61
+ assertPathUrls(returned, route.file)
62
+ urls = returned
63
+ }
64
+ else {
65
+ console.warn(`kay build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
66
+ }
67
+ }
68
+
69
+ if (urls.length === 0)
70
+ continue
71
+
72
+ for (const plugin of options.plugins) {
73
+ if (plugin.prerenderPaths !== undefined)
74
+ urls = await plugin.prerenderPaths(urls, route)
75
+ }
76
+
77
+ const map: Record<string, string> = {}
78
+ const styleHashes: Record<string, string[]> = {}
79
+ for (let i = 0; i < urls.length; i += CONCURRENCY) {
80
+ await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
81
+ const res = await app.handle(new Request(`http://localhost${u}`))
82
+ const isExplicit404 = u === '/404' && res.status === 404
83
+ if (res.status !== 200 && !isExplicit404) {
84
+ if (isStatic || res.status >= 500)
85
+ throw new Error(`kay build${isStatic ? ' --static' : ''}: prerender route "${u}" returned HTTP ${res.status} (expected 200).`)
86
+ return
87
+ }
88
+ const absHtml = resolvePrerenderHtmlPath(prerenderDir, u, isStatic)
89
+ mkdirSync(dirname(absHtml), { recursive: true })
90
+ const html = await res.text()
91
+ writeFileSync(absHtml, html)
92
+ map[u] = relPosix(isStatic ? prerenderDir : outDir, absHtml)
93
+ const hashes = inlineStyleHashes(html)
94
+ if (hashes.length > 0)
95
+ styleHashes[u] = hashes
96
+ }))
97
+ }
98
+ route.prerendered = map
99
+ route.prerenderedStyleHashes = Object.keys(styleHashes).length > 0 ? styleHashes : undefined
100
+ }
101
+ return app
102
+ }