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

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 (55) hide show
  1. package/package.json +1 -1
  2. package/src/attrs.ts +35 -0
  3. package/src/build/bundle.ts +442 -0
  4. package/src/build/compile.ts +10 -10
  5. package/src/build/files.ts +136 -0
  6. package/src/build/graph.ts +158 -0
  7. package/src/build/index.ts +204 -1460
  8. package/src/build/islands.ts +177 -0
  9. package/src/build/manifest.ts +224 -0
  10. package/src/build/plugin-host.ts +184 -0
  11. package/src/build/prerender.ts +93 -0
  12. package/src/build/report.ts +157 -0
  13. package/src/build/resolve.ts +58 -0
  14. package/src/build/routes.ts +135 -0
  15. package/src/build/static.ts +73 -0
  16. package/src/cli/check.ts +228 -114
  17. package/src/cli/index.ts +297 -94
  18. package/src/cli/new.ts +53 -32
  19. package/src/compiler/analyze.ts +666 -91
  20. package/src/compiler/dom.ts +808 -743
  21. package/src/compiler/mistakes.ts +354 -0
  22. package/src/compiler/patch.ts +1 -1
  23. package/src/compiler/server-only.ts +164 -21
  24. package/src/compiler/shared.ts +442 -0
  25. package/src/compiler/ssr.ts +329 -342
  26. package/src/context.ts +120 -0
  27. package/src/dev/index.ts +271 -75
  28. package/src/dom/action.ts +23 -13
  29. package/src/dom/extras.ts +121 -83
  30. package/src/dom/index.ts +114 -77
  31. package/src/dom/island.ts +71 -36
  32. package/src/dom/loop.ts +28 -20
  33. package/src/index.ts +2 -1
  34. package/src/jsx-runtime.ts +11 -0
  35. package/src/plugins/context.ts +57 -0
  36. package/src/plugins/index.ts +114 -18
  37. package/src/reactivity/index.ts +237 -213
  38. package/src/reactivity/selector.ts +11 -9
  39. package/src/reactivity/store.ts +36 -11
  40. package/src/server/action.ts +147 -76
  41. package/src/server/compress.ts +116 -96
  42. package/src/server/cookies.ts +46 -16
  43. package/src/server/env.ts +18 -13
  44. package/src/server/http.ts +107 -54
  45. package/src/server/index.ts +887 -870
  46. package/src/server/loader.ts +120 -0
  47. package/src/server/router.ts +22 -8
  48. package/src/server/security.ts +48 -58
  49. package/src/server/standard-schema.ts +42 -11
  50. package/src/server/static-dir.ts +144 -0
  51. package/src/ssr/context.ts +95 -10
  52. package/src/ssr/index.ts +167 -66
  53. package/src/style.ts +33 -0
  54. package/src/test/index.ts +2 -1
  55. package/src/unrenderable.ts +35 -0
