@fastify/sse 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1,9 +1,240 @@
1
1
  'use strict'
2
2
 
3
3
  const fp = require('fastify-plugin')
4
+ const createError = require('@fastify/error')
4
5
  const { Readable, Transform } = require('stream')
5
6
  const { pipeline } = require('stream/promises')
6
7
 
8
+ const FST_ERR_SSE_UNKNOWN_KIND = createError(
9
+ 'FST_ERR_SSE_UNKNOWN_KIND',
10
+ "@fastify/sse: unknown sse kind '%s'. Use 'only' (SSE-only route), 'dual' (route serves both SSE and non-SSE), 'manual' (handler decides at runtime, no Accept negotiation), or omit for back-compat."
11
+ )
12
+
13
+ const FST_ERR_SSE_INVALID_OPTION = createError(
14
+ 'FST_ERR_SSE_INVALID_OPTION',
15
+ "@fastify/sse: unsupported value for route option 'sse': %s. Use true, 'dual', 'only', 'manual', or an options object."
16
+ )
17
+
18
+ const FST_ERR_SSE_LEGACY_MISUSE = createError(
19
+ 'FST_ERR_SSE_LEGACY_MISUSE',
20
+ "@fastify/sse: route registered with { sse: true } received Accept '%s' (no explicit 'text/event-stream') " +
21
+ 'and the handler then tried to use reply.sse. If this route only serves SSE, ' +
22
+ "register it with { sse: 'only' } so ambiguous Accept headers admit SSE per " +
23
+ 'RFC 9110. If it serves both SSE and a non-SSE representation, register with ' +
24
+ "{ sse: 'dual' } and branch on the Accept header in the handler. " +
25
+ '(Underlying error: %s)'
26
+ )
27
+
28
+ const FST_ERR_SSE_CONNECTION_CLOSED = createError(
29
+ 'FST_ERR_SSE_CONNECTION_CLOSED',
30
+ 'SSE connection is closed'
31
+ )
32
+
33
+ // Character codes used by the Accept-header scanner. Hoisted to module scope
34
+ // so V8 treats them as constants and the tight loops below stay monomorphic.
35
+ const CC_SP = 32
36
+ const CC_HT = 9
37
+ const CC_COMMA = 44
38
+ const CC_SEMI = 59
39
+ const CC_EQ = 61
40
+ const CC_DOT = 46
41
+ const CC_ZERO = 48
42
+ const CC_LOWER_Q = 113
43
+ const CC_UPPER_Q = 81
44
+
45
+ function ciEqualsAt (s, start, end, lower) {
46
+ if (end - start !== lower.length) return false
47
+ for (let j = 0; j < lower.length; j++) {
48
+ let c = s.charCodeAt(start + j)
49
+ if (c >= 65 && c <= 90) c |= 32
50
+ if (c !== lower.charCodeAt(j)) return false
51
+ }
52
+ return true
53
+ }
54
+
55
+ function isQValueZero (s, start, end) {
56
+ if (end <= start) return false
57
+ if (s.charCodeAt(start) !== CC_ZERO) return false
58
+ let i = start + 1
59
+ if (i < end && s.charCodeAt(i) === CC_DOT) {
60
+ i++
61
+ while (i < end) {
62
+ if (s.charCodeAt(i) !== CC_ZERO) return false
63
+ i++
64
+ }
65
+ }
66
+ return i === end
67
+ }
68
+
69
+ /**
70
+ * Determine whether the client's Accept header admits `text/event-stream`.
71
+ *
72
+ * Implements the RFC 9110 §12.5.1 precedence model for the media ranges that
73
+ * are relevant to SSE — `text/event-stream`, `text/*`, and `*\/*`. Other
74
+ * media-type parameters are ignored; only the `q` parameter is honored, and
75
+ * only the binary distinction `q=0` (explicit refuse) vs `q>0` (admit) is
76
+ * preserved. Fractional qvalues like `q=0.5` are treated identically to
77
+ * `q=1`: observably equivalent here because the function picks the winning
78
+ * media range by specificity, not by comparing fractional qvalues.
79
+ *
80
+ * Default (lenient) returns true when the header is missing, empty, or
81
+ * contains a matching range with quality > 0. The most specific matching
82
+ * range wins, so `*\/*, text/event-stream;q=0` correctly returns false.
83
+ *
84
+ * Pass `{ strict: true }` to require an explicit `text/event-stream` token
85
+ * with quality > 0; ambiguous headers (`*\/*`, `text/*`, missing) return
86
+ * false in strict mode.
87
+ *
88
+ * Hot paths (`text/event-stream`, `*\/*`, `text/*`) short-circuit before any
89
+ * scanning, so the common case is a single string-equality compare.
90
+ *
91
+ * @param {string|undefined} acceptHeader
92
+ * @param {{ strict?: boolean }} [options]
93
+ * @returns {boolean}
94
+ */
95
+ function clientAcceptsSSE (acceptHeader, options) {
96
+ const strict = options !== undefined && options.strict === true
97
+ if (!acceptHeader) return !strict
98
+
99
+ // Hot path: the literal values that EventSource and common HTTP clients
100
+ // actually emit. Caught with a single ===, no allocation.
101
+ if (acceptHeader === 'text/event-stream') return true
102
+ if (!strict && (acceptHeader === '*/*' || acceptHeader === 'text/*')) return true
103
+
104
+ // Slow path: walk the header in place via charCodeAt. No .split(),
105
+ // no .toLowerCase(), no .trim(), no substrings allocated.
106
+ const len = acceptHeader.length
107
+ let bestSpec = -1
108
+ let bestRefused = false
109
+ let i = 0
110
+
111
+ while (i < len) {
112
+ while (i < len) {
113
+ const c = acceptHeader.charCodeAt(i)
114
+ if (c !== CC_SP && c !== CC_HT) break
115
+ i++
116
+ }
117
+
118
+ const typeStart = i
119
+ while (i < len) {
120
+ const c = acceptHeader.charCodeAt(i)
121
+ if (c === CC_SEMI || c === CC_COMMA) break
122
+ i++
123
+ }
124
+ let typeEnd = i
125
+ while (typeEnd > typeStart) {
126
+ const c = acceptHeader.charCodeAt(typeEnd - 1)
127
+ if (c !== CC_SP && c !== CC_HT) break
128
+ typeEnd--
129
+ }
130
+
131
+ let spec = -1
132
+ if (ciEqualsAt(acceptHeader, typeStart, typeEnd, 'text/event-stream')) spec = 3
133
+ else if (!strict && ciEqualsAt(acceptHeader, typeStart, typeEnd, 'text/*')) spec = 2
134
+ else if (!strict && ciEqualsAt(acceptHeader, typeStart, typeEnd, '*/*')) spec = 1
135
+
136
+ let refused = false
137
+ if (spec === -1) {
138
+ // Non-matching entry: skip its parameters in one jump.
139
+ while (i < len && acceptHeader.charCodeAt(i) !== CC_COMMA) i++
140
+ } else {
141
+ // Spec note: per RFC 9110 §5.6.6, `parameter = parameter-name "="
142
+ // parameter-value` permits no OWS inside the parameter — only around
143
+ // the `;` separator. We honor the OWS-around-`;` case (which browsers
144
+ // emit as `; q=0.8`) but do not handle OWS adjacent to `=` or
145
+ // trailing OWS on the value/key (which would be malformed input
146
+ // anyway). Node's HTTP parser also strips leading + trailing OWS
147
+ // from the whole header value, so the only WS we see in production
148
+ // is OWS after `,` and after `;`.
149
+ while (i < len && acceptHeader.charCodeAt(i) === CC_SEMI) {
150
+ i++
151
+ while (i < len) {
152
+ const c = acceptHeader.charCodeAt(i)
153
+ if (c !== CC_SP && c !== CC_HT) break
154
+ i++
155
+ }
156
+ const keyStart = i
157
+ while (i < len) {
158
+ const c = acceptHeader.charCodeAt(i)
159
+ if (c === CC_EQ || c === CC_SEMI || c === CC_COMMA) break
160
+ i++
161
+ }
162
+ const keyEnd = i
163
+
164
+ if (i < len && acceptHeader.charCodeAt(i) === CC_EQ) {
165
+ i++
166
+ const valStart = i
167
+ while (i < len) {
168
+ const c = acceptHeader.charCodeAt(i)
169
+ if (c === CC_SEMI || c === CC_COMMA) break
170
+ i++
171
+ }
172
+ const valEnd = i
173
+
174
+ if (keyEnd - keyStart === 1) {
175
+ const kc = acceptHeader.charCodeAt(keyStart)
176
+ if ((kc === CC_LOWER_Q || kc === CC_UPPER_Q) &&
177
+ isQValueZero(acceptHeader, valStart, valEnd)) {
178
+ refused = true
179
+ }
180
+ }
181
+ }
182
+ }
183
+ }
184
+
185
+ // text/event-stream with a non-refused qvalue has the maximum
186
+ // specificity; nothing later in the list can outrank it.
187
+ if (spec === 3 && !refused) return true
188
+
189
+ if (spec > bestSpec) {
190
+ bestSpec = spec
191
+ bestRefused = refused
192
+ }
193
+
194
+ if (i < len && acceptHeader.charCodeAt(i) === CC_COMMA) i++
195
+ }
196
+
197
+ return bestSpec >= 0 && !bestRefused
198
+ }
199
+
200
+ /**
201
+ * Resolve the `sse` field on route options into a normalized shape.
202
+ *
203
+ * - `sse: true` → kind 'legacy' (back-compat, strict gate + clearer
204
+ * error if the handler tries to use reply.sse on the
205
+ * fallback path)
206
+ * - `sse: 'dual'` → kind 'dual' (explicit dual-mode: strict gate, the
207
+ * handler is expected to serve a non-SSE response when
208
+ * reply.sse is undefined)
209
+ * - `sse: 'only'` → kind 'only' (SSE-only: lenient gate, returns 406
210
+ * Not Acceptable to clients that explicitly refuse SSE)
211
+ * - `sse: 'manual'` → kind 'manual' (no Accept negotiation: `reply.sse` is
212
+ * always attached and the handler decides at runtime
213
+ * whether to stream — by calling `reply.sse.*` — or to
214
+ * return a normal response. The connection is closed
215
+ * automatically when the handler resolves or throws.)
216
+ * - `sse: { ... }` → object form; same kinds via
217
+ * `kind: 'dual' | 'only' | 'manual'`, or `kind` omitted
218
+ * = 'legacy' for back-compat with existing
219
+ * `{ heartbeat, serializer, ... }` shapes
220
+ */
221
+ function resolveSSEConfig (sseField) {
222
+ if (sseField === true) return { kind: 'legacy', options: {} }
223
+ if (sseField === 'dual') return { kind: 'dual', options: {} }
224
+ if (sseField === 'only') return { kind: 'only', options: {} }
225
+ if (sseField === 'manual') return { kind: 'manual', options: {} }
226
+ if (typeof sseField === 'object' && sseField !== null) {
227
+ const kind = sseField.kind ?? 'legacy'
228
+ if (kind !== 'legacy' && kind !== 'dual' && kind !== 'only' && kind !== 'manual') {
229
+ throw new FST_ERR_SSE_UNKNOWN_KIND(kind)
230
+ }
231
+ return { kind, options: sseField }
232
+ }
233
+ throw new FST_ERR_SSE_INVALID_OPTION(JSON.stringify(sseField))
234
+ }
235
+
236
+ const MISSING_SSE_ERROR_PATTERN = /Cannot read prop(?:erties)? of undefined.*'(?:send|stream|keepAlive|close|sendHeaders|replay|onClose)'/
237
+
7
238
  /**
8
239
  * Format an SSE message according to the specification
9
240
  * @param {Object|string|Buffer} message - The message to format
@@ -93,6 +324,7 @@ class SSEContext {
93
324
  this.#keepAlive = false
94
325
  this.#headersSent = false
95
326
  this.heartbeatTimer = null
327
+ this.heartbeatInterval = options.heartbeatInterval
96
328
  this.closeCallbacks = []
97
329
  this.serializer = options.serializer
98
330
 
@@ -110,11 +342,6 @@ class SSEContext {
110
342
  // Log as info since client disconnections are normal
111
343
  this.reply.log.info({ err: error }, 'SSE connection closed')
112
344
  })
113
-
114
- // Start heartbeat if enabled
115
- if (options.heartbeatInterval > 0) {
116
- this.startHeartbeat(options.heartbeatInterval)
117
- }
118
345
  }
119
346
 
120
347
  /**
@@ -152,13 +379,19 @@ class SSEContext {
152
379
  /**
153
380
  * Closes the SSE connection and performs cleanup.
154
381
  * Safe to call multiple times.
382
+ *
383
+ * If no SSE data was ever written (i.e., headers were never committed as
384
+ * SSE), the raw response is left open so Fastify can serialize the
385
+ * handler's return value normally.
155
386
  */
