@fastify/sse 0.1.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/.claude/settings.local.json +9 -0
- package/.gitattributes +2 -0
- package/.github/.stale.yml +21 -0
- package/.github/dependabot.yml +13 -0
- package/.github/tests_checker.yml +8 -0
- package/.github/workflows/ci.yml +28 -0
- package/.github/workflows/package-manager-ci.yml +24 -0
- package/.prettierignore +1 -0
- package/README.md +391 -0
- package/docs/.gitkeep +0 -0
- package/eslint.config.js +3 -0
- package/examples/.gitkeep +0 -0
- package/examples/basic.js +121 -0
- package/index.js +342 -0
- package/package.json +50 -0
- package/test/.gitkeep +0 -0
- package/test/basic.test.js +311 -0
- package/test/lifecycle.test.js +197 -0
- package/test-types/index.test-d.ts +192 -0
- package/types/.gitkeep +0 -0
- package/types/index.d.ts +105 -0
package/index.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin')
|
|
4
|
+
const { Readable, Transform } = require('stream')
|
|
5
|
+
const { pipeline } = require('stream/promises')
|
|
6
|
+
|
|
7
|
+
const SSE_DECORATOR = Symbol.for('@fastify/sse.decorator')
|
|
8
|
+
const SSE_CONTEXT = Symbol.for('@fastify/sse.context')
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Format an SSE message according to the specification
|
|
12
|
+
* @param {Object|string|Buffer} message - The message to format
|
|
13
|
+
* @param {Function} serializer - Function to serialize data
|
|
14
|
+
* @returns {string} Formatted SSE message
|
|
15
|
+
*/
|
|
16
|
+
function formatSSEMessage (message, serializer) {
|
|
17
|
+
let payload = ''
|
|
18
|
+
|
|
19
|
+
if (typeof message === 'string') {
|
|
20
|
+
// Plain string message
|
|
21
|
+
for (const line of message.split('\n')) {
|
|
22
|
+
payload += `data: ${line}\n`
|
|
23
|
+
}
|
|
24
|
+
} else if (Buffer.isBuffer(message)) {
|
|
25
|
+
// Buffer message
|
|
26
|
+
const str = message.toString('utf-8')
|
|
27
|
+
for (const line of str.split('\n')) {
|
|
28
|
+
payload += `data: ${line}\n`
|
|
29
|
+
}
|
|
30
|
+
} else {
|
|
31
|
+
// SSEMessage object
|
|
32
|
+
if (message.id) {
|
|
33
|
+
payload += `id: ${message.id}\n`
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (message.event) {
|
|
37
|
+
payload += `event: ${message.event}\n`
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (message.data !== undefined) {
|
|
41
|
+
// Always serialize the data to ensure consistent format
|
|
42
|
+
const dataStr = serializer(message.data)
|
|
43
|
+
|
|
44
|
+
for (const line of dataStr.split('\n')) {
|
|
45
|
+
payload += `data: ${line}\n`
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (message.retry) {
|
|
50
|
+
payload += `retry: ${message.retry}\n`
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Add trailing newline to separate events
|
|
55
|
+
if (payload) {
|
|
56
|
+
payload += '\n'
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return payload
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Create a transform stream that converts objects to SSE format
|
|
64
|
+
* @param {Object} options - Transform options
|
|
65
|
+
* @returns {Transform} Transform stream
|
|
66
|
+
*/
|
|
67
|
+
function createSSETransformStream (options = {}) {
|
|
68
|
+
const { serializer = JSON.stringify } = options
|
|
69
|
+
|
|
70
|
+
return new Transform({
|
|
71
|
+
objectMode: true,
|
|
72
|
+
transform (chunk, encoding, callback) {
|
|
73
|
+
try {
|
|
74
|
+
const formatted = formatSSEMessage(chunk, serializer)
|
|
75
|
+
callback(null, formatted)
|
|
76
|
+
} catch (error) {
|
|
77
|
+
callback(error)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* SSE Context class for managing connection state
|
|
85
|
+
*/
|
|
86
|
+
class SSEContext {
|
|
87
|
+
constructor (options) {
|
|
88
|
+
this.reply = options.reply
|
|
89
|
+
this._lastEventId = options.lastEventId || null
|
|
90
|
+
this._isConnected = true
|
|
91
|
+
this._keepAlive = false
|
|
92
|
+
this.heartbeatTimer = null
|
|
93
|
+
this.closeCallbacks = []
|
|
94
|
+
this.serializer = options.serializer
|
|
95
|
+
|
|
96
|
+
// Set up connection close handler
|
|
97
|
+
this.reply.raw.on('close', () => {
|
|
98
|
+
this._isConnected = false
|
|
99
|
+
this.cleanup()
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
// Start heartbeat if enabled
|
|
103
|
+
if (options.heartbeatInterval > 0) {
|
|
104
|
+
this.startHeartbeat(options.heartbeatInterval)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
get lastEventId () {
|
|
109
|
+
return this._lastEventId
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
get isConnected () {
|
|
113
|
+
return this._isConnected
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
keepAlive () {
|
|
117
|
+
this._keepAlive = true
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
close () {
|
|
121
|
+
if (!this._isConnected) return
|
|
122
|
+
|
|
123
|
+
this._isConnected = false
|
|
124
|
+
this.cleanup()
|
|
125
|
+
this.reply.raw.end()
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
onClose (callback) {
|
|
129
|
+
this.closeCallbacks.push(callback)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async replay (callback) {
|
|
133
|
+
if (!this._lastEventId) return
|
|
134
|
+
|
|
135
|
+
await callback(this._lastEventId)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async send (source) {
|
|
139
|
+
if (!this._isConnected) {
|
|
140
|
+
throw new Error('SSE connection is closed')
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Handle single message
|
|
144
|
+
if (typeof source === 'string' || Buffer.isBuffer(source) || this.isSSEMessage(source)) {
|
|
145
|
+
const formatted = formatSSEMessage(source, this.serializer)
|
|
146
|
+
await this.writeToStream(formatted)
|
|
147
|
+
return
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Handle Readable stream
|
|
151
|
+
if (source instanceof Readable) {
|
|
152
|
+
const transform = createSSETransformStream({ serializer: this.serializer })
|
|
153
|
+
await pipeline(source, transform, this.reply.raw, { end: false })
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Handle AsyncIterable
|
|
158
|
+
if (this.isAsyncIterable(source)) {
|
|
159
|
+
for await (const chunk of source) {
|
|
160
|
+
if (!this._isConnected) break
|
|
161
|
+
const formatted = formatSSEMessage(chunk, this.serializer)
|
|
162
|
+
await this.writeToStream(formatted)
|
|
163
|
+
}
|
|
164
|
+
return
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
throw new TypeError('Invalid SSE source type')
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
stream () {
|
|
171
|
+
if (!this._isConnected) {
|
|
172
|
+
throw new Error('SSE connection is closed')
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return createSSETransformStream({ serializer: this.serializer })
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
writeToStream (data) {
|
|
179
|
+
return new Promise((resolve, reject) => {
|
|
180
|
+
if (!this._isConnected) {
|
|
181
|
+
reject(new Error('SSE connection is closed'))
|
|
182
|
+
return
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const canWrite = this.reply.raw.write(data)
|
|
186
|
+
|
|
187
|
+
if (canWrite) {
|
|
188
|
+
resolve()
|
|
189
|
+
} else {
|
|
190
|
+
// Handle backpressure
|
|
191
|
+
const onDrain = () => {
|
|
192
|
+
this.reply.raw.off('error', onError)
|
|
193
|
+
resolve()
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const onError = (err) => {
|
|
197
|
+
this.reply.raw.off('drain', onDrain)
|
|
198
|
+
reject(err)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
this.reply.raw.once('drain', onDrain)
|
|
202
|
+
this.reply.raw.once('error', onError)
|
|
203
|
+
}
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
startHeartbeat (interval) {
|
|
208
|
+
this.heartbeatTimer = setInterval(() => {
|
|
209
|
+
if (this._isConnected) {
|
|
210
|
+
this.reply.raw.write(': heartbeat\n\n')
|
|
211
|
+
} else {
|
|
212
|
+
this.stopHeartbeat()
|
|
213
|
+
}
|
|
214
|
+
}, interval)
|
|
215
|
+
|
|
216
|
+
// Ensure timer doesn't keep process alive
|
|
217
|
+
this.heartbeatTimer.unref()
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
stopHeartbeat () {
|
|
221
|
+
if (this.heartbeatTimer) {
|
|
222
|
+
clearInterval(this.heartbeatTimer)
|
|
223
|
+
this.heartbeatTimer = null
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
cleanup () {
|
|
228
|
+
this.stopHeartbeat()
|
|
229
|
+
|
|
230
|
+
// Call all close callbacks
|
|
231
|
+
for (const callback of this.closeCallbacks) {
|
|
232
|
+
try {
|
|
233
|
+
callback()
|
|
234
|
+
} catch (error) {
|
|
235
|
+
// Log error but don't throw
|
|
236
|
+
console.error('Error in SSE close callback:', error)
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
this.closeCallbacks = []
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
isSSEMessage (value) {
|
|
244
|
+
return typeof value === 'object' &&
|
|
245
|
+
value !== null &&
|
|
246
|
+
'data' in value
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
isAsyncIterable (value) {
|
|
250
|
+
return value != null &&
|
|
251
|
+
typeof value[Symbol.asyncIterator] === 'function'
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function fastifySSE (fastify, opts) {
|
|
256
|
+
const {
|
|
257
|
+
heartbeatInterval = 30000,
|
|
258
|
+
serializer = JSON.stringify
|
|
259
|
+
} = opts
|
|
260
|
+
|
|
261
|
+
// Add route-level SSE handler
|
|
262
|
+
fastify.addHook('onRoute', (routeOptions) => {
|
|
263
|
+
if (!routeOptions.sse) return
|
|
264
|
+
|
|
265
|
+
const originalHandler = routeOptions.handler
|
|
266
|
+
const sseOptions = typeof routeOptions.sse === 'object' ? routeOptions.sse : {}
|
|
267
|
+
|
|
268
|
+
routeOptions.handler = async function sseHandler (request, reply) {
|
|
269
|
+
// Check if client accepts SSE
|
|
270
|
+
const acceptHeader = request.headers.accept || ''
|
|
271
|
+
if (!acceptHeader.includes('text/event-stream')) {
|
|
272
|
+
// Fall back to regular handler for non-SSE requests
|
|
273
|
+
return await originalHandler.call(this, request, reply)
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Set up SSE response
|
|
277
|
+
reply.raw.setHeader('Content-Type', 'text/event-stream')
|
|
278
|
+
reply.raw.setHeader('Cache-Control', 'no-cache')
|
|
279
|
+
reply.raw.setHeader('Connection', 'keep-alive')
|
|
280
|
+
reply.raw.setHeader('X-Accel-Buffering', 'no') // Disable Nginx buffering
|
|
281
|
+
|
|
282
|
+
// Create SSE context
|
|
283
|
+
const context = new SSEContext({
|
|
284
|
+
reply,
|
|
285
|
+
lastEventId: request.headers['last-event-id'],
|
|
286
|
+
heartbeatInterval: sseOptions.heartbeat !== false ? heartbeatInterval : 0,
|
|
287
|
+
serializer: sseOptions.serializer || serializer
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
// Store context on reply
|
|
291
|
+
reply[SSE_CONTEXT] = context
|
|
292
|
+
|
|
293
|
+
// Decorate reply with SSE interface
|
|
294
|
+
const sseInterface = {}
|
|
295
|
+
|
|
296
|
+
// Add SSE methods
|
|
297
|
+
Object.defineProperty(sseInterface, 'lastEventId', {
|
|
298
|
+
get: () => context.lastEventId
|
|
299
|
+
})
|
|
300
|
+
|
|
301
|
+
sseInterface.send = (source) => context.send(source)
|
|
302
|
+
sseInterface.stream = () => context.stream()
|
|
303
|
+
sseInterface.keepAlive = () => context.keepAlive()
|
|
304
|
+
sseInterface.close = () => context.close()
|
|
305
|
+
sseInterface.replay = (callback) => context.replay(callback)
|
|
306
|
+
sseInterface.onClose = (callback) => context.onClose(callback)
|
|
307
|
+
|
|
308
|
+
Object.defineProperty(sseInterface, 'isConnected', {
|
|
309
|
+
get: () => context.isConnected
|
|
310
|
+
})
|
|
311
|
+
|
|
312
|
+
reply[SSE_DECORATOR] = sseInterface
|
|
313
|
+
Object.defineProperty(reply, 'sse', {
|
|
314
|
+
get () { return this[SSE_DECORATOR] }
|
|
315
|
+
})
|
|
316
|
+
|
|
317
|
+
// Send 200 OK
|
|
318
|
+
reply.raw.writeHead(200)
|
|
319
|
+
|
|
320
|
+
// Call original handler with SSE-enabled reply
|
|
321
|
+
try {
|
|
322
|
+
await originalHandler.call(this, request, reply)
|
|
323
|
+
} catch (error) {
|
|
324
|
+
// If handler doesn't call keepAlive, close connection
|
|
325
|
+
if (!reply[SSE_CONTEXT]?._keepAlive) {
|
|
326
|
+
reply[SSE_CONTEXT]?.close()
|
|
327
|
+
}
|
|
328
|
+
throw error
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// If handler doesn't call keepAlive, close connection
|
|
332
|
+
if (!reply[SSE_CONTEXT]?._keepAlive) {
|
|
333
|
+
reply[SSE_CONTEXT]?.close()
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
})
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
module.exports = fp(fastifySSE, {
|
|
340
|
+
fastify: '5.x',
|
|
341
|
+
name: '@fastify/sse'
|
|
342
|
+
})
|
package/package.json
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@fastify/sse",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Server-Sent Events plugin for Fastify",
|
|
5
|
+
"main": "index.js",
|
|
6
|
+
"types": "types/index.d.ts",
|
|
7
|
+
"scripts": {
|
|
8
|
+
"test": "node --test",
|
|
9
|
+
"test:types": "tsd",
|
|
10
|
+
"lint": "eslint .",
|
|
11
|
+
"lint:fix": "eslint . --fix"
|
|
12
|
+
},
|
|
13
|
+
"tsd": {
|
|
14
|
+
"directory": "test-types"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"fastify",
|
|
18
|
+
"sse",
|
|
19
|
+
"server-sent-events",
|
|
20
|
+
"streaming",
|
|
21
|
+
"real-time"
|
|
22
|
+
],
|
|
23
|
+
"author": "Fastify Team",
|
|
24
|
+
"license": "MIT",
|
|
25
|
+
"repository": {
|
|
26
|
+
"type": "git",
|
|
27
|
+
"url": "https://github.com/fastify/fastify-sse.git"
|
|
28
|
+
},
|
|
29
|
+
"bugs": {
|
|
30
|
+
"url": "https://github.com/fastify/fastify-sse/issues"
|
|
31
|
+
},
|
|
32
|
+
"homepage": "https://github.com/fastify/fastify-sse#readme",
|
|
33
|
+
"peerDependencies": {
|
|
34
|
+
"fastify": "^5.x"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"fastify-plugin": "^5.0.0"
|
|
38
|
+
},
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@types/node": "^24.3.0",
|
|
41
|
+
"eslint": "^9.0.0",
|
|
42
|
+
"fastify": "^5.0.0",
|
|
43
|
+
"neostandard": "^0.11.0",
|
|
44
|
+
"tsd": "^0.33.0",
|
|
45
|
+
"typescript": "^5.9.2"
|
|
46
|
+
},
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=18.0.0"
|
|
49
|
+
}
|
|
50
|
+
}
|
package/test/.gitkeep
ADDED
|
File without changes
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const { test } = require('node:test')
|
|
4
|
+
const { strict: assert } = require('node:assert')
|
|
5
|
+
const Fastify = require('fastify')
|
|
6
|
+
const { Readable } = require('stream')
|
|
7
|
+
const fastifySSE = require('../index.js')
|
|
8
|
+
|
|
9
|
+
test('basic SSE functionality', async (t) => {
|
|
10
|
+
const fastify = Fastify({ logger: false })
|
|
11
|
+
|
|
12
|
+
t.after(async () => {
|
|
13
|
+
await fastify.close()
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
await fastify.register(fastifySSE)
|
|
17
|
+
|
|
18
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
19
|
+
await reply.sse.send({ data: 'hello world' })
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
await fastify.listen({ port: 0 })
|
|
23
|
+
|
|
24
|
+
const response = await fastify.inject({
|
|
25
|
+
method: 'GET',
|
|
26
|
+
url: '/events',
|
|
27
|
+
headers: {
|
|
28
|
+
accept: 'text/event-stream'
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
assert.strictEqual(response.statusCode, 200)
|
|
33
|
+
assert.strictEqual(response.headers['content-type'], 'text/event-stream')
|
|
34
|
+
assert.strictEqual(response.headers['cache-control'], 'no-cache')
|
|
35
|
+
assert.strictEqual(response.headers.connection, 'keep-alive')
|
|
36
|
+
|
|
37
|
+
const body = response.body
|
|
38
|
+
assert.ok(body.includes('data: "hello world"'))
|
|
39
|
+
assert.ok(body.endsWith('\n\n'))
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('SSE message formatting', async (t) => {
|
|
43
|
+
const fastify = Fastify({ logger: false })
|
|
44
|
+
|
|
45
|
+
t.after(async () => {
|
|
46
|
+
await fastify.close()
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
await fastify.register(fastifySSE)
|
|
50
|
+
|
|
51
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
52
|
+
await reply.sse.send({
|
|
53
|
+
id: '123',
|
|
54
|
+
event: 'update',
|
|
55
|
+
data: { message: 'test' },
|
|
56
|
+
retry: 1000
|
|
57
|
+
})
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
await fastify.listen({ port: 0 })
|
|
61
|
+
|
|
62
|
+
const response = await fastify.inject({
|
|
63
|
+
method: 'GET',
|
|
64
|
+
url: '/events',
|
|
65
|
+
headers: {
|
|
66
|
+
accept: 'text/event-stream'
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
const body = response.body
|
|
71
|
+
assert.ok(body.includes('id: 123'))
|
|
72
|
+
assert.ok(body.includes('event: update'))
|
|
73
|
+
assert.ok(body.includes('data: {"message":"test"}'))
|
|
74
|
+
assert.ok(body.includes('retry: 1000'))
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('string message support', async (t) => {
|
|
78
|
+
const fastify = Fastify({ logger: false })
|
|
79
|
+
|
|
80
|
+
t.after(async () => {
|
|
81
|
+
await fastify.close()
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
await fastify.register(fastifySSE)
|
|
85
|
+
|
|
86
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
87
|
+
await reply.sse.send('plain text message')
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
await fastify.listen({ port: 0 })
|
|
91
|
+
|
|
92
|
+
const response = await fastify.inject({
|
|
93
|
+
method: 'GET',
|
|
94
|
+
url: '/events',
|
|
95
|
+
headers: {
|
|
96
|
+
accept: 'text/event-stream'
|
|
97
|
+
}
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
const body = response.body
|
|
101
|
+
assert.ok(body.includes('data: plain text message'))
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
test('multiline data handling', async (t) => {
|
|
105
|
+
const fastify = Fastify({ logger: false })
|
|
106
|
+
|
|
107
|
+
t.after(async () => {
|
|
108
|
+
await fastify.close()
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
await fastify.register(fastifySSE)
|
|
112
|
+
|
|
113
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
114
|
+
await reply.sse.send({ data: 'line1\nline2\nline3' })
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
await fastify.listen({ port: 0 })
|
|
118
|
+
|
|
119
|
+
const response = await fastify.inject({
|
|
120
|
+
method: 'GET',
|
|
121
|
+
url: '/events',
|
|
122
|
+
headers: {
|
|
123
|
+
accept: 'text/event-stream'
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
|
|
127
|
+
const body = response.body
|
|
128
|
+
assert.ok(body.includes('data: "line1\\nline2\\nline3"'))
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
test('async generator support', async (t) => {
|
|
132
|
+
const fastify = Fastify({ logger: false })
|
|
133
|
+
|
|
134
|
+
t.after(async () => {
|
|
135
|
+
await fastify.close()
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
await fastify.register(fastifySSE)
|
|
139
|
+
|
|
140
|
+
fastify.get('/stream', { sse: true }, async (request, reply) => {
|
|
141
|
+
async function * generate () {
|
|
142
|
+
yield { id: '1', data: 'first' }
|
|
143
|
+
yield { id: '2', data: 'second' }
|
|
144
|
+
yield { id: '3', data: 'third' }
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await reply.sse.send(generate())
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
await fastify.listen({ port: 0 })
|
|
151
|
+
|
|
152
|
+
const response = await fastify.inject({
|
|
153
|
+
method: 'GET',
|
|
154
|
+
url: '/stream',
|
|
155
|
+
headers: {
|
|
156
|
+
accept: 'text/event-stream'
|
|
157
|
+
}
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
const body = response.body
|
|
161
|
+
assert.ok(body.includes('id: 1'))
|
|
162
|
+
assert.ok(body.includes('data: "first"'))
|
|
163
|
+
assert.ok(body.includes('id: 2'))
|
|
164
|
+
assert.ok(body.includes('data: "second"'))
|
|
165
|
+
assert.ok(body.includes('id: 3'))
|
|
166
|
+
assert.ok(body.includes('data: "third"'))
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
test('readable stream support', async (t) => {
|
|
170
|
+
const fastify = Fastify({ logger: false })
|
|
171
|
+
|
|
172
|
+
t.after(async () => {
|
|
173
|
+
await fastify.close()
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
await fastify.register(fastifySSE)
|
|
177
|
+
|
|
178
|
+
fastify.get('/stream', { sse: true }, async (request, reply) => {
|
|
179
|
+
const stream = Readable.from([
|
|
180
|
+
{ id: 'a', data: 'alpha' },
|
|
181
|
+
{ id: 'b', data: 'beta' },
|
|
182
|
+
{ id: 'c', data: 'gamma' }
|
|
183
|
+
])
|
|
184
|
+
|
|
185
|
+
await reply.sse.send(stream)
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
await fastify.listen({ port: 0 })
|
|
189
|
+
|
|
190
|
+
const response = await fastify.inject({
|
|
191
|
+
method: 'GET',
|
|
192
|
+
url: '/stream',
|
|
193
|
+
headers: {
|
|
194
|
+
accept: 'text/event-stream'
|
|
195
|
+
}
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
const body = response.body
|
|
199
|
+
assert.ok(body.includes('id: a'))
|
|
200
|
+
assert.ok(body.includes('data: "alpha"'))
|
|
201
|
+
assert.ok(body.includes('id: b'))
|
|
202
|
+
assert.ok(body.includes('data: "beta"'))
|
|
203
|
+
})
|
|
204
|
+
|
|
205
|
+
test('fallback to regular handler when SSE not requested', async (t) => {
|
|
206
|
+
const fastify = Fastify({ logger: false })
|
|
207
|
+
|
|
208
|
+
t.after(async () => {
|
|
209
|
+
await fastify.close()
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
await fastify.register(fastifySSE)
|
|
213
|
+
|
|
214
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
215
|
+
// Only use SSE if the accept header is for SSE
|
|
216
|
+
const acceptHeader = request.headers.accept || ''
|
|
217
|
+
if (acceptHeader.includes('text/event-stream')) {
|
|
218
|
+
await reply.sse.send({ data: 'sse data' })
|
|
219
|
+
} else {
|
|
220
|
+
return { message: 'regular response' }
|
|
221
|
+
}
|
|
222
|
+
})
|
|
223
|
+
|
|
224
|
+
await fastify.listen({ port: 0 })
|
|
225
|
+
|
|
226
|
+
// Request without SSE accept header
|
|
227
|
+
const response = await fastify.inject({
|
|
228
|
+
method: 'GET',
|
|
229
|
+
url: '/events',
|
|
230
|
+
headers: {
|
|
231
|
+
accept: 'application/json'
|
|
232
|
+
}
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
assert.strictEqual(response.statusCode, 200)
|
|
236
|
+
assert.strictEqual(response.headers['content-type'], 'application/json; charset=utf-8')
|
|
237
|
+
|
|
238
|
+
const body = JSON.parse(response.body)
|
|
239
|
+
assert.deepStrictEqual(body, { message: 'regular response' })
|
|
240
|
+
})
|
|
241
|
+
|
|
242
|
+
test('custom serializer', async (t) => {
|
|
243
|
+
const fastify = Fastify({ logger: false })
|
|
244
|
+
|
|
245
|
+
t.after(async () => {
|
|
246
|
+
await fastify.close()
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
await fastify.register(fastifySSE, {
|
|
250
|
+
serializer: (data) => `custom:${data}`
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
fastify.get('/events', { sse: true }, async (request, reply) => {
|
|
254
|
+
await reply.sse.send({ data: 'test' })
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
await fastify.listen({ port: 0 })
|
|
258
|
+
|
|
259
|
+
const response = await fastify.inject({
|
|
260
|
+
method: 'GET',
|
|
261
|
+
url: '/events',
|
|
262
|
+
headers: {
|
|
263
|
+
accept: 'text/event-stream'
|
|
264
|
+
}
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
const body = response.body
|
|
268
|
+
assert.ok(body.includes('data: custom:test'))
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
test('reply.sse.stream() for pipeline operations', async (t) => {
|
|
272
|
+
const fastify = Fastify({ logger: false })
|
|
273
|
+
|
|
274
|
+
t.after(async () => {
|
|
275
|
+
await fastify.close()
|
|
276
|
+
})
|
|
277
|
+
|
|
278
|
+
await fastify.register(fastifySSE)
|
|
279
|
+
|
|
280
|
+
fastify.get('/pipeline', { sse: true }, async (request, reply) => {
|
|
281
|
+
const { pipeline } = require('stream/promises')
|
|
282
|
+
|
|
283
|
+
// Create a source stream with test data
|
|
284
|
+
const sourceStream = Readable.from([
|
|
285
|
+
{ id: '1', data: 'first' },
|
|
286
|
+
{ id: '2', data: 'second' },
|
|
287
|
+
{ id: '3', data: 'third' }
|
|
288
|
+
])
|
|
289
|
+
|
|
290
|
+
// Use reply.sse.stream() in a pipeline
|
|
291
|
+
await pipeline(sourceStream, reply.sse.stream(), reply.raw, { end: false })
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
await fastify.listen({ port: 0 })
|
|
295
|
+
|
|
296
|
+
const response = await fastify.inject({
|
|
297
|
+
method: 'GET',
|
|
298
|
+
url: '/pipeline',
|
|
299
|
+
headers: {
|
|
300
|
+
accept: 'text/event-stream'
|
|
301
|
+
}
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
const body = response.body
|
|
305
|
+
assert.ok(body.includes('id: 1'))
|
|
306
|
+
assert.ok(body.includes('data: "first"'))
|
|
307
|
+
assert.ok(body.includes('id: 2'))
|
|
308
|
+
assert.ok(body.includes('data: "second"'))
|
|
309
|
+
assert.ok(body.includes('id: 3'))
|
|
310
|
+
assert.ok(body.includes('data: "third"'))
|
|
311
|
+
})
|