CodeSampleX

샘플

reusify 1.1.0: reusify

검증된 샘플 — npm reusify 1.1.0: reusify. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: reusify creates an object pool from a constructor function…

sha256:29e25a865dc25bbf8c4cc55c2298e6611b8758261bec3504673eba204ceed995

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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-01

케이스

HOW
목표
verify reusify in pkg:npm/reusify@1.1.0
패키지
심벌
  • reusify
환경
node 22.23.2
생성일
2026-09-01T12:20:53Z

컨트랙트

  1. reusify creates an object pool from a constructor function returning get and release methods
  2. pool.get returns an instance of the constructor with its next property reset to null
  3. pool.release enqueues an instance to the pool for reuse in subsequent get calls
  4. pool recycles released instances preserving object identity and maintaining FIFO reuse order
  5. processWithPool processes batches of tasks reusing context instances across iterations

파일

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

소스 아티팩트 내려받기 (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 reusify in pkg:npm/reusify@1.1.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/reusify@1.1.0
Demonstrate these symbols/APIs:
  - reusify
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:1daab22fdf74024bf7cf00cb5a85bea0e0248aec1ac3fe33723e648094a389dc","constraints":{"executionContext":"node"},"contract":["reusify creates an object pool from a constructor function returning get and release methods","pool.get returns an instance of the constructor with its next property reset to null","pool.release enqueues an instance to the pool for reuse in subsequent get calls","pool recycles released instances preserving object identity and maintaining FIFO reuse order","processWithPool processes batches of tasks reusing context instances across iterations"],"goal":"verify reusify in pkg:npm/reusify@1.1.0","kind":"HOW","packages":["pkg:npm/reusify@1.1.0"],"schemaVersion":1,"symbols":["reusify"]},"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/reusify@1.1.0"],"schemaVersion":1,"subject":"pkg:npm/reusify@1.1.0","symbols":["reusify"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-reusify",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-reusify",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "reusify": "1.1.0"
      }
    },
    "node_modules/reusify": {
      "version": "1.1.0",
      "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz",
      "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==",
      "license": "MIT",
      "engines": {
        "iojs": ">=1.0.0",
        "node": ">=0.10.0"
      }
    }
  }
}
package.json
{
  "name": "sample-reusify",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room code sample for reusify@1.1.0",
  "main": "src/index.js",
  "license": "MIT-0",
  "dependencies": {
    "reusify": "1.1.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify reusify in pkg:npm/reusify@1.1.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/reusify@1.1.0"
  ],
  "symbols": [
    "reusify"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/index.js
'use strict';

const reusify = require('reusify');

/**
 * Creates an object pool for a given constructor using reusify.
 *
 * @template T
 * @param {new () => T} Constructor - The constructor function for pooled objects.
 * @returns {{ get: () => T, release: (obj: T) => void }} The object pool instance.
 */
function createPool(Constructor) {
  return reusify(Constructor);
}

/**
 * Example pooled worker context class.
 */
class TaskContext {
  constructor() {
    this.next = null;
    this.id = 0;
    this.payload = null;
  }

  reset() {
    this.id = 0;
    this.payload = null;
  }
}

/**
 * Runs a batch of operations reusing TaskContext instances.
 *
 * @param {Array<any>} items
 * @param {(ctx: TaskContext) => any} fn
 * @returns {Array<any>}
 */
function processWithPool(items, fn) {
  const pool = reusify(TaskContext);
  const results = [];

  for (let i = 0; i < items.length; i++) {
    const ctx = pool.get();
    ctx.id = i + 1;
    ctx.payload = items[i];
    try {
      results.push(fn(ctx));
    } finally {
      ctx.reset();
      pool.release(ctx);
    }
  }

  return results;
}

module.exports = {
  reusify,
  createPool,
  TaskContext,
  processWithPool
};
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);
const { reusify, createPool, TaskContext, processWithPool } = require('../src/index.js');

async function testAll() {
  // 1. Export verification
  assert.equal(typeof reusify, 'function', 'reusify export must be a function');
  assert.equal(typeof createPool, 'function', 'createPool helper must be a function');
  assert.equal(typeof TaskContext, 'function', 'TaskContext constructor must be a function');
  assert.equal(typeof processWithPool, 'function', 'processWithPool helper must be a function');

  // 2. Pool instantiation and contract shape
  function SimpleItem() {
    this.next = null;
    this.value = 'default';
  }

  const pool = reusify(SimpleItem);
  assert.equal(typeof pool, 'object', 'reusify must return an object');
  assert.equal(typeof pool.get, 'function', 'pool must provide a get method');
  assert.equal(typeof pool.release, 'function', 'pool must provide a release method');

  // 3. Initial allocation
  // First get() returns the initially constructed head instance
  const item1 = pool.get();
  assert.ok(item1 instanceof SimpleItem, 'pool.get must return an instance of Constructor');
  assert.equal(item1.next, null, 'item.next must be null upon retrieval');
  assert.equal(item1.value, 'default', 'initial state must match constructor defaults');

  // 4. Object reuse lifecycle
  item1.value = 'modified-1';
  pool.release(item1);

  // Because reusify pre-allocates the next head when pool is drained,
  // the next get() returns the pre-allocated instance, and the following get() returns the released item1
  const preAllocated = pool.get();
  assert.ok(preAllocated instanceof SimpleItem, 'get returns the queued head instance');
  assert.equal(preAllocated.value, 'default', 'pre-allocated instance has default values');

  const recycledItem1 = pool.get();
  assert.strictEqual(recycledItem1, item1, 'pool.get must return the recycled instance from the queue');
  assert.equal(recycledItem1.next, null, 'item.next must be reset to null when re-acquired');
  assert.equal(recycledItem1.value, 'modified-1', 'reused object preserves instance properties until caller resets');

  // 5. Sustained pool cycling under steady-state usage
  // Draining the pool then recycling multiple items
  const cyclePool = reusify(SimpleItem);
  const obj1 = cyclePool.get();
  obj1.value = 'first';
  const obj2 = cyclePool.get();
  obj2.value = 'second';

  // Release both items back to the pool
  cyclePool.release(obj1);
  cyclePool.release(obj2);

  // Retrieve objects from pool: pre-allocated head, then obj1, then obj2
  const r0 = cyclePool.get();
  const r1 = cyclePool.get();
  const r2 = cyclePool.get();

  assert.strictEqual(r1, obj1, 'first released object is retrieved first in FIFO order');
  assert.strictEqual(r2, obj2, 'second released object is retrieved second in FIFO order');
  assert.notStrictEqual(r0, obj1, 'pre-allocated head is distinct from released objects');
  assert.notStrictEqual(r0, obj2, 'pre-allocated head is distinct from released objects');

  // 6. TaskContext and processWithPool helper verification
  const data = [10, 20, 30, 40, 50];
  const seenContexts = [];
  const processed = processWithPool(data, (ctx) => {
    seenContexts.push(ctx);
    return ctx.id * 100 + ctx.payload;
  });

  assert.deepEqual(processed, [110, 220, 330, 440, 550], 'processWithPool must return mapped results');
  assert.equal(seenContexts.length, 5, 'processWithPool must invoke handler for every element');

  // Verify that instances were reused across loop iterations
  const uniqueContexts = new Set(seenContexts);
  assert.ok(uniqueContexts.size < seenContexts.length, 'processWithPool must reuse context instances across items');

  console.log('All reusify contract tests passed successfully.');
}

testAll().catch((err) => {
  console.error('Contract test failure:', err);
  process.exit(1);
});

오리진 시더

익명