CodeSampleX

Пример

readable-stream 2.3.8: Duplex

Проверенный пример — npm readable-stream 2.3.8: Duplex. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден: Duplex stream reads queued data…

sha256:2cf20b485662a68370ce014d55b36513782f7ff2d9a372c7514cf66b754ce7ec

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

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

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

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

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

Окружение Контракт Этапы Запуск
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-23

Кейс

HOW
Цель
verify readable-stream.Duplex in pkg:npm/readable-stream@2.3.8
Пакеты
Символы
  • readable-stream.Duplex
Окружение
node 22.23.2
Создан
2026-08-23T13:49:28Z

Контракт

  1. Duplex stream reads queued data chunks and emits data events until end
  2. Duplex stream writes data chunks and notifies completion via write callback
  3. Duplex bidirectional data flow operates independently on read and write sides

Файлы

  • PROMPT.md
  • csx.json
  • index.js
  • package-lock.json
  • package.json
  • spec.json
  • test/contract.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 readable-stream.Duplex in pkg:npm/readable-stream@2.3.8
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/readable-stream@2.3.8
Demonstrate these symbols/APIs:
  - readable-stream.Duplex

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:f9ab7d69d1ac20e966dbae9a57c201989e07104e608dce6be4bd4ac32016b1bc","contract":["Duplex stream reads queued data chunks and emits data events until end","Duplex stream writes data chunks and notifies completion via write callback","Duplex bidirectional data flow operates independently on read and write sides"],"goal":"verify readable-stream.Duplex in pkg:npm/readable-stream@2.3.8","kind":"HOW","packages":["pkg:npm/readable-stream@2.3.8"],"schemaVersion":1,"symbols":["readable-stream.Duplex"]},"contractCommand":["node","test/contract.js"],"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/readable-stream@2.3.8"],"schemaVersion":1,"subject":"pkg:npm/readable-stream@2.3.8","symbols":["readable-stream.Duplex"],"verifierAdapter":"node-typescript@1"}
index.js
const { Duplex } = require('readable-stream');

/**
 * Creates a Duplex stream that reads from an in-memory array and records written chunks.
 *
 * @param {Array<string|Buffer>} readItems
 * @param {Array<string|Buffer>} writtenItems
 * @returns {Duplex}
 */
function createDuplexStream(readItems = [], writtenItems = []) {
  let index = 0;
  return new Duplex({
    read() {
      if (index < readItems.length) {
        this.push(readItems[index++]);
      } else {
        this.push(null);
      }
    },
    write(chunk, encoding, callback) {
      writtenItems.push(chunk.toString());
      callback();
    },
  });
}

module.exports = {
  Duplex,
  createDuplexStream,
};
package-lock.json
{
  "name": "sample-readable-stream-duplex",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-readable-stream-duplex",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "readable-stream": "2.3.8"
      }
    },
    "node_modules/core-util-is": {
      "version": "1.0.3",
      "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
      "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
      "license": "MIT"
    },
    "node_modules/inherits": {
      "version": "2.0.4",
      "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
      "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
      "license": "ISC"
    },
    "node_modules/isarray": {
      "version": "1.0.0",
      "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
      "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
      "license": "MIT"
    },
    "node_modules/process-nextick-args": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
      "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
      "license": "MIT"
    },
    "node_modules/readable-stream": {
      "version": "2.3.8",
      "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
      "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
      "license": "MIT",
      "dependencies": {
        "core-util-is": "~1.0.0",
        "inherits": "~2.0.3",
        "isarray": "~1.0.0",
        "process-nextick-args": "~2.0.0",
        "safe-buffer": "~5.1.1",
        "string_decoder": "~1.1.1",
        "util-deprecate": "~1.0.1"
      }
    },
    "node_modules/safe-buffer": {
      "version": "5.1.2",
      "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
      "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
      "license": "MIT"
    },
    "node_modules/string_decoder": {
      "version": "1.1.1",
      "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
      "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
      "license": "MIT",
      "dependencies": {
        "safe-buffer": "~5.1.0"
      }
    },
    "node_modules/util-deprecate": {
      "version": "1.0.2",
      "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
      "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
      "license": "MIT"
    }
  }
}
package.json
{
  "name": "sample-readable-stream-duplex",
  "version": "1.0.0",
  "description": "Verify readable-stream Duplex stream implementation and bidirectional data flow",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "readable-stream": "2.3.8"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify readable-stream.Duplex in pkg:npm/readable-stream@2.3.8",
  "kind": "HOW",
  "packages": [
    "pkg:npm/readable-stream@2.3.8"
  ],
  "symbols": [
    "readable-stream.Duplex"
  ]
}
test/contract.js
const assert = require('node:assert');
const { Duplex, createDuplexStream } = require('../index.js');

async function main() {
  // 1. Duplex stream reads queued data chunks and emits data events until end
  {
    const writtenSink = [];
    const duplex = createDuplexStream(['hello', ' ', 'duplex'], writtenSink);
    const readChunks = [];

    duplex.on('data', (chunk) => {
      readChunks.push(chunk.toString());
    });

    await new Promise((resolve) => duplex.on('end', resolve));
    assert.strictEqual(readChunks.join(''), 'hello duplex');
  }

  // 2. Duplex stream writes data chunks and notifies completion via write callback
  {
    const writtenSink = [];
    const duplex = createDuplexStream([], writtenSink);

    await new Promise((resolve, reject) => {
      duplex.write('first-write', (err) => {
        if (err) return reject(err);
        duplex.write('second-write', (err2) => {
          if (err2) return reject(err2);
          duplex.end(resolve);
        });
      });
    });

    assert.deepStrictEqual(writtenSink, ['first-write', 'second-write']);
  }

  // 3. Duplex bidirectional data flow operates independently on read and write sides
  {
    const writtenSink = [];
    const duplex = createDuplexStream(['output-1', 'output-2'], writtenSink);
    const readChunks = [];

    duplex.on('data', (chunk) => {
      readChunks.push(chunk.toString());
    });

    duplex.write('input-a');
    duplex.write('input-b');
    duplex.end();

    await new Promise((resolve) => duplex.on('end', resolve));

    assert.strictEqual(readChunks.join(''), 'output-1output-2');
    assert.deepStrictEqual(writtenSink, ['input-a', 'input-b']);
  }

  console.log('Contract test passed successfully.');
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

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

аноним