test: add tests for experimental stream/iter implementation

Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-By: Claude/Opus 4.6
PR-URL: https://github.com/nodejs/node/pull/62066
Reviewed-By: Robert Nagy <ronagy@icloud.com>
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
This commit is contained in:
James M Snell authored and Antoine du Hamel committed 2026-03-30 17:20:29 +02:00
1 parent e1f0d2a014
commit fd41ef31f6
39 files changed
+8924

No files matched your search

@@ -0,0 +1,440 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const { open } = fs.promises;
const path = require('path');
const tmpdir = require('../common/tmpdir');
const { text, bytes } = require('stream/iter');
tmpdir.refresh();
const tmpDir = tmpdir.path;
// =============================================================================
// Basic pull()
// =============================================================================
async function testBasicPull() {
const filePath = path.join(tmpDir, 'pull-basic.txt');
fs.writeFileSync(filePath, 'hello from file');
const fh = await open(filePath, 'r');
try {
const readable = fh.pull();
const data = await text(readable);
assert.strictEqual(data, 'hello from file');
} finally {
await fh.close();
}
}
async function testPullBinary() {
const filePath = path.join(tmpDir, 'pull-binary.bin');
const buf = Buffer.alloc(256);
for (let i = 0; i < 256; i++) buf[i] = i;
fs.writeFileSync(filePath, buf);
const fh = await open(filePath, 'r');
try {
const readable = fh.pull();
const data = await bytes(readable);
assert.strictEqual(data.byteLength, 256);
for (let i = 0; i < 256; i++) {
assert.strictEqual(data[i], i);
}
} finally {
await fh.close();
}
}
async function testPullEmptyFile() {
const filePath = path.join(tmpDir, 'pull-empty.txt');
fs.writeFileSync(filePath, '');
const fh = await open(filePath, 'r');
try {
const readable = fh.pull();
const data = await bytes(readable);
assert.strictEqual(data.byteLength, 0);
} finally {
await fh.close();
}
}
// =============================================================================
// Large file (multi-chunk)
// =============================================================================
async function testPullLargeFile() {
const filePath = path.join(tmpDir, 'pull-large.bin');
// Write 64KB - enough for multiple 16KB read chunks
const size = 64 * 1024;
const buf = Buffer.alloc(size, 0x42);
fs.writeFileSync(filePath, buf);
const fh = await open(filePath, 'r');
try {
const readable = fh.pull();
const data = await bytes(readable);
assert.strictEqual(data.byteLength, size);
// Verify content
for (let i = 0; i < data.byteLength; i++) {
assert.strictEqual(data[i], 0x42);
}
} finally {
await fh.close();
}
}
// =============================================================================
// With transforms
// =============================================================================
async function testPullWithTransform() {
const filePath = path.join(tmpDir, 'pull-transform.txt');
fs.writeFileSync(filePath, 'hello');
const fh = await open(filePath, 'r');
try {
const upper = (chunks) => {
if (chunks === null) return null;
return chunks.map((c) => {
const str = new TextDecoder().decode(c);
return new TextEncoder().encode(str.toUpperCase());
});
};
const readable = fh.pull(upper);
const data = await text(readable);
assert.strictEqual(data, 'HELLO');
} finally {
await fh.close();
}
}
// =============================================================================
// autoClose option
// =============================================================================
async function testPullAutoClose() {
const filePath = path.join(tmpDir, 'pull-autoclose.txt');
fs.writeFileSync(filePath, 'auto close data');
const fh = await open(filePath, 'r');
const readable = fh.pull({ autoClose: true });
const data = await text(readable);
assert.strictEqual(data, 'auto close data');
// After consuming with autoClose, the file handle should be closed
// Trying to read again should throw
await assert.rejects(
async () => {
await fh.stat();
},
(err) => err.code === 'ERR_INVALID_STATE' || err.code === 'EBADF',
);
}
// =============================================================================
// Locking
// =============================================================================
async function testPullLocking() {
const filePath = path.join(tmpDir, 'pull-lock.txt');
fs.writeFileSync(filePath, 'lock data');
const fh = await open(filePath, 'r');
try {
// First pull locks the handle
const readable = fh.pull();
// Second pull while locked should throw
assert.throws(
() => fh.pull(),
{ code: 'ERR_INVALID_STATE' },
);
// Consume the first stream to unlock
await text(readable);
// Now it should be usable again
const readable2 = fh.pull();
const data = await text(readable2);
assert.strictEqual(data, ''); // Already read to end
} finally {
await fh.close();
}
}
// =============================================================================
// Closed handle
// =============================================================================
async function testPullClosedHandle() {
const filePath = path.join(tmpDir, 'pull-closed.txt');
fs.writeFileSync(filePath, 'data');
const fh = await open(filePath, 'r');
await fh.close();
assert.throws(
() => fh.pull(),
{ code: 'ERR_INVALID_STATE' },
);
}
// =============================================================================
// AbortSignal
// =============================================================================
async function testPullAbortSignal() {
const filePath = path.join(tmpDir, 'pull-abort.txt');
// Write enough data that we can abort mid-stream
fs.writeFileSync(filePath, 'a'.repeat(1024));
const ac = new AbortController();
const fh = await open(filePath, 'r');
try {
ac.abort();
const readable = fh.pull({ signal: ac.signal });
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) {
assert.fail('Should not reach here');
}
},
(err) => err.name === 'AbortError',
);
} finally {
await fh.close();
}
}
// =============================================================================
// Iterate batches directly
// =============================================================================
async function testPullIterateBatches() {
const filePath = path.join(tmpDir, 'pull-batches.txt');
fs.writeFileSync(filePath, 'batch data');
const fh = await open(filePath, 'r');
try {
const readable = fh.pull();
const batches = [];
for await (const batch of readable) {
batches.push(batch);
// Each batch should be an array of Uint8Array
assert.ok(Array.isArray(batch));
for (const chunk of batch) {
assert.ok(chunk instanceof Uint8Array);
}
}
assert.ok(batches.length > 0);
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with start option - read from specific position
// =============================================================================
async function testPullStart() {
const filePath = path.join(tmpDir, 'pull-start.txt');
fs.writeFileSync(filePath, 'AAABBBCCC');
const fh = await open(filePath, 'r');
try {
// Read from offset 3
const data = await text(fh.pull({ start: 3 }));
assert.strictEqual(data, 'BBBCCC');
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with limit option - read at most N bytes
// =============================================================================
async function testPullLimit() {
const filePath = path.join(tmpDir, 'pull-limit.txt');
fs.writeFileSync(filePath, 'Hello, World! Extra data here.');
const fh = await open(filePath, 'r');
try {
const data = await text(fh.pull({ limit: 13 }));
assert.strictEqual(data, 'Hello, World!');
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with start + limit - read a slice
// =============================================================================
async function testPullStartAndLimit() {
const filePath = path.join(tmpDir, 'pull-start-limit.txt');
fs.writeFileSync(filePath, 'AAABBBCCCDDD');
const fh = await open(filePath, 'r');
try {
// Read 3 bytes starting at offset 3
const data = await text(fh.pull({ start: 3, limit: 3 }));
assert.strictEqual(data, 'BBB');
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with limit larger than file - reads whole file
// =============================================================================
async function testPullLimitLargerThanFile() {
const filePath = path.join(tmpDir, 'pull-limit-large.txt');
fs.writeFileSync(filePath, 'short');
const fh = await open(filePath, 'r');
try {
const data = await text(fh.pull({ limit: 1000000 }));
assert.strictEqual(data, 'short');
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with limit spanning multiple chunks
// =============================================================================
async function testPullLimitMultiChunk() {
const filePath = path.join(tmpDir, 'pull-limit-multi.bin');
// 300KB file - spans multiple 128KB reads
const input = Buffer.alloc(300 * 1024, 'x');
fs.writeFileSync(filePath, input);
const fh = await open(filePath, 'r');
try {
// Read exactly 200KB from offset 50KB
const data = await bytes(fh.pull({ start: 50 * 1024, limit: 200 * 1024 }));
assert.strictEqual(data.byteLength, 200 * 1024);
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with start + limit + transforms
// =============================================================================
async function testPullStartLimitWithTransforms() {
const filePath = path.join(tmpDir, 'pull-start-limit-transform.txt');
fs.writeFileSync(filePath, 'aaabbbcccddd');
const fh = await open(filePath, 'r');
try {
const { compressGzip, decompressGzip } = require('zlib/iter');
const compressed = fh.pull(compressGzip(), { start: 3, limit: 6 });
const decompressed = await text(
require('stream/iter').pull(compressed, decompressGzip()));
assert.strictEqual(decompressed, 'bbbccc');
} finally {
await fh.close();
}
}
// =============================================================================
// pull() with chunkSize option
// =============================================================================
async function testPullChunkSize() {
const filePath = path.join(tmpDir, 'pull-chunksize.bin');
// Write 64KB of data
const input = Buffer.alloc(64 * 1024, 'z');
fs.writeFileSync(filePath, input);
const fh = await open(filePath, 'r');
try {
// Use 16KB chunks - should produce 4 batches
let batchCount = 0;
for await (const batch of fh.pull({ chunkSize: 16 * 1024 })) {
batchCount++;
for (const chunk of batch) {
assert.ok(chunk.byteLength <= 16 * 1024,
`Chunk ${chunk.byteLength} should be <= 16384`);
}
}
assert.strictEqual(batchCount, 4);
} finally {
await fh.close();
}
}
async function testPullChunkSizeSmall() {
const filePath = path.join(tmpDir, 'pull-chunksize-small.txt');
fs.writeFileSync(filePath, 'hello');
const fh = await open(filePath, 'r');
try {
// 1-byte chunks
let totalBytes = 0;
let batchCount = 0;
for await (const batch of fh.pull({ chunkSize: 1 })) {
batchCount++;
for (const chunk of batch) totalBytes += chunk.byteLength;
}
assert.strictEqual(totalBytes, 5);
assert.strictEqual(batchCount, 5);
} finally {
await fh.close();
}
}
async function testPullSyncArgumentValidation() {
const filePath = path.join(tmpDir, 'pull-arg-validation.txt');
fs.writeFileSync(filePath, 'data');
const fh = await open(filePath, 'r');
try {
assert.throws(() => fh.pull({ autoClose: 'no' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pull({ start: 'a' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pull({ limit: 'a' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pull({ chunkSize: 'a' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pull({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pull({ start: 1.1 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => fh.pull({ limit: 1.1 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => fh.pull({ chunkSize: 1.1 }), { code: 'ERR_OUT_OF_RANGE' });
} finally {
await fh.close();
}
}
Promise.all([
testBasicPull(),
testPullBinary(),
testPullEmptyFile(),
testPullLargeFile(),
testPullWithTransform(),
testPullAutoClose(),
testPullLocking(),
testPullClosedHandle(),
testPullAbortSignal(),
testPullIterateBatches(),
testPullStart(),
testPullLimit(),
testPullStartAndLimit(),
testPullLimitLargerThanFile(),
testPullLimitMultiChunk(),
testPullStartLimitWithTransforms(),
testPullChunkSize(),
testPullChunkSizeSmall(),
testPullSyncArgumentValidation(),
]).then(common.mustCall());
@@ -0,0 +1,498 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const fs = require('fs');
const { open } = fs.promises;
const path = require('path');
const tmpdir = require('../common/tmpdir');
const {
textSync,
bytesSync,
pipeToSync,
pullSync,
} = require('stream/iter');
const {
compressGzipSync,
decompressGzipSync,
} = require('zlib/iter');
tmpdir.refresh();
const tmpDir = tmpdir.path;
// =============================================================================
// Basic pullSync()
// =============================================================================
async function testBasicPullSync() {
const filePath = path.join(tmpDir, 'pullsync-basic.txt');
fs.writeFileSync(filePath, 'hello from sync file read');
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync());
assert.strictEqual(data, 'hello from sync file read');
} finally {
await fh.close();
}
}
// =============================================================================
// Large file (multi-chunk)
// =============================================================================
async function testLargeFile() {
const filePath = path.join(tmpDir, 'pullsync-large.txt');
const input = 'sync large data test. '.repeat(10000);
fs.writeFileSync(filePath, input);
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync());
assert.strictEqual(data, input);
} finally {
await fh.close();
}
}
// =============================================================================
// Binary data round-trip
// =============================================================================
async function testBinaryData() {
const filePath = path.join(tmpDir, 'pullsync-binary.bin');
const input = Buffer.alloc(200000);
for (let i = 0; i < input.length; i++) input[i] = i & 0xff;
fs.writeFileSync(filePath, input);
const fh = await open(filePath, 'r');
try {
const data = bytesSync(fh.pullSync());
assert.deepStrictEqual(Buffer.from(data), input);
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync with sync compression transform round-trip
// =============================================================================
async function testPullSyncWithCompression() {
const filePath = path.join(tmpDir, 'pullsync-compress-src.txt');
const dstPath = path.join(tmpDir, 'pullsync-compress-dst.gz');
const input = 'compress via sync pullSync. '.repeat(1000);
fs.writeFileSync(filePath, input);
// Compress: pullSync -> compressGzipSync -> write to file
const srcFh = await open(filePath, 'r');
const dstFh = await open(dstPath, 'w');
try {
const w = dstFh.writer();
pipeToSync(srcFh.pullSync(compressGzipSync()), w);
} finally {
await srcFh.close();
await dstFh.close();
}
// Verify compressed file is smaller
const compressedSize = fs.statSync(dstPath).size;
assert.ok(compressedSize < Buffer.byteLength(input),
`Compressed ${compressedSize} should be < original ` +
`${Buffer.byteLength(input)}`);
// Decompress and verify
const readFh = await open(dstPath, 'r');
try {
const result = textSync(readFh.pullSync(decompressGzipSync()));
assert.strictEqual(result, input);
} finally {
await readFh.close();
}
}
// =============================================================================
// pullSync with stateless transform
// =============================================================================
async function testPullSyncWithStatelessTransform() {
const filePath = path.join(tmpDir, 'pullsync-upper.txt');
fs.writeFileSync(filePath, 'hello world');
const upper = (chunks) => {
if (chunks === null) return null;
const out = new Array(chunks.length);
for (let j = 0; j < chunks.length; j++) {
const src = chunks[j];
const buf = Buffer.allocUnsafe(src.length);
for (let i = 0; i < src.length; i++) {
const b = src[i];
buf[i] = (b >= 0x61 && b <= 0x7a) ? b - 0x20 : b;
}
out[j] = buf;
}
return out;
};
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync(upper));
assert.strictEqual(data, 'HELLO WORLD');
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync with mixed stateless + stateful transforms
// =============================================================================
async function testPullSyncMixedTransforms() {
const filePath = path.join(tmpDir, 'pullsync-mixed.txt');
const input = 'mixed transform test '.repeat(500);
fs.writeFileSync(filePath, input);
const upper = (chunks) => {
if (chunks === null) return null;
const out = new Array(chunks.length);
for (let j = 0; j < chunks.length; j++) {
const src = chunks[j];
const buf = Buffer.allocUnsafe(src.length);
for (let i = 0; i < src.length; i++) {
const b = src[i];
buf[i] = (b >= 0x61 && b <= 0x7a) ? b - 0x20 : b;
}
out[j] = buf;
}
return out;
};
const fh = await open(filePath, 'r');
try {
// Upper + compress + decompress
const data = textSync(
pullSync(fh.pullSync(upper, compressGzipSync()), decompressGzipSync()),
);
assert.strictEqual(data, input.toUpperCase());
} finally {
await fh.close();
}
}
// =============================================================================
// autoClose: true - handle closed after iteration completes
// =============================================================================
async function testAutoClose() {
const filePath = path.join(tmpDir, 'pullsync-autoclose.txt');
fs.writeFileSync(filePath, 'auto close test');
const fh = await open(filePath, 'r');
const data = textSync(fh.pullSync({ autoClose: true }));
assert.strictEqual(data, 'auto close test');
// Handle should be closed
await assert.rejects(fh.stat(), { code: 'EBADF' });
}
// =============================================================================
// autoClose: true with early break
// =============================================================================
async function testAutoCloseEarlyBreak() {
const filePath = path.join(tmpDir, 'pullsync-autoclose-break.txt');
fs.writeFileSync(filePath, 'x'.repeat(1000000));
const fh = await open(filePath, 'r');
// eslint-disable-next-line no-unused-vars
for (const batch of fh.pullSync({ autoClose: true })) {
break; // Early exit
}
// Handle should be closed by autoClose
await assert.rejects(fh.stat(), { code: 'EBADF' });
}
// =============================================================================
// autoClose: false (default) - handle stays open
// =============================================================================
async function testNoAutoClose() {
const filePath = path.join(tmpDir, 'pullsync-no-autoclose.txt');
fs.writeFileSync(filePath, 'still open');
const fh = await open(filePath, 'r');
const data = textSync(fh.pullSync());
assert.strictEqual(data, 'still open');
// Handle should still be open and reusable
const stat = await fh.stat();
assert.ok(stat.size > 0);
await fh.close();
}
// =============================================================================
// Lock semantics - pullSync locks the handle
// =============================================================================
async function testLocked() {
const filePath = path.join(tmpDir, 'pullsync-locked.txt');
fs.writeFileSync(filePath, 'lock test');
const fh = await open(filePath, 'r');
const iter = fh.pullSync()[Symbol.iterator]();
iter.next(); // Start iteration, handle is locked
assert.throws(() => fh.pullSync(), {
code: 'ERR_INVALID_STATE',
});
assert.throws(() => fh.pull(), {
code: 'ERR_INVALID_STATE',
});
// Finish iteration to unlock
while (!iter.next().done) { /* drain */ }
await fh.close();
}
// =============================================================================
// Empty file
// =============================================================================
async function testEmptyFile() {
const filePath = path.join(tmpDir, 'pullsync-empty.txt');
fs.writeFileSync(filePath, '');
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync());
assert.strictEqual(data, '');
} finally {
await fh.close();
}
}
// =============================================================================
// pipeToSync: file-to-file sync pipeline
// =============================================================================
async function testPipeToSync() {
const srcPath = path.join(tmpDir, 'pullsync-pipeto-src.txt');
const dstPath = path.join(tmpDir, 'pullsync-pipeto-dst.txt');
const input = 'pipeToSync test data '.repeat(200);
fs.writeFileSync(srcPath, input);
const srcFh = await open(srcPath, 'r');
const dstFh = await open(dstPath, 'w');
try {
const w = dstFh.writer();
pipeToSync(srcFh.pullSync(), w);
} finally {
await srcFh.close();
await dstFh.close();
}
assert.strictEqual(fs.readFileSync(dstPath, 'utf8'), input);
}
// =============================================================================
// pullSync() with start option
// =============================================================================
async function testPullSyncStart() {
const filePath = path.join(tmpDir, 'pullsync-start.txt');
fs.writeFileSync(filePath, 'AAABBBCCC');
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync({ start: 3 }));
assert.strictEqual(data, 'BBBCCC');
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync() with limit option
// =============================================================================
async function testPullSyncLimit() {
const filePath = path.join(tmpDir, 'pullsync-limit.txt');
fs.writeFileSync(filePath, 'Hello, World! Extra data here.');
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync({ limit: 13 }));
assert.strictEqual(data, 'Hello, World!');
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync() with start + limit
// =============================================================================
async function testPullSyncStartAndLimit() {
const filePath = path.join(tmpDir, 'pullsync-start-limit.txt');
fs.writeFileSync(filePath, 'AAABBBCCCDDD');
const fh = await open(filePath, 'r');
try {
const data = textSync(fh.pullSync({ start: 3, limit: 3 }));
assert.strictEqual(data, 'BBB');
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync() with limit spanning multiple chunks
// =============================================================================
async function testPullSyncLimitMultiChunk() {
const filePath = path.join(tmpDir, 'pullsync-limit-multi.bin');
const input = Buffer.alloc(300 * 1024, 'x');
fs.writeFileSync(filePath, input);
const fh = await open(filePath, 'r');
try {
const data = bytesSync(fh.pullSync({ start: 50 * 1024, limit: 200 * 1024 }));
assert.strictEqual(data.byteLength, 200 * 1024);
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync() with start + limit + compression transform
// =============================================================================
async function testPullSyncStartLimitWithTransforms() {
const filePath = path.join(tmpDir, 'pullsync-start-limit-transform.txt');
fs.writeFileSync(filePath, 'aaabbbcccddd');
const fh = await open(filePath, 'r');
try {
const compressed = fh.pullSync(compressGzipSync(),
{ start: 3, limit: 6 });
const decompressed = textSync(pullSync(compressed, decompressGzipSync()));
assert.strictEqual(decompressed, 'bbbccc');
} finally {
await fh.close();
}
}
// =============================================================================
// pullSync() with start + autoClose
// =============================================================================
async function testPullSyncStartAutoClose() {
const filePath = path.join(tmpDir, 'pullsync-start-autoclose.txt');
fs.writeFileSync(filePath, 'AAABBBCCC');
const fh = await open(filePath, 'r');
const data = textSync(fh.pullSync({ start: 3, autoClose: true }));
assert.strictEqual(data, 'BBBCCC');
// Handle should be closed
await assert.rejects(fh.stat(), { code: 'EBADF' });
}
// =============================================================================
// pullSync() with chunkSize option
// =============================================================================
async function testPullSyncChunkSize() {
const filePath = path.join(tmpDir, 'pullsync-chunksize.bin');
const input = Buffer.alloc(64 * 1024, 'z');
fs.writeFileSync(filePath, input);
const fh = await open(filePath, 'r');
try {
let batchCount = 0;
for (const batch of fh.pullSync({ chunkSize: 16 * 1024 })) {
batchCount++;
for (const chunk of batch) {
assert.ok(chunk.byteLength <= 16 * 1024,
`Chunk ${chunk.byteLength} should be <= 16384`);
}
}
assert.strictEqual(batchCount, 4);
} finally {
await fh.close();
}
}
// =============================================================================
// writer() with chunkSize option (sync write threshold)
// =============================================================================
async function testWriterChunkSize() {
const filePath = path.join(tmpDir, 'pullsync-writer-chunksize.txt');
const fh = await open(filePath, 'w');
// Set chunkSize to 1024 - writes larger than this should fall back to async
const w = fh.writer({ chunkSize: 1024 });
// Small write should succeed sync
assert.strictEqual(w.writeSync(Buffer.alloc(512, 'a')), true);
// Write larger than chunkSize should return false
assert.strictEqual(w.writeSync(Buffer.alloc(2048, 'b')), false);
await w.end();
await fh.close();
}
// =============================================================================
// Argument validation
// =============================================================================
async function testPullArgumentValidation() {
const filePath = path.join(tmpDir, 'pull-arg-validation.txt');
fs.writeFileSync(filePath, 'data');
const fh = await open(filePath, 'r');
try {
assert.throws(() => fh.pullSync({ autoClose: 'no' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pullSync({ start: 'a' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pullSync({ limit: 'a' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pullSync({ chunkSize: 'a' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => fh.pullSync({ start: 1.1 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => fh.pullSync({ limit: 1.1 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => fh.pullSync({ chunkSize: 1.1 }), { code: 'ERR_OUT_OF_RANGE' });
} finally {
await fh.close();
}
}
// =============================================================================
// Run all tests
// =============================================================================
Promise.all([
testBasicPullSync(),
testLargeFile(),
testBinaryData(),
testPullSyncWithCompression(),
testPullSyncWithStatelessTransform(),
testPullSyncMixedTransforms(),
testAutoClose(),
testAutoCloseEarlyBreak(),
testNoAutoClose(),
testLocked(),
testEmptyFile(),
testPipeToSync(),
testPullSyncStart(),
testPullSyncLimit(),
testPullSyncStartAndLimit(),
testPullSyncLimitMultiChunk(),
testPullSyncStartLimitWithTransforms(),
testPullSyncStartAutoClose(),
testPullSyncChunkSize(),
testWriterChunkSize(),
testPullArgumentValidation(),
]).then(common.mustCall());
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,138 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { broadcast, text } = require('stream/iter');
// =============================================================================
// Backpressure policies
// =============================================================================
async function testDropOldest() {
const { writer, broadcast: bc } = broadcast({
highWaterMark: 2,
backpressure: 'drop-oldest',
});
const consumer = bc.push();
writer.writeSync('first');
writer.writeSync('second');
// This should drop 'first'
writer.writeSync('third');
writer.endSync();
const data = await text(consumer);
assert.strictEqual(data, 'secondthird');
}
async function testDropNewest() {
const { writer, broadcast: bc } = broadcast({
highWaterMark: 1,
backpressure: 'drop-newest',
});
const consumer = bc.push();
writer.writeSync('kept');
// This should be silently dropped
writer.writeSync('dropped');
writer.endSync();
const data = await text(consumer);
assert.strictEqual(data, 'kept');
}
// =============================================================================
// Block backpressure
// =============================================================================
async function testBlockBackpressure() {
const { writer, broadcast: bc } = broadcast({
highWaterMark: 1,
backpressure: 'block',
});
const consumer = bc.push();
writer.writeSync('a');
// Next write should block
let writeResolved = false;
const writePromise = writer.write('b').then(() => { writeResolved = true; });
await new Promise(setImmediate);
assert.strictEqual(writeResolved, false);
// Drain consumer to unblock the pending write
const iter = consumer[Symbol.asyncIterator]();
const first = await iter.next();
assert.strictEqual(first.done, false);
await new Promise(setImmediate);
assert.strictEqual(writeResolved, true);
writer.endSync();
// Drain remaining data and verify completion
const second = await iter.next();
assert.strictEqual(second.done, false);
await writePromise;
}
// Verify block backpressure data flows correctly end-to-end
async function testBlockBackpressureContent() {
const { writer, broadcast: bc } = broadcast({
highWaterMark: 1,
backpressure: 'block',
});
const consumer = bc.push();
writer.writeSync('a');
const writePromise = writer.write('b');
await new Promise(setImmediate);
// Read all and verify content
const iter = consumer[Symbol.asyncIterator]();
const first = await iter.next();
assert.strictEqual(first.done, false);
const firstStr = new TextDecoder().decode(first.value[0]);
assert.strictEqual(firstStr, 'a');
await writePromise;
writer.endSync();
const second = await iter.next();
assert.strictEqual(second.done, false);
const secondStr = new TextDecoder().decode(second.value[0]);
assert.strictEqual(secondStr, 'b');
const done = await iter.next();
assert.strictEqual(done.done, true);
}
// Writev async path
async function testWritevAsync() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 10 });
const consumer = bc.push();
await writer.writev(['hello', ' ', 'world']);
await writer.end();
const data = await text(consumer);
assert.strictEqual(data, 'hello world');
}
// endSync returns the total byte count
async function testEndSyncReturnValue() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 10 });
bc.push(); // Need a consumer to write to
writer.writeSync('hello'); // 5 bytes
writer.writeSync(' world'); // 6 bytes
const total = writer.endSync();
assert.strictEqual(total, 11);
}
Promise.all([
testDropOldest(),
testDropNewest(),
testBlockBackpressure(),
testBlockBackpressureContent(),
testWritevAsync(),
testEndSyncReturnValue(),
]).then(common.mustCall());
@@ -0,0 +1,260 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { broadcast, text } = require('stream/iter');
// =============================================================================
// Basic broadcast
// =============================================================================
async function testBasicBroadcast() {
const { writer, broadcast: bc } = broadcast();
// Create two consumers
const consumer1 = bc.push();
const consumer2 = bc.push();
assert.strictEqual(bc.consumerCount, 2);
await writer.write('hello');
await writer.end();
const [data1, data2] = await Promise.all([
text(consumer1),
text(consumer2),
]);
assert.strictEqual(data1, 'hello');
assert.strictEqual(data2, 'hello');
}
async function testMultipleWrites() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 10 });
const consumer = bc.push();
await writer.write('a');
await writer.write('b');
await writer.write('c');
await writer.end();
const data = await text(consumer);
assert.strictEqual(data, 'abc');
}
async function testConsumerCount() {
const { broadcast: bc } = broadcast();
assert.strictEqual(bc.consumerCount, 0);
const c1 = bc.push();
assert.strictEqual(bc.consumerCount, 1);
bc.push();
assert.strictEqual(bc.consumerCount, 2);
bc.cancel();
// After cancel, consumer count drops to 0
assert.strictEqual(bc.consumerCount, 0);
// Consumers are detached and yield nothing
const batches = [];
for await (const batch of c1) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
// =============================================================================
// Writer methods
// =============================================================================
async function testWriteSync() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 2 });
const consumer = bc.push();
assert.strictEqual(writer.writeSync('a'), true);
assert.strictEqual(writer.writeSync('b'), true);
// Buffer full (highWaterMark=2, strict policy)
assert.strictEqual(writer.writeSync('c'), false);
writer.endSync();
const data = await text(consumer);
assert.strictEqual(data, 'ab');
}
async function testWritevSync() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 10 });
const consumer = bc.push();
assert.strictEqual(writer.writevSync(['hello', ' ', 'world']), true);
writer.endSync();
const data = await text(consumer);
assert.strictEqual(data, 'hello world');
}
async function testWriterEnd() {
const { writer, broadcast: bc } = broadcast();
const consumer = bc.push();
await writer.write('data');
const totalBytes = await writer.end();
assert.strictEqual(totalBytes, 4); // 'data' = 4 UTF-8 bytes
const data = await text(consumer);
assert.strictEqual(data, 'data');
}
async function testWriterFail() {
const { writer, broadcast: bc } = broadcast();
const consumer = bc.push();
writer.fail(new Error('test error'));
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of consumer) {
assert.fail('Should not reach here');
}
},
{ message: 'test error' },
);
}
// =============================================================================
// Cancel
// =============================================================================
async function testCancelWithoutReason() {
const { broadcast: bc } = broadcast();
const consumer = bc.push();
bc.cancel();
const batches = [];
for await (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testCancelWithReason() {
const { broadcast: bc } = broadcast();
// Start a consumer that is waiting for data (promise pending)
const consumer = bc.push();
const resultPromise = text(consumer).catch((err) => err);
// Give the consumer time to enter the waiting state
await new Promise((resolve) => setImmediate(resolve));
bc.cancel(new Error('cancelled'));
const result = await resultPromise;
assert.ok(result instanceof Error);
assert.strictEqual(result.message, 'cancelled');
}
// =============================================================================
// Writer fail detaches consumers
// =============================================================================
async function testFailDetachesConsumers() {
const { writer, broadcast: bc } = broadcast();
const consumer1 = bc.push();
const consumer2 = bc.push();
assert.strictEqual(bc.consumerCount, 2);
// Write some data, then fail the writer
await writer.write('data');
await writer.fail(new Error('writer failed'));
// After fail, consumers are detached
assert.strictEqual(bc.consumerCount, 0);
// Both consumers should see the error
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of consumer1) {
assert.fail('Should not reach here');
}
},
{ message: 'writer failed' },
);
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of consumer2) {
assert.fail('Should not reach here');
}
},
{ message: 'writer failed' },
);
}
// =============================================================================
// Writer fail idempotent
// =============================================================================
async function testWriterFailIdempotent() {
const { writer, broadcast: bc } = broadcast();
const consumer = bc.push();
writer.writeSync('hello');
writer.fail(new Error('fail!'));
// Second call is a no-op (already errored)
writer.fail(new Error('fail2'));
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of consumer) { /* consume */ }
}, { message: 'fail!' });
}
// cancel() with falsy reason (0, "", false) should still treat as error
async function testCancelWithFalsyReason() {
const { broadcast: bc } = broadcast();
const consumer = bc.push();
const resultPromise = text(consumer).catch((err) => err);
await new Promise((resolve) => setImmediate(resolve));
bc.cancel(0);
const result = await resultPromise;
assert.strictEqual(result, 0);
}
// Late-joining consumer should read from oldest buffered entry
async function testLateJoinerSeesBufferedData() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 16 });
// Write data before any consumer joins
writer.writeSync('before-join');
writer.endSync();
// Consumer joins after data is written
const consumer = bc.push();
const result = await text(consumer);
assert.strictEqual(result, 'before-join');
}
Promise.all([
testBasicBroadcast(),
testMultipleWrites(),
testConsumerCount(),
testWriteSync(),
testWritevSync(),
testWriterEnd(),
testWriterFail(),
testCancelWithoutReason(),
testCancelWithReason(),
testCancelWithFalsyReason(),
testFailDetachesConsumers(),
testWriterFailIdempotent(),
testLateJoinerSeesBufferedData(),
]).then(common.mustCall());
@@ -0,0 +1,115 @@
// Flags: --experimental-stream-iter
'use strict';
// Coverage tests for broadcast.js: signal abort on pending write,
// sync iterable from, ringbuffer grow.
const common = require('../common');
const assert = require('assert');
const {
broadcast,
Broadcast,
text,
} = require('stream/iter');
// Signal abort on pending write (covers wireBroadcastWriteSignal + removeAt)
async function testBroadcastWriteAbort() {
const { writer, broadcast: bc } = broadcast({
highWaterMark: 1,
backpressure: 'block',
});
const consumer = bc.push();
// Fill the buffer to capacity
writer.writeSync(new Uint8Array([1]));
// Next write will block — pass a signal
const ac = new AbortController();
const writePromise = writer.write(new Uint8Array([2]),
{ signal: ac.signal });
// Abort the signal
ac.abort();
await assert.rejects(writePromise, { name: 'AbortError' });
// Clean up
writer.endSync();
// Drain the consumer
const result = [];
for await (const batch of consumer) {
result.push(...batch);
}
assert.ok(result.length >= 1);
}
// Broadcast.from with sync iterable (generator)
async function testBroadcastFromSyncIterable() {
function* source() {
yield [new Uint8Array([10, 20])];
yield [new Uint8Array([30, 40])];
}
const { broadcast: bc } = Broadcast.from(source());
const consumer = bc.push();
// Just verify it completes without error and produces data
let count = 0;
for await (const batch of consumer) {
count += batch.length;
}
assert.ok(count > 0);
}
// Broadcast.from with sync iterable — string chunks
async function testBroadcastFromSyncIterableStrings() {
function* source() {
yield 'hello';
yield ' world';
}
const { broadcast: bc } = Broadcast.from(source());
const consumer = bc.push();
const result = await text(consumer);
assert.strictEqual(result, 'hello world');
}
// Ringbuffer grow — push > 16 items without consumer draining
async function testRingbufferGrow() {
const { writer, broadcast: bc } = broadcast({ highWaterMark: 32 });
const consumer = bc.push();
// Push 20 items (exceeds default ringbuffer capacity of 16)
for (let i = 0; i < 20; i++) {
writer.writeSync(new Uint8Array([i]));
}
writer.endSync();
// Read all items back and verify order
const items = [];
for await (const batch of consumer) {
for (const chunk of batch) {
items.push(chunk[0]);
}
}
assert.strictEqual(items.length, 20);
for (let i = 0; i < 20; i++) {
assert.strictEqual(items[i], i);
}
}
// Broadcast drainableProtocol after close returns null
async function testDrainableAfterClose() {
const { drainableProtocol } = require('stream/iter');
const { writer } = broadcast();
writer.endSync();
const result = writer[drainableProtocol]();
// After close, desired should be null
assert.strictEqual(result, null);
}
Promise.all([
testBroadcastWriteAbort(),
testBroadcastFromSyncIterable(),
testBroadcastFromSyncIterableStrings(),
testRingbufferGrow(),
testDrainableAfterClose(),
]).then(common.mustCall());
@@ -0,0 +1,192 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { broadcast, Broadcast, from, text } = require('stream/iter');
// =============================================================================
// Broadcast.from
// =============================================================================
async function testBroadcastFromAsyncIterable() {
const source = from('broadcast-from');
const { broadcast: bc } = Broadcast.from(source);
const consumer = bc.push();
const data = await text(consumer);
assert.strictEqual(data, 'broadcast-from');
}
async function testBroadcastFromNonArrayChunks() {
// Source that yields single Uint8Array chunks (not arrays)
const enc = new TextEncoder();
async function* singleChunkSource() {
yield enc.encode('hello');
yield enc.encode(' world');
}
const { broadcast: bc } = Broadcast.from(singleChunkSource());
const consumer = bc.push();
const data = await text(consumer);
assert.strictEqual(data, 'hello world');
}
async function testBroadcastFromStringChunks() {
// Source that yields bare strings (not arrays)
async function* stringSource() {
yield 'foo';
yield 'bar';
}
const { broadcast: bc } = Broadcast.from(stringSource());
const consumer = bc.push();
const data = await text(consumer);
assert.strictEqual(data, 'foobar');
}
async function testBroadcastFromMultipleConsumers() {
const source = from('shared-data');
const { broadcast: bc } = Broadcast.from(source);
const c1 = bc.push();
const c2 = bc.push();
const [data1, data2] = await Promise.all([
text(c1),
text(c2),
]);
assert.strictEqual(data1, 'shared-data');
assert.strictEqual(data2, 'shared-data');
}
// =============================================================================
// AbortSignal
// =============================================================================
async function testAbortSignal() {
const ac = new AbortController();
const { broadcast: bc } = broadcast({ signal: ac.signal });
const consumer = bc.push();
ac.abort();
const batches = [];
for await (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testAlreadyAbortedSignal() {
const ac = new AbortController();
ac.abort();
const { broadcast: bc } = broadcast({ signal: ac.signal });
const consumer = bc.push();
const batches = [];
for await (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
// =============================================================================
// Broadcast.from() hang fix - cancel while write blocked on backpressure
// =============================================================================
async function testBroadcastFromCancelWhileBlocked() {
// Create a slow async source that blocks between yields
let sourceFinished = false;
async function* slowSource() {
const enc = new TextEncoder();
yield [enc.encode('chunk1')];
// Simulate a long delay - the cancel should unblock this
await new Promise((resolve) => setTimeout(resolve, 10000));
yield [enc.encode('chunk2')];
sourceFinished = true;
}
const { broadcast: bc } = Broadcast.from(slowSource());
const consumer = bc.push();
// Read the first chunk
const iter = consumer[Symbol.asyncIterator]();
const first = await iter.next();
assert.strictEqual(first.done, false);
// Cancel while the source is blocked waiting to yield the next chunk
bc.cancel();
// The iteration should complete (not hang)
const next = await iter.next();
assert.strictEqual(next.done, true);
// Source should NOT have finished (we cancelled before chunk2)
assert.strictEqual(sourceFinished, false);
}
// =============================================================================
// Source error propagation via Broadcast.from()
// =============================================================================
async function testBroadcastFromSourceError() {
async function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('broadcast source boom');
}
const { broadcast: bc } = Broadcast.from(failingSource());
const consumer = bc.push();
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of consumer) { /* consume */ }
}, { message: 'broadcast source boom' });
}
// =============================================================================
// Protocol validation
// =============================================================================
function testBroadcastProtocolReturnsNull() {
const obj = {
[Symbol.for('Stream.broadcastProtocol')]() { return null; },
};
assert.throws(
() => Broadcast.from(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
function testBroadcastProtocolReturnsString() {
const obj = {
[Symbol.for('Stream.broadcastProtocol')]() { return 'bad'; },
};
assert.throws(
() => Broadcast.from(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
function testBroadcastProtocolReturnsUndefined() {
const obj = {
[Symbol.for('Stream.broadcastProtocol')]() { },
};
assert.throws(
() => Broadcast.from(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
Promise.all([
testBroadcastFromAsyncIterable(),
testBroadcastFromNonArrayChunks(),
testBroadcastFromStringChunks(),
testBroadcastFromMultipleConsumers(),
testAbortSignal(),
testAlreadyAbortedSignal(),
testBroadcastFromCancelWhileBlocked(),
testBroadcastFromSourceError(),
testBroadcastProtocolReturnsNull(),
testBroadcastProtocolReturnsString(),
testBroadcastProtocolReturnsUndefined(),
]).then(common.mustCall());
@@ -0,0 +1,220 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
bytes,
bytesSync,
text,
textSync,
arrayBuffer,
arrayBufferSync,
array,
arraySync,
} = require('stream/iter');
// =============================================================================
// bytesSync / bytes
// =============================================================================
async function testBytesSyncBasic() {
const data = bytesSync(fromSync('hello'));
assert.deepStrictEqual(data, new TextEncoder().encode('hello'));
}
async function testBytesSyncLimit() {
assert.throws(
() => bytesSync(fromSync('hello world'), { limit: 3 }),
{ name: 'RangeError' },
);
}
async function testBytesAsync() {
const data = await bytes(from('hello-async'));
assert.deepStrictEqual(data, new TextEncoder().encode('hello-async'));
}
async function testBytesAsyncLimit() {
await assert.rejects(
() => bytes(from('hello world'), { limit: 3 }),
{ name: 'RangeError' },
);
}
async function testBytesAsyncAbort() {
const ac = new AbortController();
ac.abort();
await assert.rejects(
() => bytes(from('data'), { signal: ac.signal }),
{ name: 'AbortError' },
);
}
async function testBytesEmpty() {
const data = await bytes(from([]));
assert.ok(data instanceof Uint8Array);
assert.strictEqual(data.byteLength, 0);
}
// =============================================================================
// arrayBufferSync / arrayBuffer
// =============================================================================
async function testArrayBufferSyncBasic() {
const ab = arrayBufferSync(fromSync(new Uint8Array([1, 2, 3])));
assert.ok(ab instanceof ArrayBuffer);
assert.strictEqual(ab.byteLength, 3);
const view = new Uint8Array(ab);
assert.deepStrictEqual(view, new Uint8Array([1, 2, 3]));
}
async function testArrayBufferAsync() {
const ab = await arrayBuffer(from(new Uint8Array([10, 20, 30])));
assert.ok(ab instanceof ArrayBuffer);
assert.strictEqual(ab.byteLength, 3);
const view = new Uint8Array(ab);
assert.deepStrictEqual(view, new Uint8Array([10, 20, 30]));
}
// =============================================================================
// arraySync / array
// =============================================================================
async function testArraySyncBasic() {
function* gen() {
yield new Uint8Array([1]);
yield new Uint8Array([2]);
yield new Uint8Array([3]);
}
const chunks = arraySync(fromSync(gen()));
assert.strictEqual(chunks.length, 3);
assert.deepStrictEqual(chunks[0], new Uint8Array([1]));
assert.deepStrictEqual(chunks[1], new Uint8Array([2]));
assert.deepStrictEqual(chunks[2], new Uint8Array([3]));
}
async function testArraySyncLimit() {
function* gen() {
yield new Uint8Array(100);
yield new Uint8Array(100);
}
const source = fromSync(gen());
assert.throws(
() => arraySync(source, { limit: 50 }),
{ name: 'RangeError' },
);
}
async function testArrayAsync() {
async function* gen() {
yield [new Uint8Array([1])];
yield [new Uint8Array([2])];
}
const chunks = await array(gen());
assert.strictEqual(chunks.length, 2);
assert.deepStrictEqual(chunks[0], new Uint8Array([1]));
assert.deepStrictEqual(chunks[1], new Uint8Array([2]));
}
async function testArrayAsyncLimit() {
async function* gen() {
yield [new Uint8Array(100)];
yield [new Uint8Array(100)];
}
await assert.rejects(
() => array(gen(), { limit: 50 }),
{ name: 'RangeError' },
);
}
// =============================================================================
// Non-array batch tolerance
// =============================================================================
// Regression test: consumers should tolerate sources that yield raw
// Uint8Array or string values instead of Uint8Array[] batches.
async function testConsumersNonArrayBatch() {
const encoder = new TextEncoder();
// Source yields raw Uint8Array, not wrapped in an array
async function* rawSource() {
yield encoder.encode('hello');
yield encoder.encode(' world');
}
const result = await text(rawSource());
assert.strictEqual(result, 'hello world');
// bytes() with raw chunks
async function* rawSource2() {
yield encoder.encode('ab');
}
const data = await bytes(rawSource2());
assert.strictEqual(data.length, 2);
assert.strictEqual(data[0], 97); // 'a'
assert.strictEqual(data[1], 98); // 'b'
// array() with raw chunks
async function* rawSource3() {
yield encoder.encode('x');
yield encoder.encode('y');
}
const arr = await array(rawSource3());
assert.strictEqual(arr.length, 2);
}
async function testConsumersNonArrayBatchSync() {
const encoder = new TextEncoder();
function* rawSyncSource() {
yield encoder.encode('sync');
yield encoder.encode('data');
}
const result = textSync(rawSyncSource());
assert.strictEqual(result, 'syncdata');
const data = bytesSync(rawSyncSource());
assert.strictEqual(data.length, 8);
const arr = arraySync(rawSyncSource());
assert.strictEqual(arr.length, 2);
}
// Consumers accept string sources directly (normalized via from/fromSync)
async function testBytesStringSource() {
const result = await bytes('hello-bytes');
assert.strictEqual(new TextDecoder().decode(result), 'hello-bytes');
}
function testBytesSyncStringSource() {
const result = bytesSync('hello-sync');
assert.strictEqual(new TextDecoder().decode(result), 'hello-sync');
}
async function testTextStringSource() {
const { text } = require('stream/iter');
const result = await text('direct-string');
assert.strictEqual(result, 'direct-string');
}
Promise.all([
testBytesSyncBasic(),
testBytesSyncLimit(),
testBytesAsync(),
testBytesAsyncLimit(),
testBytesAsyncAbort(),
testBytesEmpty(),
testArrayBufferSyncBasic(),
testArrayBufferAsync(),
testArraySyncBasic(),
testArraySyncLimit(),
testArrayAsync(),
testArrayAsyncLimit(),
testConsumersNonArrayBatch(),
testConsumersNonArrayBatchSync(),
testBytesStringSource(),
testBytesSyncStringSource(),
testTextStringSource(),
]).then(common.mustCall());
@@ -0,0 +1,175 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
push,
merge,
text,
} = require('stream/iter');
// =============================================================================
// merge
// =============================================================================
async function testMergeTwoSources() {
const { writer: w1, readable: r1 } = push();
const { writer: w2, readable: r2 } = push();
w1.write('from-a');
w1.end();
w2.write('from-b');
w2.end();
const merged = merge(r1, r2);
const chunks = [];
for await (const batch of merged) {
for (const chunk of batch) {
chunks.push(new TextDecoder().decode(chunk));
}
}
// Both sources should be present (order is temporal, not guaranteed)
assert.strictEqual(chunks.length, 2);
assert.ok(chunks.includes('from-a'));
assert.ok(chunks.includes('from-b'));
}
async function testMergeSingleSource() {
const data = await text(merge(from('only-one')));
assert.strictEqual(data, 'only-one');
}
async function testMergeEmpty() {
const merged = merge();
const batches = [];
for await (const batch of merged) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testMergeWithAbortSignal() {
const ac = new AbortController();
ac.abort();
const merged = merge(from('data'), { signal: ac.signal });
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of merged) {
assert.fail('Should not reach here');
}
},
{ name: 'AbortError' },
);
}
// Regression test: merge() with sync iterable sources
async function testMergeSyncSources() {
const s1 = fromSync('abc');
const s2 = fromSync('def');
const result = await text(merge(s1, s2));
// Both sources should be fully consumed; order may vary
assert.strictEqual(result.length, 6);
for (const ch of 'abcdef') {
assert.ok(result.includes(ch), `missing '${ch}' in '${result}'`);
}
}
// =============================================================================
// Merge error propagation
// =============================================================================
async function testMergeSourceError() {
async function* goodSource() {
const enc = new TextEncoder();
yield [enc.encode('a')];
// Slow so the bad source errors first
await new Promise((r) => setTimeout(r, 50));
yield [enc.encode('b')];
}
async function* badSource() {
yield [new TextEncoder().encode('x')];
throw new Error('merge source boom');
}
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of merge(goodSource(), badSource())) { /* consume */ }
}, { message: 'merge source boom' });
}
async function testMergeConsumerBreak() {
let source1Return = false;
let source2Return = false;
async function* source1() {
try {
while (true) yield [new TextEncoder().encode('a')];
} finally {
source1Return = true;
}
}
async function* source2() {
try {
while (true) yield [new TextEncoder().encode('b')];
} finally {
source2Return = true;
}
}
// eslint-disable-next-line no-unused-vars
for await (const _ of merge(source1(), source2())) {
break; // Break after first batch
}
// Give async cleanup a tick to complete
await new Promise(setImmediate);
// Both sources should be cleaned up
assert.strictEqual(source1Return && source2Return, true);
}
async function testMergeSignalMidIteration() {
const ac = new AbortController();
async function* slowSource() {
const enc = new TextEncoder();
yield [enc.encode('a')];
await new Promise((r) => setTimeout(r, 100));
yield [enc.encode('b')];
}
const merged = merge(slowSource(), { signal: ac.signal });
const iter = merged[Symbol.asyncIterator]();
await iter.next(); // First batch
ac.abort();
await assert.rejects(() => iter.next(), { name: 'AbortError' });
}
// merge() accepts string sources (normalized via from())
async function testMergeStringSources() {
const batches = [];
for await (const batch of merge('hello', 'world')) {
batches.push(batch);
}
// Each string becomes a single-batch source
assert.strictEqual(batches.length >= 2, true);
const combined = new TextDecoder().decode(
Buffer.concat(batches.flat()));
// Both strings should appear (order may vary)
assert.ok(combined.includes('hello'));
assert.ok(combined.includes('world'));
}
Promise.all([
testMergeTwoSources(),
testMergeSingleSource(),
testMergeEmpty(),
testMergeWithAbortSignal(),
testMergeSyncSources(),
testMergeSourceError(),
testMergeConsumerBreak(),
testMergeSignalMidIteration(),
testMergeStringSources(),
]).then(common.mustCall());
@@ -0,0 +1,130 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
pull,
pullSync,
push,
tap,
tapSync,
text,
textSync,
} = require('stream/iter');
// =============================================================================
// tap / tapSync
// =============================================================================
async function testTapSync() {
const observed = [];
const observer = tapSync((chunks) => {
if (chunks !== null) {
observed.push(chunks.length);
}
});
// tapSync returns a function transform
assert.strictEqual(typeof observer, 'function');
// Test that it passes data through unchanged
const input = [new Uint8Array([1]), new Uint8Array([2])];
const result = observer(input);
assert.deepStrictEqual(result, input);
assert.deepStrictEqual(observed, [2]);
// null (flush) passes through
const flushResult = observer(null);
assert.strictEqual(flushResult, null);
}
async function testTapAsync() {
const observed = [];
const observer = tap(async (chunks) => {
if (chunks !== null) {
observed.push(chunks.length);
}
});
assert.strictEqual(typeof observer, 'function');
const input = [new Uint8Array([1])];
const result = await observer(input);
assert.deepStrictEqual(result, input);
assert.deepStrictEqual(observed, [1]);
}
async function testTapInPipeline() {
const { writer, readable } = push();
const seen = [];
const observer = tap(async (chunks) => {
if (chunks !== null) {
for (const chunk of chunks) {
seen.push(new TextDecoder().decode(chunk));
}
}
});
writer.write('hello');
writer.end();
// Use pull with tap as a transform
const result = pull(readable, observer);
const data = await text(result);
assert.strictEqual(data, 'hello');
assert.strictEqual(seen.length, 1);
assert.strictEqual(seen[0], 'hello');
}
// Tap callback error propagates through async pipeline
async function testTapAsyncErrorPropagation() {
const badTap = tap(() => { throw new Error('tap error'); });
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(from('hello'), badTap)) { /* consume */ }
}, { message: 'tap error' });
}
// TapSync callback error propagates through sync pipeline
function testTapSyncErrorPropagation() {
const badTap = tapSync(() => { throw new Error('tapSync error'); });
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of pullSync(fromSync('hello'), badTap)) { /* consume */ }
}, { message: 'tapSync error' });
}
// TapSync in a pullSync pipeline passes through data and flush
function testTapSyncInPipeline() {
const seen = [];
let sawFlush = false;
const observer = tapSync((chunks) => {
if (chunks === null) {
sawFlush = true;
} else {
for (const chunk of chunks) {
seen.push(new TextDecoder().decode(chunk));
}
}
});
const data = textSync(pullSync(fromSync('hello'), observer));
assert.strictEqual(data, 'hello');
assert.strictEqual(seen.length, 1);
assert.strictEqual(seen[0], 'hello');
assert.strictEqual(sawFlush, true);
}
Promise.all([
testTapSync(),
testTapAsync(),
testTapInPipeline(),
testTapAsyncErrorPropagation(),
testTapSyncErrorPropagation(),
testTapSyncInPipeline(),
]).then(common.mustCall());
@@ -0,0 +1,164 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
text,
textSync,
} = require('stream/iter');
// =============================================================================
// textSync / text
// =============================================================================
async function testTextSyncBasic() {
const data = textSync(fromSync('hello text'));
assert.strictEqual(data, 'hello text');
}
async function testTextAsync() {
const data = await text(from('hello async text'));
assert.strictEqual(data, 'hello async text');
}
async function testTextEncoding() {
// Default encoding is utf-8
const data = await text(from('café'));
assert.strictEqual(data, 'café');
}
// =============================================================================
// Text encoding tests
// =============================================================================
async function testTextNonUtf8Encoding() {
// Latin-1 encoding
const latin1Bytes = new Uint8Array([0xE9, 0xE8, 0xEA]); // é, è, ê in latin1
const result = await text(from(latin1Bytes), { encoding: 'iso-8859-1' });
assert.strictEqual(result, 'éèê');
}
async function testTextSyncNonUtf8Encoding() {
const latin1Bytes = new Uint8Array([0xE9, 0xE8, 0xEA]);
const result = textSync(fromSync(latin1Bytes), { encoding: 'iso-8859-1' });
assert.strictEqual(result, 'éèê');
}
async function testTextInvalidUtf8() {
// Invalid UTF-8 sequence with fatal: true should throw
const invalid = new Uint8Array([0xFF, 0xFE]);
await assert.rejects(
() => text(from(invalid)),
{ name: 'TypeError' }, // TextDecoder fatal throws TypeError
);
}
async function testTextWithLimit() {
// Limit caps total bytes; exceeding throws ERR_OUT_OF_RANGE
await assert.rejects(
() => text(from('hello world'), { limit: 5 }),
{ code: 'ERR_OUT_OF_RANGE' },
);
// Within limit should succeed
const result = await text(from('hello'), { limit: 10 });
assert.strictEqual(result, 'hello');
// Exact boundary: 'hello' is 5 UTF-8 bytes, limit: 5 should succeed
// (source uses > not >=)
const exact = await text(from('hello'), { limit: 5 });
assert.strictEqual(exact, 'hello');
}
async function testTextSyncWithLimit() {
// Sync version of limit testing
assert.throws(
() => textSync(fromSync('hello world'), { limit: 5 }),
{ code: 'ERR_OUT_OF_RANGE' },
);
const result = textSync(fromSync('hello'), { limit: 10 });
assert.strictEqual(result, 'hello');
// Exact boundary
const exact = textSync(fromSync('hello'), { limit: 5 });
assert.strictEqual(exact, 'hello');
}
async function testTextEmpty() {
const result = await text(from(''));
assert.strictEqual(result, '');
const syncResult = textSync(fromSync(''));
assert.strictEqual(syncResult, '');
}
// text() with abort signal
async function testTextWithSignal() {
const ac = new AbortController();
ac.abort();
await assert.rejects(
() => text(from('data'), { signal: ac.signal }),
{ name: 'AbortError' },
);
}
// Multi-chunk source with a multi-byte UTF-8 character split across chunks
async function testTextMultiChunkSplitCodepoint() {
// '€' is U+20AC, encoded as 3 UTF-8 bytes: 0xE2, 0x82, 0xAC
// Split these bytes across two chunks to test proper re-assembly
async function* splitSource() {
yield [new Uint8Array([0xE2, 0x82])]; // First 2 bytes of '€'
yield [new Uint8Array([0xAC])]; // Last byte of '€'
}
const result = await text(splitSource());
assert.strictEqual(result, '€');
}
// BOM should be stripped (ignoreBOM defaults to false per spec)
async function testTextBOMStripped() {
// UTF-8 BOM: 0xEF, 0xBB, 0xBF followed by 'hi'
const withBOM = new Uint8Array([0xEF, 0xBB, 0xBF, 0x68, 0x69]);
const result = await text(from(withBOM));
assert.strictEqual(result, 'hi');
}
async function testTextSyncBOMStripped() {
const withBOM = new Uint8Array([0xEF, 0xBB, 0xBF, 0x68, 0x69]);
const result = textSync(fromSync(withBOM));
assert.strictEqual(result, 'hi');
}
// Unsupported encoding throws RangeError
async function testTextUnsupportedEncodingThrowsRangeError() {
await assert.rejects(
() => text(from('hello'), { encoding: 'not-a-real-encoding' }),
{ name: 'RangeError' },
);
}
function testTextSyncUnsupportedEncodingThrowsRangeError() {
assert.throws(
() => textSync(fromSync('hello'), { encoding: 'not-a-real-encoding' }),
{ name: 'RangeError' },
);
}
Promise.all([
testTextSyncBasic(),
testTextAsync(),
testTextEncoding(),
testTextNonUtf8Encoding(),
testTextSyncNonUtf8Encoding(),
testTextInvalidUtf8(),
testTextWithLimit(),
testTextSyncWithLimit(),
testTextEmpty(),
testTextWithSignal(),
testTextMultiChunkSplitCodepoint(),
testTextBOMStripped(),
testTextSyncBOMStripped(),
testTextUnsupportedEncodingThrowsRangeError(),
testTextSyncUnsupportedEncodingThrowsRangeError(),
]).then(common.mustCall());
@@ -0,0 +1,132 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const vm = require('vm');
const { from, fromSync, pull, text, bytesSync } = require('stream/iter');
// Cross-realm objects are created in a different VM context.
// They have different prototypes, so `instanceof` checks fail.
// These tests verify that stream/iter correctly handles cross-realm types.
// Helper: compare Uint8Array content regardless of realm.
function assertBytes(actual, expected) {
assert.strictEqual(actual.length, expected.length,
`length mismatch: ${actual.length} !== ${expected.length}`);
for (let i = 0; i < expected.length; i++) {
assert.strictEqual(actual[i], expected[i], `byte mismatch at index ${i}`);
}
}
// =============================================================================
// from() / fromSync() with cross-realm Uint8Array
// =============================================================================
async function testFromSyncCrossRealmUint8Array() {
const crossRealm = vm.runInNewContext('new Uint8Array([1, 2, 3])');
const data = bytesSync(fromSync(crossRealm));
assertBytes(data, new Uint8Array([1, 2, 3]));
}
async function testFromCrossRealmUint8Array() {
const crossRealm = vm.runInNewContext('new Uint8Array([4, 5, 6])');
const result = await text(from(crossRealm));
assert.strictEqual(result, '\x04\x05\x06');
}
// =============================================================================
// from() / fromSync() with cross-realm ArrayBuffer
// =============================================================================
async function testFromSyncCrossRealmArrayBuffer() {
const crossRealm = vm.runInNewContext(
'new Uint8Array([7, 8, 9]).buffer',
);
const data = bytesSync(fromSync(crossRealm));
assertBytes(data, new Uint8Array([7, 8, 9]));
}
async function testFromCrossRealmArrayBuffer() {
const crossRealm = vm.runInNewContext(
'new Uint8Array([10, 11, 12]).buffer',
);
const result = await text(from(crossRealm));
assert.strictEqual(result, '\x0a\x0b\x0c');
}
// =============================================================================
// from() / fromSync() with cross-realm Uint8Array[]
// =============================================================================
async function testFromSyncCrossRealmUint8ArrayArray() {
const crossRealm = vm.runInNewContext(
'[new Uint8Array([1, 2]), new Uint8Array([3, 4])]',
);
const data = bytesSync(fromSync(crossRealm));
assertBytes(data, new Uint8Array([1, 2, 3, 4]));
}
async function testFromCrossRealmUint8ArrayArray() {
const crossRealm = vm.runInNewContext(
'[new Uint8Array([5, 6]), new Uint8Array([7, 8])]',
);
const result = await text(from(crossRealm));
assert.strictEqual(result, '\x05\x06\x07\x08');
}
// =============================================================================
// pull() with cross-realm Uint8Array from transforms
// =============================================================================
async function testPullCrossRealmTransformOutput() {
// Transform that returns cross-realm Uint8Array[] batches
const crossRealmTransform = (chunks) => {
if (chunks === null) return null;
// Re-encode each chunk as cross-realm Uint8Array
return vm.runInNewContext(
`[new Uint8Array([${[...chunks[0]]}])]`,
);
};
const output = await text(pull(from('hello'), crossRealmTransform));
assert.strictEqual(output, 'hello');
}
// =============================================================================
// from() with cross-realm Promise
// =============================================================================
async function testFromCrossRealmPromise() {
const crossRealmPromise = vm.runInNewContext(
'Promise.resolve("promised-data")',
);
async function* gen() {
yield crossRealmPromise;
}
const result = await text(from(gen()));
assert.strictEqual(result, 'promised-data');
}
// =============================================================================
// from() with cross-realm typed arrays (non-Uint8Array views)
// =============================================================================
async function testFromSyncCrossRealmInt32Array() {
const crossRealm = vm.runInNewContext('new Int32Array([1])');
const data = bytesSync(fromSync(crossRealm));
// Int32Array([1]) = 4 bytes, endianness varies by platform
assert.strictEqual(data.length, 4);
assert.strictEqual(new Int32Array(data.buffer, data.byteOffset, 1)[0], 1);
}
Promise.all([
testFromSyncCrossRealmUint8Array(),
testFromCrossRealmUint8Array(),
testFromSyncCrossRealmArrayBuffer(),
testFromCrossRealmArrayBuffer(),
testFromSyncCrossRealmUint8ArrayArray(),
testFromCrossRealmUint8ArrayArray(),
testPullCrossRealmTransformOutput(),
testFromCrossRealmPromise(),
testFromSyncCrossRealmInt32Array(),
]).then(common.mustCall());
@@ -0,0 +1,34 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const { spawnPromisified } = common;
async function testRequireNodeStreamIterWithoutFlag() {
const { stderr, code } = await spawnPromisified(process.execPath, [
'-e', 'require("node:stream/iter")',
]);
assert.match(stderr, /No such built-in module: node:stream\/iter/);
assert.notStrictEqual(code, 0);
}
async function testRequireStreamIterWithoutFlag() {
const { stderr, code } = await spawnPromisified(process.execPath, [
'-e', 'require("stream/iter")',
]);
assert.match(stderr, /Cannot find module/);
assert.notStrictEqual(code, 0);
}
async function testRequireWithFlag() {
const { code } = await spawnPromisified(process.execPath, [
'--experimental-stream-iter',
'-e', 'require("node:stream/iter")',
]);
assert.strictEqual(code, 0);
}
Promise.all([
testRequireNodeStreamIterWithoutFlag(),
testRequireStreamIterWithoutFlag(),
testRequireWithFlag(),
]).then(common.mustCall());
+188
View File
@@ -0,0 +1,188 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { duplex, text, bytes } = require('stream/iter');
// =============================================================================
// Basic duplex
// =============================================================================
async function testBasicDuplex() {
const [channelA, channelB] = duplex();
// A writes, B reads
await channelA.writer.write('hello from A');
await channelA.close();
const dataAtB = await text(channelB.readable);
assert.strictEqual(dataAtB, 'hello from A');
}
async function testBidirectional() {
const [channelA, channelB] = duplex();
// A writes to B, B writes to A concurrently
const writeA = (async () => {
await channelA.writer.write('A to B');
await channelA.close();
})();
const writeB = (async () => {
await channelB.writer.write('B to A');
await channelB.close();
})();
const readAtB = text(channelB.readable);
const readAtA = text(channelA.readable);
await Promise.all([writeA, writeB]);
const [dataAtA, dataAtB] = await Promise.all([readAtA, readAtB]);
assert.strictEqual(dataAtB, 'A to B');
assert.strictEqual(dataAtA, 'B to A');
}
async function testMultipleWrites() {
const [channelA, channelB] = duplex({ highWaterMark: 10 });
await channelA.writer.write('one');
await channelA.writer.write('two');
await channelA.writer.write('three');
await channelA.close();
const data = await text(channelB.readable);
assert.strictEqual(data, 'onetwothree');
}
async function testChannelClose() {
const [channelA, channelB] = duplex();
await channelA.close();
// Should be able to close twice without error
await channelA.close();
// B's readable should end (A -> B direction is closed)
const batches = [];
for await (const batch of channelB.readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testWithOptions() {
const [channelA, channelB] = duplex({
highWaterMark: 2,
backpressure: 'strict',
});
await channelA.writer.write('msg');
await channelA.close();
const data = await text(channelB.readable);
assert.strictEqual(data, 'msg');
}
async function testPerChannelOptions() {
const [channelA, channelB] = duplex({
a: { highWaterMark: 1 },
b: { highWaterMark: 4 },
});
// Channel A -> B direction uses A's options
// Channel B -> A direction uses B's options
await channelA.writer.write('from-a');
await channelA.close();
await channelB.writer.write('from-b');
await channelB.close();
const [dataAtA, dataAtB] = await Promise.all([
text(channelA.readable),
text(channelB.readable),
]);
assert.strictEqual(dataAtB, 'from-a');
assert.strictEqual(dataAtA, 'from-b');
}
async function testAbortSignal() {
const ac = new AbortController();
const [channelA] = duplex({ signal: ac.signal });
ac.abort();
// Both directions should error
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of channelA.readable) {
assert.fail('Should not reach here');
}
},
(err) => err.name === 'AbortError',
);
}
async function testEmptyDuplex() {
const [channelA, channelB] = duplex();
// Close without writing
await channelA.close();
await channelB.close();
const dataAtA = await bytes(channelA.readable);
const dataAtB = await bytes(channelB.readable);
assert.strictEqual(dataAtA.byteLength, 0);
assert.strictEqual(dataAtB.byteLength, 0);
}
// Channel fail propagation
async function testChannelFail() {
const [a, b] = duplex();
a.writer.fail(new Error('channel failed'));
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of b.readable) { /* consume */ }
}, { message: 'channel failed' });
await b.close();
}
// Abort signal affects both channels
async function testAbortSignalBothChannels() {
const ac = new AbortController();
const [channelA, channelB] = duplex({ signal: ac.signal });
ac.abort();
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of channelA.readable) {
assert.fail('Should not reach here');
}
}, (err) => err.name === 'AbortError');
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of channelB.readable) {
assert.fail('Should not reach here');
}
}, (err) => err.name === 'AbortError');
}
Promise.all([
testBasicDuplex(),
testBidirectional(),
testMultipleWrites(),
testChannelClose(),
testWithOptions(),
testPerChannelOptions(),
testAbortSignal(),
testEmptyDuplex(),
testChannelFail(),
testAbortSignalBothChannels(),
]).then(common.mustCall());
@@ -0,0 +1,251 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { from, text, Stream } = require('stream/iter');
async function testFromString() {
const readable = from('hello-async');
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0],
new TextEncoder().encode('hello-async'));
}
async function testFromAsyncGenerator() {
async function* gen() {
yield new Uint8Array([10, 20]);
yield new Uint8Array([30, 40]);
}
const readable = from(gen());
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 2);
assert.deepStrictEqual(batches[0][0], new Uint8Array([10, 20]));
assert.deepStrictEqual(batches[1][0], new Uint8Array([30, 40]));
}
async function testFromSyncIterableAsAsync() {
// Sync iterable passed to from() should work
function* gen() {
yield new Uint8Array([1]);
yield new Uint8Array([2]);
}
const readable = from(gen());
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
// Sync iterables get batched together into a single batch
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0].length, 2);
assert.deepStrictEqual(batches[0][0], new Uint8Array([1]));
assert.deepStrictEqual(batches[0][1], new Uint8Array([2]));
}
async function testFromToAsyncStreamableProtocol() {
const sym = Symbol.for('Stream.toAsyncStreamable');
const obj = {
[sym]() {
return 'async-protocol-data';
},
};
async function* gen() {
yield obj;
}
const readable = from(gen());
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0],
new TextEncoder().encode('async-protocol-data'));
}
function testFromRejectsNonStreamable() {
assert.throws(
() => from(12345),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
assert.throws(
() => from(null),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
async function testFromEmptyArray() {
const readable = from([]);
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
// Also accessible via Stream namespace
async function testStreamNamespace() {
const readable = Stream.from('via-namespace');
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new TextEncoder().encode('via-namespace'));
}
async function testCustomToStringInStreamRejects() {
// Objects with custom toString but no toStreamable protocol are rejected.
// Use toStreamable protocol instead.
const obj = { toString() { return 'from toString'; } };
async function* source() {
yield obj;
}
await assert.rejects(
() => text(from(source())),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
async function testCustomToPrimitiveInStreamRejects() {
// Objects with Symbol.toPrimitive but no toStreamable protocol are rejected.
const obj = {
[Symbol.toPrimitive](hint) {
if (hint === 'string') return 'from toPrimitive';
return 42;
},
};
async function* source() {
yield obj;
}
await assert.rejects(
() => text(from(source())),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
async function testToStreamableProtocolInStream() {
// Objects should use toStreamable protocol instead of toString
const obj = {
[Symbol.for('Stream.toStreamable')]() { return 'from protocol'; },
};
async function* source() {
yield obj;
}
const result = await text(from(source()));
assert.strictEqual(result, 'from protocol');
}
// Both toAsyncStreamable and toStreamable: async takes precedence
async function testFromAsyncStreamablePrecedence() {
const obj = {
[Symbol.for('Stream.toStreamable')]() { return 'sync version'; },
[Symbol.for('Stream.toAsyncStreamable')]() { return 'async version'; },
};
async function* gen() { yield obj; }
const result = await text(from(gen()));
assert.strictEqual(result, 'async version');
}
// Top-level toAsyncStreamable protocol on input to from()
async function testFromTopLevelToAsyncStreamable() {
const obj = {
[Symbol.for('Stream.toAsyncStreamable')]() {
return 'top-level-async';
},
};
const result = await text(from(obj));
assert.strictEqual(result, 'top-level-async');
}
// Top-level toAsyncStreamable returning a Promise
async function testFromTopLevelToAsyncStreamablePromise() {
const obj = {
[Symbol.for('Stream.toAsyncStreamable')]() {
return Promise.resolve('async-promise');
},
};
const result = await text(from(obj));
assert.strictEqual(result, 'async-promise');
}
// Top-level toStreamable protocol on input to from()
async function testFromTopLevelToStreamable() {
const obj = {
[Symbol.for('Stream.toStreamable')]() {
return 'top-level-sync';
},
};
const result = await text(from(obj));
assert.strictEqual(result, 'top-level-sync');
}
// Top-level: toAsyncStreamable takes precedence over toStreamable
async function testFromTopLevelAsyncPrecedence() {
const obj = {
[Symbol.for('Stream.toStreamable')]() { return 'sync'; },
[Symbol.for('Stream.toAsyncStreamable')]() { return 'async'; },
};
const result = await text(from(obj));
assert.strictEqual(result, 'async');
}
// Top-level: toAsyncStreamable takes precedence over Symbol.asyncIterator
async function testFromTopLevelProtocolOverIterator() {
const obj = {
[Symbol.for('Stream.toAsyncStreamable')]() { return 'from-protocol'; },
async *[Symbol.asyncIterator]() { yield [new TextEncoder().encode('from-iterator')]; },
};
const result = await text(from(obj));
assert.strictEqual(result, 'from-protocol');
}
// DataView input should be converted to Uint8Array (zero-copy)
async function testFromDataView() {
const buf = new ArrayBuffer(5);
const view = new DataView(buf);
// Write "hello" into the DataView
view.setUint8(0, 0x68); // h
view.setUint8(1, 0x65); // e
view.setUint8(2, 0x6c); // l
view.setUint8(3, 0x6c); // l
view.setUint8(4, 0x6f); // o
const result = await text(from(view));
assert.strictEqual(result, 'hello');
}
function testFromNullThrows() {
assert.throws(() => from(null), { code: 'ERR_INVALID_ARG_TYPE' });
}
function testFromUndefinedThrows() {
assert.throws(() => from(undefined), { code: 'ERR_INVALID_ARG_TYPE' });
}
Promise.all([
testFromString(),
testFromAsyncGenerator(),
testFromSyncIterableAsAsync(),
testFromToAsyncStreamableProtocol(),
testFromRejectsNonStreamable(),
testFromEmptyArray(),
testStreamNamespace(),
testCustomToStringInStreamRejects(),
testCustomToPrimitiveInStreamRejects(),
testToStreamableProtocolInStream(),
testFromAsyncStreamablePrecedence(),
testFromNullThrows(),
testFromUndefinedThrows(),
testFromTopLevelToAsyncStreamable(),
testFromTopLevelToAsyncStreamablePromise(),
testFromTopLevelToStreamable(),
testFromTopLevelAsyncPrecedence(),
testFromTopLevelProtocolOverIterator(),
testFromDataView(),
]).then(common.mustCall());
@@ -0,0 +1,144 @@
// Flags: --experimental-stream-iter
'use strict';
// Coverage tests for from.js: sub-batching >128, DataView in generator,
// non-Uint8Array TypedArray normalization.
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
bytes,
bytesSync,
} = require('stream/iter');
// fromSync: Uint8Array[] with > 128 elements triggers sub-batching
async function testFromSyncSubBatching() {
const bigBatch = Array.from({ length: 200 },
(_, i) => new Uint8Array([i & 0xFF]));
const batches = [];
for (const batch of fromSync(bigBatch)) {
batches.push(batch);
}
// Should be split into sub-batches: 128 + 72
assert.strictEqual(batches.length, 2);
assert.strictEqual(batches[0].length, 128);
assert.strictEqual(batches[1].length, 72);
// Verify no data loss
let totalChunks = 0;
for (const batch of batches) totalChunks += batch.length;
assert.strictEqual(totalChunks, 200);
}
// from: Uint8Array[] with > 128 elements triggers sub-batching (async)
async function testFromAsyncSubBatching() {
const bigBatch = Array.from({ length: 200 },
(_, i) => new Uint8Array([i & 0xFF]));
const batches = [];
for await (const batch of from(bigBatch)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 2);
assert.strictEqual(batches[0].length, 128);
assert.strictEqual(batches[1].length, 72);
}
// Exact boundary: 128 elements → single batch (no split)
async function testFromSubBatchingBoundary() {
const exactBatch = Array.from({ length: 128 },
(_, i) => new Uint8Array([i]));
const batches = [];
for (const batch of fromSync(exactBatch)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0].length, 128);
}
// 129 elements → 2 batches (128 + 1)
async function testFromSubBatchingBoundaryPlus1() {
const batch129 = Array.from({ length: 129 },
(_, i) => new Uint8Array([i & 0xFF]));
const batches = [];
for await (const batch of from(batch129)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 2);
assert.strictEqual(batches[0].length, 128);
assert.strictEqual(batches[1].length, 1);
}
// DataView yielded from a sync generator → normalizeSyncValue path
async function testFromSyncDataViewInGenerator() {
function* gen() {
const buf = new ArrayBuffer(3);
const dv = new DataView(buf);
dv.setUint8(0, 65);
dv.setUint8(1, 66);
dv.setUint8(2, 67);
yield dv;
}
const data = bytesSync(fromSync(gen()));
assert.deepStrictEqual(data, new Uint8Array([65, 66, 67]));
}
// DataView yielded from an async generator → normalizeAsyncValue path
async function testFromAsyncDataViewInGenerator() {
async function* gen() {
const buf = new ArrayBuffer(3);
const dv = new DataView(buf);
dv.setUint8(0, 68);
dv.setUint8(1, 69);
dv.setUint8(2, 70);
yield dv;
}
const data = await bytes(from(gen()));
assert.deepStrictEqual(data, new Uint8Array([68, 69, 70]));
}
// Int16Array yielded from generator → primitiveToUint8Array fallback
async function testFromSyncInt16ArrayInGenerator() {
function* gen() {
yield new Int16Array([0x0102, 0x0304]);
}
const data = bytesSync(fromSync(gen()));
assert.strictEqual(data.byteLength, 4); // 2 int16 = 4 bytes
}
// Float64Array as top-level input to from()
async function testFromFloat64Array() {
const f64 = new Float64Array([1.0]);
const batches = [];
for await (const batch of from(f64)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0][0].byteLength, 8); // 1 float64 = 8 bytes
}
// Sync generator yielding invalid type → ERR_INVALID_ARG_TYPE
async function testFromSyncInvalidYield() {
function* gen() {
yield 42; // Not a valid stream value
}
assert.throws(
() => {
// eslint-disable-next-line no-unused-vars
for (const batch of fromSync(gen())) { /* consume */ }
},
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
Promise.all([
testFromSyncSubBatching(),
testFromAsyncSubBatching(),
testFromSubBatchingBoundary(),
testFromSubBatchingBoundaryPlus1(),
testFromSyncDataViewInGenerator(),
testFromAsyncDataViewInGenerator(),
testFromSyncInt16ArrayInGenerator(),
testFromFloat64Array(),
testFromSyncInvalidYield(),
]).then(common.mustCall());
+236
View File
@@ -0,0 +1,236 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { fromSync } = require('stream/iter');
function testFromSyncString() {
// String input should be UTF-8 encoded
const readable = fromSync('hello');
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0].length, 1);
assert.deepStrictEqual(batches[0][0],
new TextEncoder().encode('hello'));
}
function testFromSyncUint8Array() {
const input = new Uint8Array([1, 2, 3]);
const readable = fromSync(input);
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0].length, 1);
assert.deepStrictEqual(batches[0][0], input);
}
function testFromSyncArrayBuffer() {
const ab = new ArrayBuffer(4);
new Uint8Array(ab).set([10, 20, 30, 40]);
const readable = fromSync(ab);
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([10, 20, 30, 40]));
}
function testFromSyncUint8ArrayArray() {
// Array of Uint8Array should yield as a single batch
const chunks = [new Uint8Array([1]), new Uint8Array([2])];
const readable = fromSync(chunks);
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0].length, 2);
assert.deepStrictEqual(batches[0][0], new Uint8Array([1]));
assert.deepStrictEqual(batches[0][1], new Uint8Array([2]));
}
function testFromSyncGenerator() {
function* gen() {
yield new Uint8Array([1, 2]);
yield new Uint8Array([3, 4]);
}
const readable = fromSync(gen());
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 2);
assert.deepStrictEqual(batches[0][0], new Uint8Array([1, 2]));
assert.deepStrictEqual(batches[1][0], new Uint8Array([3, 4]));
}
function testFromSyncNestedIterables() {
// Nested arrays and strings should be flattened
function* gen() {
yield ['hello', ' ', 'world'];
}
const readable = fromSync(gen());
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.strictEqual(batches[0].length, 3);
assert.deepStrictEqual(batches[0][0], new TextEncoder().encode('hello'));
assert.deepStrictEqual(batches[0][1], new TextEncoder().encode(' '));
assert.deepStrictEqual(batches[0][2], new TextEncoder().encode('world'));
}
function testFromSyncToStreamableProtocol() {
const sym = Symbol.for('Stream.toStreamable');
const obj = {
[sym]() {
return 'protocol-data';
},
};
function* gen() {
yield obj;
}
const readable = fromSync(gen());
const batches = [];
for (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0],
new TextEncoder().encode('protocol-data'));
}
function testFromSyncGeneratorError() {
function* gen() {
yield new Uint8Array([1]);
throw new Error('generator boom');
}
const readable = fromSync(gen());
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of readable) { /* consume */ }
}, { message: 'generator boom' });
}
function testFromSyncRejectsNonStreamable() {
assert.throws(
() => fromSync(12345),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
assert.throws(
() => fromSync(null),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
function testFromSyncEmptyGenerator() {
function* empty() {}
let count = 0;
// eslint-disable-next-line no-unused-vars
for (const _ of fromSync(empty())) { count++; }
assert.strictEqual(count, 0);
}
// Top-level toStreamable protocol on input to fromSync()
function testFromSyncTopLevelToStreamable() {
const obj = {
[Symbol.for('Stream.toStreamable')]() {
return 'top-level-sync';
},
};
const batches = [];
for (const batch of fromSync(obj)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0],
new TextEncoder().encode('top-level-sync'));
}
// Top-level: toStreamable takes precedence over Symbol.iterator
function testFromSyncTopLevelProtocolOverIterator() {
const obj = {
[Symbol.for('Stream.toStreamable')]() { return 'from-protocol'; },
*[Symbol.iterator]() { yield [new TextEncoder().encode('from-iterator')]; },
};
const batches = [];
for (const batch of fromSync(obj)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0],
new TextEncoder().encode('from-protocol'));
}
// Top-level: toAsyncStreamable is ignored by fromSync
function testFromSyncIgnoresAsyncStreamable() {
const obj = {
[Symbol.for('Stream.toAsyncStreamable')]() { return 'async'; },
};
// Has no toStreamable and no Symbol.iterator, should throw
assert.throws(() => fromSync(obj), { code: 'ERR_INVALID_ARG_TYPE' });
}
// Explicit async iterable rejected
function testFromSyncRejectsAsyncIterable() {
async function* gen() { yield [new TextEncoder().encode('a')]; }
assert.throws(() => fromSync(gen()), { code: 'ERR_INVALID_ARG_TYPE' });
}
// Promise rejected
function testFromSyncRejectsPromise() {
assert.throws(() => fromSync(Promise.resolve('hello')),
{ code: 'ERR_INVALID_ARG_TYPE' });
}
// DataView input should be converted to Uint8Array (zero-copy)
function testFromSyncDataView() {
const buf = new ArrayBuffer(3);
const view = new DataView(buf);
view.setUint8(0, 0x48); // H
view.setUint8(1, 0x49); // I
view.setUint8(2, 0x21); // !
const batches = [];
for (const batch of fromSync(view)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([0x48, 0x49, 0x21]));
}
function testFromSyncNullThrows() {
assert.throws(() => fromSync(null), { code: 'ERR_INVALID_ARG_TYPE' });
}
function testFromSyncUndefinedThrows() {
assert.throws(() => fromSync(undefined), { code: 'ERR_INVALID_ARG_TYPE' });
}
Promise.all([
testFromSyncString(),
testFromSyncUint8Array(),
testFromSyncArrayBuffer(),
testFromSyncUint8ArrayArray(),
testFromSyncGenerator(),
testFromSyncNestedIterables(),
testFromSyncToStreamableProtocol(),
testFromSyncGeneratorError(),
testFromSyncRejectsNonStreamable(),
testFromSyncEmptyGenerator(),
testFromSyncNullThrows(),
testFromSyncUndefinedThrows(),
testFromSyncTopLevelToStreamable(),
testFromSyncTopLevelProtocolOverIterator(),
testFromSyncIgnoresAsyncStreamable(),
testFromSyncRejectsAsyncIterable(),
testFromSyncRejectsPromise(),
testFromSyncDataView(),
]).then(common.mustCall());
+210
View File
@@ -0,0 +1,210 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const streamNew = require('stream/iter');
// =============================================================================
// Stream namespace object
// =============================================================================
async function testStreamNamespaceExists() {
assert.ok(streamNew.Stream);
assert.strictEqual(typeof streamNew.Stream, 'object');
}
async function testStreamNamespaceFrozen() {
assert.ok(Object.isFrozen(streamNew.Stream));
}
async function testStreamNamespaceFactories() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.push, 'function');
assert.strictEqual(typeof Stream.duplex, 'function');
assert.strictEqual(typeof Stream.from, 'function');
assert.strictEqual(typeof Stream.fromSync, 'function');
}
async function testStreamNamespacePipelines() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.pull, 'function');
assert.strictEqual(typeof Stream.pullSync, 'function');
assert.strictEqual(typeof Stream.pipeTo, 'function');
assert.strictEqual(typeof Stream.pipeToSync, 'function');
}
async function testStreamNamespaceAsyncConsumers() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.bytes, 'function');
assert.strictEqual(typeof Stream.text, 'function');
assert.strictEqual(typeof Stream.arrayBuffer, 'function');
assert.strictEqual(typeof Stream.array, 'function');
}
async function testStreamNamespaceSyncConsumers() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.bytesSync, 'function');
assert.strictEqual(typeof Stream.textSync, 'function');
assert.strictEqual(typeof Stream.arrayBufferSync, 'function');
assert.strictEqual(typeof Stream.arraySync, 'function');
}
async function testStreamNamespaceCombining() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.merge, 'function');
assert.strictEqual(typeof Stream.broadcast, 'function');
assert.strictEqual(typeof Stream.share, 'function');
assert.strictEqual(typeof Stream.shareSync, 'function');
}
async function testStreamNamespaceUtilities() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.tap, 'function');
assert.strictEqual(typeof Stream.tapSync, 'function');
assert.strictEqual(typeof Stream.ondrain, 'function');
}
async function testStreamNamespaceProtocols() {
const { Stream } = streamNew;
assert.strictEqual(typeof Stream.toStreamable, 'symbol');
assert.strictEqual(typeof Stream.toAsyncStreamable, 'symbol');
assert.strictEqual(typeof Stream.broadcastProtocol, 'symbol');
assert.strictEqual(typeof Stream.shareProtocol, 'symbol');
assert.strictEqual(typeof Stream.shareSyncProtocol, 'symbol');
assert.strictEqual(typeof Stream.drainableProtocol, 'symbol');
}
// =============================================================================
// Individual exports (destructured imports)
// =============================================================================
async function testIndividualExports() {
// Factories
assert.strictEqual(typeof streamNew.push, 'function');
assert.strictEqual(typeof streamNew.duplex, 'function');
assert.strictEqual(typeof streamNew.from, 'function');
assert.strictEqual(typeof streamNew.fromSync, 'function');
// Pipelines
assert.strictEqual(typeof streamNew.pull, 'function');
assert.strictEqual(typeof streamNew.pullSync, 'function');
assert.strictEqual(typeof streamNew.pipeTo, 'function');
assert.strictEqual(typeof streamNew.pipeToSync, 'function');
// Consumers
assert.strictEqual(typeof streamNew.bytes, 'function');
assert.strictEqual(typeof streamNew.bytesSync, 'function');
assert.strictEqual(typeof streamNew.text, 'function');
assert.strictEqual(typeof streamNew.textSync, 'function');
assert.strictEqual(typeof streamNew.arrayBuffer, 'function');
assert.strictEqual(typeof streamNew.arrayBufferSync, 'function');
assert.strictEqual(typeof streamNew.array, 'function');
assert.strictEqual(typeof streamNew.arraySync, 'function');
// Combining
assert.strictEqual(typeof streamNew.merge, 'function');
assert.strictEqual(typeof streamNew.broadcast, 'function');
assert.strictEqual(typeof streamNew.share, 'function');
assert.strictEqual(typeof streamNew.shareSync, 'function');
// Utilities
assert.strictEqual(typeof streamNew.tap, 'function');
assert.strictEqual(typeof streamNew.tapSync, 'function');
assert.strictEqual(typeof streamNew.ondrain, 'function');
// Protocol symbols
assert.strictEqual(typeof streamNew.toStreamable, 'symbol');
assert.strictEqual(typeof streamNew.toAsyncStreamable, 'symbol');
assert.strictEqual(typeof streamNew.broadcastProtocol, 'symbol');
assert.strictEqual(typeof streamNew.shareProtocol, 'symbol');
assert.strictEqual(typeof streamNew.shareSyncProtocol, 'symbol');
assert.strictEqual(typeof streamNew.drainableProtocol, 'symbol');
}
async function testMultiConsumerExports() {
// Broadcast and Share constructors/factories
assert.ok(streamNew.Broadcast);
assert.strictEqual(typeof streamNew.Broadcast.from, 'function');
assert.ok(streamNew.Share);
assert.strictEqual(typeof streamNew.Share.from, 'function');
assert.ok(streamNew.SyncShare);
assert.strictEqual(typeof streamNew.SyncShare.fromSync, 'function');
}
// =============================================================================
// Cross-check: namespace matches individual exports
// =============================================================================
async function testNamespaceMatchesExports() {
const { Stream } = streamNew;
// Every function on Stream should also be available as a direct export
assert.strictEqual(Stream.push, streamNew.push);
assert.strictEqual(Stream.duplex, streamNew.duplex);
assert.strictEqual(Stream.from, streamNew.from);
assert.strictEqual(Stream.fromSync, streamNew.fromSync);
assert.strictEqual(Stream.pull, streamNew.pull);
assert.strictEqual(Stream.pullSync, streamNew.pullSync);
assert.strictEqual(Stream.pipeTo, streamNew.pipeTo);
assert.strictEqual(Stream.pipeToSync, streamNew.pipeToSync);
assert.strictEqual(Stream.bytes, streamNew.bytes);
assert.strictEqual(Stream.text, streamNew.text);
assert.strictEqual(Stream.arrayBuffer, streamNew.arrayBuffer);
assert.strictEqual(Stream.array, streamNew.array);
assert.strictEqual(Stream.bytesSync, streamNew.bytesSync);
assert.strictEqual(Stream.textSync, streamNew.textSync);
assert.strictEqual(Stream.arrayBufferSync, streamNew.arrayBufferSync);
assert.strictEqual(Stream.arraySync, streamNew.arraySync);
assert.strictEqual(Stream.merge, streamNew.merge);
assert.strictEqual(Stream.broadcast, streamNew.broadcast);
assert.strictEqual(Stream.share, streamNew.share);
assert.strictEqual(Stream.shareSync, streamNew.shareSync);
assert.strictEqual(Stream.tap, streamNew.tap);
assert.strictEqual(Stream.tapSync, streamNew.tapSync);
assert.strictEqual(Stream.ondrain, streamNew.ondrain);
// Protocol symbols
assert.strictEqual(Stream.toStreamable, streamNew.toStreamable);
assert.strictEqual(Stream.toAsyncStreamable, streamNew.toAsyncStreamable);
assert.strictEqual(Stream.broadcastProtocol, streamNew.broadcastProtocol);
assert.strictEqual(Stream.shareProtocol, streamNew.shareProtocol);
assert.strictEqual(Stream.shareSyncProtocol, streamNew.shareSyncProtocol);
assert.strictEqual(Stream.drainableProtocol, streamNew.drainableProtocol);
}
// =============================================================================
// Require paths
// =============================================================================
async function testRequirePaths() {
// Both require('stream/iter') and require('node:stream/iter') should work
const fromPlain = require('stream/iter');
const fromNode = require('node:stream/iter');
assert.strictEqual(fromPlain.Stream, fromNode.Stream);
assert.strictEqual(fromPlain.push, fromNode.push);
}
Promise.all([
testStreamNamespaceExists(),
testStreamNamespaceFrozen(),
testStreamNamespaceFactories(),
testStreamNamespacePipelines(),
testStreamNamespaceAsyncConsumers(),
testStreamNamespaceSyncConsumers(),
testStreamNamespaceCombining(),
testStreamNamespaceUtilities(),
testStreamNamespaceProtocols(),
testIndividualExports(),
testMultiConsumerExports(),
testNamespaceMatchesExports(),
testRequirePaths(),
]).then(common.mustCall());
@@ -0,0 +1,68 @@
// Flags: --experimental-stream-iter
'use strict';
// Edge case tests for pipeToSync: endSync fallback, preventFail.
const common = require('../common');
const assert = require('assert');
const { pipeToSync, fromSync } = require('stream/iter');
// pipeToSync endSync returns negative → falls back to end()
async function testPipeToSyncEndSyncFallback() {
let endCalled = false;
const writer = {
writeSync() { return true; },
endSync() { return -1; }, // Negative → triggers end() fallback
end() { endCalled = true; },
};
pipeToSync(fromSync('data'), writer);
assert.strictEqual(endCalled, true);
}
// pipeToSync endSync missing → falls back to end()
async function testPipeToSyncNoEndSync() {
let endCalled = false;
const writer = {
writeSync() { return true; },
end() { endCalled = true; },
};
pipeToSync(fromSync('data'), writer);
assert.strictEqual(endCalled, true);
}
// pipeToSync with preventFail: true — source error does NOT call fail()
async function testPipeToSyncPreventFail() {
let failCalled = false;
const writer = {
writeSync() { return true; },
endSync() { return 0; },
fail() { failCalled = true; },
};
function* badSource() {
yield [new Uint8Array([1])];
throw new Error('source error');
}
assert.throws(
() => pipeToSync(badSource(), writer, { preventFail: true }),
{ message: 'source error' },
);
assert.strictEqual(failCalled, false);
}
// pipeToSync with preventClose: true — end/endSync not called
async function testPipeToSyncPreventClose() {
let endCalled = false;
const writer = {
writeSync() { return true; },
endSync() { endCalled = true; return 0; },
};
pipeToSync(fromSync('data'), writer, { preventClose: true });
assert.strictEqual(endCalled, false);
}
Promise.all([
testPipeToSyncEndSyncFallback(),
testPipeToSyncNoEndSync(),
testPipeToSyncPreventFail(),
testPipeToSyncPreventClose(),
]).then(common.mustCall());
@@ -0,0 +1,90 @@
// Flags: --experimental-stream-iter
'use strict';
// Tests for pipeTo with live (non-pre-aborted) AbortSignal,
// both with and without transforms.
const common = require('../common');
const assert = require('assert');
const { pipeTo, from } = require('stream/iter');
// pipeTo with live signal, no transforms — abort mid-stream
async function testPipeToLiveSignalNoTransforms() {
const ac = new AbortController();
const written = [];
const writer = {
async write(chunk) { written.push(chunk); },
async end() {},
};
async function* source() {
yield [new Uint8Array([1])];
yield [new Uint8Array([2])];
ac.abort();
yield [new Uint8Array([3])];
}
await assert.rejects(
() => pipeTo(source(), writer, { signal: ac.signal }),
{ name: 'AbortError' },
);
// Should have written at least the first two chunks before abort
assert.ok(written.length >= 1);
}
// pipeTo with live signal + transforms — abort mid-stream
async function testPipeToLiveSignalWithTransforms() {
const ac = new AbortController();
const written = [];
const writer = {
async write(chunk) { written.push(chunk); },
async end() {},
};
const identity = (chunks) => chunks;
async function* source() {
yield [new Uint8Array([10])];
yield [new Uint8Array([20])];
ac.abort();
yield [new Uint8Array([30])];
}
await assert.rejects(
() => pipeTo(source(), identity, writer, { signal: ac.signal }),
{ name: 'AbortError' },
);
assert.ok(written.length >= 1);
}
// pipeTo with live signal, no abort — runs to completion
async function testPipeToLiveSignalCompletes() {
const ac = new AbortController();
const written = [];
const writer = {
write(chunk) { written.push(chunk); },
writeSync(chunk) { written.push(chunk); return true; },
async end() {},
endSync() { return written.length; },
};
await pipeTo(from('signal-ok'), writer, { signal: ac.signal });
assert.ok(written.length > 0);
}
// pipeTo with live signal + transforms, no abort — runs to completion
async function testPipeToLiveSignalWithTransformsCompletes() {
const ac = new AbortController();
const written = [];
const writer = {
write(chunk) { written.push(chunk); },
writeSync(chunk) { written.push(chunk); return true; },
async end() {},
endSync() { return written.length; },
};
const identity = (chunks) => chunks;
await pipeTo(from('signal-tx-ok'), identity, writer,
{ signal: ac.signal });
assert.ok(written.length > 0);
}
Promise.all([
testPipeToLiveSignalNoTransforms(),
testPipeToLiveSignalWithTransforms(),
testPipeToLiveSignalCompletes(),
testPipeToLiveSignalWithTransformsCompletes(),
]).then(common.mustCall());
@@ -0,0 +1,147 @@
// Flags: --experimental-stream-iter
'use strict';
// Tests for pipeTo writev/writevSync paths and writeBatchAsyncFallback.
const common = require('../common');
const assert = require('assert');
const { pipeTo, pipeToSync } = require('stream/iter');
// Multi-chunk batch with writevSync (sync success path)
async function testWritevSyncSuccess() {
const batches = [];
const writer = {
write(chunk) {},
writevSync(chunks) { batches.push(chunks); return true; },
writev(chunks) { batches.push(chunks); },
writeSync(chunk) { return true; },
endSync() { return 0; },
};
// Source that yields multi-chunk batches
async function* source() {
yield [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
yield [new Uint8Array([4]), new Uint8Array([5])];
}
const total = await pipeTo(source(), writer);
assert.ok(batches.length > 0);
// writevSync was used for multi-chunk batches
assert.ok(batches.some((b) => b.length > 1));
assert.strictEqual(total, 5);
}
// Multi-chunk batch with writev async (no writevSync)
async function testWritevAsyncFallback() {
const batches = [];
const writer = {
async writev(chunks) { batches.push(chunks); },
async write(chunk) { batches.push([chunk]); },
async end() {},
};
async function* source() {
yield [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
}
await pipeTo(source(), writer);
assert.ok(batches.length > 0);
assert.ok(batches.some((b) => b.length > 1));
}
// writevSync returns false — falls through to async writev
async function testWritevSyncFails() {
const asyncCalls = [];
const writer = {
write() {},
writevSync() { return false; },
async writev(chunks) { asyncCalls.push(chunks); },
writeSync() { return true; },
endSync() { return 0; },
};
async function* source() {
yield [new Uint8Array([1]), new Uint8Array([2])];
}
await pipeTo(source(), writer);
assert.strictEqual(asyncCalls.length, 1);
assert.strictEqual(asyncCalls[0].length, 2);
}
// writeSync fails mid-batch — triggers writeBatchAsyncFallback
async function testWriteSyncFailsMidBatch() {
const asyncWrites = [];
const writer = {
writeSync(chunk) {
// Fail for chunk value 2 — always, including retries
if (chunk[0] === 2) return false;
return true;
},
async write(chunk) { asyncWrites.push(chunk); },
async end() {},
};
// Single batch with 3 chunks
async function* source() {
yield [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
}
const total = await pipeTo(source(), writer);
// Chunk 1: writeSync succeeds
// Chunk 2: writeSync fails → writeBatchAsyncFallback → write() called
// Chunk 3: writeBatchAsyncFallback retries writeSync → succeeds
assert.ok(asyncWrites.length >= 1);
assert.deepStrictEqual(asyncWrites[0], new Uint8Array([2]));
assert.strictEqual(total, 3);
}
// writeSync always fails — all chunks go through async
async function testWriteSyncAlwaysFails() {
const asyncWrites = [];
const writer = {
writeSync() { return false; },
async write(chunk) { asyncWrites.push(chunk); },
async end() {},
};
async function* source() {
yield [new Uint8Array([10]), new Uint8Array([20])];
}
const total = await pipeTo(source(), writer);
assert.strictEqual(asyncWrites.length, 2);
assert.strictEqual(total, 2);
}
// pipeToSync with writevSync
async function testPipeToSyncWritev() {
const batches = [];
const writer = {
writevSync(chunks) { batches.push(chunks); },
writeSync(chunk) { return true; },
endSync() { return 0; },
};
function* source() {
yield [new Uint8Array([1]), new Uint8Array([2]), new Uint8Array([3])];
yield [new Uint8Array([4])];
}
pipeToSync(source(), writer);
// Multi-chunk batch should have used writevSync
assert.ok(batches.some((b) => b.length > 1));
}
// pipeToSync with writer that has write() and writeSync() — writeSync preferred
async function testPipeToSyncWriteFallback() {
const syncWrites = [];
const writer = {
writeSync(chunk) { syncWrites.push(chunk); return true; },
write(chunk) { /* should not be called */ },
endSync() { return 0; },
};
function* source() {
yield [new Uint8Array([1]), new Uint8Array([2])];
}
pipeToSync(source(), writer);
assert.strictEqual(syncWrites.length, 2);
}
Promise.all([
testWritevSyncSuccess(),
testWritevAsyncFallback(),
testWritevSyncFails(),
testWriteSyncFailsMidBatch(),
testWriteSyncAlwaysFails(),
testPipeToSyncWritev(),
testPipeToSyncWriteFallback(),
]).then(common.mustCall());
+237
View File
@@ -0,0 +1,237 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { pipeTo, pipeToSync, from, fromSync } = require('stream/iter');
async function testPipeToSync() {
const written = [];
const writer = {
writeSync(chunk) { written.push(chunk); return true; },
endSync() { return written.length; },
fail() {},
};
const totalBytes = pipeToSync(fromSync('pipe-data'), writer);
assert.strictEqual(totalBytes, 9); // 'pipe-data' = 9 UTF-8 bytes
assert.ok(written.length > 0);
const result = new TextDecoder().decode(
new Uint8Array(written.reduce((acc, c) => [...acc, ...c], [])));
assert.strictEqual(result, 'pipe-data');
}
async function testPipeTo() {
const written = [];
const writer = {
async write(chunk) { written.push(chunk); },
async end() { return written.length; },
async fail() {},
};
const totalBytes = await pipeTo(from('async-pipe-data'), writer);
assert.strictEqual(totalBytes, 15); // 'async-pipe-data' = 15 UTF-8 bytes
assert.ok(written.length > 0);
}
async function testPipeToPreventClose() {
let endCalled = false;
const writer = {
async write() {},
async end() { endCalled = true; },
async fail() {},
};
await pipeTo(from('data'), writer, { preventClose: true });
assert.strictEqual(endCalled, false);
}
// PipeTo source error calls writer.fail()
async function testPipeToSourceError() {
let failCalled = false;
let failReason;
const writer = {
write() {},
fail(reason) { failCalled = true; failReason = reason; },
};
async function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('pipe source boom');
}
await assert.rejects(
() => pipeTo(failingSource(), writer),
{ message: 'pipe source boom' },
);
assert.strictEqual(failCalled, true);
assert.strictEqual(failReason.message, 'pipe source boom');
}
// PipeToSync source error calls writer.fail()
async function testPipeToSyncSourceError() {
let failCalled = false;
const writer = {
writeSync() { return true; },
fail(reason) { failCalled = true; },
};
function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('sync pipe boom');
}
assert.throws(
() => pipeToSync(failingSource(), writer),
{ message: 'sync pipe boom' },
);
assert.strictEqual(failCalled, true);
}
// PipeTo with AbortSignal
async function testPipeToWithSignal() {
const ac = new AbortController();
const chunks = [];
const writer = {
write(chunk) { chunks.push(chunk); },
};
async function* slowSource() {
yield [new TextEncoder().encode('a')];
await new Promise((r) => setTimeout(r, 50));
yield [new TextEncoder().encode('b')];
}
ac.abort();
await assert.rejects(
() => pipeTo(slowSource(), writer, { signal: ac.signal }),
{ name: 'AbortError' },
);
}
// PipeTo with transforms
async function testPipeToWithTransforms() {
const chunks = [];
const writer = {
write(chunk) { chunks.push(new TextDecoder().decode(chunk)); },
};
const upper = (batch) => {
if (batch === null) return null;
return batch.map((c) => {
const out = new Uint8Array(c);
for (let i = 0; i < out.length; i++)
out[i] -= (out[i] >= 97 && out[i] <= 122) * 32;
return out;
});
};
await pipeTo(from('hello'), upper, writer);
assert.strictEqual(chunks.join(''), 'HELLO');
}
// PipeToSync with transforms
async function testPipeToSyncWithTransforms() {
const chunks = [];
const writer = {
writeSync(chunk) { chunks.push(new TextDecoder().decode(chunk)); return true; },
};
const upper = (batch) => {
if (batch === null) return null;
return batch.map((c) => {
const out = new Uint8Array(c);
for (let i = 0; i < out.length; i++)
out[i] -= (out[i] >= 97 && out[i] <= 122) * 32;
return out;
});
};
pipeToSync(fromSync('hello'), upper, writer);
assert.strictEqual(chunks.join(''), 'HELLO');
}
// PipeTo with writev writer
async function testPipeToWithWritevWriter() {
const allChunks = [];
const writer = {
write(chunk) { allChunks.push(chunk); },
writev(chunks) { allChunks.push(...chunks); },
};
await pipeTo(from('hello world'), writer);
assert.strictEqual(allChunks.length > 0, true);
}
// PipeTo with writeSync/writevSync fallback
async function testPipeToSyncFallback() {
const chunks = [];
const writer = {
writeSync(chunk) { chunks.push(chunk); return true; },
write(chunk) { chunks.push(chunk); },
};
await pipeTo(from('hello'), writer);
assert.strictEqual(chunks.length > 0, true);
}
// PipeTo preventFail option
async function testPipeToPreventFail() {
let failCalled = false;
const writer = {
write() {},
fail() { failCalled = true; },
};
// eslint-disable-next-line require-yield
async function* failingSource() {
throw new Error('boom');
}
await assert.rejects(
() => pipeTo(failingSource(), writer, { preventFail: true }),
{ message: 'boom' },
);
assert.strictEqual(failCalled, false);
}
// PipeToSync preventClose option
async function testPipeToSyncPreventClose() {
let endCalled = false;
const writer = {
writeSync() { return true; },
endSync() { endCalled = true; return 0; },
};
pipeToSync(fromSync('hello'), writer, { preventClose: true });
assert.strictEqual(endCalled, false);
}
// Regression test: pipeTo should work with a minimal writer that only
// implements write(). end(), fail(), and all *Sync methods are optional.
async function testPipeToMinimalWriter() {
const chunks = [];
const minimalWriter = {
write(chunk) {
chunks.push(chunk);
},
};
await pipeTo(from('minimal'), minimalWriter);
assert.strictEqual(chunks.length > 0, true);
}
async function testPipeToSyncMinimalWriter() {
const chunks = [];
const minimalWriter = {
writeSync(chunk) {
chunks.push(chunk);
return true;
},
};
pipeToSync(fromSync('minimal-sync'), minimalWriter);
assert.strictEqual(chunks.length > 0, true);
}
Promise.all([
testPipeToSync(),
testPipeTo(),
testPipeToPreventClose(),
testPipeToSourceError(),
testPipeToSyncSourceError(),
testPipeToWithSignal(),
testPipeToWithTransforms(),
testPipeToSyncWithTransforms(),
testPipeToWithWritevWriter(),
testPipeToSyncFallback(),
testPipeToPreventFail(),
testPipeToSyncPreventClose(),
testPipeToMinimalWriter(),
testPipeToSyncMinimalWriter(),
]).then(common.mustCall());
@@ -0,0 +1,371 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { pull, from, text, tap } = require('stream/iter');
async function testPullIdentity() {
const data = await text(pull(from('hello-async')));
assert.strictEqual(data, 'hello-async');
}
async function testPullStatelessTransform() {
const upper = (chunks) => {
if (chunks === null) return null;
return chunks.map((c) => {
const str = new TextDecoder().decode(c);
return new TextEncoder().encode(str.toUpperCase());
});
};
const data = await text(pull(from('abc'), upper));
assert.strictEqual(data, 'ABC');
}
async function testPullStatefulTransform() {
const stateful = {
transform: async function*(source) {
for await (const chunks of source) {
if (chunks === null) {
yield new TextEncoder().encode('-ASYNC-END');
continue;
}
for (const chunk of chunks) {
yield chunk;
}
}
},
};
const data = await text(pull(from('data'), stateful));
assert.strictEqual(data, 'data-ASYNC-END');
}
async function testPullWithAbortSignal() {
const ac = new AbortController();
ac.abort();
async function* gen() {
yield [new Uint8Array([1])];
}
const result = pull(gen(), { signal: ac.signal });
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of result) {
assert.fail('Should not reach here');
}
},
{ name: 'AbortError' },
);
}
async function testPullChainedTransforms() {
const enc = new TextEncoder();
const transforms = [
(chunks) => {
if (chunks === null) return null;
return [...chunks, enc.encode('!')];
},
(chunks) => {
if (chunks === null) return null;
return [...chunks, enc.encode('?')];
},
];
const data = await text(pull(from('hello'), ...transforms));
assert.strictEqual(data, 'hello!?');
}
// Source error → controller.abort() → transform listener throws →
// source error propagates to consumer; listener error becomes uncaught
// exception (per EventTarget spec behavior).
async function testTransformSignalListenerErrorOnSourceError() {
// Listener errors from dispatchEvent are rethrown via process.nextTick,
// so we must catch them as uncaught exceptions.
const uncaughtErrors = [];
const handler = (err) => uncaughtErrors.push(err);
process.on('uncaughtException', handler);
const throwingTransform = {
transform(source, options) {
options.signal.addEventListener('abort', () => {
throw new Error('listener boom');
});
return source;
},
};
async function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('source error');
}
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(failingSource(), throwingTransform)) {
// Consume
}
},
{ message: 'source error' },
);
// Give the nextTick rethrow a chance to fire
await new Promise(setImmediate);
process.removeListener('uncaughtException', handler);
assert.strictEqual(uncaughtErrors.length, 1);
assert.strictEqual(uncaughtErrors[0].message, 'listener boom');
}
// Pull source error propagates to consumer
async function testPullSourceError() {
async function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('source boom');
}
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(failingSource())) { /* consume */ }
}, { message: 'source boom' });
}
// Tap callback error propagates through pipeline
async function testTapCallbackError() {
const badTap = tap(() => { throw new Error('tap boom'); });
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(from('hello'), badTap)) { /* consume */ }
}, { message: 'tap boom' });
}
// Pull signal aborted mid-iteration (not pre-aborted)
async function testPullSignalAbortMidIteration() {
const ac = new AbortController();
const enc = new TextEncoder();
async function* slowSource() {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
}
const result = pull(slowSource(), { signal: ac.signal });
const iter = result[Symbol.asyncIterator]();
const first = await iter.next(); // Read first batch
assert.strictEqual(first.done, false);
ac.abort();
await assert.rejects(() => iter.next(), { name: 'AbortError' });
}
// Pull consumer break (return()) cleans up transform signal
async function testPullConsumerBreakCleanup() {
let signalAborted = false;
const trackingTransform = {
transform(source, options) {
options.signal.addEventListener('abort', () => {
signalAborted = true;
});
return source;
},
};
async function* infiniteSource() {
let i = 0;
while (true) {
yield [new TextEncoder().encode(`chunk${i++}`)];
}
}
// Consumer breaks after first chunk
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(infiniteSource(), trackingTransform)) {
break;
}
// Give the abort handler a tick to fire
await new Promise(setImmediate);
assert.strictEqual(signalAborted, true);
}
// Pull transform returning a Promise
async function testPullTransformReturnsPromise() {
const asyncTransform = async (chunks) => {
if (chunks === null) return null;
return chunks;
};
const result = await text(pull(from('hello'), asyncTransform));
assert.strictEqual(result, 'hello');
}
// Stateless transform error propagates
async function testPullStatelessTransformError() {
const badTransform = (chunks) => {
if (chunks === null) return null;
throw new Error('async stateless boom');
};
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(from('hello'), badTransform)) { /* consume */ }
}, { message: 'async stateless boom' });
}
// Stateful transform error propagates
async function testPullStatefulTransformError() {
const badStateful = {
transform: async function*(source) { // eslint-disable-line require-yield
for await (const chunks of source) {
if (chunks === null) continue;
throw new Error('async stateful boom');
}
},
};
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(from('hello'), badStateful)) { /* consume */ }
}, { message: 'async stateful boom' });
}
// Stateless transform flush emitting data
async function testPullStatelessTransformFlush() {
const withTrailer = (chunks) => {
if (chunks === null) {
return [new TextEncoder().encode('-TRAILER')];
}
return chunks;
};
const data = await text(pull(from('data'), withTrailer));
assert.strictEqual(data, 'data-TRAILER');
}
// Stateless transform flush error propagates
async function testPullStatelessTransformFlushError() {
const badFlush = (chunks) => {
if (chunks === null) {
throw new Error('async flush boom');
}
return chunks;
};
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of pull(from('hello'), badFlush)) { /* consume */ }
}, { message: 'async flush boom' });
}
// Pull with a sync iterable source (not async)
async function testPullWithSyncSource() {
function* gen() {
yield new TextEncoder().encode('sync-source');
}
const data = await text(pull(gen()));
assert.strictEqual(data, 'sync-source');
}
// Pull transform yielding strings
async function testPullTransformYieldsStrings() {
const stringTransform = (chunks) => {
if (chunks === null) return null;
return chunks.map((c) => new TextDecoder().decode(c));
};
const result = await text(pull(from('hello'), stringTransform));
assert.strictEqual(result, 'hello');
}
// pull() accepts a string source directly (normalized via from())
async function testPullStringSource() {
const data = await text(pull('hello-direct'));
assert.strictEqual(data, 'hello-direct');
}
// Transform returning a single Uint8Array should be wrapped as a batch,
// not iterated byte-by-byte
async function testTransformReturnsSingleUint8Array() {
const transform = (chunks) => {
if (chunks === null) return null;
// Return a single Uint8Array, not an array
const enc = new TextEncoder();
return enc.encode('transformed');
};
const data = await text(pull(from('input'), transform));
assert.strictEqual(data, 'transformed');
}
// Transform returning a single string should be UTF-8 encoded,
// not iterated character-by-character
async function testTransformReturnsSingleString() {
const transform = (chunks) => {
if (chunks === null) return null;
return 'hello-string';
};
const data = await text(pull(from('input'), transform));
assert.strictEqual(data, 'hello-string');
}
// Transform returning an ArrayBuffer should be converted to Uint8Array
async function testTransformReturnsArrayBuffer() {
const transform = (chunks) => {
if (chunks === null) return null;
const enc = new TextEncoder();
return enc.encode('arraybuf').buffer;
};
const data = await text(pull(from('input'), transform));
assert.strictEqual(data, 'arraybuf');
}
// pipeTo() accepts a string source directly (normalized via from())
async function testPipeToStringSource() {
const { pipeTo, push: pushFn, text: textFn } = require('stream/iter');
const { writer, readable } = pushFn({ highWaterMark: 10 });
const consume = (async () => textFn(readable))();
await pipeTo('hello-pipe', writer);
const data = await consume;
assert.strictEqual(data, 'hello-pipe');
}
// INVARIANT: Each transform invocation receives its own options object.
// A transform that mutates options must not affect subsequent transforms.
async function testTransformOptionsNotShared() {
const seen = [];
const transform1 = (chunks, options) => {
// Mutate the options object
options.mutated = true;
seen.push({ id: 1, mutated: options.mutated });
return chunks;
};
const transform2 = (chunks, options) => {
// Should NOT see mutation from transform1
seen.push({ id: 2, mutated: options.mutated });
return chunks;
};
await text(pull(from('test'), transform1, transform2));
// transform1 sees its own mutation
assert.strictEqual(seen[0].mutated, true);
// transform2 gets a fresh options object - no mutation visible
assert.strictEqual(seen[1].mutated, undefined);
}
// Run the uncaughtException test sequentially (it installs a global handler
// that would interfere with concurrent tests).
(async () => {
await Promise.all([
testPullIdentity(),
testPullStatelessTransform(),
testPullStatefulTransform(),
testPullWithAbortSignal(),
testPullChainedTransforms(),
testPullSourceError(),
testTapCallbackError(),
testPullSignalAbortMidIteration(),
testPullConsumerBreakCleanup(),
testPullTransformReturnsPromise(),
testPullTransformYieldsStrings(),
testPullStatelessTransformError(),
testPullStatefulTransformError(),
testPullStatelessTransformFlush(),
testPullStatelessTransformFlushError(),
testPullWithSyncSource(),
testPullStringSource(),
testTransformReturnsSingleUint8Array(),
testTransformReturnsSingleString(),
testTransformReturnsArrayBuffer(),
testPipeToStringSource(),
testTransformOptionsNotShared(),
]);
// Run after all concurrent tests complete to avoid global handler races
await testTransformSignalListenerErrorOnSourceError();
})().then(common.mustCall());
+178
View File
@@ -0,0 +1,178 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { pullSync, fromSync, bytesSync, tapSync } = require('stream/iter');
function testPullSyncIdentity() {
// No transforms - just pass through
const data = bytesSync(pullSync(fromSync('hello')));
assert.deepStrictEqual(data, new TextEncoder().encode('hello'));
}
function testPullSyncStatelessTransform() {
const upper = (chunks) => {
if (chunks === null) return null;
return chunks.map((c) => {
const str = new TextDecoder().decode(c);
return new TextEncoder().encode(str.toUpperCase());
});
};
const data = bytesSync(pullSync(fromSync('abc'), upper));
assert.deepStrictEqual(data, new TextEncoder().encode('ABC'));
}
function testPullSyncStatefulTransform() {
const source = fromSync('data');
const stateful = {
transform: function*(source) {
for (const chunks of source) {
if (chunks === null) {
// Flush: emit trailer
yield new TextEncoder().encode('-END');
continue;
}
for (const chunk of chunks) {
yield chunk;
}
}
},
};
const result = pullSync(source, stateful);
const data = new TextDecoder().decode(bytesSync(result));
assert.strictEqual(data, 'data-END');
}
function testPullSyncChainedTransforms() {
const addExcl = (chunks) => {
if (chunks === null) return null;
return [...chunks, new TextEncoder().encode('!')];
};
const addQ = (chunks) => {
if (chunks === null) return null;
return [...chunks, new TextEncoder().encode('?')];
};
const result = pullSync(fromSync('hello'), addExcl, addQ);
const data = new TextDecoder().decode(bytesSync(result));
assert.strictEqual(data, 'hello!?');
}
// PullSync source error propagates
function testPullSyncSourceError() {
function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('sync source boom');
}
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of pullSync(failingSource())) { /* consume */ }
}, { message: 'sync source boom' });
}
// PullSync with empty source
function testPullSyncEmptySource() {
function* empty() {}
const result = bytesSync(pullSync(empty()));
assert.strictEqual(result.length, 0);
}
// TapSync callback error propagates
function testTapSyncCallbackError() {
const badTap = tapSync(() => { throw new Error('tapSync boom'); });
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of pullSync(fromSync('hello'), badTap)) { /* consume */ }
}, { message: 'tapSync boom' });
}
// Stateless transform error propagates
function testPullSyncStatelessTransformError() {
const badTransform = (chunks) => {
if (chunks === null) return null;
throw new Error('stateless transform boom');
};
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of pullSync(fromSync('hello'), badTransform)) { /* consume */ }
}, { message: 'stateless transform boom' });
}
// Stateful transform error propagates
function testPullSyncStatefulTransformError() {
const badStateful = {
transform: function*(source) { // eslint-disable-line require-yield
for (const chunks of source) {
if (chunks === null) continue;
throw new Error('stateful transform boom');
}
},
};
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of pullSync(fromSync('hello'), badStateful)) { /* consume */ }
}, { message: 'stateful transform boom' });
}
// Stateless transform flush emitting data
function testPullSyncStatelessTransformFlush() {
const withTrailer = (chunks) => {
if (chunks === null) {
// Flush: emit trailing data
return [new TextEncoder().encode('-TRAILER')];
}
return chunks;
};
const data = new TextDecoder().decode(bytesSync(pullSync(fromSync('data'), withTrailer)));
assert.strictEqual(data, 'data-TRAILER');
}
// Stateless transform flush error propagates
function testPullSyncStatelessTransformFlushError() {
const badFlush = (chunks) => {
if (chunks === null) {
throw new Error('flush boom');
}
return chunks;
};
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of pullSync(fromSync('hello'), badFlush)) { /* consume */ }
}, { message: 'flush boom' });
}
// Empty source result is a Uint8Array
function testPullSyncEmptySourceType() {
function* empty() {}
const result = bytesSync(pullSync(empty()));
assert.ok(result instanceof Uint8Array);
assert.strictEqual(result.byteLength, 0);
}
// Invalid transform argument
function testPullSyncInvalidTransform() {
assert.throws(
() => { for (const _ of pullSync(fromSync('x'), 42)) { /* consume */ } }, // eslint-disable-line no-unused-vars
{ code: 'ERR_INVALID_ARG_TYPE' },
);
assert.throws(
() => { for (const _ of pullSync(fromSync('x'), null)) { /* consume */ } }, // eslint-disable-line no-unused-vars
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
Promise.all([
testPullSyncIdentity(),
testPullSyncStatelessTransform(),
testPullSyncStatefulTransform(),
testPullSyncChainedTransforms(),
testPullSyncSourceError(),
testPullSyncEmptySource(),
testPullSyncEmptySourceType(),
testTapSyncCallbackError(),
testPullSyncStatelessTransformError(),
testPullSyncStatefulTransformError(),
testPullSyncStatelessTransformFlush(),
testPullSyncStatelessTransformFlushError(),
testPullSyncInvalidTransform(),
]).then(common.mustCall());
@@ -0,0 +1,156 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { push, text } = require('stream/iter');
async function testStrictBackpressure() {
const { writer, readable } = push({
highWaterMark: 1,
backpressure: 'strict',
});
// First write should succeed synchronously
assert.strictEqual(writer.writeSync('a'), true);
// Second write should fail synchronously (buffer full)
assert.strictEqual(writer.writeSync('b'), false);
// Consume to free space, then end
const resultPromise = text(readable);
writer.end();
const data = await resultPromise;
assert.strictEqual(data, 'a');
}
async function testDropOldest() {
const { writer, readable } = push({
highWaterMark: 2,
backpressure: 'drop-oldest',
});
assert.strictEqual(writer.writeSync('first'), true);
assert.strictEqual(writer.writeSync('second'), true);
// This should drop 'first' — return value is true (write accepted via drop)
assert.strictEqual(writer.writeSync('third'), true);
writer.end();
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
// Should have 'second' and 'third'
const allBytes = [];
for (const batch of batches) {
for (const chunk of batch) {
allBytes.push(...chunk);
}
}
const result = new TextDecoder().decode(new Uint8Array(allBytes));
assert.strictEqual(result, 'secondthird');
}
async function testDropNewest() {
const { writer, readable } = push({
highWaterMark: 1,
backpressure: 'drop-newest',
});
assert.strictEqual(writer.writeSync('kept'), true);
// This is silently dropped — return value is true (accepted but discarded)
assert.strictEqual(writer.writeSync('dropped'), true);
writer.end();
const data = await text(readable);
assert.strictEqual(data, 'kept');
}
async function testBlockBackpressure() {
const { writer, readable } = push({ highWaterMark: 1, backpressure: 'block' });
// Fill the buffer
writer.writeSync('a');
// Next write should block (not throw, not drop)
let writeState = 'pending';
const writePromise = writer.write('b').then(() => { writeState = 'resolved'; });
// The write cannot resolve until the buffer is drained, so a microtask
// tick is sufficient to confirm it is still blocked.
await new Promise(setImmediate);
assert.strictEqual(writeState, 'pending'); // Still blocked
// Read from the consumer to drain
const iter = readable[Symbol.asyncIterator]();
const first = await iter.next(); // Drains 'a'
assert.strictEqual(first.done, false);
// After draining, the pending write resolves as a microtask
await new Promise(setImmediate);
assert.strictEqual(writeState, 'resolved'); // Now unblocked
writer.endSync();
const second = await iter.next(); // Read 'b'
assert.strictEqual(second.done, false);
await writePromise;
}
async function testBlockWriteSyncEnqueues() {
// With block policy, writeSync should enqueue the data even when the buffer
// is full, returning false as a backpressure signal. The data IS accepted.
const { writer, readable } = push({ highWaterMark: 1, backpressure: 'block' });
// Fill the buffer
assert.strictEqual(writer.writeSync('a'), true);
// Buffer full: writeSync should enqueue and return false (data accepted)
assert.strictEqual(writer.writeSync('b'), false);
writer.endSync();
// Both chunks should be delivered (drain flushes all slots into one batch)
const result = await text(readable);
assert.strictEqual(result, 'ab');
}
async function testStrictPendingQueueOverflow() {
// With highWaterMark: 1 and strict, the pending writes queue is also limited to 1.
// Filling the buffer (1 sync write) + filling the pending queue (1 async write)
// should leave no room. A third write must reject with a RangeError.
const { writer, readable } = push({
highWaterMark: 1,
backpressure: 'strict',
});
// Fill the buffer
assert.strictEqual(writer.writeSync('a'), true);
// This async write goes into the pending queue (buffer full, queue has room)
const pendingWrite = writer.write('b');
// This write should reject: buffer full AND pending queue at capacity
await assert.rejects(
() => writer.write('c'),
{
code: 'ERR_INVALID_STATE',
name: 'RangeError',
},
);
// Clean up: drain the readable
const iter = readable[Symbol.asyncIterator]();
await iter.next();
await iter.next();
await pendingWrite;
writer.endSync();
await iter.return();
}
Promise.all([
testStrictBackpressure(),
testDropOldest(),
testDropNewest(),
testBlockBackpressure(),
testBlockWriteSyncEnqueues(),
testStrictPendingQueueOverflow(),
]).then(common.mustCall());
@@ -0,0 +1,182 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { push, text } = require('stream/iter');
async function testBasicWriteRead() {
const { writer, readable } = push();
writer.write('hello');
writer.end();
const data = await text(readable);
assert.strictEqual(data, 'hello');
}
async function testMultipleWrites() {
const { writer, readable } = push({ highWaterMark: 10 });
writer.write('a');
writer.write('b');
writer.write('c');
writer.end();
const data = await text(readable);
assert.strictEqual(data, 'abc');
}
async function testDesiredSize() {
const { writer } = push({ highWaterMark: 3 });
assert.strictEqual(writer.desiredSize, 3);
writer.writeSync('a');
assert.strictEqual(writer.desiredSize, 2);
writer.writeSync('b');
assert.strictEqual(writer.desiredSize, 1);
writer.writeSync('c');
assert.strictEqual(writer.desiredSize, 0);
writer.end();
assert.strictEqual(writer.desiredSize, null);
}
async function testWriterEnd() {
const { writer, readable } = push();
const totalBytes = writer.endSync();
assert.strictEqual(totalBytes, 0);
// Calling endSync again returns byte count (idempotent when closed)
assert.strictEqual(writer.endSync(), 0);
const batches = [];
for await (const batch of readable) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testWriterFail() {
const { writer, readable } = push();
writer.fail(new Error('test fail'));
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) {
assert.fail('Should not reach here');
}
},
{ message: 'test fail' },
);
}
async function testConsumerBreak() {
const { writer, readable } = push({ highWaterMark: 10 });
writer.writeSync('a');
writer.writeSync('b');
writer.writeSync('c');
// Break after first batch
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) {
break;
}
// Writer should now see null desiredSize
assert.strictEqual(writer.desiredSize, null);
}
async function testAbortSignal() {
const ac = new AbortController();
const { readable } = push({ signal: ac.signal });
ac.abort();
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) {
assert.fail('Should not reach here');
}
},
{ name: 'AbortError' },
);
}
async function testPreAbortedSignal() {
const ac = new AbortController();
ac.abort();
const { readable } = push({ signal: ac.signal });
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) {
assert.fail('Should not reach here');
}
}, { name: 'AbortError' });
}
async function testConsumerBreakWriteSyncReturnsFalse() {
const { writer, readable } = push({ highWaterMark: 10 });
writer.writeSync('a');
// Break after first batch
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) {
break;
}
// After consumer break, writeSync should return false
assert.strictEqual(writer.writeSync('b'), false);
assert.strictEqual(writer.desiredSize, null);
}
async function testPushWithTransforms() {
const upper = (chunks) => {
if (chunks === null) return null;
return chunks.map((c) => {
const str = new TextDecoder().decode(c);
return new TextEncoder().encode(str.toUpperCase());
});
};
const { writer, readable } = push(upper);
writer.write('hello');
writer.end();
const data = await text(readable);
assert.strictEqual(data, 'HELLO');
}
async function testInvalidBackpressure() {
assert.throws(() => push({ backpressure: 'banana' }), {
code: 'ERR_INVALID_ARG_VALUE',
});
assert.throws(() => push({ backpressure: '' }), {
code: 'ERR_INVALID_ARG_VALUE',
});
// Valid values should not throw
for (const bp of ['strict', 'block', 'drop-oldest', 'drop-newest']) {
push({ backpressure: bp });
}
}
Promise.all([
testBasicWriteRead(),
testMultipleWrites(),
testDesiredSize(),
testWriterEnd(),
testWriterFail(),
testConsumerBreak(),
testAbortSignal(),
testPreAbortedSignal(),
testConsumerBreakWriteSyncReturnsFalse(),
testPushWithTransforms(),
testInvalidBackpressure(),
]).then(common.mustCall());
@@ -0,0 +1,426 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const { push, ondrain, text } = require('stream/iter');
async function testOndrain() {
const { writer } = push({ highWaterMark: 1 });
// With space available, ondrain resolves immediately
const drainResult = ondrain(writer);
assert.ok(drainResult instanceof Promise);
const result = await drainResult;
assert.strictEqual(result, true);
// After close, ondrain returns null
writer.end();
assert.strictEqual(ondrain(writer), null);
}
async function testOndrainNonDrainable() {
// Non-drainable objects return null
assert.strictEqual(ondrain(null), null);
assert.strictEqual(ondrain({}), null);
assert.strictEqual(ondrain('string'), null);
}
async function testOndrainProtocolErrorPropagates() {
const badDrainable = {
[Symbol.for('Stream.drainableProtocol')]() {
throw new Error('protocol error');
},
};
assert.throws(
() => ondrain(badDrainable),
{ message: 'protocol error' },
);
}
async function testWriteWithSignalRejects() {
const { writer, readable } = push({ highWaterMark: 1 });
// Fill the buffer so write will block
writer.writeSync('a');
const ac = new AbortController();
const writePromise = writer.write('b', { signal: ac.signal });
// Signal fires while write is pending
ac.abort();
await assert.rejects(writePromise, { name: 'AbortError' });
// Clean up
writer.end();
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { break; }
}
async function testWriteWithPreAbortedSignal() {
const { writer, readable } = push({ highWaterMark: 1 });
const ac = new AbortController();
ac.abort();
// Pre-aborted signal should reject immediately
await assert.rejects(
writer.write('data', { signal: ac.signal }),
{ name: 'AbortError' },
);
// Writer should still be usable for other writes
writer.write('ok');
writer.end();
const data = await text(readable);
assert.strictEqual(data, 'ok');
}
async function testCancelledWriteRemovedFromQueue() {
const { writer, readable } = push({ highWaterMark: 1 });
// Fill the buffer
writer.writeSync('first');
const ac = new AbortController();
// This write should be queued since buffer is full
const cancelledWrite = writer.write('cancelled', { signal: ac.signal });
// Cancel it
ac.abort();
await cancelledWrite.catch(() => {});
// Drain 'first' to make room for the replacement write
const iter = readable[Symbol.asyncIterator]();
await iter.next();
// The cancelled write should NOT occupy a pending slot.
// A new write should succeed now that the buffer has room.
await writer.write('second');
writer.end();
const result = await iter.next();
// 'second' should be the next (and only remaining) chunk
const decoder = new TextDecoder();
let data = '';
for (const chunk of result.value) {
data += decoder.decode(chunk, { stream: true });
}
assert.strictEqual(data, 'second');
await iter.return();
}
async function testOndrainResolvesFalseOnConsumerBreak() {
const { writer, readable } = push({ highWaterMark: 1 });
// Fill the buffer so desiredSize = 0
writer.writeSync('a');
// Also queue a pending write so that reading one chunk
// doesn't clear backpressure (the pending write refills the slot)
const pendingWrite = writer.write('b');
// Start a drain wait - still at capacity
const drainPromise = ondrain(writer);
// Consumer returns without draining enough to clear backpressure
const iter = readable[Symbol.asyncIterator]();
await iter.return();
// Ondrain should resolve false since the consumer terminated
const result = await drainPromise;
assert.strictEqual(result, false);
await pendingWrite.catch(() => {}); // Ignore write rejection
}
async function testOndrainRejectsOnConsumerThrow() {
const { writer, readable } = push({ highWaterMark: 1 });
// Fill the buffer so desiredSize = 0
writer.writeSync('a');
// Also queue a pending write so that reading one chunk
// doesn't clear backpressure (the pending write refills the slot)
const pendingWrite = writer.write('b');
// Start a drain wait - still at capacity
const drainPromise = ondrain(writer);
// Consumer throws via iterator.throw() before draining enough
// to clear backpressure. The drain should reject.
const iter = readable[Symbol.asyncIterator]();
await iter.throw(new Error('consumer error'));
await assert.rejects(drainPromise, /consumer error/);
await pendingWrite.catch(() => {}); // Ignore write rejection
}
async function testWritev() {
const { writer, readable } = push({ highWaterMark: 10 });
const enc = new TextEncoder();
writer.writev([enc.encode('hel'), enc.encode('lo')]);
writer.endSync();
const result = await text(readable);
assert.strictEqual(result, 'hello');
}
async function testWritevSync() {
const { writer, readable } = push({ highWaterMark: 10 });
const enc = new TextEncoder();
assert.strictEqual(writer.writevSync([enc.encode('hel'), enc.encode('lo')]), true);
writer.endSync();
const result = await text(readable);
assert.strictEqual(result, 'hello');
}
async function testWritevMixedTypes() {
const { writer, readable } = push({ highWaterMark: 10 });
// Mix strings and Uint8Arrays
writer.writev(['hel', new TextEncoder().encode('lo')]);
writer.endSync();
const result = await text(readable);
assert.strictEqual(result, 'hello');
}
async function testWriteAfterEnd() {
const { writer } = push();
writer.endSync();
// Sync write after end returns false
assert.strictEqual(writer.writeSync('fail'), false);
// Async write after end rejects
await assert.rejects(
() => writer.write('fail'),
{ code: 'ERR_INVALID_STATE' },
);
}
async function testWriteAfterFail() {
const { writer } = push();
writer.fail(new Error('failed'));
// Sync write after fail returns false
assert.strictEqual(writer.writeSync('fail'), false);
// Async write after fail rejects with the stored error
await assert.rejects(
() => writer.write('fail'),
{ message: 'failed' },
);
}
async function testFail() {
const { writer, readable } = push();
writer.writeSync('hello');
writer.fail(new Error('boom'));
// Second fail is a no-op (already errored)
writer.fail(new Error('boom2'));
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { /* consume */ }
}, { message: 'boom' });
}
async function testEndAsyncReturnValue() {
const { writer, readable } = push();
writer.writeSync('hello');
// Start consuming concurrently (end() waits for drain)
const consume = (async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { /* drain */ }
})();
const total = await writer.end();
assert.strictEqual(total, 5);
await consume;
}
async function testWriteUint8Array() {
const { writer, readable } = push();
writer.write(new Uint8Array([72, 73])); // 'HI'
writer.endSync();
const result = await text(readable);
assert.strictEqual(result, 'HI');
}
async function testOndrainWaitsForDrain() {
const { writer, readable } = push({ highWaterMark: 1 });
writer.writeSync('a'); // Fills buffer
let drainState = 'pending';
const drainPromise = ondrain(writer).then((v) => { drainState = v; });
await new Promise(setImmediate);
assert.strictEqual(drainState, 'pending'); // Still waiting
// Read to drain
const iter = readable[Symbol.asyncIterator]();
await iter.next();
await drainPromise;
assert.strictEqual(drainState, true);
writer.endSync();
}
// Consumer throw causes subsequent writes to reject with consumer's error
async function testConsumerThrowRejectsWrites() {
const { writer, readable } = push({ highWaterMark: 1 });
writer.writeSync('a');
const iter = readable[Symbol.asyncIterator]();
await iter.throw(new Error('consumer boom'));
// Subsequent async writes should reject with the consumer's error
await assert.rejects(
() => writer.write('x'),
{ message: 'consumer boom' },
);
}
// end() resolves a pending read as done:true
async function testEndResolvesPendingRead() {
const { writer, readable } = push();
// Consumer starts reading — blocks because buffer is empty
const iter = readable[Symbol.asyncIterator]();
const readPromise = iter.next();
// Give the read a tick to enter the pending state
await new Promise(setImmediate);
// End the writer — should resolve the pending read with done:true
writer.endSync();
const result = await readPromise;
assert.strictEqual(result.done, true);
}
// fail() rejects a pending read with the error
async function testFailRejectsPendingRead() {
const { writer, readable } = push();
const iter = readable[Symbol.asyncIterator]();
const readPromise = iter.next();
await new Promise(setImmediate);
writer.fail(new Error('fail during read'));
await assert.rejects(
() => readPromise,
{ message: 'fail during read' },
);
}
// end() while writes are pending rejects those writes
async function testEndRejectsPendingWrites() {
const { writer, readable } = push({ highWaterMark: 1, backpressure: 'block' });
writer.writeSync('a'); // fill buffer
// This write blocks on backpressure
const writePromise = writer.write('b');
await new Promise(setImmediate);
// Ending should reject the pending write
writer.endSync();
await assert.rejects(
() => writePromise,
{ code: 'ERR_INVALID_STATE' },
);
// Clean up: drain the readable
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { break; }
}
async function testEndIdempotentWhenClosed() {
const { writer, readable } = push({ highWaterMark: 10 });
await writer.write('hello');
// Start consuming concurrently (end() waits for drain)
const consume = (async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { /* drain */ }
})();
const first = await writer.end();
assert.strictEqual(first, 5);
// Second end() should resolve with same byte count (idempotent)
const second = await writer.end();
assert.strictEqual(second, 5);
await consume;
}
async function testAsyncDispose() {
const { writer, readable } = push({ highWaterMark: 10 });
writer.writeSync('hello');
// Symbol.asyncDispose calls fail() with no argument
await writer[Symbol.asyncDispose]();
// Writer is now errored, writes should fail
assert.strictEqual(writer.writeSync('fail'), false);
// Drain readable
try {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { /* consume */ }
} catch {
// Expected - reader sees the error
}
}
async function testSyncDispose() {
const { writer, readable } = push({ highWaterMark: 10 });
writer.writeSync('hello');
// Symbol.dispose calls fail() with no argument
writer[Symbol.dispose]();
// Writer is now errored, writes should fail
assert.strictEqual(writer.writeSync('fail'), false);
// Drain readable
try {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { /* consume */ }
} catch {
// Expected
}
}
async function testEndRejectsWhenErrored() {
const { writer, readable } = push({ highWaterMark: 10 });
await writer.write('hello');
const err = new Error('boom');
await writer.fail(err);
// end() after fail should reject with the stored error
await assert.rejects(
() => writer.end(),
(e) => e === err,
);
// Drain readable
try {
// eslint-disable-next-line no-unused-vars
for await (const _ of readable) { break; }
} catch {
// Expected - reader may see the error
}
}
Promise.all([
testOndrain(),
testOndrainNonDrainable(),
testWriteWithSignalRejects(),
testWriteWithPreAbortedSignal(),
testCancelledWriteRemovedFromQueue(),
testOndrainResolvesFalseOnConsumerBreak(),
testOndrainRejectsOnConsumerThrow(),
testWritev(),
testWritevSync(),
testWritevMixedTypes(),
testWriteAfterEnd(),
testWriteAfterFail(),
testOndrainProtocolErrorPropagates(),
testFail(),
testEndAsyncReturnValue(),
testWriteUint8Array(),
testOndrainWaitsForDrain(),
testConsumerThrowRejectsWrites(),
testEndResolvesPendingRead(),
testFailRejectsPendingRead(),
testEndRejectsPendingWrites(),
testEndIdempotentWhenClosed(),
testEndRejectsWhenErrored(),
testAsyncDispose(),
testSyncDispose(),
]).then(common.mustCall());
@@ -0,0 +1,282 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
share,
text,
} = require('stream/iter');
const { setTimeout } = require('timers/promises');
// =============================================================================
// Async share()
// =============================================================================
async function testBasicShare() {
const shared = share(from('hello shared'));
const consumer = shared.pull();
const data = await text(consumer);
assert.strictEqual(data, 'hello shared');
}
async function testShareMultipleConsumers() {
async function* gen() {
yield [new TextEncoder().encode('chunk1')];
yield [new TextEncoder().encode('chunk2')];
yield [new TextEncoder().encode('chunk3')];
}
const shared = share(gen(), { highWaterMark: 16 });
const c1 = shared.pull();
const c2 = shared.pull();
assert.strictEqual(shared.consumerCount, 2);
const [data1, data2] = await Promise.all([
text(c1),
text(c2),
]);
assert.strictEqual(data1, 'chunk1chunk2chunk3');
assert.strictEqual(data2, 'chunk1chunk2chunk3');
}
async function testShareConsumerCount() {
const shared = share(from('data'));
assert.strictEqual(shared.consumerCount, 0);
const c1 = shared.pull();
assert.strictEqual(shared.consumerCount, 1);
const c2 = shared.pull();
assert.strictEqual(shared.consumerCount, 2);
// Cancel detaches all consumers
shared.cancel();
assert.strictEqual(shared.consumerCount, 0);
// Both should complete immediately
const [data1, data2] = await Promise.all([
text(c1),
text(c2),
]);
assert.strictEqual(data1, '');
assert.strictEqual(data2, '');
}
async function testShareCancel() {
const shared = share(from('data'));
const consumer = shared.pull();
shared.cancel();
assert.strictEqual(shared.consumerCount, 0);
const batches = [];
for await (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testShareCancelMidIteration() {
// Verify that cancel during iteration stops data flow
let sourceReturnCalled = false;
const enc = new TextEncoder();
async function* gen() {
try {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
} finally {
sourceReturnCalled = true;
}
}
const shared = share(gen(), { highWaterMark: 16 });
const consumer = shared.pull();
const items = [];
for await (const batch of consumer) {
for (const chunk of batch) {
items.push(new TextDecoder().decode(chunk));
}
// Cancel after first batch
shared.cancel();
}
assert.strictEqual(items.length, 1);
assert.strictEqual(items[0], 'a');
await new Promise(setImmediate);
assert.strictEqual(sourceReturnCalled, true);
}
async function testShareCancelWithReason() {
const shared = share(from('data'));
const consumer = shared.pull();
shared.cancel(new Error('share cancelled'));
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of consumer) {
assert.fail('Should not reach here');
}
},
{ message: 'share cancelled' },
);
}
async function testShareAbortSignal() {
const ac = new AbortController();
const shared = share(from('data'), { signal: ac.signal });
const consumer = shared.pull();
ac.abort();
const batches = [];
for await (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
async function testShareAlreadyAborted() {
const ac = new AbortController();
ac.abort();
const shared = share(from('data'), { signal: ac.signal });
const consumer = shared.pull();
const batches = [];
for await (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
// =============================================================================
// Source error propagation
// =============================================================================
async function testShareSourceError() {
async function* failingSource() {
yield [new TextEncoder().encode('a')];
throw new Error('share source boom');
}
const shared = share(failingSource());
const c1 = shared.pull();
const c2 = shared.pull();
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of c1) { /* consume */ }
}, { message: 'share source boom' });
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of c2) { /* consume */ }
}, { message: 'share source boom' });
}
async function testShareLateJoiningConsumer() {
// A consumer that joins after some data has been consumed should only
// see data remaining in the buffer (not items already trimmed).
const enc = new TextEncoder();
async function* gen() {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
}
const shared = share(gen(), { highWaterMark: 16 });
// First consumer reads all data
const c1 = shared.pull();
const data1 = await text(c1);
assert.strictEqual(data1, 'abc');
// Late-joining consumer: source is exhausted, buffer has been trimmed
// past all data by c1's reads, so c2 gets nothing.
const c2 = shared.pull();
const data2 = await text(c2);
assert.strictEqual(data2, '');
}
async function testShareConsumerBreak() {
// Verify that a consumer breaking mid-iteration detaches properly
const enc = new TextEncoder();
async function* gen() {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
}
const shared = share(gen(), { highWaterMark: 16 });
const c1 = shared.pull();
const c2 = shared.pull();
assert.strictEqual(shared.consumerCount, 2);
// c1 breaks after first batch
// eslint-disable-next-line no-unused-vars
for await (const _ of c1) {
break;
}
// c1 should be detached
assert.strictEqual(shared.consumerCount, 1);
// c2 should still get all data
const data2 = await text(c2);
assert.strictEqual(data2, 'abc');
}
async function testShareMultipleConsumersConcurrentPull() {
// Multiple consumers pulling concurrently should each receive all items
// even when only one item is pulled from source at a time.
async function* slowSource() {
const enc = new TextEncoder();
for (let i = 0; i < 5; i++) {
await setTimeout(1);
yield [enc.encode(`item-${i}`)];
}
}
const shared = share(slowSource());
const c1 = shared.pull();
const c2 = shared.pull();
const c3 = shared.pull();
const [t1, t2, t3] = await Promise.all([
text(c1), text(c2), text(c3),
]);
const expected = 'item-0item-1item-2item-3item-4';
assert.strictEqual(t1, expected);
assert.strictEqual(t2, expected);
assert.strictEqual(t3, expected);
}
// share() accepts string source directly (normalized via from())
async function testShareStringSource() {
const shared = share('hello-share');
const result = await text(shared.pull());
assert.strictEqual(result, 'hello-share');
}
Promise.all([
testBasicShare(),
testShareMultipleConsumers(),
testShareConsumerCount(),
testShareCancel(),
testShareCancelMidIteration(),
testShareCancelWithReason(),
testShareAbortSignal(),
testShareAlreadyAborted(),
testShareSourceError(),
testShareLateJoiningConsumer(),
testShareConsumerBreak(),
testShareMultipleConsumersConcurrentPull(),
testShareStringSource(),
]).then(common.mustCall());
@@ -0,0 +1,128 @@
// Flags: --experimental-stream-iter
'use strict';
// Coverage tests for share.js: protocol happy path, dispose, throw,
// non-Error source throws.
const common = require('../common');
const assert = require('assert');
const {
Share,
SyncShare,
share,
shareSync,
shareProtocol,
shareSyncProtocol,
from,
fromSync,
text,
textSync,
} = require('stream/iter');
// Share.from — protocol symbol happy path (returns valid share object)
async function testShareProtocolHappyPath() {
const obj = {
[shareProtocol](options) {
return share(from('protocol-data'), options);
},
};
const shared = Share.from(obj);
const result = await text(shared.pull());
assert.strictEqual(result, 'protocol-data');
}
// SyncShare.fromSync — protocol symbol happy path
async function testSyncShareProtocolHappyPath() {
const obj = {
[shareSyncProtocol](options) {
return shareSync(fromSync('sync-protocol'), options);
},
};
const shared = SyncShare.fromSync(obj);
const result = textSync(shared.pull());
assert.strictEqual(result, 'sync-protocol');
}
// Async share — Symbol.dispose cancels
async function testShareDispose() {
const shared = share(from('dispose-test'));
const consumer = shared.pull();
shared[Symbol.dispose]();
assert.strictEqual(shared.consumerCount, 0);
// Consumer should yield nothing (cancelled before read)
const result = await text(consumer);
assert.strictEqual(result, '');
}
// Sync share — Symbol.dispose cancels
async function testSyncShareDispose() {
const shared = shareSync(fromSync('sync-dispose'));
const consumer = shared.pull();
shared[Symbol.dispose]();
assert.strictEqual(shared.consumerCount, 0);
const result = textSync(consumer);
assert.strictEqual(result, '');
}
// Async consumer iterator throw()
async function testAsyncIteratorThrow() {
const shared = share(from('throw-test'));
const consumer = shared.pull();
const iter = consumer[Symbol.asyncIterator]();
const first = await iter.next();
assert.strictEqual(first.done, false);
const result = await iter.throw(new Error('test-throw'));
assert.strictEqual(result.done, true);
assert.strictEqual(shared.consumerCount, 0);
}
// Sync consumer iterator throw()
async function testSyncIteratorThrow() {
const shared = shareSync(fromSync('throw-sync'));
const consumer = shared.pull();
const iter = consumer[Symbol.iterator]();
const first = iter.next();
assert.strictEqual(first.done, false);
const result = iter.throw(new Error('test-throw'));
assert.strictEqual(result.done, true);
assert.strictEqual(shared.consumerCount, 0);
}
// Async source throws non-Error value → wrapError
async function testShareSourceThrowsNonError() {
async function* source() {
yield [new TextEncoder().encode('ok')];
throw 'not an error'; // eslint-disable-line no-throw-literal
}
const shared = share(source());
const consumer = shared.pull();
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const batch of consumer) { /* consume */ }
}, { code: 'ERR_OPERATION_FAILED' });
}
// Sync source throws non-Error value → wrapError
async function testSyncShareSourceThrowsNonError() {
function* source() {
yield [new TextEncoder().encode('ok')];
throw 42; // eslint-disable-line no-throw-literal
}
const shared = shareSync(source());
const consumer = shared.pull();
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const batch of consumer) { /* consume */ }
}, { code: 'ERR_OPERATION_FAILED' });
}
Promise.all([
testShareProtocolHappyPath(),
testSyncShareProtocolHappyPath(),
testShareDispose(),
testSyncShareDispose(),
testAsyncIteratorThrow(),
testSyncIteratorThrow(),
testShareSourceThrowsNonError(),
testSyncShareSourceThrowsNonError(),
]).then(common.mustCall());
@@ -0,0 +1,242 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
share,
Share,
SyncShare,
text,
textSync,
} = require('stream/iter');
// =============================================================================
// Share.from
// =============================================================================
async function testShareFrom() {
const shared = Share.from(from('share-from'));
const consumer = shared.pull();
const data = await text(consumer);
assert.strictEqual(data, 'share-from');
}
function testShareFromRejectsNonStreamable() {
assert.throws(
() => Share.from(12345),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
// =============================================================================
// SyncShare.fromSync
// =============================================================================
async function testSyncShareFromSync() {
const shared = SyncShare.fromSync(fromSync('sync-share-from'));
const consumer = shared.pull();
const data = textSync(consumer);
assert.strictEqual(data, 'sync-share-from');
}
function testSyncShareFromRejectsNonStreamable() {
assert.throws(
() => SyncShare.fromSync(12345),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
// =============================================================================
// Protocol validation
// =============================================================================
function testShareProtocolReturnsNull() {
const obj = {
[Symbol.for('Stream.shareProtocol')]() { return null; },
};
assert.throws(
() => Share.from(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
function testShareProtocolReturnsNonObject() {
const obj = {
[Symbol.for('Stream.shareProtocol')]() { return 42; },
};
assert.throws(
() => Share.from(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
function testSyncShareProtocolReturnsNull() {
const obj = {
[Symbol.for('Stream.shareSyncProtocol')]() { return null; },
};
assert.throws(
() => SyncShare.fromSync(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
function testSyncShareProtocolReturnsNonObject() {
const obj = {
[Symbol.for('Stream.shareSyncProtocol')]() { return 'bad'; },
};
assert.throws(
() => SyncShare.fromSync(obj),
{ code: 'ERR_INVALID_RETURN_VALUE' },
);
}
// =============================================================================
// Block backpressure: two consumers, slow consumer blocks the source
// =============================================================================
async function testShareBlockBackpressure() {
// A source that yields 5 items. With two consumers and highWaterMark: 2,
// the fast consumer drives the source forward. The slow consumer holds back
// trimming, causing the buffer to fill. 'block' mode should stall the
// source pull until the slow consumer catches up.
const enc = new TextEncoder();
async function* source() {
for (let i = 0; i < 5; i++) {
yield [enc.encode(`item${i}`)];
}
}
const shared = share(source(), { highWaterMark: 2, backpressure: 'block' });
const fast = shared.pull();
const slow = shared.pull();
// Both consumers should ultimately receive all 5 items
const [fastData, slowData] = await Promise.all([
text(fast),
text(slow),
]);
assert.strictEqual(fastData, 'item0item1item2item3item4');
assert.strictEqual(slowData, 'item0item1item2item3item4');
}
// =============================================================================
// Drop backpressure modes: use a fast + stalled consumer to trigger drops
// =============================================================================
async function testShareDropOldest() {
// Two consumers, fast reads eagerly then slow reads. With drop-oldest,
// the slow consumer's cursor is advanced past dropped items, so it
// misses old data and only sees recent items.
async function* source() {
for (let i = 0; i < 4; i++) {
yield [new TextEncoder().encode(`${i}`)];
}
}
const shared = share(source(), { highWaterMark: 2, backpressure: 'drop-oldest' });
const fast = shared.pull();
const slow = shared.pull();
// Fast consumer reads all items
const fastItems = [];
for await (const batch of fast) {
for (const chunk of batch) {
fastItems.push(new TextDecoder().decode(chunk));
}
}
assert.strictEqual(fastItems.length, 4);
// Slow consumer reads after fast is done — old items were dropped
const slowItems = [];
for await (const batch of slow) {
for (const chunk of batch) {
slowItems.push(new TextDecoder().decode(chunk));
}
}
// The slow consumer should see fewer items than were produced
assert.ok(slowItems.length < 4,
`Expected < 4 items after drop-oldest, got ${slowItems.length}`);
assert.ok(slowItems.length > 0,
'Expected at least some items after drop-oldest');
// The last item should always be present (most recent items kept)
assert.strictEqual(slowItems[slowItems.length - 1], '3');
}
async function testShareDropNewest() {
// With drop-newest and a stalled consumer, the async path allows the
// buffer to grow beyond highWaterMark (the "drop" applies to the
// backpressure signal, not the buffer contents). Both consumers
// ultimately see all items.
async function* source() {
for (let i = 0; i < 4; i++) {
yield [new TextEncoder().encode(`${i}`)];
}
}
const shared = share(source(), { highWaterMark: 2, backpressure: 'drop-newest' });
const fast = shared.pull();
const slow = shared.pull();
// Fast consumer reads all items
const fastItems = [];
for await (const batch of fast) {
for (const chunk of batch) {
fastItems.push(new TextDecoder().decode(chunk));
}
}
assert.strictEqual(fastItems.length, 4);
// Slow consumer also sees all items (buffer grew past hwm)
const slowItems = [];
for await (const batch of slow) {
for (const chunk of batch) {
slowItems.push(new TextDecoder().decode(chunk));
}
}
assert.strictEqual(slowItems.length, 4);
assert.strictEqual(slowItems[0], '0');
assert.strictEqual(slowItems[3], '3');
}
// =============================================================================
// Strict backpressure: should throw when buffer overflows
// =============================================================================
async function testShareStrictBackpressure() {
async function* source() {
for (let i = 0; i < 10; i++) {
yield [new TextEncoder().encode(`${i}`)];
}
}
const shared = share(source(), { highWaterMark: 2, backpressure: 'strict' });
const fast = shared.pull();
// Create a second consumer that never reads — this prevents buffer trimming
shared.pull();
// The fast consumer's pulls will eventually cause the buffer to exceed
// the highWaterMark (since the slow consumer prevents trimming),
// triggering an ERR_OUT_OF_RANGE error.
await assert.rejects(async () => {
// eslint-disable-next-line no-unused-vars
for await (const _ of fast) { /* consume */ }
}, { code: 'ERR_OUT_OF_RANGE' });
}
Promise.all([
testShareFrom(),
testShareFromRejectsNonStreamable(),
testSyncShareFromSync(),
testSyncShareFromRejectsNonStreamable(),
testShareProtocolReturnsNull(),
testShareProtocolReturnsNonObject(),
testSyncShareProtocolReturnsNull(),
testSyncShareProtocolReturnsNonObject(),
testShareBlockBackpressure(),
testShareDropOldest(),
testShareDropNewest(),
testShareStrictBackpressure(),
]).then(common.mustCall());
@@ -0,0 +1,162 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
shareSync,
fromSync,
textSync,
} = require('stream/iter');
// =============================================================================
// Sync share
// =============================================================================
async function testShareSyncBasic() {
const shared = shareSync(fromSync('sync shared'));
const consumer = shared.pull();
const data = textSync(consumer);
assert.strictEqual(data, 'sync shared');
}
async function testShareSyncMultipleConsumers() {
const enc = new TextEncoder();
function* gen() {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
}
const shared = shareSync(gen(), { highWaterMark: 16 });
const c1 = shared.pull();
const c2 = shared.pull();
const data1 = textSync(c1);
const data2 = textSync(c2);
assert.strictEqual(data1, 'abc');
assert.strictEqual(data2, 'abc');
}
function testShareSyncCancel() {
// Verify that cancel() on a pre-iteration share yields nothing
const shared = shareSync(fromSync('data'));
const consumer = shared.pull();
shared.cancel();
assert.strictEqual(shared.consumerCount, 0);
const batches = [];
for (const batch of consumer) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
function testShareSyncCancelMidIteration() {
// Verify cancel during iteration stops data flow and cleans up
const enc = new TextEncoder();
let sourceReturnCalled = false;
function* gen() {
try {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
} finally {
sourceReturnCalled = true;
}
}
const shared = shareSync(gen(), { highWaterMark: 16 });
const consumer = shared.pull();
const items = [];
for (const batch of consumer) {
for (const chunk of batch) {
items.push(new TextDecoder().decode(chunk));
}
// Cancel after first batch
shared.cancel();
}
assert.strictEqual(items.length, 1);
assert.strictEqual(items[0], 'a');
assert.strictEqual(sourceReturnCalled, true);
}
function testShareSyncCancelWithReason() {
// When cancel(reason) is called, a consumer that hasn't started
// iterating is already detached, so it sees done:true (not the error).
// But a consumer that is mid-iteration when another consumer cancels
// with a reason will see the error on the next pull after cancel.
const enc = new TextEncoder();
function* gen() {
yield [enc.encode('a')];
yield [enc.encode('b')];
yield [enc.encode('c')];
}
const shared = shareSync(gen(), { highWaterMark: 16 });
const c1 = shared.pull();
const c2 = shared.pull();
// c1 reads one item, then c2 cancels with a reason
const iter1 = c1[Symbol.iterator]();
const first = iter1.next();
assert.strictEqual(first.done, false);
shared.cancel(new Error('sync cancel reason'));
// c1 was already iterating, it's now detached → done
const next = iter1.next();
assert.strictEqual(next.done, true);
// c2 never started, also detached → done (not error)
const batches = [];
for (const batch of c2) {
batches.push(batch);
}
assert.strictEqual(batches.length, 0);
}
// =============================================================================
// Source error propagation
// =============================================================================
function testShareSyncSourceError() {
function* failingSource() {
yield [new TextEncoder().encode('ok')];
throw new Error('sync share boom');
}
const shared = shareSync(failingSource());
const c1 = shared.pull();
const c2 = shared.pull();
// Both consumers should see the error
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of c1) { /* consume */ }
}, { message: 'sync share boom' });
assert.throws(() => {
// eslint-disable-next-line no-unused-vars
for (const _ of c2) { /* consume */ }
}, { message: 'sync share boom' });
}
// shareSync() accepts string source directly (normalized via fromSync())
function testShareSyncStringSource() {
const shared = shareSync('hello-sync-share');
const result = textSync(shared.pull());
assert.strictEqual(result, 'hello-sync-share');
}
Promise.all([
testShareSyncBasic(),
testShareSyncMultipleConsumers(),
testShareSyncCancel(),
testShareSyncCancelMidIteration(),
testShareSyncCancelWithReason(),
testShareSyncSourceError(),
testShareSyncStringSource(),
]).then(common.mustCall());
@@ -0,0 +1,195 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
fromSync,
bytes,
bytesSync,
text,
textSync,
arrayBuffer,
arrayBufferSync,
pipeTo,
pipeToSync,
pull,
pullSync,
} = require('stream/iter');
// =============================================================================
// from() / fromSync() with SharedArrayBuffer
// =============================================================================
function testFromSyncSAB() {
const sab = new SharedArrayBuffer(4);
new Uint8Array(sab).set([10, 20, 30, 40]);
const batches = [];
for (const batch of fromSync(sab)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([10, 20, 30, 40]));
}
async function testFromAsyncSAB() {
const sab = new SharedArrayBuffer(4);
new Uint8Array(sab).set([10, 20, 30, 40]);
const batches = [];
for await (const batch of from(sab)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([10, 20, 30, 40]));
}
// =============================================================================
// Consumers with SAB-backed source
// =============================================================================
function testBytesSyncSAB() {
const sab = new SharedArrayBuffer(5);
new Uint8Array(sab).set([104, 101, 108, 108, 111]); // 'hello'
const data = bytesSync(fromSync(sab));
assert.deepStrictEqual(data, new Uint8Array([104, 101, 108, 108, 111]));
}
async function testBytesAsyncSAB() {
const sab = new SharedArrayBuffer(5);
new Uint8Array(sab).set([104, 101, 108, 108, 111]); // 'hello'
const data = await bytes(from(sab));
assert.deepStrictEqual(data, new Uint8Array([104, 101, 108, 108, 111]));
}
function testTextSyncSAB() {
const sab = new SharedArrayBuffer(5);
new Uint8Array(sab).set([104, 101, 108, 108, 111]); // 'hello'
const result = textSync(fromSync(sab));
assert.strictEqual(result, 'hello');
}
async function testTextAsyncSAB() {
const sab = new SharedArrayBuffer(5);
new Uint8Array(sab).set([104, 101, 108, 108, 111]); // 'hello'
const result = await text(from(sab));
assert.strictEqual(result, 'hello');
}
function testArrayBufferSyncSAB() {
const sab = new SharedArrayBuffer(4);
new Uint8Array(sab).set([1, 2, 3, 4]);
const result = arrayBufferSync(fromSync(sab));
assert.ok(result instanceof SharedArrayBuffer || result instanceof ArrayBuffer);
assert.deepStrictEqual(new Uint8Array(result), new Uint8Array([1, 2, 3, 4]));
}
async function testArrayBufferAsyncSAB() {
const sab = new SharedArrayBuffer(4);
new Uint8Array(sab).set([1, 2, 3, 4]);
const result = await arrayBuffer(from(sab));
assert.ok(result instanceof SharedArrayBuffer || result instanceof ArrayBuffer);
assert.deepStrictEqual(new Uint8Array(result), new Uint8Array([1, 2, 3, 4]));
}
// =============================================================================
// pipeTo / pipeToSync with SAB source
// =============================================================================
function testPipeToSyncSAB() {
const sab = new SharedArrayBuffer(3);
new Uint8Array(sab).set([65, 66, 67]); // 'ABC'
const written = [];
const writer = {
writeSync(chunk) { written.push(chunk); return true; },
endSync() { return written.length; },
};
const totalBytes = pipeToSync(fromSync(sab), writer);
assert.strictEqual(totalBytes, 3);
assert.deepStrictEqual(written[0], new Uint8Array([65, 66, 67]));
}
async function testPipeToAsyncSAB() {
const sab = new SharedArrayBuffer(3);
new Uint8Array(sab).set([65, 66, 67]); // 'ABC'
const written = [];
const writer = {
async write(chunk) { written.push(chunk); },
async end() { return written.length; },
};
await pipeTo(from(sab), writer);
assert.deepStrictEqual(written[0], new Uint8Array([65, 66, 67]));
}
// =============================================================================
// pull / pullSync with SAB-yielding generator
// =============================================================================
function testPullSyncSABChunks() {
function* gen() {
const sab = new SharedArrayBuffer(2);
new Uint8Array(sab).set([1, 2]);
yield [new Uint8Array(sab)];
}
const batches = [];
for (const batch of pullSync(gen())) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([1, 2]));
}
async function testPullAsyncSABChunks() {
async function* gen() {
const sab = new SharedArrayBuffer(2);
new Uint8Array(sab).set([3, 4]);
yield [new Uint8Array(sab)];
}
const batches = [];
for await (const batch of pull(gen())) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([3, 4]));
}
// =============================================================================
// Transform returning SAB
// =============================================================================
async function testTransformReturningSAB() {
function* source() {
yield [new Uint8Array([1, 2, 3])];
}
const transform = (chunks) => {
if (chunks === null) return null;
// Transform returns a Uint8Array backed by a SharedArrayBuffer
const sab = new SharedArrayBuffer(chunks[0].length);
new Uint8Array(sab).set(chunks[0]);
return new Uint8Array(sab);
};
const batches = [];
for await (const batch of pull(source(), transform)) {
batches.push(batch);
}
assert.strictEqual(batches.length, 1);
assert.deepStrictEqual(batches[0][0], new Uint8Array([1, 2, 3]));
}
// =============================================================================
Promise.all([
testFromSyncSAB(),
testFromAsyncSAB(),
testBytesSyncSAB(),
testBytesAsyncSAB(),
testTextSyncSAB(),
testTextAsyncSAB(),
testArrayBufferSyncSAB(),
testArrayBufferAsyncSAB(),
testPipeToSyncSAB(),
testPipeToAsyncSAB(),
testPullSyncSABChunks(),
testPullAsyncSABChunks(),
testTransformReturningSAB(),
]).then(common.mustCall());
@@ -0,0 +1,127 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const zlib = require('zlib');
const { promisify } = require('util');
const {
from,
pull,
bytes,
text,
} = require('stream/iter');
const {
compressGzip,
compressDeflate,
compressBrotli,
compressZstd,
decompressGzip,
decompressDeflate,
decompressBrotli,
decompressZstd,
} = require('zlib/iter');
// =============================================================================
// Cross-compatibility: verify gzip/deflate output is compatible with zlib
// =============================================================================
async function testGzipCompatWithZlib() {
const gunzip = promisify(zlib.gunzip);
const input = 'Cross-compat test with node:zlib. '.repeat(100);
const compressed = await bytes(pull(from(input), compressGzip()));
// Decompress with standard zlib
const decompressed = await gunzip(compressed);
assert.strictEqual(decompressed.toString(), input);
}
async function testDeflateCompatWithZlib() {
const inflate = promisify(zlib.inflate);
const input = 'Cross-compat deflate test. '.repeat(100);
const compressed = await bytes(pull(from(input), compressDeflate()));
// Decompress with standard zlib
const decompressed = await inflate(compressed);
assert.strictEqual(decompressed.toString(), input);
}
async function testBrotliCompatWithZlib() {
const brotliDecompress = promisify(zlib.brotliDecompress);
const input = 'Cross-compat brotli test. '.repeat(100);
const compressed = await bytes(pull(from(input), compressBrotli()));
const decompressed = await brotliDecompress(compressed);
assert.strictEqual(decompressed.toString(), input);
}
async function testZstdCompatWithZlib() {
const zstdDecompress = promisify(zlib.zstdDecompress);
const input = 'Cross-compat zstd test. '.repeat(100);
const compressed = await bytes(pull(from(input), compressZstd()));
const decompressed = await zstdDecompress(compressed);
assert.strictEqual(decompressed.toString(), input);
}
// =============================================================================
// Reverse compat: compress with zlib, decompress with new streams
// =============================================================================
async function testZlibGzipToNewStreams() {
const gzip = promisify(zlib.gzip);
const input = 'Reverse compat gzip test. '.repeat(100);
const compressed = await gzip(input);
const result = await text(pull(from(compressed), decompressGzip()));
assert.strictEqual(result, input);
}
async function testZlibDeflateToNewStreams() {
const deflate = promisify(zlib.deflate);
const input = 'Reverse compat deflate test. '.repeat(100);
const compressed = await deflate(input);
const result = await text(pull(from(compressed), decompressDeflate()));
assert.strictEqual(result, input);
}
async function testZlibBrotliToNewStreams() {
const brotliCompress = promisify(zlib.brotliCompress);
const input = 'Reverse compat brotli test. '.repeat(100);
const compressed = await brotliCompress(input);
const result = await text(pull(from(compressed), decompressBrotli()));
assert.strictEqual(result, input);
}
async function testZlibZstdToNewStreams() {
const zstdCompress = promisify(zlib.zstdCompress);
const input = 'Reverse compat zstd test. '.repeat(100);
const compressed = await zstdCompress(input);
const result = await text(pull(from(compressed), decompressZstd()));
assert.strictEqual(result, input);
}
// =============================================================================
// Run all tests
// =============================================================================
(async () => {
// Cross-compat: new streams compress → zlib decompress
await testGzipCompatWithZlib();
await testDeflateCompatWithZlib();
await testBrotliCompatWithZlib();
await testZstdCompatWithZlib();
// Reverse compat: zlib compress → new streams decompress
await testZlibGzipToNewStreams();
await testZlibDeflateToNewStreams();
await testZlibBrotliToNewStreams();
await testZlibZstdToNewStreams();
})().then(common.mustCall());
@@ -0,0 +1,119 @@
// Flags: --experimental-stream-iter
'use strict';
// Coverage tests for transform.js: abort cleanup, strategy/params options,
// early consumer exit triggering finally block.
const common = require('../common');
const assert = require('assert');
const {
from,
pull,
bytes,
text,
} = require('stream/iter');
const {
compressGzip,
decompressGzip,
compressDeflate,
decompressDeflate,
compressBrotli,
decompressBrotli,
compressZstd,
decompressZstd,
} = require('zlib/iter');
const { constants } = require('zlib');
async function roundTrip(input, compress, decompress) {
return text(pull(from(input), compress, decompress));
}
// Abort mid-compression triggers finally cleanup
async function testAbortMidCompression() {
const ac = new AbortController();
const largeInput = 'x'.repeat(100_000);
const compressed = pull(from(largeInput), compressGzip(),
{ signal: ac.signal });
const iter = compressed[Symbol.asyncIterator]();
// Read one batch then abort
const first = await iter.next();
assert.strictEqual(first.done, false);
ac.abort();
await assert.rejects(iter.next(), { name: 'AbortError' });
}
// Early consumer exit (break from for-await) triggers finally
async function testEarlyConsumerExit() {
const largeInput = 'y'.repeat(100_000);
const compressed = pull(from(largeInput), compressGzip());
// eslint-disable-next-line no-unused-vars
for await (const batch of compressed) {
break; // Early exit — should trigger finally block cleanup
}
// If we get here without hanging or crashing, cleanup worked
}
// Gzip with explicit strategy option
async function testGzipWithStrategy() {
const input = 'strategy test data '.repeat(100);
const c = compressGzip({ strategy: constants.Z_DEFAULT_STRATEGY });
const result = await roundTrip(input, c, decompressGzip());
assert.strictEqual(result, input);
}
// Deflate with Z_FIXED strategy
async function testDeflateWithFixedStrategy() {
const input = 'fixed strategy '.repeat(100);
const c = compressDeflate({ strategy: constants.Z_FIXED });
const result = await roundTrip(input, c, decompressDeflate());
assert.strictEqual(result, input);
}
// Brotli with custom quality param
async function testBrotliWithParams() {
const input = 'brotli params test '.repeat(100);
const params = { [constants.BROTLI_PARAM_QUALITY]: 5 };
const result = await roundTrip(input, compressBrotli({ params }),
decompressBrotli());
assert.strictEqual(result, input);
}
// Zstd with custom compression level param
async function testZstdWithParams() {
const input = 'zstd params test '.repeat(100);
const params = { [constants.ZSTD_c_compressionLevel]: 10 };
const result = await roundTrip(input, compressZstd({ params }),
decompressZstd());
assert.strictEqual(result, input);
}
// Gzip with custom chunkSize
async function testGzipWithChunkSize() {
const input = 'chunk size test';
const c = compressGzip({ chunkSize: 256 });
const d = decompressGzip({ chunkSize: 256 });
const result = await roundTrip(input, c, d);
assert.strictEqual(result, input);
}
// Invalid chunkSize throws when transform is invoked
async function testInvalidChunkSize() {
const tx = compressGzip({ chunkSize: 8 });
await assert.rejects(
async () => await bytes(pull(from('data'), tx)),
{ code: 'ERR_OUT_OF_RANGE' },
);
}
Promise.all([
testAbortMidCompression(),
testEarlyConsumerExit(),
testGzipWithStrategy(),
testDeflateWithFixedStrategy(),
testBrotliWithParams(),
testZstdWithParams(),
testGzipWithChunkSize(),
testInvalidChunkSize(),
]).then(common.mustCall());
@@ -0,0 +1,71 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
pull,
bytes,
} = require('stream/iter');
const {
decompressGzip,
decompressDeflate,
decompressBrotli,
decompressZstd,
} = require('zlib/iter');
// =============================================================================
// Decompression of corrupt data
// =============================================================================
async function testCorruptGzipData() {
const corrupt = new Uint8Array([0x1F, 0x8B, 0xFF, 0xFF, 0xFF]);
await assert.rejects(
async () => await bytes(pull(from(corrupt), decompressGzip())), {
name: 'Error',
code: 'Z_DATA_ERROR',
});
}
async function testCorruptDeflateData() {
const corrupt = new Uint8Array([0x78, 0xFF, 0xFF, 0xFF]);
await assert.rejects(
async () => await bytes(pull(from(corrupt), decompressDeflate())), {
name: 'Error',
code: 'Z_DATA_ERROR',
});
}
async function testCorruptBrotliData() {
const corrupt = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF]);
await assert.rejects(
async () => await bytes(pull(from(corrupt), decompressBrotli())), {
name: 'Error',
code: 'ERR__ERROR_FORMAT_PADDING_2',
});
}
async function testCorruptZstdData() {
// Completely invalid data (not even valid magic bytes)
const corrupt = new Uint8Array([0xFF, 0xFF, 0xFF, 0xFF, 0xFF]);
await assert.rejects(
async () => await bytes(pull(from(corrupt), decompressZstd())), {
name: 'Error',
code: 'ZSTD_error_prefix_unknown',
});
}
// =============================================================================
// Run all tests
// =============================================================================
(async () => {
await testCorruptGzipData();
await testCorruptDeflateData();
await testCorruptBrotliData();
await testCorruptZstdData();
})().then(common.mustCall());
@@ -0,0 +1,225 @@
// Flags: --experimental-stream-iter
'use strict';
// Tests for transform output normalization edge cases:
// ArrayBuffer, ArrayBufferView, iterables, strings, invalid types.
const common = require('../common');
const assert = require('assert');
const {
pull,
pullSync,
bytes,
bytesSync,
from,
fromSync,
} = require('stream/iter');
// Stateless transform returns ArrayBuffer (async)
async function testTransformReturnsArrayBuffer() {
const tx = (chunks) => {
if (chunks === null) return null;
const ab = new ArrayBuffer(chunks[0].length);
new Uint8Array(ab).set(chunks[0]);
return ab;
};
const data = await bytes(pull(from('AB'), tx));
assert.deepStrictEqual(data, new TextEncoder().encode('AB'));
}
// Stateless transform returns ArrayBuffer (sync)
async function testSyncTransformReturnsArrayBuffer() {
const tx = (chunks) => {
if (chunks === null) return null;
const ab = new ArrayBuffer(chunks[0].length);
new Uint8Array(ab).set(chunks[0]);
return ab;
};
const data = bytesSync(pullSync(fromSync('AB'), tx));
assert.deepStrictEqual(data, new TextEncoder().encode('AB'));
}
// Stateless transform returns Float32Array (non-Uint8Array ArrayBufferView)
async function testTransformReturnsFloat32Array() {
const tx = (chunks) => {
if (chunks === null) return null;
return new Float32Array([1.0]);
};
const data = await bytes(pull(from('x'), tx));
assert.strictEqual(data.byteLength, 4); // 1 float32 = 4 bytes
}
// Stateless sync transform returns Float32Array
async function testSyncTransformReturnsFloat32Array() {
const tx = (chunks) => {
if (chunks === null) return null;
return new Float32Array([1.0]);
};
const data = bytesSync(pullSync(fromSync('x'), tx));
assert.strictEqual(data.byteLength, 4);
}
// Stateless transform returns a sync generator (iterable)
async function testTransformReturnsGenerator() {
const tx = (chunks) => {
if (chunks === null) return null;
return (function*() {
yield new Uint8Array([65]);
yield new Uint8Array([66]);
})();
};
const data = await bytes(pull(from('x'), tx));
assert.deepStrictEqual(data, new Uint8Array([65, 66]));
}
// Stateless sync transform returns a generator
async function testSyncTransformReturnsGenerator() {
const tx = (chunks) => {
if (chunks === null) return null;
return (function*() {
yield new Uint8Array([67]);
yield new Uint8Array([68]);
})();
};
const data = bytesSync(pullSync(fromSync('x'), tx));
assert.deepStrictEqual(data, new Uint8Array([67, 68]));
}
// Stateless async transform returns an async generator
async function testTransformReturnsAsyncGenerator() {
const tx = (chunks) => {
if (chunks === null) return null;
return (async function*() {
yield new Uint8Array([69]);
yield new Uint8Array([70]);
})();
};
const data = await bytes(pull(from('x'), tx));
assert.deepStrictEqual(data, new Uint8Array([69, 70]));
}
// Stateful async transform yields string
async function testStatefulTransformYieldsString() {
const tx = {
async *transform(source) {
for await (const chunks of source) {
if (chunks === null) return;
yield 'hello';
}
},
};
const data = await bytes(pull(from('x'), tx));
assert.deepStrictEqual(data, new TextEncoder().encode('hello'));
}
// Stateful async transform yields ArrayBuffer
async function testStatefulTransformYieldsArrayBuffer() {
const tx = {
async *transform(source) {
for await (const chunks of source) {
if (chunks === null) return;
const ab = new ArrayBuffer(2);
new Uint8Array(ab).set([71, 72]);
yield ab;
}
},
};
const data = await bytes(pull(from('x'), tx));
assert.deepStrictEqual(data, new Uint8Array([71, 72]));
}
// Stateful sync transform yields string
async function testStatefulSyncTransformYieldsString() {
const tx = {
*transform(source) {
for (const chunks of source) {
if (chunks === null) return;
yield 'world';
}
},
};
const data = bytesSync(pullSync(fromSync('x'), tx));
assert.deepStrictEqual(data, new TextEncoder().encode('world'));
}
// Flush returns single Uint8Array (not batch)
async function testFlushReturnsSingleUint8Array() {
const tx = (chunks) => {
if (chunks === null) return new Uint8Array([99]); // Flush returns single
return chunks;
};
const data = await bytes(pull(from('x'), tx));
// Should contain both the original data and the flush byte
assert.ok(data.includes(99));
}
// Flush returns string
async function testFlushReturnsString() {
const tx = (chunks) => {
if (chunks === null) return 'trailer';
return chunks;
};
const data = await bytes(pull(from('x'), tx));
const trailer = new TextEncoder().encode('trailer');
// Last bytes should be the trailer
const tail = data.slice(data.length - trailer.length);
assert.deepStrictEqual(tail, trailer);
}
// Sync flush returns single Uint8Array
async function testSyncFlushReturnsSingleUint8Array() {
const tx = (chunks) => {
if (chunks === null) return new Uint8Array([88]);
return chunks;
};
const data = bytesSync(pullSync(fromSync('x'), tx));
assert.ok(data.includes(88));
}
// Transform returns invalid type → ERR_INVALID_ARG_TYPE
async function testTransformReturnsInvalidType() {
const tx = (chunks) => {
if (chunks === null) return null;
return 42; // Invalid
};
await assert.rejects(
async () => {
// eslint-disable-next-line no-unused-vars
for await (const batch of pull(from('x'), tx)) { /* consume */ }
},
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
// Sync transform returns invalid type → ERR_INVALID_ARG_TYPE
async function testSyncTransformReturnsInvalidType() {
const tx = (chunks) => {
if (chunks === null) return null;
return 42;
};
assert.throws(
() => {
// eslint-disable-next-line no-unused-vars
for (const batch of pullSync(fromSync('x'), tx)) { /* consume */ }
},
{ code: 'ERR_INVALID_ARG_TYPE' },
);
}
Promise.all([
testTransformReturnsArrayBuffer(),
testSyncTransformReturnsArrayBuffer(),
testTransformReturnsFloat32Array(),
testSyncTransformReturnsFloat32Array(),
testTransformReturnsGenerator(),
testSyncTransformReturnsGenerator(),
testTransformReturnsAsyncGenerator(),
testStatefulTransformYieldsString(),
testStatefulTransformYieldsArrayBuffer(),
testStatefulSyncTransformYieldsString(),
testFlushReturnsSingleUint8Array(),
testFlushReturnsString(),
testSyncFlushReturnsSingleUint8Array(),
testTransformReturnsInvalidType(),
testSyncTransformReturnsInvalidType(),
]).then(common.mustCall());
@@ -0,0 +1,291 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from,
pull,
bytes,
text,
} = require('stream/iter');
const {
compressGzip,
compressDeflate,
compressBrotli,
compressZstd,
decompressGzip,
decompressDeflate,
decompressBrotli,
decompressZstd,
} = require('zlib/iter');
// =============================================================================
// Helper: compress then decompress, verify round-trip equality
// =============================================================================
async function roundTrip(input, compress, decompress) {
return text(pull(pull(from(input), compress), decompress));
}
async function roundTripBytes(inputBuf, compress, decompress) {
return bytes(pull(pull(from(inputBuf), compress), decompress));
}
// =============================================================================
// Gzip round-trip tests
// =============================================================================
async function testGzipRoundTrip() {
const input = 'Hello, gzip compression!';
const result = await roundTrip(input, compressGzip(), decompressGzip());
assert.strictEqual(result, input);
}
async function testGzipLargeData() {
// 100KB of repeated text - exercises multi-chunk path
const input = 'gzip large data test. '.repeat(5000);
const result = await roundTrip(input, compressGzip(), decompressGzip());
assert.strictEqual(result, input);
}
async function testGzipActuallyCompresses() {
const input = 'Repeated data compresses well. '.repeat(1000);
const inputBuf = Buffer.from(input);
const source = from(inputBuf);
const compressed = await bytes(pull(source, compressGzip()));
assert.ok(compressed.byteLength < inputBuf.byteLength,
`Compressed ${compressed.byteLength} should be < original ${inputBuf.byteLength}`);
}
// =============================================================================
// Deflate round-trip tests
// =============================================================================
async function testDeflateRoundTrip() {
const input = 'Hello, deflate compression!';
const result = await roundTrip(input, compressDeflate(), decompressDeflate());
assert.strictEqual(result, input);
}
async function testDeflateLargeData() {
const input = 'deflate large data test. '.repeat(5000);
const result = await roundTrip(input, compressDeflate(), decompressDeflate());
assert.strictEqual(result, input);
}
async function testDeflateActuallyCompresses() {
const input = 'Repeated data compresses well. '.repeat(1000);
const inputBuf = Buffer.from(input);
const source = from(inputBuf);
const compressed = await bytes(pull(source, compressDeflate()));
assert.ok(compressed.byteLength < inputBuf.byteLength,
`Compressed ${compressed.byteLength} should be < original ${inputBuf.byteLength}`);
}
// =============================================================================
// Brotli round-trip tests
// =============================================================================
async function testBrotliRoundTrip() {
const input = 'Hello, brotli compression!';
const result = await roundTrip(input, compressBrotli(), decompressBrotli());
assert.strictEqual(result, input);
}
async function testBrotliLargeData() {
const input = 'brotli large data test. '.repeat(5000);
const result = await roundTrip(input, compressBrotli(), decompressBrotli());
assert.strictEqual(result, input);
}
async function testBrotliActuallyCompresses() {
const input = 'Repeated data compresses well. '.repeat(1000);
const inputBuf = Buffer.from(input);
const compressed = await bytes(pull(from(inputBuf), compressBrotli()));
assert.ok(compressed.byteLength < inputBuf.byteLength,
`Compressed ${compressed.byteLength} should be < original ${inputBuf.byteLength}`);
}
// =============================================================================
// Zstd round-trip tests
// =============================================================================
async function testZstdRoundTrip() {
const input = 'Hello, zstd compression!';
const result = await roundTrip(input, compressZstd(), decompressZstd());
assert.strictEqual(result, input);
}
async function testZstdLargeData() {
const input = 'zstd large data test. '.repeat(5000);
const result = await roundTrip(input, compressZstd(), decompressZstd());
assert.strictEqual(result, input);
}
async function testZstdActuallyCompresses() {
const input = 'Repeated data compresses well. '.repeat(1000);
const inputBuf = Buffer.from(input);
const compressed = await bytes(pull(from(inputBuf), compressZstd()));
assert.ok(compressed.byteLength < inputBuf.byteLength,
`Compressed ${compressed.byteLength} should be < original ${inputBuf.byteLength}`);
}
// =============================================================================
// Binary data round-trip - verify no corruption on non-text data
// =============================================================================
// Create a buffer with a repeating byte pattern covering all 256 values.
function makeBinaryTestData(size = 1024) {
const buf = Buffer.alloc(size);
for (let i = 0; i < size; i++) buf[i] = i & 0xFF;
return buf;
}
async function testBinaryRoundTripGzip() {
const input = makeBinaryTestData();
const result = await roundTripBytes(input, compressGzip(), decompressGzip());
assert.strictEqual(result.byteLength, input.byteLength);
assert.deepStrictEqual(Buffer.from(result), input);
}
async function testBinaryRoundTripDeflate() {
const input = makeBinaryTestData();
const result = await roundTripBytes(input, compressDeflate(),
decompressDeflate());
assert.strictEqual(result.byteLength, input.byteLength);
assert.deepStrictEqual(Buffer.from(result), input);
}
async function testBinaryRoundTripBrotli() {
const input = makeBinaryTestData();
const result = await roundTripBytes(input, compressBrotli(),
decompressBrotli());
assert.strictEqual(result.byteLength, input.byteLength);
assert.deepStrictEqual(Buffer.from(result), input);
}
async function testBinaryRoundTripZstd() {
const input = makeBinaryTestData();
const result = await roundTripBytes(input, compressZstd(), decompressZstd());
assert.strictEqual(result.byteLength, input.byteLength);
assert.deepStrictEqual(Buffer.from(result), input);
}
// =============================================================================
// Empty input
// =============================================================================
async function testEmptyInputGzip() {
const result = await roundTrip('', compressGzip(), decompressGzip());
assert.strictEqual(result, '');
}
async function testEmptyInputDeflate() {
const result = await roundTrip('', compressDeflate(), decompressDeflate());
assert.strictEqual(result, '');
}
async function testEmptyInputBrotli() {
const result = await roundTrip('', compressBrotli(), decompressBrotli());
assert.strictEqual(result, '');
}
async function testEmptyInputZstd() {
const result = await roundTrip('', compressZstd(), decompressZstd());
assert.strictEqual(result, '');
}
// =============================================================================
// Chained transforms - compress with one, then another, decompress in reverse
// =============================================================================
async function testChainedGzipDeflate() {
const input = 'Double compression test data. '.repeat(100);
// Compress: gzip then deflate
const compressed = pull(pull(from(input), compressGzip()), compressDeflate());
// Decompress: deflate then gzip (reverse order)
const decompressed = pull(pull(compressed, decompressDeflate()),
decompressGzip());
const result = await text(decompressed);
assert.strictEqual(result, input);
}
// =============================================================================
// Transform protocol: verify each factory returns a proper transform object
// =============================================================================
function testTransformProtocol() {
[
compressGzip, compressDeflate, compressBrotli, compressZstd,
decompressGzip, decompressDeflate, decompressBrotli, decompressZstd,
].forEach((factory) => {
const t = factory();
assert.strictEqual(typeof t.transform, 'function',
`${factory.name}() should have a transform function`);
});
}
// =============================================================================
// Compression with options
// =============================================================================
async function testGzipWithLevel() {
const data = 'a'.repeat(10000);
const level1 = await bytes(pull(from(data), compressGzip({ level: 1 })));
const level9 = await bytes(pull(from(data), compressGzip({ level: 9 })));
// Higher compression level should produce smaller output
assert.ok(level9.length <= level1.length);
// Both should decompress to original
const dec1 = await text(pull(from(level1), decompressGzip()));
const dec9 = await text(pull(from(level9), decompressGzip()));
assert.strictEqual(dec1, data);
assert.strictEqual(dec9, data);
}
// =============================================================================
// Run all tests
// =============================================================================
(async () => {
// Gzip
await testGzipRoundTrip();
await testGzipLargeData();
await testGzipActuallyCompresses();
// Deflate
await testDeflateRoundTrip();
await testDeflateLargeData();
await testDeflateActuallyCompresses();
// Brotli
await testBrotliRoundTrip();
await testBrotliLargeData();
await testBrotliActuallyCompresses();
// Zstd
await testZstdRoundTrip();
await testZstdLargeData();
await testZstdActuallyCompresses();
// Binary data
await testBinaryRoundTripGzip();
await testBinaryRoundTripDeflate();
await testBinaryRoundTripBrotli();
await testBinaryRoundTripZstd();
// Empty input
await testEmptyInputGzip();
await testEmptyInputDeflate();
await testEmptyInputBrotli();
await testEmptyInputZstd();
// Chained
await testChainedGzipDeflate();
// Protocol
testTransformProtocol();
// Compression with options
await testGzipWithLevel();
})().then(common.mustCall());
@@ -0,0 +1,227 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
fromSync,
pullSync,
bytesSync,
textSync,
} = require('stream/iter');
const {
compressGzipSync,
compressDeflateSync,
compressBrotliSync,
compressZstdSync,
decompressGzipSync,
decompressDeflateSync,
decompressBrotliSync,
decompressZstdSync,
} = require('zlib/iter');
// =============================================================================
// Helper: sync compress then decompress, verify round-trip equality
// =============================================================================
function roundTrip(input, compress, decompress) {
return textSync(pullSync(pullSync(fromSync(input), compress), decompress));
}
function roundTripBytes(inputBuf, compress, decompress) {
return bytesSync(pullSync(pullSync(fromSync(inputBuf), compress), decompress));
}
// =============================================================================
// Gzip sync round-trip tests
// =============================================================================
function testGzipRoundTrip() {
const input = 'Hello, sync gzip compression!';
const result = roundTrip(input, compressGzipSync(), decompressGzipSync());
assert.strictEqual(result, input);
}
function testGzipLargeData() {
const input = 'gzip sync large data test. '.repeat(5000);
const result = roundTrip(input, compressGzipSync(), decompressGzipSync());
assert.strictEqual(result, input);
}
function testGzipActuallyCompresses() {
const input = 'Repeated data compresses well. '.repeat(1000);
const inputBuf = Buffer.from(input);
const compressed = bytesSync(pullSync(fromSync(inputBuf),
compressGzipSync()));
assert.ok(compressed.byteLength < inputBuf.byteLength,
`Compressed ${compressed.byteLength} should be < ` +
`original ${inputBuf.byteLength}`);
}
function testGzipBinaryData() {
const inputBuf = Buffer.alloc(10000);
for (let i = 0; i < inputBuf.length; i++) inputBuf[i] = i & 0xff;
const result = roundTripBytes(inputBuf, compressGzipSync(),
decompressGzipSync());
assert.deepStrictEqual(result, inputBuf);
}
// =============================================================================
// Deflate sync round-trip tests
// =============================================================================
function testDeflateRoundTrip() {
const input = 'Hello, sync deflate compression!';
const result = roundTrip(input, compressDeflateSync(),
decompressDeflateSync());
assert.strictEqual(result, input);
}
function testDeflateLargeData() {
const input = 'deflate sync large data test. '.repeat(5000);
const result = roundTrip(input, compressDeflateSync(),
decompressDeflateSync());
assert.strictEqual(result, input);
}
// =============================================================================
// Brotli sync round-trip tests
// =============================================================================
function testBrotliRoundTrip() {
const input = 'Hello, sync brotli compression!';
const result = roundTrip(input, compressBrotliSync(),
decompressBrotliSync());
assert.strictEqual(result, input);
}
function testBrotliLargeData() {
const input = 'brotli sync large data test. '.repeat(5000);
const result = roundTrip(input, compressBrotliSync(),
decompressBrotliSync());
assert.strictEqual(result, input);
}
// =============================================================================
// Zstd sync round-trip tests
// =============================================================================
function testZstdRoundTrip() {
const input = 'Hello, sync zstd compression!';
const result = roundTrip(input, compressZstdSync(), decompressZstdSync());
assert.strictEqual(result, input);
}
function testZstdLargeData() {
const input = 'zstd sync large data test. '.repeat(5000);
const result = roundTrip(input, compressZstdSync(), decompressZstdSync());
assert.strictEqual(result, input);
}
// =============================================================================
// Cross-algorithm: compress async-compatible, decompress sync (and vice versa)
// The sync transforms should produce output compatible with the standard format
// =============================================================================
function testGzipWithOptions() {
const input = 'options test data '.repeat(100);
const result = roundTrip(input,
compressGzipSync({ level: 1 }),
decompressGzipSync());
assert.strictEqual(result, input);
}
function testBrotliWithOptions() {
const zlib = require('zlib');
const input = 'brotli options test data '.repeat(100);
const result = roundTrip(input,
compressBrotliSync({
params: {
[zlib.constants.BROTLI_PARAM_QUALITY]: 3,
},
}),
decompressBrotliSync());
assert.strictEqual(result, input);
}
// =============================================================================
// Stateless + stateful sync transform pipeline
// =============================================================================
function testMixedStatelessAndStateful() {
// Uppercase stateless transform + gzip stateful transform
const upper = (chunks) => {
if (chunks === null) return null;
const out = new Array(chunks.length);
for (let j = 0; j < chunks.length; j++) {
const src = chunks[j];
const buf = Buffer.allocUnsafe(src.length);
for (let i = 0; i < src.length; i++) {
const b = src[i];
buf[i] = (b >= 0x61 && b <= 0x7a) ? b - 0x20 : b;
}
out[j] = buf;
}
return out;
};
const input = 'hello world '.repeat(100);
const result = textSync(
pullSync(
pullSync(fromSync(input), upper, compressGzipSync()),
decompressGzipSync(),
),
);
assert.strictEqual(result, input.toUpperCase());
}
// =============================================================================
// Early consumer exit (break from for-of) triggers cleanup
// =============================================================================
function testEarlyExit() {
const input = 'y'.repeat(100_000);
const compressed = pullSync(fromSync(input), compressGzipSync());
// eslint-disable-next-line no-unused-vars
for (const batch of compressed) {
break; // Early exit - should trigger finally block cleanup
}
// If we get here without crashing, cleanup worked
}
// =============================================================================
// Empty input
// =============================================================================
function testEmptyInput() {
const result = textSync(
pullSync(
pullSync(fromSync(''), compressGzipSync()),
decompressGzipSync(),
),
);
assert.strictEqual(result, '');
}
// =============================================================================
// Run all tests
// =============================================================================
testGzipRoundTrip();
testGzipLargeData();
testGzipActuallyCompresses();
testGzipBinaryData();
testDeflateRoundTrip();
testDeflateLargeData();
testBrotliRoundTrip();
testBrotliLargeData();
testZstdRoundTrip();
testZstdLargeData();
testGzipWithOptions();
testBrotliWithOptions();
testMixedStatelessAndStateful();
testEarlyExit();
testEmptyInput();
common.mustCall()();
@@ -0,0 +1,347 @@
// Flags: --experimental-stream-iter
'use strict';
const common = require('../common');
const assert = require('assert');
const {
from, fromSync, pull, pullSync, pipeTo,
push, duplex, broadcast, Broadcast, share, shareSync,
Share, SyncShare,
bytes, bytesSync, text, textSync,
arrayBuffer, arrayBufferSync, array, arraySync,
tap, tapSync,
} = require('stream/iter');
const {
compressGzip, compressBrotli, compressZstd,
decompressGzip, decompressBrotli, decompressZstd,
} = require('zlib/iter');
// =============================================================================
// push() validation
// =============================================================================
// HighWaterMark must be integer >= 1
assert.throws(() => push({ highWaterMark: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => push({ highWaterMark: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
// Values < 1 are clamped to 1
assert.strictEqual(push({ highWaterMark: 0 }).writer.desiredSize, 1);
assert.strictEqual(push({ highWaterMark: -1 }).writer.desiredSize, 1);
assert.strictEqual(push({ highWaterMark: -100 }).writer.desiredSize, 1);
// MAX_SAFE_INTEGER is accepted
assert.strictEqual(push({ highWaterMark: Number.MAX_SAFE_INTEGER }).writer.desiredSize,
Number.MAX_SAFE_INTEGER);
// Values above MAX_SAFE_INTEGER are rejected by validateInteger
assert.throws(() => push({ highWaterMark: Number.MAX_SAFE_INTEGER + 1 }),
{ code: 'ERR_OUT_OF_RANGE' });
// Signal must be AbortSignal
assert.throws(() => push({ signal: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => push({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
// Transforms must be functions or transform objects
assert.throws(() => push(42, {}), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => push('bad', {}), { code: 'ERR_INVALID_ARG_TYPE' });
// Writer.writev requires array
{
const { writer } = push();
assert.throws(() => writer.writev('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => writer.writev(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => writer.writevSync('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
writer.endSync();
}
// Writer.write rejects non-string/non-Uint8Array
{
const { writer } = push();
assert.throws(() => writer.writeSync(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => writer.writeSync({}), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => writer.writeSync(true), { code: 'ERR_INVALID_ARG_TYPE' });
writer.endSync();
}
// =============================================================================
// duplex() validation
// =============================================================================
assert.throws(() => duplex(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => duplex('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => duplex({ a: 42 }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => duplex({ b: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
// highWaterMark validation (cascades through to push())
assert.throws(() => duplex({ highWaterMark: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => duplex({ highWaterMark: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => duplex({ highWaterMark: Number.MAX_SAFE_INTEGER + 1 }),
{ code: 'ERR_OUT_OF_RANGE' });
// Values < 1 are clamped to 1 (both directions)
{
const [a, b] = duplex({ highWaterMark: 0 });
assert.strictEqual(a.writer.desiredSize, 1);
assert.strictEqual(b.writer.desiredSize, 1);
a.close();
b.close();
}
// MAX_SAFE_INTEGER is accepted
{
const [a, b] = duplex({ highWaterMark: Number.MAX_SAFE_INTEGER });
assert.strictEqual(a.writer.desiredSize, Number.MAX_SAFE_INTEGER);
assert.strictEqual(b.writer.desiredSize, Number.MAX_SAFE_INTEGER);
a.close();
b.close();
}
// Per-direction overrides
{
const [a, b] = duplex({ a: { highWaterMark: 0 }, b: { highWaterMark: 5 } });
assert.strictEqual(a.writer.desiredSize, 1); // clamped
assert.strictEqual(b.writer.desiredSize, 5);
a.close();
b.close();
}
assert.throws(() => duplex({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
// =============================================================================
// pull() / pullSync() validation
// =============================================================================
// Signal must be AbortSignal
assert.throws(() => pull(from('a'), { signal: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
// Transforms must be functions or transform objects
assert.throws(() => pull(from('a'), 42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => pull(from('a'), 'bad'), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => pullSync(fromSync('a'), 42), { code: 'ERR_INVALID_ARG_TYPE' });
// =============================================================================
// broadcast() validation
// =============================================================================
assert.throws(() => broadcast({ highWaterMark: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => broadcast({ highWaterMark: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => broadcast({ highWaterMark: Number.MAX_SAFE_INTEGER + 1 }),
{ code: 'ERR_OUT_OF_RANGE' });
// Values < 1 are clamped to 1 (need a consumer for desiredSize to work)
{
const bc = broadcast({ highWaterMark: 0 });
bc.broadcast.push();
assert.strictEqual(bc.writer.desiredSize, 1);
bc.writer.endSync();
}
{
const bc = broadcast({ highWaterMark: -1 });
bc.broadcast.push();
assert.strictEqual(bc.writer.desiredSize, 1);
bc.writer.endSync();
}
// MAX_SAFE_INTEGER is accepted
{
const bc = broadcast({ highWaterMark: Number.MAX_SAFE_INTEGER });
bc.broadcast.push();
assert.strictEqual(bc.writer.desiredSize, Number.MAX_SAFE_INTEGER);
bc.writer.endSync();
}
assert.throws(() => broadcast({ signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => broadcast({ backpressure: 'bad' }), { code: 'ERR_INVALID_ARG_VALUE' });
// Broadcast.from rejects non-iterable input
assert.throws(() => Broadcast.from(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => Broadcast.from('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
// =============================================================================
// share() / shareSync() validation
// =============================================================================
assert.throws(() => share(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => share(from('a'), { highWaterMark: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => share(from('a'), { highWaterMark: 1.5 }), { code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => share(from('a'), { highWaterMark: Number.MAX_SAFE_INTEGER + 1 }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => share(from('a'), { signal: {} }), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => share(from('a'), { backpressure: 'bad' }), { code: 'ERR_INVALID_ARG_VALUE' });
// share() values < 1 are clamped (no desiredSize, but accepts the value)
share(from('a'), { highWaterMark: 0 }).cancel();
share(from('a'), { highWaterMark: -1 }).cancel();
share(from('a'), { highWaterMark: Number.MAX_SAFE_INTEGER }).cancel();
assert.throws(() => shareSync(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => shareSync(fromSync('a'), { highWaterMark: 'bad' }),
{ code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => shareSync(fromSync('a'), { highWaterMark: 1.5 }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => shareSync(fromSync('a'), { highWaterMark: Number.MAX_SAFE_INTEGER + 1 }),
{ code: 'ERR_OUT_OF_RANGE' });
// shareSync() values < 1 are clamped (accepts the value)
shareSync(fromSync('a'), { highWaterMark: 0 }).cancel();
shareSync(fromSync('a'), { highWaterMark: -1 }).cancel();
shareSync(fromSync('a'), { highWaterMark: Number.MAX_SAFE_INTEGER }).cancel();
// Share.from / SyncShare.fromSync reject non-iterable
assert.throws(() => Share.from(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => SyncShare.fromSync(42), { code: 'ERR_INVALID_ARG_TYPE' });
// =============================================================================
// Consumer validation (synchronous)
// =============================================================================
// tap / tapSync require function
assert.throws(() => tap(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => tap('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => tapSync(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => tapSync(null), { code: 'ERR_INVALID_ARG_TYPE' });
// Sync consumer options
assert.throws(() => bytesSync(fromSync('a'), { limit: 'bad' }),
{ code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => bytesSync(fromSync('a'), { limit: -1 }),
{ code: 'ERR_OUT_OF_RANGE' });
assert.throws(() => textSync(fromSync('a'), { encoding: 42 }),
{ code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => textSync(fromSync('a'), { encoding: 'bogus' }),
{ code: 'ERR_INVALID_ARG_VALUE' });
assert.throws(() => arrayBufferSync(fromSync('a'), { limit: 'bad' }),
{ code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => arraySync(fromSync('a'), { limit: -1 }),
{ code: 'ERR_OUT_OF_RANGE' });
// Options must be object if provided
assert.throws(() => bytesSync(fromSync('a'), 42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => textSync(fromSync('a'), 'bad'), { code: 'ERR_INVALID_ARG_TYPE' });
// Compression options must be object
assert.throws(() => compressGzip(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => decompressGzip('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => compressBrotli(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => decompressBrotli('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => compressZstd(42), { code: 'ERR_INVALID_ARG_TYPE' });
assert.throws(() => decompressZstd('bad'), { code: 'ERR_INVALID_ARG_TYPE' });
// =============================================================================
// Async consumer and compression validation
// =============================================================================
// Helper: consume a transform through a pipeline to trigger lazy validation.
const consume = (transform) => bytes(pull(from('test'), transform));
async function testAsyncValidation() {
// pipeTo signal
await assert.rejects(
() => pipeTo(from('a'), { write() {} }, { signal: 'bad' }),
{ code: 'ERR_INVALID_ARG_TYPE' },
);
// Async consumer options
await assert.rejects(
() => bytes(from('a'), 42), { code: 'ERR_INVALID_ARG_TYPE' });
await assert.rejects(
() => bytes(from('a'), { signal: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
await assert.rejects(
() => bytes(from('a'), { limit: 'bad' }), { code: 'ERR_INVALID_ARG_TYPE' });
await assert.rejects(
() => bytes(from('a'), { limit: -1 }), { code: 'ERR_OUT_OF_RANGE' });
await assert.rejects(
() => text(from('a'), { encoding: 42 }), { code: 'ERR_INVALID_ARG_TYPE' });
await assert.rejects(
() => text(from('a'), { encoding: 'not-a-real-encoding' }),
{ code: 'ERR_INVALID_ARG_VALUE' });
await assert.rejects(
() => arrayBuffer(from('a'), { limit: 'bad' }),
{ code: 'ERR_INVALID_ARG_TYPE' });
await assert.rejects(
() => array(from('a'), { limit: -1 }), { code: 'ERR_OUT_OF_RANGE' });
const TYPE = { code: 'ERR_INVALID_ARG_TYPE' };
const RANGE = { code: 'ERR_OUT_OF_RANGE' };
const BROTLI = { code: 'ERR_BROTLI_INVALID_PARAM' };
const ZSTD = { code: 'ERR_ZSTD_INVALID_PARAM' };
// ChunkSize
await assert.rejects(consume(compressGzip({ chunkSize: 'bad' })), TYPE);
await assert.rejects(consume(compressGzip({ chunkSize: 0 })), RANGE);
await assert.rejects(consume(compressGzip({ chunkSize: 10 })), RANGE);
// WindowBits
await assert.rejects(consume(compressGzip({ windowBits: 'bad' })), TYPE);
await assert.rejects(consume(compressGzip({ windowBits: 100 })), RANGE);
// Level
await assert.rejects(consume(compressGzip({ level: 'bad' })), TYPE);
await assert.rejects(consume(compressGzip({ level: 100 })), RANGE);
// MemLevel
await assert.rejects(consume(compressGzip({ memLevel: 'bad' })), TYPE);
await assert.rejects(consume(compressGzip({ memLevel: 100 })), RANGE);
// Strategy
await assert.rejects(consume(compressGzip({ strategy: 'bad' })), TYPE);
await assert.rejects(consume(compressGzip({ strategy: 100 })), RANGE);
// Dictionary
await assert.rejects(consume(compressGzip({ dictionary: 42 })), TYPE);
await assert.rejects(consume(compressGzip({ dictionary: 'bad' })), TYPE);
// Brotli params
await assert.rejects(consume(compressBrotli({ params: 42 })), TYPE);
await assert.rejects(consume(compressBrotli({ params: { bad: 1 } })), BROTLI);
await assert.rejects(consume(compressBrotli({ params: { [-1]: 1 } })), BROTLI);
await assert.rejects(consume(compressBrotli({ params: { 0: 'bad' } })), TYPE);
// Zstd params
await assert.rejects(consume(compressZstd({ params: 42 })), TYPE);
await assert.rejects(consume(compressZstd({ params: { bad: 1 } })), ZSTD);
await assert.rejects(consume(compressZstd({ params: { 0: 'bad' } })), TYPE);
// Zstd pledgedSrcSize
await assert.rejects(consume(compressZstd({ pledgedSrcSize: 'bad' })), TYPE);
await assert.rejects(consume(compressZstd({ pledgedSrcSize: -1 })), RANGE);
}
// =============================================================================
// Valid calls still work
// =============================================================================
// Push with valid options
{
const { writer } = push({ highWaterMark: 2 });
writer.writeSync('hello');
writer.endSync();
}
// Duplex with valid options
{
const [a, b] = duplex({ highWaterMark: 2 });
a.close();
b.close();
}
// Broadcast with valid options
{
const { writer } = broadcast({ highWaterMark: 4 });
writer.endSync();
}
// Share with valid options
{
const shared = share(from('hello'), { highWaterMark: 4 });
shared.cancel();
}
// Compression with valid options
{
const transform = compressGzip({ chunkSize: 1024, level: 6 });
assert.strictEqual(typeof transform.transform, 'function');
}
// Brotli with valid params
{
const { constants: { BROTLI_PARAM_QUALITY } } = require('zlib');
const transform = compressBrotli({ params: { [BROTLI_PARAM_QUALITY]: 5 } });
assert.strictEqual(typeof transform.transform, 'function');
}
testAsyncValidation().then(common.mustCall());