diff --git a/README.md b/README.md index e7b0079..424ae72 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,27 @@ createServer(toNodeHandler(app)).listen(process.env.PORT || 3000) You can also force a specific method (e.g. `compression('gzip')`) instead of detecting it from the `Accept-Encoding` header. +## Content negotiation + +The encoding is picked from the `Accept-Encoding` header as described in +[RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#section-12.5.3): + +- Quality values decide first: `gzip;q=0.1, deflate;q=0.9` picks deflate, and an encoding sent + with `q=0` is never used (`br;q=0, gzip` picks gzip, `gzip;q=0` compresses nothing). +- Among equally weighted encodings the server preference applies — zstd (opt-in), brotli, gzip, + deflate. +- `*` stands for every encoding not listed explicitly, and `x-gzip` counts as gzip. +- Without an `Accept-Encoding` header nothing is compressed. + +Every response whose encoding was negotiated gets `Vary: Accept-Encoding` — compressed or not — +so shared caches and CDNs never serve a compressed body to a client that didn't ask for it. +Existing `Vary` values are kept. A method forced on the middleware ignores `Accept-Encoding`, so +it doesn't add `Vary`; the forced composables (`useGZipCompression`, …) still only compress when +the client accepts that encoding. + +Responses that already carry a `Content-Encoding` (e.g. pre-compressed public assets) and +empty bodies are passed through untouched. + ## Brotli and stream compression The native [`CompressionStream`](https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream) @@ -245,6 +266,7 @@ H3-compression has a concept of composable utilities that accept `event` (from ` - `useBrotliCompression(event, response)` - `useZstdCompression(event, response)`  – requires Node >= 22.15 - `useCompression(event, response, options?)`  – pass `{ zstd: true }` to include zstd +- `compress(event, response, method?, options?)`  – low-level helper; negotiates when `method` is omitted #### Stream Compression @@ -253,6 +275,7 @@ H3-compression has a concept of composable utilities that accept `event` (from ` - `useBrotliCompressionStream(event, response)` - `useZstdCompressionStream(event, response)`  – requires Node >= 22.15 - `useCompressionStream(event, response, options?)`  – pass `{ brotli: true }` / `{ zstd: true }` +- `compressStream(event, response, method?, options?)`  – low-level helper; negotiates when `method` is omitted #### Middleware (h3 v2) diff --git a/src/compression.ts b/src/compression.ts index 099aafc..e54f9d4 100644 --- a/src/compression.ts +++ b/src/compression.ts @@ -1,6 +1,6 @@ import type { H3Event } from 'h3' import type { CompressionOptions, RenderResponse } from './helper' -import { compress, getAnyCompression } from './helper' +import { compress } from './helper' /** * Compresses the response with [zlib.gzip]{@link https://www.w3schools.com/nodejs/ref_zlib.asp} @@ -57,7 +57,8 @@ export async function useZstdCompression( /** * Compresses the response with [Zlib]{@link https://www.w3schools.com/nodejs/ref_zlib.asp} - * by 'Accept-Encoding' header. Best is used first. + * by 'Accept-Encoding' header. The client's quality values decide; among + * equally weighted codings the best is used first. Sets `Vary: Accept-Encoding`. * * Zstd is only picked when enabled via `options.zstd` and supported by the runtime. * @param { H3Event } event - A H3 event object. @@ -70,7 +71,5 @@ export async function useCompression( response: Partial, options: CompressionOptions = {}, ): Promise { - const compression = getAnyCompression(event, options) - if (compression) - await compress(event, response, compression, options) + await compress(event, response, undefined, options) } diff --git a/src/compressionStream.ts b/src/compressionStream.ts index 7a5f4bb..8c61b31 100644 --- a/src/compressionStream.ts +++ b/src/compressionStream.ts @@ -1,6 +1,6 @@ import type { H3Event } from 'h3' import type { RenderResponse, StreamCompressionOptions } from './helper' -import { compressStream, getStreamCompression } from './helper' +import { compressStream } from './helper' /** * Compresses the response with @@ -60,7 +60,8 @@ export async function useZstdCompressionStream( /** * Compresses the response with * [CompressionStream]{@link https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream} - * by 'Accept-Encoding' header. Best is used first. + * by 'Accept-Encoding' header. The client's quality values decide; among + * equally weighted codings the best is used first. Sets `Vary: Accept-Encoding`. * * Zstd and brotli are only picked when enabled via `options`. * @param event - A H3 event object. @@ -72,8 +73,5 @@ export async function useCompressionStream( response: Partial, options: StreamCompressionOptions = {}, ) { - const compression = getStreamCompression(event, options) - - if (compression) - await compressStream(event, response, compression) + await compressStream(event, response, undefined, options) } diff --git a/src/helper.ts b/src/helper.ts index c44c5f4..e71355d 100644 --- a/src/helper.ts +++ b/src/helper.ts @@ -87,11 +87,115 @@ const toResponse = h3Export<(val: unknown, event: H3Event) => Response | Promise // Only added in h3 1.8 — older v1 releases inside the peer range lack it. const removeResponseHeader = h3Export<(event: H3Event, name: string) => void>('removeResponseHeader') +/** + * RFC 9110 asks recipients to treat these legacy names as their modern + * equivalent (section 8.4.1.3). + */ +const CODING_ALIASES: Record = { 'x-gzip': 'gzip' } + +/** + * Parses a quality value. A malformed one makes the coding unacceptable rather + * than silently promoting it to `q=1`. + */ +function parseQuality(value: string): number { + const quality = Number(value.trim()) + return Number.isFinite(quality) ? Math.min(Math.max(quality, 0), 1) : 0 +} + +/** + * Parses an `Accept-Encoding` header into its content-codings and quality + * values ([RFC 9110, section 12.5.3](https://www.rfc-editor.org/rfc/rfc9110#section-12.5.3)). + * Codings are lowercased; a coding without `q` has quality 1. + * @param { string } header - The raw header value. + * @returns { Map } + */ +function parseAcceptEncoding(header: string): Map { + const accepted = new Map() + + for (const entry of header.split(',')) { + const [name, ...params] = entry.split(';') + const coding = name.trim().toLowerCase() + if (!coding) + continue + + let quality = 1 + for (const param of params) { + const [key, value = ''] = param.split('=') + if (key.trim().toLowerCase() === 'q') { + quality = parseQuality(value) + break + } + } + + const normalized = CODING_ALIASES[coding] ?? coding + accepted.set(normalized, Math.max(quality, accepted.get(normalized) ?? 0)) + } + + return accepted +} + +/** + * Reads and parses the request's `Accept-Encoding` header. A missing header + * yields `undefined`: the client did not ask for any coding, so nothing is + * compressed. + */ +function getAcceptedEncodings(event: H3Event): Map | undefined { + const header = getRequestHeader(event, 'accept-encoding') as string | string[] | undefined + if (!header) + return undefined + + return parseAcceptEncoding(Array.isArray(header) ? header.join(',') : header) +} + +/** + * The quality the client assigned to a coding: its own entry if listed, + * otherwise the `*` wildcard (which covers every coding not listed), otherwise + * 0 — not acceptable. + */ +function qualityOf(accepted: Map, coding: string): number { + return accepted.get(coding) ?? accepted.get('*') ?? 0 +} + +/** + * Whether the client accepts `method` with a quality above 0. + * @param { H3Event } event - A H3 event object. + * @param { string } method - The content-coding to check. + * @returns { boolean } + */ +function acceptsEncoding(event: H3Event, method: string): boolean { + const accepted = getAcceptedEncodings(event) + return !!accepted && qualityOf(accepted, method) > 0 +} + +/** + * Picks the coding with the highest client quality from `candidates`, which + * are listed in server preference order — that order breaks ties. Codings + * with quality 0 are never picked. + */ +function negotiate(event: H3Event, candidates: T[]): T | undefined { + const accepted = getAcceptedEncodings(event) + if (!accepted) + return undefined + + let best: T | undefined + let bestQuality = 0 + for (const candidate of candidates) { + const quality = qualityOf(accepted, candidate) + if (quality > bestQuality) { + best = candidate + bestQuality = quality + } + } + + return best +} + /** * Returns the best compression accepted by the client via the - * `Accept-Encoding` header. Zstd is preferred when enabled via - * `options.zstd` and supported by the runtime, then brotli, then gzip, - * then deflate. + * `Accept-Encoding` header. The client's quality values decide first + * (`q=0` rejects a coding); among equally weighted codings zstd is preferred + * when enabled via `options.zstd` and supported by the runtime, then brotli, + * then gzip, then deflate. * @param { H3Event } event - A H3 event object. * @param { CompressionOptions } [options] - Opt into zstd detection. * @returns { Compression | undefined } @@ -100,26 +204,18 @@ export function getAnyCompression( event: H3Event, options: CompressionOptions = {}, ): Compression | undefined { - const encoding = getRequestHeader(event, 'accept-encoding') - if (options.zstd && isZstdSupported() && encoding?.includes('zstd')) - return 'zstd' - - if (encoding?.includes('br')) - return 'br' + const candidates: Compression[] = ['br', 'gzip', 'deflate'] + if (options.zstd && isZstdSupported()) + candidates.unshift('zstd') - if (encoding?.includes('gzip')) - return 'gzip' - - if (encoding?.includes('deflate')) - return 'deflate' - - return undefined + return negotiate(event, candidates) } /** - * Returns the best stream compression accepted by the client. Zstd and brotli - * are only considered when enabled via `options`, otherwise gzip is preferred, - * then deflate. + * Returns the best stream compression accepted by the client. The client's + * quality values decide first (`q=0` rejects a coding). Zstd and brotli are + * only considered when enabled via `options`; among equally weighted codings + * zstd is preferred, then brotli, then gzip, then deflate. * @param { H3Event } event - A H3 event object. * @param { StreamCompressionOptions } [options] - Opt into zstd / brotli detection. * @returns { StreamCompression | undefined } @@ -128,20 +224,13 @@ export function getStreamCompression( event: H3Event, options: StreamCompressionOptions = {}, ): StreamCompression | undefined { - const encoding = getRequestHeader(event, 'accept-encoding') - if (options.zstd && isZstdSupported() && encoding?.includes('zstd')) - return 'zstd' - - if (options.brotli && encoding?.includes('br')) - return 'br' - - if (encoding?.includes('gzip')) - return 'gzip' + const candidates: StreamCompression[] = ['gzip', 'deflate'] + if (options.brotli) + candidates.unshift('br') + if (options.zstd && isZstdSupported()) + candidates.unshift('zstd') - if (encoding?.includes('deflate')) - return 'deflate' - - return undefined + return negotiate(event, candidates) } /** @@ -196,32 +285,46 @@ function isReadableStream(value: unknown): boolean { && typeof (value as ReadableStream).getReader === 'function' } +/** + * Whether a hook response body carries no bytes at all. Empty bodies are never + * compressed — the encoding framing would only add bytes, and a + * `Content-Encoding` on a 204 / 304 is wrong. + */ +function isEmptyBody(body: unknown): boolean { + if (body === null || body === undefined || body === '') + return true + + if (body instanceof Uint8Array || body instanceof ArrayBuffer) + return body.byteLength === 0 + + return false +} + /** * Turns a response body into a buffer that can be compressed. Strings, buffers * and typed arrays are used as-is; plain JSON-serializable values (e.g. objects - * returned from a `/server/api` route) are serialized to JSON. Returns - * `undefined` for bodies that can't / shouldn't be buffered (streams, empty). + * returned from a `/server/api` route) are serialized to JSON and flagged so + * the caller can set the content type. Returns `undefined` for bodies that + * can't / shouldn't be buffered (streams, empty). */ -function toCompressibleBuffer(event: H3Event, body: unknown): Buffer | undefined { +function toCompressibleBuffer(body: unknown): { payload: Buffer; json: boolean } | undefined { + if (isEmptyBody(body) || isReadableStream(body)) + return undefined + if (typeof body === 'string') - return Buffer.from(body) + return { payload: Buffer.from(body), json: false } if (body instanceof Uint8Array) - return Buffer.from(body) + return { payload: Buffer.from(body), json: false } if (body instanceof ArrayBuffer) - return Buffer.from(body) - - if (body === null || body === undefined || isReadableStream(body)) - return undefined + return { payload: Buffer.from(body), json: false } try { const json = JSON.stringify(body) if (json === undefined) return undefined - // Mirror h3, which serializes objects as JSON. - setResponseHeader(event, 'Content-Type', 'application/json') - return Buffer.from(json) + return { payload: Buffer.from(json), json: true } } catch { return undefined @@ -276,6 +379,15 @@ function removeHeader(event: H3Event, response: Partial, name: s (event as unknown as { node?: { res?: { removeHeader?: (name: string) => void } } }).node?.res?.removeHeader?.(name) } +/** + * Whether a `Content-Encoding` value means the body is already encoded. + * `identity` (or nothing) means it is not. + */ +function isEncodedValue(encoding: string | null | undefined): boolean { + const value = encoding?.trim().toLowerCase() + return !!value && value !== 'identity' +} + /** * Whether the response body is already content-encoded, e.g. a pre-compressed * `.br` / `.gz` asset served by Nitro's static handler with @@ -286,8 +398,45 @@ function removeHeader(event: H3Event, response: Partial, name: s * @returns { boolean } */ function isEncoded(event: H3Event, response: Partial): boolean { - const encoding = getHeader(event, response, 'content-encoding')?.trim().toLowerCase() - return !!encoding && encoding !== 'identity' + return isEncodedValue(getHeader(event, response, 'content-encoding')) +} + +/** + * Adds `Accept-Encoding` to a `Vary` header value, keeping the values already + * there. Returned unchanged if it is already listed or the value is `*`. + * @param { string | null | undefined } vary - The current `Vary` value. + * @returns { string } + */ +function mergeVary(vary: string | null | undefined): string { + const values = (vary ?? '').split(',').map(value => value.trim()).filter(Boolean) + if (values.some(value => value === '*' || value.toLowerCase() === 'accept-encoding')) + return vary as string + + return [...values, 'Accept-Encoding'].join(', ') +} + +/** + * Marks the response as depending on `Accept-Encoding`, so shared caches and + * CDNs don't serve a body compressed for one client to a client that never + * asked for that encoding (RFC 9110, section 12.5.5). Applied whether or not + * this particular response ends up compressed — another `Accept-Encoding` + * would have changed the outcome either way. + * + * A `Vary` in the `render:response` header record is updated in place, because + * Nitro applies that record after the hook and would overwrite the event's. + * @param { H3Event } event - A H3 event object. + * @param { Partial } response - The response object handed over by the hook. + */ +function varyOnAcceptEncoding(event: H3Event, response: Partial): void { + const headers = response.headers + const key = headers && typeof headers === 'object' ? findHeaderKey(headers, 'vary') : undefined + if (headers && key !== undefined) { + headers[key] = mergeVary(headers[key] == null ? undefined : String(headers[key])) + return + } + + const current = getResponseHeader(event, 'vary') + setResponseHeader(event, 'Vary', mergeVary(current == null ? undefined : String(current))) } /** @@ -304,25 +453,49 @@ function setEncoding(event: H3Event, response: Partial, method: setResponseHeader(event, 'Content-Encoding', method) } +/** + * Compresses a buffered response body in place — the building block of + * {@link useCompression} and the Nuxt module, for hooks that hand over a + * mutable response (h3 v1 `onBeforeResponse`, Nitro `render:response` / + * `beforeResponse`). + * + * Nothing happens for empty, streamed or already-encoded bodies, nor below + * `options.minSize`. Otherwise `Vary: Accept-Encoding` is set, and the body is + * compressed if the client accepts the coding. + * @param { H3Event } event - A H3 event object. + * @param { Partial } response - A response object with body parameter. + * @param { Compression } [method] - The coding to apply, if the client accepts it. Negotiated from `Accept-Encoding` when omitted. + * @param { CompressionOptions } [options] - Opt into zstd detection, set a minimum size. + * @returns { Promise } + */ export async function compress( event: H3Event, response: Partial, - method: Compression, + method?: Compression, options: CompressionOptions = {}, -) { - const acceptsEncoding = getRequestHeader(event, 'accept-encoding')?.includes( - method, - ) - if (!acceptsEncoding || isEncoded(event, response)) +): Promise { + if (isEncoded(event, response)) return - const payload = toCompressibleBuffer(event, response.body) - if (!payload || payload.byteLength < (options.minSize ?? 0)) + const serialized = toCompressibleBuffer(response.body) + if (!serialized || serialized.payload.byteLength < (options.minSize ?? 0)) return - const compression = createCompressor(method) - setEncoding(event, response, method) - const compressed = await compression(payload) + varyOnAcceptEncoding(event, response) + + const encoding = method + ? (acceptsEncoding(event, method) ? method : undefined) + : getAnyCompression(event, options) + if (!encoding) + return + + // Mirror h3, which serializes objects as JSON. + if (serialized.json) + setResponseHeader(event, 'Content-Type', 'application/json') + + const compression = createCompressor(encoding) + setEncoding(event, response, encoding) + const compressed = await compression(serialized.payload) // h3 v1 streams the body via `send`, h3 v2 expects the (mutated) body. if (typeof send === 'function') send(event, compressed) @@ -330,22 +503,39 @@ export async function compress( response.body = compressed } -export async function compressStream(event: H3Event, response: Partial, method: StreamCompression) { - if (isEncoded(event, response)) +/** + * Compresses a response body in place by piping it through a compression + * stream — the building block of {@link useCompressionStream}. + * + * Nothing happens for empty or already-encoded bodies. Otherwise + * `Vary: Accept-Encoding` is set, and the body is compressed if the client + * accepts the coding. + * @param { H3Event } event - A H3 event object. + * @param { Partial } response - A response object with body parameter. + * @param { StreamCompression } [method] - The coding to apply, if the client accepts it. Negotiated from `Accept-Encoding` when omitted. + * @param { StreamCompressionOptions } [options] - Opt into zstd / brotli detection. + * @returns { Promise } + */ +export async function compressStream( + event: H3Event, + response: Partial, + method?: StreamCompression, + options: StreamCompressionOptions = {}, +): Promise { + if (isEmptyBody(response.body) || isEncoded(event, response)) return - const stream = new Response(response.body as string).body as ReadableStream - const acceptsEncoding = getRequestHeader(event, 'accept-encoding')?.includes( - method, - ) + varyOnAcceptEncoding(event, response) - if (acceptsEncoding) { - setEncoding(event, response, method) - response.body = stream.pipeThrough(createCompressionTransform(method)) - } - else { - response.body = stream - } + const encoding = method + ? (acceptsEncoding(event, method) ? method : undefined) + : getStreamCompression(event, options) + if (!encoding) + return + + const stream = new Response(response.body as string).body as ReadableStream + setEncoding(event, response, encoding) + response.body = stream.pipeThrough(createCompressionTransform(encoding)) } function ensureToResponse(): NonNullable { @@ -361,21 +551,31 @@ function ensureToResponse(): NonNullable { /** * Rebuilds a `Response` around a new body. Reading `response.arrayBuffer()` * consumes the original, so even the "not compressed after all" paths have to - * go through here rather than returning the drained original. + * go through here rather than returning the drained original. Headers of a + * `fetch()` response are immutable, so they are never changed in place. * @param { Response } response - The response to copy status and headers from. - * @param { BodyInit } body - The replacement body. - * @param { string } [method] - Content-Encoding to set; omitted for a plain passthrough. + * @param { BodyInit | null } body - The replacement body. + * @param { object } [options] - What to change on the copy. + * @param { string } [options.encoding] - Content-Encoding to set; omitted for a plain passthrough. + * @param { boolean } [options.vary] - Add `Accept-Encoding` to `Vary`. * @returns { Response } */ -function cloneResponse(response: Response, body: BodyInit, method?: string): Response { +function cloneResponse( + response: Response, + body: BodyInit | null, + options: { encoding?: string; vary?: boolean } = {}, +): Response { const headers = new Headers(response.headers) - if (method) { - headers.set('Content-Encoding', method) + if (options.encoding) { + headers.set('Content-Encoding', options.encoding) // The length changes after compression, let the runtime recompute it. headers.delete('Content-Length') } + if (options.vary) + headers.set('Vary', mergeVary(headers.get('Vary'))) + return new Response(body, { status: response.status, statusText: response.statusText, @@ -383,9 +583,21 @@ function cloneResponse(response: Response, body: BodyInit, method?: string): Res }) } +/** + * Whether a `Response` has nothing to compress: no body at all (204, 304, + * HEAD) or one announced as empty — h3 v2 turns a `null` / `undefined` handler + * result into a 200 with an empty body and `Content-Length: 0`. + */ +function isBodyless(response: Response): boolean { + return !response.body || response.headers.get('Content-Length') === '0' +} + /** * Compresses an h3 v2 response value with [Zlib]{@link https://nodejs.org/api/zlib.html}. * Used by the {@link compression} middleware. + * + * A negotiated response gets `Vary: Accept-Encoding`, compressed or not. A + * forced `method` is applied regardless of `Accept-Encoding`, so it does not. * @param { H3Event } event - A H3 event object. * @param { unknown } value - The value returned by the next handler. * @param { Compression } [method] - Force a specific compression method. @@ -399,24 +611,30 @@ export async function compressResponse( options?: CompressionOptions, ): Promise { const response = await ensureToResponse()(value, event) - const compressionMethod = method ?? getAnyCompression(event, options) - - if (!compressionMethod || response.headers.has('Content-Encoding')) + if (isBodyless(response) || isEncodedValue(response.headers.get('Content-Encoding'))) return response + const negotiated = method === undefined + const compressionMethod = method ?? getAnyCompression(event, options) + if (!compressionMethod) + return cloneResponse(response, response.body, { vary: true }) + const body = new Uint8Array(await response.arrayBuffer()) if (body.byteLength === 0 || body.byteLength < (options?.minSize ?? 0)) return cloneResponse(response, body) const compression = createCompressor(compressionMethod) - return cloneResponse(response, await compression(body), compressionMethod) + return cloneResponse(response, await compression(body), { encoding: compressionMethod, vary: negotiated }) } /** * Compresses an h3 v2 response value with * [CompressionStream]{@link https://developer.mozilla.org/en-US/docs/Web/API/CompressionStream}. * Used by the {@link compressionStream} middleware. + * + * A negotiated response gets `Vary: Accept-Encoding`, compressed or not. A + * forced `method` is applied regardless of `Accept-Encoding`, so it does not. * @param { H3Event } event - A H3 event object. * @param { unknown } value - The value returned by the next handler. * @param { StreamCompression } [method] - Force a specific compression method. @@ -430,10 +648,17 @@ export async function compressResponseStream( options?: StreamCompressionOptions, ): Promise { const response = await ensureToResponse()(value, event) - const compressionMethod = method ?? getStreamCompression(event, options) - - if (!compressionMethod || !response.body || response.headers.has('Content-Encoding')) + if (isBodyless(response) || isEncodedValue(response.headers.get('Content-Encoding'))) return response - return cloneResponse(response, response.body.pipeThrough(createCompressionTransform(compressionMethod)), compressionMethod) + const negotiated = method === undefined + const compressionMethod = method ?? getStreamCompression(event, options) + if (!compressionMethod) + return cloneResponse(response, response.body, { vary: true }) + + return cloneResponse( + response, + response.body!.pipeThrough(createCompressionTransform(compressionMethod)), + { encoding: compressionMethod, vary: negotiated }, + ) } diff --git a/src/runtime/nitro-plugin.ts b/src/runtime/nitro-plugin.ts index 23da78c..2316625 100644 --- a/src/runtime/nitro-plugin.ts +++ b/src/runtime/nitro-plugin.ts @@ -4,7 +4,7 @@ import type { H3Event } from 'h3' // standalone module under `dist/runtime/`, where a relative path out of the // directory would not resolve against the bundled `dist/index.mjs`. import type { Compression, RenderResponse, StreamCompression } from 'h3-compression' -import { compress, compressStream, getAnyCompression, getStreamCompression } from 'h3-compression' +import { compress, compressStream } from 'h3-compression' import type { NuxtCompressionOptions } from './types' /** @@ -130,20 +130,17 @@ export async function applyCompression( return if (options.encoding === 'stream') { - const method = (options.method as StreamCompression | undefined) - ?? getStreamCompression(event, { brotli: options.brotli, zstd: options.zstd }) - - if (method) - await compressStream(event, response, method) - + await compressStream(event, response, options.method as StreamCompression | undefined, { + brotli: options.brotli, + zstd: options.zstd, + }) return } - const method = (options.method as Compression | undefined) - ?? getAnyCompression(event, { zstd: options.zstd }) - - if (method) - await compress(event, response, method, { minSize: options.threshold }) + await compress(event, response, options.method as Compression | undefined, { + zstd: options.zstd, + minSize: options.threshold, + }) } /** diff --git a/test/negotiation.test.ts b/test/negotiation.test.ts new file mode 100644 index 0000000..a3a33ea --- /dev/null +++ b/test/negotiation.test.ts @@ -0,0 +1,302 @@ +import { Buffer } from 'node:buffer' +import zlib from 'node:zlib' +import supertest from 'supertest' +import { describe, expect, it } from 'vitest' +import * as h3 from 'h3' +import { + compress, + compressStream, + compression, + compressionStream, + getAnyCompression, + getStreamCompression, + isZstdSupported, + useCompression, + useCompressionStream, + useGZipCompression, +} from '../src' +import { applyCompression } from '../src/runtime/nitro-plugin' +import { isV1, isV2 } from './_version' + +// Regression tests for #25: `Accept-Encoding` was matched by substring, so +// quality values (including `q=0`) were ignored, and `Vary: Accept-Encoding` +// was never set. + +const { createApp, eventHandler, mockEvent, toNodeListener, H3 } = h3 as typeof import('h3') + +const hasZstd = isZstdSupported() +const html = `

