CodeSampleX

Ejemplo

jest-worker 29.7.0: messageParent

Muestra verificada para npm jest-worker 29.7.0: messageParent. El contrato se ejecutó en node 22 · linux debian/x64 · docker y pasó.

sha256:8afc33091a2bda32948715010a28367dfcacbe6c93b78f59a37ad15392606160

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-05

Caso

HOW
Objetivo
verify jest-worker.messageParent in pkg:npm/jest-worker@29.7.0
Paquetes
Símbolos
  • jest-worker.messageParent
Entorno
node 22.23.2
Creado
2026-09-05T21:42:57Z

Contrato

  1. messageParent throws an error when called outside of a worker context
  2. messageParent delegates custom message tuple to parentProcess.send
  3. messageParent dispatches messages from worker threads to parent farm
  4. UNSTABLE_onCustomMessage receives sequential custom messages emitted by messageParent in order
  5. UNSTABLE_onCustomMessage returns an unsubscribe function that unregisters the listener
  6. messageParent preserves structured payload objects across the worker thread boundary

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 jest-worker.messageParent in pkg:npm/jest-worker@29.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/jest-worker@29.7.0
Demonstrate these symbols/APIs:
  - jest-worker.messageParent

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:73e5f5a66f48854ce5f5e58f9948f5aa0c2ee307e9cf152053c81a7e7ac14d7b","contract":["messageParent throws an error when called outside of a worker context","messageParent delegates custom message tuple to parentProcess.send","messageParent dispatches messages from worker threads to parent farm","UNSTABLE_onCustomMessage receives sequential custom messages emitted by messageParent in order","UNSTABLE_onCustomMessage returns an unsubscribe function that unregisters the listener","messageParent preserves structured payload objects across the worker thread boundary"],"goal":"verify jest-worker.messageParent in pkg:npm/jest-worker@29.7.0","kind":"HOW","packages":["pkg:npm/jest-worker@29.7.0"],"schemaVersion":1,"symbols":["jest-worker.messageParent"]},"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/jest-worker@29.7.0"],"schemaVersion":1,"subject":"pkg:npm/jest-worker@29.7.0","symbols":["jest-worker.messageParent"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-jest-worker-messageparent",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-jest-worker-messageparent",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "jest-worker": "29.7.0"
      }
    },
    "node_modules/@jest/schemas": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-29.6.3.tgz",
      "integrity": "sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==",
      "license": "MIT",
      "dependencies": {
        "@sinclair/typebox": "^0.27.8"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/@jest/types": {
      "version": "29.6.3",
      "resolved": "https://registry.npmjs.org/@jest/types/-/types-29.6.3.tgz",
      "integrity": "sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==",
      "license": "MIT",
      "dependencies": {
        "@jest/schemas": "^29.6.3",
        "@types/istanbul-lib-coverage": "^2.0.0",
        "@types/istanbul-reports": "^3.0.0",
        "@types/node": "*",
        "@types/yargs": "^17.0.8",
        "chalk": "^4.0.0"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/@sinclair/typebox": {
      "version": "0.27.12",
      "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.12.tgz",
      "integrity": "sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==",
      "license": "MIT"
    },
    "node_modules/@types/istanbul-lib-coverage": {
      "version": "2.0.6",
      "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz",
      "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==",
      "license": "MIT"
    },
    "node_modules/@types/istanbul-lib-report": {
      "version": "3.0.3",
      "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz",
      "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==",
      "license": "MIT",
      "dependencies": {
        "@types/istanbul-lib-coverage": "*"
      }
    },
    "node_modules/@types/istanbul-reports": {
      "version": "3.0.4",
      "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz",
      "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==",
      "license": "MIT",
      "dependencies": {
        "@types/istanbul-lib-report": "*"
      }
    },
    "node_modules/@types/node": {
      "version": "26.4.1",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.1.tgz",
      "integrity": "sha512-k97ENvZWtvA6yqz5/FS6a7duDgOPEeOQOc2iKS/nY6mX6qJUKtLnWzQS+Xj6tXweyj6ZcTAK2Qecetnvi9nCLA==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/@types/yargs": {
      "version": "17.0.35",
      "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz",
      "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==",
      "license": "MIT",
      "dependencies": {
        "@types/yargs-parser": "*"
      }
    },
    "node_modules/@types/yargs-parser": {
      "version": "21.0.3",
      "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
      "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
      "license": "MIT"
    },
    "node_modules/ansi-styles": {
      "version": "4.3.0",
      "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
      "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
      "license": "MIT",
      "dependencies": {
        "color-convert": "^2.0.1"
      },
      "engines": {
        "node": ">=8"
      },
      "funding": {
        "url": "https://github.com/chalk/ansi-styles?sponsor=1"
      }
    },
    "node_modules/chalk": {
      "version": "4.1.2",
      "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
      "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==",
      "license": "MIT",
      "dependencies": {
        "ansi-styles": "^4.1.0",
        "supports-color": "^7.1.0"
      },
      "engines": {
        "node": ">=10"
      },
      "funding": {
        "url": "https://github.com/chalk/chalk?sponsor=1"
      }
    },
    "node_modules/chalk/node_modules/supports-color": {
      "version": "7.2.0",
      "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
      "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
      "license": "MIT",
      "dependencies": {
        "has-flag": "^4.0.0"
      },
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/ci-info": {
      "version": "3.9.0",
      "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz",
      "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==",
      "funding": [
        {
          "type": "github",
          "url": "https://github.com/sponsors/sibiraj-s"
        }
      ],
      "license": "MIT",
      "engines": {
        "node": ">=8"
      }
    },
    "node_modules/color-convert": {
      "version": "2.0.1",
      "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
      "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
      "license": "MIT",
      "dependencies": {
        "color-name": "~1.1.4"
      },
      "engines": {
        "node": ">=7.0.0"
      }
    },
    "node_modules/color-name": {
      "version": "1.1.4",
      "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
      "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
      "license": "MIT"
    },
    "node_modules/graceful-fs": {
      "version": "4.2.11",
      "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
      "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
      "license": "ISC"
    },
    "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-util": {
      "version": "29.7.0",
      "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-29.7.0.tgz",
      "integrity": "sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==",
      "license": "MIT",
      "dependencies": {
        "@jest/types": "^29.6.3",
        "@types/node": "*",
        "chalk": "^4.0.0",
        "ci-info": "^3.2.0",
        "graceful-fs": "^4.2.9",
        "picomatch": "^2.2.3"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.0"
      }
    },
    "node_modules/jest-worker": {
      "version": "29.7.0",
      "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-29.7.0.tgz",
      "integrity": "sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*",
        "jest-util": "^29.7.0",
        "merge-stream": "^2.0.0",
        "supports-color": "^8.0.0"
      },
      "engines": {
        "node": "^14.15.0 || ^16.10.0 || >=18.0.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/picomatch": {
      "version": "2.3.2",
      "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
      "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
      "license": "MIT",
      "engines": {
        "node": ">=8.6"
      },
      "funding": {
        "url": "https://github.com/sponsors/jonschlinkert"
      }
    },
    "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"
    }
  }
}
package.json
{
  "name": "sample-jest-worker-messageparent",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "jest-worker": "29.7.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jest-worker.messageParent in pkg:npm/jest-worker@29.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/jest-worker@29.7.0"
  ],
  "symbols": [
    "jest-worker.messageParent"
  ]
}
src/index.mjs
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { Worker, messageParent } from 'jest-worker';

