CodeSampleX

샘플

eventsource 3.0.7: EventSource

검증된 샘플 — npm eventsource 3.0.7: EventSource. node 22 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: EventSource defines static and instance readyState…

sha256:cd340bf97ede5ff331cbaee746c8781fa05b500d2c9131d7299848332f346bf0

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 linux 24 · ubuntu · glibc 2.39 x64 npm

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify eventsource.EventSource in pkg:npm/eventsource@3.0.7
패키지
심벌
  • eventsource.EventSource
생성일
2026-09-07T03:33:54Z

컨트랙트

  1. EventSource defines static and instance readyState constants: CONNECTING (0), OPEN (1), and CLOSED (2)
  2. EventSource constructor initializes readyState as CONNECTING and stores target url and withCredentials option
  3. EventSource connects to SSE HTTP endpoint, emits open event, and transitions readyState to OPEN
  4. EventSource receives standard messages and delivers event payload via onmessage handler
  5. EventSource dispatches named custom SSE events to registered addEventListener listeners
  6. EventSource concatenates multiline data lines into a single newline-separated message data string
  7. EventSource accepts custom fetch implementation in EventSourceInit to stream SSE events
  8. EventSource close() terminates active stream connection and sets readyState to CLOSED
  9. EventSource onerror triggers on HTTP error responses without entering OPEN state

파일

  • 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 eventsource.EventSource in pkg:npm/eventsource@3.0.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:npm/eventsource@3.0.7
Demonstrate these symbols/APIs:
  - eventsource.EventSource

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:b960a3e55f76b2c30b2583b25ed1f3883ebc07d3f75d34db209b7908e3b9bce2","contract":["EventSource defines static and instance readyState constants: CONNECTING (0), OPEN (1), and CLOSED (2)","EventSource constructor initializes readyState as CONNECTING and stores target url and withCredentials option","EventSource connects to SSE HTTP endpoint, emits open event, and transitions readyState to OPEN","EventSource receives standard messages and delivers event payload via onmessage handler","EventSource dispatches named custom SSE events to registered addEventListener listeners","EventSource concatenates multiline data lines into a single newline-separated message data string","EventSource accepts custom fetch implementation in EventSourceInit to stream SSE events","EventSource close() terminates active stream connection and sets readyState to CLOSED","EventSource onerror triggers on HTTP error responses without entering OPEN state"],"goal":"verify eventsource.EventSource in pkg:npm/eventsource@3.0.7","kind":"HOW","packages":["pkg:npm/eventsource@3.0.7"],"schemaVersion":1,"symbols":["eventsource.EventSource"]},"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/eventsource@3.0.7"],"schemaVersion":1,"subject":"pkg:npm/eventsource@3.0.7","symbols":["eventsource.EventSource"],"verifierAdapter":"node-typescript@1"}
index.mjs
import { EventSource, ErrorEvent } from 'eventsource';

/**
 * Creates and configures an EventSource instance.
 *
 * @param {string | URL} url - The URL of the SSE endpoint.
 * @param {import('eventsource').EventSourceInit} [options] - EventSource configuration options.
 * @returns {EventSource}
 */
export function createEventSource(url, options = {}) {
  return new EventSource(url, options);
}

/**
 * Creates a mock fetch function suitable for offline EventSource testing and mocking.
 *
 * @param {string[]} sseChunks - Array of SSE formatted text chunks to stream.
 * @returns {import('eventsource').FetchLike}
 */
export function createMockSSEFetch(sseChunks) {
  const encoder = new TextEncoder();
  return async (url, init) => {
    let index = 0;
    return {
      status: 200,
      redirected: false,
      headers: {
        get(name) {
          if (name.toLowerCase() === 'content-type') {
            return 'text/event-stream';
          }
          return null;
        },
      },
      body: {
        getReader() {
          return {
            async read() {
              if (index < sseChunks.length) {
                const chunk = sseChunks[index++];
                return { done: false, value: encoder.encode(chunk) };
              }
              return { done: true, value: undefined };
            },
            async cancel() {},
          };
        },
      },
    };
  };
}

export { EventSource, ErrorEvent };
package-lock.json
{
  "name": "sample-eventsource-eventsource",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "sample-eventsource-eventsource",
      "version": "1.0.0",
      "license": "MIT-0",
      "dependencies": {
        "eventsource": "3.0.7"
      }
    },
    "node_modules/eventsource": {
      "version": "3.0.7",
      "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
      "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
      "license": "MIT",
      "dependencies": {
        "eventsource-parser": "^3.0.1"
      },
      "engines": {
        "node": ">=18.0.0"
      }
    },
    "node_modules/eventsource-parser": {
      "version": "3.1.1",
      "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
      "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
      "license": "MIT",
      "engines": {
        "node": ">=18.0.0"
      }
    }
  }
}
package.json
{
  "name": "sample-eventsource-eventsource",
  "version": "1.0.0",
  "type": "module",
  "private": true,
  "license": "MIT-0",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "dependencies": {
    "eventsource": "3.0.7"
  }
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify eventsource.EventSource in pkg:npm/eventsource@3.0.7",
  "kind": "HOW",
  "packages": [
    "pkg:npm/eventsource@3.0.7"
  ],
  "symbols": [
    "eventsource.EventSource"
  ]
}
test/contract.mjs
import assert from 'node:assert/strict';
import http from 'node:http';
import { EventSource, ErrorEvent, createEventSource, createMockSSEFetch } from '../index.mjs';

