-
-
Notifications
You must be signed in to change notification settings - Fork 547
/
index.ts
78 lines (67 loc) · 2.73 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/**
* @module
* Compress Middleware for Hono.
*/
import type { MiddlewareHandler } from '../../types'
import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'
const ENCODING_TYPES = ['gzip', 'deflate'] as const
const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i
interface CompressionOptions {
encoding?: (typeof ENCODING_TYPES)[number]
threshold?: number
}
/**
* Compress Middleware for Hono.
*
* @see {@link https://hono.dev/docs/middleware/builtin/compress}
*
* @param {CompressionOptions} [options] - The options for the compress middleware.
* @param {'gzip' | 'deflate'} [options.encoding] - The compression scheme to allow for response compression. Either 'gzip' or 'deflate'. If not defined, both are allowed and will be used based on the Accept-Encoding header. 'gzip' is prioritized if this option is not provided and the client provides both in the Accept-Encoding header.
* @param {number} [options.threshold=1024] - The minimum size in bytes to compress. Defaults to 1024 bytes.
* @returns {MiddlewareHandler} The middleware handler function.
*
* @example
* ```ts
* const app = new Hono()
*
* app.use(compress())
* ```
*/
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
const threshold = options?.threshold ?? 1024
return async function compress(ctx, next) {
await next()
const contentLength = ctx.res.headers.get('Content-Length')
// Check if response should be compressed
if (
ctx.res.headers.has('Content-Encoding') || // already encoded
ctx.req.method === 'HEAD' || // HEAD request
(contentLength && Number(contentLength) < threshold) || // content-length below threshold
!shouldCompress(ctx.res) || // not compressible type
!shouldTransform(ctx.res) // cache-control: no-transform
) {
return
}
const accepted = ctx.req.header('Accept-Encoding')
const encoding =
options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))
if (!encoding || !ctx.res.body) {
return
}
// Compress the response
const stream = new CompressionStream(encoding)
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
ctx.res.headers.delete('Content-Length')
ctx.res.headers.set('Content-Encoding', encoding)
}
}
const shouldCompress = (res: Response) => {
const type = res.headers.get('Content-Type')
return type && COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type)
}
const shouldTransform = (res: Response) => {
const cacheControl = res.headers.get('Cache-Control')
// Don't compress for Cache-Control: no-transform
// https://tools.ietf.org/html/rfc7234#section-5.2.2.4
return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl)
}