@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,61 @@
|
|
|
1
|
+
// Per-build / per-server scoped runtime context (AsyncLocalStorage-backed, zero mutable process globals).
|
|
2
|
+
|
|
3
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
4
|
+
|
|
5
|
+
export interface AppRuntimeContext {
|
|
6
|
+
readonly root: string
|
|
7
|
+
readonly outDir: string
|
|
8
|
+
readonly publicDir: string
|
|
9
|
+
readonly assetPrefix: string
|
|
10
|
+
readonly site?: string | undefined
|
|
11
|
+
readonly dev: boolean
|
|
12
|
+
provide<T>(key: string, value: T): void
|
|
13
|
+
inject<T>(key: string): T | undefined
|
|
14
|
+
registerPublicFile(relPath: string): void
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface CreateAppContextOptions {
|
|
18
|
+
root: string
|
|
19
|
+
outDir: string
|
|
20
|
+
publicDir: string
|
|
21
|
+
assetPrefix: string
|
|
22
|
+
site?: string | undefined
|
|
23
|
+
dev: boolean
|
|
24
|
+
onRegisterPublicFile?: ((relPath: string) => void) | undefined
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const APP_STORAGE_KEY = Symbol.for('kay.app.storage')
|
|
28
|
+
const appStorage: AsyncLocalStorage<AppRuntimeContext> = (
|
|
29
|
+
(globalThis as Record<symbol, AsyncLocalStorage<AppRuntimeContext> | undefined>)[APP_STORAGE_KEY]
|
|
30
|
+
??= new AsyncLocalStorage<AppRuntimeContext>()
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
export function createAppContext(options: CreateAppContextOptions): AppRuntimeContext {
|
|
34
|
+
const services = new Map<string, unknown>()
|
|
35
|
+
const site = options.site?.replace(/\/$/, '')
|
|
36
|
+
return {
|
|
37
|
+
root: options.root,
|
|
38
|
+
outDir: options.outDir,
|
|
39
|
+
publicDir: options.publicDir,
|
|
40
|
+
assetPrefix: options.assetPrefix,
|
|
41
|
+
...(site !== undefined && site !== '' ? { site } : {}),
|
|
42
|
+
dev: options.dev,
|
|
43
|
+
provide<T>(key: string, value: T): void {
|
|
44
|
+
services.set(key, value)
|
|
45
|
+
},
|
|
46
|
+
inject<T>(key: string): T | undefined {
|
|
47
|
+
return services.get(key) as T | undefined
|
|
48
|
+
},
|
|
49
|
+
registerPublicFile(relPath: string): void {
|
|
50
|
+
options.onRegisterPublicFile?.(relPath)
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function runWithAppContext<T>(ctx: AppRuntimeContext, fn: () => T): T {
|
|
56
|
+
return appStorage.run(ctx, fn)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function getAppContext(): AppRuntimeContext | undefined {
|
|
60
|
+
return appStorage.getStore()
|
|
61
|
+
}
|
package/src/plugins/index.ts
CHANGED
|
@@ -1,125 +1,12 @@
|
|
|
1
1
|
// Kay v2 public Plugin API & config helpers.
|
|
2
2
|
// Strict architectural rule: every non-core capability (@kayjs/tailwind, @kayjs/spa, @kayjs/i18n, etc.)
|
|
3
|
-
// is built strictly through these public hooks
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
export
|
|
13
|
-
readonly root: string
|
|
14
|
-
readonly outDir: string
|
|
15
|
-
readonly assetPrefix: string
|
|
16
|
-
readonly minify: boolean
|
|
17
|
-
readonly routes: readonly RouteManifestEntry[]
|
|
18
|
-
/** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
|
|
19
|
-
emitAsset(relPath: string, content: string | Uint8Array): string
|
|
20
|
-
/** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
|
|
21
|
-
emitPublic(relPath: string, content: string | Uint8Array): string
|
|
22
|
-
/** Add a stylesheet URL to <head> on every page. */
|
|
23
|
-
addStyle(href: string): void
|
|
24
|
-
/** Add a stylesheet URL to <head> on a specific route path only. */
|
|
25
|
-
addRouteStyle(routePath: string, href: string): void
|
|
26
|
-
/** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
|
|
27
|
-
addHead(html: string): void
|
|
28
|
-
/** Add raw HTML to <head> on a specific route path only. */
|
|
29
|
-
addRouteHead(routePath: string, html: string): void
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export interface CheckPluginContext {
|
|
33
|
-
readonly root: string
|
|
34
|
-
readonly routesDir: string
|
|
35
|
-
/** Report a validation error from `kay check`. */
|
|
36
|
-
error(message: string): void
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
export interface PluginRouteOptions {
|
|
40
|
-
/** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks). */
|
|
41
|
-
csrf?: boolean | undefined
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export interface ServerPluginAPI {
|
|
45
|
-
/** Register global middleware that runs before route handlers. */
|
|
46
|
-
use(middleware: Middleware): void
|
|
47
|
-
/** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
|
|
48
|
-
route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
|
|
49
|
-
/** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
|
|
50
|
-
rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export interface ServerErrorInfo {
|
|
54
|
-
error: unknown
|
|
55
|
-
request: Request
|
|
56
|
-
source: 'route' | 'action' | 'plugin'
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export interface KayPlugin {
|
|
60
|
-
name: string
|
|
61
|
-
/** Register server routes, global middleware, or URL rewrites. */
|
|
62
|
-
server?: (api: ServerPluginAPI) => void | Promise<void>
|
|
63
|
-
/** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
|
|
64
|
-
onError?: (info: ServerErrorInfo) => void
|
|
65
|
-
/** Build hook run after route compilation, before prerender / --static / --compile. */
|
|
66
|
-
build?: (ctx: BuildPluginContext) => void | Promise<void>
|
|
67
|
-
/** Code transform run during client & server compilation. */
|
|
68
|
-
transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
|
|
69
|
-
/** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). */
|
|
70
|
-
bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean }) => BunPlugin[]) | undefined
|
|
71
|
-
/** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
|
|
72
|
-
css?: string[] | undefined
|
|
73
|
-
/** Post-process rendered HTML before sending. */
|
|
74
|
-
transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
|
|
75
|
-
/** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
|
|
76
|
-
prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
|
|
77
|
-
/** Client bootstrap module path — bundled ONLY when this plugin is active. */
|
|
78
|
-
clientEntry?: string | undefined
|
|
79
|
-
/** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
|
|
80
|
-
check?: (ctx: CheckPluginContext) => void | Promise<void>
|
|
81
|
-
/** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
|
|
82
|
-
watchPaths?: string[] | ((root: string) => string[]) | undefined
|
|
83
|
-
/** Register custom CLI subcommands (e.g. `kay i18n check`). */
|
|
84
|
-
commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export interface KayConfig {
|
|
88
|
-
lang?: string | undefined
|
|
89
|
-
port?: number | undefined
|
|
90
|
-
routesDir?: string | undefined
|
|
91
|
-
outDir?: string | undefined
|
|
92
|
-
publicDir?: string | undefined
|
|
93
|
-
assetPrefix?: string | undefined
|
|
94
|
-
security?: SecurityHeadersOptions | false | undefined
|
|
95
|
-
trustedOrigins?: string[] | undefined
|
|
96
|
-
trustProxy?: boolean | undefined
|
|
97
|
-
maxRequestBodySize?: number | undefined
|
|
98
|
-
compress?: boolean | undefined
|
|
99
|
-
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
100
|
-
plugins?: KayPlugin[] | undefined
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
export function defineConfig(config: KayConfig): KayConfig {
|
|
104
|
-
return config
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
export function definePlugin(plugin: KayPlugin): KayPlugin {
|
|
108
|
-
return plugin
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const KAY_ROOT_KEY = Symbol.for('kay.root')
|
|
112
|
-
let configReloadSeq = 0
|
|
113
|
-
|
|
114
|
-
export async function loadConfig(root: string, options?: { fresh?: boolean }): Promise<KayConfig> {
|
|
115
|
-
const absRoot = resolve(root)
|
|
116
|
-
;(globalThis as Record<symbol, unknown>)[KAY_ROOT_KEY] = absRoot
|
|
117
|
-
const configPath = join(absRoot, 'kay.config.ts')
|
|
118
|
-
if (!existsSync(configPath))
|
|
119
|
-
return {}
|
|
120
|
-
const spec = options?.fresh || process.env.KAY_DEV === '1'
|
|
121
|
-
? `${configPath}?v=${++configReloadSeq}-${Date.now()}`
|
|
122
|
-
: configPath
|
|
123
|
-
const mod = await import(spec) as { default?: KayConfig }
|
|
124
|
-
return mod.default ?? {}
|
|
125
|
-
}
|
|
3
|
+
// is built strictly through these public hooks - never hardcoded in @kay/core.
|
|
4
|
+
|
|
5
|
+
export { defineConfig, definePlugin, pickRuntimeConfig, resolveServerConfig } from './config'
|
|
6
|
+
export { createAppContext, getAppContext, runWithAppContext } from './context'
|
|
7
|
+
export type { AppRuntimeContext, CreateAppContextOptions } from './context'
|
|
8
|
+
export { loadConfig } from './load'
|
|
9
|
+
export { resolvePlugins } from './order'
|
|
10
|
+
export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE } from './services'
|
|
11
|
+
export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult } from './services'
|
|
12
|
+
export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Native `kay.config.ts` load, for the build, check and dev steps that run beside the bundled app.
|
|
2
|
+
|
|
3
|
+
import type { AppRuntimeContext } from './context'
|
|
4
|
+
import type { KayConfig } from './types'
|
|
5
|
+
import { existsSync, readFileSync } from 'node:fs'
|
|
6
|
+
import { join, resolve } from 'node:path'
|
|
7
|
+
import { createAppContext, getAppContext, runWithAppContext } from './context'
|
|
8
|
+
|
|
9
|
+
let configReloadSeq = 0
|
|
10
|
+
|
|
11
|
+
// In dev the query follows the file content: a save elsewhere reuses the loaded config and its plugin instances instead of re-running every factory.
|
|
12
|
+
function configSpecifier(configPath: string, fresh: boolean): string {
|
|
13
|
+
if (fresh)
|
|
14
|
+
return `${configPath}?v=fresh-${++configReloadSeq}`
|
|
15
|
+
if (process.env.KAY_DEV === '1')
|
|
16
|
+
return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
|
|
17
|
+
return configPath
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export async function loadConfig(root: string, options?: { fresh?: boolean, appContext?: AppRuntimeContext }): Promise<KayConfig> {
|
|
21
|
+
const absRoot = resolve(root)
|
|
22
|
+
const configPath = join(absRoot, 'kay.config.ts')
|
|
23
|
+
if (!existsSync(configPath))
|
|
24
|
+
return {}
|
|
25
|
+
const spec = configSpecifier(configPath, options?.fresh === true)
|
|
26
|
+
const active = options?.appContext ?? getAppContext()
|
|
27
|
+
const ctx = active !== undefined && active.root === absRoot
|
|
28
|
+
? active
|
|
29
|
+
: createAppContext({
|
|
30
|
+
root: absRoot,
|
|
31
|
+
outDir: join(absRoot, 'dist'),
|
|
32
|
+
publicDir: join(absRoot, 'dist', 'public'),
|
|
33
|
+
assetPrefix: '/_kay',
|
|
34
|
+
dev: process.env.KAY_DEV === '1',
|
|
35
|
+
})
|
|
36
|
+
const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
|
|
37
|
+
return mod.default ?? {}
|
|
38
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// Plugin ordering: `enforce` buckets, `after` dependencies, and the `readsLocals`/`providesLocals` startup check.
|
|
2
|
+
|
|
3
|
+
import type { KayPlugin } from './types'
|
|
4
|
+
|
|
5
|
+
function enforceRank(plugin: KayPlugin): number {
|
|
6
|
+
return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
|
|
11
|
+
* then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
|
|
12
|
+
*/
|
|
13
|
+
export function resolvePlugins(plugins: readonly KayPlugin[] | undefined): KayPlugin[] {
|
|
14
|
+
if (plugins === undefined || plugins.length === 0)
|
|
15
|
+
return []
|
|
16
|
+
|
|
17
|
+
// Base stable order by `enforce` bucket, preserving config declaration order within each bucket.
|
|
18
|
+
const base = plugins
|
|
19
|
+
.map((plugin, index) => ({ plugin, index, rank: enforceRank(plugin) }))
|
|
20
|
+
.sort((a, b) => a.rank - b.rank || a.index - b.index)
|
|
21
|
+
.map(entry => entry.plugin)
|
|
22
|
+
|
|
23
|
+
const n = base.length
|
|
24
|
+
const indicesByName = new Map<string, number[]>()
|
|
25
|
+
for (let i = 0; i < n; i++) {
|
|
26
|
+
const name = base[i]!.name
|
|
27
|
+
const list = indicesByName.get(name)
|
|
28
|
+
if (list === undefined)
|
|
29
|
+
indicesByName.set(name, [i])
|
|
30
|
+
else
|
|
31
|
+
list.push(i)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Kahn's topological sort using min-index priority so `enforce` + declaration order stays deterministic.
|
|
35
|
+
const inDegree = new Int32Array(n)
|
|
36
|
+
const edges: number[][] = Array.from({ length: n }, () => [])
|
|
37
|
+
for (let i = 0; i < n; i++) {
|
|
38
|
+
const deps = base[i]!.after
|
|
39
|
+
if (deps === undefined)
|
|
40
|
+
continue
|
|
41
|
+
const seen = new Set<number>()
|
|
42
|
+
for (const depName of deps) {
|
|
43
|
+
const targets = indicesByName.get(depName)
|
|
44
|
+
if (targets === undefined)
|
|
45
|
+
continue
|
|
46
|
+
for (const depIdx of targets) {
|
|
47
|
+
if (depIdx === i || seen.has(depIdx))
|
|
48
|
+
continue
|
|
49
|
+
seen.add(depIdx)
|
|
50
|
+
edges[depIdx]!.push(i)
|
|
51
|
+
inDegree[i] = (inDegree[i] ?? 0) + 1
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const ready: number[] = []
|
|
57
|
+
for (let i = 0; i < n; i++) {
|
|
58
|
+
if (inDegree[i] === 0)
|
|
59
|
+
ready.push(i)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const sorted: KayPlugin[] = []
|
|
63
|
+
while (ready.length > 0) {
|
|
64
|
+
// Pick lowest base index so `enforce` and user declaration order are preserved whenever unconstrained.
|
|
65
|
+
let bestPos = 0
|
|
66
|
+
for (let k = 1; k < ready.length; k++) {
|
|
67
|
+
if (ready[k]! < ready[bestPos]!)
|
|
68
|
+
bestPos = k
|
|
69
|
+
}
|
|
70
|
+
const u = ready.splice(bestPos, 1)[0]!
|
|
71
|
+
sorted.push(base[u]!)
|
|
72
|
+
for (const v of edges[u]!) {
|
|
73
|
+
inDegree[v] = (inDegree[v] ?? 0) - 1
|
|
74
|
+
if (inDegree[v] === 0)
|
|
75
|
+
ready.push(v)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (sorted.length !== n) {
|
|
80
|
+
const stuck = base.filter((_, idx) => (inDegree[idx] ?? 0) > 0).map(p => p.name)
|
|
81
|
+
throw new Error(`kay: circular plugin \`after\` dependency involving: ${stuck.join(', ')}`)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Validate that no plugin reads a ctx.locals key before another active plugin provides it.
|
|
85
|
+
const providerByLocal = new Map<string, { name: string, index: number }>()
|
|
86
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
87
|
+
const plugin = sorted[i]!
|
|
88
|
+
for (const key of plugin.providesLocals ?? []) {
|
|
89
|
+
if (!providerByLocal.has(key))
|
|
90
|
+
providerByLocal.set(key, { name: plugin.name, index: i })
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
for (let i = 0; i < sorted.length; i++) {
|
|
95
|
+
const plugin = sorted[i]!
|
|
96
|
+
for (const key of plugin.readsLocals ?? []) {
|
|
97
|
+
const provider = providerByLocal.get(key)
|
|
98
|
+
if (provider !== undefined && provider.index > i) {
|
|
99
|
+
throw new Error(
|
|
100
|
+
`kay: plugin "${plugin.name}" reads ctx.locals.${key} before "${provider.name}" provides it. Add \`after: [${JSON.stringify(provider.name)}]\` or adjust plugin order.`,
|
|
101
|
+
)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return sorted
|
|
107
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Service keys shared between two plugins, kept in core as contracts so neither plugin depends on the other.
|
|
2
|
+
|
|
3
|
+
export interface ActiveI18nConfig {
|
|
4
|
+
readonly locales: readonly string[]
|
|
5
|
+
readonly defaultLocale: string
|
|
6
|
+
readonly prefixDefault: boolean
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export const I18N_CONFIG_SERVICE = 'kay.i18n.config'
|
|
10
|
+
|
|
11
|
+
export interface ContentImageResult {
|
|
12
|
+
src: string
|
|
13
|
+
srcset?: string | undefined
|
|
14
|
+
avifSrcset?: string | undefined
|
|
15
|
+
sizes?: string | undefined
|
|
16
|
+
width?: number | undefined
|
|
17
|
+
height?: number | undefined
|
|
18
|
+
loading?: 'lazy' | 'eager' | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
|
|
22
|
+
|
|
23
|
+
export const CONTENT_IMAGE_RESOLVER_SERVICE = 'kay.content.imageResolver'
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
// The plugin contract: what a `KayPlugin` declares and what the build, check and server hosts hand its hooks.
|
|
2
|
+
|
|
3
|
+
import type { BunPlugin } from 'bun'
|
|
4
|
+
import type { RouteManifestEntry } from '../build/index'
|
|
5
|
+
import type { ActionResult, ServerAction } from '../server/action'
|
|
6
|
+
import type { Middleware, RequestContext } from '../server/index'
|
|
7
|
+
import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
|
|
8
|
+
|
|
9
|
+
export type BuildPluginTarget = 'client' | 'server' | 'compile'
|
|
10
|
+
|
|
11
|
+
export interface BuildPluginContext {
|
|
12
|
+
readonly root: string
|
|
13
|
+
readonly outDir: string
|
|
14
|
+
readonly assetPrefix: string
|
|
15
|
+
readonly site?: string | undefined
|
|
16
|
+
readonly minify: boolean
|
|
17
|
+
readonly isStatic: boolean
|
|
18
|
+
readonly dev: boolean
|
|
19
|
+
readonly routes: readonly RouteManifestEntry[]
|
|
20
|
+
/** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
|
|
21
|
+
emitAsset(relPath: string, content: string | Uint8Array): string
|
|
22
|
+
/** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
|
|
23
|
+
emitPublic(relPath: string, content: string | Uint8Array): string
|
|
24
|
+
/** Add a stylesheet URL to <head> on every page. */
|
|
25
|
+
addStyle(href: string): void
|
|
26
|
+
/** Add a stylesheet URL to <head> on a specific route path only. */
|
|
27
|
+
addRouteStyle(routePath: string, href: string): void
|
|
28
|
+
/** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
|
|
29
|
+
addHead(html: string): void
|
|
30
|
+
/** Add raw HTML to <head> on a specific route path only. */
|
|
31
|
+
addRouteHead(routePath: string, html: string): void
|
|
32
|
+
/** Register an explicit build-scoped service for other plugins or render-time helpers. */
|
|
33
|
+
provide<T>(key: string, value: T): void
|
|
34
|
+
/** Look up a build-scoped service registered by another plugin. */
|
|
35
|
+
inject<T>(key: string): T | undefined
|
|
36
|
+
/** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
|
|
37
|
+
setData(data: Record<string, unknown>): void
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface FinalizeBuildContext {
|
|
41
|
+
readonly root: string
|
|
42
|
+
readonly outDir: string
|
|
43
|
+
readonly assetPrefix: string
|
|
44
|
+
readonly site?: string | undefined
|
|
45
|
+
readonly minify: boolean
|
|
46
|
+
readonly isStatic: boolean
|
|
47
|
+
readonly dev: boolean
|
|
48
|
+
/** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
|
|
49
|
+
readonly routes: readonly RouteManifestEntry[]
|
|
50
|
+
/** Relative paths of all public files known so far (including files registered during prerender). */
|
|
51
|
+
readonly publicFiles: readonly string[]
|
|
52
|
+
/** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
|
|
53
|
+
emitAsset(relPath: string, content: string | Uint8Array): string
|
|
54
|
+
/** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
|
|
55
|
+
emitPublic(relPath: string, content: string | Uint8Array): string
|
|
56
|
+
/** Register a build-scoped service. */
|
|
57
|
+
provide<T>(key: string, value: T): void
|
|
58
|
+
/** Look up a build-scoped service. */
|
|
59
|
+
inject<T>(key: string): T | undefined
|
|
60
|
+
/** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
|
|
61
|
+
setData(data: Record<string, unknown>): void
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface CheckPluginContext {
|
|
65
|
+
readonly root: string
|
|
66
|
+
readonly routesDir: string
|
|
67
|
+
/** Report a validation error from `kay check`. */
|
|
68
|
+
error(message: string): void
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface PluginRouteOptions {
|
|
72
|
+
/** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
|
|
73
|
+
csrf?: boolean | undefined
|
|
74
|
+
/** Additional trusted origins merged with `KayConfig.trustedOrigins` for this route's CSRF check. */
|
|
75
|
+
trustedOrigins?: readonly string[] | undefined
|
|
76
|
+
/** Override `KayConfig.trustProxy` for this route's CSRF check. */
|
|
77
|
+
trustProxy?: TrustProxy | undefined
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface MiddlewareOptions {
|
|
81
|
+
/** `'all'` (default) runs on every route; `'dynamic'` skips static/prerendered fast paths; a string prefix scopes to matching pathnames. */
|
|
82
|
+
scope?: 'all' | 'dynamic' | string | undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface ServerPluginAPI {
|
|
86
|
+
readonly root: string
|
|
87
|
+
readonly outDir: string
|
|
88
|
+
readonly assetPrefix: string
|
|
89
|
+
readonly site?: string | undefined
|
|
90
|
+
readonly dev: boolean
|
|
91
|
+
/** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
|
|
92
|
+
readonly trustProxy: TrustProxy
|
|
93
|
+
readonly trustedOrigins: readonly string[]
|
|
94
|
+
/** Readonly runtime config forwarded from `kay.config.ts` (minus build-only keys). */
|
|
95
|
+
readonly config?: Readonly<Record<string, unknown>> | undefined
|
|
96
|
+
/** Register global (or scoped) middleware that runs before route handlers. */
|
|
97
|
+
use(middleware: Middleware, options?: MiddlewareOptions): void
|
|
98
|
+
/** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
|
|
99
|
+
route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
|
|
100
|
+
/** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
|
|
101
|
+
rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
|
|
102
|
+
/** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
|
|
103
|
+
provide<T>(key: string, value: T): void
|
|
104
|
+
/** Look up a server-scoped service registered by another plugin. */
|
|
105
|
+
inject<T>(key: string): T | undefined
|
|
106
|
+
/** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
|
|
107
|
+
getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
|
|
108
|
+
/** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
|
|
109
|
+
onShutdown(fn: () => void | Promise<void>): void
|
|
110
|
+
/** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
|
|
111
|
+
invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface ServerErrorInfo {
|
|
115
|
+
error: unknown
|
|
116
|
+
request: Request
|
|
117
|
+
source: 'route' | 'action' | 'plugin'
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface DocumentHeadContext {
|
|
121
|
+
/** Current document `lang` attribute (mutating sets `<html lang="...">`). */
|
|
122
|
+
lang: string
|
|
123
|
+
/** Extra attributes emitted on `<html>`. */
|
|
124
|
+
readonly htmlAttrs: Record<string, string>
|
|
125
|
+
/** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
|
|
126
|
+
title: string | undefined
|
|
127
|
+
/** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
|
|
128
|
+
readonly headHtml: string
|
|
129
|
+
/** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
|
|
130
|
+
add(html: string): void
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface KayPlugin {
|
|
134
|
+
name: string
|
|
135
|
+
/** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
|
|
136
|
+
enforce?: 'pre' | 'post' | undefined
|
|
137
|
+
/** Names of plugins that must run before this plugin when present. */
|
|
138
|
+
after?: readonly string[] | undefined
|
|
139
|
+
/** `ctx.locals` keys this plugin populates (used for startup order validation). */
|
|
140
|
+
providesLocals?: readonly string[] | undefined
|
|
141
|
+
/** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
|
|
142
|
+
readsLocals?: readonly string[] | undefined
|
|
143
|
+
/** Register server routes, global middleware, URL rewrites, or runtime services. */
|
|
144
|
+
server?: (api: ServerPluginAPI) => void | Promise<void>
|
|
145
|
+
/** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
|
|
146
|
+
dispose?: () => void | Promise<void>
|
|
147
|
+
/** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
|
|
148
|
+
onError?: (info: ServerErrorInfo) => void
|
|
149
|
+
/** Build hook run after route compilation, before prerender / --static / --compile. */
|
|
150
|
+
build?: (ctx: BuildPluginContext) => void | Promise<void>
|
|
151
|
+
/** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
|
|
152
|
+
afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
|
|
153
|
+
/** Code transform run during client & server compilation (`.ts` and `.tsx`). */
|
|
154
|
+
transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
|
|
155
|
+
/** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
|
|
156
|
+
bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
|
|
157
|
+
/** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
|
|
158
|
+
css?: string[] | undefined
|
|
159
|
+
/** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
|
|
160
|
+
head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
|
|
161
|
+
/** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
|
|
162
|
+
transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
|
|
163
|
+
/** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
|
|
164
|
+
prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
|
|
165
|
+
/** Client bootstrap module path — bundled ONLY when this plugin is active. */
|
|
166
|
+
clientEntry?: string | undefined
|
|
167
|
+
/** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
|
|
168
|
+
check?: (ctx: CheckPluginContext) => void | Promise<void>
|
|
169
|
+
/** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
|
|
170
|
+
watchPaths?: string[] | ((root: string) => string[]) | undefined
|
|
171
|
+
/** Register custom CLI subcommands (e.g. `kay i18n check`). */
|
|
172
|
+
commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Shared runtime server options inherited from `kay.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
|
|
176
|
+
export interface ServerRuntimeConfig {
|
|
177
|
+
/** Public origin of the site (e.g. 'https://example.com'), inherited by @kayjs/seo, @kayjs/i18n, @kayjs/content, @kayjs/images, and @kayjs/auth. */
|
|
178
|
+
site?: string | undefined
|
|
179
|
+
lang?: string | undefined
|
|
180
|
+
assetPrefix?: string | undefined
|
|
181
|
+
security?: SecurityHeadersOptions | false | undefined
|
|
182
|
+
trustedOrigins?: string[] | undefined
|
|
183
|
+
trustProxy?: TrustProxy | undefined
|
|
184
|
+
maxRequestBodySize?: number | undefined
|
|
185
|
+
/** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
|
|
186
|
+
streamTimeout?: number | undefined
|
|
187
|
+
compress?: boolean | undefined
|
|
188
|
+
onError?: ((info: ServerErrorInfo) => void) | undefined
|
|
189
|
+
plugins?: KayPlugin[] | undefined
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export interface KayConfig extends ServerRuntimeConfig {
|
|
193
|
+
port?: number | undefined
|
|
194
|
+
routesDir?: string | undefined
|
|
195
|
+
outDir?: string | undefined
|
|
196
|
+
publicDir?: string | undefined
|
|
197
|
+
}
|