@@ -0,0 +1,120 @@
1
+ // Filesystem server loader: reads `dist/manifest.json` (or falls back to `--static` dir server) and loads built modules.
2
+
3
+ import type { BuildManifest } from '../build/index'
4
+ import type { EmbeddedBody, KayApp, ServerOptions } from './http'
5
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
6
+ import { join, resolve } from 'node:path'
7
+ import { loadConfig, pickRuntimeConfig } from '../plugins/index'
8
+ import { createServerFromEmbedded } from './index'
9
+ import { createStaticDirServer } from './static-dir'
10
+
11
+ let serverLoadSeq = 0
12
+
13
+ export async function createServer(options: ServerOptions): Promise<KayApp> {
14
+ const root = resolve(options.root)
15
+ const fileConfig = await loadConfig(root)
16
+ const plugins = options.plugins ?? fileConfig.plugins ?? []
17
+ const outDir = resolve(root, options.outDir ?? fileConfig.outDir ?? 'dist')
18
+ const clientDir = join(outDir, 'client')
19
+ const manifestPath = join(outDir, 'manifest.json')
20
+ const securityOpt = options.security ?? fileConfig.security
21
+ const trustProxy = options.trustProxy ?? fileConfig.trustProxy ?? false
22
+ const maxRequestBodySize = options.maxRequestBodySize ?? fileConfig.maxRequestBodySize
23
+ const isDev = options.dev ?? (process.env.KAY_DEV === '1')
24
+
25
+ if (!existsSync(manifestPath)) {
26
+ if (existsSync(outDir) && readdirSync(outDir).length > 0) {
27
+ return createStaticDirServer(
28
+ outDir,
29
+ options.assetPrefix ?? fileConfig.assetPrefix ?? '/_kay',
30
+ securityOpt,
31
+ (options.compress ?? fileConfig.compress) !== false,
32
+ trustProxy,
33
+ isDev,
34
+ )
35
+ }
36
+ throw new Error(`kay server: missing ${manifestPath}. Run build() first.`)
37
+ }
38
+
39
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as BuildManifest
40
+ const modules: Record<string, unknown> = {}
41
+ const assets: Record<string, EmbeddedBody> = {}
42
+ const publicAssets: Record<string, EmbeddedBody> = {}
43
+ const publicEtags: Record<string, string> = {}
44
+ const prerenderedFiles: Record<string, string> = {}
45
+ const srcPublicDir = resolve(root, fileConfig.publicDir ?? 'public')
46
+
47
+ // Store file paths only (zero-copy Bun.file() serving, zero startup RAM bloat!)
48
+ for (const rel of manifest.assets) {
49
+ const abs = join(clientDir, rel)
50
+ if (existsSync(abs)) {
51
+ assets[rel] = abs
52
+ if (existsSync(`${abs}.br`))
53
+ assets[`${rel}.br`] = `${abs}.br`
54
+ if (existsSync(`${abs}.gz`))
55
+ assets[`${rel}.gz`] = `${abs}.gz`
56
+ }
57
+ }
58
+
59
+ for (const rel of manifest.publicFiles ?? []) {
60
+ const outAbs = join(outDir, 'public', rel)
61
+ const abs = existsSync(outAbs) ? outAbs : join(srcPublicDir, rel)
62
+ if (existsSync(abs)) {
63
+ publicAssets[rel] = abs
64
+ const st = statSync(abs)
65
+ publicEtags[rel] = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
66
+ }
67
+ }
68
+
69
+ const loadStamp = `${Date.now()}-${++serverLoadSeq}`
70
+ const importModule = options.importModule ?? ((path: string) => import(`${path}?v=${loadStamp}`))
71
+ const loadMod = async (rel: string) => {
72
+ if (!(rel in modules))
73
+ modules[rel] = await importModule(join(outDir, rel))
74
+ }
75
+
76
+ for (const r of manifest.routes) {
77
+ await loadMod(r.file)
78
+ for (const l of r.layouts) await loadMod(l)
79
+ for (const m of r.middlewares) await loadMod(m)
80
+ if (r.prerendered) {
81
+ for (const relHtml of Object.values(r.prerendered)) {
82
+ const abs = join(outDir, relHtml)
83
+ if (existsSync(abs))
84
+ prerenderedFiles[relHtml] = abs
85
+ }
86
+ }
87
+ }
88
+ if (manifest.errorFile) await loadMod(manifest.errorFile)
89
+ if (manifest.notFoundFile) await loadMod(manifest.notFoundFile)
90
+ for (const a of manifest.actions) {
91
+ await loadMod(a.file)
92
+ for (const m of a.middlewares) await loadMod(m)
93
+ }
94
+
95
+ const runtimeConfig = pickRuntimeConfig(fileConfig)
96
+ return createServerFromEmbedded({
97
+ ...runtimeConfig,
98
+ manifest,
99
+ modules,
100
+ assets,
101
+ publicAssets,
102
+ publicEtags,
103
+ prerendered: {},
104
+ prerenderedFiles,
105
+ root,
106
+ outDir,
107
+ publicDir: join(outDir, 'public'),
108
+ assetPrefix: options.assetPrefix ?? fileConfig.assetPrefix,
109
+ lang: options.lang ?? fileConfig.lang,
110
+ security: securityOpt,
111
+ trustedOrigins: options.trustedOrigins ?? fileConfig.trustedOrigins,
112
+ trustProxy,
113
+ maxRequestBodySize,
114
+ streamTimeout: options.streamTimeout ?? fileConfig.streamTimeout,
115
+ compress: options.compress ?? fileConfig.compress,
116
+ dev: isDev,
117
+ onError: options.onError ?? fileConfig.onError,
118
+ plugins,
119
+ })
120
+ }
@@ -1,6 +1,8 @@
1
1
  // File-based route matcher: static > [param] > [...catchall] priority sorting + param extraction.
