{"name":"eventsource-parser","version":"1.0.0","keywords":["sse","eventsource","server-sent-events"],"author":{"name":"Espen Hovlandsdal","email":"espen@hovlandsdal.com"},"license":"MIT","_id":"eventsource-parser@1.0.0","maintainers":[{"name":"rexxars","email":"espen@hovlandsdal.com"}],"homepage":"https://github.com/rexxars/eventsource-parser#readme","bugs":{"url":"https://github.com/rexxars/eventsource-parser/issues"},"dist":{"shasum":"6332e37fd5512e3c8d9df05773b2bf9e152ccc04","tarball":"http://registry-npm.ywwl.com/eventsource-parser/download/eventsource-parser-1.0.0.tgz","fileCount":14,"integrity":"sha512-9jgfSCa3dmEme2ES3mPByGXfgZ87VbP97tng1G2nWwWx6bV2nYxm2AWCrbQjXToSe+yYlqaZNtxffR9IeQr95g==","signatures":[{"sig":"MEQCIFKgyEq4YLWUtohzZ886JWhNBJa600GTH97z4bbzrwOQAiBqpgit22+xM2PNhdQzxx+0st4QWRqOpodZhWVVdGy3VA==","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":46472,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJkHKiOACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmraaw//Z3ka9yjRJ34fTwAy75nRmTNNepzHVciz8pOscbrz3ABsovIM\r\nJBPNk30amdnVcOixYXMYdP/eedzEmgWpqBzGKcgtYVxlryrPctRlGs5lLxAT\r\nGpUL2fRskoxyE6AFvB3phZzvR5gYTosDYbZDv3jvvQaVv/8kXjhi2ui1gWv9\r\nNSmbwytJylmyq7kV7K8sILzcepqGOsRmd5ciUf2OCHV1LHxekWo/RcQV34pu\r\n70+QgyKApaapaFBx8mDYMJq22TlgjdT0bKZ+n7YuDzxPuqiEoGnSm5tpSgOA\r\nr/WvqR7vWN0SUKwMixKACNZ9fQRM2PDQxCWJYMeNH1UbIXWmocnhQYbn86UK\r\nKvXqUa3IKl6k8DODHQ1UlURWtc7rr+0SdrHxb+uh1hohKPBt8cwxBHNMq3Ev\r\nCPVr9WdaKFaif9l+a4So0OnzvuXmUAw4he8TooEtQ0CrfOyUVQu+X3kXMNDW\r\nl7+c7FvmruaZtgXcVJYp6bhZkJioueiGuYseSmcC9xInwnBTBKY339mmLMOa\r\nYQ6H8n1RShHWfQ2tNKCEycQ60MpEQUeizpD7utZ5cKGbP+fo8fePOE2gnGUN\r\nZ3cIRoPQepHMOrQu3WP5ivR+QDtX4xaK+K3cJ5eX7RYUU4ROszwZ4rLwF/vB\r\nwA1uQHZJpiVW1XX3YAHyKAUYd0AZZKBmxh8=\r\n=Sd7P\r\n-----END PGP SIGNATURE-----\r\n","size":14560,"noattachment":false,"key":"/eventsource-parser/-/eventsource-parser-1.0.0.tgz"},"main":"./dist/index.cjs","type":"module","types":"./dist/index.d.ts","module":"./dist/index.js","source":"./src/index.ts","engines":{"node":">=14.18"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.js","source":"./src/index.ts","default":"./dist/index.js","require":"./dist/index.cjs"},"./package.json":"./package.json"},"gitHead":"8ef994f0d904fd88025d24f8ae63bb58879eda7f","scripts":{"lint":"eslint . && tsc --noEmit","test":"vitest --reporter=verbose","build":"pkg-utils build && pkg-utils --strict","clean":"rimraf dist coverage","posttest":"npm run lint","prebuild":"npm run clean","prepublishOnly":"npm run build"},"_npmUser":{"name":"rexxars","email":"espen@hovlandsdal.com"},"prettier":{"semi":false,"printWidth":100,"singleQuote":true,"bracketSpacing":false},"repository":{"url":"git+ssh://git@github.com/rexxars/eventsource-parser.git","type":"git"},"_npmVersion":"8.19.4","description":"Streaming, source-agnostic EventSource/Server-Sent Events parser","directories":{},"sideEffects":false,"_nodeVersion":"18.15.0","eslintConfig":{"extends":["sanity","sanity/typescript","prettier"],"parserOptions":{"sourceType":"module","ecmaVersion":9,"ecmaFeatures":{"modules":true}},"ignorePatterns":["lib/**/"]},"_hasShrinkwrap":false,"devDependencies":{"eslint":"^7.32.0","rimraf":"^4.4.1","vitest":"^0.29.7","prettier":"^2.8.6","typescript":"^4.9.5","@types/node":"^14.18.0","semantic-release":"^20.1.3","@sanity/pkg-utils":"^2.2.13","eslint-config-sanity":"^5.1.0","eslint-config-prettier":"^8.8.0","rollup-plugin-visualizer":"^5.9.0","@typescript-eslint/parser":"^5.56.0","@sanity/semantic-release-preset":"^4.0.2","@typescript-eslint/eslint-plugin":"^5.56.0"},"_npmOperationalInternal":{"tmp":"tmp/eventsource-parser_1.0.0_1679599758537_0.09316939834404225","host":"s3://npm-registry-packages"},"readme":"# eventsource-parser\n\n[![npm version](https://npmx.dev/api/registry/badge/version/eventsource-parser)](https://npmx.dev/package/eventsource-parser) [![num dependendencies](https://npmx.dev/api/registry/badge/dependencies/eventsource-parser)](https://npmx.dev/package/eventsource-parser) [![npm weekly downloads](https://npmx.dev/api/registry/badge/downloads-week/eventsource-parser)](https://npmx.dev/package/eventsource-parser) [![install size](https://npmx.dev/api/registry/badge/size/eventsource-parser)](https://npmx.dev/package/eventsource-parser)\n\nA streaming parser for [server-sent events/eventsource](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events), without any assumptions about how the actual stream of data is retrieved. It is intended to be a building block for [clients](https://github.com/rexxars/eventsource-client) and polyfills in javascript environments such as browsers, node.js and deno.\n\nIf you are looking for a modern client implementation, see [eventsource-client](https://github.com/rexxars/eventsource-client).\n\nYou create an instance of the parser, and _feed_ it chunks of data - partial or complete, and the parser emits parsed messages once it receives a complete message. A [TransformStream variant](#stream-usage) is also available for environments that support it (modern browsers, Node 22.12 and higher).\n\nOther modules in the EventSource family:\n\n- [eventsource](https://github.com/eventsource/eventsource): Cross-runtime polyfill for the WhatWG EventSource API.\n- [eventsource-encoder](https://github.com/rexxars/eventsource-encoder): encodes messages in the EventSource/Server-Sent Events format.\n- [eventsource-client](https://github.com/rexxars/eventsource-client): modern, feature rich eventsource client for browsers, node.js, bun, deno and other modern JavaScript environments.\n\n> [!NOTE]\n> Migrating from eventsource-parser 1.x/2.x? See the [migration guide](./MIGRATE-v3.md).\n\n## Installation\n\n```bash\nnpm install --save eventsource-parser\n```\n\n## Usage\n\n```ts\nimport {createParser, type EventSourceMessage} from 'eventsource-parser'\n\nfunction onEvent(event: EventSourceMessage) {\n  console.log('Received event!')\n  console.log('id: %s', event.id || '<none>')\n  console.log('event: %s', event.event || '<none>')\n  console.log('data: %s', event.data)\n}\n\nconst parser = createParser({onEvent})\nconst sseStream = getSomeReadableStream()\n\nfor await (const chunk of sseStream) {\n  parser.feed(chunk)\n}\n\n// If you want to re-use the parser for a new stream of events, make sure to reset it!\nparser.reset()\nconsole.log('Done!')\n```\n\n### Event IDs\n\nUse `onId` if you need to track event IDs for reconnection. The parser calls it once when a blank\nline ends a block containing a valid `id` field. It runs for blocks with or without `data`, and it\nruns before `onEvent` when the same block produces an event. An empty `id` field is reported as an\nempty string. An `id` field containing U+0000 is ignored.\n\n```ts\nlet lastEventId = ''\n\nconst parser = createParser({\n  onId(id) {\n    lastEventId = id\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\n### Retry intervals\n\nIf the server sends a `retry` field in the event stream, the parser will call any `onRetry` callback specified to the `createParser` function:\n\n```ts\nconst parser = createParser({\n  onRetry(retryInterval) {\n    console.log('Server requested retry interval of %dms', retryInterval)\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\n### Parse errors\n\nIf the parser encounters an error while parsing, it will call any `onError` callback provided to the `createParser` function:\n\n```ts\nimport {type ParseError} from 'eventsource-parser'\n\nconst parser = createParser({\n  onError(error: ParseError) {\n    console.error('Error parsing event:', error)\n    if (error.type === 'unknown-field') {\n      console.error('Field name:', error.field)\n      console.error('Field value:', error.value)\n      console.error('Line:', error.line)\n    } else if (error.type === 'invalid-retry') {\n      console.error('Invalid retry interval:', error.value)\n    }\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\nNote that `unknown-field` errors are emitted for completed invalid lines, not only data shaped as `field: value`. This is because the EventSource specification says to treat anything prior to a `:` as the field name. Incomplete lines that cannot become a valid SSE field may be discarded before completion to avoid unbounded buffering, in which case `onError` is not called and no `line`, `field`, or `value` is retained.\n\n> [!NOTE]\n> When encountering the end of a stream, calling `.reset({consume: true})` on the parser to flush any remaining data and reset the parser state. This will trigger the `onError` callback if the pending data has not already been discarded as an invalid line.\n\n### Comments\n\nThe parser will ignore comments (lines starting with `:`) by default. If you want to handle comments, you can provide an `onComment` callback to the `createParser` function:\n\n```ts\nconst parser = createParser({\n  onComment(comment) {\n    console.log('Received comment:', comment)\n  },\n  onEvent(event) {\n    // …\n  },\n})\n```\n\n> [!NOTE]\n> Leading whitespace is not stripped from comments, eg `: comment` will give ` comment` as the comment value, not `comment` (note the leading space).\n\n### Limiting buffered memory (`maxBufferSize`)\n\nBy default the parser buffers valid partial lines and event data until a server completes an event. A server (or proxy) that starts a valid field and never terminates the line, or that keeps appending `data:` lines without ever sending a blank line to dispatch the event, can therefore grow the parser's buffers without bound. Lines that cannot become valid SSE fields are discarded without buffering.\n\nPass a `maxBufferSize` (in characters) to `createParser` to cap this. If the combined size of the pending line buffer and the in-progress event's data buffer exceeds the limit, the parser emits a `ParseError` with `type: 'max-buffer-size-exceeded'` and becomes terminated: subsequent calls to `feed()` will throw until `reset()` is called.\n\n```ts\nconst parser = createParser({\n  maxBufferSize: 1024 * 1024, // 1 MB\n  onEvent(event) {\n    // …\n  },\n  onError(error) {\n    if (error.type === 'max-buffer-size-exceeded') {\n      // Stream peer is misbehaving — typically you'd close the connection.\n    }\n  },\n})\n```\n\nThe same option is available on the [stream variant](#stream-usage); the stream is always errored when this limit is exceeded, regardless of the `onError` setting (since the underlying parser is unrecoverable without a `reset()`).\n\n## Stream usage\n\n```ts\nimport {EventSourceParserStream} from 'eventsource-parser/stream'\n\nconst eventStream = response.body\n  .pipeThrough(new TextDecoderStream())\n  .pipeThrough(new EventSourceParserStream())\n```\n\nThe stream constructor accepts a subset of the `createParser` options (`onComment`, `onId`, `onRetry`, `maxBufferSize`) plus an `onError` that can either be a function or set to `'terminate'` to error the stream on parse errors. Events are delivered through the stream itself rather than via an `onEvent` callback:\n\n```ts\nnew EventSourceParserStream({\n  maxBufferSize: 1024 * 1024,\n  onError: 'terminate',\n})\n```\n\nNote that the TransformStream is exposed under a separate export (`eventsource-parser/stream`), in order to maximize compatibility with environments that do not have the `TransformStream` constructor available.\n\n## License\n\nMIT © [Espen Hovlandsdal](https://espen.codes/)\n","publish_time":1679599758742,"_cnpm_publish_time":1679599758742,"dist-tags":{"beta":"3.0.0-beta.0","latest":"4.1.3"}}