@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
@@ -0,0 +1,204 @@
1
+ // What every rendered document shares: its HTML headers, the plugins' `head` hooks and `transformHtml` passes, and the islands it rendered.
2
+
3
+ import type { DocumentHeadContext, KayPlugin, ServerErrorInfo } from '../plugins/index'
4
+ import type { RenderContext } from '../ssr/context'
5
+ import type { RequestContext } from './http'
6
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
7
+ import { extractRenderedIslands, makeRequestContext } from './http'
8
+ import { inlineStyleHashes, KAY_ISLAND_STYLE_HASH, KAY_STREAM_SCRIPT_HASH, KAY_SUSPENSE_STYLE_HASH, resolveCspPolicy, withCspHashes } from './security'
9
+
10
+ const TITLE_INNER_RE = /^<title\b[^>]*>([\s\S]*?)<\/title>$/i
11
+
12
+ /** `styleHashes` are the page's own `<style>` blocks (`inlineStyleHashes`), added to its CSP. */
13
+ export type HtmlHeaders = (hasIslands: boolean, hasSuspense: boolean, isDynamic: boolean, styleHashes?: readonly string[]) => Record<string, string>
14
+
15
+ const STYLED_HEADER_CACHE_SIZE = 256
16
+
17
+ // HTML headers, one set per (dynamic, islands, suspense) combination: the CSP only gains the hashes a page needs.
18
+ export function createHtmlHeaders(security: SecurityHeadersOptions | false | undefined, securityRecord: Record<string, string>): HtmlHeaders {
19
+ const baseCsp = resolveCspPolicy(security)
20
+ const htmlHeaderSets: Record<string, string>[] = []
21
+ const kayStyleHashes: string[][] = []
22
+ for (let i = 0; i < 8; i++) {
23
+ const isDynamic = (i & 4) !== 0
24
+ const hasIslands = (i & 2) !== 0
25
+ const hasSuspense = (i & 1) !== 0
26
+ const headers: Record<string, string> = { 'content-type': 'text/html; charset=utf-8', ...securityRecord }
27
+ if (isDynamic)
28
+ headers['cache-control'] = 'private'
29
+ const styleHashes = [...(hasIslands ? [KAY_ISLAND_STYLE_HASH] : []), ...(hasSuspense ? [KAY_SUSPENSE_STYLE_HASH] : [])]
30
+ kayStyleHashes.push(styleHashes)
31
+ if (baseCsp !== undefined && (hasIslands || hasSuspense)) {
32
+ headers['content-security-policy'] = withCspHashes(baseCsp, {
33
+ styleHashes,
34
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
35
+ })
36
+ }
37
+ htmlHeaderSets.push(headers)
38
+ }
39
+
40
+ // Pages sharing a layout share its blocks, so their header sets are kept by set and hashes; past the cap a new combination is built each time.
41
+ const styledSets = new Map<string, Record<string, string>>()
42
+ return (hasIslands, hasSuspense, isDynamic, styleHashes) => {
43
+ const index = (isDynamic ? 4 : 0) | (hasIslands ? 2 : 0) | (hasSuspense ? 1 : 0)
44
+ const base = htmlHeaderSets[index]!
45
+ if (baseCsp === undefined || styleHashes === undefined || styleHashes.length === 0)
46
+ return base
47
+ const key = `${index} ${styleHashes.join(' ')}`
48
+ let headers = styledSets.get(key)
49
+ if (headers === undefined) {
50
+ headers = {
51
+ ...base,
52
+ 'content-security-policy': withCspHashes(baseCsp, {
53
+ styleHashes: [...kayStyleHashes[index]!, ...styleHashes],
54
+ scriptHashes: hasSuspense ? [KAY_STREAM_SCRIPT_HASH] : [],
55
+ }),
56
+ }
57
+ if (styledSets.size < STYLED_HEADER_CACHE_SIZE)
58
+ styledSets.set(key, headers)
59
+ }
60
+ return headers
61
+ }
62
+ }
63
+
64
+ /** A plugin's HTML page without a CSP of its own gets the app's, its `<style>` blocks hashed like a rendered page's. */
65
+ export async function withPluginHtmlCsp(res: Response, htmlHeaders: HtmlHeaders): Promise<Response> {
66
+ if (res.body === null || res.headers.has('content-security-policy') || !(res.headers.get('content-type') ?? '').startsWith('text/html'))
67
+ return res
68
+ const html = await res.text()
69
+ const headers = new Headers(res.headers)
70
+ const csp = htmlHeaders(false, false, true, inlineStyleHashes(html))['content-security-policy']
71
+ if (csp !== undefined)
72
+ headers.set('content-security-policy', csp)
73
+ return new Response(html, { status: res.status, statusText: res.statusText, headers })
74
+ }
75
+
76
+ export function resolveRenderedIslands(rctx: RenderContext, body: string): { hasIslands: boolean, eagerChunks: string[] } {
77
+ if (rctx.hasIslands) {
78
+ const eagerChunks: string[] = []
79
+ for (const [chunk, eager] of rctx.renderedIslands) {
80
+ if (eager)
81
+ eagerChunks.push(chunk)
82
+ }
83
+ return { hasIslands: true, eagerChunks }
84
+ }
85
+ // Fallback only if raw HTML injected a <kay-island> without going through ssrIsland/ssrIslandStatic.
86
+ if (body.includes('<kay-island'))
87
+ return extractRenderedIslands(body)
88
+ return { hasIslands: false, eagerChunks: [] }
89
+ }
90
+
91
+ export interface DocumentHooksOptions {
92
+ plugins: readonly KayPlugin[]
93
+ lang: string
94
+ trustProxy: TrustProxy
95
+ notifyError: (error: unknown, request: Request, source: ServerErrorInfo['source']) => void
96
+ }
97
+
98
+ export function createDocumentHooks(options: DocumentHooksOptions) {
99
+ const { lang, trustProxy, notifyError } = options
100
+ const headHooks = options.plugins
101
+ .map(p => p.head)
102
+ .filter((fn): fn is NonNullable<KayPlugin['head']> => typeof fn === 'function')
103
+ const htmlTransformers = options.plugins
104
+ .map(p => p.transformHtml)
105
+ .filter((fn): fn is NonNullable<KayPlugin['transformHtml']> => typeof fn === 'function')
106
+ const hasHeadHooks = headHooks.length > 0
107
+ const hasHtmlTransformers = htmlTransformers.length > 0
108
+
109
+ async function resolveDocumentHead(
110
+ rctx: RenderContext,
111
+ baseHeadTags: readonly string[] | undefined,
112
+ url: URL,
113
+ req?: Request,
114
+ ctx?: RequestContext,
115
+ ): Promise<{ head: string, lang: string, htmlAttrs: Record<string, string> }> {
116
+ const collectedParts = rctx.headParts.join('')
117
+ if (!hasHeadHooks) {
118
+ return {
119
+ head: (rctx.title ?? '') + collectedParts,
120
+ lang,
121
+ htmlAttrs: rctx.htmlAttrs,
122
+ }
123
+ }
124
+
125
+ const headCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
126
+ const htmlAttrs: Record<string, string> = { ...rctx.htmlAttrs }
127
+ const initialTitleTag = rctx.title
128
+ const initialTitleInner = initialTitleTag !== undefined ? TITLE_INNER_RE.exec(initialTitleTag)?.[1] : undefined
129
+ let currentTitle = initialTitleInner
130
+ let titleDirty = false
131
+ let currentLang = htmlAttrs.lang ?? lang
132
+ let headBuf = (initialTitleTag ?? '') + collectedParts
133
+ if (baseHeadTags !== undefined) {
134
+ for (let i = 0; i < baseHeadTags.length; i++)
135
+ headBuf += baseHeadTags[i]
136
+ }
137
+ const added: string[] = []
138
+
139
+ const docHead: DocumentHeadContext = {
140
+ get lang() {
141
+ return currentLang
142
+ },
143
+ set lang(v: string) {
144
+ currentLang = v
145
+ htmlAttrs.lang = v
146
+ },
147
+ htmlAttrs,
148
+ get title() {
149
+ return currentTitle
150
+ },
151
+ set title(v: string | undefined) {
152
+ currentTitle = v
153
+ titleDirty = true
154
+ },
155
+ get headHtml() {
156
+ return headBuf
157
+ },
158
+ add(html: string) {
159
+ if (html !== '') {
160
+ added.push(html)
161
+ headBuf += html
162
+ }
163
+ },
164
+ }
165
+
166
+ for (const hook of headHooks) {
167
+ try {
168
+ await hook(docHead, headCtx)
169
+ }
170
+ catch (err) {
171
+ notifyError(err, req ?? headCtx.request, 'plugin')
172
+ }
173
+ }
174
+
175
+ const titleHtml = titleDirty
176
+ ? (currentTitle !== undefined ? `<title>${currentTitle}</title>` : '')
177
+ : (initialTitleTag ?? '')
178
+ return {
179
+ head: titleHtml + collectedParts + (added.length > 0 ? added.join('') : ''),
180
+ lang: currentLang,
181
+ htmlAttrs,
182
+ }
183
+ }
184
+
185
+ async function applyHtmlTransforms(html: string, url: URL, req?: Request, ctx?: RequestContext): Promise<string> {
186
+ if (!hasHtmlTransformers)
187
+ return html
188
+ const transformCtx = ctx ?? makeRequestContext(req ?? new Request(url.toString()), {}, { trustProxy, url }).ctx
189
+ let out = html
190
+ for (const transform of htmlTransformers) {
191
+ try {
192
+ out = await transform(out, transformCtx)
193
+ }
194
+ catch (err) {
195
+ notifyError(err, req ?? transformCtx.request, 'plugin')
196
+ }
197
+ }
198
+ return out
199
+ }
200
+
201
+ return { hasHeadHooks, hasHtmlTransformers, htmlTransformers, resolveDocumentHead, applyHtmlTransforms }
202
+ }
203
+
204
+ export type DocumentHooks = ReturnType<typeof createDocumentHooks>
@@ -0,0 +1,125 @@
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: { owner: string, hook: (info: ServerErrorInfo) => void }[] = []
20
+ if (onError !== undefined)
21
+ errorHooks.push({ owner: 'kay.config.ts', hook: onError })
22
+ for (const p of plugins) {
23
+ if (p.onError !== undefined)
24
+ errorHooks.push({ owner: p.name, hook: p.onError })
25
+ }
26
+ return (error, request, source) => {
27
+ for (const { owner, hook } of errorHooks) {
28
+ try {
29
+ hook({ error, request, source })
30
+ }
31
+ catch (hookError) {
32
+ console.error(`kay: the onError hook of ${owner} threw; the other hooks still run.`, hookError)
33
+ }
34
+ }
35
+ }
36
+ }
37
+
38
+ interface LayoutModule {
39
+ default: (props: { children: Html, url?: URL, params?: Record<string, string>, locals?: object }) => Html | string | Promise<Html | string>
40
+ }
41
+
42
+ interface ErrorModule {
43
+ default: (props: { error: unknown }) => Html | string | Promise<Html | string>
44
+ }
45
+
46
+ interface NotFoundModule {
47
+ default?: (props: Record<string, unknown>) => Html | string | Promise<Html | string>
48
+ }
49
+
50
+ export interface FallbackPagesOptions {
51
+ manifest: BuildManifest
52
+ modules: Record<string, unknown>
53
+ lang: string
54
+ alwaysLoadRuntime: boolean
55
+ document: DocumentHooks
56
+ htmlHeaders: HtmlHeaders
57
+ notifyError: NotifyError
58
+ finish: (res: Response, request: Request, cookieStore?: CookieStore) => Response
59
+ }
60
+
61
+ export function createFallbackPages(options: FallbackPagesOptions) {
62
+ const { manifest, modules, document, htmlHeaders, notifyError, finish } = options
63
+ const errorMod = manifest.errorFile ? modules[manifest.errorFile] as ErrorModule : undefined
64
+ const notFoundMod = manifest.notFoundFile ? modules[manifest.notFoundFile] as NotFoundModule : undefined
65
+
66
+ // Error and 404 pages sit outside any route, so they render with the global styles and the explicit root layout only.
67
+ const rootLayoutFile = manifest.rootLayoutFile
68
+ const rootLayoutMod = rootLayoutFile !== undefined ? modules[rootLayoutFile] as LayoutModule | undefined : undefined
69
+ const fallbackDoc: DocumentOptions = {
70
+ body: '',
71
+ headTags: manifest.headTags,
72
+ styles: manifest.globalStyles ?? manifest.styles,
73
+ runtimeScript: manifest.runtimeScript,
74
+ alwaysLoadRuntime: options.alwaysLoadRuntime,
75
+ lang: options.lang,
76
+ }
77
+
78
+ async function renderFallbackPage(status: number, renderInner: (() => unknown) | undefined, text: string, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> {
79
+ if (renderInner !== undefined) {
80
+ try {
81
+ const effUrl = url ?? new URL(`http://localhost/${status}`)
82
+ const rctx = createRenderContext()
83
+ const body = await runWithRenderContext(rctx, async () => {
84
+ let inner = ssrChild(await renderInner() as Html)
85
+ if (rootLayoutMod !== undefined)
86
+ inner = ssrChild(await rootLayoutMod.default({ children: raw(inner), url: effUrl, params: {}, locals: ctx?.locals ?? {} }) as Html)
87
+ return inner
88
+ })
89
+ const { hasIslands, eagerChunks } = resolveRenderedIslands(rctx, body)
90
+ const docHead = await document.resolveDocumentHead(rctx, manifest.headTags, effUrl, req, ctx)
91
+ const docHtml = renderDocument({
92
+ ...fallbackDoc,
93
+ body,
94
+ head: docHead.head,
95
+ lang: docHead.lang,
96
+ htmlAttrs: docHead.htmlAttrs,
97
+ preloadChunks: eagerChunks,
98
+ hasIslands,
99
+ })
100
+ const html = await document.applyHtmlTransforms(docHtml, effUrl, req, ctx)
101
+ return new Response(html, { status, headers: htmlHeaders(hasIslands, false, true, inlineStyleHashes(html)) })
102
+ }
103
+ catch (err) {
104
+ if (req !== undefined)
105
+ notifyError(err, req, 'route')
106
+ }
107
+ }
108
+ return new Response(text, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })
109
+ }
110
+
111
+ const buildErrorResponse = (error: unknown, url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
112
+ renderFallbackPage(500, errorMod && (() => errorMod.default({ error })), 'Internal Server Error', url, req, ctx)
113
+
114
+ const notFoundPage = notFoundMod?.default
115
+ const buildNotFoundResponse = (url?: URL, req?: Request, ctx?: RequestContext): Promise<Response> =>
116
+ renderFallbackPage(404, notFoundPage && (() => notFoundPage({})), 'Not Found', url, req, ctx)
117
+
118
+ async function renderError(error: unknown, cookieStore: CookieStore | undefined, url: URL, request: Request, ctx?: RequestContext): Promise<Response> {
119
+ if (wantsJson(request))
120
+ return finish(Response.json({ ok: false, status: 500, error: 'Internal Server Error' }, { status: 500 }), request, cookieStore)
121
+ return finish(await buildErrorResponse(error, url, request, ctx), request, cookieStore)
122
+ }
123
+
124
+ return { buildNotFoundResponse, renderError }
125
+ }
@@ -383,3 +383,17 @@ export function finalizeResponse(
383
383
  return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
384
384
  }
385
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
+ }