CodeSampleX

示例

reusify 1.1.0: reusify

已验证示例 — npm reusify 1.1.0: reusify. contract 在 node 22 · linux debian/x64 · docker 上运行并通过: reusify creates an object pool from a constructor function…

sha256:29e25a865dc25bbf8c4cc55c2298e6611b8758261bec3504673eba204ceed995

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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);
});

原始种子者

匿名