@kayjs/kay 2.0.0-alpha.8 → 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.
- package/package.json +1 -1
- package/src/attrs.ts +35 -0
- package/src/build/bundle.ts +442 -0
- package/src/build/compile.ts +20 -11
- package/src/build/files.ts +136 -0
- package/src/build/graph.ts +158 -0
- package/src/build/index.ts +231 -1296
- package/src/build/islands.ts +177 -0
- package/src/build/manifest.ts +224 -0
- package/src/build/plugin-host.ts +184 -0
- package/src/build/prerender.ts +93 -0
- package/src/build/report.ts +157 -0
- package/src/build/resolve.ts +58 -0
- package/src/build/routes.ts +135 -0
- package/src/build/static.ts +73 -0
- package/src/cli/check.ts +228 -114
- package/src/cli/index.ts +298 -79
- package/src/cli/new.ts +67 -35
- package/src/compiler/analyze.ts +666 -91
- package/src/compiler/dom.ts +822 -629
- package/src/compiler/mistakes.ts +354 -0
- package/src/compiler/patch.ts +1 -1
- package/src/compiler/server-only.ts +164 -21
- package/src/compiler/shared.ts +442 -0
- package/src/compiler/ssr.ts +390 -324
- package/src/context.ts +120 -0
- package/src/dev/index.ts +291 -76
- package/src/dom/action.ts +23 -13
- package/src/dom/extras.ts +157 -84
- package/src/dom/index.ts +154 -33
- package/src/dom/island.ts +117 -39
- package/src/dom/loop.ts +34 -21
- package/src/index.ts +2 -1
- package/src/jsx-runtime.ts +11 -0
- package/src/plugins/context.ts +57 -0
- package/src/plugins/index.ts +120 -17
- package/src/reactivity/index.ts +250 -157
- package/src/reactivity/selector.ts +11 -9
- package/src/reactivity/store.ts +37 -12
- package/src/server/action.ts +217 -74
- package/src/server/compress.ts +155 -56
- package/src/server/cookies.ts +59 -22
- package/src/server/env.ts +18 -13
- package/src/server/http.ts +201 -33
- package/src/server/index.ts +964 -737
- package/src/server/loader.ts +120 -0
- package/src/server/router.ts +27 -8
- package/src/server/security.ts +87 -39
- package/src/server/standard-schema.ts +42 -11
- package/src/server/static-dir.ts +144 -0
- package/src/ssr/context.ts +96 -10
- package/src/ssr/index.ts +225 -56
- package/src/style.ts +33 -0
- package/src/test/index.ts +5 -0
- package/src/unrenderable.ts +35 -0
package/src/server/compress.ts
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// Never imports `node:zlib` so server RSS stays minimal.
|
|
3
3
|
|
|
4
4
|
export type CompressionEncoding = 'zstd' | 'gzip'
|
|
5
|
+
export type PrecompressedEncoding = 'br' | 'gzip'
|
|
5
6
|
|
|
6
|
-
|
|
7
|
+
const MIN_COMPRESS_BYTES = 256
|
|
7
8
|
const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
|
|
8
9
|
const encoder = new TextEncoder()
|
|
9
10
|
|
|
@@ -31,49 +32,73 @@ export function isCompressibleType(contentType: string | null | undefined): bool
|
|
|
31
32
|
return mime.endsWith('+json') || mime.endsWith('+xml')
|
|
32
33
|
}
|
|
33
34
|
|
|
34
|
-
|
|
35
|
-
if (!acceptEncoding)
|
|
36
|
-
return undefined
|
|
35
|
+
const Q_VALUE_RE = /;\s*q\s*=\s*([0-9.]+)/i
|
|
37
36
|
|
|
38
|
-
|
|
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 {
|
|
39
39
|
if (!acceptEncoding.includes(';')) {
|
|
40
40
|
const lower = acceptEncoding.toLowerCase()
|
|
41
|
-
if (hasToken(lower,
|
|
42
|
-
return
|
|
43
|
-
|
|
44
|
-
return 'gzip'
|
|
45
|
-
return undefined
|
|
41
|
+
if (first !== undefined && hasToken(lower, first))
|
|
42
|
+
return first
|
|
43
|
+
return second !== undefined && hasToken(lower, second) ? second : undefined
|
|
46
44
|
}
|
|
47
45
|
|
|
48
|
-
let
|
|
49
|
-
let
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
const part = parts[i]!.trim()
|
|
53
|
-
if (!part)
|
|
54
|
-
continue
|
|
46
|
+
let firstQ = -1
|
|
47
|
+
let secondQ = -1
|
|
48
|
+
for (const rawPart of acceptEncoding.split(',')) {
|
|
49
|
+
const part = rawPart.trim()
|
|
55
50
|
const semi = part.indexOf(';')
|
|
56
51
|
const name = (semi === -1 ? part : part.slice(0, semi)).trim().toLowerCase()
|
|
57
|
-
if (name !==
|
|
52
|
+
if (name !== first && name !== second)
|
|
58
53
|
continue
|
|
59
54
|
let q = 1
|
|
60
55
|
if (semi !== -1) {
|
|
61
|
-
const
|
|
62
|
-
if (
|
|
63
|
-
|
|
64
|
-
if (!Number.isNaN(parsed))
|
|
65
|
-
q = parsed
|
|
66
|
-
}
|
|
56
|
+
const parsed = Number(Q_VALUE_RE.exec(part.slice(semi))?.[1])
|
|
57
|
+
if (!Number.isNaN(parsed))
|
|
58
|
+
q = parsed
|
|
67
59
|
}
|
|
68
|
-
if (name ===
|
|
69
|
-
|
|
60
|
+
if (name === first)
|
|
61
|
+
firstQ = q
|
|
70
62
|
else
|
|
71
|
-
|
|
63
|
+
secondQ = q
|
|
72
64
|
}
|
|
65
|
+
if (firstQ <= 0 && secondQ <= 0)
|
|
66
|
+
return undefined
|
|
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
|
|
72
|
+
}
|
|
73
73
|
|
|
74
|
-
|
|
74
|
+
export function pickPrecompressedEncoding(
|
|
75
|
+
acceptEncoding: string | null,
|
|
76
|
+
available: { br?: boolean, gz?: boolean },
|
|
77
|
+
): PrecompressedEncoding | undefined {
|
|
78
|
+
if (!acceptEncoding)
|
|
75
79
|
return undefined
|
|
76
|
-
return
|
|
80
|
+
return pickToken(acceptEncoding, available.br ? 'br' : undefined, available.gz ? 'gzip' : undefined)
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function toWeakEtag(etag: string): string {
|
|
84
|
+
return etag.startsWith('W/') || etag.startsWith('w/') ? etag : `W/${etag}`
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function hasNoTransform(cacheControl: string | null | undefined): boolean {
|
|
88
|
+
return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Bun exposes no way to tell a streamed body from a buffered one without reading it, so its inspect output decides. Checked once at load: if the output no longer tells them apart, every body without a length counts as streamed and goes out uncompressed.
|
|
92
|
+
const STREAM_MARK = 'ReadableStream {'
|
|
93
|
+
const inspectSeesStreams = typeof Bun !== 'undefined'
|
|
94
|
+
&& Bun.inspect(new Response(new ReadableStream())).includes(STREAM_MARK)
|
|
95
|
+
&& !Bun.inspect(new Response('')).includes(STREAM_MARK)
|
|
96
|
+
|
|
97
|
+
function isStreamingBody(res: Response): boolean {
|
|
98
|
+
const te = res.headers.get('transfer-encoding')
|
|
99
|
+
if (te && te.toLowerCase().includes('chunked'))
|
|
100
|
+
return true
|
|
101
|
+
return !inspectSeesStreams || Bun.inspect(res).includes(STREAM_MARK)
|
|
77
102
|
}
|
|
78
103
|
|
|
79
104
|
function hasToken(haystack: string, token: string): boolean {
|
|
@@ -88,21 +113,40 @@ function hasToken(haystack: string, token: string): boolean {
|
|
|
88
113
|
return false
|
|
89
114
|
}
|
|
90
115
|
|
|
91
|
-
|
|
116
|
+
function compressBuffer(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> {
|
|
92
117
|
if (encoding === 'zstd')
|
|
93
118
|
return Bun.zstdCompressSync(bytes, { level: 3 }) as Uint8Array<ArrayBuffer>
|
|
94
119
|
return Bun.gzipSync(bytes, { level: 6 }) as Uint8Array<ArrayBuffer>
|
|
95
120
|
}
|
|
96
121
|
|
|
122
|
+
// `undefined` when the input is too small to be worth compressing or does not shrink.
|
|
123
|
+
function shrink(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding): Uint8Array<ArrayBuffer> | undefined {
|
|
124
|
+
if (bytes.byteLength < MIN_COMPRESS_BYTES)
|
|
125
|
+
return undefined
|
|
126
|
+
const compressed = compressBuffer(bytes, encoding)
|
|
127
|
+
return compressed.byteLength < bytes.byteLength ? compressed : undefined
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const DEFAULT_MAX_FILE_CACHE_BYTES = 8 * 1024 * 1024
|
|
131
|
+
|
|
97
132
|
export class CompressionCache {
|
|
133
|
+
// Path-keyed build files (assets, public, prerendered pages): bounded byte-budget LRU + in-flight dedup. `null` marks a file that does not shrink.
|
|
134
|
+
readonly #files = new Map<string, Uint8Array<ArrayBuffer> | null>()
|
|
135
|
+
readonly #fileInflight = new Map<string, Promise<Uint8Array<ArrayBuffer> | undefined>>()
|
|
136
|
+
readonly #maxFileBytes: number
|
|
137
|
+
readonly #maxFileEntryBytes: number
|
|
138
|
+
#fileBytes = 0
|
|
139
|
+
// Content-hashed HTML of routes rendered per request: a byte-budget LRU.
|
|
98
140
|
readonly #map = new Map<string, Uint8Array<ArrayBuffer>>()
|
|
99
141
|
readonly #maxBytes: number
|
|
100
142
|
readonly #maxEntryBytes: number
|
|
101
143
|
#totalBytes = 0
|
|
102
144
|
|
|
103
|
-
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES) {
|
|
145
|
+
constructor(maxBytes = DEFAULT_MAX_CACHE_BYTES, maxFileBytes = DEFAULT_MAX_FILE_CACHE_BYTES) {
|
|
104
146
|
this.#maxBytes = maxBytes
|
|
105
147
|
this.#maxEntryBytes = Math.floor(maxBytes / 4)
|
|
148
|
+
this.#maxFileBytes = maxFileBytes
|
|
149
|
+
this.#maxFileEntryBytes = Math.floor(maxFileBytes / 4)
|
|
106
150
|
}
|
|
107
151
|
|
|
108
152
|
get(key: string): Uint8Array<ArrayBuffer> | undefined {
|
|
@@ -136,24 +180,66 @@ export class CompressionCache {
|
|
|
136
180
|
}
|
|
137
181
|
}
|
|
138
182
|
|
|
183
|
+
/** Compresses `bytes`, kept in the LRU under `staticKey` when given; without one nothing is stored. */
|
|
139
184
|
compress(bytes: Uint8Array<ArrayBuffer>, encoding: CompressionEncoding, staticKey?: string): Uint8Array<ArrayBuffer> | undefined {
|
|
140
|
-
|
|
141
|
-
|
|
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)
|
|
185
|
+
const cacheKey = staticKey !== undefined ? `${encoding}:${staticKey}` : undefined
|
|
186
|
+
const cached = cacheKey !== undefined ? this.get(cacheKey) : undefined
|
|
146
187
|
if (cached !== undefined)
|
|
147
188
|
return cached
|
|
148
|
-
const compressed =
|
|
149
|
-
if (compressed
|
|
150
|
-
|
|
151
|
-
this.set(cacheKey, compressed)
|
|
189
|
+
const compressed = shrink(bytes, encoding)
|
|
190
|
+
if (compressed !== undefined && cacheKey !== undefined)
|
|
191
|
+
this.set(cacheKey, compressed)
|
|
152
192
|
return compressed
|
|
153
193
|
}
|
|
194
|
+
|
|
195
|
+
/** The compressed variant of a build file, read and compressed on its first request only (deduped + bounded LRU); `undefined` when it does not shrink. */
|
|
196
|
+
async file(key: string, encoding: CompressionEncoding, read: () => Uint8Array<ArrayBuffer> | Promise<Uint8Array<ArrayBuffer>>): Promise<Uint8Array<ArrayBuffer> | undefined> {
|
|
197
|
+
const variantKey = `${encoding}:${key}`
|
|
198
|
+
if (this.#files.has(variantKey)) {
|
|
199
|
+
const hit = this.#files.get(variantKey)!
|
|
200
|
+
// Refresh LRU recency
|
|
201
|
+
this.#files.delete(variantKey)
|
|
202
|
+
this.#files.set(variantKey, hit)
|
|
203
|
+
return hit ?? undefined
|
|
204
|
+
}
|
|
205
|
+
const inflight = this.#fileInflight.get(variantKey)
|
|
206
|
+
if (inflight !== undefined)
|
|
207
|
+
return inflight
|
|
208
|
+
|
|
209
|
+
const task = (async () => {
|
|
210
|
+
const bytes = await read()
|
|
211
|
+
const variant = shrink(bytes, encoding) ?? null
|
|
212
|
+
if (variant === null) {
|
|
213
|
+
this.#files.set(variantKey, null)
|
|
214
|
+
return undefined
|
|
215
|
+
}
|
|
216
|
+
if (variant.byteLength <= this.#maxFileEntryBytes) {
|
|
217
|
+
this.#files.set(variantKey, variant)
|
|
218
|
+
this.#fileBytes += variant.byteLength
|
|
219
|
+
while (this.#fileBytes > this.#maxFileBytes) {
|
|
220
|
+
const oldest = this.#files.keys().next()
|
|
221
|
+
if (oldest.done)
|
|
222
|
+
break
|
|
223
|
+
const evicted = this.#files.get(oldest.value)
|
|
224
|
+
this.#files.delete(oldest.value)
|
|
225
|
+
if (evicted !== null && evicted !== undefined)
|
|
226
|
+
this.#fileBytes -= evicted.byteLength
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
return variant
|
|
230
|
+
})()
|
|
231
|
+
|
|
232
|
+
this.#fileInflight.set(variantKey, task)
|
|
233
|
+
try {
|
|
234
|
+
return await task
|
|
235
|
+
}
|
|
236
|
+
finally {
|
|
237
|
+
this.#fileInflight.delete(variantKey)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
154
240
|
}
|
|
155
241
|
|
|
156
|
-
|
|
242
|
+
function appendVaryAcceptEncoding(headers: Headers): void {
|
|
157
243
|
const existing = headers.get('vary')
|
|
158
244
|
if (!existing) {
|
|
159
245
|
headers.set('vary', 'Accept-Encoding')
|
|
@@ -163,33 +249,37 @@ export function appendVaryAcceptEncoding(headers: Headers): void {
|
|
|
163
249
|
}
|
|
164
250
|
}
|
|
165
251
|
|
|
252
|
+
/** `reuse` keeps the compressed page by content hash, for routes whose HTML holds nothing per visitor. */
|
|
166
253
|
export function compressedHtmlResponse(
|
|
167
254
|
html: string,
|
|
168
255
|
status: number,
|
|
169
256
|
baseHeaders: Record<string, string>,
|
|
170
257
|
request: Request,
|
|
171
258
|
cache: CompressionCache | undefined,
|
|
259
|
+
reuse = false,
|
|
172
260
|
): Response {
|
|
173
|
-
|
|
261
|
+
const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
|
|
262
|
+
if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
|
|
174
263
|
const enc = pickEncoding(request.headers.get('accept-encoding'))
|
|
175
264
|
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
|
-
|
|
180
|
-
compressed = cache.compress(bytes, enc, staticKey)
|
|
181
|
-
}
|
|
265
|
+
const staticKey = reuse ? `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}` : undefined
|
|
266
|
+
let compressed = staticKey !== undefined ? cache.get(`${enc}:${staticKey}`) : undefined
|
|
267
|
+
if (compressed === undefined)
|
|
268
|
+
compressed = cache.compress(encoder.encode(html), enc, staticKey)
|
|
182
269
|
if (compressed !== undefined) {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
270
|
+
const headers: Record<string, string> = { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' }
|
|
271
|
+
const etag = headers.etag ?? headers.ETag
|
|
272
|
+
if (etag !== undefined) {
|
|
273
|
+
delete headers.ETag
|
|
274
|
+
headers.etag = toWeakEtag(etag)
|
|
275
|
+
}
|
|
276
|
+
return new Response(compressed, { status, headers })
|
|
187
277
|
}
|
|
188
278
|
}
|
|
189
279
|
}
|
|
190
280
|
return new Response(request.method === 'HEAD' ? null : html, {
|
|
191
281
|
status,
|
|
192
|
-
headers: cache !== undefined ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
|
|
282
|
+
headers: cache !== undefined && !noTransform ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
|
|
193
283
|
})
|
|
194
284
|
}
|
|
195
285
|
|
|
@@ -200,13 +290,20 @@ export async function maybeCompressResponse(
|
|
|
200
290
|
): Promise<Response> {
|
|
201
291
|
if (cache === undefined)
|
|
202
292
|
return res
|
|
203
|
-
if (res.status === 204 || res.status === 304 || (res.status >= 300 && res.status < 400))
|
|
293
|
+
if (res.status === 204 || res.status === 206 || res.status === 304 || (res.status >= 300 && res.status < 400))
|
|
204
294
|
return res
|
|
205
295
|
if (res.headers.has('content-encoding'))
|
|
206
296
|
return res
|
|
297
|
+
if (hasNoTransform(res.headers.get('cache-control')))
|
|
298
|
+
return res
|
|
207
299
|
if (!isCompressibleType(res.headers.get('content-type')))
|
|
208
300
|
return res
|
|
209
301
|
|
|
302
|
+
const cl = res.headers.get('content-length')
|
|
303
|
+
// Never buffer streaming responses that have no Content-Length (e.g. chunked streams, ReadableStream)
|
|
304
|
+
if (cl === null && isStreamingBody(res))
|
|
305
|
+
return res
|
|
306
|
+
|
|
210
307
|
const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
|
|
211
308
|
if (enc === undefined) {
|
|
212
309
|
try {
|
|
@@ -216,7 +313,6 @@ export async function maybeCompressResponse(
|
|
|
216
313
|
return res
|
|
217
314
|
}
|
|
218
315
|
|
|
219
|
-
const cl = res.headers.get('content-length')
|
|
220
316
|
if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES) {
|
|
221
317
|
try {
|
|
222
318
|
appendVaryAcceptEncoding(res.headers)
|
|
@@ -237,5 +333,8 @@ export async function maybeCompressResponse(
|
|
|
237
333
|
|
|
238
334
|
headers.set('content-encoding', enc)
|
|
239
335
|
headers.delete('content-length')
|
|
336
|
+
const etag = headers.get('etag')
|
|
337
|
+
if (etag !== null)
|
|
338
|
+
headers.set('etag', toWeakEtag(etag))
|
|
240
339
|
return new Response(compressed, { status: res.status, statusText: res.statusText, headers })
|
|
241
340
|
}
|
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
|
|
@@ -13,11 +13,14 @@ export interface CookieOptions {
|
|
|
13
13
|
export interface Cookies {
|
|
14
14
|
get(name: string): string | undefined
|
|
15
15
|
set(name: string, value: string, options?: CookieOptions): void
|
|
16
|
-
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void
|
|
16
|
+
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void
|
|
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))
|
|
@@ -39,56 +45,87 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
|
|
|
39
45
|
return map
|
|
40
46
|
}
|
|
41
47
|
|
|
42
|
-
function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {
|
|
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
|
+
|
|
57
|
+
const secure = options.secure ?? defaultSecure
|
|
58
|
+
const sameSite = options.sameSite ?? 'lax'
|
|
59
|
+
if (sameSite === 'none' && !secure)
|
|
60
|
+
throw new Error(`kay: Cookie "${name}" with sameSite: "none" requires secure: true`)
|
|
61
|
+
|
|
43
62
|
let out = `${name}=${encodeURIComponent(value)}`
|
|
44
|
-
out += `; Path=${
|
|
63
|
+
out += `; Path=${path}`
|
|
45
64
|
if (options.domain !== undefined)
|
|
46
65
|
out += `; Domain=${options.domain}`
|
|
47
|
-
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}"`)
|
|
48
69
|
out += `; Max-Age=${Math.floor(options.maxAge)}`
|
|
70
|
+
}
|
|
49
71
|
if (options.expires !== undefined)
|
|
50
72
|
out += `; Expires=${options.expires.toUTCString()}`
|
|
51
73
|
if (options.httpOnly ?? true)
|
|
52
74
|
out += '; HttpOnly'
|
|
53
|
-
if (
|
|
75
|
+
if (secure)
|
|
54
76
|
out += '; Secure'
|
|
55
|
-
const sameSite = options.sameSite ?? 'lax'
|
|
56
77
|
out += `; SameSite=${sameSite[0]!.toUpperCase()}${sameSite.slice(1)}`
|
|
57
78
|
return out
|
|
58
79
|
}
|
|
59
80
|
|
|
81
|
+
function cookieKey(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): string {
|
|
82
|
+
return `${name}\0${options?.path ?? '/'}\0${options?.domain ?? ''}`
|
|
83
|
+
}
|
|
84
|
+
|
|
60
85
|
export class CookieStore implements Cookies {
|
|
61
|
-
|
|
62
|
-
|
|
86
|
+
#rawHeader: string | null
|
|
87
|
+
#values: Map<string, string> | undefined
|
|
88
|
+
readonly #headers = new Map<string, string>()
|
|
89
|
+
readonly #isHttps: boolean
|
|
63
90
|
|
|
64
|
-
constructor(cookieHeader: string | null) {
|
|
65
|
-
this.#
|
|
91
|
+
constructor(cookieHeader: string | null, isHttps = false) {
|
|
92
|
+
this.#rawHeader = cookieHeader
|
|
93
|
+
this.#isHttps = isHttps
|
|
94
|
+
}
|
|
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
|
|
66
102
|
}
|
|
67
103
|
|
|
68
104
|
get(name: string): string | undefined {
|
|
69
|
-
return this.#
|
|
105
|
+
return this.#ensureValues().get(name)
|
|
70
106
|
}
|
|
71
107
|
|
|
72
108
|
set(name: string, value: string, options?: CookieOptions): void {
|
|
73
|
-
|
|
74
|
-
this.#
|
|
109
|
+
const serialized = serializeCookie(name, value, options, this.#isHttps)
|
|
110
|
+
this.#ensureValues().set(name, value)
|
|
111
|
+
this.#headers.set(cookieKey(name, options), serialized)
|
|
75
112
|
}
|
|
76
113
|
|
|
77
|
-
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void {
|
|
78
|
-
this.#
|
|
79
|
-
this.#headers.
|
|
114
|
+
delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
|
|
115
|
+
this.#ensureValues().delete(name)
|
|
116
|
+
this.#headers.set(cookieKey(name, options), serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
|
|
80
117
|
}
|
|
81
118
|
|
|
82
119
|
all(): Record<string, string> {
|
|
83
|
-
return Object.fromEntries(this.#
|
|
120
|
+
return Object.fromEntries(this.#ensureValues())
|
|
84
121
|
}
|
|
85
122
|
|
|
86
123
|
get hasChanges(): boolean {
|
|
87
|
-
return this.#headers.
|
|
124
|
+
return this.#headers.size > 0
|
|
88
125
|
}
|
|
89
126
|
|
|
90
127
|
applyTo(headers: Headers): void {
|
|
91
|
-
for (
|
|
92
|
-
headers.append('set-cookie',
|
|
128
|
+
for (const serialized of this.#headers.values())
|
|
129
|
+
headers.append('set-cookie', serialized)
|
|
93
130
|
}
|
|
94
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
|
}
|