CodeSampleX

Пример

thread-stream 4.2.0: ThreadStream, ThreadStream.prototype.end, ThreadStream.prototype.flushSync

Проверенный пример — npm thread-stream 4.2.0: ThreadStream, ThreadStream.prototype.end, ThreadStream.prototype.flushSync. Контракт выполнен на node 22 …

sha256:178a6277c75742b8d3166de3780a33fe5928cc75dc6f3a974e5995ea00c88e7a

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Среды запусков проверки

Окружение Контракт Этапы Запуск
node 22 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22@sha256:8a34c4ab3ea2…
2026-09-19

Кейс

HOW
Цель
verify pkg:npm/thread-stream@4.2.0
Пакеты
Символы
  • ThreadStream
  • ThreadStream.prototype.end
  • ThreadStream.prototype.flushSync
  • ThreadStream.prototype.write
Окружение
node 22.23.2
Создан
2026-09-18T14:20:53Z

Контракт

  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

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

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: verify pkg:npm/thread-stream@4.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/thread-stream@4.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:b156cce445fd570f467968202c5990b074e033bbe48d01cb7015aebc37909f8a","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":"verify pkg:npm/thread-stream@4.2.0","kind":"HOW","packages":["pkg:npm/thread-stream@4.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","executionContext":"node","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"cjs","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@4.2.0"],"schemaVersion":1,"subject":"pkg:npm/thread-stream@4.2.0","symbols":["ThreadStream","ThreadStream.prototype.end","ThreadStream.prototype.flushSync","ThreadStream.prototype.write"],"verifierAdapter":"node-typescript@1"}
index.js
const path = require('node:path');
const ThreadStream = require('thread-stream');

/**
 * 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}
 */
function createWorkerStream(dest, options = {}) {
  const workerFile = path.join(__dirname, 'worker.js');
  return new ThreadStream({
    filename: workerFile,
    workerData: { dest },
    sync: false,
    ...options
  });
}

module.exports = {
  createWorkerStream,
  ThreadStream
};
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": "4.2.0"
      }
    },
    "node_modules/real-require": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz",
      "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==",
      "license": "MIT"
    },
    "node_modules/thread-stream": {
      "version": "4.2.0",
      "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
      "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==",
      "license": "MIT",
      "dependencies": {
        "real-require": "^1.0.0"
      },
      "engines": {
        "node": ">=20"
      }
    }
  }
}
package.json
{
  "name": "sample-thread-stream",
  "version": "1.0.0",
  "description": "Clean-room sample verifying pkg:npm/thread-stream@4.2.0 functionality",
  "main": "index.js",
  "license": "MIT-0",
  "dependencies": {
    "thread-stream": "4.2.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/thread-stream@4.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/thread-stream@4.2.0"
  ],
  "symbols": [
    "ThreadStream",
    "ThreadStream.prototype.end",
    "ThreadStream.prototype.flushSync",
    "ThreadStream.prototype.write"
  ]
}
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 pkg from '../index.js';

const { ThreadStream, createWorkerStream } = pkg;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const workerPath = path.join(__dirname, '../worker.js');
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();
    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.');
worker.js
const fs = require('node:fs');
const { once } = require('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.
 */
module.exports = async function run(opts) {
  const stream = fs.createWriteStream(opts.dest);
  await once(stream, 'open');
  return stream;
};

Исходный сидер

аноним