@kayjs/kay 2.0.0-alpha.8 → 2.0.0-beta.0

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.
@@ -36,6 +36,7 @@ interface SubNode {
36
36
  d: Link | undefined // deps head
37
37
  dt: Link | undefined // deps tail
38
38
  c: Link | undefined // cursor
39
+ po: SubNode | undefined // prevOwned
39
40
  no: SubNode | undefined // nextOwned
40
41
  nq: SubNode | undefined // nextQueued
41
42
  k: (() => void) | undefined // cleanup returned by the effect
@@ -46,6 +47,7 @@ interface SubNode {
46
47
  export interface Owner {
47
48
  p: Owner | undefined // parent
48
49
  fc: Owner | undefined // firstChild
50
+ ps: Owner | undefined // prevSibling
49
51
  ns: Owner | undefined // nextSibling
50
52
  fs: SubNode | undefined // firstSub
51
53
  cl: (() => void)[] | undefined // cleanups
@@ -125,6 +127,8 @@ function linkSub(dep: DepNode, sub: SubNode): void {
125
127
 
126
128
  function unlink(l: Link): void {
127
129
  const { d, s, pd, nd, ps, ns } = l
130
+ if (d.ls === s)
131
+ d.ls = undefined
128
132
  if (pd !== undefined)
129
133
  pd.nd = nd
130
134
  else
@@ -161,6 +165,8 @@ function unlinkAll(sub: SubNode): void {
161
165
  while (l !== undefined) {
162
166
  const next = l.nd
163
167
  const { d, ps, ns } = l
168
+ if (d.ls === sub)
169
+ d.ls = undefined
164
170
  if (ps !== undefined)
165
171
  ps.ns = ns
166
172
  else
@@ -258,6 +264,8 @@ function flush(): void {
258
264
 
259
265
  function shouldRun(sub: SubNode): boolean {
260
266
  const f = sub.f
267
+ if (f & DISPOSED)
268
+ return false
261
269
  if (f & DIRTY)
262
270
  return true
263
271
  if (!(f & CHECK))
@@ -325,6 +333,7 @@ class ComputedNode<T> implements DepNode, SubNode, ReadonlySignal<T> {
325
333
  d: Link | undefined = undefined
326
334
  dt: Link | undefined = undefined
327
335
  c: Link | undefined = undefined
336
+ po: SubNode | undefined = undefined
328
337
  no: SubNode | undefined = undefined
329
338
  nq: SubNode | undefined = undefined
330
339
  k: (() => void) | undefined = undefined
@@ -333,11 +342,26 @@ class ComputedNode<T> implements DepNode, SubNode, ReadonlySignal<T> {
333
342
  _v!: T
334
343
  _i = false
335
344
 
336
- constructor(fn: () => T) {
345
+ constructor(fn: () => T, owner: Owner | undefined) {
337
346
  this._f = fn
347
+ if (owner !== undefined) {
348
+ if (owner.x) {
349
+ this.f |= DISPOSED
350
+ }
351
+ else {
352
+ this.o = owner
353
+ const first = owner.fs
354
+ this.no = first
355
+ if (first !== undefined)
356
+ first.po = this
357
+ owner.fs = this
358
+ }
359
+ }
338
360
  }
339
361
 
340
362
  r(): void {
363
+ if (this.f & DISPOSED)
364
+ return
341
365
  if (this.f & RUNNING)
342
366
  throw new Error('kay: cyclic computed')
343
367
  const prevSub = currentSub
@@ -364,15 +388,17 @@ class ComputedNode<T> implements DepNode, SubNode, ReadonlySignal<T> {
364
388
  }
365
389
 
366
390
  get value(): T {
367
- if (shouldRun(this))
368
- this.r()
369
- if (currentSub !== undefined)
370
- linkSub(this, currentSub)
391
+ if (!(this.f & DISPOSED)) {
392
+ if (shouldRun(this))
393
+ this.r()
394
+ if (currentSub !== undefined)
395
+ linkSub(this, currentSub)
396
+ }
371
397
  return this._v
372
398
  }
373
399
 
374
400
  peek(): T {
375
- if (shouldRun(this))
401
+ if (!(this.f & DISPOSED) && shouldRun(this))
376
402
  this.r()
377
403
  return this._v
378
404
  }
@@ -385,12 +411,14 @@ class EffectNode implements SubNode, Owner {
385
411
  d: Link | undefined = undefined
386
412
  dt: Link | undefined = undefined
387
413
  c: Link | undefined = undefined
414
+ po: SubNode | undefined = undefined
388
415
  no: SubNode | undefined = undefined
389
416
  nq: SubNode | undefined = undefined
390
417
  k: (() => void) | undefined = undefined
391
418
  o: Owner | undefined
392
419
  p: Owner | undefined
393
420
  fc: Owner | undefined = undefined
421
+ ps: Owner | undefined = undefined
394
422
  ns: Owner | undefined = undefined
395
423
  fs: SubNode | undefined = undefined
396
424
  cl: (() => void)[] | undefined = undefined
@@ -401,7 +429,10 @@ class EffectNode implements SubNode, Owner {
401
429
  this._f = fn
402
430
  this.o = this.p = owner
403
431
  if (owner !== undefined) {
404
- this.no = owner.fs
432
+ const first = owner.fs
433
+ this.no = first
434
+ if (first !== undefined)
435
+ first.po = this
405
436
  owner.fs = this
406
437
  }
407
438
  }
@@ -444,27 +475,65 @@ export function createOwner(parent: Owner | undefined = currentOwner): Owner {
444
475
  const owner: Owner = {
445
476
  p: parent,
446
477
  fc: undefined,
478
+ ps: undefined,
447
479
  ns: undefined,
448
480
  fs: undefined,
449
481
  cl: undefined,
450
482
  x: false,
451
483
  }
452
484
  if (parent !== undefined) {
453
- owner.ns = parent.fc
485
+ const first = parent.fc
486
+ owner.ns = first
487
+ if (first !== undefined)
488
+ first.ps = owner
454
489
  parent.fc = owner
455
490
  }
456
491
  return owner
457
492
  }
458
493
 
494
+ function unlinkOwner(owner: Owner): void {
495
+ const parent = owner.p
496
+ if (parent === undefined)
497
+ return
498
+ const prev = owner.ps
499
+ const next = owner.ns
500
+ if (prev !== undefined)
501
+ prev.ns = next
502
+ else if (parent.fc === owner)
503
+ parent.fc = next
504
+ if (next !== undefined)
505
+ next.ps = prev
506
+ owner.p = owner.ps = owner.ns = undefined
507
+ }
508
+
509
+ function unlinkOwnedSub(sub: SubNode): void {
510
+ const owner = sub.o
511
+ if (owner === undefined)
512
+ return
513
+ const prev = sub.po
514
+ const next = sub.no
515
+ if (prev !== undefined)
516
+ prev.no = next
517
+ else if (owner.fs === sub)
518
+ owner.fs = next
519
+ if (next !== undefined)
520
+ next.po = prev
521
+ sub.o = sub.po = sub.no = undefined
522
+ }
523
+
459
524
  export function disposeOwner(owner: Owner): void {
460
525
  if (owner.x)
461
526
  return
462
527
  owner.x = true
528
+ unlinkOwner(owner)
463
529
  releaseOwned(owner)
464
530
  }
465
531
 
466
532
  function disposeSub(sub: SubNode): void {
533
+ if (sub.f & DISPOSED)
534
+ return
467
535
  sub.f |= DISPOSED
536
+ unlinkOwnedSub(sub)
468
537
  unlinkAll(sub)
469
538
  if (sub.f & EFFECT)
470
539
  disposeOwner(sub as EffectNode)
@@ -480,7 +549,7 @@ function releaseOwned(owner: Owner): void {
480
549
  owner.fc = undefined
481
550
  while (child !== undefined) {
482
551
  const next = child.ns
483
- child.ns = undefined
552
+ child.p = child.ps = child.ns = undefined
484
553
  disposeOwner(child)
485
554
  child = next
486
555
  }
@@ -489,7 +558,7 @@ function releaseOwned(owner: Owner): void {
489
558
  owner.fs = undefined
490
559
  while (sub !== undefined) {
491
560
  const next = sub.no
492
- sub.no = undefined
561
+ sub.o = sub.po = sub.no = undefined
493
562
  disposeSub(sub)
494
563
  sub = next
495
564
  }
@@ -530,7 +599,7 @@ export function signal<T>(initial: T): Signal<T> {
530
599
  }
531
600
 
532
601
  export function computed<T>(fn: () => T): ReadonlySignal<T> {
533
- return new ComputedNode(fn)
602
+ return new ComputedNode(fn, currentOwner)
534
603
  }
535
604
 
536
605
  export function effect(fn: () => void | (() => void)): () => void {
@@ -35,7 +35,7 @@ function getDep(target: object, key: PropertyKey): Signal<number> {
35
35
  function notifyKey(target: object, key: PropertyKey): void {
36
36
  const dep = depsCache.get(target)?.get(key)
37
37
  if (dep !== undefined)
38
- dep.value++
38
+ dep.value = dep.peek() + 1
39
39
  }
40
40
 
41
41
  function wrap<T extends object>(target: T): T {
@@ -2,11 +2,21 @@
2
2
 
3
3
  import type { Cookies } from './cookies'
4
4
  import type { InferInput, InferOutput, StandardSchemaIssue, StandardSchemaV1 } from './standard-schema'
5
+ import { DEFAULT_MAX_REQUEST_BODY_SIZE, enforceRequestBodyLimit } from './http'
5
6
  import { isTrustedOrigin, verifyOrigin } from './security'
6
7
  import { validateSchema } from './standard-schema'
7
8
 
8
9
  export const ACTION_ERROR_COOKIE = '__kay_action_err'
9
10
 
11
+ const MAX_FLASH_COOKIE_BYTES = 3500
12
+ const MAX_FLASH_FIELD_CHARS = 512
13
+ const SENSITIVE_FIELD_RE = /password|passwd|pwd|secret|token|pin|cvv|cvc|iban|ssn|card|credit|auth|key|otp|code|routing|account|bank|tax/i
14
+
15
+ export interface ActionOptions {
16
+ /** Explicit allowlist of form field names permitted in the progressive-form validation error flash cookie. */
17
+ flashFields?: readonly string[] | undefined
18
+ }
19
+
10
20
  export interface ActionErrorFlash {
11
21
  action: string
12
22
  error: string
@@ -24,6 +34,7 @@ export interface ActionContext {
24
34
  params: Record<string, string>
25
35
  cookies: Cookies
26
36
  locals: Record<string, unknown>
37
+ ip?: string | undefined
27
38
  redirect: (location: string, status?: 301 | 302 | 303 | 307 | 308) => Response
28
39
  deny: (status: number, message: string, fieldErrors?: Record<string, string>) => Response
29
40
  }
@@ -37,6 +48,7 @@ export interface ServerAction<Input, Output> {
37
48
  readonly __kayAction: true
38
49
  readonly url: string
39
50
  readonly schema: StandardSchemaV1 | undefined
51
+ readonly flashFields: readonly string[] | undefined
40
52
  readonly handler: (input: never, ctx: ActionContext) => Output | Response | Promise<Output | Response>
41
53
  toString(): string
42
54
  }
@@ -49,19 +61,23 @@ export function actionHash(relFile: string, exportName: string): string {
49
61
  export function action<S extends StandardSchemaV1, Output>(
50
62
  schema: S,
51
63
  handler: (input: InferOutput<S>, ctx: ActionContext) => Output | Response | Promise<Output | Response>,
64
+ options?: ActionOptions,
52
65
  ): ServerAction<InferInput<S>, Exclude<Output, Response>>
53
66
  export function action<Output>(
54
67
  handler: (ctx: ActionContext) => Output | Response | Promise<Output | Response>,
68
+ options?: ActionOptions,
55
69
  ): ServerAction<void, Exclude<Output, Response>>
56
70
  export function action(
57
71
  schemaOrHandler: StandardSchemaV1 | ((ctx: ActionContext) => unknown),
58
- maybeHandler?: (input: never, ctx: ActionContext) => unknown,
72
+ maybeHandlerOrOpts?: ((input: never, ctx: ActionContext) => unknown) | ActionOptions,
73
+ maybeOpts?: ActionOptions,
59
74
  ): ServerAction<unknown, unknown> {
60
75
  const hasSchema = typeof schemaOrHandler !== 'function'
61
76
  const schema = hasSchema ? schemaOrHandler : undefined
62
77
  const handler = hasSchema
63
- ? maybeHandler!
78
+ ? (maybeHandlerOrOpts as (input: never, ctx: ActionContext) => unknown)
64
79
  : ((_input: never, ctx: ActionContext) => (schemaOrHandler as (c: ActionContext) => unknown)(ctx))
80
+ const options = hasSchema ? maybeOpts : (maybeHandlerOrOpts as ActionOptions | undefined)
65
81
 
66
82
  const fn = (async () => {
67
83
  throw new Error('kay: server action cannot be called directly without a request context; invoke it from an island or via HTTP POST')
@@ -70,6 +86,7 @@ export function action(
70
86
  Object.defineProperties(fn, {
71
87
  __kayAction: { value: true, enumerable: false },
72
88
  schema: { value: schema, enumerable: false },
89
+ flashFields: { value: options?.flashFields, enumerable: false },
73
90
  handler: { value: handler, enumerable: false },
74
91
  url: { value: '', writable: true, enumerable: true },
75
92
  toString: {
@@ -87,13 +104,24 @@ export function isServerAction(value: unknown): value is ServerAction<unknown, u
87
104
  return typeof value === 'function' && (value as { __kayAction?: boolean }).__kayAction === true
88
105
  }
89
106
 
90
- async function parseActionBody(request: Request): Promise<unknown> {
91
- const contentType = request.headers.get('content-type') ?? ''
107
+ class PayloadTooLargeError extends Error {
108
+ constructor() {
109
+ super('Payload Too Large')
110
+ }
111
+ }
112
+
113
+ async function parseActionBody(request: Request, maxRequestBodySize: number): Promise<unknown> {
114
+ const checked = await enforceRequestBodyLimit(request, maxRequestBodySize)
115
+ if (!checked.ok)
116
+ throw new PayloadTooLargeError()
117
+ const boundedReq = checked.request
118
+
119
+ const contentType = boundedReq.headers.get('content-type') ?? ''
92
120
  if (contentType.includes('application/json'))
93
- return request.json()
121
+ return boundedReq.json()
94
122
 
95
123
  if (contentType.includes('multipart/form-data') || contentType.includes('application/x-www-form-urlencoded')) {
96
- const fd = await request.formData()
124
+ const fd = await boundedReq.formData()
97
125
  const out: Record<string, unknown> = {}
98
126
  for (const [key, val] of fd.entries()) {
99
127
  if (key in out) {
@@ -110,13 +138,67 @@ async function parseActionBody(request: Request): Promise<unknown> {
110
138
  return undefined
111
139
  }
112
140
 
141
+ function encodedFlashSize(flash: ActionErrorFlash): number {
142
+ return Buffer.byteLength(encodeURIComponent(JSON.stringify(flash)), 'utf8')
143
+ }
144
+
145
+ function buildActionErrorFlash(
146
+ actionUrl: string,
147
+ fieldErrors: Record<string, string>,
148
+ rawBody: unknown,
149
+ flashFields?: readonly string[],
150
+ ): string {
151
+ const safeErrors: Record<string, string> = {}
152
+ const base: ActionErrorFlash = {
153
+ action: actionUrl,
154
+ error: 'Validation failed',
155
+ fieldErrors: safeErrors,
156
+ }
157
+ for (const [k, msg] of Object.entries(fieldErrors)) {
158
+ const trimmed = msg.length > 256 ? msg.slice(0, 256) : msg
159
+ safeErrors[k] = trimmed
160
+ if (encodedFlashSize(base) > MAX_FLASH_COOKIE_BYTES) {
161
+ delete safeErrors[k]
162
+ break
163
+ }
164
+ }
165
+
166
+ const allowSet = flashFields !== undefined ? new Set(flashFields) : undefined
167
+ const values: Record<string, string> = {}
168
+ if (rawBody !== null && typeof rawBody === 'object') {
169
+ for (const [k, v] of Object.entries(rawBody as Record<string, unknown>)) {
170
+ if (typeof v !== 'string' || v.length > MAX_FLASH_FIELD_CHARS)
171
+ continue
172
+ if (allowSet !== undefined) {
173
+ if (!allowSet.has(k))
174
+ continue
175
+ }
176
+ else if (SENSITIVE_FIELD_RE.test(k)) {
177
+ continue
178
+ }
179
+ values[k] = v
180
+ const candidate: ActionErrorFlash = { ...base, values }
181
+ if (encodedFlashSize(candidate) > MAX_FLASH_COOKIE_BYTES)
182
+ delete values[k]
183
+ }
184
+ }
185
+
186
+ const finalFlash: ActionErrorFlash = {
187
+ ...base,
188
+ ...(Object.keys(values).length > 0 ? { values } : {}),
189
+ }
190
+ return JSON.stringify(finalFlash)
191
+ }
192
+
113
193
  export async function executeAction(
114
194
  act: ServerAction<unknown, unknown>,
115
195
  request: Request,
116
196
  ctx: ActionContext,
117
197
  trustedOrigins?: ReadonlySet<string>,
198
+ trustProxy = false,
199
+ maxRequestBodySize = DEFAULT_MAX_REQUEST_BODY_SIZE,
118
200
  ): Promise<Response> {
119
- const originCheck = verifyOrigin(request, trustedOrigins)
201
+ const originCheck = verifyOrigin(request, trustedOrigins, trustProxy)
120
202
  if (!originCheck.ok) {
121
203
  return Response.json(
122
204
  { ok: false, status: 403, error: originCheck.reason },
@@ -131,15 +213,17 @@ export async function executeAction(
131
213
  if (act.schema !== undefined) {
132
214
  let rawBody: unknown
133
215
  try {
134
- rawBody = await parseActionBody(request)
216
+ rawBody = await parseActionBody(request, maxRequestBodySize)
135
217
  }
136
- catch {
218
+ catch (err) {
219
+ if (err instanceof PayloadTooLargeError)
220
+ return Response.json({ ok: false, status: 413, error: 'Payload Too Large' }, { status: 413 })
137
221
  return Response.json({ ok: false, status: 400, error: 'Invalid request body' }, { status: 400 })
138
222
  }
139
223
 
140
224
  const checked = await validateSchema(act.schema, rawBody)
141
225
  if (!checked.ok) {
142
- // Zero-JS progressive HTML <form> submit: flash fieldErrors + submitted string values and redirect 303 back to trusted Referer
226
+ // Zero-JS progressive HTML <form> submit: flash fieldErrors + safe submitted values (<4KB) and redirect 303 back to trusted Referer
143
227
  if (!wantsJson) {
144
228
  const referer = request.headers.get('referer')
145
229
  if (referer) {
@@ -150,21 +234,9 @@ export async function executeAction(
150
234
  catch {
151
235
  refUrl = undefined
152
236
  }
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), {
237
+ if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy)) {
238
+ const serializedFlash = buildActionErrorFlash(act.url, checked.fieldErrors, rawBody, act.flashFields)
239
+ ctx.cookies.set(ACTION_ERROR_COOKIE, serializedFlash, {
168
240
  httpOnly: true,
169
241
  sameSite: 'lax',
170
242
  maxAge: 60,
@@ -195,7 +267,7 @@ export async function executeAction(
195
267
  catch {
196
268
  refUrl = undefined
197
269
  }
198
- if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins))
270
+ if (refUrl !== undefined && isTrustedOrigin(refUrl.origin, request, trustedOrigins, trustProxy))
199
271
  return Response.redirect(refUrl.href, 303)
200
272
  }
201
273
  }
@@ -2,6 +2,7 @@
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
  export const MIN_COMPRESS_BYTES = 256
7
8
  const DEFAULT_MAX_CACHE_BYTES = 2 * 1024 * 1024
@@ -76,6 +77,73 @@ export function pickEncoding(acceptEncoding: string | null): CompressionEncoding
76
77
  return zstdQ >= gzipQ ? 'zstd' : 'gzip'
77
78
  }
78
79
 
80
+ export function pickPrecompressedEncoding(
81
+ acceptEncoding: string | null,
82
+ available: { br?: boolean, gz?: boolean },
83
+ ): PrecompressedEncoding | undefined {
84
+ if (!acceptEncoding || (!available.br && !available.gz))
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)
125
+ return undefined
126
+ return effBr >= effGz ? 'br' : 'gzip'
127
+ }
128
+
129
+ export function toWeakEtag(etag: string): string {
130
+ return etag.startsWith('W/') || etag.startsWith('w/') ? etag : `W/${etag}`
131
+ }
132
+
133
+ function hasNoTransform(cacheControl: string | null | undefined): boolean {
134
+ return Boolean(cacheControl && /\bno-transform\b/i.test(cacheControl))
135
+ }
136
+
137
+ function isStreamingBody(res: Response): boolean {
138
+ // Check transfer-encoding or Bun's unmaterialized ReadableStream representation BEFORE touching `res.body`.
139
+ const te = res.headers.get('transfer-encoding')
140
+ if (te && te.toLowerCase().includes('chunked'))
141
+ return true
142
+ if (typeof Bun !== 'undefined')
143
+ return Bun.inspect(res).includes('ReadableStream {')
144
+ return true
145
+ }
146
+
79
147
  function hasToken(haystack: string, token: string): boolean {
80
148
  let idx = haystack.indexOf(token)
81
149
  while (idx !== -1) {
@@ -170,7 +238,8 @@ export function compressedHtmlResponse(
170
238
  request: Request,
171
239
  cache: CompressionCache | undefined,
172
240
  ): Response {
173
- if (cache !== undefined && request.method !== 'HEAD') {
241
+ const noTransform = hasNoTransform(baseHeaders['cache-control'] ?? baseHeaders['Cache-Control'])
242
+ if (cache !== undefined && !noTransform && request.method !== 'HEAD') {
174
243
  const enc = pickEncoding(request.headers.get('accept-encoding'))
175
244
  if (enc !== undefined && html.length >= MIN_COMPRESS_BYTES) {
176
245
  const staticKey = `s:${Bun.hash.wyhash(html).toString(36)}:${html.length}`
@@ -180,16 +249,17 @@ export function compressedHtmlResponse(
180
249
  compressed = cache.compress(bytes, enc, staticKey)
181
250
  }
182
251
  if (compressed !== undefined) {
183
- return new Response(compressed, {
184
- status,
185
- headers: { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' },
186
- })
252
+ const headers: Record<string, string> = { ...baseHeaders, 'content-encoding': enc, 'vary': 'Accept-Encoding' }
253
+ const etag = headers.etag ?? headers.ETag
254
+ if (etag !== undefined)
255
+ headers.etag = toWeakEtag(etag)
256
+ return new Response(compressed, { status, headers })
187
257
  }
188
258
  }
189
259
  }
190
260
  return new Response(request.method === 'HEAD' ? null : html, {
191
261
  status,
192
- headers: cache !== undefined ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
262
+ headers: cache !== undefined && !noTransform ? { ...baseHeaders, vary: 'Accept-Encoding' } : baseHeaders,
193
263
  })
194
264
  }
195
265
 
@@ -200,13 +270,20 @@ export async function maybeCompressResponse(
200
270
  ): Promise<Response> {
201
271
  if (cache === undefined)
202
272
  return res
203
- if (res.status === 204 || res.status === 304 || (res.status >= 300 && res.status < 400))
273
+ if (res.status === 204 || res.status === 206 || res.status === 304 || (res.status >= 300 && res.status < 400))
204
274
  return res
205
275
  if (res.headers.has('content-encoding'))
206
276
  return res
277
+ if (hasNoTransform(res.headers.get('cache-control')))
278
+ return res
207
279
  if (!isCompressibleType(res.headers.get('content-type')))
208
280
  return res
209
281
 
282
+ 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
+
210
287
  const enc = request.method === 'HEAD' ? undefined : pickEncoding(request.headers.get('accept-encoding'))
211
288
  if (enc === undefined) {
212
289
  try {
@@ -216,7 +293,6 @@ export async function maybeCompressResponse(
216
293
  return res
217
294
  }
218
295
 
219
- const cl = res.headers.get('content-length')
220
296
  if (cl !== null && Number(cl) < MIN_COMPRESS_BYTES) {
221
297
  try {
222
298
  appendVaryAcceptEncoding(res.headers)
@@ -237,5 +313,8 @@ export async function maybeCompressResponse(
237
313
 
238
314
  headers.set('content-encoding', enc)
239
315
  headers.delete('content-length')
316
+ const etag = headers.get('etag')
317
+ if (etag !== null)
318
+ headers.set('etag', toWeakEtag(etag))
240
319
  return new Response(compressed, { status: res.status, statusText: res.statusText, headers })
241
320
  }
@@ -13,7 +13,7 @@ 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
 
@@ -39,7 +39,12 @@ export function parseCookieHeader(header: string | null): Map<string, string> {
39
39
  return map
40
40
  }
41
41
 
42
- function serializeCookie(name: string, value: string, options: CookieOptions = {}): string {
42
+ function serializeCookie(name: string, value: string, options: CookieOptions = {}, defaultSecure = false): string {
43
+ const secure = options.secure ?? defaultSecure
44
+ const sameSite = options.sameSite ?? 'lax'
45
+ if (sameSite === 'none' && !secure)
46
+ throw new Error(`kay: Cookie "${name}" with sameSite: "none" requires secure: true`)
47
+
43
48
  let out = `${name}=${encodeURIComponent(value)}`
44
49
  out += `; Path=${options.path ?? '/'}`
45
50
  if (options.domain !== undefined)
@@ -50,9 +55,8 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
50
55
  out += `; Expires=${options.expires.toUTCString()}`
51
56
  if (options.httpOnly ?? true)
52
57
  out += '; HttpOnly'
53
- if (options.secure)
58
+ if (secure)
54
59
  out += '; Secure'
55
- const sameSite = options.sameSite ?? 'lax'
56
60
  out += `; SameSite=${sameSite[0]!.toUpperCase()}${sameSite.slice(1)}`
57
61
  return out
58
62
  }
@@ -60,9 +64,11 @@ function serializeCookie(name: string, value: string, options: CookieOptions = {
60
64
  export class CookieStore implements Cookies {
61
65
  readonly #values: Map<string, string>
62
66
  readonly #headers: string[] = []
67
+ readonly #isHttps: boolean
63
68
 
64
- constructor(cookieHeader: string | null) {
69
+ constructor(cookieHeader: string | null, isHttps = false) {
65
70
  this.#values = parseCookieHeader(cookieHeader)
71
+ this.#isHttps = isHttps
66
72
  }
67
73
 
68
74
  get(name: string): string | undefined {
@@ -70,13 +76,14 @@ export class CookieStore implements Cookies {
70
76
  }
71
77
 
72
78
  set(name: string, value: string, options?: CookieOptions): void {
79
+ const serialized = serializeCookie(name, value, options, this.#isHttps)
73
80
  this.#values.set(name, value)
74
- this.#headers.push(serializeCookie(name, value, options))
81
+ this.#headers.push(serialized)
75
82
  }
76
83
 
77
- delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain'>): void {
84
+ delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'secure'>): void {
78
85
  this.#values.delete(name)
79
- this.#headers.push(serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }))
86
+ this.#headers.push(serializeCookie(name, '', { ...options, maxAge: 0, expires: new Date(0) }, this.#isHttps))
80
87
  }
81
88
 
82
89
  all(): Record<string, string> {