{"name":"eventsource-parser","version":"0.0.4","keywords":["sse","eventsource","server-sent-events"],"author":{"name":"Espen Hovlandsdal","email":"espen@hovlandsdal.com"},"license":"MIT","_id":"eventsource-parser@0.0.4","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":"35df1f86df3c117d83dddddcf6c2e63f348514af","tarball":"http://registry-npm.ywwl.com/eventsource-parser/download/eventsource-parser-0.0.4.tgz","fileCount":11,"integrity":"sha512-AiRkBY6mhIeAjupcklPUFKynMfnIZ6l8hPo2QMQ00buVmmll3SnminKCp5/SbWUgwpgo1/aar+m+PJclvx26dQ==","signatures":[{"sig":"MEUCICTb0kUOMF1SGnDBJlhH9u5p3WS1/qk1qPo7Uydznkf/AiEA+eFqpknXecry105d/YYXGB0eNG2or9thppJ69t8nu6o=","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":40817,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjOitQACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2VmqXIw/9HNRC7bUO4UmXoYBn2anWHcy/s72ZaqC2Fs9RzQWAdlerX19m\r\nBkoGwU0kgpr+kWfVBF6ZZPWwv3smNuUrgrLlodIaU6x3l72uphi5ZAX+jb1B\r\n5PuoBiq0g1W+iUv5E+GCWQ7rJ3L9MiaW7LXQaAzzWGLOD42ETQ8Ft/M82YLH\r\nATyZz2F8sS9wK4Ve3Wo8YOA+/SfPyCyqpxJ11pUHXF41A9RUhE1mlJZptvoi\r\nAz+U2ARWdv6MAmn0ZNkUM9MDsYc6caehM+DNZ8grH+GKSKL++uQv6g3hF3d8\r\nG0pSwvjfTNvAfDbMVQQo1xFlqFPRlN8ZTXDpnjnbEb28V5npP4ynT8++11ol\r\nwUqKI+CZqTdd16SlaHKlFlVFpmHA48IeiKK+JSZUeGhvLyU9CyBKAZGtHx/t\r\nQSGAeSb/XMH1RPrKtCh1gvh4Pwp9MoBEdhGYlX7SjU7BxzDiLYLFgpW8Xvpx\r\nXKOF59a6yLyzVezIfn1Buz/ZBKVE+c3eQgwItZUh3tsnAbYjkBfXqxIYJi8O\r\nF0f7G+iV23K5tuXO/8wIJ3xp5zCwzRfGKgKvox44cBCWGmXFE4DaUgxQ0Ek/\r\ngi8ckc4cZc6aitF4XgHtjPIQtXZKnRbfuvZ6ZxlLF6oWDc+hulz1NC3UNG9Z\r\nD6IGtiajTVtJWkA1yE/chzUtSDXbj7KhBMo=\r\n=qQPW\r\n-----END PGP SIGNATURE-----\r\n","size":8115,"noattachment":false,"key":"/eventsource-parser/-/eventsource-parser-0.0.4.tgz"},"jest":{"preset":"ts-jest","clearMocks":true,"testTimeout":30000,"collectCoverage":true,"coverageProvider":"v8","coverageDirectory":"coverage","coverageReporters":["lcov"],"slowTestThreshold":10},"main":"./dist/index.js","type":"commonjs","types":"./dist/index.d.ts","module":"./dist/index.mjs","source":"./src/index.ts","engines":{"node":">=12"},"exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","source":"./src/index.ts","default":"./dist/index.mjs","require":"./dist/index.js"}},"gitHead":"656ecbcaf0397018367cab1451dbbc12e6010d66","scripts":{"lint":"eslint . && tsc --noEmit","test":"jest","build":"pkg-utils build --tsconfig tsconfig.dist.json","posttest":"npm run lint","prebuild":"rimraf dist coverage","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.18.0","description":"Streaming, source-agnostic EventSource/Server-Sent Events parser","directories":{},"sideEffects":false,"_nodeVersion":"16.16.0","eslintConfig":{"extends":["sanity","sanity/typescript","prettier"],"parserOptions":{"sourceType":"module","ecmaVersion":9,"ecmaFeatures":{"modules":true}},"ignorePatterns":["lib/**/"]},"_hasShrinkwrap":false,"devDependencies":{"jest":"^28.1.0","eslint":"^7.32.0","rimraf":"^3.0.2","ts-jest":"^28.0.2","prettier":"^2.5.1","typescript":"^4.5.4","@types/jest":"^27.5.1","@types/node":"^12.0.0","@sanity/pkg-utils":"^1.9.0","eslint-config-sanity":"^5.1.0","eslint-config-prettier":"^8.3.0","@typescript-eslint/parser":"^5.7.0","@typescript-eslint/eslint-plugin":"^5.7.0"},"_npmOperationalInternal":{"tmp":"tmp/eventsource-parser_0.0.4_1664756559952_0.35273163070038005","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":1664756560240,"_cnpm_publish_time":1664756560240,"dist-tags":{"beta":"3.0.0-beta.0","latest":"4.1.3"}}