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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144/** * @module * Compress Middleware for Hono. */
import type { MiddlewareHandler } from '../../types'import { parseAccept } from '../../utils/accept'import { COMPRESSIBLE_CONTENT_TYPE_REGEX } from '../../utils/compress'
export { COMPRESSIBLE_CONTENT_TYPE_REGEX }
const ENCODING_TYPES = ['gzip', 'deflate'] as consttype Encoding = (typeof ENCODING_TYPES)[number]const cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/i
type ContentTypeFilter = RegExp | ((contentType: string) => boolean)
interface CompressionOptions { encoding?: Encoding threshold?: number contentTypeFilter?: ContentTypeFilter}
const selectEncoding = ( header: string | undefined, candidates: readonly Encoding[]): Encoding | undefined => { if (header === undefined) { return undefined } const accepts = parseAccept(header) const wildcardQ = accepts.find((a) => a.type === '*')?.q let best: { encoding: Encoding; q: number } | undefined for (const enc of candidates) { const explicit = accepts.find((a) => a.type.toLowerCase() === enc) const q = explicit ? explicit.q : (wildcardQ ?? 0) if (q === 1) { return enc } else if (q > 0 && (!best || q > best.q)) { best = { encoding: enc, q } } } return best?.encoding}
const varyAcceptEncodingRegExp = /(?:^|,)\s*accept-encoding\s*(?:,|$)/i
/** * 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. * @param {RegExp | Function} [options.contentTypeFilter=COMPRESSIBLE_CONTENT_TYPE_REGEX] - A RegExp or function to determine if the response Content-Type should be compressed. * @returns {MiddlewareHandler} The middleware handler function. * * @example * ```ts * const app = new Hono() * * app.use(compress()) * * // Compress only JSON responses * app.use(compress({ contentTypeFilter: /^application\/json/ })) * * // Compress based on custom Content-Type logic * app.use(compress({ contentTypeFilter: (type) => COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type) || type === "application/x-myformat" })) * ``` */export const compress = (options?: CompressionOptions): MiddlewareHandler => { const threshold = options?.threshold ?? 1024 const candidates: readonly Encoding[] = options?.encoding ? [options.encoding] : ENCODING_TYPES
const contentTypeFilter = options?.contentTypeFilter ?? COMPRESSIBLE_CONTENT_TYPE_REGEX const shouldCompress = typeof contentTypeFilter === 'function' ? (res: Response) => { const type = res.headers.get('Content-Type') return type && contentTypeFilter(type) } : (res: Response) => { const type = res.headers.get('Content-Type') return type && contentTypeFilter.test(type) }
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.status === 206 || // partial content, Content-Range refers to the uncompressed bytes ctx.res.headers.has('Content-Encoding') || // already encoded ctx.res.headers.has('Transfer-Encoding') || // already encoded or chunked 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 }
// From here on the representation is selected from the request's Accept-Encoding, // so caches must key on that header. This is done before the negotiation result is // known, because an identity response served for a missing or unsupported // Accept-Encoding is just as much a negotiated representation: RFC 9110 lists // Accept-Encoding "or lack thereof" as a determining factor. Without this, a shared // cache could reuse the identity response for a client that does accept gzip. // https://www.rfc-editor.org/rfc/rfc9110#field.vary const current = ctx.res.headers.get('Vary') if (current !== '*' && !(current && varyAcceptEncodingRegExp.test(current))) { ctx.header('Vary', current ? `${current}, Accept-Encoding` : 'Accept-Encoding') }
const accepted = ctx.req.header('Accept-Encoding') const encoding = selectEncoding(accepted, candidates) 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)
// Convert strong ETag to weak ETag since compressed content is not byte-identical const etag = ctx.res.headers.get('ETag') if (etag && !etag.startsWith('W/')) { ctx.res.headers.set('ETag', `W/${etag}`) } }}
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)}