CodeSampleX

Пример

events 3.3.0: EventEmitter, EventEmitter.prototype.emit, EventEmitter.prototype.on

Проверенный пример — npm events 3.3.0: EventEmitter, EventEmitter.prototype.emit, EventEmitter.prototype.on. Контракт выполнен на node 22 · linux alpine/x64…

sha256:c3cb00f379075fc9bebe08627a91b33c7e37ebbf5d3f29b5e753eb0631573be5

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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
Цель
verify pkg:npm/events@3.3.0
Пакеты
Символы
  • EventEmitter
  • EventEmitter.prototype.emit
  • EventEmitter.prototype.on
  • EventEmitter.prototype.once
  • EventEmitter.prototype.removeListener
  • events.once
Создан
2026-08-27T23:13:00Z

Контракт

  1. EventEmitter instances register event listeners with on and invoke them synchronously with emit passing variable arguments
  2. EventEmitter.prototype.once registers single-use event listeners that automatically deregister after their first invocation
  3. EventEmitter.prototype.removeListener removes specific listener callbacks and decreases listenerCount accordingly
  4. EventEmitter.prototype.eventNames returns an array of currently registered event names or symbols
  5. EventEmitter.prototype.setMaxListeners configures listener warning threshold and getMaxListeners retrieves it
  6. EventEmitter.prototype.prependListener inserts listeners to the beginning of the listener array
  7. events.once returns a Promise that resolves with an array of event arguments when the event fires
  8. events.once rejects the Promise if an error event is emitted before the targeted event fires

Файлы

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

Скачать артефакт с исходным кодом (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/events@3.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/events@3.3.0
Demonstrate these symbols/APIs:
  - EventEmitter
  - EventEmitter.prototype.emit
  - EventEmitter.prototype.on
  - EventEmitter.prototype.once
  - EventEmitter.prototype.removeListener
  - events.once

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:83b8474ef9a000f2cdaf16890d5665e089cda32ba052db255b45182985dd957f","contract":["EventEmitter instances register event listeners with on and invoke them synchronously with emit passing variable arguments","EventEmitter.prototype.once registers single-use event listeners that automatically deregister after their first invocation","EventEmitter.prototype.removeListener removes specific listener callbacks and decreases listenerCount accordingly","EventEmitter.prototype.eventNames returns an array of currently registered event names or symbols","EventEmitter.prototype.setMaxListeners configures listener warning threshold and getMaxListeners retrieves it","EventEmitter.prototype.prependListener inserts listeners to the beginning of the listener array","events.once returns a Promise that resolves with an array of event arguments when the event fires","events.once rejects the Promise if an error event is emitted before the targeted event fires"],"goal":"verify pkg:npm/events@3.3.0","kind":"HOW","packages":["pkg:npm/events@3.3.0"],"schemaVersion":1,"symbols":["EventEmitter","EventEmitter.prototype.emit","EventEmitter.prototype.on","EventEmitter.prototype.once","EventEmitter.prototype.removeListener","events.once"]},"contractCommand":["node","test/contract.js"],"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/events@3.3.0"],"schemaVersion":1,"subject":"pkg:npm/events@3.3.0","symbols":["EventEmitter","EventEmitter.prototype.emit","EventEmitter.prototype.on","EventEmitter.prototype.once","EventEmitter.prototype.removeListener","events.once"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "sample-events",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-events",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "events": "3.3.0"
      }
    },
    "node_modules/events": {
      "version": "3.3.0",
      "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
      "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
      "license": "MIT",
      "engines": {
        "node": ">=0.8.x"
      }
    }
  }
}
package.json
{
  "name": "sample-events",
  "version": "1.0.0",
  "private": true,
  "description": "Clean-room verification sample for events",
  "main": "src/index.js",
  "scripts": {
    "test": "node test/contract.js"
  },
  "dependencies": {
    "events": "3.3.0"
  },
  "license": "MIT-0"
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:npm/events@3.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:npm/events@3.3.0"
  ],
  "symbols": [
    "EventEmitter",
    "EventEmitter.prototype.emit",
    "EventEmitter.prototype.on",
    "EventEmitter.prototype.once",
    "EventEmitter.prototype.removeListener",
    "events.once"
  ]
}
src/index.js
'use strict';

