@kayjs/kay 2.0.0-beta.1 → 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/build/bundle.ts +209 -34
- package/src/build/compile.ts +22 -46
- package/src/build/files.ts +38 -0
- package/src/build/graph.ts +67 -2
- package/src/build/index.ts +75 -13
- package/src/build/manifest.ts +5 -0
- package/src/build/plugin-host.ts +2 -0
- package/src/build/prerender.ts +16 -7
- package/src/build/resolve.ts +11 -18
- package/src/build/routes.ts +33 -5
- package/src/build/server-entry.ts +38 -0
- package/src/cli/check.ts +102 -45
- package/src/cli/new.ts +6 -7
- package/src/compiler/analyze.ts +65 -10
- package/src/compiler/dom.ts +143 -122
- package/src/compiler/server-only.ts +14 -8
- package/src/compiler/shared.ts +57 -14
- package/src/compiler/ssr.ts +14 -12
- package/src/dev/index.ts +96 -29
- package/src/dom/action.ts +91 -1
- package/src/dom/index.ts +8 -3
- package/src/index.ts +3 -0
- package/src/jsx-runtime.ts +421 -93
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +4 -0
- package/src/plugins/index.ts +7 -216
- 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/server/action-registry.ts +72 -0
- package/src/server/action.ts +15 -8
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +87 -14
- package/src/server/document.ts +192 -0
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +103 -30
- package/src/server/index.ts +131 -701
- package/src/server/loader.ts +62 -69
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +49 -20
- package/src/server/security.ts +44 -3
- package/src/server/static-dir.ts +22 -3
- package/src/server/stream.ts +94 -0
- package/src/test/index.ts +24 -19
package/src/server/loader.ts
CHANGED
|
@@ -1,50 +1,34 @@
|
|
|
1
|
-
// Filesystem server loader: reads `dist/manifest.json` (or
|
|
1
|
+
// Filesystem server loader: reads `dist/manifest.json`, maps the built assets on disk, and starts the app from `dist/server/_entry.js` (or serves a `--static` dir).
|
|
2
2
|
|
|
3
3
|
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { ServerEntry } from './app-entry'
|
|
4
5
|
import type { EmbeddedBody, KayApp, ServerOptions } from './http'
|
|
5
6
|
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
6
7
|
import { join, resolve } from 'node:path'
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
8
|
+
import { SERVER_ENTRY_FILE } from '../build/server-entry'
|
|
9
|
+
import { loadConfig, resolveServerConfig } from '../plugins/index'
|
|
9
10
|
import { createStaticDirServer } from './static-dir'
|
|
10
11
|
|
|
11
12
|
let serverLoadSeq = 0
|
|
12
13
|
|
|
13
14
|
export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
const plugins = options.plugins ?? fileConfig.plugins ?? []
|
|
17
|
-
const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
|
|
18
|
-
const clientDir = join(outDir, 'client')
|
|
19
|
-
const manifestPath = join(outDir, 'manifest.json')
|
|
20
|
-
const securityOpt = options.security ?? fileConfig.security
|
|
21
|
-
const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
|
|
22
|
-
const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
|
|
23
|
-
const isDev = options.dev ?? (process.env.KAY_DEV === '1')
|
|
24
|
-
|
|
25
|
-
if (!existsSync(manifestPath)) {
|
|
26
|
-
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
|
|
27
|
-
return createStaticDirServer(
|
|
28
|
-
outDir,
|
|
29
|
-
options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
|
|
30
|
-
securityOpt,
|
|
31
|
-
(options.compress ?? fileConfig.compress) !== false,
|
|
32
|
-
trustProxy,
|
|
33
|
-
isDev,
|
|
34
|
-
)
|
|
35
|
-
}
|
|
36
|
-
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
37
|
-
}
|
|
15
|
+
return (await startBuiltApp(options)).app
|
|
16
|
+
}
|
|
38
17
|
|
|
39
|
-
|
|
40
|
-
|
|
18
|
+
/** The app and the entry it was assembled from, whose bundled modules `testApp().import()` and the prerender step read. */
|
|
19
|
+
export async function startBuiltApp(options: ServerOptions): Promise<{ app: KayApp, entry?: ServerEntry | undefined }> {
|
|
20
|
+
const built = await loadServerEntry(options)
|
|
21
|
+
if (built.entry === undefined)
|
|
22
|
+
return { app: await serveStaticDir(options, built.root, built.outDir) }
|
|
23
|
+
const { root, outDir, manifest, entry } = built
|
|
24
|
+
const clientDir = join(outDir, 'client')
|
|
41
25
|
const assets: Record<string, EmbeddedBody> = {}
|
|
42
26
|
const publicAssets: Record<string, EmbeddedBody> = {}
|
|
43
27
|
const publicEtags: Record<string, string> = {}
|
|
44
28
|
const prerenderedFiles: Record<string, string> = {}
|
|
45
|
-
const srcPublicDir = resolve(root,
|
|
29
|
+
const srcPublicDir = resolve(root, entry.kayConfig.publicDir ?? 'public')
|
|
46
30
|
|
|
47
|
-
//
|
|
31
|
+
// File paths only: Bun.file() serves them zero-copy, and nothing is read at startup.
|
|
48
32
|
for (const rel of manifest.assets) {
|
|
49
33
|
const abs = join(clientDir, rel)
|
|
50
34
|
if (existsSync(abs)) {
|
|
@@ -66,55 +50,64 @@ export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
|
66
50
|
}
|
|
67
51
|
}
|
|
68
52
|
|
|
69
|
-
const loadStamp = `${Date.now()}-${++serverLoadSeq}`
|
|
70
|
-
const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
|
|
71
|
-
const loadMod = async (rel: string) => {
|
|
72
|
-
if (!(rel in modules))
|
|
73
|
-
modules[rel] = await importModule(join(outDir, rel))
|
|
74
|
-
}
|
|
75
|
-
|
|
76
53
|
for (const r of manifest.routes) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
for (const relHtml of Object.values(r.prerendered)) {
|
|
82
|
-
const abs = join(outDir, relHtml)
|
|
83
|
-
if (existsSync(abs))
|
|
84
|
-
prerenderedFiles[relHtml] = abs
|
|
85
|
-
}
|
|
54
|
+
for (const relHtml of Object.values(r.prerendered ?? {})) {
|
|
55
|
+
const abs = join(outDir, relHtml)
|
|
56
|
+
if (existsSync(abs))
|
|
57
|
+
prerenderedFiles[relHtml] = abs
|
|
86
58
|
}
|
|
87
59
|
}
|
|
88
|
-
if (manifest.errorFile) await loadMod(manifest.errorFile)
|
|
89
|
-
if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
|
|
90
|
-
for (const a of manifest.actions) {
|
|
91
|
-
await loadMod(a.file)
|
|
92
|
-
for (const m of a.middlewares) await loadMod(m)
|
|
93
|
-
}
|
|
94
60
|
|
|
95
|
-
const
|
|
96
|
-
|
|
97
|
-
...runtimeConfig,
|
|
61
|
+
const app = await entry.createApp({
|
|
62
|
+
...resolveServerConfig(undefined, options),
|
|
98
63
|
manifest,
|
|
99
|
-
modules,
|
|
100
64
|
assets,
|
|
101
65
|
publicAssets,
|
|
102
66
|
publicEtags,
|
|
103
|
-
prerendered: {},
|
|
104
67
|
prerenderedFiles,
|
|
105
68
|
root,
|
|
106
69
|
outDir,
|
|
107
70
|
publicDir: join(outDir, 'public'),
|
|
108
|
-
|
|
109
|
-
lang: options.lang ?? fileConfig.lang,
|
|
110
|
-
security: securityOpt,
|
|
111
|
-
trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
|
|
112
|
-
trustProxy,
|
|
113
|
-
maxRequestBodySize,
|
|
114
|
-
streamTimeout: options.streamTimeout ?? fileConfig.streamTimeout,
|
|
115
|
-
compress: options.compress ?? fileConfig.compress,
|
|
116
|
-
dev: isDev,
|
|
117
|
-
onError: options.onError ?? fileConfig.onError,
|
|
118
|
-
plugins,
|
|
71
|
+
dev: options.dev ?? (process.env.KAY_DEV === '1'),
|
|
119
72
|
})
|
|
73
|
+
return { app, entry }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
type BuiltOutput =
|
|
77
|
+
| { root: string, outDir: string, manifest: BuildManifest, entry: ServerEntry }
|
|
78
|
+
| { root: string, outDir: string, entry?: undefined }
|
|
79
|
+
|
|
80
|
+
/** Finds the build output and imports its server entry; a `--static` export has none. */
|
|
81
|
+
async function loadServerEntry(options: ServerOptions): Promise<BuiltOutput> {
|
|
82
|
+
const root = resolve(options.root)
|
|
83
|
+
let outDir = resolve(root, options.outDir ?? 'dist')
|
|
84
|
+
// kay.config.ts is read natively only to find an `outDir` it moved; the app itself runs from its bundled copy.
|
|
85
|
+
if (options.outDir === undefined && !existsSync(join(outDir, 'manifest.json')))
|
|
86
|
+
outDir = resolve(root, (await loadConfig(root)).outDir ?? 'dist')
|
|
87
|
+
const manifestPath = join(outDir, 'manifest.json')
|
|
88
|
+
if (!existsSync(manifestPath)) {
|
|
89
|
+
if (existsSync(outDir) && readdirSync(outDir).length > 0)
|
|
90
|
+
return { root, outDir }
|
|
91
|
+
throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
|
|
92
|
+
}
|
|
93
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
|
|
94
|
+
const entryPath = join(outDir, 'server', SERVER_ENTRY_FILE)
|
|
95
|
+
if (!existsSync(entryPath))
|
|
96
|
+
throw new Error(`kay server: missing ${entryPath}, the server entry kay build writes. Run kay build again.`)
|
|
97
|
+
const stamp = `${Date.now()}-${++serverLoadSeq}`
|
|
98
|
+
const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${stamp}`))
|
|
99
|
+
const entry = await importModule(entryPath) as unknown as ServerEntry
|
|
100
|
+
return { root, outDir, manifest, entry }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function serveStaticDir(options: ServerOptions, root: string, outDir: string): Promise<KayApp> {
|
|
104
|
+
const config = await loadConfig(root)
|
|
105
|
+
return createStaticDirServer(
|
|
106
|
+
outDir,
|
|
107
|
+
options.assetPrefix ?? config.assetPrefix ?? '/_kay',
|
|
108
|
+
options.security ?? config.security,
|
|
109
|
+
(options.compress ?? config.compress) !== false,
|
|
110
|
+
options.trustProxy ?? config.trustProxy ?? false,
|
|
111
|
+
options.dev ?? (process.env.KAY_DEV === '1'),
|
|
112
|
+
)
|
|
120
113
|
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// What a route file is to the server: the page, layout and middleware modules it loads, and the answers derived from their exports.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest, RouteManifestEntry } from '../build/index'
|
|
4
|
+
import type { Html } from '../jsx-runtime'
|
|
5
|
+
import type { Middleware, RequestContext } from './http'
|
|
6
|
+
import type { KayLocals } from './index'
|
|
7
|
+
|
|
8
|
+
export interface LoadedPageModule {
|
|
9
|
+
default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
|
|
10
|
+
load?: (ctx: RequestContext) => unknown | Promise<unknown>
|
|
11
|
+
clientData?: readonly string[] | ((data: unknown) => unknown) | undefined
|
|
12
|
+
csrf?: boolean | undefined
|
|
13
|
+
GET?: (ctx: RequestContext) => Response | Promise<Response>
|
|
14
|
+
POST?: (ctx: RequestContext) => Response | Promise<Response>
|
|
15
|
+
PUT?: (ctx: RequestContext) => Response | Promise<Response>
|
|
16
|
+
PATCH?: (ctx: RequestContext) => Response | Promise<Response>
|
|
17
|
+
DELETE?: (ctx: RequestContext) => Response | Promise<Response>
|
|
18
|
+
HEAD?: (ctx: RequestContext) => Response | Promise<Response>
|
|
19
|
+
OPTIONS?: (ctx: RequestContext) => Response | Promise<Response>
|
|
20
|
+
[key: string]: unknown
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface LoadedLayoutModule {
|
|
24
|
+
default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: KayLocals }) => Html | string | Promise<Html | string>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface LoadedMiddlewareModule {
|
|
28
|
+
default: Middleware
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const HTTP_METHOD_EXPORTS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'] as const
|
|
32
|
+
|
|
33
|
+
export function mergedHeadTags(manifest: BuildManifest, entry: RouteManifestEntry): string[] | undefined {
|
|
34
|
+
return entry.headTags !== undefined && entry.headTags.length > 0
|
|
35
|
+
? [...(manifest.headTags ?? []), ...entry.headTags]
|
|
36
|
+
: manifest.headTags
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function allowedMethodsHeader(mod: LoadedPageModule): string {
|
|
40
|
+
const allowed = new Set<string>()
|
|
41
|
+
if (typeof mod.default === 'function') {
|
|
42
|
+
allowed.add('GET')
|
|
43
|
+
allowed.add('HEAD')
|
|
44
|
+
}
|
|
45
|
+
for (const m of HTTP_METHOD_EXPORTS) {
|
|
46
|
+
if (typeof mod[m] === 'function')
|
|
47
|
+
allowed.add(m)
|
|
48
|
+
}
|
|
49
|
+
if (allowed.has('GET'))
|
|
50
|
+
allowed.add('HEAD')
|
|
51
|
+
return [...allowed].join(', ')
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function cancelBodyQuietly(body: ReadableStream<Uint8Array>): Promise<void> {
|
|
55
|
+
try {
|
|
56
|
+
await body.cancel()
|
|
57
|
+
}
|
|
58
|
+
catch {}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function stripHeadBody(res: Response): Response {
|
|
62
|
+
if (res.body !== null)
|
|
63
|
+
void cancelBodyQuietly(res.body)
|
|
64
|
+
return new Response(null, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function isPlainObject(v: unknown): v is Record<string, unknown> {
|
|
68
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function pickObjectKeys(obj: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> | undefined {
|
|
72
|
+
if (keys.length === 0)
|
|
73
|
+
return undefined
|
|
74
|
+
const picked: Record<string, unknown> = {}
|
|
75
|
+
let count = 0
|
|
76
|
+
for (const k of keys) {
|
|
77
|
+
if (Object.hasOwn(obj, k)) {
|
|
78
|
+
Object.defineProperty(picked, k, { value: obj[k], enumerable: true, writable: true, configurable: true })
|
|
79
|
+
count++
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return count > 0 ? picked : undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function pickPageIslandProps(data: unknown, entry: RouteManifestEntry, mod: LoadedPageModule): Record<string, unknown> {
|
|
86
|
+
if (data === undefined)
|
|
87
|
+
return {}
|
|
88
|
+
if (typeof mod.clientData === 'function') {
|
|
89
|
+
const subset = mod.clientData(data)
|
|
90
|
+
return subset === undefined ? {} : { data: subset }
|
|
91
|
+
}
|
|
92
|
+
if (Array.isArray(mod.clientData)) {
|
|
93
|
+
if (!isPlainObject(data))
|
|
94
|
+
return {}
|
|
95
|
+
const subset = pickObjectKeys(data, mod.clientData)
|
|
96
|
+
return subset === undefined ? {} : { data: subset }
|
|
97
|
+
}
|
|
98
|
+
if (entry.islandDataKeys !== undefined) {
|
|
99
|
+
if (entry.islandDataKeys.length === 0)
|
|
100
|
+
return {}
|
|
101
|
+
if (isPlainObject(data)) {
|
|
102
|
+
const subset = pickObjectKeys(data, entry.islandDataKeys)
|
|
103
|
+
return subset === undefined ? {} : { data: subset }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { data }
|
|
107
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// What plugins see of a running server: each `server(api)` hook, and the middleware, routes, rewrites and shutdown hooks those hooks register.
|
|
2
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { AppRuntimeContext } from '../plugins/context'
|
|
5
|
+
import type { KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerPluginAPI } from '../plugins/index'
|
|
6
|
+
import type { EmbeddedServerConfig, Middleware, RequestContext } from './http'
|
|
7
|
+
import type { TrustProxy } from './security'
|
|
8
|
+
import { runWithAppContext } from '../plugins/context'
|
|
9
|
+
import { Router } from './router'
|
|
10
|
+
|
|
11
|
+
export interface PluginRouteDef {
|
|
12
|
+
handler: (ctx: RequestContext) => Response | Promise<Response>
|
|
13
|
+
csrf: boolean
|
|
14
|
+
trustedOrigins: Set<string> | undefined
|
|
15
|
+
trustProxy: TrustProxy
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
interface ScopedMiddleware {
|
|
19
|
+
mw: Middleware
|
|
20
|
+
scope: 'all' | 'dynamic' | string
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ServerPluginHostOptions {
|
|
24
|
+
plugins: readonly KayPlugin[]
|
|
25
|
+
config: EmbeddedServerConfig
|
|
26
|
+
manifest: BuildManifest
|
|
27
|
+
appCtx: AppRuntimeContext
|
|
28
|
+
root: string
|
|
29
|
+
outDir: string
|
|
30
|
+
assetPrefix: string
|
|
31
|
+
site: string | undefined
|
|
32
|
+
dev: boolean
|
|
33
|
+
trustProxy: TrustProxy
|
|
34
|
+
trustedOriginsList: readonly string[]
|
|
35
|
+
trustedOrigins: Set<string> | undefined
|
|
36
|
+
invokeAction: ServerPluginAPI['invokeAction']
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function middlewareAppliesToPath(scope: ScopedMiddleware['scope'], path: string, isStaticFast: boolean): boolean {
|
|
40
|
+
if (scope === 'all')
|
|
41
|
+
return true
|
|
42
|
+
if (scope === 'dynamic')
|
|
43
|
+
return !isStaticFast
|
|
44
|
+
return path === scope || path.startsWith(scope.endsWith('/') ? scope : `${scope}/`)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function allowedPluginMethodsHeader(methods: ReadonlyMap<string, PluginRouteDef>): string {
|
|
48
|
+
const allowed = new Set<string>()
|
|
49
|
+
for (const m of methods.keys()) {
|
|
50
|
+
if (m === 'ALL')
|
|
51
|
+
continue
|
|
52
|
+
allowed.add(m)
|
|
53
|
+
}
|
|
54
|
+
if (allowed.has('GET'))
|
|
55
|
+
allowed.add('HEAD')
|
|
56
|
+
return [...allowed].join(', ')
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function createServerPluginHost(options: ServerPluginHostOptions) {
|
|
60
|
+
const { plugins, config, manifest, appCtx, trustedOrigins, trustProxy } = options
|
|
61
|
+
const scopedMiddlewares: ScopedMiddleware[] = []
|
|
62
|
+
const shutdownHooks: (() => void | Promise<void>)[] = []
|
|
63
|
+
const rewrites: ((pathname: string, ctx: RequestContext) => string | undefined)[] = []
|
|
64
|
+
const router = new Router<Map<string, PluginRouteDef>>()
|
|
65
|
+
const routeEntries = new Map<string, Map<string, PluginRouteDef>>()
|
|
66
|
+
|
|
67
|
+
const registerRoute = (
|
|
68
|
+
method: string,
|
|
69
|
+
path: string,
|
|
70
|
+
handler: (ctx: RequestContext) => Response | Promise<Response>,
|
|
71
|
+
routeOptions?: PluginRouteOptions,
|
|
72
|
+
): void => {
|
|
73
|
+
const normPath = path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
74
|
+
let byMethod = routeEntries.get(normPath)
|
|
75
|
+
if (byMethod === undefined) {
|
|
76
|
+
byMethod = new Map()
|
|
77
|
+
routeEntries.set(normPath, byMethod)
|
|
78
|
+
router.add(normPath, byMethod)
|
|
79
|
+
}
|
|
80
|
+
let routeTrustedOrigins = trustedOrigins
|
|
81
|
+
if (routeOptions?.trustedOrigins !== undefined && routeOptions.trustedOrigins.length > 0) {
|
|
82
|
+
routeTrustedOrigins = new Set([...(trustedOrigins ?? []), ...routeOptions.trustedOrigins])
|
|
83
|
+
}
|
|
84
|
+
byMethod.set(method.toUpperCase(), {
|
|
85
|
+
handler,
|
|
86
|
+
csrf: routeOptions?.csrf ?? true,
|
|
87
|
+
trustedOrigins: routeTrustedOrigins,
|
|
88
|
+
trustProxy: routeOptions?.trustProxy ?? trustProxy,
|
|
89
|
+
})
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const {
|
|
93
|
+
manifest: _m,
|
|
94
|
+
modules: _mods,
|
|
95
|
+
assets: _a,
|
|
96
|
+
publicAssets: _pa,
|
|
97
|
+
publicEtags: _pe,
|
|
98
|
+
prerendered: _pr,
|
|
99
|
+
prerenderedFiles: _pf,
|
|
100
|
+
...forwardedConfig
|
|
101
|
+
} = config as EmbeddedServerConfig & Record<string, unknown>
|
|
102
|
+
const readonlyRuntimeConfig: Readonly<Record<string, unknown>> = Object.freeze({ ...forwardedConfig })
|
|
103
|
+
|
|
104
|
+
for (const plugin of plugins) {
|
|
105
|
+
if (plugin.dispose !== undefined)
|
|
106
|
+
shutdownHooks.push(() => plugin.dispose!())
|
|
107
|
+
if (plugin.server !== undefined) {
|
|
108
|
+
const pluginApi: ServerPluginAPI = {
|
|
109
|
+
root: options.root,
|
|
110
|
+
outDir: options.outDir,
|
|
111
|
+
assetPrefix: options.assetPrefix,
|
|
112
|
+
site: options.site,
|
|
113
|
+
dev: options.dev,
|
|
114
|
+
trustProxy,
|
|
115
|
+
trustedOrigins: options.trustedOriginsList,
|
|
116
|
+
config: readonlyRuntimeConfig,
|
|
117
|
+
use(mw: Middleware, middlewareOptions?: MiddlewareOptions) {
|
|
118
|
+
scopedMiddlewares.push({ mw, scope: middlewareOptions?.scope ?? 'all' })
|
|
119
|
+
},
|
|
120
|
+
route: registerRoute,
|
|
121
|
+
rewrite(fn) {
|
|
122
|
+
rewrites.push(fn)
|
|
123
|
+
},
|
|
124
|
+
provide: appCtx.provide,
|
|
125
|
+
inject: appCtx.inject,
|
|
126
|
+
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined {
|
|
127
|
+
return manifest.pluginData?.[pluginName ?? plugin.name] as T | undefined
|
|
128
|
+
},
|
|
129
|
+
onShutdown(fn) {
|
|
130
|
+
shutdownHooks.push(fn)
|
|
131
|
+
},
|
|
132
|
+
invokeAction: options.invokeAction,
|
|
133
|
+
}
|
|
134
|
+
await runWithAppContext(appCtx, () => plugin.server!(pluginApi))
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const allMiddlewares: readonly Middleware[] = scopedMiddlewares.map(m => m.mw)
|
|
139
|
+
const staticFastMiddlewares: readonly Middleware[] = scopedMiddlewares
|
|
140
|
+
.filter(m => m.scope === 'all')
|
|
141
|
+
.map(m => m.mw)
|
|
142
|
+
const hasPathScopedMiddlewares = scopedMiddlewares.some(m => m.scope !== 'all' && m.scope !== 'dynamic')
|
|
143
|
+
const middlewaresFor = (path: string, isStaticFast = false): readonly Middleware[] => {
|
|
144
|
+
if (scopedMiddlewares.length === 0)
|
|
145
|
+
return allMiddlewares
|
|
146
|
+
if (!hasPathScopedMiddlewares)
|
|
147
|
+
return isStaticFast ? staticFastMiddlewares : allMiddlewares
|
|
148
|
+
return scopedMiddlewares.filter(m => middlewareAppliesToPath(m.scope, path, isStaticFast)).map(m => m.mw)
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
let disposed = false
|
|
152
|
+
async function dispose(): Promise<void> {
|
|
153
|
+
if (disposed)
|
|
154
|
+
return
|
|
155
|
+
disposed = true
|
|
156
|
+
for (const hook of shutdownHooks) {
|
|
157
|
+
try {
|
|
158
|
+
await hook()
|
|
159
|
+
}
|
|
160
|
+
catch {}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
return { router, rewrites, allMiddlewares, middlewaresFor, dispose }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export type ServerPluginHost = Awaited<ReturnType<typeof createServerPluginHost>>
|
package/src/server/router.ts
CHANGED
|
@@ -2,9 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
const ENCODED_SLASH_RE = /%2f/i
|
|
4
4
|
|
|
5
|
+
const enum SegmentKind {
|
|
6
|
+
Static = 0,
|
|
7
|
+
Param = 1,
|
|
8
|
+
CatchAll = 2,
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface CompiledSegment {
|
|
12
|
+
kind: SegmentKind
|
|
13
|
+
/** Exact literal for Static, parameter name for Param/CatchAll. */
|
|
14
|
+
value: string
|
|
15
|
+
}
|
|
16
|
+
|
|
5
17
|
interface RoutePattern<T> {
|
|
6
18
|
path: string
|
|
7
|
-
segments:
|
|
19
|
+
segments: CompiledSegment[]
|
|
8
20
|
isStatic: boolean
|
|
9
21
|
hasCatchAll: boolean
|
|
10
22
|
score: number
|
|
@@ -23,24 +35,28 @@ function normalizePath(path: string): string {
|
|
|
23
35
|
function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
24
36
|
const norm = normalizePath(path)
|
|
25
37
|
const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
|
|
26
|
-
const
|
|
38
|
+
const rawSegments = clean === '' ? [] : clean.split('/')
|
|
39
|
+
const segments: CompiledSegment[] = []
|
|
27
40
|
let isStatic = true
|
|
28
41
|
let hasCatchAll = false
|
|
29
42
|
let score = 0
|
|
30
43
|
|
|
31
|
-
for (let i = 0; i <
|
|
32
|
-
const seg =
|
|
44
|
+
for (let i = 0; i < rawSegments.length; i++) {
|
|
45
|
+
const seg = rawSegments[i]!
|
|
33
46
|
if (seg.startsWith('*')) {
|
|
34
47
|
isStatic = false
|
|
35
48
|
hasCatchAll = true
|
|
36
49
|
score += 1
|
|
50
|
+
segments.push({ kind: SegmentKind.CatchAll, value: seg.slice(1) || 'rest' })
|
|
37
51
|
}
|
|
38
52
|
else if (seg.startsWith(':')) {
|
|
39
53
|
isStatic = false
|
|
40
54
|
score += 10
|
|
55
|
+
segments.push({ kind: SegmentKind.Param, value: seg.slice(1) })
|
|
41
56
|
}
|
|
42
57
|
else {
|
|
43
58
|
score += 100
|
|
59
|
+
segments.push({ kind: SegmentKind.Static, value: seg })
|
|
44
60
|
}
|
|
45
61
|
}
|
|
46
62
|
|
|
@@ -50,6 +66,7 @@ function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
|
50
66
|
export class Router<T> {
|
|
51
67
|
readonly #staticRoutes = new Map<string, T>()
|
|
52
68
|
readonly #dynamicRoutes: RoutePattern<T>[] = []
|
|
69
|
+
#sorted = true
|
|
53
70
|
|
|
54
71
|
add(path: string, data: T): void {
|
|
55
72
|
const compiled = compileRoutePattern(path, data)
|
|
@@ -62,7 +79,7 @@ export class Router<T> {
|
|
|
62
79
|
this.#dynamicRoutes[existing] = compiled
|
|
63
80
|
else
|
|
64
81
|
this.#dynamicRoutes.push(compiled)
|
|
65
|
-
this.#
|
|
82
|
+
this.#sorted = false
|
|
66
83
|
}
|
|
67
84
|
}
|
|
68
85
|
|
|
@@ -73,12 +90,18 @@ export class Router<T> {
|
|
|
73
90
|
if (exact !== undefined)
|
|
74
91
|
return { data: exact, params: {} }
|
|
75
92
|
|
|
76
|
-
|
|
93
|
+
const dynLen = this.#dynamicRoutes.length
|
|
94
|
+
if (dynLen === 0)
|
|
77
95
|
return undefined
|
|
78
96
|
|
|
97
|
+
if (!this.#sorted) {
|
|
98
|
+
this.#dynamicRoutes.sort((a, b) => b.score - a.score || b.segments.length - a.segments.length)
|
|
99
|
+
this.#sorted = true
|
|
100
|
+
}
|
|
101
|
+
|
|
79
102
|
const parts = norm === '/' ? [] : norm.slice(1).split('/')
|
|
80
103
|
|
|
81
|
-
for (let i = 0; i <
|
|
104
|
+
for (let i = 0; i < dynLen; i++) {
|
|
82
105
|
const route = this.#dynamicRoutes[i]!
|
|
83
106
|
const segs = route.segments
|
|
84
107
|
|
|
@@ -87,32 +110,38 @@ export class Router<T> {
|
|
|
87
110
|
if (route.hasCatchAll && parts.length < segs.length - 1)
|
|
88
111
|
continue
|
|
89
112
|
|
|
90
|
-
const params: Record<string, string> = {}
|
|
91
113
|
let matched = true
|
|
92
|
-
|
|
93
114
|
for (let j = 0; j < segs.length; j++) {
|
|
94
115
|
const seg = segs[j]!
|
|
95
|
-
if (seg.
|
|
96
|
-
const name = seg.slice(1) || 'rest'
|
|
97
|
-
params[name] = parts.slice(j).map(decodeSegment).join('/')
|
|
116
|
+
if (seg.kind === SegmentKind.CatchAll)
|
|
98
117
|
break
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const rawSeg = parts[j]!
|
|
102
|
-
if (ENCODED_SLASH_RE.test(rawSeg)) {
|
|
118
|
+
if (seg.kind === SegmentKind.Param) {
|
|
119
|
+
if (ENCODED_SLASH_RE.test(parts[j]!)) {
|
|
103
120
|
matched = false
|
|
104
121
|
break
|
|
105
122
|
}
|
|
106
|
-
params[seg.slice(1)] = decodeSegment(rawSeg)
|
|
107
123
|
}
|
|
108
|
-
else if (seg !== parts[j]) {
|
|
124
|
+
else if (seg.value !== parts[j]) {
|
|
109
125
|
matched = false
|
|
110
126
|
break
|
|
111
127
|
}
|
|
112
128
|
}
|
|
113
129
|
|
|
114
|
-
if (matched)
|
|
115
|
-
|
|
130
|
+
if (!matched)
|
|
131
|
+
continue
|
|
132
|
+
|
|
133
|
+
// Allocate and decode params only for the winning route.
|
|
134
|
+
const params: Record<string, string> = {}
|
|
135
|
+
for (let j = 0; j < segs.length; j++) {
|
|
136
|
+
const seg = segs[j]!
|
|
137
|
+
if (seg.kind === SegmentKind.CatchAll) {
|
|
138
|
+
params[seg.value] = parts.slice(j).map(decodeSegment).join('/')
|
|
139
|
+
break
|
|
140
|
+
}
|
|
141
|
+
if (seg.kind === SegmentKind.Param)
|
|
142
|
+
params[seg.value] = decodeSegment(parts[j]!)
|
|
143
|
+
}
|
|
144
|
+
return { data: route.data, params }
|
|
116
145
|
}
|
|
117
146
|
|
|
118
147
|
return undefined
|
package/src/server/security.ts
CHANGED
|
@@ -12,6 +12,45 @@ export const KAY_ISLAND_STYLE_HASH = cspSha256(KAY_ISLAND_STYLE)
|
|
|
12
12
|
export const KAY_SUSPENSE_STYLE_HASH = cspSha256(KAY_SUSPENSE_STYLE)
|
|
13
13
|
export const KAY_STREAM_SCRIPT_HASH = cspSha256(KAY_STREAM_SCRIPT)
|
|
14
14
|
|
|
15
|
+
const STYLE_HASH_CACHE_SIZE = 256
|
|
16
|
+
const styleHashCache = new Map<string, string>()
|
|
17
|
+
|
|
18
|
+
// Hashes stay cached by content, so a layout's fixed block costs one SHA-256 per process; past the cap a new block is hashed each time.
|
|
19
|
+
function styleHash(content: string): string {
|
|
20
|
+
let hash = styleHashCache.get(content)
|
|
21
|
+
if (hash === undefined) {
|
|
22
|
+
hash = cspSha256(content)
|
|
23
|
+
if (styleHashCache.size < STYLE_HASH_CACHE_SIZE)
|
|
24
|
+
styleHashCache.set(content, hash)
|
|
25
|
+
}
|
|
26
|
+
return hash
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// A regex finds the next tag ~10x faster than `indexOf('<style')`, which stalls on every `<span` and `<strong` of a large page.
|
|
30
|
+
const STYLE_OPEN_RE = /<style[\s>/]/g
|
|
31
|
+
|
|
32
|
+
/** CSP hashes of the app's own `<style>` blocks in `html`, leaving out kay's island and Suspense styles (hashed apart). */
|
|
33
|
+
export function inlineStyleHashes(html: string): string[] {
|
|
34
|
+
const hashes: string[] = []
|
|
35
|
+
STYLE_OPEN_RE.lastIndex = 0
|
|
36
|
+
let open = STYLE_OPEN_RE.exec(html)
|
|
37
|
+
while (open !== null) {
|
|
38
|
+
const tagEnd = html.indexOf('>', open.index)
|
|
39
|
+
const close = tagEnd === -1 ? -1 : html.indexOf('</style', tagEnd)
|
|
40
|
+
if (close === -1)
|
|
41
|
+
break
|
|
42
|
+
const content = html.slice(tagEnd + 1, close)
|
|
43
|
+
if (content !== KAY_ISLAND_STYLE && content !== KAY_SUSPENSE_STYLE) {
|
|
44
|
+
const hash = styleHash(content)
|
|
45
|
+
if (!hashes.includes(hash))
|
|
46
|
+
hashes.push(hash)
|
|
47
|
+
}
|
|
48
|
+
STYLE_OPEN_RE.lastIndex = close
|
|
49
|
+
open = STYLE_OPEN_RE.exec(html)
|
|
50
|
+
}
|
|
51
|
+
return hashes
|
|
52
|
+
}
|
|
53
|
+
|
|
15
54
|
/** Augments a Content-Security-Policy header with exact SHA-256 hashes (no `'unsafe-inline'` required). */
|
|
16
55
|
export function withCspHashes(
|
|
17
56
|
csp: string,
|
|
@@ -68,7 +107,7 @@ export function withCspHashes(
|
|
|
68
107
|
}).join('; ')
|
|
69
108
|
}
|
|
70
109
|
|
|
71
|
-
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
|
|
110
|
+
export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; style-src-attr 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
|
|
72
111
|
export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
|
|
73
112
|
export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
|
|
74
113
|
|
|
@@ -137,8 +176,9 @@ export function isTrustedOrigin(
|
|
|
137
176
|
request: Request,
|
|
138
177
|
trustedOrigins?: ReadonlySet<string>,
|
|
139
178
|
trustProxy: TrustProxy = false,
|
|
179
|
+
requestUrl?: URL,
|
|
140
180
|
): boolean {
|
|
141
|
-
return origin === new URL(request.url).origin
|
|
181
|
+
return origin === (requestUrl?.origin ?? new URL(request.url).origin)
|
|
142
182
|
|| origin === forwardedOrigin(request, trustProxy)
|
|
143
183
|
|| trustedOrigins?.has(origin) === true
|
|
144
184
|
}
|
|
@@ -148,13 +188,14 @@ export function verifyOrigin(
|
|
|
148
188
|
request: Request,
|
|
149
189
|
trustedOrigins?: ReadonlySet<string>,
|
|
150
190
|
trustProxy: TrustProxy = false,
|
|
191
|
+
requestUrl?: URL,
|
|
151
192
|
): { ok: true } | { ok: false, reason: string } {
|
|
152
193
|
if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
|
|
153
194
|
return { ok: true }
|
|
154
195
|
|
|
155
196
|
const origin = request.headers.get('origin')
|
|
156
197
|
if (origin !== null) {
|
|
157
|
-
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy))
|
|
198
|
+
if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy, requestUrl))
|
|
158
199
|
return { ok: true }
|
|
159
200
|
return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
|
|
160
201
|
}
|