export { Worker, messageParent };

const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const DEFAULT_WORKER_TASK_PATH = path.join(__dirname, 'workerTask.cjs');

/**
 * Creates a configured Worker farm for messageParent tasks.
 * @param {import('jest-worker').WorkerFarmOptions} [options]
 * @returns {Worker}
 */
export function createWorker(options = {}) {
  return new Worker(DEFAULT_WORKER_TASK_PATH, {
    numWorkers: 2,
    enableWorkerThreads: true,
    exposedMethods: [
      'runTaskWithProgress',
      'sendPayload',
      'processItems',
    ],
    ...options,
  });
}
src/workerTask.cjs
'use strict';

const { messageParent } = require('jest-worker');

/**
 * Worker task that emits progress updates to the parent process via messageParent.
 * @param {number} steps
 * @returns {{ completed: boolean, totalSteps: number }}
 */
function runTaskWithProgress(steps) {
  for (let i = 1; i <= steps; i++) {
    messageParent({ step: i, total: steps });
  }
  return { completed: true, totalSteps: steps };
}

/**
 * Sends an arbitrary payload to the parent process via messageParent.
 * @param {unknown} payload
 * @returns {boolean}
 */
function sendPayload(payload) {
  messageParent(payload);
  return true;
}

/**
 * Iterates through items and emits an event for each via messageParent.
 * @param {Array<unknown>} items
 * @returns {number}
 */
