CodeSampleX

サンプル

bare-signals 5.0.0: verify signal handling and listeners

検証済みサンプル — npm bare-signals 5.0.0: verify signal handling and listeners. node 22 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:65b80983c578684bb9d5558979249decc4da8151722537086a1a639afb4c787f

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 node 22.23 linux 24 · ubuntu · glibc 2.39 x64 node 22.23 npm 10

検証実行環境

環境 コントラクト ステージ 実行日
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
ゴール
verify pkg:npm/bare-signals@5.0.0 signal handling and listeners
パッケージ
環境
node 22.23.2
作成日
2026-08-27T12:59:20Z

コントラクト

  1. package manifest exports Signal class and SignalEmitter in TypeScript definitions and requires Bare engine >=1.7.0
  2. Signal constructor accepts string signal names and resolves them to numerical signums via constants map
  3. Signal constructor throws SignalError with code UNKNOWN_SIGNAL when an unrecognised signal string is provided
  4. Signal instances provide start, stop, ref, unref, and close lifecycle methods delegating to the native binding
  5. calling start on a closed Signal instance throws SignalError with code SIGNAL_CLOSED
  6. Signal.Emitter attaches Signal listeners dynamically on newListener and tears them down on removeListener
  7. native C binding registers bare_signals__on_signal and bare_signals__on_close callbacks with uv_signal_t

ファイル

  • PROMPT.md
  • csx.json
  • package-lock.json
  • package.json
  • spec.json
  • src/index.mjs
  • 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 pkg:npm/bare-signals@5.0.0 signal handling and listeners
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/bare-signals@5.0.0

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:daa154b52d08983aeb77c83c2402c85f5de38205b24222225809a24a85b915b4","contract":["package manifest exports Signal class and SignalEmitter in TypeScript definitions and requires Bare engine \u003e=1.7.0","Signal constructor accepts string signal names and resolves them to numerical signums via constants map","Signal constructor throws SignalError with code UNKNOWN_SIGNAL when an unrecognised signal string is provided","Signal instances provide start, stop, ref, unref, and close lifecycle methods delegating to the native binding","calling start on a closed Signal instance throws SignalError with code SIGNAL_CLOSED","Signal.Emitter attaches Signal listeners dynamically on newListener and tears them down on removeListener","native C binding registers bare_signals__on_signal and bare_signals__on_close callbacks with uv_signal_t"],"goal":"verify pkg:npm/bare-signals@5.0.0 signal handling and listeners","kind":"HOW","packages":["pkg:npm/bare-signals@5.0.0"],"schemaVersion":1},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"npm","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"npm","packageManagerVersion":"10.9.8","runtime":"node","runtimeVersion":"22.23.2","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/bare-signals@5.0.0"],"schemaVersion":1,"subject":"pkg:npm/bare-signals@5.0.0","verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-gen",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-gen",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "bare-signals": "^5.0.0"
      }
    },
    "node_modules/bare-events": {
      "version": "2.9.2",
      "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
      "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
      "license": "Apache-2.0",
      "peerDependencies": {
        "bare-abort-controller": "*"
      },
      "peerDependenciesMeta": {
        "bare-abort-controller": {
          "optional": true
        }
      }
    },
    "node_modules/bare-signals": {
      "version": "5.0.0",
      "resolved": "https://registry.npmjs.org/bare-signals/-/bare-signals-5.0.0.tgz",
      "integrity": "sha512-8Gn8bBFUh2AUCJ9wWWFjSGWIo1HIUSIQnXRJGSm/f7GCDMqsuJhRmR1dT+HtDaDBkeu2l8Koxt2JLurfJ5yHVw==",
      "license": "Apache-2.0",
      "dependencies": {
        "bare-events": "^2.5.3"
      },
      "engines": {
        "bare": ">=1.7.0"
      }
    }
  }
}
package.json
{
  "name": "bare-signals-sample",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "license": "MIT-0",
  "dependencies": {
    "bare-signals": "5.0.0"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/bare-signals@5.0.0 signal handling and listeners",
  "kind": "HOW",
  "packages": [
    "pkg:npm/bare-signals@5.0.0"
  ]
}
src/index.mjs
import fs from 'node:fs';
import { createRequire } from 'node:module';

const require = createRequire(import.meta.url);

/**
 * Returns the parsed package manifest for bare-signals.
 * @returns {object} The package.json content of bare-signals.
 */
export function getBareSignalsMetadata() {
  const pkgPath = require.resolve('bare-signals/package');
  return JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
}

/**
 * Validates whether a signal name exists in the provided constants map.
 * @param {string} name - Signal name (e.g., 'SIGINT', 'SIGTERM').
 * @param {Record<string, number>} constants - Signal constants map.
 * @returns {boolean} True if the signal is known.
 */
export function isSupportedSignal(name, constants) {
  if (typeof name !== 'string' || !constants) return false;
  return Object.prototype.hasOwnProperty.call(constants, name);
}

/**
 * Formats a signal reception event for logging or diagnostics.
 * @param {string} name - Signal name.
 * @param {number} signum - Signal number.
 * @returns {string} Human-readable representation.
 */
export function formatSignalEvent(name, signum) {
  return `Received ${name} (${signum})`;
}
test/contract.mjs
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
import { getBareSignalsMetadata, isSupportedSignal, formatSignalEvent } from '../src/index.mjs';

const require = createRequire(import.meta.url);

// 1. Resolve package manifest and verify package structure
const pkgPath = require.resolve('bare-signals/package');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));

