diff --git a/README.md b/README.md
index 5d6dcd5f4..bdaa2600a 100644
--- a/README.md
+++ b/README.md
@@ -102,11 +102,11 @@ the user's WIT world:
- `logging`: enables the `wasi:logging` import to be used for the JavaScript `console` API
- `sqlite`: enables the `node:sqlite` module with an embedded SQLite database engine
-- `crypto`, `crypto-full`, `zlib`, `brotli`, `encoding`, `timezone`, `websocket` and `golem`
+- `crypto`, `crypto-full`, `zlib`, `brotli`, `zstd`, `encoding`, `timezone`, `websocket` and `golem`
enable the corresponding builtin capabilities
The default `normal-p3` tier enables `logging`, `crypto`, `zlib` and `encoding`; `full-p3` adds
-`crypto-full`, `brotli`, `sqlite` and `timezone`, and `full-no-logging-p3` is `full-p3` without
+`crypto-full`, `brotli`, `zstd`, `sqlite` and `timezone`, and `full-no-logging-p3` is `full-p3` without
`logging`. `fetch` and `node:http` always use `wasi:http`. Keep the `p3` feature in custom feature
lists: it enables the `wit-bindgen-p3` dependency, which a `--dependency wit-bindgen-p3=...`
replacement must therefore declare with `optional = true`.
@@ -1336,11 +1336,17 @@ throws immediately. Environment-data APIs are unavailable.
node:zlib
-- **Classes:** `Deflate`, `Inflate`, `Gzip`, `Gunzip`, `DeflateRaw`, `InflateRaw`, `Unzip`, `BrotliCompress`, `BrotliDecompress`
-- **Factory:** `createGzip`, `createGunzip`, `createDeflate`, `createInflate`, `createDeflateRaw`, `createInflateRaw`, `createUnzip`, `createBrotliCompress`, `createBrotliDecompress`
-- **Async:** `gzip`, `gunzip`, `deflate`, `inflate`, `deflateRaw`, `inflateRaw`, `unzip`, `brotliCompress`, `brotliDecompress`
-- **Sync:** `gzipSync`, `gunzipSync`, `deflateSync`, `inflateSync`, `deflateRawSync`, `inflateRawSync`, `unzipSync`, `brotliCompressSync`, `brotliDecompressSync`
+- **Classes:** `Deflate`, `Inflate`, `Gzip`, `Gunzip`, `DeflateRaw`, `InflateRaw`, `Unzip`, `BrotliCompress`, `BrotliDecompress`, `ZstdCompress`, `ZstdDecompress`
+- **Factory:** `createGzip`, `createGunzip`, `createDeflate`, `createInflate`, `createDeflateRaw`, `createInflateRaw`, `createUnzip`, `createBrotliCompress`, `createBrotliDecompress`, `createZstdCompress`, `createZstdDecompress`
+- **Async:** `gzip`, `gunzip`, `deflate`, `inflate`, `deflateRaw`, `inflateRaw`, `unzip`, `brotliCompress`, `brotliDecompress`, `zstdCompress`, `zstdDecompress`
+- **Sync:** `gzipSync`, `gunzipSync`, `deflateSync`, `inflateSync`, `deflateRawSync`, `inflateRawSync`, `unzipSync`, `brotliCompressSync`, `brotliDecompressSync`, `zstdCompressSync`, `zstdDecompressSync`
- `crc32`, `constants`, `codes`
+- Zstandard constants are available through `constants` and direct `ZSTD_*` aliases on the default/CommonJS export.
+- Zstandard requires the optional `zstd` feature (included in the full tiers). It uses the reference
+ zstd codec with worker threads disabled for WASI; `normal-p3` does not include that codec.
+ The APIs remain discoverable without the feature, but calls throw `ERR_ZLIB_INITIALIZATION_FAILED`.
+ This generic initialization error can also indicate invalid codec parameters; check the build's
+ enabled features before diagnosing a parameter failure.
diff --git a/crates/wasm-rquickjs/skeleton/Cargo.lock b/crates/wasm-rquickjs/skeleton/Cargo.lock
index 86b657a9e..cba0f979f 100644
--- a/crates/wasm-rquickjs/skeleton/Cargo.lock
+++ b/crates/wasm-rquickjs/skeleton/Cargo.lock
@@ -326,6 +326,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"
dependencies = [
"find-msvc-tools",
+ "jobserver",
+ "libc",
"shlex 2.0.1",
]
@@ -1407,6 +1409,16 @@ version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+[[package]]
+name = "jobserver"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
+dependencies = [
+ "getrandom 0.3.4",
+ "libc",
+]
+
[[package]]
name = "js-sys"
version = "0.3.103"
@@ -2178,6 +2190,7 @@ dependencies = [
"wasip3",
"whirlpool",
"wit-bindgen 0.63.0",
+ "zstd-safe",
]
[[package]]
@@ -3744,3 +3757,22 @@ name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+
+[[package]]
+name = "zstd-safe"
+version = "7.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.0.16+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
diff --git a/crates/wasm-rquickjs/skeleton/Cargo.toml_ b/crates/wasm-rquickjs/skeleton/Cargo.toml_
index 00e4ce4fe..2ee319fc1 100644
--- a/crates/wasm-rquickjs/skeleton/Cargo.toml_
+++ b/crates/wasm-rquickjs/skeleton/Cargo.toml_
@@ -38,13 +38,14 @@ internal-test-execution = ["test-observability"]
# Capability tiers (cumulative). The runtime ships its own `wasi:http@0.3` based fetch and
# node:http unconditionally.
normal-p3 = ["p3", "crypto", "zlib", "logging", "encoding"]
-full-p3 = ["normal-p3", "crypto-full", "brotli", "sqlite", "timezone"]
-full-no-logging-p3 = ["p3", "crypto", "zlib", "encoding", "crypto-full", "brotli", "sqlite", "timezone"]
+full-p3 = ["normal-p3", "crypto-full", "brotli", "zstd", "sqlite", "timezone"]
+full-no-logging-p3 = ["p3", "crypto", "zlib", "encoding", "crypto-full", "brotli", "zstd", "sqlite", "timezone"]
logging = ["dep:wasi-logging"]
encoding = ["dep:encoding_rs"]
zlib = ["dep:flate2", "dep:crc32fast"]
brotli = ["dep:brotli"]
+zstd = ["zlib", "dep:zstd-safe"]
# Crypto: common subset
crypto = [
@@ -159,6 +160,7 @@ sec1 = { version = "0.8", default-features = false, features = ["der", "alloc",
base64ct = { version = "1", features = ["alloc"] }
flate2 = { version = "1", default-features = false, features = ["rust_backend"], optional = true }
brotli = { version = "7", default-features = false, features = ["std"], optional = true }
+zstd-safe = { version = "7.2.4", default-features = false, features = ["std"], optional = true }
crc32fast = { version = "1", optional = true }
# WASI Preview 2 bindings for the residual synchronous interfaces (see the `p3` feature).
wasip2 = "1.0"
diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js
index 1a8ea2900..b081034d5 100644
--- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js
+++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.js
@@ -1,5 +1,5 @@
// node:zlib implementation
-import { Transform } from 'node:stream';
+import { Transform, addAbortSignal } from 'node:stream';
import { Buffer } from 'node:buffer';
import bufferModule from 'node:buffer';
import {
@@ -17,6 +17,10 @@ import {
brotli_stream_push,
brotli_stream_pull,
brotli_stream_close,
+ zstd_stream_new,
+ zstd_stream_push,
+ zstd_stream_reset,
+ zstd_stream_close,
} from '__wasm_rquickjs_builtin/zlib_native';
const setPrototypeOf = Object.setPrototypeOf;
@@ -46,6 +50,8 @@ const getDataViewByteLength = Function.prototype.call.bind(
const getArrayBufferDetached = Function.prototype.call.bind(
Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'detached').get,
);
+const registerFinalizer = Function.prototype.call.bind(FinalizationRegistry.prototype.register);
+const unregisterFinalizer = Function.prototype.call.bind(FinalizationRegistry.prototype.unregister);
function bufferFromNativeBytes(bytes) {
setPrototypeOf(bytes, BufferPrototype);
@@ -193,7 +199,42 @@ const BROTLI_DECODER_ERROR_UNREACHABLE = -31;
const ZLIB_VERNUM = 4816;
+const zstdConstants = {
+ ZSTD_COMPRESS: 10, ZSTD_DECOMPRESS: 11,
+ ZSTD_e_continue: 0, ZSTD_e_flush: 1, ZSTD_e_end: 2,
+ ZSTD_fast: 1, ZSTD_dfast: 2, ZSTD_greedy: 3, ZSTD_lazy: 4, ZSTD_lazy2: 5,
+ ZSTD_btlazy2: 6, ZSTD_btopt: 7, ZSTD_btultra: 8, ZSTD_btultra2: 9,
+ ZSTD_c_compressionLevel: 100, ZSTD_c_windowLog: 101, ZSTD_c_hashLog: 102,
+ ZSTD_c_chainLog: 103, ZSTD_c_searchLog: 104, ZSTD_c_minMatch: 105,
+ ZSTD_c_targetLength: 106, ZSTD_c_strategy: 107,
+ ZSTD_c_enableLongDistanceMatching: 160, ZSTD_c_ldmHashLog: 161,
+ ZSTD_c_ldmMinMatch: 162, ZSTD_c_ldmBucketSizeLog: 163, ZSTD_c_ldmHashRateLog: 164,
+ ZSTD_c_contentSizeFlag: 200, ZSTD_c_checksumFlag: 201, ZSTD_c_dictIDFlag: 202,
+ ZSTD_c_nbWorkers: 400, ZSTD_c_jobSize: 401, ZSTD_c_overlapLog: 402,
+ ZSTD_d_windowLogMax: 100, ZSTD_CLEVEL_DEFAULT: 3,
+ ZSTD_error_no_error: 0, ZSTD_error_GENERIC: 1, ZSTD_error_prefix_unknown: 10,
+ ZSTD_error_version_unsupported: 12, ZSTD_error_frameParameter_unsupported: 14,
+ ZSTD_error_frameParameter_windowTooLarge: 16, ZSTD_error_corruption_detected: 20,
+ ZSTD_error_checksum_wrong: 22, ZSTD_error_literals_headerWrong: 24,
+ ZSTD_error_dictionary_corrupted: 30, ZSTD_error_dictionary_wrong: 32,
+ ZSTD_error_dictionaryCreation_failed: 34, ZSTD_error_parameter_unsupported: 40,
+ ZSTD_error_parameter_combination_unsupported: 41, ZSTD_error_parameter_outOfBound: 42,
+ ZSTD_error_tableLog_tooLarge: 44, ZSTD_error_maxSymbolValue_tooLarge: 46,
+ ZSTD_error_maxSymbolValue_tooSmall: 48, ZSTD_error_stabilityCondition_notRespected: 50,
+ ZSTD_error_stage_wrong: 60, ZSTD_error_init_missing: 62,
+ ZSTD_error_memory_allocation: 64, ZSTD_error_workSpace_tooSmall: 66,
+ ZSTD_error_dstSize_tooSmall: 70, ZSTD_error_srcSize_wrong: 72,
+ ZSTD_error_dstBuffer_null: 74, ZSTD_error_noForwardProgress_destFull: 80,
+ ZSTD_error_noForwardProgress_inputEmpty: 82,
+};
+
+const zstdErrorCodes = Object.create(null);
+for (const key of Object.keys(zstdConstants)) {
+ if (stringStartsWith(key, 'ZSTD_error_')) zstdErrorCodes[zstdConstants[key]] = key;
+}
+
export const constants = Object.freeze({
+ ...zstdConstants,
Z_NO_FLUSH,
Z_PARTIAL_FLUSH,
Z_SYNC_FLUSH,
@@ -1092,6 +1133,197 @@ export const Unzip = makeZlibWrapper(_Unzip);
export const BrotliCompress = makeZlibWrapper(_BrotliCompress);
export const BrotliDecompress = makeZlibWrapper(_BrotliDecompress);
+const zstdCleanup = new FinalizationRegistry(zstd_stream_close);
+
+class Zstd extends ZlibBase {
+ constructor(opts, decompress) {
+ opts = opts || {};
+ const params = [];
+ const seen = new Set();
+ for (const key of Object.keys(opts.params || {})) {
+ const number = +key;
+ if (!Number.isInteger(number) || number < 0 || number > (decompress ? 100 : 402) || seen.has(number)) {
+ throw makeRangeError('ERR_ZSTD_INVALID_PARAM', `${key} is not a valid zstd parameter`);
+ }
+ const value = opts.params[key];
+ if (typeof value !== 'number' && typeof value !== 'boolean') {
+ throw makeTypeError('ERR_INVALID_ARG_TYPE',
+ 'The "options.params[key]" property must be of type number.' + invalidArgTypeHelper(value));
+ }
+ if ((value | 0) !== -1) {
+ seen.add(number);
+ params.push([number, value | 0]);
+ }
+ }
+ const flush = opts.flush === undefined ? 0 : opts.flush;
+ const finishFlush = opts.finishFlush === undefined ? 2 : opts.finishFlush;
+ validateRangeInt(flush, 'options.flush', 0, 2);
+ validateRangeInt(finishFlush, 'options.finishFlush', 0, 2);
+ const chunkSize = opts.chunkSize;
+ if (chunkSize !== undefined) validateRangeInt(chunkSize, 'options.chunkSize', Z_MIN_CHUNK, _getKMaxLength());
+ if (opts.maxOutputLength !== undefined) validateRangeInt(opts.maxOutputLength, 'options.maxOutputLength', 1, _getKMaxLength());
+ const pledged = opts.pledgedSrcSize;
+ if (pledged !== undefined) {
+ if (typeof pledged !== 'number') throw makeTypeError('ERR_INVALID_ARG_TYPE', 'pledgedSrcSize must be a number');
+ if (pledged < 0) throw makeRangeError('ERR_OUT_OF_RANGE', 'pledgedSrcSize must be non-negative');
+ if (!Number.isSafeInteger(pledged)) throw makeRangeError('ERR_OUT_OF_RANGE', 'pledgedSrcSize must be a safe integer');
+ }
+ let dictionary = opts.dictionary;
+ if (dictionary === undefined) dictionary = new Uint8Array(0);
+ else if (!isArrayBufferView(dictionary) && !(dictionary instanceof ArrayBuffer) &&
+ !(typeof SharedArrayBuffer !== 'undefined' && dictionary instanceof SharedArrayBuffer)) {
+ throw makeTypeError('ERR_INVALID_ARG_TYPE',
+ 'The "options.dictionary" property must be an instance of Buffer, TypedArray, DataView, or ArrayBuffer.' + invalidArgTypeHelper(dictionary));
+ }
+ if (typeof SharedArrayBuffer !== 'undefined' && dictionary instanceof SharedArrayBuffer) {
+ dictionary = new Uint8Array(dictionary);
+ }
+ const rejectGarbage = opts.rejectGarbageAfterEnd;
+ if (rejectGarbage !== undefined && typeof rejectGarbage !== 'boolean') {
+ throw makeTypeError('ERR_INVALID_ARG_TYPE',
+ 'The "options.rejectGarbageAfterEnd" property must be of type boolean.' + invalidArgTypeHelper(rejectGarbage));
+ }
+ const signal = opts.signal;
+ const handle = zstd_stream_new(decompress, JSON.stringify(params), toUint8Array(toBuffer(dictionary)), pledged,
+ rejectGarbage === true);
+ if (handle == null) throw makeError('ERR_ZLIB_INITIALIZATION_FAILED', 'Setting parameter failed');
+ // An already-aborted signal may destroy the stream during super(). Attach
+ // it only after the native owner and its finalizer are installed.
+ try {
+ // Codec output stays binary; constructor encoding is not a setEncoding call.
+ if (opts.encoding) opts = { ...opts, encoding: null };
+ super(signal ? { ...opts, signal: undefined } : opts, decompress ? 11 : 10);
+ }
+ catch (error) { zstd_stream_close(handle); throw error; }
+ try {
+ this._finishFlush = finishFlush;
+ this._flushFlag = flush;
+ this._chunkSize = chunkSize ?? Z_DEFAULT_CHUNK;
+ this._info = opts.info;
+ this._zstdResume = null;
+ this._setNativeHandle(handle);
+ registerFinalizer(zstdCleanup, this, handle, this);
+ if (signal) addAbortSignal(signal, this);
+ }
+ catch (error) {
+ zstd_stream_close(handle);
+ unregisterFinalizer(zstdCleanup, this);
+ this._nativeHandle = null;
+ throw error;
+ }
+ }
+
+ _closeNativeHandle() {
+ if (this._nativeHandle !== null) zstd_stream_close(this._nativeHandle);
+ unregisterFinalizer(zstdCleanup, this);
+ this._nativeHandle = null;
+ }
+
+ reset() {
+ if (this._nativeHandle !== null && !zstd_stream_reset(this._nativeHandle)) {
+ this.destroy(makeError('ERR_ZLIB_INCOMPLETE_FRAME', 'Cannot reset an incomplete zstd frame'));
+ }
+ }
+
+ flush(kind, callback) {
+ if (typeof kind === 'function') { callback = kind; kind = 1; }
+ if (kind === undefined) kind = 1;
+ validateRangeInt(kind, 'kind', 0, 2);
+ super.flush(kind, callback);
+ }
+
+ _processStep(data, flush, capacity) {
+ const [bytes, message, errno, consumed, done] = zstd_stream_push(this._nativeHandle, data, flush, capacity);
+ if (errno === -7) throw makeTypeError('ERR_TRAILING_JUNK_AFTER_STREAM_END', message);
+ if (errno !== 0) {
+ const code = errno === -5 ? 'Z_BUF_ERROR' : zstdErrorCodes[errno];
+ const error = makeError(code, message);
+ error.errno = errno;
+ throw error;
+ }
+ return [bufferFromNativeBytes(bytes), consumed, done];
+ }
+
+ _processChunk(chunk, flush, limit = _getKMaxLength()) {
+ const data = toUint8Array(toBuffer(chunk));
+ const chunks = [];
+ let offset = 0, total = 0, done;
+ do {
+ const [output, consumed, complete] = this._processStep(
+ data.subarray(offset), flush, Math.min(this._chunkSize, limit - total + 1));
+ offset += consumed;
+ this._bytesWritten += consumed;
+ total += output.length;
+ if (total > limit) throw makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`);
+ if (output.length) chunks.push(output);
+ done = complete;
+ } while (!done);
+ return Buffer.concat(chunks, total);
+ }
+
+ _processStream(chunk, flush, callback) {
+ const data = toUint8Array(toBuffer(chunk));
+ let offset = 0;
+ const resume = error => {
+ if (error) { callback(error); return; }
+ try {
+ while (this._nativeHandle !== null) {
+ const [output, consumed, done] = this._processStep(data.subarray(offset), flush, this._chunkSize);
+ offset += consumed;
+ this._bytesWritten += consumed;
+ const ready = output.length === 0 || this.push(output);
+ if (this._nativeHandle === null) break;
+ if (!ready) {
+ this._zstdResume = done ? error => queueMicrotask(() => callback(error)) : resume;
+ return;
+ }
+ if (done) break;
+ }
+ queueMicrotask(callback);
+ } catch (error) { callback(error); }
+ };
+ resume();
+ }
+
+ _read(size) {
+ const resume = this._zstdResume;
+ this._zstdResume = null;
+ if (resume) resume();
+ super._read(size);
+ }
+
+ _transform(chunk, encoding, callback) {
+ try {
+ const flush = chunk.length === 0 && this._pendingFlushes.length > 0 ?
+ this._pendingFlushes.shift() : this._flushFlag;
+ this._processStream(typeof chunk === 'string' ? Buffer.from(chunk, encoding) : chunk, flush, callback);
+ } catch (error) { callback(error); }
+ }
+
+ _flush(callback) {
+ if (this._nativeHandle === null) { callback(); return; }
+ this._processStream(Buffer.alloc(0), this._finishFlush, error => {
+ this._closeHandle();
+ callback(error);
+ });
+ }
+
+ _destroy(error, callback) {
+ this._closeHandle();
+ const resume = this._zstdResume;
+ this._zstdResume = null;
+ if (resume) resume(error || makeError('ERR_STREAM_DESTROYED', 'Cannot call write after a stream was destroyed'));
+ callback(error);
+ }
+}
+
+export class ZstdCompress extends Zstd {
+ constructor(opts) { super(opts, false); }
+}
+export class ZstdDecompress extends Zstd {
+ constructor(opts) { super(opts, true); }
+}
+
// ===== Factory functions =====
export function createGzip(opts) { return new _Gzip(opts); }
@@ -1103,6 +1335,8 @@ export function createInflateRaw(opts) { return new _InflateRaw(opts); }
export function createUnzip(opts) { return new _Unzip(opts); }
export function createBrotliCompress(opts) { return new _BrotliCompress(opts); }
export function createBrotliDecompress(opts) { return new _BrotliDecompress(opts); }
+export function createZstdCompress(opts) { return new ZstdCompress(opts); }
+export function createZstdDecompress(opts) { return new ZstdDecompress(opts); }
// ===== Sync convenience functions =====
@@ -1230,6 +1464,88 @@ export function brotliDecompressSync(data, opts) {
// ===== Async convenience functions =====
+function zstdSync(data, opts, engine) {
+ try {
+ const buffer = engine._processChunk(data, engine._finishFlush, opts?.maxOutputLength ?? _getKMaxLength());
+ return engine._info ? { buffer, engine } : buffer;
+ } finally { engine._closeHandle(); }
+}
+
+// Node's synchronous convenience calls complete even with an aborted signal.
+export function zstdCompressSync(data, opts) {
+ return zstdSync(data, opts, new ZstdCompress({ ...opts, signal: undefined }));
+}
+export function zstdDecompressSync(data, opts) {
+ return zstdSync(data, opts, new ZstdDecompress({ ...opts, signal: undefined }));
+}
+
+function zstdAsync(data, opts, callback, Engine) {
+ if (typeof opts === 'function') { callback = opts; opts = {}; }
+ if (Engine === ZstdCompress && opts?.pledgedSrcSize === undefined) {
+ let pledgedSrcSize;
+ if (typeof data === 'string') {
+ const encoding = opts?.defaultEncoding;
+ // Match Node's default pledge only when the UTF-8 size is known to be
+ // the encoded size. Other encodings retain ordinary streaming behavior.
+ if (encoding == null || encoding === 'utf8' || encoding === 'utf-8') {
+ pledgedSrcSize = Buffer.byteLength(data);
+ }
+ } else if (isArrayBufferView(data) || data instanceof ArrayBuffer ||
+ (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer)) {
+ pledgedSrcSize = data.byteLength;
+ }
+ if (pledgedSrcSize !== undefined) opts = { ...opts, pledgedSrcSize };
+ }
+ // Construction and input validation throw synchronously; codec failures go
+ // to the callback. Do not turn invalid options into asynchronous errors.
+ const engine = new Engine(opts);
+ let input;
+ try {
+ if (typeof callback !== 'function') {
+ throw makeTypeError('ERR_INVALID_ARG_TYPE',
+ 'The "callback" argument must be of type function. Received ' + (callback === undefined ? 'undefined' : typeof callback));
+ }
+ input = typeof data === 'string' ? Buffer.from(data, engine._writableState.defaultEncoding) : toBuffer(data);
+ } catch (error) {
+ // This private engine cannot deliver errors after validation throws.
+ engine.on('error', () => {});
+ engine.destroy();
+ throw error;
+ }
+ const chunks = [];
+ const limit = opts?.maxOutputLength ?? _getKMaxLength();
+ let total = 0, settled = false;
+ const done = (error, result) => {
+ if (settled) return;
+ settled = true;
+ chunks.length = 0;
+ engine.destroy();
+ callback(error, result);
+ };
+ engine.once('error', done);
+ engine.on('data', chunk => {
+ total += chunk.length;
+ if (total > limit) {
+ engine.destroy(makeRangeError('ERR_BUFFER_TOO_LARGE', `Cannot create a Buffer larger than ${limit} bytes`));
+ } else {
+ chunks.push(chunk);
+ }
+ });
+ engine.once('end', () => {
+ let buffer;
+ try { buffer = Buffer.concat(chunks, total); }
+ catch (error) { done(error); return; }
+ done(null, engine._info ? { buffer, engine } : buffer);
+ });
+ try {
+ engine.end(input);
+ } catch (error) {
+ engine._closeHandle();
+ engine.destroy();
+ throw error;
+ }
+}
+
function asyncConvenience(syncFn, data, opts, callback) {
if (typeof opts === 'function') {
callback = opts;
@@ -1256,6 +1572,8 @@ export function inflateRaw(data, opts, callback) { asyncConvenience(inflateRawSy
export function unzip(data, opts, callback) { asyncConvenience(unzipSync, data, opts, callback); }
export function brotliCompress(data, opts, callback) { asyncConvenience(brotliCompressSync, data, opts, callback); }
export function brotliDecompress(data, opts, callback) { asyncConvenience(brotliDecompressSync, data, opts, callback); }
+export function zstdCompress(data, opts, callback) { zstdAsync(data, opts, callback, ZstdCompress); }
+export function zstdDecompress(data, opts, callback) { zstdAsync(data, opts, callback, ZstdDecompress); }
// ===== CRC32 =====
@@ -1295,6 +1613,8 @@ const _default = {
Unzip,
BrotliCompress,
BrotliDecompress,
+ ZstdCompress,
+ ZstdDecompress,
// Factory functions
createGzip,
@@ -1306,6 +1626,8 @@ const _default = {
createUnzip,
createBrotliCompress,
createBrotliDecompress,
+ createZstdCompress,
+ createZstdDecompress,
// Sync
gzipSync,
@@ -1317,6 +1639,8 @@ const _default = {
unzipSync,
brotliCompressSync,
brotliDecompressSync,
+ zstdCompressSync,
+ zstdDecompressSync,
// Async
gzip,
@@ -1328,6 +1652,8 @@ const _default = {
unzip,
brotliCompress,
brotliDecompress,
+ zstdCompress,
+ zstdDecompress,
// Constants (directly accessible like Node.js)
Z_NO_FLUSH,
@@ -1382,6 +1708,15 @@ const _default = {
ZLIB_VERNUM,
};
+for (const key of Object.keys(zstdConstants)) {
+ Object.defineProperty(_default, key, {
+ value: zstdConstants[key],
+ writable: false,
+ configurable: false,
+ enumerable: false,
+ });
+}
+
Object.defineProperty(_default, 'constants', {
value: constants,
writable: false,
diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs
index 4fcd90437..86f13336a 100644
--- a/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs
+++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib.rs
@@ -5,6 +5,9 @@ use std::sync::{LazyLock, Mutex};
use flate2::{Compression, Decompress, FlushDecompress, Status};
+#[cfg(feature = "zstd")]
+mod zstd;
+
// ===== Handle ID generation =====
static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1);
@@ -1117,6 +1120,7 @@ pub mod native_module {
use rquickjs::{Ctx, TypedArray};
type DecompressOutcome<'js> = List<(Option>, Option, i32)>;
+ type ZstdOutcome<'js> = List<(Option>, Option, i32, u32, bool)>;
// ===== One-shot functions =====
@@ -1287,6 +1291,83 @@ pub mod native_module {
pub fn brotli_stream_bytes_written(id: u32) -> u32 {
super::brotli_stream_bytes_written_impl(id)
}
+
+ #[rquickjs::function]
+ pub fn zstd_stream_new<'js>(
+ decompress: bool,
+ params: String,
+ dictionary: TypedArray<'js, u8>,
+ pledged: Option,
+ reject_garbage: bool,
+ ) -> Option {
+ #[cfg(feature = "zstd")]
+ {
+ // SAFETY: Codec initialization consumes the rooted dictionary without JS re-entry.
+ let dictionary = unsafe { dictionary.as_bytes() }.unwrap_or_default();
+ super::zstd::new(decompress, ¶ms, dictionary, pledged, reject_garbage)
+ }
+ #[cfg(not(feature = "zstd"))]
+ {
+ let _ = (decompress, params, dictionary, pledged, reject_garbage);
+ None
+ }
+ }
+
+ #[rquickjs::function]
+ pub fn zstd_stream_push<'js>(
+ ctx: Ctx<'js>,
+ id: u32,
+ data: TypedArray<'js, u8>,
+ flush: u8,
+ capacity: u32,
+ ) -> rquickjs::Result> {
+ #[cfg(feature = "zstd")]
+ {
+ // SAFETY: Codec processing consumes the rooted input without JS re-entry.
+ let input = unsafe { data.as_bytes() }.unwrap_or_default();
+ match super::zstd::push(id, input, flush, capacity as usize) {
+ Ok((bytes, consumed, done)) => Ok(List((
+ Some(TypedArray::new(ctx, bytes)?),
+ None,
+ 0,
+ consumed as u32,
+ done,
+ ))),
+ Err((code, message)) => Ok(List((None, Some(message), code, 0, true))),
+ }
+ }
+ #[cfg(not(feature = "zstd"))]
+ {
+ let _ = (ctx, id, data, flush, capacity);
+ Ok(List((None, None, 0, 0, true)))
+ }
+ }
+
+ #[rquickjs::function]
+ pub fn zstd_stream_reset(id: u32) -> bool {
+ #[cfg(feature = "zstd")]
+ {
+ super::zstd::reset(id)
+ }
+ #[cfg(not(feature = "zstd"))]
+ {
+ let _ = id;
+ false
+ }
+ }
+
+ #[rquickjs::function]
+ pub fn zstd_stream_close(id: u32) -> bool {
+ #[cfg(feature = "zstd")]
+ {
+ super::zstd::close(id)
+ }
+ #[cfg(not(feature = "zstd"))]
+ {
+ let _ = id;
+ false
+ }
+ }
}
pub const ZLIB_JS: &str = include_str!("zlib.js");
diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs
new file mode 100644
index 000000000..ccfe19e1a
--- /dev/null
+++ b/crates/wasm-rquickjs/skeleton/src/builtin/zlib/zstd.rs
@@ -0,0 +1,322 @@
+//! Stateful zstd backend. Every handle owns its own codec context.
+
+use std::borrow::Cow;
+use std::collections::HashMap;
+use std::ptr::NonNull;
+use std::sync::{LazyLock, Mutex};
+use zstd_safe::{DCtx, DParameter, InBuffer, OutBuffer, ResetDirective, zstd_sys};
+
+enum Codec {
+ // zstd-safe 7's boolean LDM setter cannot represent ZSTD_ps_disable.
+ // Own the C context directly so libzstd receives the original integers.
+ Compress(NonNull, Option),
+ Decompress(DCtx<'static>),
+}
+
+// SAFETY: Each context has one owner; STREAMS serializes every access.
+unsafe impl Send for Codec {}
+
+impl Drop for Codec {
+ fn drop(&mut self) {
+ if let Self::Compress(ctx, _) = self {
+ // SAFETY: This is the sole owner, and no codec call can outlive it.
+ unsafe { zstd_sys::ZSTD_freeCCtx(ctx.as_ptr()) };
+ }
+ }
+}
+
+struct Stream {
+ codec: Codec,
+ complete: bool,
+ emitted: bool,
+ input_size: Option,
+ pending: Vec,
+ garbage: bool,
+ reject_garbage: bool,
+}
+
+static STREAMS: LazyLock>> =
+ LazyLock::new(|| Mutex::new(HashMap::new()));
+
+fn compression_parameter(key: u32) -> Option {
+ use zstd_sys::ZSTD_cParameter::*;
+ Some(match key {
+ 100 => ZSTD_c_compressionLevel,
+ 101 => ZSTD_c_windowLog,
+ 102 => ZSTD_c_hashLog,
+ 103 => ZSTD_c_chainLog,
+ 104 => ZSTD_c_searchLog,
+ 105 => ZSTD_c_minMatch,
+ 106 => ZSTD_c_targetLength,
+ 107 => ZSTD_c_strategy,
+ 160 => ZSTD_c_enableLongDistanceMatching,
+ 161 => ZSTD_c_ldmHashLog,
+ 162 => ZSTD_c_ldmMinMatch,
+ 163 => ZSTD_c_ldmBucketSizeLog,
+ 164 => ZSTD_c_ldmHashRateLog,
+ 200 => ZSTD_c_contentSizeFlag,
+ 201 => ZSTD_c_checksumFlag,
+ 202 => ZSTD_c_dictIDFlag,
+ 400 => ZSTD_c_nbWorkers,
+ 401 => ZSTD_c_jobSize,
+ 402 => ZSTD_c_overlapLog,
+ _ => return None,
+ })
+}
+
+pub(super) fn new(
+ decompress: bool,
+ params: &str,
+ dictionary: &[u8],
+ pledged: Option,
+ reject_garbage: bool,
+) -> Option {
+ let params: Vec<(u32, i32)> = serde_json::from_str(params).ok()?;
+ let codec = if decompress {
+ let mut ctx = DCtx::create();
+ ctx.load_dictionary(dictionary).ok()?;
+ for (key, value) in params {
+ if key != 100 {
+ return None;
+ }
+ ctx.set_parameter(DParameter::WindowLogMax(value as u32))
+ .ok()?;
+ }
+ Codec::Decompress(ctx)
+ } else {
+ // SAFETY: The new context is immediately placed in its owning Codec,
+ // including on every initialization failure below.
+ let ctx = NonNull::new(unsafe { zstd_sys::ZSTD_createCCtx() })?;
+ let pledged = pledged.map(|v| v as u64);
+ let codec = Codec::Compress(ctx, pledged);
+ for (key, value) in params {
+ let parameter = compression_parameter(key)?;
+ // SAFETY: The context is owned, and the parameter enum is valid.
+ native_result(unsafe {
+ zstd_sys::ZSTD_CCtx_setParameter(ctx.as_ptr(), parameter, value)
+ })
+ .ok()?;
+ }
+ // SAFETY: loadDictionary copies the borrowed bytes; neither call retains
+ // a Rust reference. Parameters precede dictionary table construction.
+ native_result(unsafe {
+ zstd_sys::ZSTD_CCtx_loadDictionary(
+ ctx.as_ptr(),
+ dictionary.as_ptr().cast(),
+ dictionary.len(),
+ )
+ })
+ .ok()?;
+ native_result(unsafe {
+ zstd_sys::ZSTD_CCtx_setPledgedSrcSize(
+ ctx.as_ptr(),
+ pledged.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN),
+ )
+ })
+ .ok()?;
+ codec
+ };
+ let input_size = match &codec {
+ Codec::Compress(_, pledged) => pledged.map(|_| 0),
+ Codec::Decompress(_) => None,
+ };
+ let id = super::next_id();
+ STREAMS.lock().unwrap().insert(
+ id,
+ Stream {
+ codec,
+ complete: false,
+ emitted: false,
+ input_size,
+ pending: Vec::new(),
+ garbage: false,
+ reject_garbage,
+ },
+ );
+ Some(id)
+}
+
+fn native_error(code: usize) -> (i32, String) {
+ (
+ code.wrapping_neg() as i32,
+ zstd_safe::get_error_name(code).to_string(),
+ )
+}
+
+fn native_result(code: usize) -> Result {
+ // SAFETY: ZSTD_isError only inspects the numeric result.
+ if unsafe { zstd_sys::ZSTD_isError(code) } != 0 {
+ Err(native_error(code))
+ } else {
+ Ok(code)
+ }
+}
+
+fn frame_prefix(bytes: &[u8]) -> bool {
+ let length = bytes.len().min(4);
+ bytes[..length] == [0x28, 0xb5, 0x2f, 0xfd][..length]
+ || (0x50..=0x5f).any(|first| bytes[..length] == [first, 0x2a, 0x4d, 0x18][..length])
+}
+
+pub(super) fn push(
+ id: u32,
+ bytes: &[u8],
+ flush: u8,
+ capacity: usize,
+) -> Result<(Vec, usize, bool), (i32, String)> {
+ let mut streams = STREAMS.lock().unwrap();
+ let stream = streams.get_mut(&id).ok_or_else(|| {
+ (
+ 60,
+ "Operation not authorized at current processing stage".to_string(),
+ )
+ })?;
+ if let Codec::Compress(_, pledged) = stream.codec {
+ if stream.complete && bytes.is_empty() {
+ return Ok((Vec::new(), 0, true));
+ }
+ if let Some(input_size) = stream.input_size {
+ // A single compressStream2(end) call infers the input size even when
+ // the caller supplied a pledge. Validate only the active pledge.
+ if flush == 2 && Some(input_size + bytes.len() as u64) != pledged {
+ return Err((72, "Src size is incorrect".to_string()));
+ }
+ }
+ }
+ let prefix = std::mem::take(&mut stream.pending);
+ let prefix_len = prefix.len();
+ let data = if prefix.is_empty() {
+ Cow::Borrowed(bytes)
+ } else {
+ let mut data = prefix;
+ data.extend_from_slice(bytes);
+ Cow::Owned(data)
+ };
+ let mut input = InBuffer::around(&data);
+ if matches!(stream.codec, Codec::Decompress(_)) && stream.complete {
+ if stream.garbage || (!data.is_empty() && !frame_prefix(&data)) {
+ stream.garbage = true;
+ if stream.reject_garbage {
+ return Err((
+ -7,
+ "Trailing junk found after the end of the compressed stream".to_string(),
+ ));
+ }
+ // Stop this write without counting discarded input as consumed.
+ return Ok((Vec::new(), 0, true));
+ }
+ if data.len() < 4 {
+ if flush == 2 && !data.is_empty() && stream.reject_garbage {
+ return Err((
+ -7,
+ "Trailing junk found after the end of the compressed stream".to_string(),
+ ));
+ }
+ stream.pending.extend_from_slice(&data);
+ return Ok((Vec::new(), bytes.len(), true));
+ }
+ }
+ // One call produces at most capacity bytes. The caller retains unconsumed
+ // input and resumes only when the readable side has demand.
+ let mut chunk = vec![0; capacity];
+ let (remaining, written) = match &mut stream.codec {
+ Codec::Compress(ctx, _) => {
+ let directive = match flush {
+ 1 => zstd_sys::ZSTD_EndDirective::ZSTD_e_flush,
+ 2 => zstd_sys::ZSTD_EndDirective::ZSTD_e_end,
+ _ => zstd_sys::ZSTD_EndDirective::ZSTD_e_continue,
+ };
+ let mut raw_input = zstd_sys::ZSTD_inBuffer {
+ src: data.as_ptr().cast(),
+ size: data.len(),
+ pos: 0,
+ };
+ let mut output = zstd_sys::ZSTD_outBuffer {
+ dst: chunk.as_mut_ptr().cast(),
+ size: chunk.len(),
+ pos: 0,
+ };
+ // SAFETY: Both buffers stay alive for this synchronous call,
+ // and the exclusively owned context retains neither pointer.
+ let remaining = native_result(unsafe {
+ zstd_sys::ZSTD_compressStream2(ctx.as_ptr(), &mut output, &mut raw_input, directive)
+ })?;
+ input.pos = raw_input.pos;
+ (remaining, output.pos)
+ }
+ Codec::Decompress(ctx) => {
+ let mut output = OutBuffer::around(&mut chunk[..]);
+ let remaining = ctx
+ .decompress_stream(&mut output, &mut input)
+ .map_err(native_error)?;
+ (remaining, output.pos())
+ }
+ };
+ let done = match stream.codec {
+ Codec::Compress(_, _) => {
+ if let Some(size) = &mut stream.input_size {
+ *size += input.pos as u64;
+ }
+ stream.emitted |= written > 0;
+ stream.complete = flush == 2 && remaining == 0;
+ if stream.complete {
+ stream.emitted = false;
+ stream.input_size = None;
+ }
+ input.pos == data.len() && (flush == 0 || remaining == 0)
+ }
+ Codec::Decompress(_) => {
+ stream.complete = remaining == 0;
+ if input.pos == data.len() && written < capacity && flush == 2 && !stream.complete {
+ return Err((-5, "unexpected end of file".to_string()));
+ }
+ input.pos == data.len() && (written < capacity || stream.complete)
+ }
+ };
+ chunk.truncate(written);
+ Ok((chunk, input.pos.saturating_sub(prefix_len), done))
+}
+
+pub(super) fn reset(id: u32) -> bool {
+ let mut streams = STREAMS.lock().unwrap();
+ let Some(stream) = streams.get_mut(&id) else {
+ return false;
+ };
+ let result = match &mut stream.codec {
+ Codec::Compress(ctx, pledged) => {
+ if stream.emitted && !stream.complete {
+ return false;
+ }
+ // SAFETY: Session reset and pledge update use the exclusively owned context.
+ native_result(unsafe {
+ zstd_sys::ZSTD_CCtx_reset(
+ ctx.as_ptr(),
+ zstd_sys::ZSTD_ResetDirective::ZSTD_reset_session_only,
+ )
+ })
+ .and_then(|_| {
+ native_result(unsafe {
+ zstd_sys::ZSTD_CCtx_setPledgedSrcSize(
+ ctx.as_ptr(),
+ pledged.unwrap_or(zstd_safe::CONTENTSIZE_UNKNOWN),
+ )
+ })
+ })
+ .map_err(|_| ())
+ }
+ Codec::Decompress(ctx) => ctx.reset(ResetDirective::SessionOnly).map_err(|_| ()),
+ };
+ stream.complete = false;
+ stream.emitted = false;
+ stream.input_size = match stream.codec {
+ Codec::Compress(_, pledged) => pledged.map(|_| 0),
+ Codec::Decompress(_) => None,
+ };
+ stream.garbage = false;
+ stream.pending.clear();
+ result.is_ok()
+}
+
+pub(super) fn close(id: u32) -> bool {
+ STREAMS.lock().unwrap().remove(&id).is_some()
+}
diff --git a/examples/runtime/module-resolution/src/module-resolution.js b/examples/runtime/module-resolution/src/module-resolution.js
index 3dd3892b5..18e8b383f 100644
--- a/examples/runtime/module-resolution/src/module-resolution.js
+++ b/examples/runtime/module-resolution/src/module-resolution.js
@@ -43,13 +43,13 @@ export async function testBuiltinDiscovery(testCase) {
for (const id of ['node:test', 'node:sqlite']) {
assert.strictEqual(get(id), require(id), id);
}
- // Actual package capability probes: keep absent SEA/zstd capabilities
- // absent, so callers can take their ordinary-runtime/uncompressed path.
+ // Package probes retain the absent SEA fallback and discover the same
+ // supported codec APIs as the ordinary zlib module.
assert.strictEqual(get('node:sea'), undefined);
assert.strictEqual(get('node:sea')?.isSea() ?? false, false);
const zlib = get('node:zlib');
assert.strictEqual(zlib, require('zlib'));
- assert.strictEqual(zlib.zstdCompressSync, undefined);
+ assert.strictEqual(typeof zlib.zstdCompressSync, 'function');
assert.strictEqual(typeof zlib.gzipSync, 'function');
} else if (testCase === 1) {
const originalLoad = module._load;
diff --git a/examples/runtime/zlib/src/zlib.js b/examples/runtime/zlib/src/zlib.js
index 450e76b93..83e2835a7 100644
--- a/examples/runtime/zlib/src/zlib.js
+++ b/examples/runtime/zlib/src/zlib.js
@@ -1,4 +1,7 @@
import { Buffer } from 'node:buffer';
+import assert from 'node:assert/strict';
+import { getEventListeners } from 'node:events';
+import * as zlib from 'node:zlib';
import {
brotliCompressSync,
brotliDecompressSync,
@@ -401,3 +404,484 @@ export async function testByteTransfer() {
}
return true;
}
+
+export async function testZstd() {
+ const external = Buffer.from('KLUv/SAgAQEATm9kZSAyNiBleHRlcm5hbCB2ZWN0b3I6IDEzICsgMjk=', 'base64');
+ assert.equal(zlib.zstdDecompressSync(external).toString(), 'Node 26 external vector: 13 + 29');
+ for (const create of [zlib.createZstdCompress, zlib.createZstdDecompress]) {
+ for (const rejectGarbageAfterEnd of [1, 'true', null]) {
+ assert.throws(() => create({ rejectGarbageAfterEnd }), {
+ name: 'TypeError', code: 'ERR_INVALID_ARG_TYPE',
+ });
+ }
+ }
+ const source = Buffer.from('Ω asymmetric compression: 13|29 '.repeat(3000));
+ for (const input of [Buffer.alloc(0), source, new DataView(source.buffer, source.byteOffset + 7, 29)]) {
+ const bytes = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength);
+ const compressed = zlib.zstdCompressSync(input, { params: { [constants.ZSTD_c_checksumFlag]: true } });
+ assert.deepEqual(zlib.zstdDecompressSync(compressed), bytes);
+ await new Promise((resolve, reject) => {
+ zlib.zstdCompress(input, (error, output) => {
+ if (error) return reject(error);
+ zlib.zstdDecompress(output, (error, result) => {
+ if (error) return reject(error);
+ try { assert.deepEqual(result, bytes); resolve(); } catch (error) { reject(error); }
+ });
+ });
+ });
+ }
+ const compressed = zlib.zstdCompressSync(source);
+ const trailingJunkError = { name: 'TypeError', code: 'ERR_TRAILING_JUNK_AFTER_STREAM_END' };
+ for (const trailing of [Buffer.from('junk'), compressed.subarray(0, 3)]) {
+ const withJunk = Buffer.concat([compressed, trailing]);
+ assert.deepEqual(zlib.zstdDecompressSync(withJunk), source);
+ assert.throws(() => zlib.zstdDecompressSync(withJunk, { rejectGarbageAfterEnd: true }), trailingJunkError);
+ await assert.rejects(new Promise((resolve, reject) => {
+ zlib.zstdDecompress(withJunk, { rejectGarbageAfterEnd: true }, (error, result) => {
+ if (error) reject(error); else resolve(result);
+ });
+ }), trailingJunkError);
+ for (const rejectGarbageAfterEnd of [false, true]) {
+ const decoder = zlib.createZstdDecompress({ rejectGarbageAfterEnd });
+ const chunks = [];
+ const done = new Promise((resolve, reject) => {
+ decoder.on('data', chunk => chunks.push(chunk));
+ decoder.on('end', resolve);
+ decoder.on('error', reject);
+ });
+ decoder.write(compressed);
+ decoder.end(trailing);
+ if (rejectGarbageAfterEnd) await assert.rejects(done, trailingJunkError);
+ else {
+ await done;
+ assert.deepEqual(Buffer.concat(chunks), source);
+ }
+ }
+ }
+ assert.throws(() => zlib.zstdDecompressSync(compressed.subarray(0, compressed.length - 1)), {
+ code: 'Z_BUF_ERROR', message: 'unexpected end of file',
+ });
+ const partial = zlib.zstdDecompressSync(compressed.subarray(0, compressed.length - 1), { finishFlush: 1 });
+ assert.deepEqual(partial, source.subarray(0, partial.length));
+ assert.throws(() => zlib.zstdCompressSync(source, { pledgedSrcSize: source.length - 1 }), {
+ code: 'ZSTD_error_srcSize_wrong', errno: 72,
+ });
+ assert.throws(() => zlib.zstdDecompressSync(compressed, { maxOutputLength: source.length - 1 }), {
+ code: 'ERR_BUFFER_TOO_LARGE',
+ });
+ const info = zlib.zstdCompressSync(source, { info: true });
+ assert.ok(info.engine instanceof zlib.ZstdCompress);
+ assert.deepEqual(zlib.zstdDecompressSync(info.buffer), source);
+ await streamRoundTrip(source, zlib.createZstdCompress(), zlib.createZstdDecompress());
+ const decoder = zlib.createZstdDecompress({ chunkSize: 64 });
+ const chunks = [];
+ const done = new Promise((resolve, reject) => {
+ decoder.on('data', chunk => chunks.push(chunk));
+ decoder.on('end', resolve);
+ decoder.on('error', reject);
+ });
+ for (const byte of Buffer.concat([external, compressed, external])) decoder.write(Buffer.from([byte]));
+ decoder.end();
+ await done;
+ assert.deepEqual(Buffer.concat(chunks), Buffer.concat([
+ Buffer.from('Node 26 external vector: 13 + 29'), source, Buffer.from('Node 26 external vector: 13 + 29'),
+ ]));
+ const frameResults = [];
+ for (const scenario of ['buffered-reset', 'next-frame', 'reset-pledge']) {
+ const compressor = zlib.createZstdCompress(
+ scenario === 'buffered-reset' ? {} : { pledgedSrcSize: 5 },
+ );
+ const chunks = [];
+ const completed = new Promise(resolve => {
+ compressor.on('data', chunk => chunks.push(chunk));
+ compressor.on('end', () => resolve(null));
+ compressor.on('error', resolve);
+ });
+ const write = data => new Promise((resolve, reject) => {
+ compressor.write(data, error => error ? reject(error) : resolve());
+ });
+ try {
+ await write('hello');
+ await new Promise((resolve, reject) => {
+ compressor.flush(constants.ZSTD_e_end, error => error ? reject(error) : resolve());
+ });
+ if (scenario === 'buffered-reset') {
+ const completedChunks = chunks.length;
+ await write('x');
+ assert.equal(chunks.length, completedChunks);
+ compressor.reset();
+ compressor.end('world');
+ } else {
+ if (scenario === 'reset-pledge') compressor.reset();
+ compressor.end('x');
+ }
+ const error = await completed;
+ if (error) throw error;
+ frameResults.push(zlib.zstdDecompressSync(Buffer.concat(chunks)).toString());
+ } catch (error) {
+ compressor.destroy();
+ frameResults.push({ code: error.code, errno: error.errno });
+ }
+ }
+ assert.deepEqual(frameResults, [
+ 'helloworld', 'hellox', { code: 'ZSTD_error_srcSize_wrong', errno: 72 },
+ ]);
+ return true;
+}
+
+export async function testZstdContracts() {
+ const failures = [];
+ for (const [name, check] of [
+ ['decompression byte accounting', async () => {
+ // Node 26 frame for "hello", independent of this runtime's compressor.
+ const frame = Buffer.from('28b52ffd200529000068656c6c6f', 'hex');
+ const junk = Buffer.from('junk');
+ const skippable = Buffer.from('502a4d1803000000616263', 'hex');
+ for (const [suffix, expectedBytes, expectedOutput] of [
+ [Buffer.alloc(0), 14, 'hello'],
+ [junk, 14, 'hello'],
+ [frame.subarray(0, 2), 16, 'hello'],
+ [Buffer.from([0x28, 0xb5, 0, 0]), 14, 'hello'],
+ [frame, 28, 'hellohello'],
+ [Buffer.concat([skippable, frame, junk]), 39, 'hellohello'],
+ ]) {
+ const input = Buffer.concat([frame, suffix]);
+ const sync = zlib.zstdDecompressSync(input, { info: true, chunkSize: 64 });
+ assert.equal(sync.buffer.toString(), expectedOutput);
+ assert.equal(sync.engine.bytesWritten, expectedBytes);
+ const callback = await new Promise((resolve, reject) => zlib.zstdDecompress(input,
+ { info: true, chunkSize: 64 }, (error, value) => error ? reject(error) : resolve(value)));
+ assert.equal(callback.buffer.toString(), expectedOutput);
+ assert.equal(callback.engine.bytesWritten, expectedBytes);
+ }
+ for (const [parts, expectedBytes, expectedOutput] of [
+ [[Buffer.concat([frame, junk])], 14, 'hello'],
+ [[frame, junk], 14, 'hello'],
+ [[Buffer.concat([frame, frame.subarray(0, 1)]), junk], 15, 'hello'],
+ [[frame, frame.subarray(0, 1), junk], 15, 'hello'],
+ [[frame, frame.subarray(0, 2)], 16, 'hello'],
+ [[frame, frame.subarray(0, 1), frame.subarray(1), junk], 28, 'hellohello'],
+ [[frame, skippable.subarray(0, 3), skippable.subarray(3), frame, junk], 39, 'hellohello'],
+ ]) {
+ const decoder = zlib.createZstdDecompress({ chunkSize: 64 });
+ const chunks = [];
+ const done = new Promise((resolve, reject) => {
+ decoder.on('data', chunk => chunks.push(chunk));
+ decoder.on('end', resolve);
+ decoder.on('error', reject);
+ });
+ for (const part of parts) {
+ await new Promise((resolve, reject) => decoder.write(part,
+ error => error ? reject(error) : resolve()));
+ }
+ decoder.end();
+ await done;
+ assert.equal(Buffer.concat(chunks).toString(), expectedOutput);
+ assert.equal(decoder.bytesWritten, expectedBytes);
+ }
+ }],
+ ['binary output despite constructor encoding', async () => {
+ const source = Buffer.from([0, 255, 13, 29, 128, 65]);
+ const options = { encoding: 'hex' };
+ const frame = await new Promise((resolve, reject) => zlib.zstdCompress(source, options,
+ (error, value) => error ? reject(error) : resolve(value)));
+ assert.ok(Buffer.isBuffer(frame));
+ const decoded = await new Promise((resolve, reject) => zlib.zstdDecompress(frame, options,
+ (error, value) => error ? reject(error) : resolve(value)));
+ assert.ok(Buffer.isBuffer(decoded));
+ assert.deepEqual(decoded, source);
+ await streamRoundTrip(source, zlib.createZstdCompress(options), zlib.createZstdDecompress(options));
+ assert.deepEqual(options, { encoding: 'hex' });
+ }],
+ ['callback info snapshot', async () => {
+ const source = Buffer.from('callback shape 13|29');
+ const frame = zlib.zstdCompressSync(source);
+ for (const info of [false, true]) {
+ const options = { info };
+ const result = new Promise((resolve, reject) => zlib.zstdDecompress(frame, options,
+ (error, value) => error ? reject(error) : resolve(value)));
+ options.info = !info;
+ const value = await result;
+ assert.deepEqual(info ? value.buffer : value, source);
+ assert.equal(Buffer.isBuffer(value), !info);
+ if (info) assert.ok(value.engine instanceof zlib.ZstdDecompress);
+ }
+ }],
+ ['direct constant aliases', async () => {
+ assert.equal(zlib.default.ZSTD_c_compressionLevel, 100);
+ assert.equal(zlib.default.ZSTD_e_end, 2);
+ assert.throws(() => { zlib.default.ZSTD_e_end = 99; }, TypeError);
+ const source = Buffer.from('direct constant parameter 13|29');
+ const frame = zlib.zstdCompressSync(source,
+ { params: { [zlib.default.ZSTD_c_compressionLevel]: 9 } });
+ assert.deepEqual(zlib.zstdDecompressSync(frame), source);
+ }],
+ ['callback validation precedence', async () => {
+ for (const operation of [zlib.zstdCompress, zlib.zstdDecompress]) {
+ assert.throws(() => operation(123),
+ { code: 'ERR_INVALID_ARG_TYPE', message: /callback/ });
+ }
+ }],
+ ['callback source pledge', async () => {
+ const bytes = Buffer.from('héllo wörld 🚀 '.repeat(1000));
+ const padded = Buffer.concat([Buffer.alloc(7), bytes, Buffer.alloc(11)]);
+ const mismatches = [];
+ for (const [input, options, normalized] of [
+ ['', {}, Buffer.alloc(0)],
+ ['hello', {}, Buffer.from('hello')],
+ [bytes.toString(), {}, bytes],
+ [new DataView(padded.buffer, padded.byteOffset + 7, bytes.length), {}, bytes],
+ [Buffer.alloc(131073, 65), { chunkSize: 64 }, Buffer.alloc(131073, 65)],
+ [bytes.toString(), { defaultEncoding: 'utf-8' }, bytes],
+ ]) {
+ const opts = { ...options, params: { [zlib.constants.ZSTD_c_compressionLevel]: 9 } };
+ const compressed = await new Promise((resolve, reject) => zlib.zstdCompress(input, opts,
+ (error, output) => error ? reject(error) : resolve(output)));
+ const expected = zlib.zstdCompressSync(normalized, opts);
+ console.log(`pledge ${normalized.length}: ${compressed.toString('hex')} sync: ${expected.toString('hex')}`);
+ if (!compressed.equals(expected)) mismatches.push(`${typeof input}/${normalized.length}`);
+ assert.equal(opts.pledgedSrcSize, undefined);
+ }
+ const latin1 = await new Promise((resolve, reject) => zlib.zstdCompress('é',
+ { defaultEncoding: 'latin1', params: { [zlib.constants.ZSTD_c_compressionLevel]: 9 } },
+ (error, output) => error ? reject(error) : resolve(output)));
+ // Node deliberately leaves non-UTF-8 strings unpledged; their frame is
+ // not byte-identical to synchronous compression of the encoded bytes.
+ console.log(`latin1 unpledged: ${latin1.toString('hex')}`);
+ assert.equal(latin1[4] & 0xe0, 0);
+ assert.deepEqual(zlib.zstdDecompressSync(latin1), Buffer.from([0xe9]));
+ const mismatch = await new Promise(resolve => zlib.zstdCompress(Buffer.from('hello'),
+ { pledgedSrcSize: 1 }, error => resolve(error)));
+ assert.equal(mismatch?.code, 'ZSTD_error_srcSize_wrong');
+ assert.equal(mismatch?.errno, 72);
+ assert.deepEqual(mismatches, []);
+ }],
+ ['constructor option ownership', async () => {
+ let reads = 0;
+ const compressor = zlib.createZstdCompress({
+ get chunkSize() {
+ if (++reads > 2) throw new Error('unowned third chunkSize read');
+ return 64;
+ },
+ });
+ await streamRoundTrip(Buffer.from('constructor ownership 13|29'), compressor, zlib.createZstdDecompress());
+ assert.throws(() => zlib.createZstdCompress({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
+ }],
+ ['error intrinsic capture', async () => {
+ const original = String.prototype.startsWith;
+ const find = Array.prototype.find;
+ const keys = Object.keys;
+ let error;
+ // Construct first: parameter enumeration is not the error-mapping path.
+ const decoder = zlib.createZstdDecompress();
+ const failed = new Promise(resolve => decoder.on('error', resolve));
+ try {
+ String.prototype.startsWith = () => { throw new Error('mutable startsWith'); };
+ Array.prototype.find = () => { throw new Error('mutable find'); };
+ Object.keys = () => { throw new Error('mutable keys'); };
+ decoder.end(Buffer.from([1, 2, 3, 4]));
+ error = await failed;
+ } finally {
+ String.prototype.startsWith = original;
+ Array.prototype.find = find;
+ Object.keys = keys;
+ }
+ assert.equal(error?.code, 'ZSTD_error_prefix_unknown');
+ assert.equal(error?.errno, 10);
+ }],
+ ['callback encoding', async () => {
+ for (const pledgedSrcSize of [undefined, 1]) {
+ const compressed = await new Promise((resolve, reject) => {
+ zlib.zstdCompress('é', { defaultEncoding: 'latin1', pledgedSrcSize },
+ (error, result) => error ? reject(error) : resolve(result));
+ });
+ assert.deepEqual(zlib.zstdDecompressSync(compressed), Buffer.from([0xe9]));
+ }
+ }],
+ ['shared dictionaries', async () => {
+ const shared = new SharedArrayBuffer(128);
+ const dictionary = Buffer.from('dictionary asymmetric 13|29 '.repeat(3));
+ new Uint8Array(shared).set(dictionary, 7);
+ const source = Buffer.from('dictionary asymmetric 13|29 '.repeat(100));
+ for (const value of [shared, new Uint8Array(shared, 7, dictionary.length),
+ new DataView(shared, 7, dictionary.length)]) {
+ const compressed = zlib.zstdCompressSync(source, { dictionary: value });
+ assert.deepEqual(zlib.zstdDecompressSync(compressed, { dictionary: value }), source);
+ await streamRoundTrip(source, zlib.createZstdCompress({ dictionary: value }),
+ zlib.createZstdDecompress({ dictionary: value }));
+ }
+ }],
+ ['numeric parameters', async () => {
+ for (const value of [-2, 3, 100]) {
+ assert.throws(() => zlib.createZstdCompress({ params: { 160: value } }),
+ { code: 'ERR_ZLIB_INITIALIZATION_FAILED' });
+ }
+ const source = Buffer.from('numeric control 13|29');
+ for (const value of [0, 1, 2]) {
+ assert.deepEqual(zlib.zstdDecompressSync(zlib.zstdCompressSync(source, { params: { 160: value } })), source);
+ }
+ for (const key of [200, 201, 202]) {
+ const enabled = zlib.zstdCompressSync(source, { params: { [key]: 1 } });
+ for (const value of [-2, 2, 3, 100]) {
+ assert.deepEqual(zlib.zstdCompressSync(source, { params: { [key]: value } }), enabled);
+ }
+ }
+ }],
+ ['stream backpressure', async () => {
+ assert.throws(() => zlib.createZstdDecompress({ chunkSize: Number.MAX_SAFE_INTEGER + 1 }),
+ { code: 'ERR_OUT_OF_RANGE' });
+ const source = Buffer.alloc(1024 * 1024, 0x61);
+ const decoder = zlib.createZstdDecompress({ chunkSize: 64, readableHighWaterMark: 64 });
+ const chunks = [];
+ let written = false;
+ const done = new Promise((resolve, reject) => {
+ decoder.on('error', reject);
+ decoder.on('end', resolve);
+ });
+ decoder.write(zlib.zstdCompressSync(source), error => {
+ if (error) decoder.destroy(error);
+ written = true;
+ });
+ await new Promise(resolve => setTimeout(resolve, 0));
+ const buffered = decoder.readableLength;
+ const writeCompleted = written;
+ decoder.on('data', chunk => chunks.push(chunk));
+ decoder.end();
+ await done;
+ assert.deepEqual(Buffer.concat(chunks), source);
+ assert.equal(writeCompleted, false);
+ assert.ok(buffered <= 64, `paused decoder buffered ${buffered} bytes`);
+ assert.ok(chunks.every(chunk => chunk.length <= 64), 'output exceeds chunkSize');
+
+ const random = Buffer.alloc(300000);
+ let seed = 0x12345678;
+ for (let i = 0; i < random.length; i++) {
+ seed ^= seed << 13; seed ^= seed >>> 17; seed ^= seed << 5;
+ random[i] = seed & 255;
+ }
+ const encoder = zlib.createZstdCompress({ chunkSize: 64, readableHighWaterMark: 64 });
+ const encoded = [];
+ const encodedDone = new Promise((resolve, reject) => {
+ encoder.on('error', reject); encoder.on('end', resolve);
+ });
+ encoder.write(random);
+ encoder.end();
+ await new Promise(resolve => setTimeout(resolve, 0));
+ const encodedBuffered = encoder.readableLength;
+ encoder.on('data', chunk => encoded.push(chunk));
+ await encodedDone;
+ assert.ok(encodedBuffered <= 64, `paused encoder buffered ${encodedBuffered} bytes`);
+ assert.ok(encoded.every(chunk => chunk.length <= 64), 'encoded output exceeds chunkSize');
+ assert.deepEqual(zlib.zstdDecompressSync(Buffer.concat(encoded)), random);
+
+ const frame = zlib.zstdCompressSync(source);
+ assert.deepEqual(zlib.zstdDecompressSync(frame, { chunkSize: 64, maxOutputLength: source.length }), source);
+ assert.throws(() => zlib.zstdDecompressSync(frame, { chunkSize: 64, maxOutputLength: source.length - 1 }),
+ { code: 'ERR_BUFFER_TOO_LARGE' });
+ }],
+ ['paused stream destruction', async () => {
+ const decoder = zlib.createZstdDecompress({ chunkSize: 64, readableHighWaterMark: 64 });
+ const failure = new Error('cancel paused decoder');
+ let callbacks = 0;
+ const closed = new Promise(resolve => decoder.on('close', resolve));
+ decoder.on('error', error => assert.equal(error, failure));
+ decoder.write(zlib.zstdCompressSync(Buffer.alloc(1024 * 1024)), () => callbacks++);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ decoder.destroy(failure);
+ await closed;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ assert.equal(decoder.destroyed, true);
+ assert.ok(callbacks <= 1);
+ }],
+ ['stream string encodings', async () => {
+ const source = Buffer.from('base64 decoder control 13|29');
+ const frame = zlib.zstdCompressSync(source);
+ for (const [decode, input, encoding, defaultEncoding, expected] of [
+ [false, 'é', 'latin1', undefined, Buffer.from([0xe9])],
+ [false, 'é', undefined, 'latin1', Buffer.from([0xe9])],
+ [true, frame.toString('base64'), 'base64', undefined, source],
+ ]) {
+ const engine = decode ? zlib.createZstdDecompress({ decodeStrings: false }) :
+ zlib.createZstdCompress({ decodeStrings: false, defaultEncoding });
+ const chunks = [];
+ const done = new Promise((resolve, reject) => {
+ engine.on('error', reject); engine.on('end', resolve);
+ });
+ engine.on('data', chunk => chunks.push(chunk));
+ engine.end(input, encoding);
+ await done;
+ const output = Buffer.concat(chunks);
+ assert.deepEqual(decode ? output : zlib.zstdDecompressSync(output), expected);
+ }
+ }],
+ ['finalizer method capture', async () => {
+ const { register, unregister } = FinalizationRegistry.prototype;
+ try {
+ FinalizationRegistry.prototype.register = () => { throw new Error('mutable register'); };
+ FinalizationRegistry.prototype.unregister = () => { throw new Error('mutable unregister'); };
+ const source = Buffer.from('captured cleanup methods 13|29');
+ assert.deepEqual(zlib.zstdDecompressSync(zlib.zstdCompressSync(source)), source);
+ await streamRoundTrip(source, zlib.createZstdCompress(), zlib.createZstdDecompress());
+ } finally {
+ FinalizationRegistry.prototype.register = register;
+ FinalizationRegistry.prototype.unregister = unregister;
+ }
+ }],
+ ['callback cancellation and completion', async () => {
+ const source = Buffer.from('callback lifecycle control 13|29');
+ const frame = zlib.zstdCompressSync(source);
+ const aborted = new AbortController();
+ aborted.abort();
+ for (const create of [zlib.createZstdCompress, zlib.createZstdDecompress]) {
+ const engine = create({ signal: aborted.signal });
+ const closed = new Promise(resolve => engine.on('close', resolve));
+ const error = await new Promise(resolve => engine.on('error', resolve));
+ await closed;
+ assert.equal(error.code, 'ABORT_ERR');
+ }
+ assert.deepEqual(zlib.zstdDecompressSync(zlib.zstdCompressSync(source,
+ { signal: aborted.signal }), { signal: aborted.signal }), source);
+ for (const [operation, input] of [[zlib.zstdCompress, source], [zlib.zstdDecompress, frame]]) {
+ for (const initiallyAborted of [false, true]) {
+ const controller = new AbortController();
+ if (initiallyAborted) controller.abort();
+ let callbacks = 0;
+ const done = new Promise(resolve => operation(input, { signal: controller.signal }, error => {
+ callbacks++; resolve(error);
+ }));
+ if (!initiallyAborted) controller.abort();
+ assert.equal((await done)?.code, 'ABORT_ERR');
+ await new Promise(resolve => setTimeout(resolve, 0));
+ assert.equal(callbacks, 1);
+ assert.equal(getEventListeners(controller.signal, 'abort').length, 0);
+ }
+ const controller = new AbortController();
+ const result = await new Promise((resolve, reject) => operation(input,
+ { signal: controller.signal, info: true }, (error, value) => error ? reject(error) : resolve(value)));
+ assert.ok(Buffer.isBuffer(result.buffer));
+ assert.deepEqual(operation === zlib.zstdCompress ? zlib.zstdDecompressSync(result.buffer) : result.buffer, source);
+ await new Promise(resolve => setTimeout(resolve, 0));
+ assert.equal(getEventListeners(controller.signal, 'abort').length, 0);
+ }
+ const error = await new Promise(resolve => zlib.zstdDecompress(frame,
+ { maxOutputLength: source.length - 1 }, error => resolve(error)));
+ assert.equal(error?.code, 'ERR_BUFFER_TOO_LARGE');
+ const invalid = await new Promise(resolve => zlib.zstdDecompress(Buffer.from([1, 2]), error => resolve(error)));
+ assert.ok(invalid);
+ }],
+ ]) {
+ try { await check(); console.log(`${name}: PASS`); }
+ catch (error) { failures.push(name); console.log(`${name}: FAIL ${error.message}`); }
+ }
+ assert.deepEqual(failures, []);
+ return true;
+}
+
+export function testZstdDisabled() {
+ const source = Buffer.from('normal tier: gzip stays available, zstd does not');
+ assert.deepEqual(gunzipSync(gzipSync(source)), source);
+ for (const operation of [zlib.zstdCompressSync, zlib.zstdDecompressSync]) {
+ assert.throws(() => operation(source), { code: 'ERR_ZLIB_INITIALIZATION_FAILED' });
+ }
+ return true;
+}
diff --git a/examples/runtime/zlib/wit/zlib.wit b/examples/runtime/zlib/wit/zlib.wit
index d426ee1f4..1fe357d79 100644
--- a/examples/runtime/zlib/wit/zlib.wit
+++ b/examples/runtime/zlib/wit/zlib.wit
@@ -2,4 +2,7 @@ package quickjs:zlib;
world zlib {
export test-byte-transfer: func() -> bool;
+ export test-zstd: func() -> bool;
+ export test-zstd-contracts: func() -> bool;
+ export test-zstd-disabled: func() -> bool;
}
diff --git a/tests/goldenfiles/generated_types_zlib_exports.d.ts b/tests/goldenfiles/generated_types_zlib_exports.d.ts
index c2b0130cc..32e7e71bb 100644
--- a/tests/goldenfiles/generated_types_zlib_exports.d.ts
+++ b/tests/goldenfiles/generated_types_zlib_exports.d.ts
@@ -1,3 +1,6 @@
declare module 'zlib' {
export function testByteTransfer(): boolean;
+ export function testZstd(): boolean;
+ export function testZstdContracts(): boolean;
+ export function testZstdDisabled(): boolean;
}
diff --git a/tests/node_compat/config.jsonc b/tests/node_compat/config.jsonc
index e02fbb956..84cf899a1 100644
--- a/tests/node_compat/config.jsonc
+++ b/tests/node_compat/config.jsonc
@@ -4052,7 +4052,7 @@
}
},
"parallel/test-worker-message-port-close-while-receiving.js": {},
- "parallel/test-zlib-zero-byte.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
+ "parallel/test-zlib-zero-byte.js": {},
"parallel/test-async-hooks-vm-gc.js": {},
"parallel/test-finalization-registry-shutdown.js": {},
"parallel/test-heapdump-async-hooks-init-promise.js": { "category": "engine-difference", "reason": "v8.getHeapSnapshot is V8-specific and unavailable in QuickJS" },
@@ -4198,10 +4198,10 @@
}
},
"parallel/test-zlib-flush-flags.js": {},
- "parallel/test-zlib-convenience-methods.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
+ "parallel/test-zlib-convenience-methods.js": {},
"parallel/test-zlib-from-string.js": {},
"parallel/test-zlib-brotli-from-string.js": {},
- "parallel/test-zlib-empty-buffer.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
+ "parallel/test-zlib-empty-buffer.js": {},
"parallel/test-zlib-deflate-constructors.js": {},
"parallel/test-zlib-not-string-or-buffer.js": {},
"parallel/test-zlib-sync-no-event.js": {},
@@ -4252,20 +4252,20 @@
"parallel/test-zlib-kmaxlength-rangeerror.js": {},
"parallel/test-zlib-maxOutputLength.js": {},
"parallel/test-zlib-params.js": {},
- "parallel/test-zlib-random-byte-pipes.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
+ "parallel/test-zlib-random-byte-pipes.js": {},
"parallel/test-zlib-reset-before-write.js": {},
"parallel/test-zlib-truncated.js": {
"split": true,
"subtests": {
- "block_00_value_as_truncated_input": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
- "block_01_mistaken_for_an_empty_truncated_frame": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
- "block_02_must_report_that_the_frame_is_incomplete": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }
+ "block_00_value_as_truncated_input": {},
+ "block_01_mistaken_for_an_empty_truncated_frame": {},
+ "block_02_must_report_that_the_frame_is_incomplete": {}
}
},
"parallel/test-zlib-unused-weak.js": { "category": "node-internals", "reason": "asserts internal zlib native-handle weak-reference/external-memory behavior" },
"parallel/test-zlib-write-after-close.js": {},
"parallel/test-zlib-write-after-end.js": {},
- "parallel/test-zlib-write-after-flush.js": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
+ "parallel/test-zlib-write-after-flush.js": {},
"parallel/test-zlib-close-after-error.js": { "category": "node-internals", "reason": "asserts private zlib stream _closed state after error" },
"parallel/test-zlib-close-in-ondata.js": {},
"parallel/test-zlib-destroy.js": {
@@ -10665,8 +10665,8 @@
"parallel/test-zlib.js": {
"split": true,
"subtests": {
- "block_00_block_00": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" },
- "block_01_block_01": { "category": "known-gap", "reason": "zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented" }
+ "block_00_block_00": {},
+ "block_01_block_01": {}
}
},
"sequential/test-async-wrap-getasyncid.js": {
@@ -16832,11 +16832,11 @@
"test_01_brotlidecompress_reset_preserves_its_dictionary": {}
}
},
- "parallel/test-zlib-decode-strings.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
+ "parallel/test-zlib-decode-strings.js": {},
"parallel/test-zlib-negative-zero.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
"parallel/test-zlib-reject-garbage-after-end.js": {
- "category": "unevaluated",
- "reason": "newly discovered, not yet evaluated",
+ "category": "known-gap",
+ "reason": "shared non-zstd rejectGarbageAfterEnd assertions fail before complete subtest qualification",
"split": true,
"subtests": {
"test_00_zstd_decompresses_concatenated_frames_regardless_of_chunking": {},
@@ -17211,15 +17211,13 @@
"test_10_a_deflate_and_a_zstd_member_each_stream_back_through_content": {}
}
},
- "parallel/test-zlib-zstd-dictionary.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
- "parallel/test-zlib-zstd-flush.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
- "parallel/test-zlib-zstd-from-string.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
- "parallel/test-zlib-zstd-from-zstd.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
- "parallel/test-zlib-zstd-kmaxlength-rangeerror.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
- "parallel/test-zlib-zstd-pledged-src-size.js": { "category": "unevaluated", "reason": "newly discovered, not yet evaluated" },
+ "parallel/test-zlib-zstd-dictionary.js": {},
+ "parallel/test-zlib-zstd-flush.js": {},
+ "parallel/test-zlib-zstd-from-string.js": {},
+ "parallel/test-zlib-zstd-from-zstd.js": {},
+ "parallel/test-zlib-zstd-kmaxlength-rangeerror.js": {},
+ "parallel/test-zlib-zstd-pledged-src-size.js": {},
"parallel/test-zlib-zstd-reset-incomplete-frame.js": {
- "category": "unevaluated",
- "reason": "newly discovered, not yet evaluated",
"split": true,
"subtests": {
"test_00_zstdcompress_reset_throws_when_an_incomplete_frame_has_emitt": {},
@@ -17230,8 +17228,6 @@
}
},
"parallel/test-zlib-zstd-reset.js": {
- "category": "unevaluated",
- "reason": "newly discovered, not yet evaluated",
"split": true,
"subtests": {
"test_00_zstdcompress_reset_preserves_its_initial_options": {},
@@ -17240,8 +17236,6 @@
}
},
"parallel/test-zlib-zstd.js": {
- "category": "unevaluated",
- "reason": "newly discovered, not yet evaluated",
"split": true,
"subtests": {
"block_00_block_00": {},
diff --git a/tests/node_compat/report.md b/tests/node_compat/report.md
index 4ed8b14d1..d1247247e 100644
--- a/tests/node_compat/report.md
+++ b/tests/node_compat/report.md
@@ -8,21 +8,21 @@ This report is generated from `config.jsonc` and the pinned vendored Node.js sou
Primary compatibility is measured over the public API surface we can provide: CI-enforced passing (`runnable`) plus `known-gap`. WASI-impossible tests, engine differences, unevaluated tests, and Node.js-internals tests are acknowledged separately and excluded from the primary percentage.
-**Primary compatibility (CI-enforced):** 3200/4499 (71.1%)
+**Primary compatibility (CI-enforced):** 3228/4523 (71.4%)
When comparing revisions, read the runnable count and secondary full-public percentage alongside the primary percentage. Reclassifying a test into an excluded category can increase the primary percentage without increasing runnable coverage.
| Classification | Count | Primary % | Public inventory % | All listed % |
|----------------|-------|-----------|--------------------|--------------|
-| ✅ passing (runnable) | 3200 | 71.1% | 33.1% | 29.6% |
-| 🧩 known gap | 1299 | 28.9% | 13.5% | 12.0% |
+| ✅ passing (runnable) | 3228 | 71.4% | 33.4% | 29.9% |
+| 🧩 known gap | 1295 | 28.6% | 13.4% | 12.0% |
| 🚫 WASI-impossible (excluded) | 1148 | — | 11.9% | 10.6% |
| ⚙️ engine difference (excluded) | 167 | — | 1.7% | 1.5% |
-| ❔ unevaluated (excluded) | 3840 | — | 39.8% | 35.6% |
+| ❔ unevaluated (excluded) | 3816 | — | 39.5% | 35.4% |
| 🔒 Node.js internals (excluded) | 1140 | — | — | 10.6% |
| **Total** | **10794** | | | **100.0%** |
-Secondary full-public compatibility, including public tests that are currently excluded from primary: **3200/9654 (33.1%)**.
+Secondary full-public compatibility, including public tests that are currently excluded from primary: **3228/9654 (33.4%)**.
## Inventory by Module
@@ -88,7 +88,7 @@ Secondary full-public compatibility, including public tests that are currently e
| webstreams | 89 | 66 | 1 | 0 | 0 | 21 | 1 | 98.5% | 75.0% |
| whatwg | 319 | 43 | 32 | 0 | 0 | 56 | 188 | 57.3% | 32.8% |
| worker_threads | 202 | 25 | 29 | 127 | 0 | 13 | 8 | 46.3% | 12.9% |
-| zlib | 324 | 45 | 15 | 0 | 0 | 260 | 4 | 75.0% | 14.1% |
+| zlib | 324 | 73 | 11 | 0 | 0 | 236 | 4 | 86.9% | 22.8% |
## Split Test Summary
@@ -1040,9 +1040,9 @@ Secondary full-public compatibility, including public tests that are currently e
| `test-zlib-dictionary-fail.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 |
| `test-zlib-failed-init.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 |
| `test-zlib-invalid-input.js` | 2 | 0 | 2 | 0 | 0 | 0 | 0 |
-| `test-zlib-reject-garbage-after-end.js` | 6 | 0 | 0 | 0 | 0 | 6 | 0 |
+| `test-zlib-reject-garbage-after-end.js` | 6 | 0 | 6 | 0 | 0 | 0 | 0 |
| `test-zlib-reset-incomplete-output.js` | 7 | 0 | 0 | 0 | 0 | 7 | 0 |
-| `test-zlib-truncated.js` | 3 | 0 | 3 | 0 | 0 | 0 | 0 |
+| `test-zlib-truncated.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 |
| `test-zlib-type-error.js` | 4 | 0 | 0 | 0 | 0 | 4 | 0 |
| `test-zlib-zero-windowBits.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 |
| `test-zlib-zip-coverage.js` | 65 | 0 | 0 | 0 | 0 | 65 | 0 |
@@ -1063,10 +1063,10 @@ Secondary full-public compatibility, including public tests that are currently e
| `test-zlib-zip-writable.js` | 13 | 0 | 0 | 0 | 0 | 13 | 0 |
| `test-zlib-zip-zip64.js` | 2 | 0 | 0 | 0 | 0 | 2 | 0 |
| `test-zlib-zip.js` | 11 | 0 | 0 | 0 | 0 | 11 | 0 |
-| `test-zlib-zstd-reset-incomplete-frame.js` | 5 | 0 | 0 | 0 | 0 | 5 | 0 |
-| `test-zlib-zstd-reset.js` | 3 | 0 | 0 | 0 | 0 | 3 | 0 |
-| `test-zlib-zstd.js` | 3 | 0 | 0 | 0 | 0 | 3 | 0 |
-| `test-zlib.js` | 2 | 0 | 2 | 0 | 0 | 0 | 0 |
+| `test-zlib-zstd-reset-incomplete-frame.js` | 5 | 5 | 0 | 0 | 0 | 0 | 0 |
+| `test-zlib-zstd-reset.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 |
+| `test-zlib-zstd.js` | 3 | 3 | 0 | 0 | 0 | 0 | 0 |
+| `test-zlib.js` | 2 | 2 | 0 | 0 | 0 | 0 | 0 |
| `test-async-wrap-getasyncid.js` | 18 | 0 | 0 | 0 | 0 | 0 | 18 |
| `test-benchmark-node-bench-tools.js` | 16 | 0 | 0 | 0 | 0 | 16 | 0 |
| `test-child-process-execsync.js` | 7 | 0 | 0 | 7 | 0 | 0 | 0 |
@@ -1090,7 +1090,7 @@ Secondary full-public compatibility, including public tests that are currently e
## Classified Non-Runnable Tests
-### known gap (1299)
+### known gap (1295)
| Reason | Count | Example entries |
|--------|-------|-----------------|
@@ -1113,7 +1113,6 @@ Secondary full-public compatibility, including public tests that are currently e
| rooted symlink targets cannot be resolved inside a WASI preopen; the adapter rejects them at creation, while persistent relative symlinks are covered by runtime tests | 11 | `es-module/test-esm-preserve-symlinks-main.js`, `es-module/test-esm-preserve-symlinks.js`, `es-module/test-esm-symlink-main.js`, ... (+8) |
| wasi:sockets UDP implementation hangs in wasmtime | 11 | `parallel/test-dgram-implicit-bind.js`, `parallel/test-dgram-multicast-set-interface.js#block_00_block_00`, `parallel/test-dgram-multicast-set-interface.js#block_02_block_02`, ... (+8) |
| dgram multicast membership APIs are not implemented (ENOSYS) | 10 | `parallel/test-dgram-membership.js#block_02_addmembership_with_no_argument_should_throw`, `parallel/test-dgram-membership.js#block_03_dropmembership_with_no_argument_should_throw`, `parallel/test-dgram-membership.js#block_04_addmembership_with_invalid_multicast_address_should_throw`, ... (+7) |
-| zlib zstd compression APIs (zstdCompress, ZstdCompress) are not implemented | 10 | `parallel/test-zlib-convenience-methods.js`, `parallel/test-zlib-empty-buffer.js`, `parallel/test-zlib-random-byte-pipes.js`, ... (+7) |
| async_hooks not fully implemented | 9 | `parallel/test-async-hooks-destroy-on-gc.js`, `parallel/test-async-hooks-disable-during-promise.js`, `parallel/test-async-hooks-disable-gc-tracking.js`, ... (+6) |
| net.js TCP implementation incomplete - needs event handling and API fixes | 9 | `parallel/test-net-connect-nodelay.js`, `parallel/test-net-connect-paused-connection.js`, `parallel/test-net-during-close.js`, ... (+6) |
| spawn() AbortSignal handling is incomplete (exit code/signal/error semantics differ from Node) | 9 | `parallel/test-child-process-spawn-controller.js#block_00_block_00`, `parallel/test-child-process-spawn-controller.js#block_01_block_01`, `parallel/test-child-process-spawn-controller.js#block_02_block_02`, ... (+6) |
@@ -1129,6 +1128,7 @@ Secondary full-public compatibility, including public tests that are currently e
| inherited: common.canCreateSymLink shim always returns false, so symlink permission tests are skipped | 6 | `parallel/test-permission-fs-symlink-target-write.js#block_00_block_00`, `parallel/test-permission-fs-symlink-target-write.js#block_01_block_01`, `parallel/test-permission-fs-symlink.js#block_00_block_00`, ... (+3) |
| inherited: perf_hooks createHistogram/monitorEventLoopDelay are not implemented | 6 | `parallel/test-perf-hooks-histogram.js#block_00_block_00`, `parallel/test-perf-hooks-histogram.js#block_01_block_01`, `parallel/test-perf-hooks-histogram.js#block_02_block_02`, ... (+3) |
| same-process import.meta.resolve behavior is covered by runtime tests; remaining vendored failure requires child_process execPath emulation for --input-type/--import ESM CLI modes | 6 | `es-module/test-esm-import-meta-resolve.mjs#block_00_block_00`, `es-module/test-esm-import-meta-resolve.mjs#block_01_block_01`, `es-module/test-esm-import-meta-resolve.mjs#block_02_block_02`, ... (+3) |
+| shared non-zstd rejectGarbageAfterEnd assertions fail before complete subtest qualification | 6 | `parallel/test-zlib-reject-garbage-after-end.js#test_00_zstd_decompresses_concatenated_frames_regardless_of_chunking`, `parallel/test-zlib-reject-garbage-after-end.js#test_01_zstd_trailing_junk_handling_is_independent_of_chunking`, `parallel/test-zlib-reject-garbage-after-end.js#test_02_zstd_handles_incomplete_trailing_frame_identifiers_as_junk`, ... (+3) |
| the test's meaningful body requires rooted symlink targets; common.canCreateSymLink skips it under the supported relative-only WASI boundary | 6 | `parallel/test-fs-options-immutable.js#block_00_block_00`, `parallel/test-fs-options-immutable.js#block_01_block_01`, `parallel/test-fs-options-immutable.js#block_02_block_02`, ... (+3) |
| common-shim spawnPromisified child emulation does not support --experimental-webstorage/--localstorage-file flags | 5 | `parallel/test-webstorage.js#test_00_storage_instances_cannot_be_created_in_userland`, `parallel/test-webstorage.js#test_02_sessionstorage_is_not_persisted`, `parallel/test-webstorage.js#test_05_localstorage_is_not_persisted_if_it_is_unused`, ... (+2) |
| inherited: buffer.transcode and ICU transcoding are not implemented | 5 | `parallel/test-icu-transcode.js#block_00_block_00`, `parallel/test-icu-transcode.js#block_01_block_01`, `parallel/test-icu-transcode.js#block_02_test_that_uint8array_arguments_are_okay`, ... (+2) |
@@ -1957,11 +1957,11 @@ Secondary full-public compatibility, including public tests that are currently e
| vm.Script.createCachedData relies on V8 code cache internals unavailable in QuickJS | 1 | `parallel/test-vm-createcacheddata.js` |
| vm.SourceTextModule dynamic import referrer realm semantics depend on Node VM realm behavior not modeled by the QuickJS host | 1 | `parallel/test-vm-module-referrer-realm.mjs` |
-### unevaluated (3840)
+### unevaluated (3816)
| Reason | Count | Example entries |
|--------|-------|-----------------|
-| newly discovered, not yet evaluated | 3639 | `es-module/test-cjs-defer-static-import-eval.mjs`, `es-module/test-defer-import-builtin-module.mjs`, `es-module/test-defer-import-eval-with-tla.mjs`, ... (+3636) |
+| newly discovered, not yet evaluated | 3615 | `es-module/test-cjs-defer-static-import-eval.mjs`, `es-module/test-defer-import-builtin-module.mjs`, `es-module/test-defer-import-eval-with-tla.mjs`, ... (+3612) |
| newly discovered subtest, not yet evaluated | 201 | `es-module/test-esm-json.mjs#test_01_should_load_json_with_import_calls`, `parallel/test-assert-deep.js#test_01_loose_deepequal`, `parallel/test-assert-deep.js#test_08_deepstrictequal_handles_shared_expected_array_elements_after`, ... (+198) |
### Node.js internals (1140)
diff --git a/tests/runtime/zlib.rs b/tests/runtime/zlib.rs
index f77918f8f..2603333e5 100644
--- a/tests/runtime/zlib.rs
+++ b/tests/runtime/zlib.rs
@@ -22,3 +22,37 @@ async fn zlib_byte_transfer(#[tagged_as("zlib")] compiled: &CompiledTest) -> any
assert_eq!(result?, Some(Val::Bool(true)));
Ok(())
}
+
+#[test]
+async fn zlib_zstd(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Result<()> {
+ let (result, output) =
+ invoke_and_capture_output(compiled.wasm_path(), None, "test-zstd", &[]).await;
+ println!("Output:\n{}", output);
+ assert_eq!(result?, Some(Val::Bool(true)));
+ Ok(())
+}
+
+#[test]
+async fn zlib_zstd_contracts(#[tagged_as("zlib")] compiled: &CompiledTest) -> anyhow::Result<()> {
+ let (result, output) =
+ invoke_and_capture_output(compiled.wasm_path(), None, "test-zstd-contracts", &[]).await;
+ println!("Output:\n{}", output);
+ assert_eq!(result?, Some(Val::Bool(true)));
+ Ok(())
+}
+
+#[test]
+async fn zlib_zstd_disabled() -> anyhow::Result<()> {
+ // Keep this component's Cargo output separate from the full-tier dependency.
+ let compiled = CompiledTest::new_with_features(
+ Utf8Path::new("examples/runtime/zlib"),
+ false,
+ FeatureCombination::Normal,
+ )
+ .await?;
+ let (result, output) =
+ invoke_and_capture_output(compiled.wasm_path(), None, "test-zstd-disabled", &[]).await;
+ println!("Output:\n{}", output);
+ assert_eq!(result?, Some(Val::Bool(true)));
+ Ok(())
+}