@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
@@ -7,7 +7,7 @@ import { existsSync, statSync } from 'node:fs'
7
7
  import { extname, join, resolve } from 'node:path'
8
8
  import { CompressionCache, isCompressibleType, maybeCompressResponse, pickPrecompressedEncoding, toWeakEtag } from './compress'
9
9
  import { applyHstsHeader, etagMatches, MIME } from './http'
10
- import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
10
+ import { buildSecurityHeaderEntries, inlineStyleHashes, KAY_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
11
11
 
12
12
  const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
13
13
 
@@ -68,6 +68,21 @@ export function createStaticDirServer(
68
68
 
69
69
  const initHeaders = (isHtml = false): Headers => new Headers((isHtml ? htmlSecurityEntries : securityEntries) as [string, string][])
70
70
 
71
+ // An exported page's CSP gains the hashes of its own `<style>` blocks, read once per file version.
72
+ const pageCsp = new Map<string, { etag: string, csp: string }>()
73
+ async function setPageCsp(headers: Headers, filePath: string, etag: string): Promise<void> {
74
+ if (htmlCsp === undefined)
75
+ return
76
+ let cached = pageCsp.get(filePath)
77
+ if (cached?.etag !== etag) {
78
+ const styleHashes = inlineStyleHashes(await Bun.file(filePath).text())
79
+ cached = { etag, csp: withCspHashes(htmlCsp, { styleHashes }) }
80
+ pageCsp.set(filePath, cached)
81
+ }
82
+ headers.set('content-security-policy', cached.csp)
83
+ }
84
+ const fileEtag = (st: Stats): string => `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
85
+
71
86
  const handle = async (req: Request): Promise<Response> => {
72
87
  if (!isRead(req)) {
73
88
  const headers = initHeaders()
@@ -79,9 +94,11 @@ export function createStaticDirServer(
79
94
  const found = resolveStaticFile(url.pathname)
80
95
  if (found === undefined) {
81
96
  const notFoundPath = join(absRoot, '404.html')
82
- if (statFile(notFoundPath) !== undefined) {
97
+ const notFoundStat = statFile(notFoundPath)
98
+ if (notFoundStat !== undefined) {
83
99
  const headers = initHeaders(true)
84
100
  headers.set('content-type', 'text/html; charset=utf-8')
101
+ await setPageCsp(headers, notFoundPath, fileEtag(notFoundStat))
85
102
  return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
86
103
  }
87
104
  return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
@@ -91,12 +108,14 @@ export function createStaticDirServer(
91
108
  const ext = extname(filePath).toLowerCase()
92
109
  const mime = MIME[ext] ?? 'application/octet-stream'
93
110
  const isHtml = ext === '.html' || ext === '.htm'
94
- const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
111
+ const etag = fileEtag(st)
95
112
  const isImmutable = url.pathname.startsWith(cleanPrefix)
96
113
  const headers = initHeaders(isHtml)
97
114
  headers.set('content-type', mime)
98
115
  headers.set('cache-control', isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
99
116
  headers.set('etag', etag)
117
+ if (isHtml)
118
+ await setPageCsp(headers, filePath, etag)
100
119
 
101
120
  const hasBr = compressEnabled && existsSync(`${filePath}.br`)
102
121
  const hasGz = compressEnabled && existsSync(`${filePath}.gz`)
@@ -0,0 +1,94 @@
1
+ // A page with pending `<Suspense>` boundaries: its document flushes first, then each boundary as a script once it resolves or times out.
2
+
3
+ import type { PendingChunk, RenderContext, SettledChunk } from '../ssr/context'
4
+ import { streamChunkScript } from '../ssr/context'
5
+
6
+ const textEncoder = new TextEncoder()
7
+ // Where a streamed page's document splits: everything before it flushes first, resolved boundaries go in between.
8
+ export const STREAM_TAIL_MARK = '<!--kay:stream-tail-->'
9
+
10
+ async function settleWithin(chunk: PendingChunk, deadlineMs: number, signal: AbortSignal): Promise<SettledChunk | undefined> {
11
+ if (signal.aborted)
12
+ return undefined
13
+ const remaining = Math.max(0, deadlineMs - Date.now())
14
+ let timer: ReturnType<typeof setTimeout> | undefined
15
+ const abortedOrTimedOut = new Promise<SettledChunk | undefined>((resolve) => {
16
+ const onAbort = () => resolve(undefined)
17
+ signal.addEventListener('abort', onAbort, { once: true })
18
+ timer = setTimeout(() => {
19
+ signal.removeEventListener('abort', onAbort)
20
+ const error = new Error(`<Suspense> boundary ${chunk.id} did not resolve within ${remaining} ms`)
21
+ resolve({ html: chunk.renderError(error), error })
22
+ }, remaining)
23
+ })
24
+ try {
25
+ return await Promise.race([chunk.settled, abortedOrTimedOut])
26
+ }
27
+ finally {
28
+ clearTimeout(timer)
29
+ }
30
+ }
31
+
32
+ /** Streams `shell` (a document holding `STREAM_TAIL_MARK`), with every boundary of `rctx` flushed before its tail. */
33
+ export function streamDocument(shell: string, rctx: RenderContext, streamTimeout: number, onBoundaryError: (error: unknown) => void): ReadableStream<Uint8Array> {
34
+ let splitAt = shell.lastIndexOf(STREAM_TAIL_MARK)
35
+ let tailOffset = STREAM_TAIL_MARK.length
36
+ if (splitAt === -1) {
37
+ splitAt = shell.lastIndexOf('</body>')
38
+ tailOffset = 0
39
+ }
40
+ const openingHtml = splitAt === -1 ? shell : shell.slice(0, splitAt)
41
+ const tailHtml = splitAt === -1 ? '' : shell.slice(splitAt + tailOffset)
42
+
43
+ const abortCtrl = new AbortController()
44
+ let closed = false
45
+ const deadline = Date.now() + streamTimeout
46
+
47
+ const safeEnqueue = (controller: ReadableStreamDefaultController<Uint8Array>, data: Uint8Array): void => {
48
+ if (closed || abortCtrl.signal.aborted)
49
+ return
50
+ try {
51
+ controller.enqueue(data)
52
+ }
53
+ catch {
54
+ closed = true
55
+ abortCtrl.abort()
56
+ }
57
+ }
58
+
59
+ return new ReadableStream<Uint8Array>({
60
+ async start(controller) {
61
+ safeEnqueue(controller, textEncoder.encode(openingHtml))
62
+ // A resolved boundary can render boundaries of its own, so each flush also drains the ones it added.
63
+ let flushed = 0
64
+ const flushPending = async (): Promise<void> => {
65
+ if (closed || abortCtrl.signal.aborted)
66
+ return
67
+ const chunks = rctx.pending.slice(flushed)
68
+ flushed = rctx.pending.length
69
+ await Promise.all(chunks.map(async (chunk) => {
70
+ const settled = await settleWithin(chunk, deadline, abortCtrl.signal)
71
+ if (settled === undefined || closed || abortCtrl.signal.aborted)
72
+ return
73
+ if ('error' in settled)
74
+ onBoundaryError(settled.error)
75
+ safeEnqueue(controller, textEncoder.encode(streamChunkScript(chunk.id, settled.html)))
76
+ await flushPending()
77
+ }))
78
+ }
79
+ await flushPending()
80
+ if (!closed && !abortCtrl.signal.aborted) {
81
+ safeEnqueue(controller, textEncoder.encode(tailHtml))
82
+ closed = true
83
+ try {
84
+ controller.close()
85
+ }
86
+ catch {}
87
+ }
88
+ },
89
+ cancel() {
90
+ closed = true
91
+ abortCtrl.abort()
92
+ },
93
+ })
94
+ }
package/src/test/index.ts CHANGED
@@ -1,18 +1,15 @@
1
1
  // kay/test: in-process testing for pages, middleware, cookies, and actions — zero port binding.
2
2
 
3
3
  import type { BuildManifest, BuildOptions } from '../build/index'
4
- import type { KayApp, ServerOptions } from '../server/index'
5
- import type { TrustProxy } from '../server/security'
4
+ import type { KayApp, ServerAction, ServerRuntimeConfig } from '../server/index'
5
+ import { resolve } from 'node:path'
6
6
  import { build } from '../build/index'
7
- import { createServer } from '../server/index'
7
+ import { relPosix } from '../build/files'
8
+ import { resolveServerConfig } from '../server/index'
9
+ import { startBuiltApp } from '../server/loader'
8
10
 
9
- export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'> {
11
+ export interface TestAppOptions extends Omit<BuildOptions, 'compile' | 'static'>, Partial<ServerRuntimeConfig> {
10
12
  prebuilt?: boolean | undefined
11
- lang?: string | undefined
12
- security?: ServerOptions['security']
13
- trustedOrigins?: string[] | undefined
14
- trustProxy?: TrustProxy | undefined
15
- maxRequestBodySize?: number | undefined
16
13
  }
17
14
 
18
15
  export interface TestApp {
@@ -22,7 +19,10 @@ export interface TestApp {
22
19
  fetch(pathOrReq: string | Request, init?: RequestInit): Promise<Response>
23
20
  get(path: string, headers?: HeadersInit): Promise<Response>
24
21
  post(path: string, body?: unknown, headers?: HeadersInit): Promise<Response>
25
- submit(actionUrl: string, fields: Record<string, string>, headers?: HeadersInit): Promise<Response>
22
+ /** The app's own bundled copy of a route, layout, middleware, action file or `kay.config.ts`, by path from the root. */
23
+ import(path: string): Promise<Record<string, unknown>>
24
+ /** Posts `fields` as a form to an action, given as one from `import()` or as its URL. */
25
+ submit(action: ServerAction<never, unknown> | string, fields: Record<string, string>, headers?: HeadersInit): Promise<Response>
26
26
  clearCookies(): void
27
27
  }
28
28
 
@@ -33,19 +33,14 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
33
33
  outDir: options.outDir,
34
34
  minify: options.minify ?? false,
35
35
  assetPrefix: options.assetPrefix,
36
+ site: options.site,
36
37
  plugins: options.plugins,
37
38
  })
38
39
 
39
- const app = await createServer({
40
+ const { app, entry } = await startBuiltApp({
40
41
  root: options.root,
41
42
  outDir: options.outDir,
42
- assetPrefix: options.assetPrefix,
43
- lang: options.lang,
44
- security: options.security,
45
- trustedOrigins: options.trustedOrigins,
46
- trustProxy: options.trustProxy,
47
- maxRequestBodySize: options.maxRequestBodySize,
48
- plugins: options.plugins,
43
+ ...resolveServerConfig(undefined, options),
49
44
  })
50
45
 
51
46
  const cookies = new Map<string, string>()
@@ -112,7 +107,17 @@ export async function testApp(options: TestAppOptions): Promise<TestApp> {
112
107
  headers: h,
113
108
  })
114
109
  },
115
- submit(actionUrl, fields, headers) {
110
+ async import(path) {
111
+ const source = relPosix(options.root, resolve(options.root, path))
112
+ const mod = entry?.sources[source]
113
+ if (mod === undefined)
114
+ throw new Error(`kay: testApp().import('${path}') found no bundled module. Only routes, layouts, middlewares, action files and kay.config.ts are bundled entries; reach ${source} through one of them.`)
115
+ return mod
116
+ },
117
+ submit(action, fields, headers) {
118
+ const actionUrl = typeof action === 'string' ? action : action.url
119
+ if (actionUrl === '')
120
+ throw new Error('kay: testApp().submit() got an action with no URL. Pass one from `await app.import(path)`, not one the test file imported itself.')
116
121
  const fd = new FormData()
117
122
  for (const [k, v] of Object.entries(fields))
118
123
  fd.append(k, v)