assert.equal(pkg.name, 'bare-signals', 'Package name must be bare-signals');
assert.equal(pkg.version, '5.0.0', 'Package version must be 5.0.0');
assert.equal(pkg.license, 'Apache-2.0', 'Package license must be Apache-2.0');
assert.equal(pkg.addon, true, 'Package must be marked as addon');
assert.equal(pkg.engines?.bare, '>=1.7.0', 'Package must specify Bare engine requirement');

assert.ok(pkg.exports, 'Package must define exports map');
assert.equal(pkg.exports['.'].types, './index.d.ts', 'Root export must specify index.d.ts types');
assert.equal(pkg.exports['.'].default, './index.js', 'Root export must specify index.js default');
assert.equal(pkg.exports['./errors'], './lib/errors.js', 'Errors export must specify lib/errors.js');
assert.equal(pkg.exports['./emitter'], './lib/emitter.js', 'Emitter export must specify lib/emitter.js');

const pkgDir = path.dirname(pkgPath);

// 2. Verify TypeScript type definitions in index.d.ts
const indexDts = fs.readFileSync(path.join(pkgDir, 'index.d.ts'), 'utf8');
assert.ok(indexDts.includes('declare class Signal'), 'index.d.ts must declare Signal class');
assert.ok(indexDts.includes('declare class SignalEmitter'), 'index.d.ts must declare SignalEmitter class');
assert.ok(indexDts.includes('declare class SignalError extends Error'), 'index.d.ts must declare SignalError class');
assert.ok(indexDts.includes('export const constants: Record<string, number>'), 'index.d.ts must declare constants');
assert.ok(indexDts.includes('export { SignalEmitter as Emitter, SignalError as errors }'), 'index.d.ts must export Emitter and errors');

// 3. Verify Error class (lib/errors.js)
const SignalError = require('bare-signals/errors');
const errUnknown = SignalError.UNKNOWN_SIGNAL("Unknown signal 'SIGINVALID'");
assert.equal(errUnknown.name, 'SignalError', 'SignalError name must be SignalError');
assert.equal(errUnknown.code, 'UNKNOWN_SIGNAL', 'UNKNOWN_SIGNAL error code must match');
assert.ok(errUnknown.message.includes('UNKNOWN_SIGNAL: Unknown signal'), 'SignalError message format');

const errClosed = SignalError.SIGNAL_CLOSED('Signal is closed');
assert.equal(errClosed.code, 'SIGNAL_CLOSED', 'SIGNAL_CLOSED error code must match');

// 4. Mock binding to test Signal and SignalEmitter lifecycle in offline runtime
const bindingPath = path.join(pkgDir, 'binding.js');
const mockSignals = {
  SIGHUP: 1,
  SIGINT: 2,
  SIGQUIT: 3,
  SIGTERM: 15,
  SIGUSR1: 10,
  SIGUSR2: 12,
};

const calls = [];
let nextHandleId = 1;
const handles = new Map();

require.cache[bindingPath] = {
  id: bindingPath,
  filename: bindingPath,
  loaded: true,
  exports: {
    signals: mockSignals,
    init: (ctx, onsignal, onclose) => {
      const handle = { id: nextHandleId++, ctx, onsignal, onclose, active: false, refed: true };
      handles.set(handle.id, handle);
      calls.push({ op: 'init', handleId: handle.id });
      return handle;
    },
    start: (handle, signum) => {
      calls.push({ op: 'start', handleId: handle.id, signum });
      handle.active = true;
    },
    stop: (handle) => {
      calls.push({ op: 'stop', handleId: handle.id });
      handle.active = false;
    },
    ref: (handle) => {
      calls.push({ op: 'ref', handleId: handle.id });
      handle.refed = true;
    },
    unref: (handle) => {
      calls.push({ op: 'unref', handleId: handle.id });
      handle.refed = false;
    },
    close: (handle) => {
      calls.push({ op: 'close', handleId: handle.id });
      setImmediate(() => {
        handle.onclose.call(handle.ctx);
      });
    },
  },
};

