Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
77e8ffd
feat: add brotli to supported compression 🗜️
bricss May 19, 2024
3b168b5
chore: address comments 📝
bricss May 19, 2024
0d8cdd4
chore: address comments 📝
bricss May 26, 2024
a302743
feat: add br & zstd to supported compression 🗜️ algos
bricss Jul 26, 2025
f3cb451
fix: cure ⚕️ ci
bricss Jul 26, 2025
16d3e98
feat: adjust default priority 🎛️
bricss Jul 27, 2025
36db0b6
feat: make built-in `br` & `zstd` algos opt-in and disabled by default
bricss Jul 29, 2025
a5ba404
chore: brush up 💄
bricss Jul 29, 2025
b26b41a
feat: add support for compression 🗜 options 🎛️
bricss Aug 2, 2025
ec58da7
fix: fixate 🪛 types
bricss Aug 2, 2025
b5f50e6
fix: fixate 🪛 types, take 2 🎬
bricss Aug 2, 2025
3a64184
chore: clean up 🧽
bricss Aug 2, 2025
0f05108
feat: address comments 📝
bricss Aug 3, 2025
6792069
feat: reverse ↩️ engine 🚂 version
bricss Aug 3, 2025
7888aad
feat: reverse ↩️ ci min node version 🔢
bricss Aug 3, 2025
9a4336d
feat: betterment 💈
bricss Aug 3, 2025
31c1b4b
feat: address comments 📝
bricss Aug 3, 2025
08bf768
fix: cure 🩹 code coverage
bricss Aug 4, 2025
22fac0d
refactor: refinement ⚗️
bricss Sep 14, 2025
2163c18
fix: adjust 🪛 default params
bricss Sep 14, 2025
df96b0f
feat: betterment 💈
bricss Sep 14, 2025
d5e7fa8
feat: betterment 💈 take 2 🎬
bricss Sep 14, 2025
af8b50b
refactor: refinement ⚗️ take 2 🎬
bricss Sep 15, 2025
498ba9f
feat: add opt to disable decompression ⛔
bricss Sep 15, 2025
f5607aa
feat: improve tests 🧪
bricss Sep 15, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,35 @@ assigned one or more (array):

#### <a name="server.options.compression" /> `server.options.compression`

Default value: `{ minBytes: 1024 }`.
Default value: `{ decompress: true, encodings: { gzip: true, deflate: true, br: false, zstd: false }, minBytes: 1024 }`.

Defines server handling of content encoding requests. If `false`, response content encoding is
disabled and no compression is performed by the server.
disabled, and no compression is performed by the server.

#### <a name="server.options.compression.decompress" /> `server.options.compression.decompress`

Default value: `true`.

Controls whether the server automatically decompresses incoming content encoding requests.
If `false`, no decompression automatically performed by the server.

#### <a name="server.options.compression.encodings" /> `server.options.compression.encodings`

Default value: `{ gzip: true, deflate: true, br: false, zstd: false }`.

Configures the built-in support of compression algorithms aka encodings, represented by the object of kv pairs.

Available values for each kv pair:

- `true` - enables the encoding with default options.
- `false` - disables the encoding.

