@kayjs/kay 2.0.0-alpha.5 → 2.0.0-alpha.6
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.
- package/package.json +1 -1
- package/src/build/compile.ts +10 -6
- package/src/build/index.ts +400 -25
- package/src/cli/check.ts +165 -4
- package/src/cli/index.ts +2 -1
- package/src/cli/new.ts +1 -1
- package/src/dev/index.ts +135 -22
- package/src/dom/extras.ts +67 -11
- package/src/dom/index.ts +3 -3
- package/src/dom/island.ts +97 -75
- package/src/plugins/index.ts +25 -2
- package/src/server/action.ts +47 -0
- package/src/server/compress.ts +241 -0
- package/src/server/cookies.ts +4 -0
- package/src/server/http.ts +40 -7
- package/src/server/index.ts +435 -158
- package/src/server/security.ts +81 -1
- package/src/ssr/context.ts +5 -2
- package/src/ssr/index.ts +30 -3
package/src/dom/island.ts
CHANGED
|
@@ -5,98 +5,120 @@ import { hydrate, mount } from './index'
|
|
|
5
5
|
declare const KAY_DEFERRED: boolean | undefined
|
|
6
6
|
declare const KAY_CLIENT_ONLY: boolean | undefined
|
|
7
7
|
|
|
8
|
+
export function parseIslandProps(raw: string): Record<string, unknown> {
|
|
9
|
+
if (!raw.includes('"__k":'))
|
|
10
|
+
return JSON.parse(raw) as Record<string, unknown>
|
|
11
|
+
return JSON.parse(raw, (_k, v: unknown) => {
|
|
12
|
+
if (v !== null && typeof v === 'object' && '__k' in v && 'v' in v) {
|
|
13
|
+
const tagged = v as { __k: string, v: unknown }
|
|
14
|
+
if (tagged.__k === 'D') return new Date(tagged.v as string)
|
|
15
|
+
if (tagged.__k === 'S') return new Set(tagged.v as unknown[])
|
|
16
|
+
if (tagged.__k === 'M') return new Map(tagged.v as [unknown, unknown][])
|
|
17
|
+
if (tagged.__k === 'U') return new URL(tagged.v as string)
|
|
18
|
+
if (tagged.__k === 'R') {
|
|
19
|
+
const [src, flags] = tagged.v as [string, string]
|
|
20
|
+
return new RegExp(src, flags)
|
|
21
|
+
}
|
|
22
|
+
if (tagged.__k === 'B') return BigInt(tagged.v as string)
|
|
23
|
+
}
|
|
24
|
+
return v
|
|
25
|
+
}) as Record<string, unknown>
|
|
26
|
+
}
|
|
27
|
+
|
|
8
28
|
type IslandModule = { default: (props: Record<string, unknown>) => Node | DocumentFragment | null }
|
|
9
29
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
30
|
+
export function defineIslandElement(): void {
|
|
31
|
+
if (typeof customElements === 'undefined' || customElements.get('kay-island'))
|
|
32
|
+
return
|
|
13
33
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
this._s = true
|
|
34
|
+
class KayIsland extends HTMLElement {
|
|
35
|
+
_d: (() => void) | undefined
|
|
36
|
+
_s = false
|
|
18
37
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
if (h === 'visible') {
|
|
22
|
-
const target = this.firstElementChild ?? this
|
|
23
|
-
const io = new IntersectionObserver((entries) => {
|
|
24
|
-
if (entries.some(e => e.isIntersecting)) {
|
|
25
|
-
io.disconnect()
|
|
26
|
-
void this._l(false)
|
|
27
|
-
}
|
|
28
|
-
}, { rootMargin: '200px' })
|
|
29
|
-
io.observe(target)
|
|
30
|
-
return
|
|
31
|
-
}
|
|
32
|
-
if (h === 'idle') {
|
|
33
|
-
const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
|
|
34
|
-
ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
|
|
38
|
+
connectedCallback(): void {
|
|
39
|
+
if (this._s)
|
|
35
40
|
return
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
41
|
+
this._s = true
|
|
42
|
+
|
|
43
|
+
const h = this.getAttribute('h')
|
|
44
|
+
if (typeof KAY_DEFERRED === 'undefined' || KAY_DEFERRED) {
|
|
45
|
+
if (h === 'visible') {
|
|
46
|
+
const target = this.firstElementChild ?? this
|
|
47
|
+
const io = new IntersectionObserver((entries) => {
|
|
48
|
+
if (entries.some(e => e.isIntersecting)) {
|
|
49
|
+
io.disconnect()
|
|
50
|
+
void this._l(false)
|
|
51
|
+
}
|
|
52
|
+
}, { rootMargin: '200px' })
|
|
53
|
+
io.observe(target)
|
|
54
|
+
return
|
|
42
55
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const mq = matchMedia(h.slice(6, -1))
|
|
48
|
-
if (mq.matches) {
|
|
49
|
-
void this._l(false)
|
|
56
|
+
if (h === 'idle') {
|
|
57
|
+
const ric = (globalThis as { requestIdleCallback?: (cb: () => void) => void }).requestIdleCallback
|
|
58
|
+
ric ? ric(() => void this._l(false)) : setTimeout(() => void this._l(false), 1)
|
|
59
|
+
return
|
|
50
60
|
}
|
|
51
|
-
|
|
61
|
+
if (h === 'interaction') {
|
|
62
|
+
const evs = ['pointerdown', 'focusin', 'keydown']
|
|
52
63
|
const go = () => {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
64
|
+
for (const e of evs) this.removeEventListener(e, go, true)
|
|
65
|
+
void this._l(false)
|
|
66
|
+
}
|
|
67
|
+
for (const e of evs) this.addEventListener(e, go, { capture: true, once: true })
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
if (h !== null && h.startsWith('media(')) {
|
|
71
|
+
const mq = matchMedia(h.slice(6, -1))
|
|
72
|
+
if (mq.matches) {
|
|
73
|
+
void this._l(false)
|
|
74
|
+
}
|
|
75
|
+
else {
|
|
76
|
+
const go = () => {
|
|
77
|
+
if (mq.matches) {
|
|
78
|
+
mq.removeEventListener('change', go)
|
|
79
|
+
void this._l(false)
|
|
80
|
+
}
|
|
56
81
|
}
|
|
82
|
+
mq.addEventListener('change', go)
|
|
57
83
|
}
|
|
58
|
-
|
|
84
|
+
return
|
|
59
85
|
}
|
|
60
|
-
return
|
|
61
86
|
}
|
|
62
|
-
}
|
|
63
87
|
|
|
64
|
-
|
|
65
|
-
|
|
88
|
+
void this._l(h === 'client')
|
|
89
|
+
}
|
|
66
90
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
91
|
+
disconnectedCallback(): void {
|
|
92
|
+
// Defer disposal by a microtask so synchronous DOM moves (e.g. SPA persistent islands) stay alive!
|
|
93
|
+
queueMicrotask(() => {
|
|
94
|
+
if (!this.isConnected) {
|
|
95
|
+
this._d?.()
|
|
96
|
+
this._d = undefined
|
|
97
|
+
this._s = false
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
}
|
|
77
101
|
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
102
|
+
async _l(clientOnly: boolean): Promise<void> {
|
|
103
|
+
const chunk = this.getAttribute('c')
|
|
104
|
+
if (!chunk)
|
|
105
|
+
return
|
|
82
106
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
107
|
+
const mod = await import(chunk) as IslandModule
|
|
108
|
+
if (!this.isConnected)
|
|
109
|
+
return
|
|
86
110
|
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
111
|
+
const p = this.getAttribute('p')
|
|
112
|
+
const props: Record<string, unknown> = p ? parseIslandProps(p) : {}
|
|
113
|
+
const slot = this.querySelector('kay-slot')
|
|
114
|
+
if (slot !== null)
|
|
115
|
+
props.children = slot
|
|
116
|
+
const render = () => mod.default(props)
|
|
117
|
+
this._d = (typeof KAY_CLIENT_ONLY === 'undefined' || KAY_CLIENT_ONLY) && clientOnly
|
|
118
|
+
? mount(this, render)
|
|
119
|
+
: hydrate(this, render)
|
|
120
|
+
}
|
|
96
121
|
}
|
|
97
|
-
}
|
|
98
122
|
|
|
99
|
-
|
|
100
|
-
if (typeof customElements !== 'undefined' && !customElements.get('kay-island'))
|
|
101
|
-
customElements.define('kay-island', KayIsland)
|
|
123
|
+
customElements.define('kay-island', KayIsland)
|
|
102
124
|
}
|
package/src/plugins/index.ts
CHANGED
|
@@ -21,8 +21,19 @@ export interface BuildPluginContext {
|
|
|
21
21
|
emitPublic(relPath: string, content: string | Uint8Array): string
|
|
22
22
|
/** Add a stylesheet URL to <head> on every page. */
|
|
23
23
|
addStyle(href: string): void
|
|
24
|
+
/** Add a stylesheet URL to <head> on a specific route path only. */
|
|
25
|
+
addRouteStyle(routePath: string, href: string): void
|
|
24
26
|
/** Add raw HTML to <head> on every page (e.g. font preloads, default meta/OG, JSON-LD). */
|
|
25
27
|
addHead(html: string): void
|
|
28
|
+
/** Add raw HTML to <head> on a specific route path only. */
|
|
29
|
+
addRouteHead(routePath: string, html: string): void
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CheckPluginContext {
|
|
33
|
+
readonly root: string
|
|
34
|
+
readonly routesDir: string
|
|
35
|
+
/** Report a validation error from `kay check`. */
|
|
36
|
+
error(message: string): void
|
|
26
37
|
}
|
|
27
38
|
|
|
28
39
|
export interface ServerPluginAPI {
|
|
@@ -52,6 +63,10 @@ export interface KayPlugin {
|
|
|
52
63
|
prerenderPaths?: (paths: string[], route: RouteManifestEntry) => string[] | Promise<string[]>
|
|
53
64
|
/** Client bootstrap module path — bundled ONLY when this plugin is active. */
|
|
54
65
|
clientEntry?: string | undefined
|
|
66
|
+
/** Validate plugin-specific invariants during `kay check` (e.g. missing i18n keys, content frontmatter). */
|
|
67
|
+
check?: (ctx: CheckPluginContext) => void | Promise<void>
|
|
68
|
+
/** Extra directories or files (relative to app root or absolute) for `kay dev` to watch. */
|
|
69
|
+
watchPaths?: string[] | ((root: string) => string[]) | undefined
|
|
55
70
|
/** Register custom CLI subcommands (e.g. `kay i18n check`). */
|
|
56
71
|
commands?: Record<string, (args: string[], root: string) => void | Promise<void>> | undefined
|
|
57
72
|
}
|
|
@@ -64,6 +79,7 @@ export interface KayConfig {
|
|
|
64
79
|
assetPrefix?: string | undefined
|
|
65
80
|
security?: SecurityHeadersOptions | false | undefined
|
|
66
81
|
trustedOrigins?: string[] | undefined
|
|
82
|
+
compress?: boolean | undefined
|
|
67
83
|
plugins?: KayPlugin[] | undefined
|
|
68
84
|
}
|
|
69
85
|
|
|
@@ -75,11 +91,18 @@ export function definePlugin(plugin: KayPlugin): KayPlugin {
|
|
|
75
91
|
return plugin
|
|
76
92
|
}
|
|
77
93
|
|
|
78
|
-
|
|
94
|
+
const KAY_ROOT_KEY = Symbol.for('kay.root')
|
|
95
|
+
let configReloadSeq = 0
|
|
96
|
+
|
|
97
|
+
export async function loadConfig(root: string, options?: { fresh?: boolean }): Promise<KayConfig> {
|
|
79
98
|
const absRoot = resolve(root)
|
|
99
|
+
;(globalThis as Record<symbol, unknown>)[KAY_ROOT_KEY] = absRoot
|
|
80
100
|
const configPath = join(absRoot, 'kay.config.ts')
|
|
81
101
|
if (!existsSync(configPath))
|
|
82
102
|
return {}
|
|
83
|
-
const
|
|
103
|
+
const spec = options?.fresh || process.env.KAY_DEV === '1'
|
|
104
|
+
? `${configPath}?v=${++configReloadSeq}-${Date.now()}`
|
|
105
|
+
: configPath
|
|
106
|
+
const mod = await import(spec) as { default?: KayConfig }
|
|
84
107
|
return mod.default ?? {}
|
|
85
108
|
}
|
package/src/server/action.ts
CHANGED
|
@@ -5,6 +5,19 @@ import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } f
|
|
|
5
5
|
import { isTrustedOrigin, verifyOrigin } from './security'
|
|
6
6
|
import { validateSchema } from './standard-schema'
|
|
7
7
|
|
|
8
|
+
export const ACTION_ERROR_COOKIE = '__kay_action_err'
|
|
9
|
+
|
|
10
|
+
export interface ActionErrorFlash {
|
|
11
|
+
action: string
|
|
12
|
+
error: string
|
|
13
|
+
fieldErrors?: Record<string, string> | undefined
|
|
14
|
+
values?: Record<string, string> | undefined
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function getActionError(locals?: Record<string, unknown>): ActionErrorFlash | undefined {
|
|
18
|
+
return locals?.actionError as ActionErrorFlash | undefined
|
|
19
|
+
}
|
|
20
|
+
|
|
8
21
|
export interface ActionContext {
|
|
9
22
|
request: Request
|
|
10
23
|
url: URL
|
|
@@ -126,6 +139,40 @@ export async function executeAction(
|
|
|
126
139
|
|
|
127
140
|
const checked = await validateSchema(act.schema, rawBody)
|
|
128
141
|
if (!checked.ok) {
|
|
142
|
+
// Zero-JS progressive HTML <form> submit: flash fieldErrors + submitted string values and redirect 303 back to trusted Referer
|
|
143
|
+
if (!wantsJson) {
|
|
144
|
+
const referer = request.headers.get('referer')
|
|
145
|
+
if (referer) {
|
|
146
|
+
let refUrl: URL | undefined
|
|
147
|
+
try {
|
|
148
|
+
refUrl = new URL(referer)
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
refUrl = undefined
|
|
152
|
+
}
|
|
153
|
+
if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins)) {
|
|
154
|
+
const values: Record<string, string> = {}
|
|
155
|
+
if (rawBody !== null && typeof rawBody === 'object') {
|
|
156
|
+
for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
|
|
157
|
+
if (typeof v === 'string' && !/password|secret|token/i.test(k) && v.length <= 512)
|
|
158
|
+
values[k] = v
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
const flash: ActionErrorFlash = {
|
|
162
|
+
action: act.url,
|
|
163
|
+
error: 'Validation failed',
|
|
164
|
+
fieldErrors: checked.fieldErrors,
|
|
165
|
+
...(Object.keys(values).length > 0 ? { values } : {}),
|
|
166
|
+
}
|
|
167
|
+
ctx.cookies.set(ACTION_ERROR_COOKIE, JSON.stringify(flash), {
|
|
168
|
+
httpOnly: true,
|
|
169
|
+
sameSite: 'lax',
|
|
170
|
+
maxAge: 60,
|
|
171
|
+
})
|
|
172
|
+
return Response.redirect(refUrl.href, 303)
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
129
176
|
return Response.json(
|
|
130
177
|
{ ok: false, status: 400, error: 'Validation failed', fieldErrors: checked.fieldErrors, issues: checked.issues },
|
|
131
178
|
{ status: 400 },
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// Zero-dependency native HTTP compression (Bun.zstdCompressSync / Bun.gzipSync) with bounded byte-budget LRU.
|
|
2
|
+
// Never imports `node:zlib` so server RSS stays minimal.
|
|
3
|
+
|
|
4
|
+
export type CompressionEncoding = 'zstd' | 'gzip'
|
|
5
|
+
|
|
6
|
+
export const MIN_COMPRESS_BYTES = 256
|
|
7
|
+
const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
|
|
8
|
+
const encoder = new TextEncoder()
|
|
9
|
+
|
|
10
|
+
const COMPRESSIBLE_EXACT = new Set([
|
|
11
|
+
'application/javascript',
|
|
12
|
+
'application/json',
|
|
13
|
+
'application/xml',
|
|
14
|
+
'application/xhtml+xml',
|
|
15
|
+
'application/manifest+json',
|
|
16
|
+
'application/rss+xml',
|
|
17
|
+
'application/atom+xml',
|
|
18
|
+
'application/wasm',
|
|
19
|
+
'image/svg+xml',
|
|
20
|
+
])
|
|
21
|
+
|
|
22
|
+
export function isCompressibleType(contentType: string | null | undefined): boolean {
|
|
23
|
+
if (!contentType)
|
|
24
|
+
return false
|
|
25
|
+
const semi = contentType.indexOf(';')
|
|
26
|
+
const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase()
|
|
27
|
+
if (mime.startsWith('text/'))
|
|
28
|
+
return mime !== 'text/event-stream'
|
|
29
|
+
if (COMPRESSIBLE_EXACT.has(mime))
|
|
30
|
+
return true
|
|
31
|
+
return mime.endsWith('+json') || mime.endsWith('+xml')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function pickEncoding(acceptEncoding: string | null): CompressionEncoding | undefined {
|
|
35
|
+
if (!acceptEncoding)
|
|
36
|
+
return undefined
|
|
37
|
+
|
|
38
|
+
// Fast path: standard browser headers without q-values (e.g. "gzip, deflate, br, zstd")
|
|
39
|
+
if (!acceptEncoding.includes(';')) {
|
|
40
|
+
const lower = acceptEncoding.toLowerCase()
|
|
41
|
+
if (hasToken(lower, 'zstd'))
|
|
42
|
+
return 'zstd'
|
|
43
|
+
if (hasToken(lower, 'gzip'))
|
|
44
|
+
return 'gzip'
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
let zstdQ = -1
|
|
49
|
+
let gzipQ = -1
|
|
50
|
+
const parts = acceptEncoding.split(',')
|
|
51
|
+
for (let i = 0; i < parts.length; i++) {
|
|
52
|
+
const part = parts[i]!.trim()
|
|
53
|
+
if (!part)
|
|
54
|
+
continue
|
|
55
|
+
const semi = part.indexOf(';')
|
|
56
|
+
const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
|
|
57
|
+
if (name !== 'zstd' && name !== 'gzip')
|
|
58
|
+
continue
|
|
59
|
+
let q = 1
|
|
60
|
+
if (semi !== -1) {
|
|
61
|
+
const m = /;\s*q\s*=\s*([0-9.]+)/i.exec(part.slice(semi))
|
|
62
|
+
if (m !== null) {
|
|
63
|
+
const parsed = Number(m[1])
|
|
64
|
+
if (!Number.isNaN(parsed))
|
|
65
|
+
q = parsed
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
if (name === 'zstd')
|
|
69
|
+
zstdQ = q
|
|
70
|
+
else
|
|
71
|
+
gzipQ = q
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (zstdQ <= 0 && gzipQ <= 0)
|
|
75
|
+
return undefined
|
|
76
|
+
return zstdQ >= gzipQ ? 'zstd' : 'gzip'
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function hasToken(haystack: string, token: string): boolean {
|
|
80
|
+
let idx = haystack.indexOf(token)
|
|
81
|
+
while (idx !== -1) {
|
|
82
|
+
const before = idx === 0 ? ',' : haystack[idx - 1]!
|
|
83
|
+
const after = idx + token.length === haystack.length ? ',' : haystack[idx + token.length]!
|
|
84
|
+
if ((before === ',' || before === ' ' || before === '\t') && (after === ',' || after === ' ' || after === '\t'))
|
|
85
|
+
return true
|
|
86
|
+
idx = haystack.indexOf(token, idx + token.length)
|
|
87
|
+
}
|
|
88
|
+
return false
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
|
|
92
|
+
if (encoding === 'zstd')
|
|
93
|
+
return Bun.zstdCompressSync(bytes, { level: 3 }) as Uint8Array<ArrayBuffer>
|
|
94
|
+
return Bun.gzipSync(bytes, { level: 6 }) as Uint8Array<ArrayBuffer>
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export class CompressionCache {
|
|
98
|
+
readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
99
|
+
readonly #maxBytes: number
|
|
100
|
+
readonly #maxEntryBytes: number
|
|
101
|
+
#totalBytes = 0
|
|
102
|
+
|
|
103
|
+
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES) {
|
|
104
|
+
this.#maxBytes = maxBytes
|
|
105
|
+
this.#maxEntryBytes = Math.floor(maxBytes / 4)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
get(key: string): Uint8Array<ArrayBuffer> | undefined {
|
|
109
|
+
const hit = this.#map.get(key)
|
|
110
|
+
if (hit === undefined)
|
|
111
|
+
return undefined
|
|
112
|
+
// Refresh recency
|
|
113
|
+
this.#map.delete(key)
|
|
114
|
+
this.#map.set(key, hit)
|
|
115
|
+
return hit
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
set(key: string, value: Uint8Array<ArrayBuffer>): void {
|
|
119
|
+
const size = value.byteLength
|
|
120
|
+
if (size > this.#maxEntryBytes)
|
|
121
|
+
return
|
|
122
|
+
const prev = this.#map.get(key)
|
|
123
|
+
if (prev !== undefined) {
|
|
124
|
+
this.#totalBytes -= prev.byteLength
|
|
125
|
+
this.#map.delete(key)
|
|
126
|
+
}
|
|
127
|
+
this.#map.set(key, value)
|
|
128
|
+
this.#totalBytes += size
|
|
129
|
+
while (this.#totalBytes > this.#maxBytes) {
|
|
130
|
+
const oldest = this.#map.keys().next()
|
|
131
|
+
if (oldest.done)
|
|
132
|
+
break
|
|
133
|
+
const evicted = this.#map.get(oldest.value)!
|
|
134
|
+
this.#map.delete(oldest.value)
|
|
135
|
+
this.#totalBytes -= evicted.byteLength
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
compress(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
|
|
140
|
+
if (bytes.byteLength < MIN_COMPRESS_BYTES)
|
|
141
|
+
return undefined
|
|
142
|
+
const cacheKey = staticKey !== undefined
|
|
143
|
+
? `${encoding}:${staticKey}`
|
|
144
|
+
: `${encoding}:h:${Bun.hash.wyhash(bytes).toString(36)}:${bytes.byteLength}`
|
|
145
|
+
const cached = this.get(cacheKey)
|
|
146
|
+
if (cached !== undefined)
|
|
147
|
+
return cached
|
|
148
|
+
const compressed = compressBuffer(bytes, encoding)
|
|
149
|
+
if (compressed.byteLength >= bytes.byteLength)
|
|
150
|
+
return undefined
|
|
151
|
+
this.set(cacheKey, compressed)
|
|
152
|
+
return compressed
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function appendVaryAcceptEncoding(headers: Headers): void {
|
|
157
|
+
const existing = headers.get('vary')
|
|
158
|
+
if (!existing) {
|
|
159
|
+
headers.set('vary', 'Accept-Encoding')
|
|
160
|
+
}
|
|
161
|
+
else if (!existing.toLowerCase().includes('accept-encoding')) {
|
|
162
|
+
headers.set('vary', `${existing}, Accept-Encoding`)
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function compressedHtmlResponse(
|
|
167
|
+
html: string,
|
|
168
|
+
status: number,
|
|
169
|
+
baseHeaders: Record<string, string>,
|
|
170
|
+
request: Request,
|
|
171
|
+
cache: CompressionCache | undefined,
|
|
172
|
+
): Response {
|
|
173
|
+
if (cache !== undefined && request.method !== 'HEAD') {
|
|
174
|
+
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
175
|
+
if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
|
|
176
|
+
const staticKey = `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}`
|
|
177
|
+
let compressed = cache.get(`${enc}:${staticKey}`)
|
|
178
|
+
if (compressed === undefined) {
|
|
179
|
+
const bytes = encoder.encode(html)
|
|
180
|
+
compressed = cache.compress(bytes, enc, staticKey)
|
|
181
|
+
}
|
|
182
|
+
if (compressed !== undefined) {
|
|
183
|
+
return new Response(compressed, {
|
|
184
|
+
status,
|
|
185
|
+
headers: { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' },
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return new Response(request.method === 'HEAD' ? null : html, {
|
|
191
|
+
status,
|
|
192
|
+
headers: cache !== undefined ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
|
|
193
|
+
})
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export async function maybeCompressResponse(
|
|
197
|
+
res: Response,
|
|
198
|
+
request: Request,
|
|
199
|
+
cache: CompressionCache | undefined,
|
|
200
|
+
): Promise<Response> {
|
|
201
|
+
if (cache === undefined)
|
|
202
|
+
return res
|
|
203
|
+
if (res.status === 204 || res.status === 304 || (res.status >= 300 && res.status < 400))
|
|
204
|
+
return res
|
|
205
|
+
if (res.headers.has('content-encoding'))
|
|
206
|
+
return res
|
|
207
|
+
if (!isCompressibleType(res.headers.get('content-type')))
|
|
208
|
+
return res
|
|
209
|
+
|
|
210
|
+
const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
|
|
211
|
+
if (enc === undefined) {
|
|
212
|
+
try {
|
|
213
|
+
appendVaryAcceptEncoding(res.headers)
|
|
214
|
+
}
|
|
215
|
+
catch {}
|
|
216
|
+
return res
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const cl = res.headers.get('content-length')
|
|
220
|
+
if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES) {
|
|
221
|
+
try {
|
|
222
|
+
appendVaryAcceptEncoding(res.headers)
|
|
223
|
+
}
|
|
224
|
+
catch {}
|
|
225
|
+
return res
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (res.body === null)
|
|
229
|
+
return res
|
|
230
|
+
|
|
231
|
+
const raw = new Uint8Array(await res.arrayBuffer())
|
|
232
|
+
const compressed = cache.compress(raw, enc)
|
|
233
|
+
const headers = new Headers(res.headers)
|
|
234
|
+
appendVaryAcceptEncoding(headers)
|
|
235
|
+
if (compressed === undefined)
|
|
236
|
+
return new Response(raw, { status: res.status, statusText: res.statusText, headers })
|
|
237
|
+
|
|
238
|
+
headers.set('content-encoding', enc)
|
|
239
|
+
headers.delete('content-length')
|
|
240
|
+
return new Response(compressed, { status: res.status, statusText: res.statusText, headers })
|
|
241
|
+
}
|
package/src/server/cookies.ts
CHANGED
|
@@ -83,6 +83,10 @@ export class CookieStore implements Cookies {
|
|
|
83
83
|
return Object.fromEntries(this.#values)
|
|
84
84
|
}
|
|
85
85
|
|
|
86
|
+
get hasChanges(): boolean {
|
|
87
|
+
return this.#headers.length > 0
|
|
88
|
+
}
|
|
89
|
+
|
|
86
90
|
applyTo(headers: Headers): void {
|
|
87
91
|
for (let i = 0; i < this.#headers.length; i++)
|
|
88
92
|
headers.append('set-cookie', this.#headers[i]!)
|
package/src/server/http.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { KayPlugin } from '../plugins/index'
|
|
|
5
5
|
import type { Cookies } from './cookies'
|
|
6
6
|
import type { SecurityHeadersOptions } from './security'
|
|
7
7
|
import { CookieStore } from './cookies'
|
|
8
|
-
import {
|
|
8
|
+
import { buildSecurityHeaderEntries } from './security'
|
|
9
9
|
|
|
10
10
|
export interface ServerOptions {
|
|
11
11
|
root: string
|
|
@@ -15,6 +15,7 @@ export interface ServerOptions {
|
|
|
15
15
|
lang?: string | undefined
|
|
16
16
|
security?: SecurityHeadersOptions | false | undefined
|
|
17
17
|
trustedOrigins?: string[] | undefined
|
|
18
|
+
compress?: boolean | undefined
|
|
18
19
|
plugins?: KayPlugin[] | undefined
|
|
19
20
|
}
|
|
20
21
|
|
|
@@ -46,10 +47,12 @@ export interface EmbeddedServerConfig {
|
|
|
46
47
|
publicAssets?: Record<string, EmbeddedBody> | undefined
|
|
47
48
|
publicEtags?: Record<string, string> | undefined
|
|
48
49
|
prerendered: Record<string, string>
|
|
50
|
+
prerenderedFiles?: Record<string, string> | undefined
|
|
49
51
|
assetPrefix?: string | undefined
|
|
50
52
|
lang?: string | undefined
|
|
51
53
|
security?: SecurityHeadersOptions | false | undefined
|
|
52
54
|
trustedOrigins?: string[] | undefined
|
|
55
|
+
compress?: boolean | undefined
|
|
53
56
|
plugins?: KayPlugin[] | undefined
|
|
54
57
|
}
|
|
55
58
|
|
|
@@ -114,10 +117,40 @@ export function makeRequestContext(request: Request, params: Record<string, stri
|
|
|
114
117
|
return { ctx, cookieStore }
|
|
115
118
|
}
|
|
116
119
|
|
|
117
|
-
export function finalizeResponse(
|
|
118
|
-
|
|
119
|
-
cookieStore
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
120
|
+
export function finalizeResponse(
|
|
121
|
+
res: Response,
|
|
122
|
+
cookieStore: CookieStore,
|
|
123
|
+
securityEntries: readonly [string, string][] | SecurityHeadersOptions | false | undefined,
|
|
124
|
+
): Response {
|
|
125
|
+
const entries: readonly [string, string][] = Array.isArray(securityEntries)
|
|
126
|
+
? securityEntries
|
|
127
|
+
: buildSecurityHeaderEntries(securityEntries as SecurityHeadersOptions | false | undefined)
|
|
128
|
+
|
|
129
|
+
if (!cookieStore.hasChanges && entries.length === 0)
|
|
130
|
+
return res
|
|
131
|
+
|
|
132
|
+
// Fast path: mutate Response.headers in place (zero Response/Headers copy in Bun!)
|
|
133
|
+
try {
|
|
134
|
+
const h = res.headers
|
|
135
|
+
if (cookieStore.hasChanges)
|
|
136
|
+
cookieStore.applyTo(h)
|
|
137
|
+
for (let i = 0; i < entries.length; i++) {
|
|
138
|
+
const [k, v] = entries[i]!
|
|
139
|
+
if (!h.has(k))
|
|
140
|
+
h.set(k, v)
|
|
141
|
+
}
|
|
142
|
+
return res
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
// Fallback for immutable headers (e.g. proxied upstream fetch Response)
|
|
146
|
+
const headers = new Headers(res.headers)
|
|
147
|
+
if (cookieStore.hasChanges)
|
|
148
|
+
cookieStore.applyTo(headers)
|
|
149
|
+
for (let i = 0; i < entries.length; i++) {
|
|
150
|
+
const [k, v] = entries[i]!
|
|
151
|
+
if (!headers.has(k))
|
|
152
|
+
headers.set(k, v)
|
|
153
|
+
}
|
|
154
|
+
return new Response(res.body, { status: res.status, statusText: res.statusText, headers })
|
|
155
|
+
}
|
|
123
156
|
}
|