@kayjs/kay 2.0.0-beta.1 → 2.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/src/build/bundle.ts +209 -34
  3. package/src/build/compile.ts +22 -46
  4. package/src/build/files.ts +38 -0
  5. package/src/build/graph.ts +67 -2
  6. package/src/build/index.ts +75 -13
  7. package/src/build/manifest.ts +5 -0
  8. package/src/build/plugin-host.ts +2 -0
  9. package/src/build/prerender.ts +16 -7
  10. package/src/build/resolve.ts +11 -18
  11. package/src/build/routes.ts +33 -5
  12. package/src/build/server-entry.ts +38 -0
  13. package/src/cli/check.ts +102 -45
  14. package/src/cli/new.ts +6 -7
  15. package/src/compiler/analyze.ts +65 -10
  16. package/src/compiler/dom.ts +143 -122
  17. package/src/compiler/server-only.ts +14 -8
  18. package/src/compiler/shared.ts +57 -14
  19. package/src/compiler/ssr.ts +14 -12
  20. package/src/dev/index.ts +96 -29
  21. package/src/dom/action.ts +91 -1
  22. package/src/dom/index.ts +8 -3
  23. package/src/index.ts +3 -0
  24. package/src/jsx-runtime.ts +421 -93
  25. package/src/plugins/config.ts +49 -0
  26. package/src/plugins/context.ts +4 -0
  27. package/src/plugins/index.ts +7 -216
  28. package/src/plugins/load.ts +38 -0
  29. package/src/plugins/order.ts +107 -0
  30. package/src/plugins/services.ts +23 -0
  31. package/src/plugins/types.ts +197 -0
  32. package/src/server/action-registry.ts +72 -0
  33. package/src/server/action.ts +15 -8
  34. package/src/server/app-entry.ts +23 -0
  35. package/src/server/assets.ts +182 -0
  36. package/src/server/compress.ts +87 -14
  37. package/src/server/document.ts +192 -0
  38. package/src/server/errors.ts +123 -0
  39. package/src/server/http.ts +103 -30
  40. package/src/server/index.ts +131 -701
  41. package/src/server/loader.ts +62 -69
  42. package/src/server/page.ts +107 -0
  43. package/src/server/plugin-host.ts +167 -0
  44. package/src/server/router.ts +49 -20
  45. package/src/server/security.ts +44 -3
  46. package/src/server/static-dir.ts +22 -3
  47. package/src/server/stream.ts +94 -0
  48. package/src/test/index.ts +24 -19
