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

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 (101) hide show
  1. package/llms.txt +42 -0
  2. package/package.json +24 -13
  3. package/src/build/bundle.ts +15 -53
  4. package/src/build/client-plugin.ts +108 -0
  5. package/src/build/compile.ts +9 -44
  6. package/src/build/graph.ts +16 -3
  7. package/src/build/index.ts +45 -25
  8. package/src/build/islands.ts +28 -30
  9. package/src/build/manifest.ts +9 -4
  10. package/src/build/prerender.ts +15 -7
  11. package/src/build/report.ts +82 -13
  12. package/src/build/resolve.ts +6 -7
  13. package/src/build/routes.ts +12 -21
  14. package/src/build/server-entry.ts +38 -0
  15. package/src/cli/check.ts +49 -43
  16. package/src/cli/commands.ts +224 -0
  17. package/src/cli/index.ts +46 -302
  18. package/src/cli/new.ts +15 -509
  19. package/src/cli/upgrade-plugins.ts +168 -0
  20. package/src/cli/upgrade.ts +220 -0
  21. package/src/compiler/analyze.ts +319 -565
  22. package/src/compiler/ast.ts +39 -0
  23. package/src/compiler/data-keys.ts +233 -0
  24. package/src/compiler/dom.ts +18 -15
  25. package/src/compiler/interactivity.ts +174 -0
  26. package/src/compiler/mistakes.ts +19 -1
  27. package/src/compiler/server-only.ts +4 -1
  28. package/src/compiler/shared.ts +1 -1
  29. package/src/compiler/ssr.ts +28 -28
  30. package/src/context.ts +1 -1
  31. package/src/dev/index.ts +19 -46
  32. package/src/dom/extras.ts +43 -12
  33. package/src/dom/index.ts +25 -1
  34. package/src/index.ts +0 -13
  35. package/src/jsx-runtime.ts +1 -1
  36. package/src/plugins/config.ts +49 -0
  37. package/src/plugins/context.ts +8 -28
  38. package/src/plugins/index.ts +10 -385
  39. package/src/plugins/load.ts +61 -0
  40. package/src/plugins/order.ts +107 -0
  41. package/src/plugins/public.ts +6 -0
  42. package/src/plugins/services.ts +35 -0
  43. package/src/plugins/types.ts +193 -0
  44. package/src/server/action-registry.ts +78 -0
  45. package/src/server/action.ts +8 -2
  46. package/src/server/app-entry.ts +23 -0
  47. package/src/server/assets.ts +182 -0
  48. package/src/server/document.ts +204 -0
  49. package/src/server/errors.ts +125 -0
  50. package/src/server/http.ts +14 -0
  51. package/src/server/index.ts +66 -766
  52. package/src/server/lifecycle.ts +22 -0
  53. package/src/server/loader.ts +60 -85
  54. package/src/server/page.ts +107 -0
  55. package/src/server/plugin-host.ts +165 -0
  56. package/src/server/public.ts +15 -0
  57. package/src/server/request-scope.ts +22 -0
  58. package/src/server/security.ts +40 -1
  59. package/src/server/static-dir.ts +22 -3
  60. package/src/server/stream.ts +95 -0
  61. package/src/ssr/context.ts +25 -0
  62. package/src/ssr/index.ts +10 -7
  63. package/src/test/browser.ts +180 -0
  64. package/src/test/index.ts +25 -6
  65. package/templates/_shared/AGENTS.md +5 -0
  66. package/templates/_shared/CLAUDE.md +1 -0
  67. package/templates/_shared/public/robots.txt +2 -0
  68. package/templates/_shared/tsconfig.json +19 -0
  69. package/templates/app/.env.example +4 -0
  70. package/templates/app/kay.config.ts +11 -0
  71. package/templates/app/package.json +20 -0
  72. package/templates/app/src/auth.ts +14 -0
  73. package/templates/app/src/routes/_layout.tsx +32 -0
  74. package/templates/app/src/routes/dashboard/_middleware.ts +3 -0
  75. package/templates/app/src/routes/dashboard/index.tsx +13 -0
  76. package/templates/app/src/routes/index.tsx +15 -0
  77. package/templates/app/src/routes/login.tsx +34 -0
  78. package/templates/app/src/styles/app.css +7 -0
  79. package/templates/blog/content/posts/welcome.md +9 -0
  80. package/templates/blog/kay.config.ts +23 -0
  81. package/templates/blog/package.json +21 -0
  82. package/templates/blog/src/posts.ts +26 -0
  83. package/templates/blog/src/routes/_layout.tsx +20 -0
  84. package/templates/blog/src/routes/blog/[slug].tsx +31 -0
  85. package/templates/blog/src/routes/index.tsx +29 -0
  86. package/templates/blog/src/styles/app.css +10 -0
  87. package/templates/fullstack/kay.config.ts +6 -0
  88. package/templates/fullstack/package.json +18 -0
  89. package/templates/fullstack/src/actions/greet.ts +19 -0
  90. package/templates/fullstack/src/components/Counter.tsx +10 -0
  91. package/templates/fullstack/src/components/GreetForm.tsx +26 -0
  92. package/templates/fullstack/src/routes/_layout.tsx +14 -0
  93. package/templates/fullstack/src/routes/api/health.ts +5 -0
  94. package/templates/fullstack/src/routes/index.tsx +13 -0
  95. package/templates/fullstack/src/styles/app.css +29 -0
  96. package/templates/minimal/kay.config.ts +6 -0
  97. package/templates/minimal/package.json +18 -0
  98. package/templates/minimal/src/components/Counter.tsx +10 -0
  99. package/templates/minimal/src/routes/_layout.tsx +14 -0
  100. package/templates/minimal/src/routes/index.tsx +11 -0
  101. package/templates/minimal/src/styles/app.css +22 -0