2
2
 
3
- export interface RoutePattern<T> {
3
+ const ENCODED_SLASH_RE = /%2f/i
4
+
5
+ interface RoutePattern<T> {
4
6
  path: string
5
7
  segments: string[]
6
8
  isStatic: boolean
@@ -14,8 +16,13 @@ export interface RouteMatch<T> {
14
16
  params: Record<string, string>
15
17
  }
16
18
 
17
- export function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
18
- const clean = path === '/' ? '' : path.replace(/^\/|\/$/g, '')
19
+ function normalizePath(path: string): string {
20
+ return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path
21
+ }
22
+
23
+ function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
24
+ const norm = normalizePath(path)
25
+ const clean = norm === '/' ? '' : norm.replace(/^\/|\/$/g, '')
19
26
  const segments = clean === '' ? [] : clean.split('/')
20
27
  let isStatic = true
21
28
  let hasCatchAll = false
@@ -37,7 +44,7 @@ export function compileRoutePattern<T>(path: string, data: T): RoutePattern<T> {
37
44
  }
38
45
  }
39
46
 
40
- return { path, segments, isStatic, hasCatchAll, score, data }
47
+ return { path: norm, segments, isStatic, hasCatchAll, score, data }
41
48
  }
42
49
 
43
50
  export class Router<T> {
@@ -47,21 +54,28 @@ export class Router<T> {
47
54
  add(path: string, data: T): void {
48
55
  const compiled = compileRoutePattern(path, data)
49
56
  if (compiled.isStatic) {
50
- this.#staticRoutes.set(path, data)
57
+ this.#staticRoutes.set(compiled.path, data)
51
58
  }
52
59
  else {
53
- this.#dynamicRoutes.push(compiled)
60
+ const existing = this.#dynamicRoutes.findIndex(r => r.path === compiled.path)
61
+ if (existing !== -1)
62
+ this.#dynamicRoutes[existing] = compiled
63
+ else
64
+ this.#dynamicRoutes.push(compiled)
54
65
  this.#dynamicRoutes.sort((a, b) => b.score - a.score || b.segments.length - a.segments.length)
55
66
  }
56
67
  }
57
68
 
58
69
  match(pathname: string): RouteMatch<T> | undefined {
59
- const norm = pathname.length > 1 && pathname.endsWith('/') ? pathname.slice(0, -1) : pathname
70
+ const norm = normalizePath(pathname)
60
71
 
61
72
  const exact = this.#staticRoutes.get(norm)
62
73
  if (exact !== undefined)
63
74
  return { data: exact, params: {} }
64
75
 
76
+ if (this.#dynamicRoutes.length === 0)
77
+ return undefined
78
+
65
79
  const parts = norm === '/' ? [] : norm.slice(1).split('/')
66
80
 
67
81
  for (let i = 0; i < this.#dynamicRoutes.length; i++) {
@@ -85,7 +99,7 @@ export class Router<T> {
85
99
  }
86
100
  else if (seg.startsWith(':')) {
87
101
  const rawSeg = parts[j]!
88
- if (/%2f/i.test(rawSeg)) {
102
+ if (ENCODED_SLASH_RE.test(rawSeg)) {
89
103
  matched = false
90
104
  break
91
105
  }
@@ -56,7 +56,11 @@ export function withCspHashes(
56
56
  }
57
57
 
58
58
  addHashes('style-src', styleHashes)
59
+ if (directives.has('style-src-elem'))
60
+ addHashes('style-src-elem', styleHashes)
59
61
  addHashes('script-src', scriptHashes)
62
+ if (directives.has('script-src-elem'))
63
+ addHashes('script-src-elem', scriptHashes)
60
64
 
61
65
  return order.map((name) => {
62
66
  const tokens = directives.get(name)!
@@ -66,59 +70,60 @@ export function withCspHashes(
66
70
 
67
71
  export const DEFAULT_CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'"
68
72
  export const DEFAULT_HSTS = 'max-age=31536000; includeSubDomains'
73
+ export const DEFAULT_PERMISSIONS_POLICY = 'camera=(), microphone=(), geolocation=()'
69
74
 
70
75
  export interface SecurityHeadersOptions {
71
76
  frameOptions?: 'DENY' | 'SAMEORIGIN' | false | undefined
72
77
  referrerPolicy?: string | false | undefined
73
78
  contentTypeOptions?: boolean | undefined
79
+ permissionsPolicy?: string | false | undefined
74
80
  csp?: string | false | undefined
75
81
  hsts?: string | boolean | undefined
76
82
  }
77
83
 
78
84
  const UNSAFE_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE'])
79
85
 
80
- function requestOrigins(request: Request, trustProxy = false): { expectedOrigin: string, forwardedOrigin: string | undefined } {
81
- const expectedOrigin = new URL(request.url).origin
82
- let forwardedOrigin: string | undefined
83
- if (trustProxy) {
84
- const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim()
85
- const fwdHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() || request.headers.get('host')?.trim()
86
- if (fwdProto && fwdHost) {
87
- try {
88
- forwardedOrigin = new URL(`${fwdProto}://${fwdHost}`).origin
89
- }
90
- catch {
91
- forwardedOrigin = `${fwdProto}://${fwdHost}`
92
- }
93
- }
94
- }
95
- return { expectedOrigin, forwardedOrigin }
86
+ /** How many reverse proxies sit in front of the app: `true` is one, a number is that many, `false` trusts no forwarded header. */
87
+ export type TrustProxy = boolean | number
88
+
89
+ function proxyHops(trustProxy: TrustProxy): number {
90
+ return trustProxy === true ? 1 : trustProxy === false ? 0 : Math.max(0, Math.floor(trustProxy))
96
91
  }
97
92
 
98
- /** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
99
- export function isHttpsRequest(request: Request, trustProxy = false): boolean {
93
+ // Proxies append to X-Forwarded-*, so only the entries the trusted hops wrote count: the one `hops` from the right.
94
+ function forwardedValue(request: Request, header: string, trustProxy: TrustProxy): string | undefined {
95
+ const hops = proxyHops(trustProxy)
96
+ if (hops === 0)
97
+ return undefined
98
+ const entries = (request.headers.get(header) ?? '').split(',').map(e => e.trim()).filter(e => e !== '')
99
+ return entries[Math.max(0, entries.length - hops)]
100
+ }
101
+
102
+ function forwardedOrigin(request: Request, trustProxy: TrustProxy): string | undefined {
103
+ const proto = forwardedValue(request, 'x-forwarded-proto', trustProxy)
104
+ const host = forwardedValue(request, 'x-forwarded-host', trustProxy) || request.headers.get('host')?.trim()
105
+ if (!proto || !host)
106
+ return undefined
100
107
  try {
101
- if (new URL(request.url).protocol === 'https:')
102
- return true
108
+ return new URL(`${proto}://${host}`).origin
103
109
  }
104
- catch {}
105
- if (trustProxy) {
106
- const fwdProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase()
107
- if (fwdProto === 'https')
108
- return true
110
+ catch {
111
+ return undefined
109
112
  }
110
- return false
111
113
  }
112
114
 
113
- /** Extracts the client IP from proxy headers (only when `trustProxy` is true) or falls back to the direct socket IP. */
114
- export function getClientIp(request: Request, trustProxy = false, remoteIp?: string): string | undefined {
115
- if (trustProxy) {
116
- const xff = request.headers.get('x-forwarded-for')
117
- if (xff) {
118
- const first = xff.split(',')[0]?.trim()
119
- if (first)
120
- return first
121
- }
115
+ /** Returns true when the request arrived over HTTPS (directly, or via X-Forwarded-Proto when `trustProxy` is true). */
116
+ export function isHttpsRequest(request: Request, trustProxy: TrustProxy = false): boolean {
117
+ return request.url.startsWith('https:')
118
+ || forwardedValue(request, 'x-forwarded-proto', trustProxy)?.toLowerCase() === 'https'
119
+ }
120
+
121
+ /** Extracts the client IP from the trusted proxies' headers, or falls back to the direct socket IP. */
122
+ export function getClientIp(request: Request, trustProxy: TrustProxy = false, remoteIp?: string): string | undefined {
123
+ if (proxyHops(trustProxy) > 0) {
124
+ const forwarded = forwardedValue(request, 'x-forwarded-for', trustProxy)
125
+ if (forwarded)
126
+ return forwarded
122
127
  const realIp = request.headers.get('x-real-ip')?.trim()
123
128
  if (realIp)
124
129
  return realIp
@@ -131,11 +136,10 @@ export function isTrustedOrigin(
131
136
  origin: string,
132
137
  request: Request,
133
138
  trustedOrigins?: ReadonlySet<string>,
134
- trustProxy = false,
139
+ trustProxy: TrustProxy = false,
135
140
  ): boolean {
136
- const { expectedOrigin, forwardedOrigin } = requestOrigins(request, trustProxy)
137
- return origin === expectedOrigin
138
- || (forwardedOrigin !== undefined && origin === forwardedOrigin)
141
+ return origin === new URL(request.url).origin
142
+ || origin === forwardedOrigin(request, trustProxy)
139
143
  || trustedOrigins?.has(origin) === true
140
144
  }
141
145
 
@@ -143,18 +147,16 @@ export function isTrustedOrigin(
143
147
  export function verifyOrigin(
144
148
  request: Request,
145
149
  trustedOrigins?: ReadonlySet<string>,
146
- trustProxy = false,
150
+ trustProxy: TrustProxy = false,
147
151
  ): { ok: true } | { ok: false, reason: string } {
148
152
  if (!UNSAFE_METHODS.has(request.method.toUpperCase()))
149
153
  return { ok: true }
150
154
 
151
- const { expectedOrigin, forwardedOrigin } = requestOrigins(request, trustProxy)
152
155
  const origin = request.headers.get('origin')
153
-
154
156
  if (origin !== null) {
155
- if (origin === expectedOrigin || (forwardedOrigin !== undefined && origin === forwardedOrigin) || trustedOrigins?.has(origin))
157
+ if (isTrustedOrigin(origin, request, trustedOrigins, trustProxy))
156
158
  return { ok: true }
157
- return { ok: false, reason: `Cross-site request blocked: origin ${origin} does not match ${forwardedOrigin ?? expectedOrigin}` }
159
+ return { ok: false, reason: `Cross-site request blocked: untrusted origin ${origin}` }
158
160
  }
159
161
 
160
162
  const fetchSite = request.headers.get('sec-fetch-site')
@@ -191,21 +193,9 @@ export function buildSecurityHeaderEntries(options: SecurityHeadersOptions | fal
191
193
  entries.push(['x-frame-options', opts.frameOptions ?? 'SAMEORIGIN'])
192
194
  if (opts.referrerPolicy !== false)
193
195
  entries.push(['referrer-policy', opts.referrerPolicy ?? 'strict-origin-when-cross-origin'])
196
+ if (opts.permissionsPolicy !== false)
197
+ entries.push(['permissions-policy', opts.permissionsPolicy ?? DEFAULT_PERMISSIONS_POLICY])
194
198
  if (opts.csp !== false)
195
199
  entries.push(['content-security-policy', opts.csp ?? DEFAULT_CSP])
196
200
  return entries
197
201
  }
198
-
199
- export function applySecurityHeaders(headers: Headers, options: SecurityHeadersOptions = {}): void {
200
- if ((options.contentTypeOptions ?? true) && !headers.has('x-content-type-options'))
201
- headers.set('x-content-type-options', 'nosniff')
202
-
203
- if (options.frameOptions !== false && !headers.has('x-frame-options'))
204
- headers.set('x-frame-options', options.frameOptions ?? 'SAMEORIGIN')
205
-
206
- if (options.referrerPolicy !== false && !headers.has('referrer-policy'))
207
- headers.set('referrer-policy', options.referrerPolicy ?? 'strict-origin-when-cross-origin')
208
-
209
- if (options.csp !== false && !headers.has('content-security-policy'))
210
- headers.set('content-security-policy', options.csp ?? DEFAULT_CSP)
211
- }
@@ -36,21 +36,52 @@ export interface ValidationSuccess<T> {
36
36
 
37
37
  export type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure
38
38
 
39
+ export function formatIssuePath(issue: StandardSchemaIssue): string {
40
+ if (!issue.path || issue.path.length === 0)
41
+ return ''
42
+ return issue.path
43
+ .map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg)))
44
+ .join('.')
45
+ }
46
+
47
+ export function formatSchemaIssues(issues: ReadonlyArray<StandardSchemaIssue>): string {
48
+ return issues
49
+ .map((issue) => {
50
+ const path = formatIssuePath(issue)
51
+ return path ? `${path}: ${issue.message}` : issue.message
52
+ })
53
+ .join('; ')
54
+ }
55
+
56
+ function buildValidationFailure(issues: ReadonlyArray<StandardSchemaIssue>): ValidationFailure {
57
+ const fieldErrors: Record<string, string> = {}
58
+ for (const issue of issues) {
59
+ const key = formatIssuePath(issue)
60
+ if (!Object.hasOwn(fieldErrors, key))
61
+ Object.defineProperty(fieldErrors, key, { value: issue.message, enumerable: true, writable: true, configurable: true })
62
+ }
63
+ return { ok: false, issues, fieldErrors }
64
+ }
65
+
66
+ export function validateSchemaSync<S extends StandardSchemaV1>(
67
+ schema: S,
68
+ input: unknown,
69
+ asyncErrorMessage = 'kay: synchronous Standard Schema validator required',
70
+ ): ValidationResult<InferOutput<S>> {
71
+ const res = schema['~standard'].validate(input)
72
+ if (res instanceof Promise)
73
+ throw new TypeError(asyncErrorMessage)
74
+ if (res.issues && res.issues.length > 0)
75
+ return buildValidationFailure(res.issues)
76
+ return { ok: true, value: (res as { value: InferOutput<S> }).value }
77
+ }
78
+
39
79
  export async function validateSchema<S extends StandardSchemaV1>(
40
80
  schema: S,
41
81
  input: unknown,
42
82
  ): Promise<ValidationResult<InferOutput<S>>> {
43
83
  const res = await schema['~standard'].validate(input)
44
- if (res.issues && res.issues.length > 0) {
45
- const fieldErrors: Record<string, string> = {}
46
- for (const issue of res.issues) {
47
- const key = issue.path && issue.path.length > 0
48
- ? issue.path.map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg))).join('.')
49
- : ''
50
- if (!(key in fieldErrors))
51
- fieldErrors[key] = issue.message
52
- }
53
- return { ok: false, issues: res.issues, fieldErrors }
54
- }
84
+ if (res.issues && res.issues.length > 0)
85
+ return buildValidationFailure(res.issues)
55
86
  return { ok: true, value: (res as { value: InferOutput<S> }).value }
56
87
  }
@@ -0,0 +1,144 @@
1
+ // Standalone `--static` directory server (used when `outDir` holds exported HTML without `manifest.json`).
2
+
3
+ import type { Stats } from 'node:fs'
4
+ import type { KayApp } from './http'
5
+ import type { SecurityHeadersOptions, TrustProxy } from './security'
6
+ import { existsSync, statSync } from 'node:fs'
7
+ import { extname, join, resolve } from 'node:path'
8
+ import { CompressionCache, isCompressibleType, maybeCompressResponse, pickPrecompressedEncoding, toWeakEtag } from './compress'
9
+ import { applyHstsHeader, etagMatches, MIME } from './http'
10
+ import { buildSecurityHeaderEntries, KAY_ISLAND_STYLE_HASH, resolveCspPolicy, resolveHstsValue, withCspHashes } from './security'
11
+
12
+ const isRead = (request: Request): boolean => request.method === 'GET' || request.method === 'HEAD'
13
+
14
+ export function createStaticDirServer(
15
+ outDir: string,
16
+ assetPrefix: string,
17
+ security: SecurityHeadersOptions | false | undefined,
18
+ compressEnabled: boolean,
19
+ trustProxy: TrustProxy,
20
+ isDev = false,
21
+ ): KayApp {
22
+ const cleanPrefix = `${assetPrefix.replace(/\/$/, '')}/`
23
+ const absRoot = resolve(outDir)
24
+ const compressCache = compressEnabled ? new CompressionCache() : undefined
25
+ const securityEntries = buildSecurityHeaderEntries(security)
26
+ const baseCsp = resolveCspPolicy(security)
27
+ const htmlCsp = baseCsp !== undefined ? withCspHashes(baseCsp, { styleHashes: [KAY_ISLAND_STYLE_HASH] }) : undefined
28
+ const htmlSecurityEntries: [string, string][] = securityEntries.map(([k, v]) =>
29
+ k === 'content-security-policy' && htmlCsp !== undefined ? [k, htmlCsp] : [k, v],
30
+ )
31
+ const hstsValue = resolveHstsValue(security)
32
+ const withHsts = (res: Response, req: Request) => applyHstsHeader(res, req, hstsValue, trustProxy, isDev)
33
+
34
+ function statFile(abs: string): Stats | undefined {
35
+ try {
36
+ const st = statSync(abs, { throwIfNoEntry: false })
37
+ return st?.isFile() ? st : undefined
38
+ }
39
+ catch {
40
+ return undefined
41
+ }
42
+ }
43
+
44
+ function resolveStaticFile(pathname: string): { path: string, st: Stats } | undefined {
45
+ let decoded: string
46
+ try {
47
+ decoded = decodeURIComponent(pathname)
48
+ }
49
+ catch {
50
+ return undefined
51
+ }
52
+ if (decoded.includes('\0'))
53
+ return undefined
54
+ const rel = decoded.replace(/^\/+/, '').replace(/\/+$/, '')
55
+ const candidates = rel === ''
56
+ ? ['index.html']
57
+ : [rel, `${rel}.html`, `${rel}/index.html`]
58
+ for (const c of candidates) {
59
+ const abs = resolve(absRoot, c)
60
+ if (abs !== absRoot && !abs.startsWith(`${absRoot}/`) && !abs.startsWith(`${absRoot}\\`))
61
+ continue
62
+ const st = statFile(abs)
63
+ if (st !== undefined)
64
+ return { path: abs, st }
65
+ }
66
+ return undefined
67
+ }
68
+
69
+ const initHeaders = (isHtml = false): Headers => new Headers((isHtml ? htmlSecurityEntries : securityEntries) as [string, string][])
70
+
71
+ const handle = async (req: Request): Promise<Response> => {
72
+ if (!isRead(req)) {
73
+ const headers = initHeaders()
74
+ headers.set('allow', 'GET, HEAD')
75
+ return withHsts(new Response('Method Not Allowed', { status: 405, headers }), req)
76
+ }
77
+
78
+ const url = new URL(req.url)
79
+ const found = resolveStaticFile(url.pathname)
80
+ if (found === undefined) {
81
+ const notFoundPath = join(absRoot, '404.html')
82
+ if (statFile(notFoundPath) !== undefined) {
83
+ const headers = initHeaders(true)
84
+ headers.set('content-type', 'text/html; charset=utf-8')
85
+ return withHsts(new Response(req.method === 'HEAD' ? null : Bun.file(notFoundPath), { status: 404, headers }), req)
86
+ }
87
+ return withHsts(new Response('Not Found', { status: 404, headers: initHeaders() }), req)
88
+ }
89
+
90
+ const { path: filePath, st } = found
91
+ const ext = extname(filePath).toLowerCase()
92
+ const mime = MIME[ext] ?? 'application/octet-stream'
93
+ const isHtml = ext === '.html' || ext === '.htm'
94
+ const etag = `W/"${st.size.toString(36)}-${Math.floor(st.mtimeMs).toString(36)}"`
95
+ const isImmutable = url.pathname.startsWith(cleanPrefix)
96
+ const headers = initHeaders(isHtml)
97
+ headers.set('content-type', mime)
98
+ headers.set('cache-control', isImmutable ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate')
99
+ headers.set('etag', etag)
100
+
101
+ const hasBr = compressEnabled && existsSync(`${filePath}.br`)
102
+ const hasGz = compressEnabled && existsSync(`${filePath}.gz`)
103
+ if (hasBr || hasGz || (compressEnabled && isCompressibleType(mime)))
104
+ headers.set('vary', 'Accept-Encoding')
105
+
106
+ if (etagMatches(req.headers.get('if-none-match'), etag))
107
+ return withHsts(new Response(null, { status: 304, headers }), req)
108
+
109
+ if (compressEnabled && req.method !== 'HEAD' && (hasBr || hasGz)) {
110
+ const preEnc = pickPrecompressedEncoding(req.headers.get('accept-encoding'), { br: hasBr, gz: hasGz })
111
+ if (preEnc !== undefined) {
112
+ headers.set('content-encoding', preEnc)
113
+ headers.set('etag', toWeakEtag(etag))
114
+ return withHsts(new Response(Bun.file(`${filePath}.${preEnc === 'br' ? 'br' : 'gz'}`), { status: 200, headers }), req)
115
+ }
116
+ }
117
+
118
+ headers.set('content-length', String(st.size))
119
+ const res = new Response(req.method === 'HEAD' ? null : Bun.file(filePath), { status: 200, headers })
120
+ if (!compressEnabled || req.method === 'HEAD')
121
+ return withHsts(res, req)
122
+ return withHsts(await maybeCompressResponse(res, req, compressCache), req)
123
+ }
124
+
125
+ return {
126
+ handle,
127
+ serve(port = 3000, hostname = '127.0.0.1') {
128
+ return Bun.serve({
129
+ port,
130
+ hostname,
131
+ idleTimeout: 30,
132
+ development: false,
133
+ fetch: handle,
134
+ error() {
135
+ return new Response('Internal Server Error', {
136
+ status: 500,
137
+ headers: { 'content-type': 'text/plain; charset=utf-8', ...Object.fromEntries(securityEntries) },
138
+ })
139
+ },
140
+ })
141
+ },
142
+ async dispose() {},
143
+ }
144
+ }