const EventEmitter = require('events');
const { once } = EventEmitter;

function createEmitter() {
  return new EventEmitter();
}

async function waitForEvent(emitter, eventName) {
  return await once(emitter, eventName);
}

module.exports = {
  EventEmitter,
  once,
  createEmitter,
  waitForEvent
};
test/contract.js
'use strict';

const assert = require('assert');
const EventEmitter = require('events');
const { once } = EventEmitter;
const { createEmitter, waitForEvent } = require('../src/index.js');

async function testEventEmitter() {
  // 1. EventEmitter instance creation and basic emit/on
  const ee = new EventEmitter();
  let receivedArgs = [];
  ee.on('data', (a, b, c) => {
    receivedArgs.push([a, b, c]);
  });

  const emitted = ee.emit('data', 1, 'test', { key: 'value' });
  assert.strictEqual(emitted, true, 'emit should return true when listeners exist');
  assert.deepStrictEqual(receivedArgs, [[1, 'test', { key: 'value' }]]);

  // emit with no listeners returns false
  assert.strictEqual(ee.emit('nonexistent'), false, 'emit should return false when no listeners exist');

  // 2. once listener
  let onceCalls = 0;
  ee.once('single', (val) => {
    onceCalls += val;
  });

  ee.emit('single', 10);
  assert.strictEqual(onceCalls, 10);
  ee.emit('single', 10);
  assert.strictEqual(onceCalls, 10, 'once listener should only fire once');

  // 3. removeListener / off
  const fn1 = () => {};
  const fn2 = () => {};
  ee.on('custom', fn1);
  ee.on('custom', fn2);
  assert.strictEqual(ee.listenerCount('custom'), 2);

  ee.removeListener('custom', fn1);
  assert.strictEqual(ee.listenerCount('custom'), 1);
  assert.strictEqual(ee.listeners('custom')[0], fn2);

  ee.off('custom', fn2);
  assert.strictEqual(ee.listenerCount('custom'), 0);

  // 4. eventNames
  ee.on('alpha', () => {});
  ee.on('beta', () => {});
  const names = ee.eventNames();
  assert(names.includes('alpha'));
  assert(names.includes('beta'));
  ee.removeAllListeners('alpha');
  ee.removeAllListeners('beta');

  // 5. setMaxListeners and getMaxListeners
  assert.strictEqual(ee.getMaxListeners(), 10);
  ee.setMaxListeners(25);
  assert.strictEqual(ee.getMaxListeners(), 25);

  // 6. prependListener
  const order = [];
  ee.on('orderTest', () => order.push('second'));
  ee.prependListener('orderTest', () => order.push('first'));
  ee.emit('orderTest');
  assert.deepStrictEqual(order, ['first', 'second']);

  // 7. events.once Promise wrapper
  const helperEe = createEmitter();
  const promise = waitForEvent(helperEe, 'ready');
  helperEe.emit('ready', 'payload1', 42);
  const results = await promise;
  assert.deepStrictEqual(results, ['payload1', 42]);

  // 8. events.once rejection on error event
  const errorEe = createEmitter();
  const failingPromise = once(errorEe, 'success');
  const testError = new Error('Operation failed');
  errorEe.emit('error', testError);

  await assert.rejects(
    async () => {
      await failingPromise;
    },
    (err) => {
      assert.strictEqual(err, testError);
      return true;
    },
    'events.once should reject when error is emitted'
  );

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

testEventEmitter().catch((err) => {
  console.error('Contract test failed:', err);
  process.exit(1);
});

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

аноним