CodeSampleX

Sample

gensync 1.0.0-beta.2: sync and async generator execution with gensync

Verified sample for npm gensync 1.0.0-beta.2: sync and async generator execution with gensync. The contract ran on node 22 · linux alpine/x64 · docker and…

sha256:f2ad7f3559b9e0001cd231479bacb25599439f845acb8a84ffaa10c612744cc2

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
2
Signing keys that built it
1
Declared environment node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 javascript npm 10

Verification-run environments

Environment Contract Stages Run
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-26
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-07

Case

HOW
Goal
sync and async generator execution with gensync
Packages
Symbols
  • gensync
  • gensync.all
  • gensync.race
Environment
node 22.23.2
Created
2026-08-26T06:50:44Z

Contract

  1. gensync wraps sync and async function handlers into a unified dual-mode operation
  2. gensync wraps generator functions allowing unified sync and async execution via .sync and .async
  3. gensync function supports Node.js errback callback pattern via .errback
  4. gensync.all executes multiple gensync operations concurrently in async mode and sequentially in sync mode
  5. gensync.race resolves with the first completed operation across sync and async modes
  6. gensync.race throws GENSYNC_RACE_NONEMPTY when given an empty iterable
  7. gensync throws GENSYNC_OPTIONS_ERROR when invalid handler options are provided
  8. gensync throws GENSYNC_ERRBACK_NO_CALLBACK when .errback is invoked without a callback function
  9. gensync propagates errors thrown inside generator steps in both sync and async modes

Files

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

Download the source artifact (tar.gz)

Source

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: sync and async generator execution with gensync
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/gensync@1.0.0-beta.2
Demonstrate these symbols/APIs:
  - gensync
  - gensync.all
  - gensync.race

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:af1bd453985aafa47f0987993694356e4b604bfd9e911d9522c1f7bd0098dfb8","contract":["gensync wraps sync and async function handlers into a unified dual-mode operation","gensync wraps generator functions allowing unified sync and async execution via .sync and .async","gensync function supports Node.js errback callback pattern via .errback","gensync.all executes multiple gensync operations concurrently in async mode and sequentially in sync mode","gensync.race resolves with the first completed operation across sync and async modes","gensync.race throws GENSYNC_RACE_NONEMPTY when given an empty iterable","gensync throws GENSYNC_OPTIONS_ERROR when invalid handler options are provided","gensync throws GENSYNC_ERRBACK_NO_CALLBACK when .errback is invoked without a callback function","gensync propagates errors thrown inside generator steps in both sync and async modes"],"goal":"sync and async generator execution with gensync","kind":"HOW","packages":["pkg:npm/gensync@1.0.0-beta.2"],"schemaVersion":1,"symbols":["gensync","gensync.all","gensync.race"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","language":"javascript","libc":"glibc","libcVersion":"2.39","moduleSystem":"esm","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/gensync@1.0.0-beta.2"],"schemaVersion":1,"subject":"pkg:npm/gensync@1.0.0-beta.2","symbols":["gensync","gensync.all","gensync.race"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-gensync",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-gensync",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "gensync": "1.0.0-beta.2"
      }
    },
    "node_modules/gensync": {
      "version": "1.0.0-beta.2",
      "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
      "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==",
      "license": "MIT",
      "engines": {
        "node": ">=6.9.0"
      }
    }
  }
}
package.json
{
  "name": "sample-gensync",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "gensync": "1.0.0-beta.2"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "sync and async generator execution with gensync",
  "kind": "HOW",
  "packages": [
    "pkg:npm/gensync@1.0.0-beta.2"
  ],
  "symbols": [
    "gensync",
    "gensync.all",
    "gensync.race"
  ]
}
src/index.mjs
import gensync from 'gensync';

/**
 * Creates a gensync operation from sync and async handlers.
 * @param {object} options Options object containing sync, async, or errback handlers.
 * @returns {Function} Gensync wrapped operation.
 */
export function createOperation(options) {
  return gensync(options);
}

/**
 * Creates a gensync workflow generator function that coordinates operations.
 * @param {GeneratorFunction} genFn Generator function using yield* for gensync operations.
 * @returns {Function} Gensync wrapped workflow.
 */
export function createWorkflow(genFn) {
  return gensync(genFn);
}

/**
 * Runs an array of gensync tasks concurrently (in async mode) or sequentially (in sync mode).
 * @param {Iterable} tasks Iterable of gensync generator calls.
 * @returns {Generator} Gensync all generator.
 */
export function runAll(tasks) {
  return gensync.all(tasks);
}

/**
 * Races an array of gensync tasks to return the first result.
 * @param {Iterable} tasks Iterable of gensync generator calls.
 * @returns {Generator} Gensync race generator.
 */
export function runRace(tasks) {
  return gensync.race(tasks);
}

export { gensync };
export default gensync;
test/contract.mjs
import assert from 'node:assert/strict';
import gensync from 'gensync';
import {
  createOperation,
  createWorkflow,
  runAll,
  runRace,
} from '../src/index.mjs';

