{"name":"eventsource","version":"3.0.3","keywords":["sse","eventsource","server-sent-events"],"author":{"name":"Espen Hovlandsdal","email":"espen@hovlandsdal.com"},"license":"MIT","_id":"eventsource@3.0.3","maintainers":[{"name":"aslakhellesoy","email":"aslak.hellesoy@gmail.com"},{"name":"rexxars","email":"espen@hovlandsdal.com"}],"contributors":[{"name":"Aslak Hellesøy","email":"aslak.hellesoy@gmail.com"},{"name":"Einar Otto Stangvik","email":"einaro.s@gmail.com"}],"homepage":"https://github.com/EventSource/eventsource#readme","bugs":{"url":"https://github.com/EventSource/eventsource/issues"},"dist":{"shasum":"f54d8c7b5ecfc2c395cd02e428a45926e0028e6a","tarball":"http://registry-npm.ywwl.com/eventsource/download/eventsource-3.0.3.tgz","fileCount":13,"integrity":"sha512-dz1sFfDM1EK7/HrGMoIW1+qdQc15w0ibDu4N7i4QzPVQoT8A8cRouZO2R/nq8o8XlW/pMx6pNqq18Vfi3rgKzw==","signatures":[{"sig":"MEUCIQDMQe4gZdE0AybCUOhMNHpwi/GyBgzolKFu8GPqa1KpYQIgGKJXrmpV2+6/mvQyg5yw1Hc6u6/IcWmH44PbgUZJE+8=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/eventsource@3.0.3","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":127232,"size":21479,"noattachment":false,"key":"/eventsource/-/eventsource-3.0.3.tgz"},"main":"./dist/index.cjs","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","engines":{"node":">=18.0.0"},"exports":{".":{"bun":"./dist/index.js","deno":"./dist/index.js","import":"./dist/index.js","source":"./src/index.ts","default":"./dist/index.js","require":"./dist/index.cjs"},"./package.json":"./package.json"},"gitHead":"568f209ad6d1727a8e9fd41a27f4beadf58a5cba","scripts":{"lint":"eslint . && tsc --noEmit","test":"npm run test:node && npm run test:browser","build":"pkg-utils build && pkg-utils --strict","clean":"rimraf dist coverage","prepare":"npm run build","posttest":"npm run lint","prebuild":"npm run clean","test:bun":"bun run test/bun/client.bun.test.ts","test:deno":"deno run --allow-net --allow-read --allow-env --unstable-sloppy-imports test/deno/client.deno.test.ts","test:node":"tsx test/node/client.node.test.ts","build:watch":"pkg-utils watch","test:browser":"tsx test/browser/client.browser.test.ts"},"_npmUser":{"name":"rexxars","email":"espen@hovlandsdal.com"},"prettier":{"semi":false,"printWidth":100,"singleQuote":true,"bracketSpacing":false},"overrides":{"cross-spawn":"7.0.6"},"repository":{"url":"git://git@github.com/EventSource/eventsource.git","type":"git"},"_npmVersion":"10.9.2","description":"WhatWG/W3C compliant EventSource client for Node.js and browsers","directories":{},"sideEffects":false,"_nodeVersion":"22.13.0","browserslist":["node >= 18","chrome >= 71","safari >= 14.1","firefox >= 105","edge >= 79"],"dependencies":{"eventsource-parser":"^3.0.0"},"eslintConfig":{"rules":{"no-empty":"off","no-undef":"off"},"extends":["sanity","sanity/typescript","prettier"],"globals":{"globalThis":false},"parserOptions":{"sourceType":"module","ecmaVersion":9,"ecmaFeatures":{"modules":true}},"ignorePatterns":["lib/**/"]},"publishConfig":{"provenance":true},"_hasShrinkwrap":false,"devDependencies":{"tsx":"^4.19.2","sinon":"^17.0.1","eslint":"^8.57.0","rimraf":"^5.0.5","undici":"^6.20.1","esbuild":"^0.24.0","prettier":"^3.2.5","playwright":"^1.48.2","typescript":"^5.6.3","@types/sinon":"^17.0.3","semantic-release":"^24.2.0","@sanity/pkg-utils":"^6.11.10","@tsconfig/strictest":"^2.0.5","eventsource-encoder":"^1.0.0","eslint-config-sanity":"^7.1.3","eslint-config-prettier":"^9.1.0","rollup-plugin-visualizer":"^5.12.0","@typescript-eslint/parser":"^6.11.0","@sanity/semantic-release-preset":"^5.0.0","@typescript-eslint/eslint-plugin":"^6.11.0"},"_npmOperationalInternal":{"tmp":"tmp/eventsource_3.0.3_1738013376945_0.8396915122895683","host":"s3://npm-registry-packages-npm-production"},"readme":"# eventsource\n\n[![npm version](https://img.shields.io/npm/v/eventsource.svg?style=flat-square)](https://www.npmjs.com/package/eventsource)[![npm bundle size](https://img.shields.io/bundlephobia/minzip/eventsource?style=flat-square)](https://bundlephobia.com/result?p=eventsource)[![npm weekly downloads](https://img.shields.io/npm/dw/eventsource.svg?style=flat-square)](https://www.npmjs.com/package/eventsource)\n\nWhatWG/W3C-compatible [server-sent events/eventsource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) client. The module attempts to implement an absolute minimal amount of features/changes beyond the specification.\n\nIf you're looking for a modern alternative with a less constrained API, check out the [`eventsource-client` package](https://www.npmjs.com/package/eventsource-client).\n\n## Installation\n\n```bash\nnpm install --save eventsource\n```\n\n## Supported engines\n\n- Node.js >= 22.12\n- Chrome >= 84\n- Safari >= 15\n- Firefox >= 105\n- Edge >= 84\n- Deno >= 2\n- Bun >= 1.1.23\n- Cloudflare Workers: [partial](#cloudflare-workers)\n\nBasically, any environment that supports:\n\n- [fetch](https://developer.mozilla.org/en-US/docs/Web/API/fetch)\n- [ReadableStream](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)\n- [TextDecoder](https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder)\n- [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL)\n- [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event), [MessageEvent](https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent), [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)\n- [Private class fields, methods, and accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_elements)\n- [Symbol.for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/for)\n\nIf you need to support runtimes without private class fields, methods and accessors, try the `4.x` branch/version range.\n\nIf you need to support even older runtimes, try the `2.x` branch/version range (note: 2.x branch is primarily targeted at Node.js, not browsers).\n\n## Usage\n\n```ts\nimport {EventSource} from 'eventsource'\n\nconst es = new EventSource('https://my-server.com/sse')\n\n/*\n * This will listen for events with the field `event: notice`.\n */\nes.addEventListener('notice', (event) => {\n  console.log(event.data)\n})\n\n/*\n * This will listen for events with the field `event: update`.\n */\nes.addEventListener('update', (event) => {\n  console.log(event.data)\n})\n\n/*\n * The event \"message\" is a special case, as it will capture events _without_ an\n * event field, as well as events that have the specific type `event: message`.\n * It will not trigger on any other event type.\n */\nes.addEventListener('message', (event) => {\n  console.log(event.data)\n})\n\n/**\n * To explicitly close the connection, call the `close` method.\n * This will prevent any reconnection from happening.\n */\nsetTimeout(() => {\n  es.close()\n}, 10_000)\n```\n\n### TypeScript\n\nMake sure you have configured your TSConfig so it matches the environment you are targetting. If you are targetting browsers, this would be `dom`:\n\n```jsonc\n{\n  \"compilerOptions\": {\n    \"lib\": [\"dom\"],\n  },\n}\n```\n\nIf you're using Node.js, ensure you have `@types/node` installed (and it is version 22 or higher). Cloudflare workers have `@cloudflare/workers-types` etc.\n\nThe following errors are caused by targetting an environment that does not have the necessary types available:\n\n```\nerror TS2304: Cannot find name 'Event'.\nerror TS2304: Cannot find name 'EventTarget'.\nerror TS2304: Cannot find name 'MessageEvent'.\n```\n\n### Cloudflare Workers\n\nCloudflare Workers require `compatibilityDate: '2024-11-11'` or later, and `addEventListener()` instead of the `onmessage`, `onopen` and `onerror` properties.\n\nworkerd's `EventTarget` dispatches `on<type>` handler properties itself, on top of the listener this module registers, so a handler assigned that way is called twice per event - and assigning `null` only removes one of the two registrations, so it does not unsubscribe ([workerd#6022](https://github.com/cloudflare/workerd/issues/6022)).\n\n```js\n// Called twice per message on Cloudflare Workers\neventSource.onmessage = (event) => console.log(event.data)\n\n// Use this instead\neventSource.addEventListener('message', (event) => console.log(event.data))\n```\n\nworkerd also drops `origin` and `lastEventId` from the `MessageEvent` constructor. This module assigns them itself, so both are correct on Workers today; the workaround goes away once [workerd#6995](https://github.com/cloudflare/workerd/pull/6995) lands.\n\n## Migrating from v1 / v2\n\nSee [MIGRATION.md](MIGRATION.md#v2-to-v3) for a detailed migration guide.\n\n## Extensions to the WhatWG/W3C API\n\n### Message and code properties on errors\n\nThe `error` event has a `message` and `code` property that can be used to get more information about the error. In the specification, the Event\n\n```ts\nes.addEventListener('error', (err) => {\n  if (err.code === 401 || err.code === 403) {\n    console.log('not authorized')\n  }\n})\n```\n\n### Limit parser buffer size\n\nThe parser buffers up to 100 MB while waiting for a complete EventSource line. To change that limit, pass `maxBufferSize` in the constructor options:\n\n```ts\nconst es = new EventSource('https://my-server.com/sse', {\n  maxBufferSize: 10 * 1024 * 1024, // 10 MB\n})\n```\n\nIf the limit is exceeded, the connection fails and emits an `error` event, and will not reconnect. Prefer servers that emit smaller chunks or newlines more frequently over increasing this limit.\n\n### Specify `fetch` implementation\n\nThe `EventSource` constructor accepts an optional `fetch` property in the second argument that can be used to specify the `fetch` implementation to use.\n\nThis can be useful in environments where the global `fetch` function is not available - but it can also be used to alter the request/response behaviour.\n\n#### Setting HTTP request headers\n\n```ts\nconst es = new EventSource('https://my-server.com/sse', {\n  fetch: (input, init) =>\n    fetch(input, {\n      ...init,\n      headers: {\n        ...init.headers,\n        Authorization: 'Bearer myToken',\n      },\n    }),\n})\n```\n\n#### HTTP/HTTPS proxy\n\nUse a package like [`undici`](https://github.com/nodejs/undici) to add proxy support, either through environment variables or explicit configuration.\n\n```ts\n// npm install undici --save\nimport {fetch, EnvHttpProxyAgent} from 'undici'\n\nconst proxyAgent = new EnvHttpProxyAgent()\n\nconst es = new EventSource('https://my-server.com/sse', {\n  fetch: (input, init) => fetch(input, {...init, dispatcher: proxyAgent}),\n})\n```\n\n#### Using HTTP2\n\nUse a package like [`undici`](https://github.com/nodejs/undici) that supports HTTP2.\n\n```ts\n// npm install undici --save\nimport {Agent, fetch} from 'undici'\n\nconst http2Dispatcher = new Agent({allowH2: true})\n\nconst es = new EventSource('https://my-server.com/sse', {\n  fetch: (url, init) => fetch(url, {...init, dispatcher: http2Dispatcher}),\n})\n```\n\n#### Allow unauthorized HTTPS requests\n\nUse a package like [`undici`](https://github.com/nodejs/undici) for more control of fetch options through the use of an [`Agent`](https://undici.nodejs.org/#/docs/api/Agent.md).\n\n```ts\n// npm install undici --save\nimport {fetch, Agent} from 'undici'\n\nconst unsafeAgent = new Agent({\n  connect: {\n    rejectUnauthorized: false,\n  },\n})\n\nawait fetch('https://my-server.com/sse', {\n  dispatcher: unsafeAgent,\n})\n```\n\n#### Feature checking\n\nFor library authors, you may want to feature-check if an EventSource implementation supports passing a custom `fetch` implementation (such as this library does). We declare (from [v4.1.0](https://github.com/EventSource/eventsource/releases/tag/v4.1.0) and onwards) a non-enumerable symbol on the EventSource class to indicate this, named `eventsource.supports-fetch-override`. It can be used downstream such as:\n\n```ts\nfunction yourLibrary(options) {\n  const OurEventSource = options.polyfills.EventSource || globalThis.EventSource\n\n  if (OurEventSource && Symbol.for('eventsource.supports-fetch-override') in OurEventSource) {\n    // We can safely assume this supports overriding/specifying `fetch`!\n    const es = new OurEventSource('https://some.url', {\n      fetch: (input, init) =>\n        fetch(input, {\n          ...init,\n          headers: {\n            ...(init.headers || {}),\n            'x-some-header': 'foo',\n          },\n        }),\n    })\n    // …\n  }\n}\n```\n\n## License\n\nMIT-licensed. See [LICENSE](LICENSE).\n","publish_time":1738013377149,"_cnpm_publish_time":1738013377149,"dist-tags":{"latest":"5.1.4","next":"3.0.0-beta.0","umd":"3.0.5-umd.0"}}