CodeSampleX

Пример

builder-util-runtime 9.7.0: CancellationToken

Проверенный пример — npm builder-util-runtime 9.7.0: CancellationToken. Контракт выполнен на node 22 · linux alpine/x64 · docker и пройден.

sha256:e5a0630e171648c7c50459540cc2c8b6ee351e9017188e311c86406df4bec6e6

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-28

Кейс

HOW
Цель
verify builder-util-runtime.CancellationToken in pkg:npm/builder-util-runtime@9.7.0
Пакеты
Символы
  • builder-util-runtime.CancellationToken
Создан
2026-08-28T05:02:26Z

Контракт

  1. assert CancellationToken starts uncancelled and emits cancel on cancel()
  2. assert child CancellationToken cancels when parent token cancels
  3. assert createPromise resolves successfully when task completes
  4. assert createPromise rejects with CancellationError and executes cleanup when cancelled
  5. assert createPromise on already-cancelled token immediately rejects with CancellationError
  6. assert dispose cleans up listeners and decouples from parent

Файлы

  • PROMPT.md
  • csx.json
  • index.mjs
  • package-lock.json
  • package.json
  • spec.json
  • 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 builder-util-runtime.CancellationToken in pkg:npm/builder-util-runtime@9.7.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/builder-util-runtime@9.7.0
Demonstrate these symbols/APIs:
  - builder-util-runtime.CancellationToken

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:eaceb4d2ce97f1354e489eb813f60a57fbc1a76ca738a2f810134d1a239264e6","contract":["assert CancellationToken starts uncancelled and emits cancel on cancel()","assert child CancellationToken cancels when parent token cancels","assert createPromise resolves successfully when task completes","assert createPromise rejects with CancellationError and executes cleanup when cancelled","assert createPromise on already-cancelled token immediately rejects with CancellationError","assert dispose cleans up listeners and decouples from parent"],"goal":"verify builder-util-runtime.CancellationToken in pkg:npm/builder-util-runtime@9.7.0","kind":"HOW","packages":["pkg:npm/builder-util-runtime@9.7.0"],"schemaVersion":1,"symbols":["builder-util-runtime.CancellationToken"]},"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/builder-util-runtime@9.7.0"],"schemaVersion":1,"subject":"pkg:npm/builder-util-runtime@9.7.0","symbols":["builder-util-runtime.CancellationToken"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { CancellationToken, CancellationError } from 'builder-util-runtime';

/**
 * Creates a new CancellationToken, optionally chained to a parent token.
 * @param {CancellationToken} [parent]
 * @returns {CancellationToken}
 */
export function createCancellationToken(parent) {
  return new CancellationToken(parent);
}

/**
 * Executes an async task with cancellation support.
 * @template T
 * @param {CancellationToken} token
 * @param {(resolve: (value: T) => void, reject: (reason?: any) => void, onCancel: (callback: () => void) => void) => void} callback
 * @returns {Promise<T>}
 */
export function executeWithCancellation(token, callback) {
  return token.createPromise(callback);
}