// Contract 1: EventSource defines static and instance readyState constants: CONNECTING (0), OPEN (1), and CLOSED (2)
assert.equal(EventSource.CONNECTING, 0);
assert.equal(EventSource.OPEN, 1);
assert.equal(EventSource.CLOSED, 2);

const esInit = createEventSource('http://127.0.0.1:9000/sse', { withCredentials: true });
assert.equal(esInit.CONNECTING, 0);
assert.equal(esInit.OPEN, 1);
assert.equal(esInit.CLOSED, 2);

// Contract 2: EventSource constructor initializes readyState as CONNECTING and stores target url and withCredentials option
assert.equal(esInit.readyState, EventSource.CONNECTING);
assert.equal(esInit.url, 'http://127.0.0.1:9000/sse');
assert.equal(esInit.withCredentials, true);

// Contract 8: EventSource close() terminates active stream connection and sets readyState to CLOSED
esInit.close();
assert.equal(esInit.readyState, EventSource.CLOSED);

// Contract 7: EventSource accepts custom fetch implementation in EventSourceInit to stream SSE events
// Contract 6: EventSource concatenates multiline data lines into a single newline-separated message data string
await new Promise((resolve, reject) => {
  let customFetchCalled = false;
  const mockChunks = [
    'data: line1\ndata: line2\n\n',
    'data: single-line\n\n',
  ];
  const customFetch = createMockSSEFetch(mockChunks);
  const wrappedFetch = async (url, init) => {
    customFetchCalled = true;
    assert.equal(init.headers.Accept, 'text/event-stream');
    return customFetch(url, init);
  };

  const es = createEventSource('http://localhost/mock-sse', { fetch: wrappedFetch });
  const received = [];

  es.onmessage = (event) => {
    received.push(event.data);
    if (received.length === 2) {
      try {
        assert.ok(customFetchCalled, 'Custom fetch implementation must be invoked');
        assert.equal(received[0], 'line1\nline2', 'Multiline data must be joined with newlines');
        assert.equal(received[1], 'single-line');
        es.close();
        assert.equal(es.readyState, EventSource.CLOSED);
        resolve();
      } catch (err) {
        es.close();
        reject(err);
      }
    }
  };

  es.onerror = (err) => {
    es.close();
    reject(new Error('Unexpected error in mock fetch: ' + String(err)));
  };
});

// Contract 3: EventSource connects to SSE HTTP endpoint, emits open event, and transitions readyState to OPEN
// Contract 4: EventSource receives standard messages and delivers event payload via onmessage handler
// Contract 5: EventSource dispatches named custom SSE events to registered addEventListener listeners
await new Promise((resolve, reject) => {
  const server = http.createServer((req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
    });
    res.write('data: standard greeting\n\n');
    res.write('event: ping\ndata: heartbeat\n\n');
  });

  server.listen(0, '127.0.0.1', () => {
    const port = server.address().port;
    const es = createEventSource(`http://127.0.0.1:${port}/events`);

    let openFired = false;
    let standardReceived = false;

    es.onopen = () => {
      openFired = true;
      assert.equal(es.readyState, EventSource.OPEN);
    };

    es.onmessage = (event) => {
      assert.equal(event.data, 'standard greeting');
      standardReceived = true;
    };

    es.addEventListener('ping', (event) => {
      try {
        assert.ok(openFired, 'open event must fire before or with messages');
        assert.ok(standardReceived, 'standard onmessage must receive payload');
        assert.equal(event.data, 'heartbeat', 'custom event listener must receive data');
        es.close();
        assert.equal(es.readyState, EventSource.CLOSED);
        server.close(() => resolve());
      } catch (err) {
        es.close();
        server.close(() => reject(err));
      }
    });

    es.onerror = (err) => {
      es.close();
      server.close(() => reject(new Error('Unexpected HTTP server stream error: ' + String(err))));
    };
  });
});

// Contract 9: EventSource onerror triggers on HTTP error responses without entering OPEN state
await new Promise((resolve, reject) => {
  const server = http.createServer((req, res) => {
    res.writeHead(500, { 'Content-Type': 'text/plain' });
    res.end('Internal Server Error');
  });

  server.listen(0, '127.0.0.1', () => {
    const port = server.address().port;
    const es = createEventSource(`http://127.0.0.1:${port}/error`);

    let opened = false;
    es.onopen = () => {
      opened = true;
    };

    es.onerror = (event) => {
      try {
        assert.equal(opened, false, 'Connection must not open on 500 error');
        assert.equal(event.type, 'error');
        es.close();
        assert.equal(es.readyState, EventSource.CLOSED);
        server.close(() => resolve());
      } catch (err) {
        es.close();
        server.close(() => reject(err));
      }
    };
  });
});

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

오리진 시더

익명