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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +615 -0
  4. package/src/build/compile.ts +32 -19
  5. package/src/build/files.ts +174 -0
  6. package/src/build/graph.ts +223 -0
  7. package/src/build/index.ts +255 -1461
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +227 -0
  10. package/src/build/plugin-host.ts +186 -0
  11. package/src/build/prerender.ts +94 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +51 -0
  14. package/src/build/routes.ts +163 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +300 -129
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +58 -38
  19. package/src/compiler/analyze.ts +723 -93
  20. package/src/compiler/dom.ts +848 -762
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +172 -23
  24. package/src/compiler/shared.ts +485 -0
  25. package/src/compiler/ssr.ts +331 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +358 -76
  28. package/src/dom/action.ts +114 -14
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +122 -80
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +5 -1
  34. package/src/jsx-runtime.ts +432 -93
  35. package/src/plugins/context.ts +83 -0
  36. package/src/plugins/index.ts +285 -23
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +157 -79
  41. package/src/server/compress.ts +197 -104
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +189 -77
  45. package/src/server/index.ts +1024 -878
  46. package/src/server/loader.ts +138 -0
  47. package/src/server/router.ts +69 -26
  48. package/src/server/security.ts +50 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +5 -15
  55. package/src/unrenderable.ts +35 -0
@@ -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,227 @@
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
+ }
38
+
39
+ export interface BuildManifest {
40
+ runtimeScript: string | undefined
41
+ styles: string[]
42
+ /** Stylesheets applied globally (plugin CSS, ctx.addStyle, and root layout CSS) — used by _error/_404. */
43
+ globalStyles?: string[] | undefined
44
+ headTags?: string[] | undefined
45
+ routes: RouteManifestEntry[]
46
+ configFile?: string | undefined
47
+ /** Explicit root `_layout.tsx` compiled module path (never inferred from subdirectory layouts). */
48
+ rootLayoutFile?: string | undefined
49
+ errorFile?: string | undefined
50
+ notFoundFile?: string | undefined
51
+ actions: ActionManifestEntry[]
52
+ islands: Record<string, string>
53
+ assets: string[]
54
+ publicFiles: string[]
55
+ /** Serializable build-time metadata persisted by plugins via `ctx.setData()`, read via `api.getBuildData()`. */
56
+ pluginData?: Record<string, Record<string, unknown>> | undefined
57
+ }
58
+
59
+ interface FileReach {
60
+ /** Island chunks reachable from the file, and the subset loaded eagerly. */
61
+ chunks: Set<string>
62
+ eager: Set<string>
63
+ styles: Set<string>
64
+ usesRenderContext: boolean
65
+ }
66
+
67
+ /** Walks what a module renders and imports to find the island chunks, stylesheets and render-context use behind it. */
68
+ function createReachWalker(graph: ModuleGraph, islands: IslandPlan, islandChunks: Map<string, string>, srcCssToUrl: Map<string, string>, islandCssUrl: Map<string, string>) {
69
+ const { analyses } = graph
70
+
71
+ function walkIslands(file: string, seen: Set<string>, reach: FileReach): void {
72
+ if (seen.has(file))
73
+ return
74
+ seen.add(file)
75
+ const analysis = analyses.get(file)
76
+ if (analysis === undefined)
77
+ return
78
+ if (analysis.isInteractive) {
79
+ const chunk = islandChunks.get(`${file}#default`)
80
+ if (chunk !== undefined) {
81
+ reach.chunks.add(chunk)
82
+ if (analysis.defaultHydrate === undefined || analysis.defaultHydrate === 'load')
83
+ reach.eager.add(chunk)
84
+ }
85
+ return
86
+ }
87
+ for (const [localName, target] of islands.pageBindings.get(file) ?? []) {
88
+ const chunk = islandChunks.get(islandKey(target))
89
+ if (chunk === undefined)
90
+ continue
91
+ reach.chunks.add(chunk)
92
+ const isDeferred = analysis.deferredIslandTags.has(localName)
93
+ || (target.defaultHydrate !== undefined && target.defaultHydrate !== 'load')
94
+ if (!isDeferred)
95
+ reach.eager.add(chunk)
96
+ }
97
+ for (const dep of graph.localDeps(file))
98
+ walkIslands(dep, seen, reach)
99
+ }
100
+
101
+ function walkStyles(file: string, seen: Set<string>, out: Set<string>): void {
102
+ if (seen.has(file))
103
+ return
104
+ seen.add(file)
105
+ const analysis = analyses.get(file)
106
+ if (analysis === undefined)
107
+ return
108
+ if (analysis.isInteractive) {
109
+ const islCss = islandCssUrl.get(`${file}#default`)
110
+ if (islCss !== undefined)
111
+ out.add(islCss)
112
+ }
113
+ for (const target of islands.pageBindings.get(file)?.values() ?? []) {
114
+ const islCss = islandCssUrl.get(islandKey(target))
115
+ if (islCss !== undefined)
116
+ out.add(islCss)
117
+ walkStyles(target.file, seen, out)
118
+ }
119
+ for (const imp of analysis.imports) {
120
+ const cssUrl = srcCssToUrl.get(graph.resolve(file, imp.source) ?? '')
121
+ if (cssUrl !== undefined)
122
+ out.add(cssUrl)
123
+ }
124
+ for (const dep of graph.localDeps(file))
125
+ walkStyles(dep, seen, out)
126
+ }
127
+
128
+ function walkRenderContext(file: string, seen: Set<string>): boolean {
129
+ if (seen.has(file))
130
+ return false
131
+ seen.add(file)
132
+ const analysis = analyses.get(file)
133
+ if (analysis === undefined)
134
+ return false
135
+ return analysis.usesRenderContext || graph.localDeps(file).some(dep => walkRenderContext(dep, seen))
136
+ }
137
+
138
+ // Layouts are shared by many routes, so each file is walked once.
139
+ const memo = new Map<string, FileReach>()
140
+ return (file: string): FileReach => {
141
+ let reach = memo.get(file)
142
+ if (reach === undefined) {
143
+ reach = { chunks: new Set(), eager: new Set(), styles: new Set(), usesRenderContext: false }
144
+ walkIslands(file, new Set(), reach)
145
+ walkStyles(file, new Set(), reach.styles)
146
+ reach.usesRenderContext = walkRenderContext(file, new Set())
147
+ memo.set(file, reach)
148
+ }
149
+ return reach
150
+ }
151
+ }
152
+
153
+ export interface RouteEntries {
154
+ routes: RouteManifestEntry[]
155
+ /** Stylesheets of every page: the plugins' CSS, then the root layout's. */
156
+ globalStyles: string[]
157
+ /** The plugins' CSS alone. */
158
+ globalPluginStyles: string[]
159
+ }
160
+
161
+ export function buildRouteEntries(options: {
162
+ graph: ModuleGraph
163
+ islands: IslandPlan
164
+ islandChunks: Map<string, string>
165
+ srcCssToUrl: Map<string, string>
166
+ islandCssUrl: Map<string, string>
167
+ routesDir: string
168
+ pageFiles: string[]
169
+ pluginCssFiles: string[]
170
+ isStatic: boolean
171
+ /** Maps a source file to its compiled module, relative to the out dir. */
172
+ toOutRel: (srcFile: string) => string
173
+ }): RouteEntries {
174
+ const { graph, islands, islandChunks, routesDir, toOutRel } = options
175
+ const reachOf = createReachWalker(graph, islands, islandChunks, options.srcCssToUrl, options.islandCssUrl)
176
+
177
+ const globalPluginStyles = [...new Set(options.pluginCssFiles.map(css => options.srcCssToUrl.get(css)).filter((url): url is string => url !== undefined))]
178
+ const rootLayout = join(routesDir, '_layout.tsx')
179
+ const globalStyles = [...new Set([...globalPluginStyles, ...(graph.analyses.has(rootLayout) ? reachOf(rootLayout).styles : [])])]
180
+
181
+ const routes = options.pageFiles.map((file): RouteManifestEntry => {
182
+ const analysis = graph.analyses.get(file)
183
+ const layoutSrcs = ancestorFiles(routesDir, file, ['_layout.tsx'])
184
+ const chunks = new Set<string>()
185
+ const eagerChunks = new Set<string>()
186
+ const styles = new Set<string>(globalPluginStyles)
187
+ let usesRenderContext = false
188
+ for (const src of [...layoutSrcs, file]) {
189
+ const reach = reachOf(src)
190
+ for (const chunk of reach.chunks)
191
+ chunks.add(chunk)
192
+ for (const chunk of reach.eager)
193
+ eagerChunks.add(chunk)
194
+ for (const style of reach.styles)
195
+ styles.add(style)
196
+ usesRenderContext ||= reach.usesRenderContext
197
+ }
198
+ return {
199
+ path: fileToRoutePath(routesDir, file),
200
+ file: toOutRel(file),
201
+ layouts: layoutSrcs.map(toOutRel),
202
+ middlewares: ancestorFiles(routesDir, file, MIDDLEWARE_NAMES).map(toOutRel),
203
+ hasLoad: analysis?.hasLoadExport,
204
+ isIsland: analysis?.isInteractive,
205
+ islandChunk: islandChunks.get(`${file}#default`),
206
+ islandHydrate: analysis?.defaultHydrate,
207
+ islandDataKeys: analysis?.isInteractive && analysis.hasLoadExport ? analysis.defaultDataKeys : undefined,
208
+ islandChunks: [...chunks],
209
+ eagerIslandChunks: [...eagerChunks],
210
+ styles: [...styles],
211
+ usesRenderContext,
212
+ prerender: analysis?.hasPrerender || options.isStatic,
213
+ }
214
+ })
215
+ return { routes, globalStyles, globalPluginStyles }
216
+ }
217
+
218
+ export function buildActionEntries(actionsByFile: Map<string, { exportName: string, url: string }[]>, routesDir: string, toOutRel: (srcFile: string) => string): ActionManifestEntry[] {
219
+ const entries: ActionManifestEntry[] = []
220
+ for (const [srcFile, list] of actionsByFile) {
221
+ const inRoutes = !relative(routesDir, srcFile).startsWith('..')
222
+ const middlewares = inRoutes ? ancestorFiles(routesDir, srcFile, MIDDLEWARE_NAMES).map(toOutRel) : []
223
+ for (const a of list)
224
+ entries.push({ url: a.url, file: toOutRel(srcFile), exportName: a.exportName, middlewares })
225
+ }
226
+ return entries
227
+ }
@@ -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,94 @@
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, join, resolve } from 'node:path'
7
+ import { relPosix } from './files'
8
+ import { assertPathUrls } from './routes'
9
+
10
+ const CONCURRENCY = 8
11
+ const SLASH_EDGES_RE = /^\/|\/$/g
12
+
13
+ let prerenderImportSeq = 0
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
+ isDev: boolean
36
+ isStatic: boolean
37
+ /** Where the HTML lands: the static stage dir, or `<outDir>/prerendered`. */
38
+ prerenderDir: string
39
+ routes: RouteManifestEntry[]
40
+ }
41
+
42
+ /** Renders every route to HTML, records `route.prerendered`, and returns the server the pages were rendered with. */
43
+ export async function prerender(options: PrerenderOptions) {
44
+ const { root, outDir, prerenderDir, isStatic } = options
45
+ const { createServer } = await import('../server/index')
46
+ const app = await createServer({ root, outDir: relPosix(root, outDir), assetPrefix: options.assetPrefix, site: options.site, plugins: options.plugins, dev: options.isDev })
47
+ mkdirSync(prerenderDir, { recursive: true })
48
+
49
+ const stamp = `${Date.now()}-${++prerenderImportSeq}`
50
+ for (const route of options.routes) {
51
+ let urls: string[] = []
52
+ if (!route.path.includes(':') && !route.path.includes('*')) {
53
+ urls = [route.path]
54
+ }
55
+ else {
56
+ const mod = await import(`${join(outDir, route.file)}?v=${stamp}`) as { paths?: () => Promise<string[]> | string[] }
57
+ if (typeof mod.paths === 'function') {
58
+ const returned: unknown = await mod.paths()
59
+ assertPathUrls(returned, route.file)
60
+ urls = returned
61
+ }
62
+ else {
63
+ console.warn(`kay build${isStatic ? ' --static' : ''}: skipping dynamic route "${route.path}" (${route.file}) because it does not export a paths() function.`)
64
+ }
65
+ }
66
+
67
+ if (urls.length === 0)
68
+ continue
69
+
70
+ for (const plugin of options.plugins) {
71
+ if (plugin.prerenderPaths !== undefined)
72
+ urls = await plugin.prerenderPaths(urls, route)
73
+ }
74
+
75
+ const map: Record<string, string> = {}
76
+ for (let i = 0; i < urls.length; i += CONCURRENCY) {
77
+ await Promise.all(urls.slice(i, i + CONCURRENCY).map(async (u) => {
78
+ const res = await app.handle(new Request(`http://localhost${u}`))
79
+ const isExplicit404 = u === '/404' && res.status === 404
80
+ if (res.status !== 200 && !isExplicit404) {
81
+ if (isStatic || res.status >= 500)
82
+ throw new Error(`kay build${isStatic ? ' --static' : ''}: prerender route "${u}" returned HTTP ${res.status} (expected 200).`)
83
+ return
84
+ }
85
+ const absHtml = resolvePrerenderHtmlPath(prerenderDir, u, isStatic)
86
+ mkdirSync(dirname(absHtml), { recursive: true })
87
+ writeFileSync(absHtml, await res.text())
88
+ map[u] = relPosix(isStatic ? prerenderDir : outDir, absHtml)
89
+ }))
90
+ }
91
+ route.prerendered = map
92
+ }
93
+ return app
94
+ }