Note that default encoder and decoder options can be configured at the server default [route configuration](#server.options.routes)

Zstd compression is experimental (see [node Zstd documentation](https://nodejs.org/api/zlib.html#zlibcreatezstdcompressoptions)).

Disabling an encoding allows custom compression algorithm to be applied by
[`server.encoder()`](#server.encoder()) and [`server.decoder()`](#server.decoder()).

##### <a name="server.options.compression.minBytes" /> `server.options.compression.minBytes`

Expand All @@ -110,6 +135,13 @@ Default value: '1024'.
Sets the minimum response payload size in bytes that is required for content encoding compression.
If the payload size is under the limit, no compression is performed.

##### <a name="server.options.compression.priority" /> `server.options.compression.priority`

Default value: `null`.

Sets the priority for content encoding compression algorithms in descending order,
e.g.: `['zstd', 'br', 'gzip', 'deflate']`.

#### <a name="server.options.debug" /> `server.options.debug`

Default value: `{ request: ['implementation'] }`.
Expand Down Expand Up @@ -1290,8 +1322,7 @@ are called, where:

### <a name="server.decoder()" /> `server.decoder(encoding, decoder)`

Registers a custom content decoding compressor to extend the built-in support for `'gzip'` and
'`deflate`' where:
Registers a custom content decoding compressor to extend the built-in support where:

- `encoding` - the decoder name string.

Expand Down Expand Up @@ -1487,8 +1518,7 @@ The `dependencies` configuration accepts one of:

### <a name="server.encoder()" /> `server.encoder(encoding, encoder)`

Registers a custom content encoding compressor to extend the built-in support for `'gzip'` and
'`deflate`' where:
Registers a custom content encoding compressor to extend the built-in support where:

- `encoding` - the encoder name string.

Expand Down
88 changes: 74 additions & 14 deletions lib/compression.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,87 @@ const Zlib = require('zlib');
const Accept = require('@hapi/accept');
const Bounce = require('@hapi/bounce');
const Hoek = require('@hapi/hoek');
const Boom = require('@hapi/boom');

const defaultBrotliOptions = {
params: {
[Zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
};

const defaultZstdOptions = {
params: {
[Zlib.constants.ZSTD_c_compressionLevel]: 6
}
};

const internals = {
common: ['gzip, deflate', 'deflate, gzip', 'gzip', 'deflate', 'gzip, deflate, br']
common: [
'gzip, deflate, br, zstd',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It makes sense to update the common encoding with 'gzip, deflate, br, zstd', as this is used by both Chrome and Firefox. This can go in a separate PR.

'gzip, deflate, br',
'zstd',
'br',
'gzip, deflate',
'deflate, gzip',
'gzip',
'deflate'
],
provision: new Map([
['zstd', [
(options = {}) => Zlib.createZstdCompress(Hoek.applyToDefaults(defaultZstdOptions, options)),
(options) => Zlib.createZstdDecompress(options)
]],
['br', [
(options = {}) => Zlib.createBrotliCompress(Hoek.applyToDefaults(defaultBrotliOptions, options)),
(options) => Zlib.createBrotliDecompress(options)
]],
['deflate', [
(options) => Zlib.createDeflate(options),
(options) => Zlib.createInflate(options)
]],
['gzip', [
(options) => Zlib.createGzip(options),
(options) => Zlib.createGunzip(options)
]]
])
};


exports = module.exports = internals.Compression = class {

decoders = {
gzip: (options) => Zlib.createGunzip(options),
deflate: (options) => Zlib.createInflate(options)
};
decoders = {};

encodings = ['identity', 'gzip', 'deflate'];
encodings = ['identity'];

encoders = {
identity: null,
gzip: (options) => Zlib.createGzip(options),
deflate: (options) => Zlib.createDeflate(options)
identity: null
};

#common = null;
#options = null;

constructor() {
constructor(options) {

this._updateCommons();
this.#options = options;
if (!this.#options) {
return this._updateCommons();
}

for (const [encoding, [encoder, decoder]] of internals.provision.entries()) {
const conditions = this.#options?.encodings?.[encoding];
if (conditions) {
this.addEncoder(encoding, encoder);
if (this.#options.decompress !== false) {
this.addDecoder(encoding, decoder);
}
else {
this.addDecoder(encoding, () => {

throw Boom.unsupportedMediaType();
});
}
}
}
}

_updateCommons() {
Expand Down Expand Up @@ -89,13 +143,13 @@ exports = module.exports = internals.Compression = class {
return null;
}

const request = response.request;
if (!request._core.settings.compression ||
length !== null && length < request._core.settings.compression.minBytes) {
if (!this.#options ||
length !== null && length < this.#options.minBytes) {

return null;
}

const request = response.request;
const mime = request._core.mime.type(response.headers['content-type'] || 'application/octet-stream');
if (!mime.compressible) {
return null;
Expand All @@ -116,4 +170,10 @@ exports = module.exports = internals.Compression = class {
Hoek.assert(encoder !== undefined, `Unknown encoding ${encoding}`);
return encoder(request.route.settings.compression[encoding]);
}

setPriority(priority) {

this.encodings = [...new Set([...priority, ...this.encodings])];
this._updateCommons();
}
};
10 changes: 9 additions & 1 deletion lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,15 @@ internals.server = Validate.object({
autoListen: Validate.boolean(),
cache: Validate.allow(null), // Validated elsewhere
compression: Validate.object({
minBytes: Validate.number().min(1).integer().default(1024)
decompress: Validate.boolean().default(true),
encodings: Validate.object({
gzip: Validate.boolean().default(true),
deflate: Validate.boolean().default(true),
br: Validate.boolean().default(false),
zstd: Validate.boolean().default(false)
}).default(),
minBytes: Validate.number().min(1).integer().default(1024),
priority: Validate.array().items(Validate.string().valid('gzip', 'deflate', 'br', 'zstd')).default(null)
})
.allow(false)
.default(),
Expand Down
7 changes: 6 additions & 1 deletion lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ exports = module.exports = internals.Core = class {
app = {};
auth = new Auth(this);
caches = new Map(); // Cache clients
compression = new Compression();
compression = null;
controlled = null; // Other servers linked to the phases of this server
dependencies = []; // Plugin dependencies
events = new Podium.Podium(internals.events);
Expand Down Expand Up @@ -119,6 +119,7 @@ exports = module.exports = internals.Core = class {
this.settings = settings;
this.type = type;

this.compression = new Compression(this.settings.compression);
this.heavy = new Heavy(this.settings.load);
this.mime = new Mimos(this.settings.mime);
this.router = new Call.Router(this.settings.router);
Expand All @@ -127,6 +128,10 @@ exports = module.exports = internals.Core = class {
this._debug();
this._initializeCache();

if (this.settings.compression.priority) {
this.compression.setPriority(this.settings.compression.priority);
}

if (this.settings.routes.validate.validator) {
this.validator = Validation.validator(this.settings.routes.validate.validator);
}
Expand Down
6 changes: 5 additions & 1 deletion lib/types/server/encoders.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createDeflate, createGunzip, createGzip, createInflate } from 'zlib';
import { createBrotliCompress, createBrotliDecompress, createDeflate, createGunzip, createGzip, createInflate, createZstdCompress, createZstdDecompress } from 'zlib';

/**
* Available [content encoders](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder).
Expand All @@ -7,6 +7,8 @@ export interface ContentEncoders {

deflate: typeof createDeflate;
gzip: typeof createGzip;
br: typeof createBrotliCompress;
zstd: typeof createZstdCompress;
}

/**
Expand All @@ -16,4 +18,6 @@ export interface ContentDecoders {

deflate: typeof createInflate;
gzip: typeof createGunzip;
br: typeof createBrotliDecompress;
zstd: typeof createZstdDecompress;
}
8 changes: 8 additions & 0 deletions lib/types/server/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ import { CacheProvider, ServerOptionsCache } from './cache';
import { SameSitePolicy, ServerStateCookieOptions } from './state';

export interface ServerOptionsCompression {
decompress?: boolean;
encodings?: {
gzip?: boolean;
deflate?: boolean;
br?: boolean;
zstd?: boolean;
};
minBytes: number;
priority?: string[];
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/types/server/server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ export class Server<A = ServerApplicationState> {
cache: ServerCache;

/**
* Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
* Registers a custom content decoding compressor to extend the built-in support where:
* @param encoding - the decoder name string.
* @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the
* return value is an object compatible with the output of node's zlib.createGunzip().
Expand Down Expand Up @@ -392,7 +392,7 @@ export class Server<A = ServerApplicationState> {
dependency(dependencies: Dependencies, after?: ((server: Server) => Promise<void>) | undefined): void;

/**
* Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
* Registers a custom content encoding compressor to extend the built-in support where:
* @param encoding - the encoder name string.
* @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object
* compatible with the output of node's zlib.createGzip().
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,22 +39,22 @@
"@hapi/somever": "^4.1.1",
"@hapi/statehood": "^8.2.0",
"@hapi/subtext": "^8.1.1",
"@hapi/teamwork": "^6.0.0",
"@hapi/teamwork": "^6.0.1",
"@hapi/topo": "^6.0.2",
"@hapi/validate": "^2.0.1"
},
"devDependencies": {
"@hapi/code": "^9.0.3",
"@hapi/eslint-plugin": "^6.0.0",
"@hapi/inert": "^7.1.0",
"@hapi/joi-legacy-test": "npm:@hapi/joi@^15.0.0",
"@hapi/joi-legacy-test": "npm:@hapi/joi@^15.1.1",
"@hapi/lab": "^25.3.2",
"@hapi/vision": "^7.0.3",
"@hapi/wreck": "^18.1.0",
"@types/node": "^18.19.122",
"@types/node": "^22.18.3",
"handlebars": "^4.7.8",
"joi": "^17.13.3",
"legacy-readable-stream": "npm:readable-stream@^1.0.34",
"legacy-readable-stream": "npm:readable-stream@^1.1.14",
"typescript": "^4.9.5"
},
"scripts": {
Expand Down
3 changes: 3 additions & 0 deletions test/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const ChildProcess = require('child_process');
const Http = require('http');
const Net = require('net');
const Zlib = require('zlib');

const internals = {};

Expand Down Expand Up @@ -30,3 +31,5 @@ internals.hasIPv6 = () => {
exports.hasLsof = internals.hasLsof();

exports.hasIPv6 = internals.hasIPv6();

exports.hasZstd = !!Zlib.constants.ZSTD_CLEVEL_DEFAULT;
Loading