CodeSampleX

Sample

thread-stream 3.2.0: stream data to worker thread using ThreadStream

Verified sample for npm thread-stream 3.2.0: stream data to worker thread using ThreadStream. The contract ran on node 22 · linux alpine/x64 · docker and…

sha256:a59962af883671973d323b24c2b30bb8cb29e2860c3028b5f668d696c136401b

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Verification-run environments

Environment Contract Stages Run
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-08-28

Case

HOW
Goal
stream data to worker thread using ThreadStream
Packages
Symbols
  • ThreadStream
  • ThreadStream.prototype.end
  • ThreadStream.prototype.flushSync
  • ThreadStream.prototype.write
Environment
node 22.23.2
Created
2026-08-28T09:51:47Z

Contract

  1. ThreadStream constructor creates an active stream instance to a worker thread
  2. ThreadStream.prototype.write writes data to the worker stream buffer
  3. ThreadStream.prototype.flushSync synchronously flushes buffered data to the destination
  4. ThreadStream.prototype.end closes the stream and flushes remaining data before exit
  5. ThreadStream supports synchronous streaming mode with sync option enabled
  6. ThreadStream.prototype.write emits an error event when called after end

Files

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • src/worker.mjs
  • test/contract.mjs

Download the source artifact (tar.gz)

Source

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: stream data to worker thread using ThreadStream
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/thread-stream@3.2.0
Demonstrate these symbols/APIs:
  - ThreadStream
  - ThreadStream.prototype.end
  - ThreadStream.prototype.flushSync
  - ThreadStream.prototype.write

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:9aa427b41d9d81984c501753844590bf95f0db1d09be11008ab1bbc97a24b6ac","contract":["ThreadStream constructor creates an active stream instance to a worker thread","ThreadStream.prototype.write writes data to the worker stream buffer","ThreadStream.prototype.flushSync synchronously flushes buffered data to the destination","ThreadStream.prototype.end closes the stream and flushes remaining data before exit","ThreadStream supports synchronous streaming mode with sync option enabled","ThreadStream.prototype.write emits an error event when called after end"],"goal":"stream data to worker thread using ThreadStream","kind":"HOW","packages":["pkg:npm/thread-stream@3.2.0"],"schemaVersion":1,"symbols":["ThreadStream","ThreadStream.prototype.end","ThreadStream.prototype.flushSync","ThreadStream.prototype.write"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/thread-stream@3.2.0"],"schemaVersion":1,"subject":"pkg:npm/thread-stream@3.2.0","symbols":["ThreadStream","ThreadStream.prototype.end","ThreadStream.prototype.flushSync","ThreadStream.prototype.write"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-thread-stream",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-thread-stream",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "thread-stream": "3.2.0"
      }
    },
    "node_modules/real-require": {
      "version": "0.2.0",
      "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz",
      "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==",
      "license": "MIT",
      "engines": {
        "node": ">= 12.13.0"
      }
    },
    "node_modules/thread-stream": {
      "version": "3.2.0",
      "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz",
      "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==",
      "license": "MIT",
      "dependencies": {
        "real-require": "^0.2.0"
      }
    }
  }
}
package.json
{
  "name": "sample-thread-stream",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "thread-stream": "3.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "stream data to worker thread using ThreadStream",
  "kind": "HOW",
  "packages": [
    "pkg:npm/thread-stream@3.2.0"
  ],
  "symbols": [
    "ThreadStream",
    "ThreadStream.prototype.end",
    "ThreadStream.prototype.flushSync",
    "ThreadStream.prototype.write"
  ]
}
src/index.mjs
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import ThreadStream from 'thread-stream';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

/**
 * Creates a ThreadStream configured to stream data to a worker file destination.
 * @param {string} dest Destination file path.
 * @param {object} [options={}] Additional ThreadStream options.
 * @returns {ThreadStream}
 */