@@ -0,0 +1,123 @@
1
+ // Errors a request runs into: the app's and plugins' `onError` hooks, and the `_error` and `_404` pages rendered outside any route.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { Html } from '../jsx-runtime'
5
+ import type { KayPlugin, ServerErrorInfo } from '../plugins/index'
6
+ import type { DocumentOptions } from '../ssr/index'
7
+ import type { CookieStore } from './cookies'
8
+ import type { DocumentHooks, HtmlHeaders } from './document'
9
+ import type { RequestContext } from './http'
10
+ import { createRenderContext, runWithRenderContext } from '../ssr/context'
11
+ import { raw, renderDocument, ssrChild } from '../ssr/index'
12
+ import { resolveRenderedIslands } from './document'
13
+ import { wantsJson } from './http'
14
+ import { inlineStyleHashes } from './security'
15
+
16
+ export type NotifyError = (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
17
+
18
+ export function createErrorNotifier(onError: ((info: ServerErrorInfo) => void) | undefined, plugins: readonly KayPlugin[]): NotifyError {
19
+ const errorHooks: ((info: ServerErrorInfo) => void)[] = []
20
+ if (onError !== undefined)
21
+ errorHooks.push(onError)
22
+ for (const p of plugins) {
23
+ if (p.onError !== undefined)
24
+ errorHooks.push(p.onError)
25
+ }
26
+ return (error, request, source) => {
27
+ for (const hook of errorHooks) {
28
+ try {
29
+ hook({ error, request, source })
30
+ }
31
+ catch {}
32
+ }
33
+ }
34
+ }
35
+
36
+ interface LayoutModule {
37
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
38
+ }
39
+
40
+ interface ErrorModule {
41
+ default: (props: { error: unknown }) => Html | string | Promise<Html | string>
42
+ }
43
+
44
+ interface NotFoundModule {
45
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
46
+ }
47
+
48
+ export interface FallbackPagesOptions {
49
+ manifest: BuildManifest
50
+ modules: Record<string, unknown>
51
+ lang: string
52
+ alwaysLoadRuntime: boolean
53
+ document: DocumentHooks
54
+ htmlHeaders: HtmlHeaders
55
+ notifyError: NotifyError
56
+ finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
57
+ }
58
+
59
+ export function createFallbackPages(options: FallbackPagesOptions) {
60
+ const { manifest, modules, document, htmlHeaders, notifyError, finish } = options
61
+ const errorMod = manifest.errorFile ? modules[manifest.errorFile] as ErrorModule : undefined
62
+ const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as NotFoundModule : undefined
63
+
64
+ // Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
65
+ const rootLayoutFile = manifest.rootLayoutFile
66
+ const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LayoutModule | undefined : undefined
67
+ const fallbackDoc: DocumentOptions = {
68
+ body: '',
69
+ headTags: manifest.headTags,
70
+ styles: manifest.globalStyles ?? manifest.styles,
71
+ runtimeScript: manifest.runtimeScript,
72
+ alwaysLoadRuntime: options.alwaysLoadRuntime,
73
+ lang: options.lang,
74
+ }
75
+
76
+ async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
77
+ if (renderInner !== undefined) {
78
+ try {
79
+ const effUrl = url ?? new URL(`http://localhost/${status}`)
80
+ const rctx = createRenderContext()
81
+ const body = await runWithRenderContext(rctx, async () => {
82
+ let inner = ssrChild(await renderInner() as Html)
83
+ if (rootLayoutMod !== undefined)
84
+ inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
85
+ return inner
86
+ })
87
+ const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
88
+ const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
89
+ const docHtml = renderDocument({
90
+ ...fallbackDoc,
91
+ body,
92
+ head: docHead.head,
93
+ lang: docHead.lang,
94
+ htmlAttrs: docHead.htmlAttrs,
95
+ preloadChunks: eagerChunks,
96
+ hasIslands,
97
+ })
98
+ const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
99
+ return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)) })
100
+ }
101
+ catch (err) {
102
+ if (req !== undefined)
103
+ notifyError(err, req, 'route')
104
+ }
105
+ }
106
+ return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
107
+ }
108
+
109
+ const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
110
+ renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), 'Internal Server Error', url, req, ctx)
111
+
112
+ const notFoundPage = notFoundMod?.default
113
+ const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
114
+ renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
115
+
116
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
117
+ if (wantsJson(request))
118
+ return finish(Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
119
+ return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
120
+ }
121
+
122
+ return { buildNotFoundResponse, renderError }
123
+ }
@@ -1,41 +1,108 @@
1
1
  // HTTP helpers, MIME table, RequestContext factory, and island tag scanner for Kay v2 server.
2
2
 
3
3
  import type { BuildManifest } from '../build/index'