function processItems(items) {
  for (const item of items) {
    messageParent({ type: 'item_processed', item });
  }
  return items.length;
}

module.exports = {
  runTaskWithProgress,
  sendPayload,
  processItems,
};
test/contract.mjs
import assert from 'node:assert/strict';
import { Worker, messageParent, createWorker } from '../src/index.mjs';

// 1. messageParent throws an error when called outside of a worker context
{
  assert.throws(
    () => {
      messageParent({ type: 'test' });
    },
    {
      name: 'Error',
      message: '"messageParent" can only be used inside a worker',
    }
  );
}

// 2. messageParent delegates custom message tuple to parentProcess.send
{
  const recordedMessages = [];
  const mockParentProcess = {
    send(msg) {
      recordedMessages.push(msg);
    },
  };

  const payload = { event: 'heartbeat', id: 42 };
  messageParent(payload, mockParentProcess);

  assert.strictEqual(recordedMessages.length, 1);
  assert.strictEqual(recordedMessages[0][0], 3);
  assert.deepStrictEqual(recordedMessages[0][1], payload);
}

// 3. messageParent dispatches messages from worker threads to parent farm
{
  const farm = createWorker({ numWorkers: 1 });
  const received = [];

  const promise = farm.sendPayload({ status: 'started', stage: 'initialization' });
  promise.UNSTABLE_onCustomMessage((msg) => {
    received.push(msg);
  });

  const result = await promise;
  assert.strictEqual(result, true);
  assert.strictEqual(received.length, 1);
  assert.deepStrictEqual(received[0], { status: 'started', stage: 'initialization' });

  await farm.end();
}

// 4. UNSTABLE_onCustomMessage receives sequential custom messages emitted by messageParent in order
{
  const farm = createWorker({ numWorkers: 1 });
  const stepEvents = [];

  const promise = farm.runTaskWithProgress(4);
  promise.UNSTABLE_onCustomMessage((msg) => {
    stepEvents.push(msg.step);
  });

  const result = await promise;
  assert.deepStrictEqual(result, { completed: true, totalSteps: 4 });
  assert.deepStrictEqual(stepEvents, [1, 2, 3, 4]);

  await farm.end();
}

// 5. UNSTABLE_onCustomMessage returns an unsubscribe function that unregisters the listener
{
  const farm = createWorker({ numWorkers: 1 });
  const fullLog = [];
  const partialLog = [];

  const promise = farm.runTaskWithProgress(5);

  promise.UNSTABLE_onCustomMessage((msg) => {
    fullLog.push(msg.step);
  });

  const unsubscribe = promise.UNSTABLE_onCustomMessage((msg) => {
    partialLog.push(msg.step);
    if (msg.step === 2) {
      unsubscribe();
    }
  });

  await promise;
  assert.deepStrictEqual(fullLog, [1, 2, 3, 4, 5]);
  assert.deepStrictEqual(partialLog, [1, 2]);

  await farm.end();
}

// 6. messageParent preserves structured payload objects across the worker thread boundary
{
  const farm = createWorker({ numWorkers: 1 });
  const receivedItems = [];

  const inputItems = [
    { id: 1, name: 'alpha', tags: ['a', 'b'], nested: { active: true } },
    { id: 2, name: 'beta', tags: ['c'], nested: { active: false } },
  ];

  const promise = farm.processItems(inputItems);
  promise.UNSTABLE_onCustomMessage((msg) => {
    receivedItems.push(msg);
  });

  const count = await promise;
  assert.strictEqual(count, 2);
  assert.strictEqual(receivedItems.length, 2);
  assert.deepStrictEqual(receivedItems[0], {
    type: 'item_processed',
    item: { id: 1, name: 'alpha', tags: ['a', 'b'], nested: { active: true } },
  });
  assert.deepStrictEqual(receivedItems[1], {
    type: 'item_processed',
    item: { id: 2, name: 'beta', tags: ['c'], nested: { active: false } },
  });

  await farm.end();
}

console.log('All jest-worker.messageParent contract assertions passed.');

Seeder de origen

anónimo