@kayjs/kay 2.0.0-beta.0 → 2.0.0-beta.2
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/attrs.ts +35 -0
- package/src/build/bundle.ts +615 -0
- package/src/build/compile.ts +32 -19
- package/src/build/files.ts +174 -0
- package/src/build/graph.ts +223 -0
- package/src/build/index.ts +255 -1461
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +227 -0
- package/src/build/plugin-host.ts +186 -0
- package/src/build/prerender.ts +94 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +51 -0
- package/src/build/routes.ts +163 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +300 -129
- package/src/cli/index.ts +297 -94
- package/src/cli/new.ts +58 -38
- package/src/compiler/analyze.ts +723 -93
- package/src/compiler/dom.ts +848 -762
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +172 -23
- package/src/compiler/shared.ts +485 -0
- package/src/compiler/ssr.ts +331 -342
- package/src/context.ts +120 -0
- package/src/dev/index.ts +358 -76
- package/src/dom/action.ts +114 -14
- package/src/dom/extras.ts +121 -83
- package/src/dom/index.ts +122 -80
- package/src/dom/island.ts +71 -36
- package/src/dom/loop.ts +28 -20
- package/src/index.ts +5 -1
- package/src/jsx-runtime.ts +432 -93
- package/src/plugins/context.ts +83 -0
- package/src/plugins/index.ts +285 -23
- package/src/reactivity/index.ts +237 -213
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +36 -11
- package/src/server/action.ts +157 -79
- package/src/server/compress.ts +197 -104
- package/src/server/cookies.ts +46 -16
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +189 -77
- package/src/server/index.ts +1024 -878
- package/src/server/loader.ts +138 -0
- package/src/server/router.ts +69 -26
- package/src/server/security.ts +50 -58
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +95 -10
- package/src/ssr/index.ts +167 -66
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -15
- package/src/unrenderable.ts +35 -0
package/src/server/compress.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
export type CompressionEncoding = 'zstd' | 'gzip'
|
|
5
5
|
export type PrecompressedEncoding = 'br' | 'gzip'
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
const MIN_COMPRESS_BYTES = 256
|
|
8
8
|
const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
|
|
9
9
|
const encoder = new TextEncoder()
|
|
10
10
|
|
|
@@ -32,98 +32,52 @@ export function isCompressibleType(contentType: string | null | undefined): bool
|
|
|
32
32
|
return mime.endsWith('+json') || mime.endsWith('+xml')
|
|
33
33
|
}
|
|
34
34
|
|
|
35
|
-
|
|
36
|
-
if (!acceptEncoding)
|
|
37
|
-
return undefined
|
|
35
|
+
const Q_VALUE_RE = /;\s*q\s*=\s*([0-9.]+)/i
|
|
38
36
|
|
|
39
|
-
|
|
37
|
+
// The `first` token wins ties; a token the header omits or gives q=0 never wins. Headers without q-values (the usual browser ones) take the allocation-free path.
|
|
38
|
+
function pickToken<A extends string, B extends string>(acceptEncoding: string, first: A | undefined, second: B | undefined): A | B | undefined {
|
|
40
39
|
if (!acceptEncoding.includes(';')) {
|
|
41
40
|
const lower = acceptEncoding.toLowerCase()
|
|
42
|
-
if (hasToken(lower,
|
|
43
|
-
return
|
|
44
|
-
|
|
45
|
-
return 'gzip'
|
|
46
|
-
return undefined
|
|
41
|
+
if (first !== undefined && hasToken(lower, first))
|
|
42
|
+
return first
|
|
43
|
+
return second !== undefined && hasToken(lower, second) ? second : undefined
|
|
47
44
|
}
|
|
48
45
|
|
|
49
|
-
let
|
|
50
|
-
let
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
const part = parts[i]!.trim()
|
|
54
|
-
if (!part)
|
|
55
|
-
continue
|
|
46
|
+
let firstQ = -1
|
|
47
|
+
let secondQ = -1
|
|
48
|
+
for (const rawPart of acceptEncoding.split(',')) {
|
|
49
|
+
const part = rawPart.trim()
|
|
56
50
|
const semi = part.indexOf(';')
|
|
57
51
|
const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
|
|
58
|
-
if (name !==
|
|
52
|
+
if (name !== first && name !== second)
|
|
59
53
|
continue
|
|
60
54
|
let q = 1
|
|
61
55
|
if (semi !== -1) {
|
|
62
|
-
const
|
|
63
|
-
if (
|
|
64
|
-
|
|
65
|
-
if (!Number.isNaN(parsed))
|
|
66
|
-
q = parsed
|
|
67
|
-
}
|
|
56
|
+
const parsed = Number(Q_VALUE_RE.exec(part.slice(semi))?.[1])
|
|
57
|
+
if (!Number.isNaN(parsed))
|
|
58
|
+
q = parsed
|
|
68
59
|
}
|
|
69
|
-
if (name ===
|
|
70
|
-
|
|
60
|
+
if (name === first)
|
|
61
|
+
firstQ = q
|
|
71
62
|
else
|
|
72
|
-
|
|
63
|
+
secondQ = q
|
|
73
64
|
}
|
|
74
|
-
|
|
75
|
-
if (zstdQ <= 0 && gzipQ <= 0)
|
|
65
|
+
if (firstQ <= 0 && secondQ <= 0)
|
|
76
66
|
return undefined
|
|
77
|
-
return
|
|
67
|
+
return firstQ >= secondQ ? first : second
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function pickEncoding(acceptEncoding: string | null): CompressionEncoding | undefined {
|
|
71
|
+
return acceptEncoding ? pickToken(acceptEncoding, 'zstd', 'gzip') : undefined
|
|
78
72
|
}
|
|
79
73
|
|
|
80
74
|
export function pickPrecompressedEncoding(
|
|
81
75
|
acceptEncoding: string | null,
|
|
82
76
|
available: { br?: boolean, gz?: boolean },
|
|
83
77
|
): PrecompressedEncoding | undefined {
|
|
84
|
-
if (!acceptEncoding
|
|
85
|
-
return undefined
|
|
86
|
-
|
|
87
|
-
if (!acceptEncoding.includes(';')) {
|
|
88
|
-
const lower = acceptEncoding.toLowerCase()
|
|
89
|
-
if (available.br && hasToken(lower, 'br'))
|
|
90
|
-
return 'br'
|
|
91
|
-
if (available.gz && hasToken(lower, 'gzip'))
|
|
92
|
-
return 'gzip'
|
|
93
|
-
return undefined
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
let brQ = -1
|
|
97
|
-
let gzipQ = -1
|
|
98
|
-
const parts = acceptEncoding.split(',')
|
|
99
|
-
for (let i = 0; i < parts.length; i++) {
|
|
100
|
-
const part = parts[i]!.trim()
|
|
101
|
-
if (!part)
|
|
102
|
-
continue
|
|
103
|
-
const semi = part.indexOf(';')
|
|
104
|
-
const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
|
|
105
|
-
if (name !== 'br' && name !== 'gzip')
|
|
106
|
-
continue
|
|
107
|
-
let q = 1
|
|
108
|
-
if (semi !== -1) {
|
|
109
|
-
const m = /;\s*q\s*=\s*([0-9.]+)/i.exec(part.slice(semi))
|
|
110
|
-
if (m !== null) {
|
|
111
|
-
const parsed = Number(m[1])
|
|
112
|
-
if (!Number.isNaN(parsed))
|
|
113
|
-
q = parsed
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
if (name === 'br')
|
|
117
|
-
brQ = q
|
|
118
|
-
else
|
|
119
|
-
gzipQ = q
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const effBr = available.br ? brQ : -1
|
|
123
|
-
const effGz = available.gz ? gzipQ : -1
|
|
124
|
-
if (effBr <= 0 && effGz <= 0)
|
|
78
|
+
if (!acceptEncoding)
|
|
125
79
|
return undefined
|
|
126
|
-
return
|
|
80
|
+
return pickToken(acceptEncoding, available.br ? 'br' : undefined, available.gz ? 'gzip' : undefined)
|
|
127
81
|
}
|
|
128
82
|
|
|
129
83
|
export function toWeakEtag(etag: string): string {
|
|
@@ -134,14 +88,85 @@ function hasNoTransform(cacheControl: string | null | undefined): boolean {
|
|
|
134
88
|
return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
|
|
135
89
|
}
|
|
136
90
|
|
|
137
|
-
|
|
138
|
-
|
|
91
|
+
const PENDING: unique symbol = Symbol('pending')
|
|
92
|
+
const MAX_BUFFERED_PROBE_CHUNKS = 32
|
|
93
|
+
const MAX_BUFFERED_PROBE_BYTES = 4 * 1024 * 1024
|
|
94
|
+
|
|
95
|
+
function concatChunks(chunks: readonly Uint8Array[], totalBytes: number): Uint8Array<ArrayBuffer> {
|
|
96
|
+
if (chunks.length === 1) {
|
|
97
|
+
const only = chunks[0]!
|
|
98
|
+
if (only.buffer instanceof ArrayBuffer && only.byteOffset === 0 && only.byteLength === only.buffer.byteLength)
|
|
99
|
+
return only as Uint8Array<ArrayBuffer>
|
|
100
|
+
}
|
|
101
|
+
const out = new Uint8Array(totalBytes)
|
|
102
|
+
let offset = 0
|
|
103
|
+
for (const chunk of chunks) {
|
|
104
|
+
out.set(chunk, offset)
|
|
105
|
+
offset += chunk.byteLength
|
|
106
|
+
}
|
|
107
|
+
return out
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Microtask-only probe: buffered bodies (string, TypedArray, JSON, closed streams) settle all chunks
|
|
111
|
+
// within microtasks and can be compressed; open streams stay pending and pass straight through unbuffered.
|
|
112
|
+
async function readBufferedOrPassThrough(
|
|
113
|
+
res: Response,
|
|
114
|
+
): Promise<{ buffered: Uint8Array<ArrayBuffer> } | { passthrough: Response }> {
|
|
139
115
|
const te = res.headers.get('transfer-encoding')
|
|
140
|
-
if (te && te.toLowerCase().includes('chunked'))
|
|
141
|
-
return
|
|
142
|
-
if (
|
|
143
|
-
return
|
|
144
|
-
|
|
116
|
+
if (te !== null && te.toLowerCase().includes('chunked'))
|
|
117
|
+
return { passthrough: res }
|
|
118
|
+
if (res.body === null)
|
|
119
|
+
return { buffered: new Uint8Array(0) }
|
|
120
|
+
|
|
121
|
+
const reader = res.body.getReader()
|
|
122
|
+
const chunks: Uint8Array[] = []
|
|
123
|
+
let totalBytes = 0
|
|
124
|
+
let pendingRead: ReturnType<typeof reader.read> | undefined
|
|
125
|
+
|
|
126
|
+
while (true) {
|
|
127
|
+
const readPromise = reader.read()
|
|
128
|
+
const tick = Promise.resolve().then(() => Promise.resolve()).then((): typeof PENDING => PENDING)
|
|
129
|
+
const outcome = await Promise.race([readPromise, tick])
|
|
130
|
+
if (outcome === PENDING) {
|
|
131
|
+
pendingRead = readPromise
|
|
132
|
+
break
|
|
133
|
+
}
|
|
134
|
+
if (outcome.done) {
|
|
135
|
+
reader.releaseLock()
|
|
136
|
+
return { buffered: concatChunks(chunks, totalBytes) }
|
|
137
|
+
}
|
|
138
|
+
chunks.push(outcome.value)
|
|
139
|
+
totalBytes += outcome.value.byteLength
|
|
140
|
+
if (chunks.length >= MAX_BUFFERED_PROBE_CHUNKS || totalBytes > MAX_BUFFERED_PROBE_BYTES)
|
|
141
|
+
break
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
let chunkIdx = 0
|
|
145
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
146
|
+
async pull(controller) {
|
|
147
|
+
if (chunkIdx < chunks.length) {
|
|
148
|
+
controller.enqueue(chunks[chunkIdx++]!)
|
|
149
|
+
return
|
|
150
|
+
}
|
|
151
|
+
const next = pendingRead !== undefined ? pendingRead : reader.read()
|
|
152
|
+
pendingRead = undefined
|
|
153
|
+
const { done, value } = await next
|
|
154
|
+
if (done)
|
|
155
|
+
controller.close()
|
|
156
|
+
else
|
|
157
|
+
controller.enqueue(value)
|
|
158
|
+
},
|
|
159
|
+
cancel(reason) {
|
|
160
|
+
return reader.cancel(reason)
|
|
161
|
+
},
|
|
162
|
+
})
|
|
163
|
+
return {
|
|
164
|
+
passthrough: new Response(stream, {
|
|
165
|
+
status: res.status,
|
|
166
|
+
statusText: res.statusText,
|
|
167
|
+
headers: res.headers,
|
|
168
|
+
}),
|
|
169
|
+
}
|
|
145
170
|
}
|
|
146
171
|
|
|
147
172
|
function hasToken(haystack: string, token: string): boolean {
|
|
@@ -156,21 +181,40 @@ function hasToken(haystack: string, token: string): boolean {
|
|
|
156
181
|
return false
|
|
157
182
|
}
|
|
158
183
|
|
|
159
|
-
|
|
184
|
+
function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
|
|
160
185
|
if (encoding === 'zstd')
|
|
161
186
|
return Bun.zstdCompressSync(bytes, { level: 3 }) as Uint8Array<ArrayBuffer>
|
|
162
187
|
return Bun.gzipSync(bytes, { level: 6 }) as Uint8Array<ArrayBuffer>
|
|
163
188
|
}
|
|
164
189
|
|
|
190
|
+
// `undefined` when the input is too small to be worth compressing or does not shrink.
|
|
191
|
+
function shrink(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | undefined {
|
|
192
|
+
if (bytes.byteLength < MIN_COMPRESS_BYTES)
|
|
193
|
+
return undefined
|
|
194
|
+
const compressed = compressBuffer(bytes, encoding)
|
|
195
|
+
return compressed.byteLength < bytes.byteLength ? compressed : undefined
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const DEFAULT_MAX_FILE_CACHE_BYTES = 8 * 1024 * 1024
|
|
199
|
+
|
|
165
200
|
export class CompressionCache {
|
|
201
|
+
// Path-keyed build files (assets, public, prerendered pages): bounded byte-budget LRU + in-flight dedup. `null` marks a file that does not shrink.
|
|
202
|
+
readonly #files = new Map<string, Uint8Array<ArrayBuffer> | null>()
|
|
203
|
+
readonly #fileInflight = new Map<string, Promise<Uint8Array<ArrayBuffer> | undefined>>()
|
|
204
|
+
readonly #maxFileBytes: number
|
|
205
|
+
readonly #maxFileEntryBytes: number
|
|
206
|
+
#fileBytes = 0
|
|
207
|
+
// Content-hashed HTML of routes rendered per request: a byte-budget LRU.
|
|
166
208
|
readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
167
209
|
readonly #maxBytes: number
|
|
168
210
|
readonly #maxEntryBytes: number
|
|
169
211
|
#totalBytes = 0
|
|
170
212
|
|
|
171
|
-
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES) {
|
|
213
|
+
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES, maxFileBytes = DEFAULT_MAX_FILE_CACHE_BYTES) {
|
|
172
214
|
this.#maxBytes = maxBytes
|
|
173
215
|
this.#maxEntryBytes = Math.floor(maxBytes / 4)
|
|
216
|
+
this.#maxFileBytes = maxFileBytes
|
|
217
|
+
this.#maxFileEntryBytes = Math.floor(maxFileBytes / 4)
|
|
174
218
|
}
|
|
175
219
|
|
|
176
220
|
get(key: string): Uint8Array<ArrayBuffer> | undefined {
|
|
@@ -204,24 +248,66 @@ export class CompressionCache {
|
|
|
204
248
|
}
|
|
205
249
|
}
|
|
206
250
|
|
|
251
|
+
/** Compresses `bytes`, kept in the LRU under `staticKey` when given; without one nothing is stored. */
|
|
207
252
|
compress(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
const cacheKey = staticKey !== undefined
|
|
211
|
-
? `${encoding}:${staticKey}`
|
|
212
|
-
: `${encoding}:h:${Bun.hash.wyhash(bytes).toString(36)}:${bytes.byteLength}`
|
|
213
|
-
const cached = this.get(cacheKey)
|
|
253
|
+
const cacheKey = staticKey !== undefined ? `${encoding}:${staticKey}` : undefined
|
|
254
|
+
const cached = cacheKey !== undefined ? this.get(cacheKey) : undefined
|
|
214
255
|
if (cached !== undefined)
|
|
215
256
|
return cached
|
|
216
|
-
const compressed =
|
|
217
|
-
if (compressed
|
|
218
|
-
|
|
219
|
-
this.set(cacheKey, compressed)
|
|
257
|
+
const compressed = shrink(bytes, encoding)
|
|
258
|
+
if (compressed !== undefined && cacheKey !== undefined)
|
|
259
|
+
this.set(cacheKey, compressed)
|
|
220
260
|
return compressed
|
|
221
261
|
}
|
|
262
|
+
|
|
263
|
+
/** The compressed variant of a build file, read and compressed on its first request only (deduped + bounded LRU); `undefined` when it does not shrink. */
|
|
264
|
+
async file(key: string, encoding: CompressionEncoding, read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
265
|
+
const variantKey = `${encoding}:${key}`
|
|
266
|
+
if (this.#files.has(variantKey)) {
|
|
267
|
+
const hit = this.#files.get(variantKey)!
|
|
268
|
+
// Refresh LRU recency
|
|
269
|
+
this.#files.delete(variantKey)
|
|
270
|
+
this.#files.set(variantKey, hit)
|
|
271
|
+
return hit ?? undefined
|
|
272
|
+
}
|
|
273
|
+
const inflight = this.#fileInflight.get(variantKey)
|
|
274
|
+
if (inflight !== undefined)
|
|
275
|
+
return inflight
|
|
276
|
+
|
|
277
|
+
const task = (async () => {
|
|
278
|
+
const bytes = await read()
|
|
279
|
+
const variant = shrink(bytes, encoding) ?? null
|
|
280
|
+
if (variant === null) {
|
|
281
|
+
this.#files.set(variantKey, null)
|
|
282
|
+
return undefined
|
|
283
|
+
}
|
|
284
|
+
if (variant.byteLength <= this.#maxFileEntryBytes) {
|
|
285
|
+
this.#files.set(variantKey, variant)
|
|
286
|
+
this.#fileBytes += variant.byteLength
|
|
287
|
+
while (this.#fileBytes > this.#maxFileBytes) {
|
|
288
|
+
const oldest = this.#files.keys().next()
|
|
289
|
+
if (oldest.done)
|
|
290
|
+
break
|
|
291
|
+
const evicted = this.#files.get(oldest.value)
|
|
292
|
+
this.#files.delete(oldest.value)
|
|
293
|
+
if (evicted !== null && evicted !== undefined)
|
|
294
|
+
this.#fileBytes -= evicted.byteLength
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
return variant
|
|
298
|
+
})()
|
|
299
|
+
|
|
300
|
+
this.#fileInflight.set(variantKey, task)
|
|
301
|
+
try {
|
|
302
|
+
return await task
|
|
303
|
+
}
|
|
304
|
+
finally {
|
|
305
|
+
this.#fileInflight.delete(variantKey)
|
|
306
|
+
}
|
|
307
|
+
}
|
|
222
308
|
}
|
|
223
309
|
|
|
224
|
-
|
|
310
|
+
function appendVaryAcceptEncoding(headers: Headers): void {
|
|
225
311
|
const existing = headers.get('vary')
|
|
226
312
|
if (!existing) {
|
|
227
313
|
headers.set('vary', 'Accept-Encoding')
|
|
@@ -231,28 +317,30 @@ export function appendVaryAcceptEncoding(headers: Headers): void {
|
|
|
231
317
|
}
|
|
232
318
|
}
|
|
233
319
|
|
|
320
|
+
/** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
|
|
234
321
|
export function compressedHtmlResponse(
|
|
235
322
|
html: string,
|
|
236
323
|
status: number,
|
|
237
324
|
baseHeaders: Record<string, string>,
|
|
238
325
|
request: Request,
|
|
239
326
|
cache: CompressionCache | undefined,
|
|
327
|
+
reuse = false,
|
|
240
328
|
): Response {
|
|
241
329
|
const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
|
|
242
330
|
if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
|
|
243
331
|
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
244
332
|
if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
|
|
245
|
-
const staticKey = `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}`
|
|
246
|
-
let compressed = cache.get(`${enc}:${staticKey}`)
|
|
247
|
-
if (compressed === undefined)
|
|
248
|
-
|
|
249
|
-
compressed = cache.compress(bytes, enc, staticKey)
|
|
250
|
-
}
|
|
333
|
+
const staticKey = reuse ? `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}` : undefined
|
|
334
|
+
let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
|
|
335
|
+
if (compressed === undefined)
|
|
336
|
+
compressed = cache.compress(encoder.encode(html), enc, staticKey)
|
|
251
337
|
if (compressed !== undefined) {
|
|
252
338
|
const headers: Record<string, string> = { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' }
|
|
253
339
|
const etag = headers.etag ?? headers.ETag
|
|
254
|
-
if (etag !== undefined)
|
|
340
|
+
if (etag !== undefined) {
|
|
341
|
+
delete headers.ETag
|
|
255
342
|
headers.etag = toWeakEtag(etag)
|
|
343
|
+
}
|
|
256
344
|
return new Response(compressed, { status, headers })
|
|
257
345
|
}
|
|
258
346
|
}
|
|
@@ -280,10 +368,6 @@ export async function maybeCompressResponse(
|
|
|
280
368
|
return res
|
|
281
369
|
|
|
282
370
|
const cl = res.headers.get('content-length')
|
|
283
|
-
// Never buffer streaming responses that have no Content-Length (e.g. chunked streams, ReadableStream)
|
|
284
|
-
if (cl === null && isStreamingBody(res))
|
|
285
|
-
return res
|
|
286
|
-
|
|
287
371
|
const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
|
|
288
372
|
if (enc === undefined) {
|
|
289
373
|
try {
|
|
@@ -304,7 +388,16 @@ export async function maybeCompressResponse(
|
|
|
304
388
|
if (res.body === null)
|
|
305
389
|
return res
|
|
306
390
|
|
|
307
|
-
|
|
391
|
+
let raw: Uint8Array<ArrayBuffer>
|
|
392
|
+
if (cl !== null) {
|
|
393
|
+
raw = new Uint8Array(await res.arrayBuffer())
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
const probe = await readBufferedOrPassThrough(res)
|
|
397
|
+
if ('passthrough' in probe)
|
|
398
|
+
return probe.passthrough
|
|
399
|
+
raw = probe.buffered
|
|
400
|
+
}
|
|
308
401
|
const compressed = cache.compress(raw, enc)
|
|
309
402
|
const headers = new Headers(res.headers)
|
|
310
403
|
appendVaryAcceptEncoding(headers)
|
package/src/server/cookies.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Typed cookie jar for RequestContext (
|
|
1
|
+
// Typed cookie jar for RequestContext (lazy Cookie header parsing, validated & deduplicated Set-Cookie serialization).
|
|
2
2
|
|
|
3
3
|
export interface CookieOptions {
|
|
4
4
|
path?: string | undefined
|
|
@@ -17,7 +17,10 @@ export interface Cookies {
|
|
|
17
17
|
all(): Record<string, string>
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
const VALID_COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/
|
|
21
|
+
const UNSAFE_ATTR_VAL = /[;\r\n\u0000-\u001F\u007F]/
|
|
22
|
+
|
|
23
|
+
function parseCookieHeader(header: string | null): Map<string, string> {
|
|
21
24
|
const map = new Map<string, string>()
|
|
22
25
|
if (!header)
|
|
23
26
|
return map
|
|
@@ -28,6 +31,9 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
|
|
|
28
31
|
if (eq <= 0)
|
|
29
32
|
continue
|
|
30
33
|
const name = part.slice(0, eq).trim()
|
|
34
|
+
// RFC 6265 §5.4: more specific path cookies come first, so first wins.
|
|
35
|
+
if (name === '' || map.has(name))
|
|
36
|
+
continue
|
|
31
37
|
const raw = part.slice(eq + 1).trim()
|
|
32
38
|
try {
|
|
33
39
|
map.set(name, decodeURIComponent(raw))
|
|
@@ -40,17 +46,28 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
|
|
|
40
46
|
}
|
|
41
47
|
|
|
42
48
|
function serializeCookie(name: string, value: string, options: CookieOptions = {}, defaultSecure = false): string {
|
|
49
|
+
if (!VALID_COOKIE_NAME.test(name))
|
|
50
|
+
throw new TypeError(`kay: invalid cookie name "${name}"`)
|
|
51
|
+
const path = options.path ?? '/'
|
|
52
|
+
if (UNSAFE_ATTR_VAL.test(path))
|
|
53
|
+
throw new TypeError(`kay: invalid cookie path "${path}"`)
|
|
54
|
+
if (options.domain !== undefined && UNSAFE_ATTR_VAL.test(options.domain))
|
|
55
|
+
throw new TypeError(`kay: invalid cookie domain "${options.domain}"`)
|
|
56
|
+
|
|
43
57
|
const secure = options.secure ?? defaultSecure
|
|
44
58
|
const sameSite = options.sameSite ?? 'lax'
|
|
45
59
|
if (sameSite === 'none' && !secure)
|
|
46
60
|
throw new Error(`kay: Cookie "${name}" with sameSite: "none" requires secure: true`)
|
|
47
61
|
|
|
48
62
|
let out = `${name}=${encodeURIComponent(value)}`
|
|
49
|
-
out += `; Path=${
|
|
63
|
+
out += `; Path=${path}`
|
|
50
64
|
if (options.domain !== undefined)
|
|
51
65
|
out += `; Domain=${options.domain}`
|
|
52
|
-
if (options.maxAge !== undefined)
|
|
66
|
+
if (options.maxAge !== undefined) {
|
|
67
|
+
if (!Number.isFinite(options.maxAge))
|
|
68
|
+
throw new TypeError(`kay: invalid cookie maxAge "${options.maxAge}"`)
|
|
53
69
|
out += `; Max-Age=${Math.floor(options.maxAge)}`
|
|
70
|
+
}
|
|
54
71
|
if (options.expires !== undefined)
|
|
55
72
|
out += `; Expires=${options.expires.toUTCString()}`
|
|
56
73
|
if (options.httpOnly ?? true)
|
|
@@ -61,41 +78,54 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
|
|
|
61
78
|
return out
|
|
62
79
|
}
|
|
63
80
|
|
|
81
|
+
function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): string {
|
|
82
|
+
return `${name}\0${options?.path ?? '/'}\0${options?.domain ?? ''}`
|
|
83
|
+
}
|
|
84
|
+
|
|
64
85
|
export class CookieStore implements Cookies {
|
|
65
|
-
|
|
66
|
-
|
|
86
|
+
#rawHeader: string | null
|
|
87
|
+
#values: Map<string, string> | undefined
|
|
88
|
+
readonly #headers = new Map<string, string>()
|
|
67
89
|
readonly #isHttps: boolean
|
|
68
90
|
|
|
69
91
|
constructor(cookieHeader: string | null, isHttps = false) {
|
|
70
|
-
this.#
|
|
92
|
+
this.#rawHeader = cookieHeader
|
|
71
93
|
this.#isHttps = isHttps
|
|
72
94
|
}
|
|
73
95
|
|
|
96
|
+
#ensureValues(): Map<string, string> {
|
|
97
|
+
if (this.#values === undefined) {
|
|
98
|
+
this.#values = parseCookieHeader(this.#rawHeader)
|
|
99
|
+
this.#rawHeader = null
|
|
100
|
+
}
|
|
101
|
+
return this.#values
|
|
102
|
+
}
|
|
103
|
+
|
|
74
104
|
get(name: string): string | undefined {
|
|
75
|
-
return this.#
|
|
105
|
+
return this.#ensureValues().get(name)
|
|
76
106
|
}
|
|
77
107
|
|
|
78
108
|
set(name: string, value: string, options?: CookieOptions): void {
|
|
79
109
|
const serialized = serializeCookie(name, value, options, this.#isHttps)
|
|
80
|
-
this.#
|
|
81
|
-
this.#headers.
|
|
110
|
+
this.#ensureValues().set(name, value)
|
|
111
|
+
this.#headers.set(cookieKey(name, options), serialized)
|
|
82
112
|
}
|
|
83
113
|
|
|
84
114
|
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
|
|
85
|
-
this.#
|
|
86
|
-
this.#headers.
|
|
115
|
+
this.#ensureValues().delete(name)
|
|
116
|
+
this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
|
|
87
117
|
}
|
|
88
118
|
|
|
89
119
|
all(): Record<string, string> {
|
|
90
|
-
return Object.fromEntries(this.#
|
|
120
|
+
return Object.fromEntries(this.#ensureValues())
|
|
91
121
|
}
|
|
92
122
|
|
|
93
123
|
get hasChanges(): boolean {
|
|
94
|
-
return this.#headers.
|
|
124
|
+
return this.#headers.size > 0
|
|
95
125
|
}
|
|
96
126
|
|
|
97
127
|
applyTo(headers: Headers): void {
|
|
98
|
-
for (
|
|
99
|
-
headers.append('set-cookie',
|
|
128
|
+
for (const serialized of this.#headers.values())
|
|
129
|
+
headers.append('set-cookie', serialized)
|
|
100
130
|
}
|
|
101
131
|
}
|
package/src/server/env.ts
CHANGED
|
@@ -1,27 +1,32 @@
|
|
|
1
1
|
// Typed environment variable loader using any Standard Schema validator.
|
|
2
2
|
|
|
3
3
|
import type { InferOutput, StandardSchemaV1 } from './standard-schema'
|
|
4
|
+
import { formatIssuePath, validateSchemaSync } from './standard-schema'
|
|
5
|
+
|
|
6
|
+
const NODE_ENV_KEY = 'NODE_ENV'
|
|
7
|
+
|
|
8
|
+
/** Reads NODE_ENV at runtime: the dynamic key keeps Bun.build from constant-folding it in compiled binaries. */
|
|
9
|
+
export function nodeEnv(): string | undefined {
|
|
10
|
+
return process.env[NODE_ENV_KEY]
|
|
11
|
+
}
|
|
4
12
|
|
|
5
13
|
export function defineEnv<S extends StandardSchemaV1>(
|
|
6
14
|
schema: S,
|
|
7
15
|
source: Record<string, string | undefined> = process.env,
|
|
8
16
|
): Readonly<InferOutput<S>> {
|
|
9
|
-
const result =
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
17
|
+
const result = validateSchemaSync(
|
|
18
|
+
schema,
|
|
19
|
+
source,
|
|
20
|
+
'kay: defineEnv() requires a synchronous Standard Schema validator',
|
|
21
|
+
)
|
|
22
|
+
if (!result.ok) {
|
|
14
23
|
const details = result.issues
|
|
15
|
-
.map((issue)
|
|
16
|
-
const key = issue.path && issue.path.length > 0
|
|
17
|
-
? issue.path.map(seg => (typeof seg === 'object' && seg !== null && 'key' in seg ? String(seg.key) : String(seg))).join('.')
|
|
18
|
-
: '(root)'
|
|
19
|
-
return ` - ${key}: ${issue.message}`
|
|
20
|
-
})
|
|
24
|
+
.map(issue => ` - ${formatIssuePath(issue) || '(root)'}: ${issue.message}`)
|
|
21
25
|
.join('\n')
|
|
22
26
|
throw new Error(`kay: invalid environment variables:\n${details}`)
|
|
23
27
|
}
|
|
24
28
|
|
|
25
|
-
|
|
26
|
-
|
|
29
|
+
return typeof result.value === 'object' && result.value !== null
|
|
30
|
+
? Object.freeze({ ...result.value })
|
|
31
|
+
: result.value
|
|
27
32
|
}
|