${'Hello world! '.repeat(100)}

` + +function eventFor(encoding?: string) { + return mockEvent('/', { headers: encoding === undefined ? {} : { 'accept-encoding': encoding } }) +} + +describe.runIf(isV2)('Accept-Encoding negotiation (#25)', () => { + it.each([ + ['br;q=0, gzip', 'gzip'], + ['gzip;q=0', undefined], + ['gzip;q=0.1, deflate;q=0.9', 'deflate'], + ['gzip, deflate, br', 'br'], + ['gzip;q=1.0, br;q=0.5', 'gzip'], + ['BR, GZIP', 'br'], + [' gzip ; q=0.5 , deflate ; q=0.4 ', 'gzip'], + ['*', 'br'], + ['*;q=0.5, gzip', 'gzip'], + ['br;q=0, *', 'gzip'], + ['*;q=0, deflate', 'deflate'], + ['x-gzip', 'gzip'], + ['gzip;q=abc, deflate', 'deflate'], + ['gzip;q=', undefined], + ['deflate-raw', undefined], + ['identity', undefined], + ['', undefined], + ])('getAnyCompression(%j) -> %s', (header, expected) => { + expect(getAnyCompression(eventFor(header))).toEqual(expected) + }) + + it('does not compress without an Accept-Encoding header', () => { + expect(getAnyCompression(eventFor())).toBeUndefined() + expect(getStreamCompression(eventFor())).toBeUndefined() + }) + + it.each([ + ['br, gzip', {}, 'gzip'], + ['br;q=1, gzip;q=0.5', {}, 'gzip'], + ['br;q=1, gzip;q=0.5', { brotli: true }, 'br'], + ['br;q=0.5, gzip', { brotli: true }, 'gzip'], + ['gzip;q=0, deflate;q=0.2', {}, 'deflate'], + ['gzip;q=0', {}, undefined], + ] as const)('getStreamCompression(%j, %j) -> %s', (header, options, expected) => { + expect(getStreamCompression(eventFor(header), options)).toEqual(expected) + }) + + it.runIf(hasZstd)('honours quality values for zstd', () => { + expect(getAnyCompression(eventFor('zstd;q=0, br'), { zstd: true })).toEqual('br') + expect(getAnyCompression(eventFor('zstd;q=0.5, gzip'), { zstd: true })).toEqual('gzip') + expect(getAnyCompression(eventFor('zstd, br'), { zstd: true })).toEqual('zstd') + expect(getStreamCompression(eventFor('zstd;q=0, gzip'), { zstd: true })).toEqual('gzip') + }) +}) + +describe.runIf(isV2)('Vary: Accept-Encoding on the hook path (#25)', () => { + it('is set on a compressed response', async () => { + const event = eventFor('gzip') + const response = { body: html } + + await useCompression(event, response) + + expect(event.res.headers.get('content-encoding')).toEqual('gzip') + expect(event.res.headers.get('vary')).toEqual('Accept-Encoding') + }) + + it('is set when nothing acceptable was offered', async () => { + const event = eventFor('gzip;q=0') + const response = { body: html } + + await useCompression(event, response) + + expect(event.res.headers.get('content-encoding')).toBeNull() + expect(event.res.headers.get('vary')).toEqual('Accept-Encoding') + expect(response.body).toEqual(html) + }) + + it('keeps existing values and does not duplicate itself', async () => { + const event = eventFor('gzip') + event.res.headers.set('vary', 'Origin') + const response = { body: html } + + await useCompression(event, response) + await useCompression(event, response) + + expect(event.res.headers.get('vary')).toEqual('Origin, Accept-Encoding') + }) + + it('leaves `Vary: *` and an existing accept-encoding entry alone', async () => { + const star = eventFor('gzip') + star.res.headers.set('vary', '*') + await useCompression(star, { body: html }) + expect(star.res.headers.get('vary')).toEqual('*') + + const listed = eventFor('gzip') + listed.res.headers.set('vary', 'origin, accept-encoding') + await useCompression(listed, { body: html }) + expect(listed.res.headers.get('vary')).toEqual('origin, accept-encoding') + }) + + it('updates a Vary in the render:response header record', async () => { + const event = eventFor('gzip') + const response = { body: html, headers: { 'Vary': 'Cookie', 'Content-Type': 'text/html' } } + + await useCompression(event, response) + + expect(response.headers.Vary).toEqual('Cookie, Accept-Encoding') + }) + + it('is not set for responses that are never compressed', async () => { + const encoded = eventFor('gzip') + encoded.res.headers.set('content-encoding', 'br') + await useCompression(encoded, { body: html }) + expect(encoded.res.headers.get('vary')).toBeNull() + + const empty = eventFor('gzip') + await useCompression(empty, { body: '' }) + expect(empty.res.headers.get('vary')).toBeNull() + expect(empty.res.headers.get('content-encoding')).toBeNull() + + const small = eventFor('gzip') + await compress(small, { body: html }, undefined, { minSize: 1_000_000 }) + expect(small.res.headers.get('vary')).toBeNull() + }) + + it('is set by a forced method the client rejects', async () => { + const event = eventFor('gzip;q=0, deflate') + const response = { body: html } + + await useGZipCompression(event, response) + + expect(event.res.headers.get('content-encoding')).toBeNull() + expect(event.res.headers.get('vary')).toEqual('Accept-Encoding') + expect(response.body).toEqual(html) + }) + + it('is set on the stream path, compressed or not', async () => { + const compressed = eventFor('br;q=0, gzip') + const response: { body: unknown } = { body: html } + await useCompressionStream(compressed, response, { brotli: true }) + expect(compressed.res.headers.get('content-encoding')).toEqual('gzip') + expect(compressed.res.headers.get('vary')).toEqual('Accept-Encoding') + + const rejected = eventFor('gzip;q=0') + const untouched = { body: html } + await compressStream(rejected, untouched, 'gzip') + expect(rejected.res.headers.get('content-encoding')).toBeNull() + expect(rejected.res.headers.get('vary')).toEqual('Accept-Encoding') + expect(untouched.body).toEqual(html) + }) + + it('skips empty bodies on the stream path', async () => { + const event = eventFor('gzip') + const response = { body: undefined } + + await useCompressionStream(event, response) + + expect(response.body).toBeUndefined() + expect(event.res.headers.get('content-encoding')).toBeNull() + expect(event.res.headers.get('vary')).toBeNull() + }) + + it('applies to the nuxt plugin', async () => { + const event = eventFor('br;q=0, gzip') + const response = { body: html, headers: { 'content-type': 'text/html' } } + + await applyCompression(event, response, {}) + + expect(event.res.headers.get('content-encoding')).toEqual('gzip') + expect(event.res.headers.get('vary')).toEqual('Accept-Encoding') + expect(zlib.gunzipSync(response.body as unknown as Buffer).toString()).toEqual(html) + }) +}) + +describe.runIf(isV2)('negotiation on the h3 v2 middleware (#25)', () => { + function appWith(middleware: ReturnType, vary?: string) { + const app = new H3() + app.use(middleware) + app.get('/', (event) => { + if (vary) + event.res.headers.set('vary', vary) + return html + }) + app.get('/empty', () => null) + app.get('/no-content', () => new Response(null, { status: 204 })) + return app + } + + async function get(app: InstanceType, encoding: string, path = '/') { + return app.fetch(new Request(`http://localhost${path}`, { headers: { 'accept-encoding': encoding } })) + } + + // The reproduction from the issue. + it.each([ + ['compression()', () => compression(), 'br;q=0, gzip', 'gzip'], + ['compression()', () => compression(), 'gzip;q=0', null], + ['compression()', () => compression(), 'gzip;q=0.1, deflate;q=0.9', 'deflate'], + ['compressionStream()', () => compressionStream(), 'br;q=0, gzip', 'gzip'], + ['compressionStream()', () => compressionStream(), 'gzip;q=0', null], + ['compressionStream()', () => compressionStream(), 'gzip;q=0.1, deflate;q=0.9', 'deflate'], + ] as const)('%s with %j -> %s', async (_name, middleware, encoding, expected) => { + const res = await get(appWith(middleware()), encoding) + + expect(res.headers.get('content-encoding')).toEqual(expected) + expect(res.headers.get('vary')).toEqual('Accept-Encoding') + + const body = Buffer.from(await res.arrayBuffer()) + const decoded = expected === 'gzip' + ? zlib.gunzipSync(body) + : expected === 'deflate' ? zlib.inflateSync(body) : body + expect(decoded.toString()).toEqual(html) + }) + + it('keeps a Vary set by the handler', async () => { + for (const middleware of [compression(), compressionStream()]) { + const res = await get(appWith(middleware, 'Origin'), 'gzip') + + expect(res.headers.get('vary')).toEqual('Origin, Accept-Encoding') + } + }) + + it('does not add Vary for a forced method, which ignores Accept-Encoding', async () => { + const res = await get(appWith(compression('gzip')), 'deflate') + + expect(res.headers.get('content-encoding')).toEqual('gzip') + expect(res.headers.get('vary')).toBeNull() + }) + + it('passes bodyless responses through', async () => { + for (const middleware of [compression(), compressionStream()]) { + for (const path of ['/empty', '/no-content']) { + const res = await get(appWith(middleware), 'gzip', path) + + expect(res.headers.get('content-encoding')).toBeNull() + expect(res.headers.get('vary')).toBeNull() + expect((await res.arrayBuffer()).byteLength).toEqual(0) + } + } + }) +}) + +describe.runIf(isV1)('negotiation on the h3 v1 app hook (#25)', () => { + function appWith(hook: (event: any, response: any) => unknown) { + const app = createApp({ onBeforeResponse: hook }) + app.use('/', eventHandler(() => html)) + return supertest(toNodeListener(app)) + } + + for (const [name, hook] of [ + ['useCompression', useCompression], + ['useCompressionStream', (event: any, response: any) => useCompressionStream(event, response, { brotli: true })], + ['nuxt plugin', (event: any, response: any) => applyCompression(event, response, {})], + ] as const) { + it(`${name} skips an encoding rejected with q=0`, async () => { + const result = await appWith(hook).get('/').set('Accept-Encoding', 'br;q=0, gzip') + + expect(result.headers['content-encoding']).toEqual('gzip') + expect(result.headers.vary).toEqual('Accept-Encoding') + expect(result.text).toEqual(html) + }) + + it(`${name} does not compress when every encoding is rejected`, async () => { + const result = await appWith(hook).get('/').set('Accept-Encoding', 'gzip;q=0, br;q=0') + + expect(result.headers['content-encoding']).toBeUndefined() + expect(result.headers.vary).toEqual('Accept-Encoding') + expect(result.text).toEqual(html) + }) + } + + it('picks the highest quality value', async () => { + const result = await appWith(useCompression).get('/').set('Accept-Encoding', 'gzip;q=0.1, deflate;q=0.9') + + expect(result.headers['content-encoding']).toEqual('deflate') + expect(result.text).toEqual(html) + }) +})