const Signal = require('bare-signals');
assert.equal(typeof Signal, 'function', 'bare-signals export must be a class constructor');
assert.deepEqual(Signal.constants, mockSignals, 'Signal.constants must match binding signals');

// Test Signal instance with string name
const sigint = new Signal('SIGINT');
assert.equal(sigint._signum, 2, 'SIGINT must resolve to signum 2');

sigint.start();
assert.equal(calls[calls.length - 1].op, 'start', 'start() must invoke binding.start');
assert.equal(calls[calls.length - 1].signum, 2, 'start() passes resolved signum 2');

sigint.stop();
assert.equal(calls[calls.length - 1].op, 'stop', 'stop() must invoke binding.stop');

sigint.unref();
assert.equal(calls[calls.length - 1].op, 'unref', 'unref() must invoke binding.unref');

sigint.ref();
assert.equal(calls[calls.length - 1].op, 'ref', 'ref() must invoke binding.ref');

// Test signal event emission
let signalReceived = null;
sigint.on('signal', (signum) => {
  signalReceived = signum;
});
sigint._onsignal();
assert.equal(signalReceived, 2, 'Signal must emit "signal" event with signum');

// Test signal close lifecycle and promise
let closedFired = false;
sigint.on('close', () => {
  closedFired = true;
});
const closePromise = sigint.close();
assert.ok(closePromise instanceof Promise, 'close() must return a Promise');

await closePromise;
assert.equal(closedFired, true, 'close event must fire upon handle closing');

// Test closed state error
assert.throws(
  () => sigint.start(),
  (err) => err.code === 'SIGNAL_CLOSED',
  'start() on closed signal must throw SIGNAL_CLOSED'
);

// Test unknown signal string throws UNKNOWN_SIGNAL
assert.throws(
  () => new Signal('SIGNONEXISTENT'),
  (err) => err.code === 'UNKNOWN_SIGNAL',
  'Unknown signal string must throw UNKNOWN_SIGNAL'
);

// 5. Test Signal.Emitter
const Emitter = Signal.Emitter;
const emitter = new Emitter();

let emitterCaught = null;
const onSigterm = (name, signum) => {
  emitterCaught = { name, signum };
};

emitter.on('SIGTERM', onSigterm);
assert.ok(emitter._signals.has('SIGTERM'), 'Emitter must track active signal');

emitter.unref();
assert.equal(emitter._unrefed, true, 'Emitter unref() must set unrefed flag');

emitter.ref();
assert.equal(emitter._unrefed, false, 'Emitter ref() must clear unrefed flag');

// Trigger signal on the tracked signal instance
const sigtermInstance = emitter._signals.get('SIGTERM');
sigtermInstance._onsignal();
assert.deepEqual(emitterCaught, { name: 'SIGTERM', signum: 15 }, 'Emitter emits signal name and signum');

// Remove listener triggers signal close
emitter.removeListener('SIGTERM', onSigterm);
assert.equal(emitter._signals.has('SIGTERM'), false, 'Removing listener must remove signal from map');

// 6. Verify native C binding implementation
const bindingC = fs.readFileSync(path.join(pkgDir, 'binding.c'), 'utf8');
assert.ok(bindingC.includes('bare_signals__on_signal(uv_signal_t *handle, int signum)'), 'binding.c must implement bare_signals__on_signal');
assert.ok(bindingC.includes('bare_signals__on_close(uv_handle_t *handle)'), 'binding.c must implement bare_signals__on_close');
assert.ok(bindingC.includes('bare_signals__on_teardown'), 'binding.c must handle deferred teardown');
assert.ok(bindingC.includes('V("init", bare_signals_init)'), 'binding.c must export init method');
assert.ok(bindingC.includes('V("start", bare_signals_start)'), 'binding.c must export start method');
assert.ok(bindingC.includes('V("stop", bare_signals_stop)'), 'binding.c must export stop method');
assert.ok(bindingC.includes('V("close", bare_signals_close)'), 'binding.c must export close method');

// 7. Verify helper functions from src/index.mjs
const metadata = getBareSignalsMetadata();
assert.equal(metadata.name, 'bare-signals');
assert.equal(metadata.version, '5.0.0');

assert.equal(isSupportedSignal('SIGINT', mockSignals), true);
assert.equal(isSupportedSignal('SIGUNKNOWN', mockSignals), false);
assert.equal(isSupportedSignal(123, mockSignals), false);

assert.equal(formatSignalEvent('SIGINT', 2), 'Received SIGINT (2)');

console.log('All bare-signals contract assertions passed successfully.');

オリジンシーダー

匿名