156
387
  close () {
157
388
  if (!this.#isConnected) return
158
389
 
159
390
  this.#isConnected = false
160
391
  this.cleanup()
161
- this.reply.raw.end()
392
+ if (this.#headersSent) {
393
+ this.reply.raw.end()
394
+ }
162
395
  }
163
396
 
164
397
  /**
@@ -182,14 +415,22 @@ class SSEContext {
182
415
 
183
416
  /**
184
417
  * Sends HTTP headers for the SSE response if not already sent.
185
- * This method ensures headers set via reply.header() are transferred
186
- * to the raw response before calling writeHead(200).
187
- * Called automatically before the first SSE data is sent, but can
188
- * also be called manually if needed.
418
+ * Applies the SSE-specific response headers, transfers any headers set
419
+ * via reply.header(), and calls writeHead(200). Called automatically
420
+ * before the first SSE data is sent, but can also be called manually.
421
+ *
422
+ * Until this fires, the response is not yet committed as SSE — a handler
423
+ * that never writes SSE data will return through Fastify's normal
424
+ * serialization path.
189
425
  */
190
426
  sendHeaders () {
191
427
  if (!this.#headersSent) {
192
- // Get any headers set via reply.header() and transfer to raw response
428
+ this.reply.raw.setHeader('Content-Type', 'text/event-stream')
429
+ this.reply.raw.setHeader('Cache-Control', 'no-cache')
430
+ this.reply.raw.setHeader('Connection', 'keep-alive')
431
+ this.reply.raw.setHeader('X-Accel-Buffering', 'no') // Disable Nginx buffering
432
+
433
+ // Transfer headers set via reply.header() to the raw response
193
434
  const replyHeaders = this.reply.getHeaders()
194
435
  for (const [name, value] of Object.entries(replyHeaders)) {
195
436
  this.reply.raw.setHeader(name, value)
@@ -197,6 +438,15 @@ class SSEContext {
197
438
 
198
439
  this.reply.raw.writeHead(200)
199
440
  this.#headersSent = true
441
+
442
+ // Start the heartbeat only once the response is committed as SSE.
443
+ // Deferring it until here means a handler that decorates reply.sse
444
+ // but ultimately returns a non-SSE response (e.g. a 'manual' route
445
+ // that branches on the request body) is never interrupted by a
446
+ // heartbeat write corrupting its payload.
447
+ if (this.heartbeatInterval > 0) {
448
+ this.startHeartbeat(this.heartbeatInterval)
449
+ }
200
450
  }
201
451
  }
202
452
 
@@ -208,7 +458,7 @@ class SSEContext {
208
458
  */
209
459
  async send (source) {
210
460
  if (!this.#isConnected) {
211
- throw new Error('SSE connection is closed')
461
+ throw new FST_ERR_SSE_CONNECTION_CLOSED()
212
462
  }
213
463
 
214
464
  // Handle single message
@@ -260,7 +510,7 @@ class SSEContext {
260
510
  */
261
511
  stream () {
262
512
  if (!this.#isConnected) {
263
- throw new Error('SSE connection is closed')
513
+ throw new FST_ERR_SSE_CONNECTION_CLOSED()
264
514
  }
265
515
 
266
516
  const transform = createSSETransformStream({ serializer: this.serializer })
@@ -402,24 +652,58 @@ async function fastifySSE (fastify, opts) {
402
652
  fastify.addHook('onRoute', (routeOptions) => {
403
653
  if (!routeOptions.sse) return
404
654
 
655
+ const { kind, options: sseOptions } = resolveSSEConfig(routeOptions.sse)
405
656
  const originalHandler = routeOptions.handler
406
- const sseOptions = typeof routeOptions.sse === 'object' ? routeOptions.sse : {}
407
657
 
408
658
  routeOptions.handler = async function sseHandler (request, reply) {
409
- // Check if client accepts SSE
410
- const acceptHeader = request.headers.accept || ''
411
- if (!acceptHeader.includes('text/event-stream')) {
412
- // Fall back to regular handler for non-SSE requests
413
- return await originalHandler.call(this, request, reply)
659
+ const acceptHeader = request.headers.accept
660
+
661
+ // Kind-specific gate.
662
+ // 'only' — SSE-only route. Lenient gate: any spec-compliant Accept
663
+ // admits SSE. Clients that explicitly refuse SSE get 406.
664
+ // 'dual' — Route serves both SSE and non-SSE on the same handler.
665
+ // Strict gate: only an explicit `text/event-stream` token
666
+ // admits SSE; everything else falls through to the
667
+ // handler, which is expected to serve a non-SSE response.
668
+ // 'legacy' — `sse: true` back-compat. Same routing as 'dual'. If
669
+ // the fallback handler then tries to use `reply.sse`
670
+ // (which is undefined because the gate refused), the
671
+ // plugin rethrows with a message that names
672
+ // `sse: 'only'` as the likely fix.
673
+ // 'manual' — No Accept negotiation at all. `reply.sse` is always
674
+ // attached and the handler decides at runtime whether to
675
+ // stream. This supports clients (OpenAI-style streaming
676
+ // APIs and other LLM endpoints) that signal streaming via
677
+ // the request body rather than the Accept header.
678
+ if (kind === 'only') {
679
+ if (!clientAcceptsSSE(acceptHeader)) {
680
+ return reply.code(406).type('application/json').send({
681
+ statusCode: 406,
682
+ error: 'Not Acceptable',
683
+ message: "This endpoint only produces 'text/event-stream'."
684
+ })
685
+ }
686
+ // Fall through to SSE setup.
687
+ } else if (kind === 'dual' || kind === 'legacy') {
688
+ if (!clientAcceptsSSE(acceptHeader, { strict: true })) {
689
+ if (kind === 'legacy') {
690
+ try {
691
+ return await originalHandler.call(this, request, reply)
692
+ } catch (err) {
693
+ if (err instanceof TypeError && MISSING_SSE_ERROR_PATTERN.test(err.message)) {
694
+ throw new FST_ERR_SSE_LEGACY_MISUSE(acceptHeader || '<missing>', err.message)
695
+ }
696
+ throw err
697
+ }
698
+ }
699
+ // 'dual' — handler intentionally handles the fallback.
700
+ return await originalHandler.call(this, request, reply)
701
+ }
702
+ // Fall through to SSE setup.
414
703
  }
704
+ // 'manual' — skip negotiation entirely and fall through to SSE setup.
415
705
 
416
- // Set up SSE response
417
- reply.raw.setHeader('Content-Type', 'text/event-stream')
418
- reply.raw.setHeader('Cache-Control', 'no-cache')
419
- reply.raw.setHeader('Connection', 'keep-alive')
420
- reply.raw.setHeader('X-Accel-Buffering', 'no') // Disable Nginx buffering
421
-
422
- // Create SSE context
706
+ // Set up SSE context. Headers are written lazily on the first send.
423
707
  const context = new SSEContext({
424
708
  reply,
425
709
  lastEventId: request.headers['last-event-id'],
@@ -431,19 +715,15 @@ async function fastifySSE (fastify, opts) {
431
715
  reply.sse = context
432
716
 
433
717
  let res
434
- // Call original handler with SSE-enabled reply
435
- // Note: Headers will be sent on first SSE send
436
718
  try {
437
719
  res = await originalHandler.call(this, request, reply)
438
720
  } catch (error) {
439
- // If handler doesn't call keepAlive, close connection
440
721
  if (!context.shouldKeepAlive) {
441
722
  context.close()
442
723
  }
443
724
  throw error
444
725
  }
445
726
 
446
- // If handler doesn't call keepAlive, close connection
447
727
  if (!context.shouldKeepAlive) {
448
728
  context.close()
449
729
  }
@@ -457,3 +737,5 @@ module.exports = fp(fastifySSE, {
457
737
  fastify: '5.x',
458
738
  name: '@fastify/sse'
459
739
  })
740
+ module.exports.default = fastifySSE
741
+ module.exports.fastifySSE = fastifySSE
package/package.json CHANGED
@@ -1,18 +1,17 @@
1
1
  {
2
2
  "name": "@fastify/sse",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Server-Sent Events plugin for Fastify",
5
5
  "main": "index.js",
6
6
  "types": "types/index.d.ts",
7
7
  "scripts": {
8
- "test": "node --test",
9
- "test:types": "tsd",
8
+ "test": "npm run test:unit && npm run test:typescript && npm run test:attw",
9
+ "test:unit": "node --test",
10
+ "test:typescript": "tstyche",
11
+ "test:attw": "attw --pack .",
10
12
  "lint": "eslint .",
11
13
  "lint:fix": "eslint . --fix"
12
14
  },
13
- "tsd": {
14
- "directory": "test-types"
15
- },
16
15
  "keywords": [
17
16
  "fastify",
18
17
  "sse",
@@ -34,18 +33,20 @@
34
33
  "fastify": "^5.x"
35
34
  },
36
35
  "dependencies": {
37
- "fastify-plugin": "^5.0.0"
36
+ "@fastify/error": "^4.2.0",
37
+ "fastify-plugin": "^6.0.0"
38
38
  },
39
39
  "devDependencies": {
40
- "@types/node": "^24.3.0",
40
+ "@arethetypeswrong/cli": "^0.18.2",
41
+ "@types/node": "^26.0.0",
41
42
  "eslint": "^9.0.0",
42
43
  "fastify": "^5.0.0",
43
- "neostandard": "^0.12.2",
44
- "tsd": "^0.33.0",
45
- "typescript": "^5.9.2",
44
+ "neostandard": "^0.13.0",
45
+ "tstyche": "^7.1.0",
46
+ "typescript": "~6.0.2",
46
47
  "undici": "^7.15.0"
47
48
  },
48
49
  "engines": {
49
- "node": ">=20"
50
+ "node": ">=20.20.2"
50
51
  }
51
52
  }