示例
jest-worker 27.5.1: execute exported worker functions in parallel with Worker pool and shut down
已验证示例 — npm jest-worker 27.5.1: execute exported worker functions in parallel with Worker pool and shut down. contract 在 node 22 · linux alpine/x64 · docker…
sha256:98f59ba510be78133f81990262a4b0c1bde5959243ec82052e7499080d666f78
本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。
提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。
MIT-0
执行证据
声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。
- 证据依据
- 签名契约通过
- 验证回执
- 1
- 构建过它的签名密钥
- 1
声明的环境
linux 24 · ubuntu · glibc 2.39 x64 npm
验证运行环境
| 环境 | 契约 | 阶段 | 运行日期 |
|---|---|---|---|
| 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-27 |
案例
HOW- 目标
- execute exported worker functions in parallel with Worker pool and shut down
- 符号
-
- Worker
- Worker.end
- 创建时间
- 2026-08-27T23:15:51Z
契约
- Worker initializes worker pool with worker_threads and executes synchronous exported functions
- Worker executes asynchronous exported functions and resolves returned Promises
- Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end
- Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises
- Worker executes setup lifecycle hook with setupArgs during worker initialization
- Worker supports forked child process mode and terminates with Worker.end
文件
- PROMPT.md
- csx.json
- package-lock.json
- package.json
- spec.json
- src/index.mjs
- src/worker.cjs
- test/contract.mjs
源代码
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: execute exported worker functions in parallel with Worker pool and shut down
Kind: HOW
Use EXACTLY these public packages and versions:
- pkg:npm/jest-worker@27.5.1
Demonstrate these symbols/APIs:
- Worker
- Worker.end
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.
{"case":{"caseId":"case:sha256:8c8c9c25377cae62468ee59eda236d0d23b6efd867403de2a5644a68498f15eb","contract":["Worker initializes worker pool with worker_threads and executes synchronous exported functions","Worker executes asynchronous exported functions and resolves returned Promises","Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end","Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises","Worker executes setup lifecycle hook with setupArgs during worker initialization","Worker supports forked child process mode and terminates with Worker.end"],"goal":"execute exported worker functions in parallel with Worker pool and shut down","kind":"HOW","packages":["pkg:npm/jest-worker@27.5.1"],"schemaVersion":1,"symbols":["Worker","Worker.end"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/jest-worker@27.5.1"],"schemaVersion":1,"subject":"pkg:npm/jest-worker@27.5.1","symbols":["Worker","Worker.end"],"verifierAdapter":"node-typescript@1"}
{
"name": "sample-jest-worker",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sample-jest-worker",
"version": "1.0.0",
"license": "MIT-0",
"dependencies": {
"jest-worker": "27.5.1"
}
},
"node_modules/@types/node": {
"version": "26.4.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz",
"integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==",
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/jest-worker": {
"version": "27.5.1",
"resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-27.5.1.tgz",
"integrity": "sha512-7vuh85V5cdDofPyxn58nrPjBktZo0u9x1g8WtjQol+jZDaE+fhN+cIvTj11GndBnMnyfrUOG1sZQxCdjKh+DKg==",
"license": "MIT",
"dependencies": {
"@types/node": "*",
"merge-stream": "^2.0.0",
"supports-color": "^8.0.0"
},
"engines": {
"node": ">= 10.13.0"
}
},
"node_modules/merge-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz",
"integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==",
"license": "MIT"
},
"node_modules/supports-color": {
"version": "8.1.1",
"resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz",
"integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==",
"license": "MIT",
"dependencies": {
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"license": "MIT"
}
}
}
{
"name": "sample-jest-worker",
"version": "1.0.0",
"type": "module",
"private": true,
"license": "MIT-0",
"scripts": {
"test": "node test/contract.mjs"
},
"dependencies": {
"jest-worker": "27.5.1"
}
}
{
"schemaVersion": 1,
"goal": "execute exported worker functions in parallel with Worker pool and shut down",
"kind": "HOW",
"packages": [
"pkg:npm/jest-worker@27.5.1"
],
"symbols": [
"Worker",
"Worker.end"
]
}
import { Worker } from 'jest-worker';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const __dirname = dirname(fileURLToPath(import.meta.url));
export const DEFAULT_WORKER_PATH = join(__dirname, 'worker.cjs');
/**
* Creates a jest-worker pool pointing to the specified worker file.
* @param {string} [workerPath] Absolute path to worker module.
* @param {object} [options] Worker options (numWorkers, enableWorkerThreads, etc.).
* @returns {Worker} Worker instance.
*/
export function createWorkerPool(workerPath = DEFAULT_WORKER_PATH, options = {}) {
return new Worker(workerPath, {
numWorkers: options.numWorkers ?? 2,
enableWorkerThreads: options.enableWorkerThreads ?? true,
...options
});
}
/**
* Runs a batch of tasks concurrently across worker threads and terminates the pool.
* @param {Array<{ id: number, payload: number }>} items Items to process.
* @param {object} [options] Worker options.
* @returns {Promise<Array<any>>} Results of batch execution.
*/
export async function runBatchAndClose(items, options = {}) {
const worker = createWorkerPool(DEFAULT_WORKER_PATH, options);
try {
const promises = items.map(item => worker.processTask(item.id, item.payload));
return await Promise.all(promises);
} finally {
await worker.end();
}
}
export { Worker };
export default Worker;
/**
* Worker module providing compute tasks for jest-worker pool.
*/
let initializedState = null;
function setup(initVal) {
initializedState = initVal || 'ready';
}
function teardown() {
initializedState = null;
}
function getStatus() {
return initializedState;
}
function computeSum(a, b) {
return a + b;
}
async function transformText(text) {
return text.toUpperCase();
}
function processTask(id, payload) {
return {
taskId: id,
processed: true,
result: payload * 2
};
}
function failingTask(msg) {
throw new Error(msg || 'task failed');
}
module.exports = {
setup,
teardown,
getStatus,
computeSum,
transformText,
processTask,
failingTask
};
import assert from 'node:assert/strict';
import { Worker } from 'jest-worker';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import { createWorkerPool, runBatchAndClose, DEFAULT_WORKER_PATH } from '../src/index.mjs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const workerPath = join(__dirname, '../src/worker.cjs');
// 1. Worker initializes worker pool with worker_threads and executes synchronous exported functions
{
const worker = new Worker(workerPath, {
numWorkers: 2,
enableWorkerThreads: true
});
const sum = await worker.computeSum(15, 27);
assert.equal(sum, 42);
const endResult = await worker.end();
assert.equal(endResult.forceExited, false);
}
// 2. Worker executes asynchronous exported functions and resolves returned Promises
{
const worker = new Worker(workerPath, {
numWorkers: 2,
enableWorkerThreads: true
});
const res = await worker.transformText('hello jest worker');
assert.equal(res, 'HELLO JEST WORKER');
const endResult = await worker.end();
assert.equal(endResult.forceExited, false);
}
// 3. Worker executes batch tasks in parallel across worker instances and shuts down cleanly with Worker.end
{
const items = [
{ id: 1, payload: 10 },
{ id: 2, payload: 20 },
{ id: 3, payload: 30 },
{ id: 4, payload: 40 }
];
const results = await runBatchAndClose(items, { numWorkers: 2 });
assert.deepEqual(results, [
{ taskId: 1, processed: true, result: 20 },
{ taskId: 2, processed: true, result: 40 },
{ taskId: 3, processed: true, result: 60 },
{ taskId: 4, processed: true, result: 80 }
]);
}
// 4. Worker propagates synchronous exceptions thrown within worker tasks as rejected Promises
{
const worker = new Worker(workerPath, {
numWorkers: 1,
enableWorkerThreads: true
});
let caughtError = null;
try {
await worker.failingTask('invalid payload input');
} catch (err) {
caughtError = err;
}
assert.ok(caughtError instanceof Error);
assert.match(caughtError.message, /invalid payload input/);
await worker.end();
}
// 5. Worker executes setup lifecycle hook with setupArgs during worker initialization
{
const worker = new Worker(workerPath, {
numWorkers: 1,
enableWorkerThreads: true,
setupArgs: ['custom-init-state']
});
const status = await worker.getStatus();
assert.equal(status, 'custom-init-state');
await worker.end();
}
// 6. Worker supports forked child process mode and terminates with Worker.end
{
const worker = new Worker(workerPath, {
numWorkers: 2,
enableWorkerThreads: false
});
const res = await worker.computeSum(100, 200);
assert.equal(res, 300);
const endResult = await worker.end();
assert.equal(endResult.forceExited, false);
}
console.log('Contract tests passed successfully.');
原始种子者
匿名