index.ts
This file
Path
src/middleware/compress/index.ts
143 lines · 5.6 KiB · TypeScript
Last changed by
Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
History of this fileTake it
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–45why, one step back1/**2 * @module3 * Compress Middleware for Hono.4 */56import type { MiddlewareHandler } from '../../types'7import { parseAccept } from '../../utils/accept'8import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'910export { COMPRESSIBLE_CONTENT_TYPE_REGEX }1112const ENCODING_TYPES = ['gzip', 'deflate'] as const13type Encoding = (typeof ENCODING_TYPES)[number]14const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i1516type ContentTypeFilter = RegExp | ((contentType: string) => boolean)1718interface CompressionOptions {19 encoding?: Encoding20 threshold?: number21 contentTypeFilter?: ContentTypeFilter22}2324const selectEncoding = (25 header: string | undefined,26 candidates: readonly Encoding[]27): Encoding | undefined => {28 if (header === undefined) {29 return undefined30 }31 const accepts = parseAccept(header)32 const wildcardQ = accepts.find((a) => a.type === '*')?.q33 let best: { encoding: Encoding; q: number } | undefined34 for (const enc of candidates) {35 const explicit = accepts.find((a) => a.type.toLowerCase() === enc)36 const q = explicit ? explicit.q : (wildcardQ ?? 0)37 if (q === 1) {38 return enc39 } else if (q > 0 && (!best || q > best.q)) {40 best = { encoding: enc, q }41 }42 }43 return best?.encoding44}45Merge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 46–47why, one step back46const varyAcceptEncodingRegExp = /(?:^|,)\s*accept-encoding\s*(?:,|$)/i47Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 48–94why, one step back48/**49 * Compress Middleware for Hono.50 *51 * @see {@link https://hono.dev/docs/middleware/builtin/compress}52 *53 * @param {CompressionOptions} [options] - The options for the compress middleware.54 * @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.55 * @param {number} [options.threshold=1024] - The minimum size in bytes to compress. Defaults to 1024 bytes.56 * @param {RegExp | Function} [options.contentTypeFilter=COMPRESSIBLE_CONTENT_TYPE_REGEX] - A RegExp or function to determine if the response Content-Type should be compressed.57 * @returns {MiddlewareHandler} The middleware handler function.58 *59 * @example60 * ```ts61 * const app = new Hono()62 *63 * app.use(compress())64 *65 * // Compress only JSON responses66 * app.use(compress({ contentTypeFilter: /^application\/json/ }))67 *68 * // Compress based on custom Content-Type logic69 * app.use(compress({ contentTypeFilter: (type) => COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type) || type === "application/x-myformat" }))70 * ```71 */72export const compress = (options?: CompressionOptions): MiddlewareHandler => {73 const threshold = options?.threshold ?? 102474 const candidates: readonly Encoding[] = options?.encoding ? [options.encoding] : ENCODING_TYPES7576 const contentTypeFilter = options?.contentTypeFilter ?? COMPRESSIBLE_CONTENT_TYPE_REGEX77 const shouldCompress =78 typeof contentTypeFilter === 'function'79 ? (res: Response) => {80 const type = res.headers.get('Content-Type')81 return type && contentTypeFilter(type)82 }83 : (res: Response) => {84 const type = res.headers.get('Content-Type')85 return type && contentTypeFilter.test(type)86 }8788 return async function compress(ctx, next) {89 await next()9091 const contentLength = ctx.res.headers.get('Content-Length')9293 // Check if response should be compressed94 if (fix(compress): do not compress 206 Partial Content responses (#5020)Rıdvan Bahçecibefore adoption67efb27
line 95why, one step back95 ctx.res.status === 206 || // partial content, Content-Range refers to the uncompressed bytesMerge commit from forkYusuke Wadabefore adoptionf0b094d
lines 96–103why, one step back96 ctx.res.headers.has('Content-Encoding') || // already encoded97 ctx.res.headers.has('Transfer-Encoding') || // already encoded or chunked98 ctx.req.method === 'HEAD' || // HEAD request99 (contentLength && Number(contentLength) < threshold) || // content-length below threshold100 !shouldCompress(ctx.res) || // not compressible type101 !shouldTransform(ctx.res) // cache-control: no-transform102 ) {103 returnMerge pull request #5154 from honojs/nextYusuke Wadabefore adoptionb0c2d90
lines 104–115why, one step back104 }105106 // From here on the representation is selected from the request's Accept-Encoding,107 // so caches must key on that header. This is done before the negotiation result is108 // known, because an identity response served for a missing or unsupported109 // Accept-Encoding is just as much a negotiated representation: RFC 9110 lists110 // Accept-Encoding "or lack thereof" as a determining factor. Without this, a shared111 // cache could reuse the identity response for a client that does accept gzip.112 // https://www.rfc-editor.org/rfc/rfc9110#field.vary113 const current = ctx.res.headers.get('Vary')114 if (current !== '*' && !(current && varyAcceptEncodingRegExp.test(current))) {115 ctx.header('Vary', current ? `${current}, Accept-Encoding` : 'Accept-Encoding')Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 116–143why, one step back116 }117118 const accepted = ctx.req.header('Accept-Encoding')119 const encoding = selectEncoding(accepted, candidates)120 if (!encoding || !ctx.res.body) {121 return122 }123124 // Compress the response125 const stream = new CompressionStream(encoding)126 ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)127 ctx.res.headers.delete('Content-Length')128 ctx.res.headers.set('Content-Encoding', encoding)129130 // Convert strong ETag to weak ETag since compressed content is not byte-identical131 const etag = ctx.res.headers.get('ETag')132 if (etag && !etag.startsWith('W/')) {133 ctx.res.headers.set('ETag', `W/${etag}`)134 }135 }136}137138const shouldTransform = (res: Response) => {139 const cacheControl = res.headers.get('Cache-Control')140 // Don't compress for Cache-Control: no-transform141 // https://tools.ietf.org/html/rfc7234#section-5.2.2.4142 return !cacheControl || !cacheControlNoTransformRegExp.test(cacheControl)143}