@@ -1,387 +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 — never hardcoded in @kay/core.
4
-
5
- import type { BunPlugin } from 'bun'
6
- import type { RouteManifestEntry } from '../build/index'
7
- import type { ActionResult, ServerAction } from '../server/action'
8
- import type { Middleware, RequestContext } from '../server/index'
9
- import type { SecurityHeadersOptions, TrustProxy } from '../server/security'
10
- import type { AppRuntimeContext } from './context'
11
- import { existsSync, readFileSync } from 'node:fs'
12
- import { join, resolve } from 'node:path'
13
- import { createAppContext, getAppContext, runWithAppContext } from './context'
14
-
15
- export { CONTENT_IMAGE_RESOLVER_SERVICE, createAppContext, getAppContext, I18N_CONFIG_SERVICE, runWithAppContext } from './context'
16
- export type { ActiveI18nConfig, AppRuntimeContext, ContentImageResolver, ContentImageResult, CreateAppContextOptions } from './context'
17
-
18
- export type BuildPluginTarget = 'client' | 'server' | 'compile'
19
-
20
- export interface BuildPluginContext {
21
- readonly root: string
22
- readonly outDir: string
23
- readonly assetPrefix: string
24
- readonly site?: string | undefined
25
- readonly minify: boolean
26
- readonly isStatic: boolean
27
- readonly dev: boolean
28
- readonly routes: readonly RouteManifestEntry[]
29
- /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
30
- emitAsset(relPath: string, content: string | Uint8Array): string
31
- /** Emit a static file into dist/public/<relPath> served at `/<relPath>`. */
32
- emitPublic(relPath: string, content: string | Uint8Array): string
33
- /** Add a stylesheet URL to <head> on every page. */
34
- addStyle(href: string): void
35
- /** Add a stylesheet URL to <head> on a specific route path only. */
36
- addRouteStyle(routePath: string, href: string): void
37
- /** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
38
- addHead(html: string): void
39
- /** Add raw HTML to <head> on a specific route path only. */
40
- addRouteHead(routePath: string, html: string): void
41
- /** Register an explicit build-scoped service for other plugins or render-time helpers. */
42
- provide<T>(key: string, value: T): void
43
- /** Look up a build-scoped service registered by another plugin. */
44
- inject<T>(key: string): T | undefined
45
- /** Persist JSON-serializable build data into `manifest.pluginData[plugin.name]` for cold-start servers and `--compile`. */
46
- setData(data: Record<string, unknown>): void
47
- }
48
-
49
- export interface FinalizeBuildContext {
50
- readonly root: string
51
- readonly outDir: string
52
- readonly assetPrefix: string
53
- readonly site?: string | undefined
54
- readonly minify: boolean
55
- readonly isStatic: boolean
56
- readonly dev: boolean
57
- /** Route manifest entries with `prerendered` maps populated after Step 3 prerendering. */
58
- readonly routes: readonly RouteManifestEntry[]
59
- /** Relative paths of all public files known so far (including files registered during prerender). */
60
- readonly publicFiles: readonly string[]
61
- /** Emit an immutable build asset into dist/client/<relPath>; returns its public URL (`/_kay/<relPath>`). */
62
- emitAsset(relPath: string, content: string | Uint8Array): string
63
- /** Emit a static file into dist/public/<relPath> served at `/<relPath>` (included in `--static` and `--compile`). */
64
- emitPublic(relPath: string, content: string | Uint8Array): string
65
- /** Register a build-scoped service. */
66
- provide<T>(key: string, value: T): void
67
- /** Look up a build-scoped service. */
68
- inject<T>(key: string): T | undefined
69
- /** Merge/persist JSON-serializable build data into `manifest.pluginData[plugin.name]`. */
70
- setData(data: Record<string, unknown>): void
71
- }
72
-
73
- export interface CheckPluginContext {
74
- readonly root: string
75
- readonly routesDir: string
76
- /** Report a validation error from `kay check`. */
77
- error(message: string): void
78
- }
79
-
80
- export interface PluginRouteOptions {
81
- /** Enable CSRF Origin/Sec-Fetch-Site verification on unsafe methods (default: true). Set `false` to opt out (e.g. webhooks, bearer-token APIs). */
82
- csrf?: boolean | undefined
83
- /** Additional trusted origins merged with `KayConfig.trustedOrigins` for this route's CSRF check. */
84
- trustedOrigins?: readonly string[] | undefined
85
- /** Override `KayConfig.trustProxy` for this route's CSRF check. */
86
- trustProxy?: TrustProxy | undefined
87
- }
88
-
89
- export interface MiddlewareOptions {
90
- /** `'all'` (default) runs on every route; `'dynamic'` skips static/prerendered fast paths; a string prefix scopes to matching pathnames. */
91
- scope?: 'all' | 'dynamic' | string | undefined
92
- }
93
-
94
- export interface ServerPluginAPI {
95
- readonly root: string
96
- readonly outDir: string
97
- readonly assetPrefix: string
98
- readonly site?: string | undefined
99
- readonly dev: boolean
100
- /** Readonly server security configuration so plugins inherit `trustProxy` / `trustedOrigins` without overriding them. */
101
- readonly trustProxy: TrustProxy
102
- readonly trustedOrigins: readonly string[]
103
- /** Readonly runtime config forwarded from `kay.config.ts` (minus build-only keys). */
104
- readonly config?: Readonly<Record<string, unknown>> | undefined
105
- /** Register global (or scoped) middleware that runs before route handlers. */
106
- use(middleware: Middleware, options?: MiddlewareOptions): void
107
- /** Register a custom HTTP route (e.g. GET /sitemap.xml, POST /auth/callback). */
108
- route(method: string, path: string, handler: (ctx: RequestContext) => Response | Promise<Response>, options?: PluginRouteOptions): void
109
- /** Rewrite an incoming pathname before route matching (e.g. strip /fr locale prefix). */
110
- rewrite(fn: (pathname: string, ctx: RequestContext) => string | undefined): void
111
- /** Register a server-scoped service for other plugins or render-time helpers (isolated per server instance). */
112
- provide<T>(key: string, value: T): void
113
- /** Look up a server-scoped service registered by another plugin. */
114
- inject<T>(key: string): T | undefined
115
- /** Read persisted build data from `manifest.pluginData` (defaults to the current plugin's name). */
116
- getBuildData<T = Record<string, unknown>>(pluginName?: string): T | undefined
117
- /** Register a shutdown cleanup callback run when `app.dispose()` is called (dev reloads, tests, graceful exit). */
118
- onShutdown(fn: () => void | Promise<void>): void
119
- /** Invoke a ServerAction with Standard Schema validation and directory-scoped `_middleware.ts` checks. */
120
- invokeAction<I, O>(action: ServerAction<I, O>, input: I, ctx: RequestContext): Promise<ActionResult<O>>
121
- }
122
-
123
- export interface ServerErrorInfo {
124
- error: unknown
125
- request: Request
126
- source: 'route' | 'action' | 'plugin'
127
- }
128
-
129
- export interface DocumentHeadContext {
130
- /** Current document `lang` attribute (mutating sets `<html lang="...">`). */
131
- lang: string
132
- /** Extra attributes emitted on `<html>`. */
133
- readonly htmlAttrs: Record<string, string>
134
- /** Inner HTML of the page's `<title>` tag (if rendered via `<Head><title>...</title></Head>`), or `undefined`. */
135
- title: string | undefined
136
- /** Read-only view of head HTML already collected from `<Head>`, build `addHead`, and earlier plugins. */
137
- readonly headHtml: string
138
- /** Append raw HTML to `<head>` (emitted once by core when assembling the document). */
139
- add(html: string): void
140
- }
141
-
142
- export interface KayPlugin {
143
- name: string
144
- /** Execution phase: `'pre'` runs before normal plugins, `'post'` runs after them. */
145
- enforce?: 'pre' | 'post' | undefined
146
- /** Names of plugins that must run before this plugin when present. */
147
- after?: readonly string[] | undefined
148
- /** `ctx.locals` keys this plugin populates (used for startup order validation). */
149
- providesLocals?: readonly string[] | undefined
150
- /** `ctx.locals` keys this plugin reads (startup fails if a provider is ordered after it). */
151
- readsLocals?: readonly string[] | undefined
152
- /** Register server routes, global middleware, URL rewrites, or runtime services. */
153
- server?: (api: ServerPluginAPI) => void | Promise<void>
154
- /** Optional cleanup hook called when a server instance is disposed (dev reloads, tests, graceful shutdown). */
155
- dispose?: () => void | Promise<void>
156
- /** Error hook called whenever a route, action, or plugin handler throws an unhandled error. */
157
- onError?: (info: ServerErrorInfo) => void
158
- /** Build hook run after route compilation, before prerender / --static / --compile. */
159
- build?: (ctx: BuildPluginContext) => void | Promise<void>
160
- /** Post-prerender build hook run after `route.prerendered` is populated, before `--static` / `--compile` / final manifest write. */
161
- afterPrerender?: (ctx: FinalizeBuildContext) => void | Promise<void>
162
- /** Code transform run during client & server compilation (`.ts` and `.tsx`). */
163
- transform?: (code: string, id: string, target: 'server' | 'client') => string | undefined | void
164
- /** Native Bun.build plugins (e.g. bun-plugin-tailwind, images, icons). Factory is invoked per build target. */
165
- bunPlugins?: BunPlugin[] | ((info: { root: string, assetPrefix: string, minify: boolean, target: BuildPluginTarget }) => BunPlugin[]) | undefined
166
- /** Global CSS files to bundle and inject as <link rel="stylesheet"> in <head>. */
167
- css?: string[] | undefined
168
- /** Mutate `<html lang>`, `htmlAttrs`, `<title>`, or append tags to `<head>` before core renders the document once. */
169
- head?: (head: DocumentHeadContext, ctx: RequestContext) => void | Promise<void>
170
- /** Post-process rendered HTML before sending (applies to pages, `<Suspense>` shells, `_error.tsx`, and `_404.tsx`). */
171
- transformHtml?: (html: string, ctx: RequestContext) => string | Promise<string>
172
- /** Expand or filter prerender URLs for a route (e.g. @kayjs/i18n expanding `/posts/a` -> `['/posts/a', '/fr/posts/a']`). */
173
- prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
174
- /** Client bootstrap module path — bundled ONLY when this plugin is active. */
175
- clientEntry?: string | undefined
176
- /** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
177
- check?: (ctx: CheckPluginContext) => void | Promise<void>
178
- /** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
179
- watchPaths?: string[] | ((root: string) => string[]) | undefined
180
- /** Register custom CLI subcommands (e.g. `kay i18n check`). */
181
- commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
182
- }
183
-
184
- /** Shared runtime server options inherited from `kay.config.ts` and overridable by `createServer`, `testApp`, `devServer`, and `--compile`. */
185
- export interface ServerRuntimeConfig {
186
- /** Public origin of the site (e.g. 'https://example.com'), inherited by @kayjs/seo, @kayjs/i18n, @kayjs/content, @kayjs/images, and @kayjs/auth. */
187
- site?: string | undefined
188
- lang?: string | undefined
189
- assetPrefix?: string | undefined
190
- security?: SecurityHeadersOptions | false | undefined
191
- trustedOrigins?: string[] | undefined
192
- trustProxy?: TrustProxy | undefined
193
- maxRequestBodySize?: number | undefined
194
- /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
195
- streamTimeout?: number | undefined
196
- compress?: boolean | undefined
197
- onError?: ((info: ServerErrorInfo) => void) | undefined
198
- plugins?: KayPlugin[] | undefined
199
- }
200
-
201
- export interface KayConfig extends ServerRuntimeConfig {
202
- port?: number | undefined
203
- routesDir?: string | undefined
204
- outDir?: string | undefined
205
- publicDir?: string | undefined
206
- }
207
-
208
- export function defineConfig(config: KayConfig): KayConfig {
209
- return config
210
- }
211
-
212
- /** Forwards every runtime key from `kay.config.ts`, stripping build/CLI-only keys (`routesDir`, `outDir`, `publicDir`, `port`). */
213
- export function pickRuntimeConfig(config: KayConfig | undefined): ServerRuntimeConfig {
214
- if (config === undefined)
215
- return {}
216
- const { routesDir: _r, outDir: _o, publicDir: _p, port: _pt, ...runtime } = config
217
- return runtime
218
- }
219
-
220
- const RUNTIME_CONFIG_KEYS: readonly (keyof ServerRuntimeConfig)[] = [
221
- 'site',
222
- 'lang',
223
- 'assetPrefix',
224
- 'security',
225
- 'trustedOrigins',
226
- 'trustProxy',
227
- 'maxRequestBodySize',
228
- 'streamTimeout',
229
- 'compress',
230
- 'onError',
231
- 'plugins',
232
- ]
233
-
234
- /** Merges runtime options from `kay.config.ts` with explicit caller overrides (ignoring `undefined` override fields). */
235
- export function resolveServerConfig(
236
- fileConfig: KayConfig | undefined,
237
- overrides?: Partial<ServerRuntimeConfig> | undefined,
238
- ): ServerRuntimeConfig {
239
- const merged: Record<string, unknown> = { ...pickRuntimeConfig(fileConfig) }
240
- if (overrides !== undefined) {
241
- for (const key of RUNTIME_CONFIG_KEYS) {
242
- const value = overrides[key]
243
- if (value !== undefined)
244
- merged[key] = value
245
- }
246
- }
247
- return merged as ServerRuntimeConfig
248
- }
249
-
250
- export function definePlugin(plugin: KayPlugin): KayPlugin {
251
- return plugin
252
- }
253
-
254
- function enforceRank(plugin: KayPlugin): number {
255
- return plugin.enforce === 'pre' ? 0 : plugin.enforce === 'post' ? 2 : 1
256
- }
257
-
258
- /**
259
- * Sorts plugins stably by `enforce` (`'pre'` -> normal -> `'post'`) and `after` dependencies,
260
- * then fails fast if any plugin declares `readsLocals` for a key whose provider runs after it.
261
- */
262
- export function resolvePlugins(plugins: readonly KayPlugin[] | undefined): KayPlugin[] {
263
- if (plugins === undefined || plugins.length === 0)
264
- return []
265
-
266
- // Base stable order by `enforce` bucket, preserving config declaration order within each bucket.
267
- const base = plugins
268
- .map((plugin, index) => ({ plugin, index, rank: enforceRank(plugin) }))
269
- .sort((a, b) => a.rank - b.rank || a.index - b.index)
270
- .map(entry => entry.plugin)
271
-
272
- const n = base.length
273
- const indicesByName = new Map<string, number[]>()
274
- for (let i = 0; i < n; i++) {
275
- const name = base[i]!.name
276
- const list = indicesByName.get(name)
277
- if (list === undefined)
278
- indicesByName.set(name, [i])
279
- else
280
- list.push(i)
281
- }
282
-
283
- // Kahn's topological sort using min-index priority so `enforce` + declaration order stays deterministic.
284
- const inDegree = new Int32Array(n)
285
- const edges: number[][] = Array.from({ length: n }, () => [])
286
- for (let i = 0; i < n; i++) {
287
- const deps = base[i]!.after
288
- if (deps === undefined)
289
- continue
290
- const seen = new Set<number>()
291
- for (const depName of deps) {
292
- const targets = indicesByName.get(depName)
293
- if (targets === undefined)
294
- continue
295
- for (const depIdx of targets) {
296
- if (depIdx === i || seen.has(depIdx))
297
- continue
298
- seen.add(depIdx)
299
- edges[depIdx]!.push(i)
300
- inDegree[i] = (inDegree[i] ?? 0) + 1
301
- }
302
- }
303
- }
304
-
305
- const ready: number[] = []
306
- for (let i = 0; i < n; i++) {
307
- if (inDegree[i] === 0)
308
- ready.push(i)
309
- }
310
-
311
- const sorted: KayPlugin[] = []
312
- while (ready.length > 0) {
313
- // Pick lowest base index so `enforce` and user declaration order are preserved whenever unconstrained.
314
- let bestPos = 0
315
- for (let k = 1; k < ready.length; k++) {
316
- if (ready[k]! < ready[bestPos]!)
317
- bestPos = k
318
- }
319
- const u = ready.splice(bestPos, 1)[0]!
320
- sorted.push(base[u]!)
321
- for (const v of edges[u]!) {
322
- inDegree[v] = (inDegree[v] ?? 0) - 1
323
- if (inDegree[v] === 0)
324
- ready.push(v)
325
- }
326
- }
327
-
328
- if (sorted.length !== n) {
329
- const stuck = base.filter((_, idx) => (inDegree[idx] ?? 0) > 0).map(p => p.name)
330
- throw new Error(`kay: circular plugin \`after\` dependency involving: ${stuck.join(', ')}`)
331
- }
332
-
333
- // Validate that no plugin reads a ctx.locals key before another active plugin provides it.
334
- const providerByLocal = new Map<string, { name: string, index: number }>()
335
- for (let i = 0; i < sorted.length; i++) {
336
- const plugin = sorted[i]!
337
- for (const key of plugin.providesLocals ?? []) {
338
- if (!providerByLocal.has(key))
339
- providerByLocal.set(key, { name: plugin.name, index: i })
340
- }
341
- }
342
-
343
- for (let i = 0; i < sorted.length; i++) {
344
- const plugin = sorted[i]!
345
- for (const key of plugin.readsLocals ?? []) {
346
- const provider = providerByLocal.get(key)
347
- if (provider !== undefined && provider.index > i) {
348
- throw new Error(
349
- `kay: plugin "${plugin.name}" reads ctx.locals.${key} before "${provider.name}" provides it. Add \`after: [${JSON.stringify(provider.name)}]\` or adjust plugin order.`,
350
- )
351
- }
352
- }
353
- }
354
-
355
- return sorted
356
- }
357
-
358
- let configReloadSeq = 0
359
-
360
- // 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.
361
- function configSpecifier(configPath: string, fresh: boolean): string {
362
- if (fresh)
363
- return `${configPath}?v=fresh-${++configReloadSeq}`
364
- if (process.env.KAY_DEV === '1')
365
- return `${configPath}?v=${Bun.hash(readFileSync(configPath)).toString(36)}`
366
- return configPath
367
- }
368
-
369
- export async function loadConfig(root: string, options?: { fresh?: boolean, appContext?: AppRuntimeContext }): Promise<KayConfig> {
370
- const absRoot = resolve(root)
371
- const configPath = join(absRoot, 'kay.config.ts')
372
- if (!existsSync(configPath))
373
- return {}
374
- const spec = configSpecifier(configPath, options?.fresh === true)
375
- const active = options?.appContext ?? getAppContext()
376
- const ctx = active !== undefined && active.root === absRoot
377
- ? active
378
- : createAppContext({
379
- root: absRoot,
380
- outDir: join(absRoot, 'dist'),
381
- publicDir: join(absRoot, 'dist', 'public'),
382
- assetPrefix: '/_kay',
383
- dev: process.env.KAY_DEV === '1',
384
- })
385
- const mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
386
- return mod.default ?? {}
387
- }
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, serviceKey } from './services'
11
+ export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
12
+ export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -0,0 +1,61 @@
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, relative, 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
+ let mod: { default?: KayConfig }
37
+ try {
38
+ mod = await runWithAppContext(ctx, () => import(spec)) as { default?: KayConfig }
39
+ }
40
+ catch (error) {
41
+ // Several syntax errors arrive together; the first one names the line to fix.
42
+ const first: unknown = (error as AggregateError).errors?.[0] ?? error
43
+ throw new Error(`kay: ${configErrorLocation(first, configPath, absRoot)}: ${first instanceof Error ? first.message : String(first)}`, { cause: error })
44
+ }
45
+ return mod.default ?? {}
46
+ }
47
+
48
+ const STACK_LOCATION_RE = /:(\d+):(\d+)\)?$/
49
+
50
+ // Where a config failed: the syntax error's position, else the config's own frame in the stack, which names the line calling a throwing plugin factory.
51
+ function configErrorLocation(error: unknown, configPath: string, root: string): string {
52
+ const position = (error as { position?: { file?: string, line: number, column: number } }).position
53
+ if (position?.file !== undefined)
54
+ return `${relative(root, position.file)}:${position.line}:${position.column}`
55
+ for (const frame of String((error as Error).stack ?? '').split('\n')) {
56
+ const match = frame.includes(configPath) ? STACK_LOCATION_RE.exec(frame) : null
57
+ if (match !== null)
58
+ return `kay.config.ts:${match[1]}:${match[2]}`
59
+ }
60
+ return 'kay.config.ts'
61
+ }
@@ -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,6 @@
1
+ // `@kayjs/kay/config`: what `kay.config.ts` and plugin packages use.
2
+
3
+ export { defineConfig, definePlugin } from './config'
4
+ export { CONTENT_IMAGE_RESOLVER_SERVICE, I18N_CONFIG_SERVICE, serviceKey } from './services'
5
+ export type { ActiveI18nConfig, ContentImageResolver, ContentImageResult, ServiceKey } from './services'
6
+ export type { BuildPluginContext, BuildPluginTarget, CheckPluginContext, DocumentHeadContext, FinalizeBuildContext, KayConfig, KayPlugin, MiddlewareOptions, PluginRouteOptions, ServerErrorInfo, ServerPluginAPI, ServerRuntimeConfig } from './types'
@@ -0,0 +1,35 @@
1
+ // Service keys: `serviceKey` for any plugin, and the keys shared between two plugins, kept in core as contracts so neither depends on the other.
2
+
3
+ declare const SERVICE_TYPE: unique symbol
4
+
5
+ /** Names a service and the type of its value; `provide` and `inject` take one instead of a string. */
6
+ export interface ServiceKey<T> {
7
+ readonly name: string
8
+ readonly [SERVICE_TYPE]?: T
9
+ }
10
+
11
+ export function serviceKey<T>(name: string): ServiceKey<T> {
12
+ return { name }
13
+ }
14
+
15
+ export interface ActiveI18nConfig {
16
+ readonly locales: readonly string[]
17
+ readonly defaultLocale: string
18
+ readonly prefixDefault: boolean
19
+ }
20
+
21
+ export const I18N_CONFIG_SERVICE = serviceKey<ActiveI18nConfig>('kay.i18n.config')
22
+
23
+ export interface ContentImageResult {
24
+ src: string
25
+ srcset?: string | undefined
26
+ avifSrcset?: string | undefined
27
+ sizes?: string | undefined
28
+ width?: number | undefined
29
+ height?: number | undefined
30
+ loading?: 'lazy' | 'eager' | undefined
31
+ }
32
+
33
+ export type ContentImageResolver = (src: string, file: string | undefined) => ContentImageResult | string | undefined
34
+
35
+ export const CONTENT_IMAGE_RESOLVER_SERVICE = serviceKey<ContentImageResolver>('kay.content.imageResolver')