@softistx/alxia-compress 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +83 -2
- package/dist/compress.d.ts +33 -0
- package/dist/compress.d.ts.map +1 -0
- package/dist/flushing.d.ts +19 -0
- package/dist/flushing.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +193 -0
- package/dist/index.js.map +11 -0
- package/docs/README.md +12 -0
- package/docs/guide.md +391 -0
- package/docs/roadmap.md +59 -0
- package/docs/troubleshooting.md +304 -0
- package/package.json +51 -5
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Steve Tsala
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @softistx/alxia-compress
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> Moved from `@alxia/compress`: see the [migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md).
|
|
4
|
+
|
|
5
|
+
Response compression for [alxia](https://www.npmjs.com/package/@softistx/alxia):
|
|
6
|
+
zstd, Brotli, gzip and deflate, negotiated from `Accept-Encoding` and
|
|
7
|
+
streamed with Bun's and Node's own codecs. No dependency.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
bun add @softistx/alxia-compress @softistx/alxia
|
|
11
|
+
bun add -d typescript
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { compress } from '@softistx/alxia-compress';
|
|
18
|
+
|
|
19
|
+
app.use(compress());
|
|
20
|
+
app.use(compress({ encodings: ['br', 'gzip'], threshold: 2048 }));
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`compress()` is a middleware: it compresses every response that comes back
|
|
24
|
+
through it, a 404's and an error's included.
|
|
25
|
+
|
|
26
|
+
Compressed: text, JSON, JavaScript, XML and SVG of at least `threshold`
|
|
27
|
+
bytes (1 KiB), files included; a `ReadableStream` has no length, and is
|
|
28
|
+
compressed whatever its size. Never: a `HEAD`, a 204, 206 or 304, a
|
|
29
|
+
response already encoded, or one marked `Cache-Control: no-transform`. An
|
|
30
|
+
event stream is left alone unless `compressible` lets it in.
|
|
31
|
+
`Vary: Accept-Encoding` is set, a strong ETag becomes weak, and
|
|
32
|
+
`Accept-Ranges` is dropped from a compressed response. Brotli runs at
|
|
33
|
+
quality 4, near gzip's speed; for the smallest static assets, serve copies
|
|
34
|
+
compressed at build time with `static`'s `precompressed` option.
|
|
35
|
+
|
|
36
|
+
## Streams
|
|
37
|
+
|
|
38
|
+
A body with no `Content-Length` — a `ReadableStream`, a server-rendered
|
|
39
|
+
page, an event stream let in — is flushed as it comes: what the source
|
|
40
|
+
yields in one turn of the event loop leaves at once, decodable, so a
|
|
41
|
+
page's shell reaches the browser before its deferred parts. A body with a
|
|
42
|
+
length is compressed whole, which compresses better.
|
|
43
|
+
|
|
44
|
+
```tsx
|
|
45
|
+
import { renderToReadableStream } from 'react-dom/server';
|
|
46
|
+
|
|
47
|
+
app.use(compress()).get('/page', async ({ reply }) =>
|
|
48
|
+
reply(200, await renderToReadableStream(<App />), {
|
|
49
|
+
headers: { 'content-type': 'text/html;charset=utf-8' },
|
|
50
|
+
}),
|
|
51
|
+
);
|
|
52
|
+
// the shell arrives as soon as it is rendered, compressed
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Options
|
|
56
|
+
|
|
57
|
+
| option | default | |
|
|
58
|
+
| --- | --- | --- |
|
|
59
|
+
| `encodings` | `['zstd', 'br', 'gzip', 'deflate']` | offered, in the server's order of preference |
|
|
60
|
+
| `threshold` | `1024` | bytes under which a body is sent as it is |
|
|
61
|
+
| `compressible` | text, JSON, JS, XML, SVG | `(contentType) => boolean` |
|
|
62
|
+
|
|
63
|
+
## API
|
|
64
|
+
|
|
65
|
+
| export | |
|
|
66
|
+
| --- | --- |
|
|
67
|
+
| `compress(options?)` | the middleware, for `app.use` |
|
|
68
|
+
| `negotiate(accept, offered)` | the encoding an `Accept-Encoding` gets |
|
|
69
|
+
| `CompressOptions`, `Encoding` | its types |
|
|
70
|
+
| `CompressMiddleware` | what `compress()` returns: a middleware that adds nothing to the context |
|
|
71
|
+
|
|
72
|
+
## Traps
|
|
73
|
+
|
|
74
|
+
`use` it before the routes: a route declared before `app.use(compress())` is
|
|
75
|
+
not compressed. Declare it after `logger()` and `secureHeaders()`, so they
|
|
76
|
+
see the response as it leaves, and before a middleware that sets
|
|
77
|
+
`Cache-Control: no-transform` on the way out (see
|
|
78
|
+
[the guide](https://github.com/softistx/alxia/blob/develop/packages/compress/docs/guide.md#order-with-other-middlewares)).
|
|
79
|
+
|
|
80
|
+
## Documentation
|
|
81
|
+
|
|
82
|
+
- [Guide](https://github.com/softistx/alxia/tree/develop/packages/compress/docs): what is compressed and what is not, streamed bodies, every option, the headers written, the order among other middlewares, testing, and `negotiate`.
|
|
83
|
+
- [Troubleshooting](https://github.com/softistx/alxia/blob/develop/packages/compress/docs/troubleshooting.md): an error message, and what to do about it.
|
|
84
|
+
- [Roadmap](https://github.com/softistx/alxia/blob/develop/packages/compress/docs/roadmap.md): what is coming, and what is not planned.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type Empty, type Middleware } from '@softistx/alxia';
|
|
2
|
+
export type Encoding = 'zstd' | 'br' | 'gzip' | 'deflate';
|
|
3
|
+
export interface CompressOptions {
|
|
4
|
+
/** The encodings offered, in the server's order of preference. */
|
|
5
|
+
readonly encodings?: readonly Encoding[];
|
|
6
|
+
/** Bodies smaller than this, in bytes, are sent as they are. 1 KiB by default. */
|
|
7
|
+
readonly threshold?: number;
|
|
8
|
+
/** Whether a `content-type` is worth compressing. Text, JSON, JavaScript, XML and SVG by default. */
|
|
9
|
+
readonly compressible?: (type: string) => boolean;
|
|
10
|
+
}
|
|
11
|
+
/** What `compress()` makes: a middleware that adds nothing to the context. */
|
|
12
|
+
export type CompressMiddleware = Middleware<Empty, Promise<Response>>;
|
|
13
|
+
/**
|
|
14
|
+
* Compression, as a middleware: each response worth it — every one the
|
|
15
|
+
* routes after it and a request no route matches answer, an error's
|
|
16
|
+
* included — is streamed through the
|
|
17
|
+
* best encoding both sides accept — zstd, Brotli, gzip or deflate — with
|
|
18
|
+
* Bun's and Node's own codecs. A body with no `Content-Length` is flushed
|
|
19
|
+
* as it comes, so a streamed page's shell leaves before its stream ends. An
|
|
20
|
+
* event stream is left alone by default: `compressible` can opt it in, and
|
|
21
|
+
* each event is then flushed in the same way.
|
|
22
|
+
*
|
|
23
|
+
* ```ts
|
|
24
|
+
* app.use(compress());
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export declare function compress(options?: CompressOptions): CompressMiddleware;
|
|
28
|
+
/**
|
|
29
|
+
* The encoding to answer `accept` with: the first of `offered` the client
|
|
30
|
+
* accepts, by its own `q` order first. `identity` alone, or nothing, is none.
|
|
31
|
+
*/
|
|
32
|
+
export declare function negotiate(accept: string | null, offered: readonly Encoding[]): Encoding | undefined;
|
|
33
|
+
//# sourceMappingURL=compress.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"compress.d.ts","sourceRoot":"","sources":["../src/compress.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,KAAK,KAAK,EACV,KAAK,UAAU,EAKf,MAAM,iBAAiB,CAAC;AAGzB,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,IAAI,GAAG,MAAM,GAAG,SAAS,CAAC;AAE1D,MAAM,WAAW,eAAe;IAC/B,kEAAkE;IAClE,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC;IACzC,kFAAkF;IAClF,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,qGAAqG;IACrG,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAClD;AAED,8EAA8E;AAC9E,MAAM,MAAM,kBAAkB,GAAG,UAAU,CAAC,KAAK,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;AAKtE;;;;;;;;;;;;;GAaG;AACH,wBAAgB,QAAQ,CAAC,OAAO,GAAE,eAAoB,GAAG,kBAAkB,CAS1E;AAsED;;;GAGG;AACH,wBAAgB,SAAS,CACxB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,OAAO,EAAE,SAAS,QAAQ,EAAE,GAC1B,QAAQ,GAAG,SAAS,CAmBtB"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Encoding } from './compress';
|
|
2
|
+
/**
|
|
3
|
+
* zlib's default, 11, is meant for compressing once ahead of time: on a
|
|
4
|
+
* response compressed per request it costs many times gzip's CPU for a few
|
|
5
|
+
* percent. 4 is still smaller than gzip's default, at about its speed.
|
|
6
|
+
*/
|
|
7
|
+
export declare const BROTLI_QUALITY = 4;
|
|
8
|
+
/**
|
|
9
|
+
* `source` compressed as `encoding`, flushed after the chunks of each turn
|
|
10
|
+
* of the event loop: what the source has yielded leaves at once, decodable,
|
|
11
|
+
* instead of waiting in the codec for a block to fill or the stream to end.
|
|
12
|
+
* The chunks a source yields in one turn — a renderer writing its shell —
|
|
13
|
+
* share one flush, which costs less ratio than one each.
|
|
14
|
+
*
|
|
15
|
+
* A source that fails errors the result; a reader that cancels cancels the
|
|
16
|
+
* source. Either way the codec is destroyed.
|
|
17
|
+
*/
|
|
18
|
+
export declare function flushing(source: ReadableStream<Uint8Array>, encoding: Encoding): ReadableStream<Uint8Array>;
|
|
19
|
+
//# sourceMappingURL=flushing.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flushing.d.ts","sourceRoot":"","sources":["../src/flushing.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3C;;;;GAIG;AACH,eAAO,MAAM,cAAc,IAAI,CAAC;AAuChC;;;;;;;;;GASG;AACH,wBAAgB,QAAQ,CACvB,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,EAClC,QAAQ,EAAE,QAAQ,GAChB,cAAc,CAAC,UAAU,CAAC,CAyE5B"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,QAAQ,EACR,KAAK,QAAQ,EACb,SAAS,GACT,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// src/compress.ts
|
|
2
|
+
import { Duplex } from "node:stream";
|
|
3
|
+
import { constants as constants2, createBrotliCompress as createBrotliCompress2 } from "node:zlib";
|
|
4
|
+
import {
|
|
5
|
+
defineMiddleware,
|
|
6
|
+
markFactory,
|
|
7
|
+
settle,
|
|
8
|
+
vary,
|
|
9
|
+
withHeaders
|
|
10
|
+
} from "@softistx/alxia";
|
|
11
|
+
|
|
12
|
+
// src/flushing.ts
|
|
13
|
+
import {
|
|
14
|
+
constants,
|
|
15
|
+
createBrotliCompress,
|
|
16
|
+
createDeflate,
|
|
17
|
+
createGzip,
|
|
18
|
+
createZstdCompress
|
|
19
|
+
} from "node:zlib";
|
|
20
|
+
var BROTLI_QUALITY = 4;
|
|
21
|
+
function codec(encoding) {
|
|
22
|
+
switch (encoding) {
|
|
23
|
+
case "zstd":
|
|
24
|
+
return { codec: createZstdCompress(), kind: constants.ZSTD_e_flush };
|
|
25
|
+
case "br":
|
|
26
|
+
return {
|
|
27
|
+
codec: createBrotliCompress({
|
|
28
|
+
params: { [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY }
|
|
29
|
+
}),
|
|
30
|
+
kind: constants.BROTLI_OPERATION_FLUSH
|
|
31
|
+
};
|
|
32
|
+
case "gzip":
|
|
33
|
+
return { codec: createGzip(), kind: constants.Z_SYNC_FLUSH };
|
|
34
|
+
case "deflate":
|
|
35
|
+
return { codec: createDeflate(), kind: constants.Z_SYNC_FLUSH };
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
function drained(zlib) {
|
|
39
|
+
if (zlib.destroyed)
|
|
40
|
+
return Promise.resolve();
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
const done = () => {
|
|
43
|
+
zlib.off("drain", done);
|
|
44
|
+
zlib.off("close", done);
|
|
45
|
+
resolve();
|
|
46
|
+
};
|
|
47
|
+
zlib.once("drain", done);
|
|
48
|
+
zlib.once("close", done);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
function flushing(source, encoding) {
|
|
52
|
+
const { codec: zlib, kind } = codec(encoding);
|
|
53
|
+
const reader = source.getReader();
|
|
54
|
+
let settled = false;
|
|
55
|
+
let ending = false;
|
|
56
|
+
let scheduled = false;
|
|
57
|
+
const gone = new Promise((resolve) => zlib.once("close", resolve));
|
|
58
|
+
const flush = () => {
|
|
59
|
+
scheduled = false;
|
|
60
|
+
if (!ending && !settled)
|
|
61
|
+
zlib.flush(kind, () => {});
|
|
62
|
+
};
|
|
63
|
+
return new ReadableStream({
|
|
64
|
+
start(controller) {
|
|
65
|
+
zlib.on("data", (chunk) => {
|
|
66
|
+
if (!settled)
|
|
67
|
+
controller.enqueue(chunk);
|
|
68
|
+
});
|
|
69
|
+
zlib.once("end", () => {
|
|
70
|
+
if (settled)
|
|
71
|
+
return;
|
|
72
|
+
settled = true;
|
|
73
|
+
controller.close();
|
|
74
|
+
});
|
|
75
|
+
zlib.once("error", (error) => {
|
|
76
|
+
if (!settled) {
|
|
77
|
+
settled = true;
|
|
78
|
+
controller.error(error);
|
|
79
|
+
}
|
|
80
|
+
reader.cancel(error).catch(() => {});
|
|
81
|
+
});
|
|
82
|
+
},
|
|
83
|
+
async pull(controller) {
|
|
84
|
+
while (!settled && (controller.desiredSize ?? 0) > 0) {
|
|
85
|
+
let next;
|
|
86
|
+
try {
|
|
87
|
+
next = await reader.read();
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (!settled) {
|
|
90
|
+
settled = true;
|
|
91
|
+
controller.error(error);
|
|
92
|
+
}
|
|
93
|
+
zlib.destroy();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
if (settled)
|
|
97
|
+
return;
|
|
98
|
+
if (next.done) {
|
|
99
|
+
ending = true;
|
|
100
|
+
zlib.end();
|
|
101
|
+
return gone;
|
|
102
|
+
}
|
|
103
|
+
if (!scheduled) {
|
|
104
|
+
scheduled = true;
|
|
105
|
+
setImmediate(flush);
|
|
106
|
+
}
|
|
107
|
+
if (!zlib.write(next.value))
|
|
108
|
+
await drained(zlib);
|
|
109
|
+
}
|
|
110
|
+
},
|
|
111
|
+
cancel(reason) {
|
|
112
|
+
settled = true;
|
|
113
|
+
zlib.destroy();
|
|
114
|
+
return reader.cancel(reason).catch(() => {});
|
|
115
|
+
}
|
|
116
|
+
}, new ByteLengthQueuingStrategy({ highWaterMark: 64 * 1024 }));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// src/compress.ts
|
|
120
|
+
var COMPRESSIBLE = /^(text\/(?!event-stream)|application\/(.+\+)?(json|javascript|xml)|image\/svg\+xml)/i;
|
|
121
|
+
function compress(options = {}) {
|
|
122
|
+
const settings = {
|
|
123
|
+
encodings: options.encodings ?? ["zstd", "br", "gzip", "deflate"],
|
|
124
|
+
threshold: options.threshold ?? 1024,
|
|
125
|
+
compressible: options.compressible ?? ((type) => COMPRESSIBLE.test(type))
|
|
126
|
+
};
|
|
127
|
+
return defineMiddleware(async function compress(ctx, next) {
|
|
128
|
+
return compressed(await settle(ctx, next()), ctx.request, settings);
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
function compressed(given, request, { encodings, threshold, compressible }) {
|
|
132
|
+
const type = given.headers.get("content-type") ?? "";
|
|
133
|
+
const response = compressible(type) ? withHeaders(given, (headers) => vary(headers, "Accept-Encoding")) : given;
|
|
134
|
+
if (response.body === null || request.method === "HEAD" || response.headers.has("content-encoding") || response.status === 204 || response.status === 206 || response.status === 304 || /\bno-transform\b/.test(response.headers.get("cache-control") ?? "") || !compressible(type)) {
|
|
135
|
+
return response;
|
|
136
|
+
}
|
|
137
|
+
const length = response.headers.get("content-length");
|
|
138
|
+
if (length !== null && Number(length) < threshold)
|
|
139
|
+
return response;
|
|
140
|
+
const encoding = negotiate(request.headers.get("accept-encoding"), encodings);
|
|
141
|
+
if (encoding === undefined)
|
|
142
|
+
return response;
|
|
143
|
+
const headers = new Headers(response.headers);
|
|
144
|
+
headers.set("content-encoding", encoding);
|
|
145
|
+
headers.delete("content-length");
|
|
146
|
+
headers.delete("accept-ranges");
|
|
147
|
+
const etag = headers.get("etag");
|
|
148
|
+
if (etag !== null && !etag.startsWith("W/"))
|
|
149
|
+
headers.set("etag", `W/${etag}`);
|
|
150
|
+
const body = length === null ? flushing(response.body, encoding) : response.body.pipeThrough(compressor(encoding));
|
|
151
|
+
return new Response(body, {
|
|
152
|
+
status: response.status,
|
|
153
|
+
statusText: response.statusText,
|
|
154
|
+
headers
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function compressor(encoding) {
|
|
158
|
+
if (encoding === "br") {
|
|
159
|
+
return Duplex.toWeb(createBrotliCompress2({
|
|
160
|
+
params: { [constants2.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY }
|
|
161
|
+
}));
|
|
162
|
+
}
|
|
163
|
+
return new CompressionStream(encoding);
|
|
164
|
+
}
|
|
165
|
+
function negotiate(accept, offered) {
|
|
166
|
+
if (accept === null)
|
|
167
|
+
return;
|
|
168
|
+
const weights = new Map;
|
|
169
|
+
for (const part of accept.split(",")) {
|
|
170
|
+
const [name, ...params] = part.trim().toLowerCase().split(";");
|
|
171
|
+
if (!name)
|
|
172
|
+
continue;
|
|
173
|
+
const q = params.map((param) => param.trim()).find((param) => param.startsWith("q="));
|
|
174
|
+
weights.set(name, q === undefined ? 1 : Number(q.slice(2)) || 0);
|
|
175
|
+
}
|
|
176
|
+
const weight = (encoding) => weights.get(encoding) ?? weights.get("*") ?? 0;
|
|
177
|
+
let best;
|
|
178
|
+
for (const encoding of offered) {
|
|
179
|
+
if (weight(encoding) <= 0)
|
|
180
|
+
continue;
|
|
181
|
+
if (best === undefined || weight(encoding) > weight(best))
|
|
182
|
+
best = encoding;
|
|
183
|
+
}
|
|
184
|
+
return best;
|
|
185
|
+
}
|
|
186
|
+
markFactory(compress);
|
|
187
|
+
export {
|
|
188
|
+
compress,
|
|
189
|
+
negotiate
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
//# debugId=7209FF84594CC67264756E2164756E21
|
|
193
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/compress.ts", "../src/flushing.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import { Duplex } from 'node:stream';\nimport { constants, createBrotliCompress } from 'node:zlib';\nimport {\n\tdefineMiddleware,\n\ttype Empty,\n\ttype Middleware,\n\tmarkFactory,\n\tsettle,\n\tvary,\n\twithHeaders,\n} from '@softistx/alxia';\nimport { BROTLI_QUALITY, flushing } from './flushing';\n\nexport type Encoding = 'zstd' | 'br' | 'gzip' | 'deflate';\n\nexport interface CompressOptions {\n\t/** The encodings offered, in the server's order of preference. */\n\treadonly encodings?: readonly Encoding[];\n\t/** Bodies smaller than this, in bytes, are sent as they are. 1 KiB by default. */\n\treadonly threshold?: number;\n\t/** Whether a `content-type` is worth compressing. Text, JSON, JavaScript, XML and SVG by default. */\n\treadonly compressible?: (type: string) => boolean;\n}\n\n/** What `compress()` makes: a middleware that adds nothing to the context. */\nexport type CompressMiddleware = Middleware<Empty, Promise<Response>>;\n\nconst COMPRESSIBLE =\n\t/^(text\\/(?!event-stream)|application\\/(.+\\+)?(json|javascript|xml)|image\\/svg\\+xml)/i;\n\n/**\n * Compression, as a middleware: each response worth it — every one the\n * routes after it and a request no route matches answer, an error's\n * included — is streamed through the\n * best encoding both sides accept — zstd, Brotli, gzip or deflate — with\n * Bun's and Node's own codecs. A body with no `Content-Length` is flushed\n * as it comes, so a streamed page's shell leaves before its stream ends. An\n * event stream is left alone by default: `compressible` can opt it in, and\n * each event is then flushed in the same way.\n *\n * ```ts\n * app.use(compress());\n * ```\n */\nexport function compress(options: CompressOptions = {}): CompressMiddleware {\n\tconst settings: Settings = {\n\t\tencodings: options.encodings ?? ['zstd', 'br', 'gzip', 'deflate'],\n\t\tthreshold: options.threshold ?? 1024,\n\t\tcompressible: options.compressible ?? ((type) => COMPRESSIBLE.test(type)),\n\t};\n\treturn defineMiddleware(async function compress(ctx, next) {\n\t\treturn compressed(await settle(ctx, next()), ctx.request, settings);\n\t});\n}\n\ninterface Settings {\n\treadonly encodings: readonly Encoding[];\n\treadonly threshold: number;\n\treadonly compressible: (type: string) => boolean;\n}\n\n/** `response`, encoded for `request` when it is worth it; as it is otherwise. */\nfunction compressed(\n\tgiven: Response,\n\trequest: Request,\n\t{ encodings, threshold, compressible }: Settings,\n): Response {\n\tconst type = given.headers.get('content-type') ?? '';\n\tconst response = compressible(type)\n\t\t? withHeaders(given, (headers) => vary(headers, 'Accept-Encoding'))\n\t\t: given;\n\tif (\n\t\tresponse.body === null ||\n\t\trequest.method === 'HEAD' ||\n\t\tresponse.headers.has('content-encoding') ||\n\t\tresponse.status === 204 ||\n\t\tresponse.status === 206 ||\n\t\tresponse.status === 304 ||\n\t\t/\\bno-transform\\b/.test(response.headers.get('cache-control') ?? '') ||\n\t\t!compressible(type)\n\t) {\n\t\treturn response;\n\t}\n\tconst length = response.headers.get('content-length');\n\tif (length !== null && Number(length) < threshold) return response;\n\tconst encoding = negotiate(request.headers.get('accept-encoding'), encodings);\n\tif (encoding === undefined) return response;\n\tconst headers = new Headers(response.headers);\n\theaders.set('content-encoding', encoding);\n\theaders.delete('content-length');\n\t// A range of the encoded body is not a range of the file.\n\theaders.delete('accept-ranges');\n\tconst etag = headers.get('etag');\n\tif (etag !== null && !etag.startsWith('W/')) headers.set('etag', `W/${etag}`);\n\t// A body with no length is a stream: flushed as it comes, so a\n\t// streamed page or an event leaves at once. One with a length is\n\t// compressed whole, which compresses better.\n\tconst body =\n\t\tlength === null\n\t\t\t? flushing(response.body, encoding)\n\t\t\t: response.body.pipeThrough(compressor(encoding));\n\treturn new Response(body, {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders,\n\t});\n}\n\nfunction compressor(\n\tencoding: Encoding,\n): ReadableWritablePair<Uint8Array, Uint8Array> {\n\tif (encoding === 'br') {\n\t\treturn Duplex.toWeb(\n\t\t\tcreateBrotliCompress({\n\t\t\t\tparams: { [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY },\n\t\t\t}),\n\t\t) as unknown as ReadableWritablePair<Uint8Array, Uint8Array>;\n\t}\n\treturn new CompressionStream(\n\t\tencoding as CompressionFormat,\n\t) as unknown as ReadableWritablePair<Uint8Array, Uint8Array>;\n}\n\n/**\n * The encoding to answer `accept` with: the first of `offered` the client\n * accepts, by its own `q` order first. `identity` alone, or nothing, is none.\n */\nexport function negotiate(\n\taccept: string | null,\n\toffered: readonly Encoding[],\n): Encoding | undefined {\n\tif (accept === null) return undefined;\n\tconst weights = new Map<string, number>();\n\tfor (const part of accept.split(',')) {\n\t\tconst [name, ...params] = part.trim().toLowerCase().split(';');\n\t\tif (!name) continue;\n\t\tconst q = params\n\t\t\t.map((param) => param.trim())\n\t\t\t.find((param) => param.startsWith('q='));\n\t\tweights.set(name, q === undefined ? 1 : Number(q.slice(2)) || 0);\n\t}\n\tconst weight = (encoding: string) =>\n\t\tweights.get(encoding) ?? weights.get('*') ?? 0;\n\tlet best: Encoding | undefined;\n\tfor (const encoding of offered) {\n\t\tif (weight(encoding) <= 0) continue;\n\t\tif (best === undefined || weight(encoding) > weight(best)) best = encoding;\n\t}\n\treturn best;\n}\n\nmarkFactory(compress);\n",
|
|
6
|
+
"import type { Transform } from 'node:stream';\nimport {\n\tconstants,\n\tcreateBrotliCompress,\n\tcreateDeflate,\n\tcreateGzip,\n\tcreateZstdCompress,\n} from 'node:zlib';\nimport type { Encoding } from './compress';\n\n/**\n * zlib's default, 11, is meant for compressing once ahead of time: on a\n * response compressed per request it costs many times gzip's CPU for a few\n * percent. 4 is still smaller than gzip's default, at about its speed.\n */\nexport const BROTLI_QUALITY = 4;\n\ntype Codec = Transform & {\n\tflush(kind: number, callback: () => void): void;\n};\n\n/** A `node:zlib` stream for `encoding`, and the flush that empties it. */\nfunction codec(encoding: Encoding): { codec: Codec; kind: number } {\n\tswitch (encoding) {\n\t\tcase 'zstd':\n\t\t\treturn { codec: createZstdCompress(), kind: constants.ZSTD_e_flush };\n\t\tcase 'br':\n\t\t\treturn {\n\t\t\t\tcodec: createBrotliCompress({\n\t\t\t\t\tparams: { [constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY },\n\t\t\t\t}),\n\t\t\t\tkind: constants.BROTLI_OPERATION_FLUSH,\n\t\t\t};\n\t\tcase 'gzip':\n\t\t\treturn { codec: createGzip(), kind: constants.Z_SYNC_FLUSH };\n\t\tcase 'deflate':\n\t\t\treturn { codec: createDeflate(), kind: constants.Z_SYNC_FLUSH };\n\t}\n}\n\n/** Until the codec can take more, or is gone. */\nfunction drained(zlib: Codec): Promise<void> {\n\tif (zlib.destroyed) return Promise.resolve();\n\treturn new Promise((resolve) => {\n\t\tconst done = () => {\n\t\t\tzlib.off('drain', done);\n\t\t\tzlib.off('close', done);\n\t\t\tresolve();\n\t\t};\n\t\tzlib.once('drain', done);\n\t\tzlib.once('close', done);\n\t});\n}\n\n/**\n * `source` compressed as `encoding`, flushed after the chunks of each turn\n * of the event loop: what the source has yielded leaves at once, decodable,\n * instead of waiting in the codec for a block to fill or the stream to end.\n * The chunks a source yields in one turn — a renderer writing its shell —\n * share one flush, which costs less ratio than one each.\n *\n * A source that fails errors the result; a reader that cancels cancels the\n * source. Either way the codec is destroyed.\n */\nexport function flushing(\n\tsource: ReadableStream<Uint8Array>,\n\tencoding: Encoding,\n): ReadableStream<Uint8Array> {\n\tconst { codec: zlib, kind } = codec(encoding);\n\tconst reader = source.getReader();\n\t// Set once the result is closed, errored or cancelled: what the codec\n\t// emits after that has nowhere to go.\n\tlet settled = false;\n\tlet ending = false;\n\tlet scheduled = false;\n\tconst gone = new Promise<void>((resolve) => zlib.once('close', resolve));\n\tconst flush = () => {\n\t\tscheduled = false;\n\t\tif (!ending && !settled) zlib.flush(kind, () => {});\n\t};\n\treturn new ReadableStream<Uint8Array>(\n\t\t{\n\t\t\tstart(controller) {\n\t\t\t\tzlib.on('data', (chunk: Uint8Array) => {\n\t\t\t\t\tif (!settled) controller.enqueue(chunk);\n\t\t\t\t});\n\t\t\t\tzlib.once('end', () => {\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tsettled = true;\n\t\t\t\t\tcontroller.close();\n\t\t\t\t});\n\t\t\t\tzlib.once('error', (error) => {\n\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t}\n\t\t\t\t\treader.cancel(error).catch(() => {});\n\t\t\t\t});\n\t\t\t},\n\t\t\t// Reads on while the reader wants more: a pull that enqueued nothing\n\t\t\t// is not called again until the codec's bytes arrive, a turn later,\n\t\t\t// which would flush each chunk on its own.\n\t\t\tasync pull(controller) {\n\t\t\t\twhile (!settled && (controller.desiredSize ?? 0) > 0) {\n\t\t\t\t\tlet next: Awaited<ReturnType<typeof reader.read>>;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnext = await reader.read();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!settled) {\n\t\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tzlib.destroy();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (settled) return;\n\t\t\t\t\tif (next.done) {\n\t\t\t\t\t\tending = true;\n\t\t\t\t\t\tzlib.end();\n\t\t\t\t\t\t// No pull until the codec is done: the last bytes close it.\n\t\t\t\t\t\treturn gone;\n\t\t\t\t\t}\n\t\t\t\t\tif (!scheduled) {\n\t\t\t\t\t\tscheduled = true;\n\t\t\t\t\t\tsetImmediate(flush);\n\t\t\t\t\t}\n\t\t\t\t\tif (!zlib.write(next.value)) await drained(zlib);\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel(reason) {\n\t\t\t\tsettled = true;\n\t\t\t\tzlib.destroy();\n\t\t\t\treturn reader.cancel(reason).catch(() => {});\n\t\t\t},\n\t\t},\n\t\t// Once about 64 KiB of compressed bytes wait for the reader, the\n\t\t// source is read no further; what the codec still holds may add as\n\t\t// much again.\n\t\tnew ByteLengthQueuingStrategy({ highWaterMark: 64 * 1024 }),\n\t);\n}\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": "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",
|
|
9
|
+
"debugId": "7209FF84594CC67264756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
package/docs/README.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# @softistx/alxia-compress documentation
|
|
2
|
+
|
|
3
|
+
The [package README](../README.md) is the short version. This folder is
|
|
4
|
+
the long one: what is compressed and what is not, how a stream is
|
|
5
|
+
flushed, every option with its default, the headers written, and the
|
|
6
|
+
errors you may meet.
|
|
7
|
+
|
|
8
|
+
| Page | Read it when |
|
|
9
|
+
| --- | --- |
|
|
10
|
+
| [Guide](guide.md) | choosing encodings, a threshold or the types compressed, streaming a page or events compressed, placing the middleware among others, testing it, or negotiating an encoding yourself |
|
|
11
|
+
| [Troubleshooting](troubleshooting.md) | something went wrong and you have the message, or a response is not encoded as you expected |
|
|
12
|
+
| [Roadmap](roadmap.md) | wondering what is coming, and what is not planned |
|
package/docs/guide.md
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
# Guide
|
|
2
|
+
|
|
3
|
+
This page covers what `compress()` compresses, what it leaves alone, how a
|
|
4
|
+
streamed body is flushed, the headers it writes, its options, and
|
|
5
|
+
`negotiate` on its own.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { alxia } from '@softistx/alxia';
|
|
9
|
+
import { compress } from '@softistx/alxia-compress';
|
|
10
|
+
|
|
11
|
+
const app = alxia()
|
|
12
|
+
.use(compress())
|
|
13
|
+
.get('/report', ({ reply }) => reply(200, { rows: Array.from({ length: 500 }, (_, i) => ({ i })) }));
|
|
14
|
+
|
|
15
|
+
app.listen(3000);
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
A client sending `Accept-Encoding: gzip, br, zstd` receives the JSON as
|
|
19
|
+
zstd; one sending `gzip` receives gzip; one sending nothing receives it as
|
|
20
|
+
it is.
|
|
21
|
+
|
|
22
|
+
## Signatures
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
type Encoding = 'zstd' | 'br' | 'gzip' | 'deflate';
|
|
26
|
+
|
|
27
|
+
interface CompressOptions {
|
|
28
|
+
readonly encodings?: readonly Encoding[];
|
|
29
|
+
readonly threshold?: number;
|
|
30
|
+
readonly compressible?: (type: string) => boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function compress(options?: CompressOptions): Middleware<Empty, Promise<Response>>;
|
|
34
|
+
|
|
35
|
+
function negotiate(accept: string | null, offered: readonly Encoding[]): Encoding | undefined;
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`compress` returns a middleware from `@softistx/alxia`, for `app.use`. It waits
|
|
39
|
+
for the rest of the chain, then answers the response compressed, and adds
|
|
40
|
+
nothing to the context: routes and replies are the same with or without it.
|
|
41
|
+
It sees every response that comes back through it: the routes declared
|
|
42
|
+
after it, and a request no route matches (a 404, a 405), an error's reply
|
|
43
|
+
included. A route declared before it is not compressed.
|
|
44
|
+
|
|
45
|
+
## Options
|
|
46
|
+
|
|
47
|
+
| Option | Type | Default | Effect |
|
|
48
|
+
| --- | --- | --- | --- |
|
|
49
|
+
| `encodings` | `readonly Encoding[]` | `['zstd', 'br', 'gzip', 'deflate']` | the encodings offered, in the server's order of preference |
|
|
50
|
+
| `threshold` | `number` | `1024` | a body whose `Content-Length` is under this many bytes is sent as it is |
|
|
51
|
+
| `compressible` | `(type: string) => boolean` | text, JSON, JavaScript, XML, SVG | whether a response's `Content-Type` is worth compressing |
|
|
52
|
+
|
|
53
|
+
### `encodings`
|
|
54
|
+
|
|
55
|
+
The client's `q` values decide first; among encodings the client weighs
|
|
56
|
+
equally, the first in `encodings` wins. Leave out what you do not want to
|
|
57
|
+
spend CPU on:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
app.use(compress({ encodings: ['br', 'gzip'] }));
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
| `Accept-Encoding` | `encodings` | Sent |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| `gzip, deflate, br, zstd` | default | `zstd` |
|
|
66
|
+
| `gzip, br` | `['br', 'gzip']` | `br` |
|
|
67
|
+
| `gzip, br` | `['gzip', 'br']` | `gzip` |
|
|
68
|
+
| `gzip;q=1, br;q=0.8` | `['br', 'gzip']` | `gzip`: the client prefers it |
|
|
69
|
+
| `zstd` | `['br', 'gzip']` | nothing: not offered |
|
|
70
|
+
| `identity`, or no header | any | nothing |
|
|
71
|
+
|
|
72
|
+
A body with a `Content-Length` goes through the runtime's
|
|
73
|
+
`CompressionStream` for `zstd`, `gzip` and `deflate`, and through
|
|
74
|
+
`node:zlib`'s `createBrotliCompress` for `br`, at quality 4, not zlib's
|
|
75
|
+
default of 11. A body with none goes through `node:zlib` in all four, which
|
|
76
|
+
can flush: see [Streamed bodies](#streamed-bodies). Quality 11 is meant for
|
|
77
|
+
compressing once, ahead of time: paid on every request, it costs many
|
|
78
|
+
times gzip's CPU for a few percent, while 4 is still smaller than gzip at
|
|
79
|
+
about its speed. None of the codecs' levels is an option. For the smallest
|
|
80
|
+
static assets, let the build write `.br` and `.gz` copies at the highest
|
|
81
|
+
level and serve them with `static`'s
|
|
82
|
+
[`precompressed`](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/static-files.md#options)
|
|
83
|
+
option; the middleware leaves them alone. An empty list never compresses.
|
|
84
|
+
|
|
85
|
+
### `threshold`
|
|
86
|
+
|
|
87
|
+
Read from the response's `Content-Length`. A JSON or string reply has one
|
|
88
|
+
when the middleware sees it, and so does a binary one — a `Blob`, a `Bun.file(…)`,
|
|
89
|
+
what `static` and `file` serve, an `ArrayBuffer` or a typed array. A
|
|
90
|
+
`ReadableStream` does not: its size is unknown until it ends, and **a body
|
|
91
|
+
with no `Content-Length` is compressed whatever its size**:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
app.use(compress({ threshold: 2048 }));
|
|
95
|
+
// reply(200, 'x'.repeat(1500)) → sent as it is: 1500 < 2048
|
|
96
|
+
// reply(200, { text: 'alxia '.repeat(1000) }) → compressed: 6011 bytes
|
|
97
|
+
// static('/s', '.') for a 117-byte file → sent as it is: 117 < 2048
|
|
98
|
+
// reply(200, readableStreamOfTwoBytes) → compressed: no Content-Length
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
`threshold: 0` compresses every compressible body.
|
|
102
|
+
|
|
103
|
+
### `compressible`
|
|
104
|
+
|
|
105
|
+
Called with the response's `Content-Type` as it is, parameters included
|
|
106
|
+
(`text/plain;charset=utf-8`), or `''` when there is none. The default
|
|
107
|
+
accepts:
|
|
108
|
+
|
|
109
|
+
| Accepted | Examples |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| any `text/*` except `text/event-stream` | `text/html`, `text/css`, `text/csv`, `text/markdown` |
|
|
112
|
+
| `application/json`, `application/javascript`, `application/xml`, and their `+suffix` forms | `application/problem+json`, `application/ld+json`, `application/atom+xml` |
|
|
113
|
+
| `image/svg+xml` | |
|
|
114
|
+
|
|
115
|
+
Anything else — images, video, fonts, archives, `application/octet-stream`,
|
|
116
|
+
`application/wasm` — is sent as it is. To add a type, keep the default's
|
|
117
|
+
test and extend it:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
const defaults = /^(text\/(?!event-stream)|application\/(.+\+)?(json|javascript|xml)|image\/svg\+xml)/i;
|
|
121
|
+
|
|
122
|
+
app.use(
|
|
123
|
+
compress({
|
|
124
|
+
compressible: (type) => defaults.test(type) || type.startsWith('application/wasm'),
|
|
125
|
+
}),
|
|
126
|
+
);
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
The default leaves `text/event-stream` out: events are small, and a
|
|
130
|
+
compressed one saves little. A function that answers `true` for it
|
|
131
|
+
compresses event streams too, and each event still leaves as it is sent:
|
|
132
|
+
see [Streamed bodies](#streamed-bodies).
|
|
133
|
+
|
|
134
|
+
## What is never compressed
|
|
135
|
+
|
|
136
|
+
Whatever `compressible` says, a response is sent as it is when:
|
|
137
|
+
|
|
138
|
+
| Condition | Why |
|
|
139
|
+
| --- | --- |
|
|
140
|
+
| it has no body | nothing to compress |
|
|
141
|
+
| the request is a `HEAD` | it has no body to send |
|
|
142
|
+
| its status is 204, 206 or 304 | no body, or a byte range of the uncompressed one |
|
|
143
|
+
| it already has a `Content-Encoding` | a precompressed file from `static(…, { precompressed })`, or a body a handler encoded |
|
|
144
|
+
| its `Cache-Control` holds `no-transform` | the sender asked for its bytes to be kept |
|
|
145
|
+
| its `Content-Length` is under `threshold` | the gain would be smaller than the headers |
|
|
146
|
+
| the client accepts none of `encodings` | |
|
|
147
|
+
|
|
148
|
+
## Streamed bodies
|
|
149
|
+
|
|
150
|
+
A body with no `Content-Length` when the middleware sees it — a `ReadableStream`, a
|
|
151
|
+
page rendered by `renderToReadableStream`, an event stream that
|
|
152
|
+
`compressible` lets in — is flushed as it comes. After the chunks the
|
|
153
|
+
source yields in one turn of the event loop, the codec is flushed
|
|
154
|
+
(`Z_SYNC_FLUSH` for gzip and deflate, `BROTLI_OPERATION_FLUSH` for br,
|
|
155
|
+
`ZSTD_e_flush` for zstd), and the bytes so far leave, decodable on their
|
|
156
|
+
own. Without it, a codec holds its input until a block fills or the stream
|
|
157
|
+
ends, and a page's shell would reach the browser only with its last
|
|
158
|
+
deferred part.
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
import { alxia } from '@softistx/alxia';
|
|
162
|
+
import { compress } from '@softistx/alxia-compress';
|
|
163
|
+
|
|
164
|
+
const encoder = new TextEncoder();
|
|
165
|
+
const app = alxia()
|
|
166
|
+
.use(compress())
|
|
167
|
+
.get('/page', ({ reply }) =>
|
|
168
|
+
reply(
|
|
169
|
+
200,
|
|
170
|
+
new ReadableStream<Uint8Array>({
|
|
171
|
+
start(controller) {
|
|
172
|
+
controller.enqueue(encoder.encode('<!DOCTYPE html><html><body><main>…the shell…'));
|
|
173
|
+
setTimeout(() => {
|
|
174
|
+
controller.enqueue(encoder.encode('…the deferred part…</main></body></html>'));
|
|
175
|
+
controller.close();
|
|
176
|
+
}, 300);
|
|
177
|
+
},
|
|
178
|
+
}),
|
|
179
|
+
{ headers: { 'content-type': 'text/html;charset=utf-8' } },
|
|
180
|
+
),
|
|
181
|
+
);
|
|
182
|
+
// gzip, br, zstd and deflate alike: the shell arrives in about 1 ms,
|
|
183
|
+
// the rest at 300 ms.
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**What it costs.** The chunks of one turn share one flush, so a renderer
|
|
187
|
+
that writes its shell as many small chunks at once pays for one flush, not
|
|
188
|
+
for each. On a 41 KB streamed page of 308 chunks written in three turns,
|
|
189
|
+
the flushed output was within 2% of the same page compressed whole, in all
|
|
190
|
+
four encodings. A source that yields each small chunk in a turn of its own
|
|
191
|
+
pays a flush per chunk: the same page, one chunk per turn, came out 56%
|
|
192
|
+
larger in gzip and deflate and 89–94% larger in br and zstd. A source
|
|
193
|
+
yielding a row at a time can batch its rows before it yields them.
|
|
194
|
+
|
|
195
|
+
**What keeps today's path.** A body with a `Content-Length` — a string, a
|
|
196
|
+
JSON reply, a `Blob`, a file — is compressed whole, unflushed, through the
|
|
197
|
+
codecs listed under [`encodings`](#encodings): its bytes are the same as
|
|
198
|
+
before streams were flushed.
|
|
199
|
+
|
|
200
|
+
**Errors and cancellation.** A source that fails errors the compressed
|
|
201
|
+
body after what it had already sent: through `listen`, the connection is
|
|
202
|
+
closed with the response cut short. A client that goes away cancels the
|
|
203
|
+
source, as it would without compression, and the codec is released.
|
|
204
|
+
|
|
205
|
+
To assert in a spec that a stream is flushed, read the body as it comes
|
|
206
|
+
and decode what arrived before the source's pause, with the flush mode as
|
|
207
|
+
`finishFlush`:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import { expect, test } from 'bun:test';
|
|
211
|
+
import { constants, gunzipSync } from 'node:zlib';
|
|
212
|
+
|
|
213
|
+
test('the shell leaves before the stream ends', async () => {
|
|
214
|
+
const since = performance.now();
|
|
215
|
+
const response = await app.request('/page', { headers: { 'accept-encoding': 'gzip' } });
|
|
216
|
+
const early: Uint8Array[] = [];
|
|
217
|
+
for await (const chunk of response.body ?? []) {
|
|
218
|
+
if (performance.now() - since < 150) early.push(chunk);
|
|
219
|
+
}
|
|
220
|
+
const shell = gunzipSync(Buffer.concat(early), { finishFlush: constants.Z_SYNC_FLUSH });
|
|
221
|
+
expect(shell.toString()).toBe('<!DOCTYPE html><html><body><main>…the shell…');
|
|
222
|
+
});
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
## The headers it writes
|
|
226
|
+
|
|
227
|
+
On a compressed response:
|
|
228
|
+
|
|
229
|
+
| Header | What happens |
|
|
230
|
+
| --- | --- |
|
|
231
|
+
| `Content-Encoding` | set to the encoding chosen |
|
|
232
|
+
| `Content-Length` | removed: the body is streamed, its final size unknown |
|
|
233
|
+
| `Accept-Ranges` | removed: a range of the encoded body is not a range of the file |
|
|
234
|
+
| `ETag` | a strong one (`"v1"`) becomes weak (`W/"v1"`); a weak one is kept |
|
|
235
|
+
| `Vary` | `Accept-Encoding` added |
|
|
236
|
+
|
|
237
|
+
The status and status text are kept. `Vary: Accept-Encoding` is added to
|
|
238
|
+
**every** response whose type is compressible, compressed or not — a small
|
|
239
|
+
one, a 404, a `HEAD` — so a cache never serves the compressed body to a
|
|
240
|
+
client that did not ask for it. An existing `Vary` keeps its names, and
|
|
241
|
+
`Vary: *` is left as it is.
|
|
242
|
+
|
|
243
|
+
The weak `ETag` comes back in `If-None-Match` as `W/"v1"`; compare it
|
|
244
|
+
weakly:
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
app.get('/doc', ({ request, reply }) => {
|
|
248
|
+
const etag = '"v1"';
|
|
249
|
+
const match = request.headers.get('if-none-match')?.replace(/^W\//, '');
|
|
250
|
+
return match === etag ? reply(304) : reply(200, document, { headers: { etag } });
|
|
251
|
+
});
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
## Order with other middlewares
|
|
255
|
+
|
|
256
|
+
Middlewares nest: the first `use` is the outermost. On the way out, a
|
|
257
|
+
middleware sees the response the ones after it returned. So `compress()`
|
|
258
|
+
reads the headers as the middlewares **after** it left them, and the ones
|
|
259
|
+
**before** it see the compressed response.
|
|
260
|
+
|
|
261
|
+
```ts
|
|
262
|
+
import { alxia, defineMiddleware, settle, withHeaders } from '@softistx/alxia';
|
|
263
|
+
import { compress } from '@softistx/alxia-compress';
|
|
264
|
+
|
|
265
|
+
// after compress(): its Cache-Control is read when compress() decides
|
|
266
|
+
const noTransformRaw = defineMiddleware(async (ctx, next) => {
|
|
267
|
+
const response = await settle(ctx, next());
|
|
268
|
+
return new URL(ctx.request.url).pathname.startsWith('/raw/')
|
|
269
|
+
? withHeaders(response, (headers) => headers.set('cache-control', 'no-transform'))
|
|
270
|
+
: response;
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
// before compress(): sees Content-Encoding, and no Content-Length on a compressed body
|
|
274
|
+
const log = defineMiddleware(async (ctx, next) => {
|
|
275
|
+
const response = await settle(ctx, next());
|
|
276
|
+
console.log(ctx.request.method, ctx.request.url, response.status, response.headers.get('content-encoding') ?? 'identity');
|
|
277
|
+
return response;
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
const app = alxia()
|
|
281
|
+
.use(log)
|
|
282
|
+
.use(compress())
|
|
283
|
+
.use(noTransformRaw);
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Declare `compress()` before every middleware that sets `Content-Type`,
|
|
287
|
+
`Cache-Control` or `Content-Encoding` on the way out, and after every one
|
|
288
|
+
that logs or measures what is sent (`logger()`, `secureHeaders()`, `cors()`).
|
|
289
|
+
`settle(ctx, next())` makes a middleware see the final response, a 404's
|
|
290
|
+
or an error's included; see
|
|
291
|
+
[Middlewares](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/middleware.md).
|
|
292
|
+
|
|
293
|
+
## A realistic app
|
|
294
|
+
|
|
295
|
+
An API, a built front end whose bundler already wrote `.br` and `.gz`
|
|
296
|
+
copies, and an event stream — compressed where it pays, and nowhere else:
|
|
297
|
+
|
|
298
|
+
```ts
|
|
299
|
+
import { alxia, eventStream, responds } from '@softistx/alxia';
|
|
300
|
+
import { compress } from '@softistx/alxia-compress';
|
|
301
|
+
import { z } from 'zod';
|
|
302
|
+
|
|
303
|
+
const Tick = z.object({ at: z.number() });
|
|
304
|
+
|
|
305
|
+
const app = alxia()
|
|
306
|
+
.use(compress({ encodings: ['zstd', 'br', 'gzip'] }))
|
|
307
|
+
.get('/api/products', ({ reply }) => reply(200, products)) // JSON: compressed over 1 KiB
|
|
308
|
+
.get('/api/ticks', responds({ 200: eventStream(Tick) }), ({ reply }) =>
|
|
309
|
+
reply(
|
|
310
|
+
200,
|
|
311
|
+
(async function* () {
|
|
312
|
+
yield { at: Date.now() }; // text/event-stream: left alone by default
|
|
313
|
+
})(),
|
|
314
|
+
),
|
|
315
|
+
)
|
|
316
|
+
.static('/', './dist', {
|
|
317
|
+
fallback: 'index.html',
|
|
318
|
+
precompressed: ['br', 'gzip'], // app.js.br is served as it is
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
app.listen(3000);
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
A file `static` serves without a precompressed copy — `index.html`, an SVG
|
|
325
|
+
— is compressed on the fly when it is at least
|
|
326
|
+
[`threshold`](#threshold) bytes, and sent without `Accept-Ranges`; one
|
|
327
|
+
with a copy keeps its `Content-Encoding` and is left alone; a range
|
|
328
|
+
request answered 206 is never compressed.
|
|
329
|
+
|
|
330
|
+
## Testing it
|
|
331
|
+
|
|
332
|
+
`app.request` runs the app in process, so the encoding can be asserted and
|
|
333
|
+
the body decoded with `node:zlib`:
|
|
334
|
+
|
|
335
|
+
```ts
|
|
336
|
+
import { expect, test } from 'bun:test';
|
|
337
|
+
import { brotliDecompressSync, gunzipSync } from 'node:zlib';
|
|
338
|
+
import { alxia } from '@softistx/alxia';
|
|
339
|
+
import { compress } from '@softistx/alxia-compress';
|
|
340
|
+
|
|
341
|
+
const big = 'alxia '.repeat(1000);
|
|
342
|
+
const app = alxia()
|
|
343
|
+
.use(compress())
|
|
344
|
+
.get('/big', ({ reply }) => reply(200, { text: big }));
|
|
345
|
+
|
|
346
|
+
const get = (encoding: string) => app.request('/big', { headers: { 'accept-encoding': encoding } });
|
|
347
|
+
|
|
348
|
+
test('gzip, then Brotli when the client prefers it', async () => {
|
|
349
|
+
const gzip = await get('gzip');
|
|
350
|
+
expect(gzip.headers.get('content-encoding')).toBe('gzip');
|
|
351
|
+
expect(gzip.headers.get('vary')).toBe('Accept-Encoding');
|
|
352
|
+
expect(JSON.parse(gunzipSync(new Uint8Array(await gzip.arrayBuffer())).toString()).text).toBe(big);
|
|
353
|
+
|
|
354
|
+
const br = await get('gzip;q=0.5, br');
|
|
355
|
+
expect(br.headers.get('content-encoding')).toBe('br');
|
|
356
|
+
expect(JSON.parse(brotliDecompressSync(new Uint8Array(await br.arrayBuffer())).toString()).text).toBe(big);
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
test('identity only: sent as it is', async () => {
|
|
360
|
+
expect((await get('identity')).headers.get('content-encoding')).toBeNull();
|
|
361
|
+
});
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
## `negotiate(accept, offered)`
|
|
365
|
+
|
|
366
|
+
The choice `compress()` makes, exported for a handler or a middleware that
|
|
367
|
+
encodes on its own — a file it caches per encoding, a proxy:
|
|
368
|
+
|
|
369
|
+
```ts
|
|
370
|
+
import { negotiate } from '@softistx/alxia-compress';
|
|
371
|
+
|
|
372
|
+
negotiate('gzip, deflate, br, zstd', ['zstd', 'br', 'gzip']); // 'zstd'
|
|
373
|
+
negotiate('gzip;q=1, br;q=0.8', ['br', 'gzip']); // 'gzip'
|
|
374
|
+
negotiate('*', ['gzip']); // 'gzip'
|
|
375
|
+
negotiate('*, gzip;q=0', ['gzip', 'br']); // 'br'
|
|
376
|
+
negotiate('br;q=0', ['br']); // undefined
|
|
377
|
+
negotiate('identity', ['gzip']); // undefined
|
|
378
|
+
negotiate(null, ['gzip']); // undefined
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
- `accept` is the raw `Accept-Encoding`, or `null` when the request has
|
|
382
|
+
none: `request.headers.get('accept-encoding')`.
|
|
383
|
+
- Names are compared case-insensitively. A missing `q` is 1; a `q` that is
|
|
384
|
+
not a number is 0.
|
|
385
|
+
- `*` stands for every encoding the header does not name; an encoding named
|
|
386
|
+
with `q=0` is refused even under `*`.
|
|
387
|
+
- The highest `q` wins; on a tie, the first in `offered`.
|
|
388
|
+
- `undefined` means send the body as it is.
|
|
389
|
+
|
|
390
|
+
Something not behaving as described here: see
|
|
391
|
+
[Troubleshooting](troubleshooting.md).
|
package/docs/roadmap.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Roadmap
|
|
2
|
+
|
|
3
|
+
What `@softistx/alxia-compress` gives an app, and what is coming. This page is a
|
|
4
|
+
direction, not a commitment: the version something shipped in is the only
|
|
5
|
+
number on it. Every release, with each change it made, is in
|
|
6
|
+
[`CHANGELOG.md`](https://github.com/softistx/alxia/blob/develop/packages/compress/CHANGELOG.md).
|
|
7
|
+
|
|
8
|
+
## Now
|
|
9
|
+
|
|
10
|
+
- **Moving to the `@softistx` scope.** The package is now `@softistx/alxia-compress` (it was `@alxia/compress`). Same code and API; replace the dependency and the imports ([migration guide](https://github.com/softistx/alxia/blob/develop/packages/core/docs/guide/migrating-from-alxia-scope.md)). The old name is deprecated.
|
|
11
|
+
|
|
12
|
+
## Next
|
|
13
|
+
|
|
14
|
+
Nothing scheduled yet.
|
|
15
|
+
|
|
16
|
+
## Later
|
|
17
|
+
|
|
18
|
+
Nothing scheduled yet.
|
|
19
|
+
|
|
20
|
+
## Not planned
|
|
21
|
+
|
|
22
|
+
- **A runtime dependency.** `@softistx/alxia-compress` installs nothing beside its
|
|
23
|
+
`@softistx/alxia` peer: zstd, gzip and deflate come from the runtime's
|
|
24
|
+
`CompressionStream`, and Brotli and every streamed body from `node:zlib`,
|
|
25
|
+
so adding it to an app adds no native binding or transitive package to
|
|
26
|
+
audit or update.
|
|
27
|
+
|
|
28
|
+
## Shipped
|
|
29
|
+
|
|
30
|
+
### 0.3.0
|
|
31
|
+
|
|
32
|
+
- **Compression as a middleware.** `app.use(compress())` compresses every
|
|
33
|
+
response that comes back through it, a 404's and an error's included;
|
|
34
|
+
`app.plugin(compress())`, its deprecated alias, was removed in 0.5.
|
|
35
|
+
|
|
36
|
+
### 0.1.0
|
|
37
|
+
|
|
38
|
+
- **Compression as a plugin**, the 0.1 form. `compress()` streams every response
|
|
39
|
+
worth it through zstd, Brotli, gzip or deflate, chosen from the client's
|
|
40
|
+
`Accept-Encoding` and the server's order of preference, with the app's
|
|
41
|
+
routes and type unchanged.
|
|
42
|
+
- **Only what pays.** Text, JSON, JavaScript, XML and SVG of at least 1 KiB
|
|
43
|
+
by default — files included — with the encodings, the threshold and the
|
|
44
|
+
types compressed as options. An event stream (unless `compressible` lets
|
|
45
|
+
it in), a `HEAD`, a 204, 206 or 304, a response already encoded — a
|
|
46
|
+
precompressed static file — or one marked `Cache-Control: no-transform`
|
|
47
|
+
is sent as it is. Brotli runs at quality 4, near gzip's speed, rather
|
|
48
|
+
than the ahead-of-time default of 11.
|
|
49
|
+
- **Streamed bodies flushed as they come.** A body with no
|
|
50
|
+
`Content-Length` — a server-rendered page, a `ReadableStream`, an event
|
|
51
|
+
stream that `compressible` lets in — is flushed after the chunks of each
|
|
52
|
+
turn of the event loop, in all four encodings, so a page's shell reaches
|
|
53
|
+
the browser at once instead of with its last deferred part. A body with a
|
|
54
|
+
length is compressed whole, as before.
|
|
55
|
+
- **Cache-safe headers.** `Vary: Accept-Encoding` on every compressible
|
|
56
|
+
response, a strong `ETag` made weak, and no stale `Content-Length` or
|
|
57
|
+
`Accept-Ranges`.
|
|
58
|
+
- **`negotiate`.** The same choice of encoding, exported for a handler or a
|
|
59
|
+
plugin that encodes on its own.
|
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
# Troubleshooting
|
|
2
|
+
|
|
3
|
+
`@softistx/alxia-compress` throws nothing of its own: a mistake is either a
|
|
4
|
+
TypeScript error, or a response that is not encoded the way you expected.
|
|
5
|
+
Each entry is headed by the text you see — what `tsc` prints, or the
|
|
6
|
+
header you read in the response.
|
|
7
|
+
|
|
8
|
+
**Types**
|
|
9
|
+
|
|
10
|
+
- [`Type '"identity"' is not assignable to type 'Encoding'`](#type-identity-is-not-assignable-to-type-encoding)
|
|
11
|
+
- [`Type 'RegExp' is not assignable to type '(type: string) => boolean'`](#type-regexp-is-not-assignable-to-type-type-string--boolean)
|
|
12
|
+
- [`Type 'CompressMiddleware' is not assignable to type '"this looks like a factory given uncalled: call it, as use(cors()) and not use(cors)"'`](#type-compressmiddleware-is-not-assignable-to-type-this-looks-like-a-factory-given-uncalled-call-it-as-usecors-and-not-usecors)
|
|
13
|
+
|
|
14
|
+
**Responses**
|
|
15
|
+
|
|
16
|
+
- [No `Content-Encoding` on a response](#no-content-encoding-on-a-response)
|
|
17
|
+
- [`Content-Encoding: gzip` on a tiny body, larger than the original](#content-encoding-gzip-on-a-tiny-body-larger-than-the-original)
|
|
18
|
+
- [`Cache-Control: no-transform` and `Content-Encoding` on the same response](#cache-control-no-transform-and-content-encoding-on-the-same-response)
|
|
19
|
+
- [A streamed page or server-sent events arrive late and in bursts](#a-streamed-page-or-server-sent-events-arrive-late-and-in-bursts)
|
|
20
|
+
- [A streamed body is larger compressed than the same body sent whole](#a-streamed-body-is-larger-compressed-than-the-same-body-sent-whole)
|
|
21
|
+
- [`ETag: W/"…"` where the handler set `"…"`](#etag-w-where-the-handler-set-)
|
|
22
|
+
- [No `Content-Length` on a compressed response](#no-content-length-on-a-compressed-response)
|
|
23
|
+
- [No `Accept-Ranges: bytes` on a compressed file](#no-accept-ranges-bytes-on-a-compressed-file)
|
|
24
|
+
- [`Vary: Accept-Encoding` on a response that is not compressed](#vary-accept-encoding-on-a-response-that-is-not-compressed)
|
|
25
|
+
|
|
26
|
+
## Types
|
|
27
|
+
|
|
28
|
+
### `Type '"identity"' is not assignable to type 'Encoding'`
|
|
29
|
+
|
|
30
|
+
**When:** `encodings` names something other than `zstd`, `br`, `gzip` or
|
|
31
|
+
`deflate`.
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
error TS2322: Type '"identity"' is not assignable to type 'Encoding'.
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The same message comes for `'brotli'`, `'x-gzip'` or `'compress'`.
|
|
38
|
+
|
|
39
|
+
**Why:** `encodings` lists what the middleware can produce, by the token that
|
|
40
|
+
goes in `Content-Encoding`. `identity` is not an encoding to offer — it is
|
|
41
|
+
what a client gets when none is chosen — and Brotli's token is `br`.
|
|
42
|
+
|
|
43
|
+
**Fix:** use the tokens, and leave `identity` out:
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
app.use(compress({ encodings: ['br', 'gzip'] }));
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### `Type 'RegExp' is not assignable to type '(type: string) => boolean'`
|
|
50
|
+
|
|
51
|
+
**When:** `compressible` is given a regular expression.
|
|
52
|
+
|
|
53
|
+
```text
|
|
54
|
+
error TS2322: Type 'RegExp' is not assignable to type '(type: string) => boolean'.
|
|
55
|
+
Type 'RegExp' provides no match for the signature '(type: string): boolean'.
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**Why:** `compressible` is a function of the `Content-Type`.
|
|
59
|
+
|
|
60
|
+
**Fix:** wrap the expression:
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
app.use(compress({ compressible: (type) => /json|text\//.test(type) }));
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### `Type 'CompressMiddleware' is not assignable to type '"this looks like a factory given uncalled: call it, as use(cors()) and not use(cors)"'`
|
|
67
|
+
|
|
68
|
+
```text
|
|
69
|
+
error TS2345: Argument of type '(options?: CompressOptions | undefined) => CompressMiddleware' is not assignable to parameter of type '…'.
|
|
70
|
+
…
|
|
71
|
+
Type 'CompressMiddleware' is not assignable to type '"this looks like a factory given uncalled: call it, as use(cors()) and not use(cors)"'.
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
**When:** `app.use(compress)`, the factory given uncalled. The message names
|
|
75
|
+
`cors` as its example, whichever factory it is. It also throws where it is
|
|
76
|
+
declared, since alxia 0.5, rather than answering each request with a 500:
|
|
77
|
+
|
|
78
|
+
```text
|
|
79
|
+
TypeError: use(): argument 1 looks like a factory (compress): call it, use(compress())
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Why:** `compress` makes the middleware; it is not the middleware. A
|
|
83
|
+
function that returns a function is no middleware, and `compress` is marked
|
|
84
|
+
as a factory, so `use`, a route and `plugin` refuse it.
|
|
85
|
+
|
|
86
|
+
**Fix:** call it, with no options for the defaults:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
app.use(compress());
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Responses
|
|
93
|
+
|
|
94
|
+
### No `Content-Encoding` on a response
|
|
95
|
+
|
|
96
|
+
**When:** a response you expected compressed arrives as it is.
|
|
97
|
+
|
|
98
|
+
**Why:** one of these holds:
|
|
99
|
+
|
|
100
|
+
| Check | How to see it |
|
|
101
|
+
| --- | --- |
|
|
102
|
+
| the request sent no `Accept-Encoding`, only `identity`, or none of `encodings` | `curl` sends none unless given `--compressed`; `fetch` in a test sends what you pass |
|
|
103
|
+
| the `Content-Type` is not compressible | images, fonts, archives, `application/octet-stream`, `text/event-stream`; see [`compressible`](guide.md#compressible) |
|
|
104
|
+
| the request is a `HEAD`, or the status is 204, 206 or 304 | a range request answers 206 |
|
|
105
|
+
| the response already has a `Content-Encoding` | a precompressed file from `static(…, { precompressed })` |
|
|
106
|
+
| its `Cache-Control` holds `no-transform` | |
|
|
107
|
+
| its `Content-Length` is under `threshold` (1024 by default) | a short JSON error, a small string, a small file from `static` or `file` |
|
|
108
|
+
| `compress()` does not run for this route | it was given to `use` on another app, not at all, or after the route: a route declared before `app.use(compress())` is not compressed |
|
|
109
|
+
|
|
110
|
+
**Fix:** ask for an encoding to check the middleware works:
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
curl -s -D - -o /dev/null -H 'accept-encoding: gzip' localhost:3000/report
|
|
114
|
+
# Vary: Accept-Encoding
|
|
115
|
+
# Content-Encoding: gzip
|
|
116
|
+
# Transfer-Encoding: chunked
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
then lower `threshold` or widen `compressible` if the response is one you
|
|
120
|
+
want compressed:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
app.use(compress({ threshold: 256 }));
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
### `Content-Encoding: gzip` on a tiny body, larger than the original
|
|
127
|
+
|
|
128
|
+
**When:** a `ReadableStream` of a few bytes comes back compressed, and
|
|
129
|
+
its compressed size is larger than the original (a 2-byte stream becomes
|
|
130
|
+
22 bytes of gzip).
|
|
131
|
+
|
|
132
|
+
**Why:** `threshold` is read from `Content-Length`. A stream has none when
|
|
133
|
+
the middleware sees it, so its size is unknown and it is compressed whatever it is.
|
|
134
|
+
A string, JSON or binary body — a file included — has one, and is measured.
|
|
135
|
+
|
|
136
|
+
**Fix:** for a stream that is always small, mark it, or send it as a
|
|
137
|
+
string or a `Blob` instead:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
app.get('/ping', ({ reply }) => reply(200, smallStream, { headers: { 'content-type': 'text/plain', 'cache-control': 'no-transform' } }));
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### `Cache-Control: no-transform` and `Content-Encoding` on the same response
|
|
144
|
+
|
|
145
|
+
**When:** a middleware sets `Cache-Control: no-transform`, and the response is
|
|
146
|
+
compressed anyway.
|
|
147
|
+
|
|
148
|
+
**Why:** middlewares nest, and the first one declared is the outermost. A
|
|
149
|
+
middleware declared **before** `compress()` sets its header on the way out,
|
|
150
|
+
after `compress()` has already decided. Every middleware before it also sees
|
|
151
|
+
the compressed body: one that reads or measures the body reads the encoded
|
|
152
|
+
bytes.
|
|
153
|
+
|
|
154
|
+
**Fix:** declare the middlewares that set `Cache-Control`, `Content-Type` or
|
|
155
|
+
`Content-Encoding` after `compress()`, and those that log before it:
|
|
156
|
+
|
|
157
|
+
```ts
|
|
158
|
+
import { alxia, defineMiddleware, settle, withHeaders } from '@softistx/alxia';
|
|
159
|
+
import { compress } from '@softistx/alxia-compress';
|
|
160
|
+
|
|
161
|
+
const noTransform = defineMiddleware(async (ctx, next) =>
|
|
162
|
+
withHeaders(await settle(ctx, next()), (headers) => headers.set('cache-control', 'no-transform')),
|
|
163
|
+
);
|
|
164
|
+
|
|
165
|
+
const app = alxia()
|
|
166
|
+
.use(compress())
|
|
167
|
+
.use(noTransform);
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
A `Cache-Control` set by the handler itself (`reply(200, body, { headers })`
|
|
171
|
+
or `set.headers`) is always seen.
|
|
172
|
+
|
|
173
|
+
### A streamed page or server-sent events arrive late and in bursts
|
|
174
|
+
|
|
175
|
+
**When:** a server-rendered page's shell, or the events of an event stream
|
|
176
|
+
that `compressible` lets in, reach the client only when later chunks push
|
|
177
|
+
them out, or when the stream ends.
|
|
178
|
+
|
|
179
|
+
**Why:** not the middleware. A body with no `Content-Length` is flushed after
|
|
180
|
+
the chunks of each turn of the event loop, in every encoding: see
|
|
181
|
+
[Streamed bodies](guide.md#streamed-bodies). An earlier `@softistx/alxia-compress`
|
|
182
|
+
held a stream in the codec until a block filled, and the default
|
|
183
|
+
`compressible` left event streams out for that reason; it still leaves
|
|
184
|
+
them out, now because events are small. What holds a stream back now is
|
|
185
|
+
outside the middleware:
|
|
186
|
+
|
|
187
|
+
| Cause | How to see it |
|
|
188
|
+
| --- | --- |
|
|
189
|
+
| a proxy in front of the server buffers the response | the delay is gone with `curl -N` against the server itself; nginx honours the `X-Accel-Buffering: no` that alxia sets on an event stream, not on a page |
|
|
190
|
+
| a middleware before `compress()` reads the body, as `await response.text()` does, and answers a new one | the middleware's response has a `Content-Length` |
|
|
191
|
+
| the response has a `Content-Length` | a body with one is compressed whole; a stream handed to `reply` has none |
|
|
192
|
+
| the renderer waits for everything before it writes | React Router's default entry waits for `allReady` when the user agent looks like a bot, as Bun's default user agent does: send a browser's |
|
|
193
|
+
|
|
194
|
+
**Fix:** check the server alone first, and decode as it comes:
|
|
195
|
+
|
|
196
|
+
```sh
|
|
197
|
+
curl -N -s -H 'accept-encoding: gzip' localhost:3000/page | gunzip
|
|
198
|
+
# the shell prints at once, the deferred part after it
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
### A streamed body is larger compressed than the same body sent whole
|
|
202
|
+
|
|
203
|
+
**When:** a `ReadableStream` that yields many small chunks, each in a turn
|
|
204
|
+
of its own — a row at a time from a cursor, a token at a time — comes out
|
|
205
|
+
much larger than the same text compressed in one piece: on a 41 KB page
|
|
206
|
+
of 308 small chunks, 56% larger in gzip and deflate, and 89–94% in br and
|
|
207
|
+
zstd.
|
|
208
|
+
|
|
209
|
+
**Why:** a streamed body is flushed after each turn of the event loop, so
|
|
210
|
+
what the source yields leaves at once. Each flush ends a block, and a
|
|
211
|
+
block costs bytes. Chunks yielded in the same turn share one flush, which
|
|
212
|
+
costs almost nothing: the same page written in three turns came out within
|
|
213
|
+
2% of the whole.
|
|
214
|
+
|
|
215
|
+
**Fix:** batch in the source what has no reason to leave alone, or, for a
|
|
216
|
+
body that need not stream, send it with a length:
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
// a row at a time, batched by 100 before it is yielded
|
|
220
|
+
async function* batched(rows: AsyncIterable<string>) {
|
|
221
|
+
let batch = '';
|
|
222
|
+
let count = 0;
|
|
223
|
+
for await (const row of rows) {
|
|
224
|
+
batch += row;
|
|
225
|
+
if (++count % 100 === 0) {
|
|
226
|
+
yield batch;
|
|
227
|
+
batch = '';
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (batch !== '') yield batch;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
app.get('/report', async ({ reply }) =>
|
|
234
|
+
reply(200, ReadableStream.from(batched(rows())).pipeThrough(new TextEncoderStream()), {
|
|
235
|
+
headers: { 'content-type': 'text/csv' },
|
|
236
|
+
}),
|
|
237
|
+
);
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
### `ETag: W/"…"` where the handler set `"…"`
|
|
241
|
+
|
|
242
|
+
**When:** a handler sets a strong `ETag`, the client receives it weak, and
|
|
243
|
+
a comparison with `If-None-Match` never matches.
|
|
244
|
+
|
|
245
|
+
**Why:** a strong ETag promises the same bytes, and the compressed bytes
|
|
246
|
+
differ from the uncompressed ones, so the middleware weakens it. The client
|
|
247
|
+
then sends `If-None-Match: W/"…"`.
|
|
248
|
+
|
|
249
|
+
**Fix:** compare the tag weakly, ignoring the `W/` prefix:
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
const match = request.headers.get('if-none-match')?.replace(/^W\//, '');
|
|
253
|
+
if (match === etag) return reply(304);
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### No `Content-Length` on a compressed response
|
|
257
|
+
|
|
258
|
+
**When:** a client, a proxy or a test expects a `Content-Length`.
|
|
259
|
+
|
|
260
|
+
**Why:** the body is compressed as it is streamed, so its final size is not
|
|
261
|
+
known when the headers leave; the header is removed rather than left
|
|
262
|
+
wrong, and the response is sent chunked.
|
|
263
|
+
|
|
264
|
+
**Fix:** read the body to know its size; to keep a `Content-Length` on a
|
|
265
|
+
response, keep it out of compression:
|
|
266
|
+
|
|
267
|
+
```ts
|
|
268
|
+
reply(200, body, { headers: { 'cache-control': 'no-transform' } });
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### No `Accept-Ranges: bytes` on a compressed file
|
|
272
|
+
|
|
273
|
+
**When:** a file served by `static` or `file` carries `Accept-Ranges:
|
|
274
|
+
bytes` when fetched without `Accept-Encoding`, and none when it comes back
|
|
275
|
+
compressed.
|
|
276
|
+
|
|
277
|
+
**Why:** a byte range of the encoded body is not a range of the file, so
|
|
278
|
+
the middleware removes the header rather than advertise ranges of a body that
|
|
279
|
+
is not the one sent. A request that carries `Range` is answered 206 with
|
|
280
|
+
the slice, uncompressed: the middleware never compresses a 206.
|
|
281
|
+
|
|
282
|
+
**Fix:** nothing to fix: a client that seeks sends `Range` and gets the
|
|
283
|
+
slice. To keep `Accept-Ranges` on every response for a file type, keep it
|
|
284
|
+
out of compression:
|
|
285
|
+
|
|
286
|
+
```ts
|
|
287
|
+
// The default test, as the guide's `compressible` section spells it.
|
|
288
|
+
const defaults = /^(text\/(?!event-stream)|application\/(.+\+)?(json|javascript|xml)|image\/svg\+xml)/i;
|
|
289
|
+
|
|
290
|
+
app.use(compress({ compressible: (type) => defaults.test(type) && !type.startsWith('text/csv') }));
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
### `Vary: Accept-Encoding` on a response that is not compressed
|
|
294
|
+
|
|
295
|
+
**When:** a small response, a 404, a `HEAD`, or a request with no
|
|
296
|
+
`Accept-Encoding` carries `Vary: Accept-Encoding`.
|
|
297
|
+
|
|
298
|
+
**Why:** this is on purpose. The same URL is compressed for a client that
|
|
299
|
+
accepts it, so a cache must key the response on `Accept-Encoding` whether
|
|
300
|
+
this copy was compressed or not. It is added to every response whose type
|
|
301
|
+
is compressible.
|
|
302
|
+
|
|
303
|
+
**Fix:** nothing to fix. A response whose type is not compressible gets no
|
|
304
|
+
`Vary` from the middleware.
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@softistx/alxia-compress",
|
|
3
|
+
"version": "0.4.1",
|
|
4
|
+
"description": "Response compression for alxia: zstd, Brotli, gzip and deflate, negotiated, streamed, with no dependency",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"docs",
|
|
12
|
+
"README.md",
|
|
13
|
+
"package.json",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"repository": {
|
|
25
|
+
"type": "git",
|
|
26
|
+
"url": "git+https://github.com/softistx/alxia.git",
|
|
27
|
+
"directory": "packages/compress"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"registry": "https://registry.npmjs.org",
|
|
31
|
+
"access": "restricted"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "bun run ../../build.ts",
|
|
35
|
+
"test": "bun test src",
|
|
36
|
+
"typecheck": "tsc --noEmit"
|
|
37
|
+
},
|
|
38
|
+
"alxia": {
|
|
39
|
+
"entrypoints": [
|
|
40
|
+
"src/index.ts"
|
|
41
|
+
]
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@softistx/alxia": "^0.29.0",
|
|
45
|
+
"@types/bun": "^1.4.5",
|
|
46
|
+
"zod": "^4.2.0"
|
|
47
|
+
},
|
|
48
|
+
"peerDependencies": {
|
|
49
|
+
"@softistx/alxia": "^0.29.0",
|
|
50
|
+
"typescript": "^6.0.3 || ^7.0.0"
|
|
51
|
+
}
|
|
52
|
+
}
|