import type { ExecutionRequest } from '@graphql-tools/utils'; import { useContentEncoding as useOrigContentEncoding } from '@whatwg-node/server'; import type { FetchAPI } from 'graphql-yoga'; import type { GatewayPlugin } from '../types'; export interface UseContentEncodingOpts { subgraphs?: string[]; } function createContentEncodingPlugin>() { const origPlugin = useOrigContentEncoding(); return { ...origPlugin, onResponse( payload: Parameters>[0], ) { // Skip compression for SSE responses — CompressionStream buffers small // events and never flushes them, breaking real-time delivery. const contentType = payload.response.headers.get('content-type'); if (contentType?.includes('text/event-stream')) { return; } return origPlugin.onResponse?.(payload); }, } as GatewayPlugin; } export function useContentEncoding>({ subgraphs, }: UseContentEncodingOpts = {}): GatewayPlugin { if (!subgraphs?.length) { return createContentEncodingPlugin(); } const compressionAlgorithm: CompressionFormat = 'gzip'; let fetchAPI: FetchAPI; const execReqWithContentEncoding = new WeakSet(); return { onYogaInit({ yoga }) { fetchAPI = yoga.fetchAPI; }, onPluginInit({ addPlugin }) { // @ts-ignore - this is flakey addPlugin(createContentEncodingPlugin()); }, onSubgraphExecute({ subgraphName, executionRequest }) { if (subgraphs.includes(subgraphName) || subgraphs.includes('*')) { execReqWithContentEncoding.add(executionRequest); } }, onFetch({ executionRequest, options, setOptions }) { if ( options.body && !options.headers?.['Content-Encoding'] && executionRequest && execReqWithContentEncoding.has(executionRequest) && fetchAPI.CompressionStream ) { const compressionStream = new fetchAPI.CompressionStream( compressionAlgorithm, ); let bodyStream: ReadableStream; if (options.body instanceof fetchAPI.ReadableStream) { bodyStream = options.body; } else { // Create a fake Response and use its body to pipe through the compression stream bodyStream = new fetchAPI.Response(options.body).body!; } setOptions({ ...options, headers: { 'Accept-Encoding': 'gzip, deflate', ...options.headers, 'Content-Encoding': compressionAlgorithm, }, body: bodyStream.pipeThrough(compressionStream), }); } }, }; }