@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +617 -0
- package/src/build/compile.ts +27 -51
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +272 -1466
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +229 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +102 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/server-entry.ts +38 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +339 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/config.ts +49 -0
- package/src/plugins/context.ts +61 -0
- package/src/plugins/index.ts +10 -123
- package/src/plugins/load.ts +38 -0
- package/src/plugins/order.ts +107 -0
- package/src/plugins/services.ts +23 -0
- package/src/plugins/types.ts +197 -0
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action-registry.ts +72 -0
- package/src/server/action.ts +157 -79
- package/src/server/app-entry.ts +23 -0
- package/src/server/assets.ts +182 -0
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/document.ts +192 -0
- package/src/server/env.ts +18 -13
- package/src/server/errors.ts +123 -0
- package/src/server/http.ts +203 -77
- package/src/server/index.ts +420 -973
- package/src/server/loader.ts +113 -0
- package/src/server/page.ts +107 -0
- package/src/server/plugin-host.ts +167 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +90 -59
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +163 -0
- package/src/server/stream.ts +94 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +24 -18
- package/src/unrenderable.ts +35 -0
|
@@ -0,0 +1,113 @@
|
|
|
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
|
+
|
|
3
|
+
import type { BuildManifest } from '../build/index'
|
|
4
|
+
import type { ServerEntry } from './app-entry'
|
|
5
|
+
import type { EmbeddedBody, KayApp, ServerOptions } from './http'
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
|
|
7
|
+
import { join, resolve } from 'node:path'
|
|
8
|
+
import { SERVER_ENTRY_FILE } from '../build/server-entry'
|
|
9
|
+
import { loadConfig, resolveServerConfig } from '../plugins/index'
|
|
10
|
+
import { createStaticDirServer } from './static-dir'
|
|
11
|
+
|
|
12
|
+
let serverLoadSeq = 0
|
|
13
|
+
|
|
14
|
+
export async function createServer(options: ServerOptions): Promise<KayApp> {
|
|
15
|
+
return (await startBuiltApp(options)).app
|
|
16
|
+
}
|
|
17
|
+
|
|
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')
|
|
25
|
+
const assets: Record<string, EmbeddedBody> = {}
|
|
26
|
+
const publicAssets: Record<string, EmbeddedBody> = {}
|
|
27
|
+
const publicEtags: Record<string, string> = {}
|
|
28
|
+
const prerenderedFiles: Record<string, string> = {}
|
|
29
|
+
const srcPublicDir = resolve(root, entry.kayConfig.publicDir ?? 'public')
|
|
30
|
+
|
|
31
|
+
// File paths only: Bun.file() serves them zero-copy, and nothing is read at startup.
|
|
32
|
+
for (const rel of manifest.assets) {
|
|
33
|
+
const abs = join(clientDir, rel)
|
|
34
|
+
if (existsSync(abs)) {
|
|
35
|
+
assets[rel] = abs
|
|
36
|
+
if (existsSync(`${abs}.br`))
|
|
37
|
+
assets[`${rel}.br`] = `${abs}.br`
|
|
38
|
+
if (existsSync(`${abs}.gz`))
|
|
39
|
+
assets[`${rel}.gz`] = `${abs}.gz`
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
for (const rel of manifest.publicFiles ?? []) {
|
|
44
|
+
const outAbs = join(outDir, 'public', rel)
|
|
45
|
+
const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
|
|
46
|
+
if (existsSync(abs)) {
|
|
47
|
+
publicAssets[rel] = abs
|
|
48
|
+
const st = statSync(abs)
|
|
49
|
+
publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (const r of manifest.routes) {
|
|
54
|
+
for (const relHtml of Object.values(r.prerendered ?? {})) {
|
|
55
|
+
const abs = join(outDir, relHtml)
|
|
56
|
+
if (existsSync(abs))
|
|
57
|
+
prerenderedFiles[relHtml] = abs
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const app = await entry.createApp({
|
|
62
|
+
...resolveServerConfig(undefined, options),
|
|
63
|
+
manifest,
|
|
64
|
+
assets,
|
|
65
|
+
publicAssets,
|
|
66
|
+
publicEtags,
|
|
67
|
+
prerenderedFiles,
|
|
68
|
+
root,
|
|
69
|
+
outDir,
|
|
70
|
+
publicDir: join(outDir, 'public'),
|
|
71
|
+
dev: options.dev ?? (process.env.KAY_DEV === '1'),
|
|
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
|
+
)
|
|
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
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
// File-based route matcher: static > [param] > [...catchall] priority sorting + param extraction.
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
const ENCODED_SLASH_RE = /%2f/i
|
|
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
|
+
|
|
17
|
+
interface RoutePattern<T> {
|
|
4
18
|
path: string
|
|
5
|
-
segments:
|
|
19
|
+
segments: CompiledSegment[]
|
|
6
20
|
isStatic: boolean
|
|
7
21
|
hasCatchAll: boolean
|
|
8
22
|
score: number
|
|
@@ -14,57 +28,80 @@ export interface RouteMatch<T> {
|
|
|
14
28
|
params: Record<string, string>
|
|
15
29
|
}
|
|
16
30
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
31
|
+
function normalizePath(path: string): string {
|
|
32
|
+
return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
|
|
36
|
+
const norm = normalizePath(path)
|
|
37
|
+
const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
|
|
38
|
+
const rawSegments = clean === '' ? [] : clean.split('/')
|
|
39
|
+
const segments: CompiledSegment[] = []
|
|
20
40
|
let isStatic = true
|
|
21
41
|
let hasCatchAll = false
|
|
22
42
|
let score = 0
|
|
23
43
|
|
|
24
|
-
for (let i = 0; i <
|
|
25
|
-
const seg =
|
|
44
|
+
for (let i = 0; i < rawSegments.length; i++) {
|
|
45
|
+
const seg = rawSegments[i]!
|
|
26
46
|
if (seg.startsWith('*')) {
|
|
27
47
|
isStatic = false
|
|
28
48
|
hasCatchAll = true
|
|
29
49
|
score += 1
|
|
50
|
+
segments.push({ kind: SegmentKind.CatchAll, value: seg.slice(1) || 'rest' })
|
|
30
51
|
}
|
|
31
52
|
else if (seg.startsWith(':')) {
|
|
32
53
|
isStatic = false
|
|
33
54
|
score += 10
|
|
55
|
+
segments.push({ kind: SegmentKind.Param, value: seg.slice(1) })
|
|
34
56
|
}
|
|
35
57
|
else {
|
|
36
58
|
score += 100
|
|
59
|
+
segments.push({ kind: SegmentKind.Static, value: seg })
|
|
37
60
|
}
|
|
38
61
|
}
|
|
39
62
|
|
|
40
|
-
return { path, segments, isStatic, hasCatchAll, score, data }
|
|
63
|
+
return { path: norm, segments, isStatic, hasCatchAll, score, data }
|
|
41
64
|
}
|
|
42
65
|
|
|
43
66
|
export class Router<T> {
|
|
44
67
|
readonly #staticRoutes = new Map<string, T>()
|
|
45
68
|
readonly #dynamicRoutes: RoutePattern<T>[] = []
|
|
69
|
+
#sorted = true
|
|
46
70
|
|
|
47
71
|
add(path: string, data: T): void {
|
|
48
72
|
const compiled = compileRoutePattern(path, data)
|
|
49
73
|
if (compiled.isStatic) {
|
|
50
|
-
this.#staticRoutes.set(path, data)
|
|
74
|
+
this.#staticRoutes.set(compiled.path, data)
|
|
51
75
|
}
|
|
52
76
|
else {
|
|
53
|
-
this.#dynamicRoutes.
|
|
54
|
-
|
|
77
|
+
const existing = this.#dynamicRoutes.findIndex(r => r.path === compiled.path)
|
|
78
|
+
if (existing !== -1)
|
|
79
|
+
this.#dynamicRoutes[existing] = compiled
|
|
80
|
+
else
|
|
81
|
+
this.#dynamicRoutes.push(compiled)
|
|
82
|
+
this.#sorted = false
|
|
55
83
|
}
|
|
56
84
|
}
|
|
57
85
|
|
|
58
86
|
match(pathname: string): RouteMatch<T> | undefined {
|
|
59
|
-
const norm =
|
|
87
|
+
const norm = normalizePath(pathname)
|
|
60
88
|
|
|
61
89
|
const exact = this.#staticRoutes.get(norm)
|
|
62
90
|
if (exact !== undefined)
|
|
63
91
|
return { data: exact, params: {} }
|
|
64
92
|
|
|
93
|
+
const dynLen = this.#dynamicRoutes.length
|
|
94
|
+
if (dynLen === 0)
|
|
95
|
+
return undefined
|
|
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
|
+
|
|
65
102
|
const parts = norm === '/' ? [] : norm.slice(1).split('/')
|
|
66
103
|
|
|
67
|
-
for (let i = 0; i <
|
|
104
|
+
for (let i = 0; i < dynLen; i++) {
|
|
68
105
|
const route = this.#dynamicRoutes[i]!
|
|
69
106
|
const segs = route.segments
|
|
70
107
|
|
|
@@ -73,32 +110,38 @@ export class Router<T> {
|
|
|
73
110
|
if (route.hasCatchAll && parts.length < segs.length - 1)
|
|
74
111
|
continue
|
|
75
112
|
|
|
76
|
-
const params: Record<string, string> = {}
|
|
77
113
|
let matched = true
|
|
78
|
-
|
|
79
114
|
for (let j = 0; j < segs.length; j++) {
|
|
80
115
|
const seg = segs[j]!
|
|
81
|
-
if (seg.
|
|
82
|
-
const name = seg.slice(1) || 'rest'
|
|
83
|
-
params[name] = parts.slice(j).map(decodeSegment).join('/')
|
|
116
|
+
if (seg.kind === SegmentKind.CatchAll)
|
|
84
117
|
break
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
const rawSeg = parts[j]!
|
|
88
|
-
if (/%2f/i.test(rawSeg)) {
|
|
118
|
+
if (seg.kind === SegmentKind.Param) {
|
|
119
|
+
if (ENCODED_SLASH_RE.test(parts[j]!)) {
|
|
89
120
|
matched = false
|
|
90
121
|
break
|
|
91
122
|
}
|
|
92
|
-
params[seg.slice(1)] = decodeSegment(rawSeg)
|
|
93
123
|
}
|
|
94
|
-
else if (seg !== parts[j]) {
|
|
124
|
+
else if (seg.value !== parts[j]) {
|
|
95
125
|
matched = false
|
|
96
126
|
break
|
|
97
127
|
}
|
|
98
128
|
}
|
|
99
129
|
|
|
100
|
-
if (matched)
|
|
101
|
-
|
|
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 }
|
|
102
145
|
}
|
|
103
146
|
|
|
104
147
|
return undefined
|