// 1. gensync wraps sync and async function handlers into a unified dual-mode operation
{
  const readData = createOperation({
    name: 'readData',
    sync: (key) => `sync:${key}`,
    async: async (key) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return `async:${key}`;
    },
  });

  const syncResult = readData.sync('config');
  assert.equal(syncResult, 'sync:config');

  const asyncResult = await readData.async('config');
  assert.equal(asyncResult, 'async:config');
}

// 2. gensync wraps generator functions allowing unified sync and async execution via .sync and .async
{
  const fetchPart = gensync({
    sync: (part) => `part-${part}`,
    async: async (part) => `part-${part}`,
  });

  const assemble = createWorkflow(function* (id) {
    const part1 = yield* fetchPart(`${id}-A`);
    const part2 = yield* fetchPart(`${id}-B`);
    return `${part1}+${part2}`;
  });

  const syncAssembled = assemble.sync('job1');
  assert.equal(syncAssembled, 'part-job1-A+part-job1-B');

  const asyncAssembled = await assemble.async('job1');
  assert.equal(asyncAssembled, 'part-job1-A+part-job1-B');
}

// 3. gensync function supports Node.js errback callback pattern via .errback
{
  const compute = gensync({
    sync: (val) => val * 10,
    async: async (val) => val * 10,
  });

  const res = await new Promise((resolve, reject) => {
    compute.errback(5, (err, val) => {
      if (err) reject(err);
      else resolve(val);
    });
  });
  assert.equal(res, 50);
}

// 4. gensync.all executes multiple gensync operations concurrently in async mode and sequentially in sync mode
{
  const task = gensync({
    sync: (x) => `res:${x}`,
    async: async (x) => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return `res:${x}`;
    },
  });

  const batch = gensync(function* (items) {
    const results = yield* runAll(items.map((item) => task(item)));
    return results;
  });

  const syncResults = batch.sync(['a', 'b', 'c']);
  assert.deepEqual(syncResults, ['res:a', 'res:b', 'res:c']);

  const asyncResults = await batch.async(['a', 'b', 'c']);
  assert.deepEqual(asyncResults, ['res:a', 'res:b', 'res:c']);

  // Empty iterable handling
  const emptyBatch = gensync(function* () {
    return yield* gensync.all([]);
  });
  assert.deepEqual(emptyBatch.sync(), []);
  assert.deepEqual(await emptyBatch.async(), []);
}

// 5. gensync.race resolves with the first completed operation across sync and async modes
{
  const fastTask = gensync({
    sync: () => 'fast-sync',
    async: async () => {
      await new Promise((resolve) => setTimeout(resolve, 5));
      return 'fast-async';
    },
  });

  const slowTask = gensync({
    sync: () => 'slow-sync',
    async: async () => {
      await new Promise((resolve) => setTimeout(resolve, 50));
      return 'slow-async';
    },
  });

  const raceWorkflow = gensync(function* () {
    return yield* runRace([fastTask(), slowTask()]);
  });

  const syncRace = raceWorkflow.sync();
  assert.equal(syncRace, 'fast-sync');

  const asyncRace = await raceWorkflow.async();
  assert.equal(asyncRace, 'fast-async');
}

// 6. gensync.race throws GENSYNC_RACE_NONEMPTY when given an empty iterable
{
  const emptyRaceSync = gensync(function* () {
    return yield* gensync.race([]);
  });

  assert.throws(
    () => emptyRaceSync.sync(),
    (err) => err.code === 'GENSYNC_RACE_NONEMPTY'
  );

  await assert.rejects(
    async () => emptyRaceSync.async(),
    (err) => err.code === 'GENSYNC_RACE_NONEMPTY'
  );
}

// 7. gensync throws GENSYNC_OPTIONS_ERROR when invalid handler options are provided
{
  assert.throws(
    () => gensync({ sync: 'not-a-function' }),
    (err) => err.code === 'GENSYNC_OPTIONS_ERROR'
  );

  assert.throws(
    () => gensync({ sync: () => {}, async: () => {}, errback: () => {} }),
    (err) => err.code === 'GENSYNC_OPTIONS_ERROR'
  );
}

// 8. gensync throws GENSYNC_ERRBACK_NO_CALLBACK when .errback is invoked without a callback function
{
  const fn = gensync({
    sync: () => 1,
    async: async () => 1,
  });

  assert.throws(
    () => fn.errback(123),
    (err) => err.code === 'GENSYNC_ERRBACK_NO_CALLBACK'
  );
}

// 9. gensync propagates errors thrown inside generator steps in both sync and async modes
{
  const failingOp = gensync({
    sync: () => {
      throw new Error('sync failure');
    },
    async: async () => {
      throw new Error('async failure');
    },
  });

  const failWorkflow = gensync(function* () {
    yield* failingOp();
  });

  assert.throws(() => failWorkflow.sync(), /sync failure/);
  await assert.rejects(async () => failWorkflow.async(), /async failure/);
}

console.log('Contract tests passed successfully.');

Origin Seeder

anonymous