4
- import type { KayPlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { KayChild } from '../jsx-runtime'
5
+ import type { ServerRuntimeConfig } from '../plugins/index'
5
6
  import type { Cookies } from './cookies'
6
- import type { SecurityHeadersOptions, TrustProxy } from './security'
7
+ import type { KayLocals } from './index'
8
+ import type { TrustProxy } from './security'
7
9
  import { CookieStore } from './cookies'
8
10
  import { nodeEnv } from './env'
9
11
  import { getClientIp, isHttpsRequest } from './security'
10
12
 
11
13
  export const DEFAULT_MAX_REQUEST_BODY_SIZE = 1024 * 1024
12
14
 
13
- export interface ServerOptions {
15
+ const NOT_FOUND_SYMBOL = Symbol.for('kay.notFound')
16
+ declare const NOT_FOUND_BRAND: unique symbol
17
+
18
+ export interface NotFoundResult {
19
+ readonly [NOT_FOUND_BRAND]: true
20
+ }
21
+
22
+ /** Return (or throw) from `load()` to render `_404.tsx` with HTTP status 404. */
23
+ export function notFound(): NotFoundResult {
24
+ return { [NOT_FOUND_SYMBOL]: true } as unknown as NotFoundResult
25
+ }
26
+
27
+ export function isNotFound(value: unknown): value is NotFoundResult {
28
+ return typeof value === 'object' && value !== null && (value as Record<symbol, unknown>)[NOT_FOUND_SYMBOL] === true
29
+ }
30
+
31
+ type SegmentParam<Seg extends string> =
32
+ Seg extends `[...${infer Name}]`
33
+ ? { [K in Name]: string }
34
+ : Seg extends `[${infer Name}]`
35
+ ? { [K in Name]: string }
36
+ : Seg extends `*${infer Name}`
37
+ ? { [K in Name extends '' ? 'rest' : Name]: string }
38
+ : Seg extends `:${infer Name}`
39
+ ? { [K in Name]: string }
40
+ : unknown
41
+
42
+ type MergeParams<A, B> = {
43
+ [K in keyof A | keyof B]: K extends keyof B ? B[K] : K extends keyof A ? A[K] : never
44
+ }
45
+
46
+ type ExtractRouteParamsRec<Path extends string, Acc = {}> =
47
+ Path extends `${infer Seg}/${infer Rest}`
48
+ ? ExtractRouteParamsRec<Rest, Seg extends '' ? Acc : MergeParams<Acc, SegmentParam<Seg>>>
49
+ : Path extends ''
50
+ ? Acc
51
+ : MergeParams<Acc, SegmentParam<Path>>
52
+
53
+ /** Extracts typed route params from a Kay route path (`'/notices/[id]'` -> `{ id: string }`, `'/docs/[...rest]'` -> `{ rest: string }`). */
54
+ export type ExtractRouteParams<Path extends string> =
55
+ string extends Path
56
+ ? Record<string, string>
57
+ : ExtractRouteParamsRec<Path>
58
+
59
+ export type LoaderFn = (...args: never[]) => unknown
60
+
61
+ /** Infers the resolved page `data` type returned by a route's `load()` function, excluding `Response` and `notFound()`. */
62
+ export type LoaderData<T extends LoaderFn> = Exclude<Awaited<ReturnType<T>>, Response | NotFoundResult>
63
+
64
+ type InferLoaderParams<T extends LoaderFn> =
65
+ Parameters<T> extends [ctx: { params: infer P }, ...unknown[]]
66
+ ? P
67
+ : Record<string, string>
68
+
69
+ /** Props passed to a Kay route page component. Pass `typeof load` to infer `data` (and `params` when `load` uses `RouteContext<Path>`), or a route path string when there is no `load`. */
70
+ export type PageProps<
71
+ TLoadOrPath extends LoaderFn | string | undefined = undefined,
72
+ TPath extends string = string,
73
+ > = {
74
+ params: TLoadOrPath extends string
75
+ ? ExtractRouteParams<TLoadOrPath>
76
+ : string extends TPath
77
+ ? (TLoadOrPath extends LoaderFn ? InferLoaderParams<TLoadOrPath> : Record<string, string>)
78
+ : ExtractRouteParams<TPath>
79
+ locals: KayLocals
80
+ url: URL
81
+ } & (TLoadOrPath extends LoaderFn ? { data: LoaderData<TLoadOrPath> } : { data?: undefined })
82
+
83
+ /** Props passed to a Kay `_layout.tsx` component. */
84
+ export interface LayoutProps<Path extends string = string> {
85
+ children: KayChild
86
+ params: ExtractRouteParams<Path>
87
+ locals: KayLocals
88
+ url: URL
89
+ }
90
+
91
+ export interface ServerOptions extends ServerRuntimeConfig {
14
92
  root: string
15
93
  outDir?: string | undefined
16
- assetPrefix?: string | undefined
17
94
  port?: number | undefined
18
- lang?: string | undefined
19
- security?: SecurityHeadersOptions | false | undefined
20
- trustedOrigins?: string[] | undefined
21
- trustProxy?: TrustProxy | undefined
22
- maxRequestBodySize?: number | undefined
23
- /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
24
- streamTimeout?: number | undefined
25
- compress?: boolean | undefined
26
95
  dev?: boolean | undefined
27
- onError?: ((info: ServerErrorInfo) => void) | undefined
28
- plugins?: KayPlugin[] | undefined
29
96
  /** @internal Imports a built server module by absolute path; `kay dev` passes one that keeps unchanged modules loaded. */
30
97
  importModule?: ((path: string) => Promise<Record<string, unknown>>) | undefined
31
98
  }
32
99
 
33
- export interface RequestContext {
100
+ export interface RequestContext<Params = Record<string, string>> {
34
101
  request: Request
35
102
  url: URL
36
- params: Record<string, string>
103
+ params: Params
37
104
  cookies: Cookies
38
- locals: Record<string, unknown>
105
+ locals: KayLocals
39
106
  ip?: string | undefined
40
107
  json: (data: unknown, init?: ResponseInit) => Response
41
108
  text: (body: string, init?: ResponseInit) => Response
@@ -43,6 +110,9 @@ export interface RequestContext {
43
110
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
44
111
  }
45
112
 
113
+ /** `RequestContext` with `params` inferred from a Kay route pattern (e.g. `RouteContext<'/notices/[id]'>`). */
114
+ export type RouteContext<Path extends string = string> = RequestContext<ExtractRouteParams<Path>>
115
+
46
116
  export type Middleware = (ctx: RequestContext, next: () => Promise<Response>) => Response | Promise<Response>
47
117
 
48
118
  export interface KayApp {
@@ -54,29 +124,18 @@ export interface KayApp {
54
124
 
55
125
  export type EmbeddedBody = Uint8Array<ArrayBuffer> | string
56
126
 
57
- export interface EmbeddedServerConfig {
127
+ export interface EmbeddedServerConfig extends ServerRuntimeConfig {
58
128
  manifest: BuildManifest
59
129
  modules: Record<string, unknown>
60
130
  assets: Record<string, EmbeddedBody>
61
131
  publicAssets?: Record<string, EmbeddedBody> | undefined
62
132
  publicEtags?: Record<string, string> | undefined
63
- prerendered: Record<string, string>
133
+ prerendered?: Record<string, string> | undefined
64
134
  prerenderedFiles?: Record<string, string> | undefined
65
135
  root?: string | undefined
66
136
  outDir?: string | undefined
67
137
  publicDir?: string | undefined
68
- assetPrefix?: string | undefined
69
- lang?: string | undefined
70
- security?: SecurityHeadersOptions | false | undefined
71
- trustedOrigins?: string[] | undefined
72
- trustProxy?: TrustProxy | undefined
73
- maxRequestBodySize?: number | undefined
74
- /** Milliseconds a streamed `<Suspense>` boundary may take before it renders its error and the response ends (default 30000). */
75
- streamTimeout?: number | undefined
76
- compress?: boolean | undefined
77
138
  dev?: boolean | undefined
78
- onError?: ((info: ServerErrorInfo) => void) | undefined
79
- plugins?: KayPlugin[] | undefined
80
139
  }
81
140
 
82
141
  export const MIME: Record<string, string> = {
@@ -324,3 +383,17 @@ export function finalizeResponse(
324
383
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
325
384
  }
326
385
  }
386
+
387
+ /** Runs `middlewares` in order around `last`; each calls `next` at most once. */
388
+ export async function runChain(ctx: RequestContext, middlewares: readonly Middleware[], last: () => Response | Promise<Response>): Promise<Response> {
389
+ if (middlewares.length === 0)
390
+ return last()
391
+ let index = -1
392
+ const dispatch = async (i: number): Promise<Response> => {
393
+ if (i <= index)
394
+ throw new Error('kay: middleware called next() multiple times')
395
+ index = i
396
+ return i < middlewares.length ? middlewares[i]!(ctx, () => dispatch(i + 1)) : last()
397
+ }
398
+ return dispatch(0)
399
+ }