import { test } from "node:test"; import assert from "node:assert/strict"; import { mapInYieldingChunks } from "./channelSnapshot"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/snapshotYield.test.ts // // THE WALK YIELDS BETWEEN CHUNKS (release 17 slice D0). A macrotask queued // while the first chunk runs — a request's I/O callback, here a setImmediate // probe — runs before the second chunk's first unit starts. Without the yield // every unit below would finish in microtasks before the probe ever ran. test("a macrotask queued during chunk 1 runs before chunk 2 starts", async () => { const events: string[] = []; const items = Array.from({ length: 64 }, (_, i) => i); const out = await mapInYieldingChunks(items, 32, async (i) => { if (i === 0) setImmediate(() => events.push("probe")); events.push(`unit ${i}`); await Promise.resolve(); return i * 2; }); assert.deepEqual(out, items.map((i) => i * 2), "results in order"); const probe = events.indexOf("probe"); assert.ok(probe > events.indexOf("unit 31"), "after the first chunk"); assert.ok(probe < events.indexOf("unit 32"), "before the second chunk"); }); test("one chunk, no yield; an empty list, no call", async () => { let calls = 0; assert.deepEqual( await mapInYieldingChunks([1, 2, 3], 32, async (i) => { calls++; return i; }), [1, 2, 3], ); assert.equal(calls, 3); assert.deepEqual(await mapInYieldingChunks([], 32, async (i: number) => i), []); });