Skip to content

Commit

Permalink
Enable compression on responses
Browse files Browse the repository at this point in the history
  • Loading branch information
stramel committed Jun 3, 2020
1 parent 3ffb036 commit a2e4eb5
Showing 1 changed file with 36 additions and 4 deletions.
40 changes: 36 additions & 4 deletions src/commands/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import cacache from 'cacache';
import chalk from 'chalk';
import chokidar from 'chokidar';
import detectPort from 'detect-port';
import etag from 'etag';
import {EventEmitter} from 'events';
import execa from 'execa';
Expand All @@ -37,9 +38,10 @@ import mime from 'mime-types';
import npmRunPath from 'npm-run-path';
import os from 'os';
import path from 'path';
import url from 'url';
import onProcessExit from 'signal-exit';
import detectPort from 'detect-port';
import stream from 'stream'
import url from 'url';
import zlib from 'zlib';
import {BuildScript, SnowpackPluginBuildResult} from '../config';
import {EsmHmrEngine} from '../hmr-server-engine';
import {scanCodeImportsExports, transformEsmImports} from '../rewrite-imports';
Expand Down Expand Up @@ -101,19 +103,49 @@ const sendFile = (
ext = '.html',
) => {
const ETag = etag(body);
const headers = {
const headers: Record<string, string> = {
'Content-Type': mime.contentType(ext) || 'application/octet-stream',
'Access-Control-Allow-Origin': '*',
ETag,
Vary: 'Accept-Encoding'
};

if (req.headers['if-none-match'] === ETag) {
res.writeHead(304, headers);
res.end()
return
}

let acceptEncoding = (req.headers['accept-encoding'] as string) || ''
if (req.headers["cache-control"]?.includes('no-transform') || ['HEAD', 'OPTIONS'].includes(req.method!)) {
acceptEncoding = ''
}

function onError(err) {
if (err) {
res.end()
console.error('An error occurred:', err)
}
}

const raw = stream.Readable.from([body])
if (/\bgzip\b/.test(acceptEncoding)) {
headers['Content-Encoding'] = 'gzip'
res.writeHead(200, headers)
stream.pipeline(raw, zlib.createGzip(), res, onError)
} else if (/\bbr\b/.test(acceptEncoding)) {
headers['Content-Encoding'] = 'br'
res.writeHead(200, headers)
stream.pipeline(raw, zlib.createBrotliCompress(), res, onError);
} else if (/\bdeflate\b/.test(acceptEncoding)) {
headers['Content-Encoding'] = 'deflate'
res.writeHead(200, headers);
stream.pipeline(raw, zlib.createDeflate(), res, onError);
} else {
res.writeHead(200, headers);
res.write(body, getEncodingType(ext));
res.end()
}
res.end();
};

const sendError = (res, status) => {
Expand Down

0 comments on commit a2e4eb5

Please sign in to comment.