export { CancellationToken, CancellationError };
package-lock.json
{
  "name": "builder-util-runtime-cancellation-token-sample",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "builder-util-runtime-cancellation-token-sample",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "builder-util-runtime": "9.7.0"
      }
    },
    "node_modules/builder-util-runtime": {
      "version": "9.7.0",
      "resolved": "https://registry.npmjs.org/builder-util-runtime/-/builder-util-runtime-9.7.0.tgz",
      "integrity": "sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==",
      "license": "MIT",
      "dependencies": {
        "debug": "^4.3.4",
        "sax": "^1.2.4"
      },
      "engines": {
        "node": ">=12.0.0"
      }
    },
    "node_modules/debug": {
      "version": "4.4.3",
      "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
      "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
      "license": "MIT",
      "dependencies": {
        "ms": "^2.1.3"
      },
      "engines": {
        "node": ">=6.0"
      },
      "peerDependenciesMeta": {
        "supports-color": {
          "optional": true
        }
      }
    },
    "node_modules/ms": {
      "version": "2.1.3",
      "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
      "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
      "license": "MIT"
    },
    "node_modules/sax": {
      "version": "1.6.1",
      "resolved": "https://registry.npmjs.org/sax/-/sax-1.6.1.tgz",
      "integrity": "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==",
      "license": "BlueOak-1.0.0",
      "engines": {
        "node": ">=11.0.0"
      }
    }
  }
}
package.json
{
  "name": "builder-util-runtime-cancellation-token-sample",
  "version": "1.0.0",
  "description": "Demonstrate builder-util-runtime.CancellationToken usage and behavior",
  "main": "index.mjs",
  "type": "module",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "builder-util-runtime": "9.7.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify builder-util-runtime.CancellationToken in pkg:npm/builder-util-runtime@9.7.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/builder-util-runtime@9.7.0"
  ],
  "symbols": [
    "builder-util-runtime.CancellationToken"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import { EventEmitter } from 'node:events';
import { CancellationToken, CancellationError } from 'builder-util-runtime';
import { createCancellationToken, executeWithCancellation } from '../index.mjs';

// 1. assert CancellationToken starts uncancelled and emits cancel on cancel()
{
  const token = createCancellationToken();
  assert.ok(token instanceof EventEmitter, 'token must inherit from EventEmitter');
  assert.equal(token.cancelled, false, 'initial cancelled state must be false');

  let eventEmitted = false;
  token.on('cancel', () => {
    eventEmitted = true;
  });

  token.cancel();
  assert.equal(token.cancelled, true, 'cancelled state must be true after cancel()');
  assert.equal(eventEmitted, true, 'cancel event must be emitted');
}

// 2. assert child CancellationToken cancels when parent token cancels
{
  const parent = createCancellationToken();
  const child = createCancellationToken(parent);

  assert.equal(parent.cancelled, false);
  assert.equal(child.cancelled, false);

  parent.cancel();
  assert.equal(parent.cancelled, true);
  assert.equal(child.cancelled, true, 'child token must be cancelled when parent is cancelled');
}

// 3. assert createPromise resolves successfully when task completes
{
  const token = createCancellationToken();
  const result = await executeWithCancellation(token, (resolve) => {
    setTimeout(() => resolve('success-payload'), 10);
  });
  assert.equal(result, 'success-payload', 'createPromise must resolve with task value');
}

// 4. assert createPromise rejects with CancellationError and executes cleanup when cancelled
{
  const token = createCancellationToken();
  let cleanupInvoked = false;

  const promise = executeWithCancellation(token, (resolve, _reject, onCancel) => {
    const timer = setTimeout(() => resolve('done'), 1000);
    onCancel(() => {
      clearTimeout(timer);
      cleanupInvoked = true;
    });
  });

  assert.equal(token.cancelled, false);
  token.cancel();
  assert.equal(token.cancelled, true);

  await assert.rejects(
    promise,
    (err) => {
      assert.ok(err instanceof CancellationError, 'rejection error must be CancellationError');
      assert.equal(err.message, 'cancelled', 'error message must be cancelled');
      return true;
    },
    'createPromise must reject with CancellationError when cancelled'
  );
  assert.equal(cleanupInvoked, true, 'onCancel callback must be invoked');
}

// 5. assert createPromise on already-cancelled token immediately rejects with CancellationError
{
  const token = createCancellationToken();
  token.cancel();

  let taskStarted = false;
  const promise = executeWithCancellation(token, (resolve) => {
    taskStarted = true;
    resolve('done');
  });

  await assert.rejects(
    promise,
    CancellationError,
    'createPromise on cancelled token must immediately reject'
  );
  assert.equal(taskStarted, false, 'task callback must not execute when already cancelled');
}

// 6. assert dispose cleans up listeners and decouples from parent
{
  const parent = createCancellationToken();
  const child = createCancellationToken(parent);

  child.dispose();
  assert.equal(child.listenerCount('cancel'), 0, 'dispose must remove all listeners');

  parent.cancel();
  assert.equal(parent.cancelled, true);
  assert.equal(child.cancelled, false, 'disposed child must not be cancelled by parent');
}

console.log('All CancellationToken contract tests passed.');

Исходный сидер

аноним