export function createWorkerStream(dest, options = {}) {
  const workerFile = path.join(__dirname, 'worker.mjs');
  return new ThreadStream({
    filename: workerFile,
    workerData: { dest },
    sync: false,
    ...options
  });
}

export { ThreadStream };
export default ThreadStream;
src/worker.mjs
import fs from 'node:fs';
import { once } from 'node:events';

/**
 * Worker thread destination entrypoint.
 * @param {object} opts Worker options containing destination file path.
 * @returns {Promise<fs.WriteStream>} Writable stream for worker thread data.
 */
export default async function run(opts) {
  const stream = fs.createWriteStream(opts.dest);
  await once(stream, 'open');
  return stream;
}
test/contract.mjs
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import ThreadStream, { createWorkerStream } from '../src/index.mjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const workerPath = path.join(__dirname, '../src/worker.mjs');
const tmpDir = path.join(os.tmpdir(), `thread-stream-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
fs.mkdirSync(tmpDir, { recursive: true });

try {
  // 1. ThreadStream constructor creates an active stream instance to a worker thread
  {
    const dest = path.join(tmpDir, 'test-constructor.log');
    const stream = new ThreadStream({
      filename: workerPath,
      workerData: { dest }
    });
    assert.ok(stream instanceof ThreadStream);
    assert.strictEqual(typeof stream.write, 'function');
    assert.strictEqual(typeof stream.flushSync, 'function');
    assert.strictEqual(typeof stream.end, 'function');
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
  }

  // 2. ThreadStream.prototype.write writes data to the worker stream buffer
  {
    const dest = path.join(tmpDir, 'test-write.log');
    const stream = createWorkerStream(dest);
    const accepted1 = stream.write('message line 1\n');
    const accepted2 = stream.write('message line 2\n');
    assert.strictEqual(accepted1, true);
    assert.strictEqual(accepted2, true);
    stream.flushSync();
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'message line 1\nmessage line 2\n');
  }

  // 3. ThreadStream.prototype.flushSync synchronously flushes buffered data to the destination
  {
    const dest = path.join(tmpDir, 'test-flush.log');
    const stream = createWorkerStream(dest);
    stream.write('chunk-alpha\n');
    stream.flushSync();
    // After flushSync, the data has reached the worker thread
    stream.write('chunk-beta\n');
    stream.flushSync();
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'chunk-alpha\nchunk-beta\n');
  }

  // 4. ThreadStream.prototype.end closes the stream and flushes remaining data before exit
  {
    const dest = path.join(tmpDir, 'test-end.log');
    const stream = createWorkerStream(dest);
    stream.write('final-line\n');
    stream.end();
    let finishFired = false;
    stream.on('finish', () => {
      finishFired = true;
    });
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    assert.strictEqual(finishFired, true);
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'final-line\n');
  }

  // 5. ThreadStream supports synchronous streaming mode with sync option enabled
  {
    const dest = path.join(tmpDir, 'test-sync-mode.log');
    const stream = new ThreadStream({
      filename: workerPath,
      workerData: { dest },
      sync: true
    });
    const writeResult = stream.write('sync-entry\n');
    assert.strictEqual(writeResult, true);
    stream.flushSync();
    stream.end();
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    const content = fs.readFileSync(dest, 'utf8');
    assert.strictEqual(content, 'sync-entry\n');
  }

  // 6. ThreadStream.prototype.write emits an error event when called after end
  {
    const dest = path.join(tmpDir, 'test-write-after-end.log');
    const stream = createWorkerStream(dest);
    stream.write('before-end\n');
    stream.end();

    let errorReceived = false;
    stream.on('error', (err) => {
      if (err) errorReceived = true;
    });

    stream.write('after-end\n');
    await new Promise(resolve => stream.on('finish', resolve));
    await new Promise(r => setTimeout(r, 50));
    assert.strictEqual(errorReceived, true);
  }
} finally {
  fs.rmSync(tmpDir, { recursive: true, force: true });
}

console.log('Contract tests passed successfully.');

Origin Seeder

anonymous