opinionated-machine 6.7.0 → 6.8.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/README.md CHANGED
@@ -1,1787 +1,1887 @@
1
- # opinionated-machine
2
- Very opinionated DI framework for fastify, built on top of awilix
3
-
4
- ## Table of Contents
5
-
6
- - [Basic usage](#basic-usage)
7
- - [Defining controllers](#defining-controllers)
8
- - [Putting it all together](#putting-it-all-together)
9
- - [Resolver Functions](#resolver-functions)
10
- - [Basic Resolvers](#basic-resolvers)
11
- - [`asSingletonClass`](#assingletonclasstype-opts)
12
- - [`asSingletonFunction`](#assingletonfunctionfn-opts)
13
- - [`asClassWithConfig`](#asclasswithconfigtype-config-opts)
14
- - [Domain Layer Resolvers](#domain-layer-resolvers)
15
- - [`asServiceClass`](#asserviceclasstype-opts)
16
- - [`asUseCaseClass`](#asusecaseclasstype-opts)
17
- - [`asRepositoryClass`](#asrepositoryclasstype-opts)
18
- - [`asControllerClass`](#ascontrollerclasstype-opts)
19
- - [`asSSEControllerClass`](#asssecontrollerclasstype-sseoptions-opts)
20
- - [`asDualModeControllerClass`](#asdualmodecontrollerclasstype-sseoptions-opts)
21
- - [Message Queue Resolvers](#message-queue-resolvers)
22
- - [`asMessageQueueHandlerClass`](#asmessagequeuehandlerclasstype-mqoptions-opts)
23
- - [Background Job Resolvers](#background-job-resolvers)
24
- - [`asEnqueuedJobWorkerClass`](#asenqueuedjobworkerclasstype-workeroptions-opts)
25
- - [`asPgBossProcessorClass`](#aspgbossprocessorclasstype-processoroptions-opts)
26
- - [`asPeriodicJobClass`](#asperiodicjobclasstype-workeroptions-opts)
27
- - [`asJobQueueClass`](#asjobqueueclasstype-queueoptions-opts)
28
- - [`asEnqueuedJobQueueManagerFunction`](#asenqueuedjobqueuemanagerfunctionfn-dioptions-opts)
29
- - [Server-Sent Events (SSE)](#server-sent-events-sse)
30
- - [Prerequisites](#prerequisites)
31
- - [Defining SSE Contracts](#defining-sse-contracts)
32
- - [Creating SSE Controllers](#creating-sse-controllers)
33
- - [Type-Safe SSE Handlers with buildHandler](#type-safe-sse-handlers-with-buildhandler)
34
- - [SSE Controllers Without Dependencies](#sse-controllers-without-dependencies)
35
- - [Registering SSE Controllers](#registering-sse-controllers)
36
- - [Registering SSE Routes](#registering-sse-routes)
37
- - [Broadcasting Events](#broadcasting-events)
38
- - [Controller-Level Hooks](#controller-level-hooks)
39
- - [Route-Level Options](#route-level-options)
40
- - [Graceful Shutdown](#graceful-shutdown)
41
- - [Error Handling](#error-handling)
42
- - [Long-lived Connections vs Request-Response Streaming](#long-lived-connections-vs-request-response-streaming)
43
- - [SSE Parsing Utilities](#sse-parsing-utilities)
44
- - [parseSSEEvents](#parsesseevents)
45
- - [parseSSEBuffer](#parsessebuffer)
46
- - [ParsedSSEEvent Type](#parsedsseevent-type)
47
- - [Testing SSE Controllers](#testing-sse-controllers)
48
- - [SSESessionSpy API](#ssesessionspy-api)
49
- - [Session Monitoring](#session-monitoring)
50
- - [SSE Test Utilities](#sse-test-utilities)
51
- - [Quick Reference](#quick-reference)
52
- - [Inject vs HTTP Comparison](#inject-vs-http-comparison)
53
- - [SSETestServer](#ssetestserver)
54
- - [SSEHttpClient](#ssehttpclient)
55
- - [SSEInjectClient](#sseinjectclient)
56
- - [Contract-Aware Inject Helpers](#contract-aware-inject-helpers)
57
- - [Dual-Mode Controllers (SSE + Sync)](#dual-mode-controllers-sse--sync)
58
- - [Overview](#overview)
59
- - [Defining Dual-Mode Contracts](#defining-dual-mode-contracts)
60
- - [Implementing Dual-Mode Controllers](#implementing-dual-mode-controllers)
61
- - [Registering Dual-Mode Controllers](#registering-dual-mode-controllers)
62
- - [Accept Header Routing](#accept-header-routing)
63
- - [Testing Dual-Mode Controllers](#testing-dual-mode-controllers)
64
-
65
- ## Basic usage
66
-
67
- Define a module, or several modules, that will be used for resolving dependency graphs, using awilix:
68
-
69
- ```ts
70
- import { AbstractModule, asSingletonClass, asMessageQueueHandlerClass, asJobWorkerClass, asJobQueueClass, asControllerClass } from 'opinionated-machine'
71
-
72
- export type ModuleDependencies = {
73
- service: Service
74
- messageQueueConsumer: MessageQueueConsumer
75
- jobWorker: JobWorker
76
- queueManager: QueueManager
77
- }
78
-
79
- export class MyModule extends AbstractModule<ModuleDependencies, ExternalDependencies> {
80
- resolveDependencies(
81
- diOptions: DependencyInjectionOptions,
82
- _externalDependencies: ExternalDependencies,
83
- ): MandatoryNameAndRegistrationPair<ModuleDependencies> {
84
- return {
85
- service: asSingletonClass(Service),
86
-
87
- // by default init and disposal methods from `message-queue-toolkit` consumers
88
- // will be assumed. If different values are necessary, pass second config object
89
- // and specify "asyncInit" and "asyncDispose" fields
90
- messageQueueConsumer: asMessageQueueHandlerClass(MessageQueueConsumer, {
91
- queueName: MessageQueueConsumer.QUEUE_ID,
92
- diOptions,
93
- }),
94
-
95
- // by default init and disposal methods from `background-jobs-commons` job workers
96
- // will be assumed. If different values are necessary, pass second config object
97
- // and specify "asyncInit" and "asyncDispose" fields
98
- jobWorker: asEnqueuedJobWorkerClass(JobWorker, {
99
- queueName: JobWorker.QUEUE_ID,
100
- diOptions,
101
- }),
102
-
103
- // by default disposal methods from `background-jobs-commons` job queue manager
104
- // will be assumed. If different values are necessary, specify "asyncDispose" fields
105
- // in the second config object
106
- queueManager: asJobQueueClass(
107
- QueueManager,
108
- {
109
- diOptions,
110
- },
111
- {
112
- asyncInit: (manager) => manager.start(resolveJobQueuesEnabled(options)),
113
- },
114
- ),
115
- }
116
- }
117
-
118
- // controllers will be automatically registered on fastify app
119
- // both REST and SSE controllers go here - SSE controllers are auto-detected
120
- resolveControllers(diOptions: DependencyInjectionOptions) {
121
- return {
122
- controller: asControllerClass(MyController),
123
- }
124
- }
125
- }
126
- ```
127
-
128
- ## Defining controllers
129
-
130
- Controllers require using fastify-api-contracts and allow to define application routes.
131
-
132
- ```ts
133
- import { buildFastifyNoPayloadRoute } from '@lokalise/fastify-api-contracts'
134
- import { buildDeleteRoute } from '@lokalise/universal-ts-utils/api-contracts/apiContracts'
135
- import { z } from 'zod/v4'
136
- import { AbstractController } from 'opinionated-machine'
137
-
138
- const BODY_SCHEMA = z.object({})
139
- const PATH_PARAMS_SCHEMA = z.object({
140
- userId: z.string(),
141
- })
142
-
143
- const contract = buildDeleteRoute({
144
- successResponseBodySchema: BODY_SCHEMA,
145
- requestPathParamsSchema: PATH_PARAMS_SCHEMA,
146
- pathResolver: (pathParams) => `/users/${pathParams.userId}`,
147
- })
148
-
149
- export class MyController extends AbstractController<typeof MyController.contracts> {
150
- public static contracts = { deleteItem: contract } as const
151
- private readonly service: Service
152
-
153
- constructor({ service }: ModuleDependencies) {
154
- super()
155
- this.service = testService
156
- }
157
-
158
- private deleteItem = buildFastifyNoPayloadRoute(
159
- TestController.contracts.deleteItem,
160
- async (req, reply) => {
161
- req.log.info(req.params.userId)
162
- this.service.execute()
163
- await reply.status(204).send()
164
- },
165
- )
166
-
167
- public buildRoutes() {
168
- return {
169
- deleteItem: this.deleteItem,
170
- }
171
- }
172
- }
173
- ```
174
-
175
- ## Putting it all together
176
-
177
- Typical usage with a fastify app looks like this:
178
-
179
- ```ts
180
- import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod'
181
- import { createContainer } from 'awilix'
182
- import { fastify } from 'fastify'
183
- import { DIContext } from 'opinionated-machine'
184
-
185
- const module = new MyModule()
186
- const container = createContainer({
187
- injectionMode: 'PROXY',
188
- })
189
-
190
- type AppConfig = {
191
- DATABASE_URL: string
192
- // ...
193
- // everything related to app configuration
194
- }
195
-
196
- type ExternalDependencies = {
197
- logger: Logger // most likely you would like to reuse logger instance from fastify app
198
- }
199
-
200
- const context = new DIContext<ModuleDependencies, AppConfig, ExternalDependencies>(container, {
201
- messageQueueConsumersEnabled: [MessageQueueConsumer.QUEUE_ID],
202
- jobQueuesEnabled: false,
203
- jobWorkersEnabled: false,
204
- periodicJobsEnabled: false,
205
- })
206
-
207
- context.registerDependencies({
208
- modules: [module],
209
- dependencyOverrides: {}, // dependency overrides if necessary, usually for testing purposes
210
- configOverrides: {}, // config overrides if necessary, will be merged with value inside existing config
211
- configDependencyId?: string // what is the dependency id in the graph for the config entity. Only used for config overrides. Default value is `config`
212
- },
213
- // external dependencies that are instantiated outside of DI
214
- {
215
- logger: app.logger
216
- })
217
-
218
- const app = fastify()
219
- app.setValidatorCompiler(validatorCompiler)
220
- app.setSerializerCompiler(serializerCompiler)
221
-
222
- app.after(() => {
223
- context.registerRoutes(app)
224
- })
225
- await app.ready()
226
- ```
227
-
228
- ## Resolver Functions
229
-
230
- The library provides a set of resolver functions that wrap awilix's `asClass` and `asFunction` with sensible defaults for different types of dependencies. All resolvers create singletons by default.
231
-
232
- ### Basic Resolvers
233
-
234
- #### `asSingletonClass(Type, opts?)`
235
- Basic singleton class resolver. Use for general-purpose dependencies that don't fit other categories.
236
-
237
- ```ts
238
- service: asSingletonClass(MyService)
239
- ```
240
-
241
- #### `asSingletonFunction(fn, opts?)`
242
- Basic singleton function resolver. Use when you need to resolve a dependency using a factory function.
243
-
244
- ```ts
245
- config: asSingletonFunction(() => loadConfig())
246
- ```
247
-
248
- #### `asClassWithConfig(Type, config, opts?)`
249
- Register a class with an additional config parameter passed to the constructor. Uses `asFunction` wrapper internally to pass the config as a second parameter. Requires PROXY injection mode.
250
-
251
- ```ts
252
- myService: asClassWithConfig(MyService, { enableFeature: true })
253
- ```
254
-
255
- The class constructor receives dependencies as the first parameter and config as the second:
256
-
257
- ```ts
258
- class MyService {
259
- constructor(deps: Dependencies, config: { enableFeature: boolean }) {
260
- // ...
261
- }
262
- }
263
- ```
264
-
265
- ### Domain Layer Resolvers
266
-
267
- #### `asServiceClass(Type, opts?)`
268
- For service classes. Marks the dependency as **public** (exposed when module is used as secondary).
269
-
270
- ```ts
271
- userService: asServiceClass(UserService)
272
- ```
273
-
274
- #### `asUseCaseClass(Type, opts?)`
275
- For use case classes. Marks the dependency as **public**.
276
-
277
- ```ts
278
- createUserUseCase: asUseCaseClass(CreateUserUseCase)
279
- ```
280
-
281
- #### `asRepositoryClass(Type, opts?)`
282
- For repository classes. Marks the dependency as **private** (not exposed when module is secondary).
283
-
284
- ```ts
285
- userRepository: asRepositoryClass(UserRepository)
286
- ```
287
-
288
- #### `asControllerClass(Type, opts?)`
289
- For REST controller classes. Marks the dependency as **private**. Use in `resolveControllers()`.
290
-
291
- ```ts
292
- userController: asControllerClass(UserController)
293
- ```
294
-
295
- #### `asSSEControllerClass(Type, sseOptions?, opts?)`
296
- For SSE controller classes. Marks the dependency as **private** with `isSSEController: true` for auto-detection. Automatically configures `closeAllConnections` as the async dispose method for graceful shutdown. When `sseOptions.diOptions.isTestMode` is true, enables the connection spy for testing. Use in `resolveControllers()` alongside REST controllers.
297
-
298
- ```ts
299
- // In resolveControllers()
300
- resolveControllers(diOptions: DependencyInjectionOptions) {
301
- return {
302
- userController: asControllerClass(UserController),
303
- notificationsSSEController: asSSEControllerClass(NotificationsSSEController, { diOptions }),
304
- }
305
- }
306
- ```
307
-
308
- #### `asDualModeControllerClass(Type, sseOptions?, opts?)`
309
- For dual-mode controller classes that handle both SSE and JSON responses on the same route. Marks the dependency as **private** with `isDualModeController: true` for auto-detection. Inherits all SSE controller features including connection management and graceful shutdown. When `sseOptions.diOptions.isTestMode` is true, enables the connection spy for testing SSE mode.
310
-
311
- ```ts
312
- // In resolveControllers()
313
- resolveControllers(diOptions: DependencyInjectionOptions) {
314
- return {
315
- userController: asControllerClass(UserController),
316
- chatController: asDualModeControllerClass(ChatDualModeController, { diOptions }),
317
- }
318
- }
319
- ```
320
-
321
- ### Message Queue Resolvers
322
-
323
- #### `asMessageQueueHandlerClass(Type, mqOptions, opts?)`
324
- For message queue consumers following `message-queue-toolkit` conventions. Automatically handles `start`/`close` lifecycle and respects `messageQueueConsumersEnabled` option.
325
-
326
- ```ts
327
- messageQueueConsumer: asMessageQueueHandlerClass(MessageQueueConsumer, {
328
- queueName: MessageQueueConsumer.QUEUE_ID,
329
- diOptions,
330
- })
331
- ```
332
-
333
- ### Background Job Resolvers
334
-
335
- #### `asEnqueuedJobWorkerClass(Type, workerOptions, opts?)`
336
- For enqueued job workers following `background-jobs-common` conventions. Automatically handles `start`/`dispose` lifecycle and respects `enqueuedJobWorkersEnabled` option.
337
-
338
- ```ts
339
- jobWorker: asEnqueuedJobWorkerClass(JobWorker, {
340
- queueName: JobWorker.QUEUE_ID,
341
- diOptions,
342
- })
343
- ```
344
-
345
- #### `asPgBossProcessorClass(Type, processorOptions, opts?)`
346
- For pg-boss job processor classes. Similar to `asEnqueuedJobWorkerClass` but uses `start`/`stop` lifecycle methods and initializes after pgBoss (priority 20).
347
-
348
- ```ts
349
- enrichUserPresenceJob: asPgBossProcessorClass(EnrichUserPresenceJob, {
350
- queueName: EnrichUserPresenceJob.QUEUE_ID,
351
- diOptions,
352
- })
353
- ```
354
-
355
- #### `asPeriodicJobClass(Type, workerOptions, opts?)`
356
- For periodic job classes following `background-jobs-common` conventions. Uses eager injection via `register` method and respects `periodicJobsEnabled` option.
357
-
358
- ```ts
359
- cleanupJob: asPeriodicJobClass(CleanupJob, {
360
- jobName: CleanupJob.JOB_NAME,
361
- diOptions,
362
- })
363
- ```
364
-
365
- #### `asJobQueueClass(Type, queueOptions, opts?)`
366
- For job queue classes. Marks the dependency as **public**. Respects `jobQueuesEnabled` option.
367
-
368
- ```ts
369
- queueManager: asJobQueueClass(QueueManager, {
370
- diOptions,
371
- })
372
- ```
373
-
374
- #### `asEnqueuedJobQueueManagerFunction(fn, diOptions, opts?)`
375
- For job queue manager factory functions. Automatically calls `start()` with resolved enabled queues during initialization.
376
-
377
- ```ts
378
- jobQueueManager: asEnqueuedJobQueueManagerFunction(
379
- createJobQueueManager,
380
- diOptions,
381
- )
382
- ```
383
-
384
- ## Server-Sent Events (SSE)
385
-
386
- The library provides first-class support for Server-Sent Events using [@fastify/sse](https://github.com/fastify/sse). SSE enables real-time, unidirectional streaming from server to client - perfect for notifications, live updates, and streaming responses (like AI chat completions).
387
-
388
- ### Prerequisites
389
-
390
- Register the `@fastify/sse` plugin before using SSE controllers:
391
-
392
- ```ts
393
- import FastifySSEPlugin from '@fastify/sse'
394
-
395
- const app = fastify()
396
- await app.register(FastifySSEPlugin)
397
- ```
398
-
399
- ### Defining SSE Contracts
400
-
401
- Use `buildSseContract` from `@lokalise/api-contracts` to define SSE routes. The contract type is automatically determined based on the presence of `requestBody` and `syncResponseBody` fields. Paths are defined using `pathResolver`, a type-safe function that receives typed params and returns the URL path:
402
-
403
- ```ts
404
- import { z } from 'zod'
405
- import { buildSseContract } from '@lokalise/api-contracts'
406
-
407
- // GET-based SSE stream with path params (no body = GET)
408
- export const channelStreamContract = buildSseContract({
409
- pathResolver: (params) => `/api/channels/${params.channelId}/stream`,
410
- params: z.object({ channelId: z.string() }),
411
- query: z.object({}),
412
- requestHeaders: z.object({}),
413
- sseEvents: {
414
- message: z.object({ content: z.string() }),
415
- },
416
- })
417
-
418
- // GET-based SSE stream without path params
419
- export const notificationsContract = buildSseContract({
420
- pathResolver: () => '/api/notifications/stream',
421
- params: z.object({}),
422
- query: z.object({ userId: z.string().optional() }),
423
- requestHeaders: z.object({}),
424
- sseEvents: {
425
- notification: z.object({
426
- id: z.string(),
427
- message: z.string(),
428
- }),
429
- },
430
- })
431
-
432
- // POST-based SSE stream (e.g., AI chat completions) - has requestBody = POST/PUT/PATCH
433
- export const chatCompletionContract = buildSseContract({
434
- method: 'post',
435
- pathResolver: () => '/api/chat/completions',
436
- params: z.object({}),
437
- query: z.object({}),
438
- requestHeaders: z.object({}),
439
- requestBody: z.object({
440
- message: z.string(),
441
- stream: z.literal(true),
442
- }),
443
- sseEvents: {
444
- chunk: z.object({ content: z.string() }),
445
- done: z.object({ totalTokens: z.number() }),
446
- },
447
- })
448
- ```
449
-
450
- For reusable event schema definitions, you can use the `SSEEventSchemas` type (requires TypeScript 4.9+ for `satisfies`):
451
-
452
- ```ts
453
- import { z } from 'zod'
454
- import type { SSEEventSchemas } from 'opinionated-machine'
455
-
456
- // Define reusable event schemas for multiple contracts
457
- const streamingEvents = {
458
- chunk: z.object({ content: z.string() }),
459
- done: z.object({ totalTokens: z.number() }),
460
- error: z.object({ code: z.number(), message: z.string() }),
461
- } satisfies SSEEventSchemas
462
- ```
463
-
464
- ### Creating SSE Controllers
465
-
466
- SSE controllers extend `AbstractSSEController` and must implement a two-parameter constructor. Use `buildHandler` for automatic type inference of request parameters:
467
-
468
- ```ts
469
- import {
470
- AbstractSSEController,
471
- buildHandler,
472
- type SSEControllerConfig,
473
- type SSESession
474
- } from 'opinionated-machine'
475
-
476
- type Contracts = {
477
- notificationsStream: typeof notificationsContract
478
- }
479
-
480
- type Dependencies = {
481
- notificationService: NotificationService
482
- }
483
-
484
- export class NotificationsSSEController extends AbstractSSEController<Contracts> {
485
- public static contracts = {
486
- notificationsStream: notificationsContract,
487
- } as const
488
-
489
- private readonly notificationService: NotificationService
490
-
491
- // Required: two-parameter constructor (deps object, optional SSE config)
492
- constructor(deps: Dependencies, sseConfig?: SSEControllerConfig) {
493
- super(deps, sseConfig)
494
- this.notificationService = deps.notificationService
495
- }
496
-
497
- public buildSSERoutes() {
498
- return {
499
- notificationsStream: this.handleStream,
500
- }
501
- }
502
-
503
- // Handler with automatic type inference from contract
504
- // sse.start(mode) returns a session with type-safe event sending
505
- // Options (onConnect, onClose) are passed as the third parameter to buildHandler
506
- private handleStream = buildHandler(notificationsContract, {
507
- sse: async (request, sse) => {
508
- // request.query is typed from contract: { userId?: string }
509
- const userId = request.query.userId ?? 'anonymous'
510
-
511
- // Start streaming with 'keepAlive' mode - stays open for external events
512
- // Sends HTTP 200 + SSE headers immediately
513
- const session = sse.start('keepAlive', { context: { userId } })
514
-
515
- // For external triggers (subscriptions, timers, message queues), use sendEventInternal.
516
- // session.send is only available within this handler's scope - external callbacks
517
- // like subscription handlers execute later, outside this function, so they can't access session.
518
- // sendEventInternal is a controller method, so it's accessible from any callback.
519
- // It provides autocomplete for all event names defined in the controller's contracts.
520
- this.notificationService.subscribe(userId, async (notification) => {
521
- await this.sendEventInternal(session.id, {
522
- event: 'notification',
523
- data: notification,
524
- })
525
- })
526
-
527
- // For direct sending within the handler, use the session's send method.
528
- // It provides stricter per-route typing (only events from this specific contract).
529
- await session.send('notification', { id: 'welcome', message: 'Connected!' })
530
-
531
- // 'keepAlive' mode: handler returns, but connection stays open for subscription events
532
- // Connection closes when client disconnects or server calls closeConnection()
533
- },
534
- }, {
535
- onConnect: (session) => console.log('Client connected:', session.id),
536
- onClose: (session, reason) => {
537
- const userId = session.context?.userId as string
538
- this.notificationService.unsubscribe(userId)
539
- console.log(`Client disconnected (${reason}):`, session.id)
540
- },
541
- })
542
- }
543
- ```
544
-
545
- ### Type-Safe SSE Handlers with `buildHandler`
546
-
547
- For automatic type inference of request parameters (similar to `buildFastifyPayloadRoute` for regular controllers), use `buildHandler`:
548
-
549
- ```ts
550
- import {
551
- AbstractSSEController,
552
- buildHandler,
553
- type SSEControllerConfig,
554
- type SSESession
555
- } from 'opinionated-machine'
556
-
557
- class ChatSSEController extends AbstractSSEController<Contracts> {
558
- public static contracts = {
559
- chatCompletion: chatCompletionContract,
560
- } as const
561
-
562
- constructor(deps: Dependencies, sseConfig?: SSEControllerConfig) {
563
- super(deps, sseConfig)
564
- }
565
-
566
- // Handler with automatic type inference from contract
567
- // sse.start(mode) returns session with fully typed send()
568
- private handleChatCompletion = buildHandler(chatCompletionContract, {
569
- sse: async (request, sse) => {
570
- // request.body is typed as { message: string; stream: true }
571
- // request.query, request.params, request.headers all typed from contract
572
- const words = request.body.message.split(' ')
573
-
574
- // Start streaming with 'autoClose' mode - closes after handler completes
575
- // Sends HTTP 200 + SSE headers immediately
576
- const session = sse.start('autoClose')
577
-
578
- for (const word of words) {
579
- // session.send() provides compile-time type checking for event names and data
580
- await session.send('chunk', { content: word })
581
- }
582
-
583
- // 'autoClose' mode: connection closes automatically when handler returns
584
- },
585
- })
586
-
587
- public buildSSERoutes() {
588
- return {
589
- chatCompletion: this.handleChatCompletion,
590
- }
591
- }
592
- }
593
- ```
594
-
595
- You can also use `InferSSERequest<Contract>` for manual type annotation when needed:
596
-
597
- ```ts
598
- import { type InferSSERequest, type SSEContext, type SSESession } from 'opinionated-machine'
599
-
600
- private handleStream = async (
601
- request: InferSSERequest<typeof chatCompletionContract>,
602
- sse: SSEContext<typeof chatCompletionContract['sseEvents']>,
603
- ) => {
604
- // request.body, request.params, etc. all typed from contract
605
- const session = sse.start('autoClose')
606
- // session.send() is typed based on contract sseEvents
607
- await session.send('chunk', { content: 'hello' })
608
- // 'autoClose' mode: connection closes when handler returns
609
- }
610
- ```
611
-
612
- ### SSE Controllers Without Dependencies
613
-
614
- For controllers without dependencies, still provide the two-parameter constructor:
615
-
616
- ```ts
617
- export class SimpleSSEController extends AbstractSSEController<Contracts> {
618
- constructor(deps: object, sseConfig?: SSEControllerConfig) {
619
- super(deps, sseConfig)
620
- }
621
-
622
- // ... implementation
623
- }
624
- ```
625
-
626
- ### Registering SSE Controllers
627
-
628
- Use `asSSEControllerClass` in your module's `resolveControllers` method alongside REST controllers. SSE controllers are automatically detected via the `isSSEController` flag and registered in the DI container:
629
-
630
- ```ts
631
- import { AbstractModule, asControllerClass, asSSEControllerClass, asServiceClass, type DependencyInjectionOptions } from 'opinionated-machine'
632
-
633
- export class NotificationsModule extends AbstractModule<Dependencies> {
634
- resolveDependencies() {
635
- return {
636
- notificationService: asServiceClass(NotificationService),
637
- }
638
- }
639
-
640
- resolveControllers(diOptions: DependencyInjectionOptions) {
641
- return {
642
- // REST controller
643
- usersController: asControllerClass(UsersController),
644
- // SSE controller (automatically detected and registered for SSE routes)
645
- notificationsSSEController: asSSEControllerClass(NotificationsSSEController, { diOptions }),
646
- }
647
- }
648
- }
649
- ```
650
-
651
- ### Registering SSE Routes
652
-
653
- Call `registerSSERoutes` after registering the `@fastify/sse` plugin:
654
-
655
- ```ts
656
- const app = fastify()
657
- app.setValidatorCompiler(validatorCompiler)
658
- app.setSerializerCompiler(serializerCompiler)
659
-
660
- // Register @fastify/sse plugin first
661
- await app.register(FastifySSEPlugin)
662
-
663
- // Then register SSE routes
664
- context.registerSSERoutes(app)
665
-
666
- // Optionally with global preHandler for authentication
667
- context.registerSSERoutes(app, {
668
- preHandler: async (request, reply) => {
669
- if (!request.headers.authorization) {
670
- reply.code(401).send({ error: 'Unauthorized' })
671
- }
672
- },
673
- })
674
-
675
- await app.ready()
676
- ```
677
-
678
- ### Broadcasting Events
679
-
680
- Send events to multiple connections using `broadcast()` or `broadcastIf()`:
681
-
682
- ```ts
683
- // Broadcast to ALL connected clients
684
- await this.broadcast({
685
- event: 'system',
686
- data: { message: 'Server maintenance in 5 minutes' },
687
- })
688
-
689
- // Broadcast to sessions matching a predicate
690
- await this.broadcastIf(
691
- { event: 'channel-update', data: { channelId: '123', newMessage: msg } },
692
- (session) => session.context.channelId === '123',
693
- )
694
- ```
695
-
696
- Both methods return the number of clients the message was successfully sent to.
697
-
698
- ### Controller-Level Hooks
699
-
700
- Override these optional methods on your controller for global session handling:
701
-
702
- ```ts
703
- class MySSEController extends AbstractSSEController<Contracts> {
704
- // Called AFTER session is registered (for all routes)
705
- protected onConnectionEstablished(session: SSESession): void {
706
- this.metrics.incrementConnections()
707
- }
708
-
709
- // Called BEFORE session is unregistered (for all routes)
710
- protected onConnectionClosed(session: SSESession): void {
711
- this.metrics.decrementConnections()
712
- }
713
- }
714
- ```
715
-
716
- ### Route-Level Options
717
-
718
- Each route can have its own `preHandler`, lifecycle hooks, and logger. Pass these as the third parameter to `buildHandler`:
719
-
720
- ```ts
721
- public buildSSERoutes() {
722
- return {
723
- adminStream: this.handleAdminStream,
724
- }
725
- }
726
-
727
- private handleAdminStream = buildHandler(adminStreamContract, {
728
- sse: async (request, sse) => {
729
- const session = sse.start('keepAlive')
730
- // ... handler logic
731
- },
732
- }, {
733
- // Route-specific authentication
734
- preHandler: (request, reply) => {
735
- if (!request.user?.isAdmin) {
736
- reply.code(403).send({ error: 'Forbidden' })
737
- }
738
- },
739
- onConnect: (session) => console.log('Admin connected'),
740
- onClose: (session, reason) => console.log(`Admin disconnected (${reason})`),
741
- // Handle client reconnection with Last-Event-ID
742
- onReconnect: async (session, lastEventId) => {
743
- // Return events to replay, or handle manually
744
- return this.getEventsSince(lastEventId)
745
- },
746
- // Optional: logger for error handling (requires @lokalise/node-core)
747
- logger: this.logger,
748
- })
749
- ```
750
-
751
- **Available route options:**
752
-
753
- | Option | Description |
754
- | -------- | ------------- |
755
- | `preHandler` | Authentication/authorization hook that runs before SSE session |
756
- | `onConnect` | Called after client connects (SSE handshake complete) |
757
- | `onClose` | Called when session closes (client disconnect, network failure, or server close). Receives `(session, reason)` where reason is `'server'` or `'client'` |
758
- | `onReconnect` | Handle Last-Event-ID reconnection, return events to replay |
759
- | `logger` | Optional `SSELogger` for error handling (compatible with pino and `@lokalise/node-core`). If not provided, errors in lifecycle hooks are silently ignored |
760
- | `serializer` | Custom serializer for SSE data (e.g., for custom JSON encoding) |
761
- | `heartbeatInterval` | Interval in ms for heartbeat keep-alive messages |
762
-
763
- **onClose reason parameter:**
764
- - `'server'`: Server explicitly closed the session (via `closeConnection()` or `autoClose` mode)
765
- - `'client'`: Client closed the session (EventSource.close(), navigation, network failure)
766
-
767
- ```ts
768
- options: {
769
- onConnect: (session) => console.log('Client connected'),
770
- onClose: (session, reason) => {
771
- console.log(`Session closed (${reason}):`, session.id)
772
- // reason is 'server' or 'client'
773
- },
774
- serializer: (data) => JSON.stringify(data, null, 2), // Pretty-print JSON
775
- heartbeatInterval: 30000, // Send heartbeat every 30 seconds
776
- }
777
- ```
778
-
779
- ### SSE Session Methods
780
-
781
- The `session` object returned by `sse.start(mode)` provides several useful methods:
782
-
783
- ```ts
784
- private handleStream = buildHandler(streamContract, {
785
- sse: async (request, sse) => {
786
- const session = sse.start('autoClose')
787
-
788
- // Check if session is still active
789
- if (session.isConnected()) {
790
- await session.send('status', { connected: true })
791
- }
792
-
793
- // Get raw writable stream for advanced use cases (e.g., pipeline)
794
- const stream = session.getStream()
795
-
796
- // Stream messages from an async iterable with automatic validation
797
- async function* generateMessages() {
798
- yield { event: 'message' as const, data: { text: 'Hello' } }
799
- yield { event: 'message' as const, data: { text: 'World' } }
800
- }
801
- await session.sendStream(generateMessages())
802
-
803
- // 'autoClose' mode: connection closes when handler returns
804
- },
805
- })
806
- ```
807
-
808
- | Method | Description |
809
- | -------- | ------------- |
810
- | `send(event, data, options?)` | Send a typed event (validates against contract schema) |
811
- | `isConnected()` | Check if the session is still active |
812
- | `getStream()` | Get the underlying `WritableStream` for advanced use cases |
813
- | `sendStream(messages)` | Stream messages from an `AsyncIterable` with validation |
814
-
815
- ### Graceful Shutdown
816
-
817
- SSE controllers automatically close all connections during application shutdown. This is configured by `asSSEControllerClass` which sets `closeAllConnections` as the async dispose method with priority 5 (early in shutdown sequence).
818
-
819
- ### Error Handling
820
-
821
- When `sendEvent()` fails (e.g., client disconnected), it:
822
- - Returns `false` to indicate failure
823
- - Automatically removes the dead connection from tracking
824
- - Prevents further send attempts to that connection
825
-
826
- ```ts
827
- const sent = await this.sendEvent(connectionId, { event: 'update', data })
828
- if (!sent) {
829
- // Connection was closed or failed - already removed from tracking
830
- this.cleanup(connectionId)
831
- }
832
- ```
833
-
834
- **Lifecycle hook errors** (`onConnect`, `onReconnect`, `onClose`):
835
- - All lifecycle hooks are wrapped in try/catch to prevent crashes
836
- - If a `logger` is provided in route options, errors are logged with context
837
- - If no logger is provided, errors are silently ignored
838
- - The session lifecycle continues even if a hook throws
839
-
840
- ```ts
841
- // Provide a logger to capture lifecycle errors
842
- public buildSSERoutes() {
843
- return {
844
- stream: this.handleStream,
845
- }
846
- }
847
-
848
- private handleStream = buildHandler(streamContract, {
849
- sse: async (request, sse) => {
850
- const session = sse.start('autoClose')
851
- // ... handler logic
852
- },
853
- }, {
854
- logger: this.logger, // pino-compatible logger
855
- onConnect: (session) => { /* may throw */ },
856
- onClose: (session, reason) => { /* may throw */ },
857
- })
858
- ```
859
-
860
- ### Long-lived Connections vs Request-Response Streaming
861
-
862
- SSE session lifetime is determined by the mode passed to `sse.start(mode)`:
863
-
864
- ```ts
865
- // sse.start('autoClose') - close connection when handler returns (request-response pattern)
866
- // sse.start('keepAlive') - keep connection open for external events (subscription pattern)
867
- // sse.respond(code, body) - send HTTP response before streaming (early return)
868
- ```
869
-
870
- **Long-lived sessions** (notifications, live updates):
871
- - Handler starts streaming with `sse.start('keepAlive')`
872
- - Session stays open indefinitely after handler returns
873
- - Events are sent later via callbacks using `sendEventInternal()`
874
- - **Client closes session** when done (e.g., `eventSource.close()` or navigating away)
875
- - Server cleans up via `onConnectionClosed()` hook
876
-
877
- ```ts
878
- private handleStream = buildHandler(streamContract, {
879
- sse: async (request, sse) => {
880
- // Start streaming with 'keepAlive' mode - stays open for external events
881
- const session = sse.start('keepAlive')
882
-
883
- // Set up subscription - events sent via callback AFTER handler returns
884
- this.service.subscribe(session.id, (data) => {
885
- this.sendEventInternal(session.id, { event: 'update', data })
886
- })
887
- // 'keepAlive' mode: handler returns, but connection stays open
888
- },
889
- })
890
-
891
- // Clean up when client disconnects
892
- protected onConnectionClosed(session: SSESession): void {
893
- this.service.unsubscribe(session.id)
894
- }
895
- ```
896
-
897
- **Request-response streaming** (AI completions):
898
- - Handler starts streaming with `sse.start('autoClose')`
899
- - Use `session.send()` for type-safe event sending within the handler
900
- - Session automatically closes when handler returns
901
-
902
- ```ts
903
- private handleChatCompletion = buildHandler(chatCompletionContract, {
904
- sse: async (request, sse) => {
905
- // Start streaming with 'autoClose' mode - closes when handler returns
906
- const session = sse.start('autoClose')
907
-
908
- const words = request.body.message.split(' ')
909
- for (const word of words) {
910
- await session.send('chunk', { content: word })
911
- }
912
- await session.send('done', { totalTokens: words.length })
913
-
914
- // 'autoClose' mode: connection closes automatically when handler returns
915
- },
916
- })
917
- ```
918
-
919
- **Error handling before streaming:**
920
-
921
- Use `sse.respond(code, body)` to return an HTTP response before streaming starts. This is useful for any early return: validation errors, not found, redirects, etc.
922
-
923
- ```ts
924
- private handleStream = buildHandler(streamContract, {
925
- sse: async (request, sse) => {
926
- // Early return BEFORE starting stream - can return any HTTP response
927
- const entity = await this.service.find(request.params.id)
928
- if (!entity) {
929
- return sse.respond(404, { error: 'Entity not found' })
930
- }
931
-
932
- // Validation passed - start streaming with autoClose mode
933
- const session = sse.start('autoClose')
934
- await session.send('data', entity)
935
- // Connection closes automatically when handler returns
936
- },
937
- })
938
-
939
- ### SSE Parsing Utilities
940
-
941
- The library provides production-ready utilities for parsing SSE (Server-Sent Events) streams:
942
-
943
- | Function | Use Case |
944
- |----------|----------|
945
- | `parseSSEEvents` | **Testing & complete responses** - when you have the full response body |
946
- | `parseSSEBuffer` | **Production streaming** - when data arrives incrementally in chunks |
947
-
948
- #### parseSSEEvents
949
-
950
- Parse a complete SSE response body into an array of events.
951
-
952
- **When to use:** Testing with Fastify's `inject()`, or when the full response is available (e.g., request-response style SSE like OpenAI completions):
953
-
954
- ```ts
955
- import { parseSSEEvents, type ParsedSSEEvent } from 'opinionated-machine'
956
-
957
- const responseBody = `event: notification
958
- data: {"id":"1","message":"Hello"}
959
-
960
- event: notification
961
- data: {"id":"2","message":"World"}
962
-
963
- `
964
-
965
- const events: ParsedSSEEvent[] = parseSSEEvents(responseBody)
966
- // Result:
967
- // [
968
- // { event: 'notification', data: '{"id":"1","message":"Hello"}' },
969
- // { event: 'notification', data: '{"id":"2","message":"World"}' }
970
- // ]
971
-
972
- // Access parsed data
973
- const notifications = events.map(e => JSON.parse(e.data))
974
- ```
975
-
976
- #### parseSSEBuffer
977
-
978
- Parse a streaming SSE buffer, handling incomplete events at chunk boundaries.
979
-
980
- **When to use:** Production clients consuming real-time SSE streams (notifications, live feeds, chat) where events arrive incrementally:
981
-
982
- ```ts
983
- import { parseSSEBuffer, type ParseSSEBufferResult } from 'opinionated-machine'
984
-
985
- let buffer = ''
986
-
987
- // As chunks arrive from a stream...
988
- for await (const chunk of stream) {
989
- buffer += chunk
990
- const result: ParseSSEBufferResult = parseSSEBuffer(buffer)
991
-
992
- // Process complete events
993
- for (const event of result.events) {
994
- console.log('Received:', event.event, event.data)
995
- }
996
-
997
- // Keep incomplete data for next chunk
998
- buffer = result.remaining
999
- }
1000
- ```
1001
-
1002
- **Production example with fetch:**
1003
-
1004
- ```ts
1005
- const response = await fetch(url)
1006
- const reader = response.body!.getReader()
1007
- const decoder = new TextDecoder()
1008
- let buffer = ''
1009
-
1010
- while (true) {
1011
- const { done, value } = await reader.read()
1012
- if (done) break
1013
-
1014
- buffer += decoder.decode(value, { stream: true })
1015
- const { events, remaining } = parseSSEBuffer(buffer)
1016
- buffer = remaining
1017
-
1018
- for (const event of events) {
1019
- console.log('Received:', event.event, JSON.parse(event.data))
1020
- }
1021
- }
1022
- ```
1023
-
1024
- #### ParsedSSEEvent Type
1025
-
1026
- Both functions return events with this structure:
1027
-
1028
- ```ts
1029
- type ParsedSSEEvent = {
1030
- id?: string // Event ID (from "id:" field)
1031
- event?: string // Event type (from "event:" field)
1032
- data: string // Event data (from "data:" field, always present)
1033
- retry?: number // Reconnection interval (from "retry:" field)
1034
- }
1035
- ```
1036
-
1037
- ### Testing SSE Controllers
1038
-
1039
- Enable the connection spy for testing by passing `isTestMode: true` in diOptions:
1040
-
1041
- ```ts
1042
- import { createContainer } from 'awilix'
1043
- import { DIContext, SSETestServer, SSEHttpClient } from 'opinionated-machine'
1044
-
1045
- describe('NotificationsSSEController', () => {
1046
- let server: SSETestServer
1047
- let controller: NotificationsSSEController
1048
-
1049
- beforeEach(async () => {
1050
- // Create test server with isTestMode enabled
1051
- server = await SSETestServer.create(
1052
- async (app) => {
1053
- // Register your SSE routes here
1054
- },
1055
- {
1056
- setup: async () => {
1057
- // Set up DI container and resources
1058
- return { context }
1059
- },
1060
- }
1061
- )
1062
-
1063
- controller = server.resources.context.diContainer.cradle.notificationsSSEController
1064
- })
1065
-
1066
- afterEach(async () => {
1067
- await server.resources.context.destroy()
1068
- await server.close()
1069
- })
1070
-
1071
- it('receives notifications over SSE', async () => {
1072
- // Connect with awaitServerConnection to eliminate race condition
1073
- const { client, serverConnection } = await SSEHttpClient.connect(
1074
- server.baseUrl,
1075
- '/api/notifications/stream',
1076
- {
1077
- query: { userId: 'test-user' },
1078
- awaitServerConnection: { controller },
1079
- },
1080
- )
1081
-
1082
- expect(client.response.ok).toBe(true)
1083
-
1084
- // Start collecting events
1085
- const eventsPromise = client.collectEvents(2)
1086
-
1087
- // Send events from server (serverConnection is ready immediately)
1088
- await controller.sendEvent(serverConnection.id, {
1089
- event: 'notification',
1090
- data: { id: '1', message: 'Hello!' },
1091
- })
1092
-
1093
- await controller.sendEvent(serverConnection.id, {
1094
- event: 'notification',
1095
- data: { id: '2', message: 'World!' },
1096
- })
1097
-
1098
- // Wait for events
1099
- const events = await eventsPromise
1100
-
1101
- expect(events).toHaveLength(2)
1102
- expect(JSON.parse(events[0].data)).toEqual({ id: '1', message: 'Hello!' })
1103
- expect(JSON.parse(events[1].data)).toEqual({ id: '2', message: 'World!' })
1104
-
1105
- // Clean up
1106
- client.close()
1107
- })
1108
- })
1109
- ```
1110
-
1111
- ### SSESessionSpy API
1112
-
1113
- The `connectionSpy` is available when `isTestMode: true` is passed to `asSSEControllerClass`:
1114
-
1115
- ```ts
1116
- // Wait for a session to be established (with timeout)
1117
- const session = await controller.connectionSpy.waitForConnection({ timeout: 5000 })
1118
-
1119
- // Wait for a session matching a predicate (useful for multiple sessions)
1120
- const session = await controller.connectionSpy.waitForConnection({
1121
- timeout: 5000,
1122
- predicate: (s) => s.request.url.includes('/api/notifications'),
1123
- })
1124
-
1125
- // Check if a specific session is active
1126
- const isConnected = controller.connectionSpy.isConnected(sessionId)
1127
-
1128
- // Wait for a specific session to disconnect
1129
- await controller.connectionSpy.waitForDisconnection(sessionId, { timeout: 5000 })
1130
-
1131
- // Get all session events (connect/disconnect history)
1132
- const events = controller.connectionSpy.getEvents()
1133
-
1134
- // Clear event history and claimed sessions between tests
1135
- controller.connectionSpy.clear()
1136
- ```
1137
-
1138
- **Note**: `waitForConnection` tracks "claimed" sessions internally. Each call returns a unique unclaimed session, allowing sequential waits for the same URL path without returning the same session twice. This is used internally by `SSEHttpClient.connect()` with `awaitServerConnection`.
1139
-
1140
- ### Session Monitoring
1141
-
1142
- Controllers have access to utility methods for monitoring sessions:
1143
-
1144
- ```ts
1145
- // Get count of active sessions
1146
- const count = this.getConnectionCount()
1147
-
1148
- // Get all active sessions (for iteration/inspection)
1149
- const sessions = this.getConnections()
1150
-
1151
- // Check if session spy is enabled (useful for conditional logic)
1152
- if (this.hasConnectionSpy()) {
1153
- // ...
1154
- }
1155
- ```
1156
-
1157
- ### SSE Test Utilities
1158
-
1159
- The library provides utilities for testing SSE endpoints.
1160
-
1161
- **Two transport methods:**
1162
- - **Inject** - Uses Fastify's built-in `inject()` to simulate HTTP requests directly in-memory, without network overhead. No `listen()` required. Handler must close the session for the request to complete.
1163
- - **Real HTTP** - Actual HTTP via `fetch()`. Requires the server to be listening. Supports long-lived sessions.
1164
-
1165
- #### Quick Reference
1166
-
1167
- | Utility | Connection | Requires Contract | Use Case |
1168
- |---------|------------|-------------------|----------|
1169
- | `SSEInjectClient` | Inject (in-memory) | No | Request-response SSE without contracts |
1170
- | `injectSSE` / `injectPayloadSSE` | Inject (in-memory) | **Yes** | Request-response SSE with type-safe contracts |
1171
- | `SSEHttpClient` | Real HTTP | No | Long-lived SSE connections |
1172
-
1173
- `SSEInjectClient` and `injectSSE`/`injectPayloadSSE` do the same thing (Fastify inject), but `injectSSE`/`injectPayloadSSE` provide type safety via contracts while `SSEInjectClient` works with raw URLs.
1174
-
1175
- #### Inject vs HTTP Comparison
1176
-
1177
- | Feature | Inject (`SSEInjectClient`, `injectSSE`) | HTTP (`SSEHttpClient`) |
1178
- |---------|----------------------------------------|------------------------|
1179
- | **Connection** | Fastify's `inject()` - in-memory | Real HTTP via `fetch()` |
1180
- | **Event delivery** | All events returned at once (after handler closes) | Events arrive incrementally |
1181
- | **Connection lifecycle** | Handler must close for request to complete | Can stay open indefinitely |
1182
- | **Server requirement** | No `listen()` needed | Requires running server |
1183
- | **Best for** | OpenAI-style streaming, batch exports | Notifications, live feeds, chat |
1184
-
1185
- #### SSETestServer
1186
-
1187
- Creates a test server with `@fastify/sse` pre-configured:
1188
-
1189
- ```ts
1190
- import { SSETestServer, SSEHttpClient } from 'opinionated-machine'
1191
-
1192
- // Basic usage
1193
- const server = await SSETestServer.create(async (app) => {
1194
- app.get('/api/events', async (request, reply) => {
1195
- reply.sse({ event: 'message', data: { hello: 'world' } })
1196
- reply.sse.close()
1197
- })
1198
- })
1199
-
1200
- // Connect and test
1201
- const client = await SSEHttpClient.connect(server.baseUrl, '/api/events')
1202
- const events = await client.collectEvents(1)
1203
- expect(events[0].event).toBe('message')
1204
-
1205
- // Cleanup
1206
- client.close()
1207
- await server.close()
1208
- ```
1209
-
1210
- With custom resources (DI container, controllers):
1211
-
1212
- ```ts
1213
- const server = await SSETestServer.create(
1214
- async (app) => {
1215
- // Register routes using resources from setup
1216
- myController.registerRoutes(app)
1217
- },
1218
- {
1219
- configureApp: async (app) => {
1220
- app.setValidatorCompiler(validatorCompiler)
1221
- },
1222
- setup: async () => {
1223
- // Resources are available via server.resources
1224
- const container = createContainer()
1225
- return { container }
1226
- },
1227
- }
1228
- )
1229
-
1230
- const { container } = server.resources
1231
- ```
1232
-
1233
- #### SSEHttpClient
1234
-
1235
- For testing long-lived SSE connections using real HTTP:
1236
-
1237
- ```ts
1238
- import { SSEHttpClient } from 'opinionated-machine'
1239
-
1240
- // Connect to SSE endpoint with awaitServerConnection (recommended)
1241
- // This eliminates the race condition between client connect and server-side registration
1242
- const { client, serverConnection } = await SSEHttpClient.connect(
1243
- server.baseUrl,
1244
- '/api/stream',
1245
- {
1246
- query: { userId: 'test' },
1247
- headers: { authorization: 'Bearer token' },
1248
- awaitServerConnection: { controller }, // Pass your SSE controller
1249
- },
1250
- )
1251
-
1252
- // serverConnection is ready to use immediately
1253
- expect(client.response.ok).toBe(true)
1254
- await controller.sendEvent(serverConnection.id, { event: 'test', data: {} })
1255
-
1256
- // Collect events by count with timeout
1257
- const events = await client.collectEvents(3, 5000) // 3 events, 5s timeout
1258
-
1259
- // Or collect until a predicate is satisfied
1260
- const events = await client.collectEvents(
1261
- (event) => event.event === 'done',
1262
- 5000,
1263
- )
1264
-
1265
- // Iterate over events as they arrive
1266
- for await (const event of client.events()) {
1267
- console.log(event.event, event.data)
1268
- if (event.event === 'done') break
1269
- }
1270
-
1271
- // Cleanup
1272
- client.close()
1273
- ```
1274
-
1275
- **`collectEvents(countOrPredicate, timeout?)`**
1276
-
1277
- Collects events until a count is reached or a predicate returns true.
1278
-
1279
- | Parameter | Type | Description |
1280
- |-----------|------|-------------|
1281
- | `countOrPredicate` | `number \| (event) => boolean` | Number of events to collect, or predicate that returns `true` when collection should stop |
1282
- | `timeout` | `number` | Maximum time to wait in milliseconds (default: 5000) |
1283
-
1284
- Returns `Promise<ParsedSSEEvent[]>`. Throws an error if the timeout is reached before the condition is met.
1285
-
1286
- ```ts
1287
- // Collect exactly 3 events
1288
- const events = await client.collectEvents(3)
1289
-
1290
- // Collect with custom timeout
1291
- const events = await client.collectEvents(5, 10000) // 10s timeout
1292
-
1293
- // Collect until a specific event type (the matching event IS included)
1294
- const events = await client.collectEvents((event) => event.event === 'done')
1295
-
1296
- // Collect until condition with timeout
1297
- const events = await client.collectEvents(
1298
- (event) => JSON.parse(event.data).status === 'complete',
1299
- 30000,
1300
- )
1301
- ```
1302
-
1303
- **`events(signal?)`**
1304
-
1305
- Async generator that yields events as they arrive. Accepts an optional `AbortSignal` for cancellation.
1306
-
1307
- ```ts
1308
- // Basic iteration
1309
- for await (const event of client.events()) {
1310
- console.log(event.event, event.data)
1311
- if (event.event === 'done') break
1312
- }
1313
-
1314
- // With abort signal for timeout control
1315
- const controller = new AbortController()
1316
- const timeoutId = setTimeout(() => controller.abort(), 5000)
1317
-
1318
- try {
1319
- for await (const event of client.events(controller.signal)) {
1320
- console.log(event)
1321
- }
1322
- } finally {
1323
- clearTimeout(timeoutId)
1324
- }
1325
- ```
1326
-
1327
- **When to omit `awaitServerConnection`**
1328
-
1329
- Omit `awaitServerConnection` only in these cases:
1330
- - Testing against external SSE endpoints (not your own controller)
1331
- - When `isTestMode: false` (connectionSpy not available)
1332
- - Simple smoke tests that only verify response headers/status without sending server events
1333
-
1334
- **Consequence**: Without `awaitServerConnection`, `connect()` resolves as soon as HTTP headers are received. Server-side connection registration may not have completed yet, so you cannot reliably send events from the server immediately after `connect()` returns.
1335
-
1336
- ```ts
1337
- // Example: smoke test that only checks connection works
1338
- const client = await SSEHttpClient.connect(server.baseUrl, '/api/stream')
1339
- expect(client.response.ok).toBe(true)
1340
- expect(client.response.headers.get('content-type')).toContain('text/event-stream')
1341
- client.close()
1342
- ```
1343
-
1344
- #### SSEInjectClient
1345
-
1346
- For testing request-response style SSE streams (like OpenAI completions):
1347
-
1348
- ```ts
1349
- import { SSEInjectClient } from 'opinionated-machine'
1350
-
1351
- const client = new SSEInjectClient(app) // No server.listen() needed
1352
-
1353
- // GET request
1354
- const conn = await client.connect('/api/export/progress', {
1355
- headers: { authorization: 'Bearer token' },
1356
- })
1357
-
1358
- // POST request with body (OpenAI-style)
1359
- const conn = await client.connectWithBody(
1360
- '/api/chat/completions',
1361
- { model: 'gpt-4', messages: [...], stream: true },
1362
- )
1363
-
1364
- // All events are available immediately (inject waits for complete response)
1365
- expect(conn.getStatusCode()).toBe(200)
1366
- const events = conn.getReceivedEvents()
1367
- const chunks = events.filter(e => e.event === 'chunk')
1368
- ```
1369
-
1370
- #### Contract-Aware Inject Helpers
1371
-
1372
- For typed testing with SSE contracts:
1373
-
1374
- ```ts
1375
- import { injectSSE, injectPayloadSSE, parseSSEEvents } from 'opinionated-machine'
1376
-
1377
- // For GET SSE endpoints with contracts
1378
- const { closed } = injectSSE(app, notificationsContract, {
1379
- query: { userId: 'test' },
1380
- })
1381
- const result = await closed
1382
- const events = parseSSEEvents(result.body)
1383
-
1384
- // For POST/PUT/PATCH SSE endpoints with contracts
1385
- const { closed } = injectPayloadSSE(app, chatCompletionContract, {
1386
- body: { message: 'Hello', stream: true },
1387
- })
1388
- const result = await closed
1389
- const events = parseSSEEvents(result.body)
1390
- ```
1391
-
1392
- ## Dual-Mode Controllers (SSE + Sync)
1393
-
1394
- Dual-mode controllers handle both SSE streaming and sync responses on the same route path, automatically branching based on the `Accept` header. This is ideal for APIs that support both real-time streaming and traditional request-response patterns.
1395
-
1396
- ### Overview
1397
-
1398
- | Accept Header | Response Mode |
1399
- | ------------- | ------------- |
1400
- | `text/event-stream` | SSE streaming |
1401
- | `application/json` | Sync response |
1402
- | `*/*` or missing | Sync (default, configurable) |
1403
-
1404
- Dual-mode controllers extend `AbstractDualModeController` which inherits from `AbstractSSEController`, providing access to all SSE features (connection management, broadcasting, lifecycle hooks) while adding sync response support.
1405
-
1406
- ### Defining Dual-Mode Contracts
1407
-
1408
- Dual-mode contracts define endpoints that can return **either** a complete sync response **or** stream SSE events, based on the client's `Accept` header. Use dual-mode when:
1409
-
1410
- - Clients may want immediate results (sync) or real-time updates (SSE)
1411
- - You're building OpenAI-style APIs where `stream: true` triggers SSE
1412
- - You need polling fallback for clients that don't support SSE
1413
-
1414
- To create a dual-mode contract, include a `syncResponseBody` schema in your `buildSseContract` call:
1415
- - Has `syncResponseBody` but no `requestBody` → GET dual-mode route
1416
- - Has both `syncResponseBody` and `requestBody` → POST/PUT/PATCH dual-mode route
1417
-
1418
- ```ts
1419
- import { z } from 'zod'
1420
- import { buildSseContract } from '@lokalise/api-contracts'
1421
-
1422
- // GET dual-mode route (polling or streaming job status) - has syncResponseBody, no requestBody
1423
- export const jobStatusContract = buildSseContract({
1424
- pathResolver: (params) => `/api/jobs/${params.jobId}/status`,
1425
- params: z.object({ jobId: z.string().uuid() }),
1426
- query: z.object({ verbose: z.string().optional() }),
1427
- requestHeaders: z.object({}),
1428
- syncResponseBody: z.object({
1429
- status: z.enum(['pending', 'running', 'completed', 'failed']),
1430
- progress: z.number(),
1431
- result: z.string().optional(),
1432
- }),
1433
- sseEvents: {
1434
- progress: z.object({ percent: z.number(), message: z.string().optional() }),
1435
- done: z.object({ result: z.string() }),
1436
- },
1437
- })
1438
-
1439
- // POST dual-mode route (OpenAI-style chat completion) - has both syncResponseBody and requestBody
1440
- export const chatCompletionContract = buildSseContract({
1441
- method: 'post',
1442
- pathResolver: (params) => `/api/chats/${params.chatId}/completions`,
1443
- params: z.object({ chatId: z.string().uuid() }),
1444
- query: z.object({}),
1445
- requestHeaders: z.object({ authorization: z.string() }),
1446
- requestBody: z.object({ message: z.string() }),
1447
- syncResponseBody: z.object({
1448
- reply: z.string(),
1449
- usage: z.object({ tokens: z.number() }),
1450
- }),
1451
- sseEvents: {
1452
- chunk: z.object({ delta: z.string() }),
1453
- done: z.object({ usage: z.object({ total: z.number() }) }),
1454
- },
1455
- })
1456
- ```
1457
-
1458
- **Note**: Dual-mode contracts use `pathResolver` instead of static `path` for type-safe path construction. The `pathResolver` function receives typed params and returns the URL path.
1459
-
1460
- ### Response Headers (Sync Mode)
1461
-
1462
- Dual-mode contracts support an optional `responseHeaders` schema to define and validate headers sent with sync responses. This is useful for documenting expected headers (rate limits, pagination, cache control) and validating that your handlers set them correctly:
1463
-
1464
- ```ts
1465
- export const rateLimitedContract = buildSseContract({
1466
- method: 'post',
1467
- pathResolver: () => '/api/rate-limited',
1468
- params: z.object({}),
1469
- query: z.object({}),
1470
- requestHeaders: z.object({}),
1471
- requestBody: z.object({ data: z.string() }),
1472
- syncResponseBody: z.object({ result: z.string() }),
1473
- // Define expected response headers
1474
- responseHeaders: z.object({
1475
- 'x-ratelimit-limit': z.string(),
1476
- 'x-ratelimit-remaining': z.string(),
1477
- 'x-ratelimit-reset': z.string(),
1478
- }),
1479
- sseEvents: {
1480
- result: z.object({ success: z.boolean() }),
1481
- },
1482
- })
1483
- ```
1484
-
1485
- In your handler, set headers using `reply.header()`:
1486
-
1487
- ```ts
1488
- handlers: buildHandler(rateLimitedContract, {
1489
- sync: async (request, reply) => {
1490
- reply.header('x-ratelimit-limit', '100')
1491
- reply.header('x-ratelimit-remaining', '99')
1492
- reply.header('x-ratelimit-reset', '1640000000')
1493
- return { result: 'success' }
1494
- },
1495
- sse: async (request, sse) => {
1496
- const session = sse.start('autoClose')
1497
- // ... send events ...
1498
- // Connection closes automatically when handler returns
1499
- },
1500
- })
1501
- ```
1502
-
1503
- If the handler doesn't set the required headers, validation will fail with a `RESPONSE_HEADERS_VALIDATION_FAILED` error.
1504
-
1505
- ### Single Sync Handler
1506
-
1507
- Dual-mode contracts use a single `sync` handler that returns the response data. The framework handles content-type negotiation automatically:
1508
-
1509
- ```ts
1510
- handlers: buildHandler(chatCompletionContract, {
1511
- sync: async (request, reply) => {
1512
- // Return the response data matching syncResponseBody schema
1513
- const result = await aiService.complete(request.body.message)
1514
- return {
1515
- reply: result.text,
1516
- usage: { tokens: result.tokenCount },
1517
- }
1518
- },
1519
- sse: async (request, sse) => {
1520
- // SSE streaming handler
1521
- const session = sse.start('autoClose')
1522
- // ... stream events ...
1523
- },
1524
- })
1525
- ```
1526
-
1527
- TypeScript enforces the correct handler structure:
1528
- - `syncResponseBody` contracts must use `sync` handler (returns response data)
1529
- - `sseEvents` contracts must use `sse` handler (streams events)
1530
-
1531
- ### Implementing Dual-Mode Controllers
1532
-
1533
- Dual-mode controllers use `buildHandler` to define both sync and SSE handlers. The handler is returned directly from `buildDualModeRoutes`, with options passed as the third parameter to `buildHandler`:
1534
-
1535
- ```ts
1536
- import {
1537
- AbstractDualModeController,
1538
- buildHandler,
1539
- type BuildFastifyDualModeRoutesReturnType,
1540
- type DualModeControllerConfig,
1541
- } from 'opinionated-machine'
1542
-
1543
- type Contracts = {
1544
- chatCompletion: typeof chatCompletionContract
1545
- }
1546
-
1547
- type Dependencies = {
1548
- aiService: AIService
1549
- }
1550
-
1551
- export class ChatDualModeController extends AbstractDualModeController<Contracts> {
1552
- public static contracts = {
1553
- chatCompletion: chatCompletionContract,
1554
- } as const
1555
-
1556
- private readonly aiService: AIService
1557
-
1558
- constructor(deps: Dependencies, config?: DualModeControllerConfig) {
1559
- super(deps, config)
1560
- this.aiService = deps.aiService
1561
- }
1562
-
1563
- public buildDualModeRoutes(): BuildFastifyDualModeRoutesReturnType<Contracts> {
1564
- return {
1565
- chatCompletion: this.handleChatCompletion,
1566
- }
1567
- }
1568
-
1569
- // Handler with options as third parameter
1570
- private handleChatCompletion = buildHandler(chatCompletionContract, {
1571
- // Sync mode - return complete response
1572
- sync: async (request, _reply) => {
1573
- const result = await this.aiService.complete(request.body.message)
1574
- return {
1575
- reply: result.text,
1576
- usage: { tokens: result.tokenCount },
1577
- }
1578
- },
1579
- // SSE mode - stream response chunks
1580
- sse: async (request, sse) => {
1581
- const session = sse.start('autoClose')
1582
- let totalTokens = 0
1583
- for await (const chunk of this.aiService.stream(request.body.message)) {
1584
- await session.send('chunk', { delta: chunk.text })
1585
- totalTokens += chunk.tokenCount ?? 0
1586
- }
1587
- await session.send('done', { usage: { total: totalTokens } })
1588
- // Connection closes automatically when handler returns
1589
- },
1590
- }, {
1591
- // Optional: set SSE as default mode (instead of sync)
1592
- defaultMode: 'sse',
1593
- // Optional: route-level authentication
1594
- preHandler: (request, reply) => {
1595
- if (!request.headers.authorization) {
1596
- return Promise.resolve(reply.code(401).send({ error: 'Unauthorized' }))
1597
- }
1598
- },
1599
- // Optional: SSE lifecycle hooks
1600
- onConnect: (session) => console.log('Client connected:', session.id),
1601
- onClose: (session, reason) => console.log(`Client disconnected (${reason}):`, session.id),
1602
- })
1603
- }
1604
- ```
1605
-
1606
- **Handler Signatures:**
1607
-
1608
- | Mode | Signature |
1609
- | ---- | --------- |
1610
- | `sync` | `(request, reply) => Response` |
1611
- | `sse` | `(request, sse) => SSEHandlerResult` |
1612
-
1613
- The `sync` handler must return a value matching `syncResponseBody` schema. The `sse` handler uses `sse.start(mode)` to begin streaming (`'autoClose'` for request-response, `'keepAlive'` for long-lived sessions) and `session.send()` for type-safe event sending.
1614
-
1615
- ### Registering Dual-Mode Controllers
1616
-
1617
- Use `asDualModeControllerClass` in your module:
1618
-
1619
- ```ts
1620
- import {
1621
- AbstractModule,
1622
- asControllerClass,
1623
- asDualModeControllerClass,
1624
- asServiceClass,
1625
- } from 'opinionated-machine'
1626
-
1627
- export class ChatModule extends AbstractModule<Dependencies> {
1628
- resolveDependencies() {
1629
- return {
1630
- aiService: asServiceClass(AIService),
1631
- }
1632
- }
1633
-
1634
- resolveControllers(diOptions: DependencyInjectionOptions) {
1635
- return {
1636
- // REST controller
1637
- usersController: asControllerClass(UsersController),
1638
- // Dual-mode controller (auto-detected via isDualModeController flag)
1639
- chatController: asDualModeControllerClass(ChatDualModeController, { diOptions }),
1640
- }
1641
- }
1642
- }
1643
- ```
1644
-
1645
- Register dual-mode routes after the `@fastify/sse` plugin:
1646
-
1647
- ```ts
1648
- const app = fastify()
1649
- app.setValidatorCompiler(validatorCompiler)
1650
- app.setSerializerCompiler(serializerCompiler)
1651
-
1652
- // Register @fastify/sse plugin
1653
- await app.register(FastifySSEPlugin)
1654
-
1655
- // Register routes
1656
- context.registerRoutes(app) // REST routes
1657
- context.registerSSERoutes(app) // SSE-only routes
1658
- context.registerDualModeRoutes(app) // Dual-mode routes
1659
-
1660
- // Check if controllers exist before registration (optional)
1661
- if (context.hasDualModeControllers()) {
1662
- context.registerDualModeRoutes(app)
1663
- }
1664
-
1665
- await app.ready()
1666
- ```
1667
-
1668
- ### Accept Header Routing
1669
-
1670
- The `Accept` header determines response mode:
1671
-
1672
- ```bash
1673
- # JSON mode (complete response)
1674
- curl -X POST http://localhost:3000/api/chats/123/completions \
1675
- -H "Content-Type: application/json" \
1676
- -H "Accept: application/json" \
1677
- -d '{"message": "Hello world"}'
1678
-
1679
- # SSE mode (streaming response)
1680
- curl -X POST http://localhost:3000/api/chats/123/completions \
1681
- -H "Content-Type: application/json" \
1682
- -H "Accept: text/event-stream" \
1683
- -d '{"message": "Hello world"}'
1684
- ```
1685
-
1686
- **Quality values** are supported for content negotiation:
1687
-
1688
- ```bash
1689
- # Prefer JSON (higher quality value)
1690
- curl -H "Accept: text/event-stream;q=0.5, application/json;q=1.0" ...
1691
-
1692
- # Prefer SSE (higher quality value)
1693
- curl -H "Accept: application/json;q=0.5, text/event-stream;q=1.0" ...
1694
- ```
1695
-
1696
- **Subtype wildcards** are supported for flexible content negotiation:
1697
-
1698
- ```bash
1699
- # Accept any text format (matches text/plain, text/csv, etc.)
1700
- curl -H "Accept: text/*" ...
1701
-
1702
- # Accept any application format (matches application/json, application/xml, etc.)
1703
- curl -H "Accept: application/*" ...
1704
-
1705
- # Combine with quality values
1706
- curl -H "Accept: text/event-stream;q=0.9, application/*;q=0.5" ...
1707
- ```
1708
-
1709
- The matching priority is: `text/event-stream` (SSE) > exact matches > subtype wildcards > `*/*` > fallback.
1710
-
1711
- ### Testing Dual-Mode Controllers
1712
-
1713
- Test both sync and SSE modes:
1714
-
1715
- ```ts
1716
- import { createContainer } from 'awilix'
1717
- import { DIContext, SSETestServer, SSEInjectClient } from 'opinionated-machine'
1718
-
1719
- describe('ChatDualModeController', () => {
1720
- let server: SSETestServer
1721
- let injectClient: SSEInjectClient
1722
-
1723
- beforeEach(async () => {
1724
- const container = createContainer({ injectionMode: 'PROXY' })
1725
- const context = new DIContext(container, { isTestMode: true }, {})
1726
- context.registerDependencies({ modules: [new ChatModule()] }, undefined)
1727
-
1728
- server = await SSETestServer.create(
1729
- (app) => {
1730
- context.registerDualModeRoutes(app)
1731
- },
1732
- {
1733
- configureApp: (app) => {
1734
- app.setValidatorCompiler(validatorCompiler)
1735
- app.setSerializerCompiler(serializerCompiler)
1736
- },
1737
- setup: () => ({ context }),
1738
- },
1739
- )
1740
-
1741
- injectClient = new SSEInjectClient(server.app)
1742
- })
1743
-
1744
- afterEach(async () => {
1745
- await server.resources.context.destroy()
1746
- await server.close()
1747
- })
1748
-
1749
- it('returns sync response for Accept: application/json', async () => {
1750
- const response = await server.app.inject({
1751
- method: 'POST',
1752
- url: '/api/chats/550e8400-e29b-41d4-a716-446655440000/completions',
1753
- headers: {
1754
- 'content-type': 'application/json',
1755
- accept: 'application/json',
1756
- authorization: 'Bearer token',
1757
- },
1758
- payload: { message: 'Hello' },
1759
- })
1760
-
1761
- expect(response.statusCode).toBe(200)
1762
- expect(response.headers['content-type']).toContain('application/json')
1763
-
1764
- const body = JSON.parse(response.body)
1765
- expect(body).toHaveProperty('reply')
1766
- expect(body).toHaveProperty('usage')
1767
- })
1768
-
1769
- it('streams SSE for Accept: text/event-stream', async () => {
1770
- const conn = await injectClient.connectWithBody(
1771
- '/api/chats/550e8400-e29b-41d4-a716-446655440000/completions',
1772
- { message: 'Hello' },
1773
- { headers: { authorization: 'Bearer token' } },
1774
- )
1775
-
1776
- expect(conn.getStatusCode()).toBe(200)
1777
- expect(conn.getHeaders()['content-type']).toContain('text/event-stream')
1778
-
1779
- const events = conn.getReceivedEvents()
1780
- const chunks = events.filter((e) => e.event === 'chunk')
1781
- const doneEvents = events.filter((e) => e.event === 'done')
1782
-
1783
- expect(chunks.length).toBeGreaterThan(0)
1784
- expect(doneEvents).toHaveLength(1)
1785
- })
1786
- })
1787
-
1
+ # opinionated-machine
2
+ Very opinionated DI framework for fastify, built on top of awilix
3
+
4
+ ## Table of Contents
5
+
6
+ - [Basic usage](#basic-usage)
7
+ - [Defining controllers](#defining-controllers)
8
+ - [Putting it all together](#putting-it-all-together)
9
+ - [Resolver Functions](#resolver-functions)
10
+ - [Basic Resolvers](#basic-resolvers)
11
+ - [`asSingletonClass`](#assingletonclasstype-opts)
12
+ - [`asSingletonFunction`](#assingletonfunctionfn-opts)
13
+ - [`asClassWithConfig`](#asclasswithconfigtype-config-opts)
14
+ - [Domain Layer Resolvers](#domain-layer-resolvers)
15
+ - [`asServiceClass`](#asserviceclasstype-opts)
16
+ - [`asUseCaseClass`](#asusecaseclasstype-opts)
17
+ - [`asRepositoryClass`](#asrepositoryclasstype-opts)
18
+ - [`asControllerClass`](#ascontrollerclasstype-opts)
19
+ - [`asSSEControllerClass`](#asssecontrollerclasstype-sseoptions-opts)
20
+ - [`asDualModeControllerClass`](#asdualmodecontrollerclasstype-sseoptions-opts)
21
+ - [Message Queue Resolvers](#message-queue-resolvers)
22
+ - [`asMessageQueueHandlerClass`](#asmessagequeuehandlerclasstype-mqoptions-opts)
23
+ - [Background Job Resolvers](#background-job-resolvers)
24
+ - [`asEnqueuedJobWorkerClass`](#asenqueuedjobworkerclasstype-workeroptions-opts)
25
+ - [`asPgBossProcessorClass`](#aspgbossprocessorclasstype-processoroptions-opts)
26
+ - [`asPeriodicJobClass`](#asperiodicjobclasstype-workeroptions-opts)
27
+ - [`asJobQueueClass`](#asjobqueueclasstype-queueoptions-opts)
28
+ - [`asEnqueuedJobQueueManagerFunction`](#asenqueuedjobqueuemanagerfunctionfn-dioptions-opts)
29
+ - [Server-Sent Events (SSE)](#server-sent-events-sse)
30
+ - [Prerequisites](#prerequisites)
31
+ - [Defining SSE Contracts](#defining-sse-contracts)
32
+ - [Creating SSE Controllers](#creating-sse-controllers)
33
+ - [Type-Safe SSE Handlers with buildHandler](#type-safe-sse-handlers-with-buildhandler)
34
+ - [SSE Controllers Without Dependencies](#sse-controllers-without-dependencies)
35
+ - [Registering SSE Controllers](#registering-sse-controllers)
36
+ - [Registering SSE Routes](#registering-sse-routes)
37
+ - [Broadcasting Events](#broadcasting-events)
38
+ - [Controller-Level Hooks](#controller-level-hooks)
39
+ - [Route-Level Options](#route-level-options)
40
+ - [Graceful Shutdown](#graceful-shutdown)
41
+ - [Error Handling](#error-handling)
42
+ - [Long-lived Connections vs Request-Response Streaming](#long-lived-connections-vs-request-response-streaming)
43
+ - [SSE Parsing Utilities](#sse-parsing-utilities)
44
+ - [parseSSEEvents](#parsesseevents)
45
+ - [parseSSEBuffer](#parsessebuffer)
46
+ - [ParsedSSEEvent Type](#parsedsseevent-type)
47
+ - [Testing SSE Controllers](#testing-sse-controllers)
48
+ - [SSESessionSpy API](#ssesessionspy-api)
49
+ - [Session Monitoring](#session-monitoring)
50
+ - [SSE Test Utilities](#sse-test-utilities)
51
+ - [Quick Reference](#quick-reference)
52
+ - [Inject vs HTTP Comparison](#inject-vs-http-comparison)
53
+ - [SSETestServer](#ssetestserver)
54
+ - [SSEHttpClient](#ssehttpclient)
55
+ - [SSEInjectClient](#sseinjectclient)
56
+ - [Contract-Aware Inject Helpers](#contract-aware-inject-helpers)
57
+ - [Dual-Mode Controllers (SSE + Sync)](#dual-mode-controllers-sse--sync)
58
+ - [Overview](#overview)
59
+ - [Defining Dual-Mode Contracts](#defining-dual-mode-contracts)
60
+ - [Response Headers (Sync Mode)](#response-headers-sync-mode)
61
+ - [Status-Specific Response Schemas (responseSchemasByStatusCode)](#status-specific-response-schemas-responseschemasbystatuscode)
62
+ - [Implementing Dual-Mode Controllers](#implementing-dual-mode-controllers)
63
+ - [Registering Dual-Mode Controllers](#registering-dual-mode-controllers)
64
+ - [Accept Header Routing](#accept-header-routing)
65
+ - [Testing Dual-Mode Controllers](#testing-dual-mode-controllers)
66
+
67
+ ## Basic usage
68
+
69
+ Define a module, or several modules, that will be used for resolving dependency graphs, using awilix:
70
+
71
+ ```ts
72
+ import { AbstractModule, asSingletonClass, asMessageQueueHandlerClass, asJobWorkerClass, asJobQueueClass, asControllerClass } from 'opinionated-machine'
73
+
74
+ export type ModuleDependencies = {
75
+ service: Service
76
+ messageQueueConsumer: MessageQueueConsumer
77
+ jobWorker: JobWorker
78
+ queueManager: QueueManager
79
+ }
80
+
81
+ export class MyModule extends AbstractModule<ModuleDependencies, ExternalDependencies> {
82
+ resolveDependencies(
83
+ diOptions: DependencyInjectionOptions,
84
+ _externalDependencies: ExternalDependencies,
85
+ ): MandatoryNameAndRegistrationPair<ModuleDependencies> {
86
+ return {
87
+ service: asSingletonClass(Service),
88
+
89
+ // by default init and disposal methods from `message-queue-toolkit` consumers
90
+ // will be assumed. If different values are necessary, pass second config object
91
+ // and specify "asyncInit" and "asyncDispose" fields
92
+ messageQueueConsumer: asMessageQueueHandlerClass(MessageQueueConsumer, {
93
+ queueName: MessageQueueConsumer.QUEUE_ID,
94
+ diOptions,
95
+ }),
96
+
97
+ // by default init and disposal methods from `background-jobs-commons` job workers
98
+ // will be assumed. If different values are necessary, pass second config object
99
+ // and specify "asyncInit" and "asyncDispose" fields
100
+ jobWorker: asEnqueuedJobWorkerClass(JobWorker, {
101
+ queueName: JobWorker.QUEUE_ID,
102
+ diOptions,
103
+ }),
104
+
105
+ // by default disposal methods from `background-jobs-commons` job queue manager
106
+ // will be assumed. If different values are necessary, specify "asyncDispose" fields
107
+ // in the second config object
108
+ queueManager: asJobQueueClass(
109
+ QueueManager,
110
+ {
111
+ diOptions,
112
+ },
113
+ {
114
+ asyncInit: (manager) => manager.start(resolveJobQueuesEnabled(options)),
115
+ },
116
+ ),
117
+ }
118
+ }
119
+
120
+ // controllers will be automatically registered on fastify app
121
+ // both REST and SSE controllers go here - SSE controllers are auto-detected
122
+ resolveControllers(diOptions: DependencyInjectionOptions) {
123
+ return {
124
+ controller: asControllerClass(MyController),
125
+ }
126
+ }
127
+ }
128
+ ```
129
+
130
+ ## Defining controllers
131
+
132
+ Controllers require using fastify-api-contracts and allow to define application routes.
133
+
134
+ ```ts
135
+ import { buildFastifyNoPayloadRoute } from '@lokalise/fastify-api-contracts'
136
+ import { buildDeleteRoute } from '@lokalise/universal-ts-utils/api-contracts/apiContracts'
137
+ import { z } from 'zod/v4'
138
+ import { AbstractController } from 'opinionated-machine'
139
+
140
+ const BODY_SCHEMA = z.object({})
141
+ const PATH_PARAMS_SCHEMA = z.object({
142
+ userId: z.string(),
143
+ })
144
+
145
+ const contract = buildDeleteRoute({
146
+ successResponseBodySchema: BODY_SCHEMA,
147
+ requestPathParamsSchema: PATH_PARAMS_SCHEMA,
148
+ pathResolver: (pathParams) => `/users/${pathParams.userId}`,
149
+ })
150
+
151
+ export class MyController extends AbstractController<typeof MyController.contracts> {
152
+ public static contracts = { deleteItem: contract } as const
153
+ private readonly service: Service
154
+
155
+ constructor({ service }: ModuleDependencies) {
156
+ super()
157
+ this.service = testService
158
+ }
159
+
160
+ private deleteItem = buildFastifyNoPayloadRoute(
161
+ TestController.contracts.deleteItem,
162
+ async (req, reply) => {
163
+ req.log.info(req.params.userId)
164
+ this.service.execute()
165
+ await reply.status(204).send()
166
+ },
167
+ )
168
+
169
+ public buildRoutes() {
170
+ return {
171
+ deleteItem: this.deleteItem,
172
+ }
173
+ }
174
+ }
175
+ ```
176
+
177
+ ## Putting it all together
178
+
179
+ Typical usage with a fastify app looks like this:
180
+
181
+ ```ts
182
+ import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod'
183
+ import { createContainer } from 'awilix'
184
+ import { fastify } from 'fastify'
185
+ import { DIContext } from 'opinionated-machine'
186
+
187
+ const module = new MyModule()
188
+ const container = createContainer({
189
+ injectionMode: 'PROXY',
190
+ })
191
+
192
+ type AppConfig = {
193
+ DATABASE_URL: string
194
+ // ...
195
+ // everything related to app configuration
196
+ }
197
+
198
+ type ExternalDependencies = {
199
+ logger: Logger // most likely you would like to reuse logger instance from fastify app
200
+ }
201
+
202
+ const context = new DIContext<ModuleDependencies, AppConfig, ExternalDependencies>(container, {
203
+ messageQueueConsumersEnabled: [MessageQueueConsumer.QUEUE_ID],
204
+ jobQueuesEnabled: false,
205
+ jobWorkersEnabled: false,
206
+ periodicJobsEnabled: false,
207
+ })
208
+
209
+ context.registerDependencies({
210
+ modules: [module],
211
+ dependencyOverrides: {}, // dependency overrides if necessary, usually for testing purposes
212
+ configOverrides: {}, // config overrides if necessary, will be merged with value inside existing config
213
+ configDependencyId?: string // what is the dependency id in the graph for the config entity. Only used for config overrides. Default value is `config`
214
+ },
215
+ // external dependencies that are instantiated outside of DI
216
+ {
217
+ logger: app.logger
218
+ })
219
+
220
+ const app = fastify()
221
+ app.setValidatorCompiler(validatorCompiler)
222
+ app.setSerializerCompiler(serializerCompiler)
223
+
224
+ app.after(() => {
225
+ context.registerRoutes(app)
226
+ })
227
+ await app.ready()
228
+ ```
229
+
230
+ ## Resolver Functions
231
+
232
+ The library provides a set of resolver functions that wrap awilix's `asClass` and `asFunction` with sensible defaults for different types of dependencies. All resolvers create singletons by default.
233
+
234
+ ### Basic Resolvers
235
+
236
+ #### `asSingletonClass(Type, opts?)`
237
+ Basic singleton class resolver. Use for general-purpose dependencies that don't fit other categories.
238
+
239
+ ```ts
240
+ service: asSingletonClass(MyService)
241
+ ```
242
+
243
+ #### `asSingletonFunction(fn, opts?)`
244
+ Basic singleton function resolver. Use when you need to resolve a dependency using a factory function.
245
+
246
+ ```ts
247
+ config: asSingletonFunction(() => loadConfig())
248
+ ```
249
+
250
+ #### `asClassWithConfig(Type, config, opts?)`
251
+ Register a class with an additional config parameter passed to the constructor. Uses `asFunction` wrapper internally to pass the config as a second parameter. Requires PROXY injection mode.
252
+
253
+ ```ts
254
+ myService: asClassWithConfig(MyService, { enableFeature: true })
255
+ ```
256
+
257
+ The class constructor receives dependencies as the first parameter and config as the second:
258
+
259
+ ```ts
260
+ class MyService {
261
+ constructor(deps: Dependencies, config: { enableFeature: boolean }) {
262
+ // ...
263
+ }
264
+ }
265
+ ```
266
+
267
+ ### Domain Layer Resolvers
268
+
269
+ #### `asServiceClass(Type, opts?)`
270
+ For service classes. Marks the dependency as **public** (exposed when module is used as secondary).
271
+
272
+ ```ts
273
+ userService: asServiceClass(UserService)
274
+ ```
275
+
276
+ #### `asUseCaseClass(Type, opts?)`
277
+ For use case classes. Marks the dependency as **public**.
278
+
279
+ ```ts
280
+ createUserUseCase: asUseCaseClass(CreateUserUseCase)
281
+ ```
282
+
283
+ #### `asRepositoryClass(Type, opts?)`
284
+ For repository classes. Marks the dependency as **private** (not exposed when module is secondary).
285
+
286
+ ```ts
287
+ userRepository: asRepositoryClass(UserRepository)
288
+ ```
289
+
290
+ #### `asControllerClass(Type, opts?)`
291
+ For REST controller classes. Marks the dependency as **private**. Use in `resolveControllers()`.
292
+
293
+ ```ts
294
+ userController: asControllerClass(UserController)
295
+ ```
296
+
297
+ #### `asSSEControllerClass(Type, sseOptions?, opts?)`
298
+ For SSE controller classes. Marks the dependency as **private** with `isSSEController: true` for auto-detection. Automatically configures `closeAllConnections` as the async dispose method for graceful shutdown. When `sseOptions.diOptions.isTestMode` is true, enables the connection spy for testing. Use in `resolveControllers()` alongside REST controllers.
299
+
300
+ ```ts
301
+ // In resolveControllers()
302
+ resolveControllers(diOptions: DependencyInjectionOptions) {
303
+ return {
304
+ userController: asControllerClass(UserController),
305
+ notificationsSSEController: asSSEControllerClass(NotificationsSSEController, { diOptions }),
306
+ }
307
+ }
308
+ ```
309
+
310
+ #### `asDualModeControllerClass(Type, sseOptions?, opts?)`
311
+ For dual-mode controller classes that handle both SSE and JSON responses on the same route. Marks the dependency as **private** with `isDualModeController: true` for auto-detection. Inherits all SSE controller features including connection management and graceful shutdown. When `sseOptions.diOptions.isTestMode` is true, enables the connection spy for testing SSE mode.
312
+
313
+ ```ts
314
+ // In resolveControllers()
315
+ resolveControllers(diOptions: DependencyInjectionOptions) {
316
+ return {
317
+ userController: asControllerClass(UserController),
318
+ chatController: asDualModeControllerClass(ChatDualModeController, { diOptions }),
319
+ }
320
+ }
321
+ ```
322
+
323
+ ### Message Queue Resolvers
324
+
325
+ #### `asMessageQueueHandlerClass(Type, mqOptions, opts?)`
326
+ For message queue consumers following `message-queue-toolkit` conventions. Automatically handles `start`/`close` lifecycle and respects `messageQueueConsumersEnabled` option.
327
+
328
+ ```ts
329
+ messageQueueConsumer: asMessageQueueHandlerClass(MessageQueueConsumer, {
330
+ queueName: MessageQueueConsumer.QUEUE_ID,
331
+ diOptions,
332
+ })
333
+ ```
334
+
335
+ ### Background Job Resolvers
336
+
337
+ #### `asEnqueuedJobWorkerClass(Type, workerOptions, opts?)`
338
+ For enqueued job workers following `background-jobs-common` conventions. Automatically handles `start`/`dispose` lifecycle and respects `enqueuedJobWorkersEnabled` option.
339
+
340
+ ```ts
341
+ jobWorker: asEnqueuedJobWorkerClass(JobWorker, {
342
+ queueName: JobWorker.QUEUE_ID,
343
+ diOptions,
344
+ })
345
+ ```
346
+
347
+ #### `asPgBossProcessorClass(Type, processorOptions, opts?)`
348
+ For pg-boss job processor classes. Similar to `asEnqueuedJobWorkerClass` but uses `start`/`stop` lifecycle methods and initializes after pgBoss (priority 20).
349
+
350
+ ```ts
351
+ enrichUserPresenceJob: asPgBossProcessorClass(EnrichUserPresenceJob, {
352
+ queueName: EnrichUserPresenceJob.QUEUE_ID,
353
+ diOptions,
354
+ })
355
+ ```
356
+
357
+ #### `asPeriodicJobClass(Type, workerOptions, opts?)`
358
+ For periodic job classes following `background-jobs-common` conventions. Uses eager injection via `register` method and respects `periodicJobsEnabled` option.
359
+
360
+ ```ts
361
+ cleanupJob: asPeriodicJobClass(CleanupJob, {
362
+ jobName: CleanupJob.JOB_NAME,
363
+ diOptions,
364
+ })
365
+ ```
366
+
367
+ #### `asJobQueueClass(Type, queueOptions, opts?)`
368
+ For job queue classes. Marks the dependency as **public**. Respects `jobQueuesEnabled` option.
369
+
370
+ ```ts
371
+ queueManager: asJobQueueClass(QueueManager, {
372
+ diOptions,
373
+ })
374
+ ```
375
+
376
+ #### `asEnqueuedJobQueueManagerFunction(fn, diOptions, opts?)`
377
+ For job queue manager factory functions. Automatically calls `start()` with resolved enabled queues during initialization.
378
+
379
+ ```ts
380
+ jobQueueManager: asEnqueuedJobQueueManagerFunction(
381
+ createJobQueueManager,
382
+ diOptions,
383
+ )
384
+ ```
385
+
386
+ ## Server-Sent Events (SSE)
387
+
388
+ The library provides first-class support for Server-Sent Events using [@fastify/sse](https://github.com/fastify/sse). SSE enables real-time, unidirectional streaming from server to client - perfect for notifications, live updates, and streaming responses (like AI chat completions).
389
+
390
+ ### Prerequisites
391
+
392
+ Register the `@fastify/sse` plugin before using SSE controllers:
393
+
394
+ ```ts
395
+ import FastifySSEPlugin from '@fastify/sse'
396
+
397
+ const app = fastify()
398
+ await app.register(FastifySSEPlugin)
399
+ ```
400
+
401
+ ### Defining SSE Contracts
402
+
403
+ Use `buildSseContract` from `@lokalise/api-contracts` to define SSE routes. The contract type is automatically determined based on the presence of `requestBody` and `syncResponseBody` fields. Paths are defined using `pathResolver`, a type-safe function that receives typed params and returns the URL path:
404
+
405
+ ```ts
406
+ import { z } from 'zod'
407
+ import { buildSseContract } from '@lokalise/api-contracts'
408
+
409
+ // GET-based SSE stream with path params (no body = GET)
410
+ export const channelStreamContract = buildSseContract({
411
+ pathResolver: (params) => `/api/channels/${params.channelId}/stream`,
412
+ params: z.object({ channelId: z.string() }),
413
+ query: z.object({}),
414
+ requestHeaders: z.object({}),
415
+ sseEvents: {
416
+ message: z.object({ content: z.string() }),
417
+ },
418
+ })
419
+
420
+ // GET-based SSE stream without path params
421
+ export const notificationsContract = buildSseContract({
422
+ pathResolver: () => '/api/notifications/stream',
423
+ params: z.object({}),
424
+ query: z.object({ userId: z.string().optional() }),
425
+ requestHeaders: z.object({}),
426
+ sseEvents: {
427
+ notification: z.object({
428
+ id: z.string(),
429
+ message: z.string(),
430
+ }),
431
+ },
432
+ })
433
+
434
+ // POST-based SSE stream (e.g., AI chat completions) - has requestBody = POST/PUT/PATCH
435
+ export const chatCompletionContract = buildSseContract({
436
+ method: 'post',
437
+ pathResolver: () => '/api/chat/completions',
438
+ params: z.object({}),
439
+ query: z.object({}),
440
+ requestHeaders: z.object({}),
441
+ requestBody: z.object({
442
+ message: z.string(),
443
+ stream: z.literal(true),
444
+ }),
445
+ sseEvents: {
446
+ chunk: z.object({ content: z.string() }),
447
+ done: z.object({ totalTokens: z.number() }),
448
+ },
449
+ })
450
+ ```
451
+
452
+ For reusable event schema definitions, you can use the `SSEEventSchemas` type (requires TypeScript 4.9+ for `satisfies`):
453
+
454
+ ```ts
455
+ import { z } from 'zod'
456
+ import type { SSEEventSchemas } from 'opinionated-machine'
457
+
458
+ // Define reusable event schemas for multiple contracts
459
+ const streamingEvents = {
460
+ chunk: z.object({ content: z.string() }),
461
+ done: z.object({ totalTokens: z.number() }),
462
+ error: z.object({ code: z.number(), message: z.string() }),
463
+ } satisfies SSEEventSchemas
464
+ ```
465
+
466
+ ### Creating SSE Controllers
467
+
468
+ SSE controllers extend `AbstractSSEController` and must implement a two-parameter constructor. Use `buildHandler` for automatic type inference of request parameters:
469
+
470
+ ```ts
471
+ import {
472
+ AbstractSSEController,
473
+ buildHandler,
474
+ type SSEControllerConfig,
475
+ type SSESession
476
+ } from 'opinionated-machine'
477
+
478
+ type Contracts = {
479
+ notificationsStream: typeof notificationsContract
480
+ }
481
+
482
+ type Dependencies = {
483
+ notificationService: NotificationService
484
+ }
485
+
486
+ export class NotificationsSSEController extends AbstractSSEController<Contracts> {
487
+ public static contracts = {
488
+ notificationsStream: notificationsContract,
489
+ } as const
490
+
491
+ private readonly notificationService: NotificationService
492
+
493
+ // Required: two-parameter constructor (deps object, optional SSE config)
494
+ constructor(deps: Dependencies, sseConfig?: SSEControllerConfig) {
495
+ super(deps, sseConfig)
496
+ this.notificationService = deps.notificationService
497
+ }
498
+
499
+ public buildSSERoutes() {
500
+ return {
501
+ notificationsStream: this.handleStream,
502
+ }
503
+ }
504
+
505
+ // Handler with automatic type inference from contract
506
+ // sse.start(mode) returns a session with type-safe event sending
507
+ // Options (onConnect, onClose) are passed as the third parameter to buildHandler
508
+ private handleStream = buildHandler(notificationsContract, {
509
+ sse: async (request, sse) => {
510
+ // request.query is typed from contract: { userId?: string }
511
+ const userId = request.query.userId ?? 'anonymous'
512
+
513
+ // Start streaming with 'keepAlive' mode - stays open for external events
514
+ // Sends HTTP 200 + SSE headers immediately
515
+ const session = sse.start('keepAlive', { context: { userId } })
516
+
517
+ // For external triggers (subscriptions, timers, message queues), use sendEventInternal.
518
+ // session.send is only available within this handler's scope - external callbacks
519
+ // like subscription handlers execute later, outside this function, so they can't access session.
520
+ // sendEventInternal is a controller method, so it's accessible from any callback.
521
+ // It provides autocomplete for all event names defined in the controller's contracts.
522
+ this.notificationService.subscribe(userId, async (notification) => {
523
+ await this.sendEventInternal(session.id, {
524
+ event: 'notification',
525
+ data: notification,
526
+ })
527
+ })
528
+
529
+ // For direct sending within the handler, use the session's send method.
530
+ // It provides stricter per-route typing (only events from this specific contract).
531
+ await session.send('notification', { id: 'welcome', message: 'Connected!' })
532
+
533
+ // 'keepAlive' mode: handler returns, but connection stays open for subscription events
534
+ // Connection closes when client disconnects or server calls closeConnection()
535
+ },
536
+ }, {
537
+ onConnect: (session) => console.log('Client connected:', session.id),
538
+ onClose: (session, reason) => {
539
+ const userId = session.context?.userId as string
540
+ this.notificationService.unsubscribe(userId)
541
+ console.log(`Client disconnected (${reason}):`, session.id)
542
+ },
543
+ })
544
+ }
545
+ ```
546
+
547
+ ### Type-Safe SSE Handlers with `buildHandler`
548
+
549
+ For automatic type inference of request parameters (similar to `buildFastifyPayloadRoute` for regular controllers), use `buildHandler`:
550
+
551
+ ```ts
552
+ import {
553
+ AbstractSSEController,
554
+ buildHandler,
555
+ type SSEControllerConfig,
556
+ type SSESession
557
+ } from 'opinionated-machine'
558
+
559
+ class ChatSSEController extends AbstractSSEController<Contracts> {
560
+ public static contracts = {
561
+ chatCompletion: chatCompletionContract,
562
+ } as const
563
+
564
+ constructor(deps: Dependencies, sseConfig?: SSEControllerConfig) {
565
+ super(deps, sseConfig)
566
+ }
567
+
568
+ // Handler with automatic type inference from contract
569
+ // sse.start(mode) returns session with fully typed send()
570
+ private handleChatCompletion = buildHandler(chatCompletionContract, {
571
+ sse: async (request, sse) => {
572
+ // request.body is typed as { message: string; stream: true }
573
+ // request.query, request.params, request.headers all typed from contract
574
+ const words = request.body.message.split(' ')
575
+
576
+ // Start streaming with 'autoClose' mode - closes after handler completes
577
+ // Sends HTTP 200 + SSE headers immediately
578
+ const session = sse.start('autoClose')
579
+
580
+ for (const word of words) {
581
+ // session.send() provides compile-time type checking for event names and data
582
+ await session.send('chunk', { content: word })
583
+ }
584
+
585
+ // 'autoClose' mode: connection closes automatically when handler returns
586
+ },
587
+ })
588
+
589
+ public buildSSERoutes() {
590
+ return {
591
+ chatCompletion: this.handleChatCompletion,
592
+ }
593
+ }
594
+ }
595
+ ```
596
+
597
+ You can also use `InferSSERequest<Contract>` for manual type annotation when needed:
598
+
599
+ ```ts
600
+ import { type InferSSERequest, type SSEContext, type SSESession } from 'opinionated-machine'
601
+
602
+ private handleStream = async (
603
+ request: InferSSERequest<typeof chatCompletionContract>,
604
+ sse: SSEContext<typeof chatCompletionContract['sseEvents']>,
605
+ ) => {
606
+ // request.body, request.params, etc. all typed from contract
607
+ const session = sse.start('autoClose')
608
+ // session.send() is typed based on contract sseEvents
609
+ await session.send('chunk', { content: 'hello' })
610
+ // 'autoClose' mode: connection closes when handler returns
611
+ }
612
+ ```
613
+
614
+ ### SSE Controllers Without Dependencies
615
+
616
+ For controllers without dependencies, still provide the two-parameter constructor:
617
+
618
+ ```ts
619
+ export class SimpleSSEController extends AbstractSSEController<Contracts> {
620
+ constructor(deps: object, sseConfig?: SSEControllerConfig) {
621
+ super(deps, sseConfig)
622
+ }
623
+
624
+ // ... implementation
625
+ }
626
+ ```
627
+
628
+ ### Registering SSE Controllers
629
+
630
+ Use `asSSEControllerClass` in your module's `resolveControllers` method alongside REST controllers. SSE controllers are automatically detected via the `isSSEController` flag and registered in the DI container:
631
+
632
+ ```ts
633
+ import { AbstractModule, asControllerClass, asSSEControllerClass, asServiceClass, type DependencyInjectionOptions } from 'opinionated-machine'
634
+
635
+ export class NotificationsModule extends AbstractModule<Dependencies> {
636
+ resolveDependencies() {
637
+ return {
638
+ notificationService: asServiceClass(NotificationService),
639
+ }
640
+ }
641
+
642
+ resolveControllers(diOptions: DependencyInjectionOptions) {
643
+ return {
644
+ // REST controller
645
+ usersController: asControllerClass(UsersController),
646
+ // SSE controller (automatically detected and registered for SSE routes)
647
+ notificationsSSEController: asSSEControllerClass(NotificationsSSEController, { diOptions }),
648
+ }
649
+ }
650
+ }
651
+ ```
652
+
653
+ ### Registering SSE Routes
654
+
655
+ Call `registerSSERoutes` after registering the `@fastify/sse` plugin:
656
+
657
+ ```ts
658
+ const app = fastify()
659
+ app.setValidatorCompiler(validatorCompiler)
660
+ app.setSerializerCompiler(serializerCompiler)
661
+
662
+ // Register @fastify/sse plugin first
663
+ await app.register(FastifySSEPlugin)
664
+
665
+ // Then register SSE routes
666
+ context.registerSSERoutes(app)
667
+
668
+ // Optionally with global preHandler for authentication
669
+ context.registerSSERoutes(app, {
670
+ preHandler: async (request, reply) => {
671
+ if (!request.headers.authorization) {
672
+ reply.code(401).send({ error: 'Unauthorized' })
673
+ }
674
+ },
675
+ })
676
+
677
+ await app.ready()
678
+ ```
679
+
680
+ ### Broadcasting Events
681
+
682
+ Send events to multiple connections using `broadcast()` or `broadcastIf()`:
683
+
684
+ ```ts
685
+ // Broadcast to ALL connected clients
686
+ await this.broadcast({
687
+ event: 'system',
688
+ data: { message: 'Server maintenance in 5 minutes' },
689
+ })
690
+
691
+ // Broadcast to sessions matching a predicate
692
+ await this.broadcastIf(
693
+ { event: 'channel-update', data: { channelId: '123', newMessage: msg } },
694
+ (session) => session.context.channelId === '123',
695
+ )
696
+ ```
697
+
698
+ Both methods return the number of clients the message was successfully sent to.
699
+
700
+ ### Controller-Level Hooks
701
+
702
+ Override these optional methods on your controller for global session handling:
703
+
704
+ ```ts
705
+ class MySSEController extends AbstractSSEController<Contracts> {
706
+ // Called AFTER session is registered (for all routes)
707
+ protected onConnectionEstablished(session: SSESession): void {
708
+ this.metrics.incrementConnections()
709
+ }
710
+
711
+ // Called BEFORE session is unregistered (for all routes)
712
+ protected onConnectionClosed(session: SSESession): void {
713
+ this.metrics.decrementConnections()
714
+ }
715
+ }
716
+ ```
717
+
718
+ ### Route-Level Options
719
+
720
+ Each route can have its own `preHandler`, lifecycle hooks, and logger. Pass these as the third parameter to `buildHandler`:
721
+
722
+ ```ts
723
+ public buildSSERoutes() {
724
+ return {
725
+ adminStream: this.handleAdminStream,
726
+ }
727
+ }
728
+
729
+ private handleAdminStream = buildHandler(adminStreamContract, {
730
+ sse: async (request, sse) => {
731
+ const session = sse.start('keepAlive')
732
+ // ... handler logic
733
+ },
734
+ }, {
735
+ // Route-specific authentication
736
+ preHandler: (request, reply) => {
737
+ if (!request.user?.isAdmin) {
738
+ reply.code(403).send({ error: 'Forbidden' })
739
+ }
740
+ },
741
+ onConnect: (session) => console.log('Admin connected'),
742
+ onClose: (session, reason) => console.log(`Admin disconnected (${reason})`),
743
+ // Handle client reconnection with Last-Event-ID
744
+ onReconnect: async (session, lastEventId) => {
745
+ // Return events to replay, or handle manually
746
+ return this.getEventsSince(lastEventId)
747
+ },
748
+ // Optional: logger for error handling (requires @lokalise/node-core)
749
+ logger: this.logger,
750
+ })
751
+ ```
752
+
753
+ **Available route options:**
754
+
755
+ | Option | Description |
756
+ | -------- | ------------- |
757
+ | `preHandler` | Authentication/authorization hook that runs before SSE session |
758
+ | `onConnect` | Called after client connects (SSE handshake complete) |
759
+ | `onClose` | Called when session closes (client disconnect, network failure, or server close). Receives `(session, reason)` where reason is `'server'` or `'client'` |
760
+ | `onReconnect` | Handle Last-Event-ID reconnection, return events to replay |
761
+ | `logger` | Optional `SSELogger` for error handling (compatible with pino and `@lokalise/node-core`). If not provided, errors in lifecycle hooks are silently ignored |
762
+ | `serializer` | Custom serializer for SSE data (e.g., for custom JSON encoding) |
763
+ | `heartbeatInterval` | Interval in ms for heartbeat keep-alive messages |
764
+
765
+ **onClose reason parameter:**
766
+ - `'server'`: Server explicitly closed the session (via `closeConnection()` or `autoClose` mode)
767
+ - `'client'`: Client closed the session (EventSource.close(), navigation, network failure)
768
+
769
+ ```ts
770
+ options: {
771
+ onConnect: (session) => console.log('Client connected'),
772
+ onClose: (session, reason) => {
773
+ console.log(`Session closed (${reason}):`, session.id)
774
+ // reason is 'server' or 'client'
775
+ },
776
+ serializer: (data) => JSON.stringify(data, null, 2), // Pretty-print JSON
777
+ heartbeatInterval: 30000, // Send heartbeat every 30 seconds
778
+ }
779
+ ```
780
+
781
+ ### SSE Session Methods
782
+
783
+ The `session` object returned by `sse.start(mode)` provides several useful methods:
784
+
785
+ ```ts
786
+ private handleStream = buildHandler(streamContract, {
787
+ sse: async (request, sse) => {
788
+ const session = sse.start('autoClose')
789
+
790
+ // Check if session is still active
791
+ if (session.isConnected()) {
792
+ await session.send('status', { connected: true })
793
+ }
794
+
795
+ // Get raw writable stream for advanced use cases (e.g., pipeline)
796
+ const stream = session.getStream()
797
+
798
+ // Stream messages from an async iterable with automatic validation
799
+ async function* generateMessages() {
800
+ yield { event: 'message' as const, data: { text: 'Hello' } }
801
+ yield { event: 'message' as const, data: { text: 'World' } }
802
+ }
803
+ await session.sendStream(generateMessages())
804
+
805
+ // 'autoClose' mode: connection closes when handler returns
806
+ },
807
+ })
808
+ ```
809
+
810
+ | Method | Description |
811
+ | -------- | ------------- |
812
+ | `send(event, data, options?)` | Send a typed event (validates against contract schema) |
813
+ | `isConnected()` | Check if the session is still active |
814
+ | `getStream()` | Get the underlying `WritableStream` for advanced use cases |
815
+ | `sendStream(messages)` | Stream messages from an `AsyncIterable` with validation |
816
+
817
+ ### Graceful Shutdown
818
+
819
+ SSE controllers automatically close all connections during application shutdown. This is configured by `asSSEControllerClass` which sets `closeAllConnections` as the async dispose method with priority 5 (early in shutdown sequence).
820
+
821
+ ### Error Handling
822
+
823
+ When `sendEvent()` fails (e.g., client disconnected), it:
824
+ - Returns `false` to indicate failure
825
+ - Automatically removes the dead connection from tracking
826
+ - Prevents further send attempts to that connection
827
+
828
+ ```ts
829
+ const sent = await this.sendEvent(connectionId, { event: 'update', data })
830
+ if (!sent) {
831
+ // Connection was closed or failed - already removed from tracking
832
+ this.cleanup(connectionId)
833
+ }
834
+ ```
835
+
836
+ **Lifecycle hook errors** (`onConnect`, `onReconnect`, `onClose`):
837
+ - All lifecycle hooks are wrapped in try/catch to prevent crashes
838
+ - If a `logger` is provided in route options, errors are logged with context
839
+ - If no logger is provided, errors are silently ignored
840
+ - The session lifecycle continues even if a hook throws
841
+
842
+ ```ts
843
+ // Provide a logger to capture lifecycle errors
844
+ public buildSSERoutes() {
845
+ return {
846
+ stream: this.handleStream,
847
+ }
848
+ }
849
+
850
+ private handleStream = buildHandler(streamContract, {
851
+ sse: async (request, sse) => {
852
+ const session = sse.start('autoClose')
853
+ // ... handler logic
854
+ },
855
+ }, {
856
+ logger: this.logger, // pino-compatible logger
857
+ onConnect: (session) => { /* may throw */ },
858
+ onClose: (session, reason) => { /* may throw */ },
859
+ })
860
+ ```
861
+
862
+ ### Long-lived Connections vs Request-Response Streaming
863
+
864
+ SSE session lifetime is determined by the mode passed to `sse.start(mode)`:
865
+
866
+ ```ts
867
+ // sse.start('autoClose') - close connection when handler returns (request-response pattern)
868
+ // sse.start('keepAlive') - keep connection open for external events (subscription pattern)
869
+ // sse.respond(code, body) - send HTTP response before streaming (early return)
870
+ ```
871
+
872
+ **Long-lived sessions** (notifications, live updates):
873
+ - Handler starts streaming with `sse.start('keepAlive')`
874
+ - Session stays open indefinitely after handler returns
875
+ - Events are sent later via callbacks using `sendEventInternal()`
876
+ - **Client closes session** when done (e.g., `eventSource.close()` or navigating away)
877
+ - Server cleans up via `onConnectionClosed()` hook
878
+
879
+ ```ts
880
+ private handleStream = buildHandler(streamContract, {
881
+ sse: async (request, sse) => {
882
+ // Start streaming with 'keepAlive' mode - stays open for external events
883
+ const session = sse.start('keepAlive')
884
+
885
+ // Set up subscription - events sent via callback AFTER handler returns
886
+ this.service.subscribe(session.id, (data) => {
887
+ this.sendEventInternal(session.id, { event: 'update', data })
888
+ })
889
+ // 'keepAlive' mode: handler returns, but connection stays open
890
+ },
891
+ })
892
+
893
+ // Clean up when client disconnects
894
+ protected onConnectionClosed(session: SSESession): void {
895
+ this.service.unsubscribe(session.id)
896
+ }
897
+ ```
898
+
899
+ **Request-response streaming** (AI completions):
900
+ - Handler starts streaming with `sse.start('autoClose')`
901
+ - Use `session.send()` for type-safe event sending within the handler
902
+ - Session automatically closes when handler returns
903
+
904
+ ```ts
905
+ private handleChatCompletion = buildHandler(chatCompletionContract, {
906
+ sse: async (request, sse) => {
907
+ // Start streaming with 'autoClose' mode - closes when handler returns
908
+ const session = sse.start('autoClose')
909
+
910
+ const words = request.body.message.split(' ')
911
+ for (const word of words) {
912
+ await session.send('chunk', { content: word })
913
+ }
914
+ await session.send('done', { totalTokens: words.length })
915
+
916
+ // 'autoClose' mode: connection closes automatically when handler returns
917
+ },
918
+ })
919
+ ```
920
+
921
+ **Error handling before streaming:**
922
+
923
+ Use `sse.respond(code, body)` to return an HTTP response before streaming starts. This is useful for any early return: validation errors, not found, redirects, etc.
924
+
925
+ ```ts
926
+ private handleStream = buildHandler(streamContract, {
927
+ sse: async (request, sse) => {
928
+ // Early return BEFORE starting stream - can return any HTTP response
929
+ const entity = await this.service.find(request.params.id)
930
+ if (!entity) {
931
+ return sse.respond(404, { error: 'Entity not found' })
932
+ }
933
+
934
+ // Validation passed - start streaming with autoClose mode
935
+ const session = sse.start('autoClose')
936
+ await session.send('data', entity)
937
+ // Connection closes automatically when handler returns
938
+ },
939
+ })
940
+
941
+ ### SSE Parsing Utilities
942
+
943
+ The library provides production-ready utilities for parsing SSE (Server-Sent Events) streams:
944
+
945
+ | Function | Use Case |
946
+ |----------|----------|
947
+ | `parseSSEEvents` | **Testing & complete responses** - when you have the full response body |
948
+ | `parseSSEBuffer` | **Production streaming** - when data arrives incrementally in chunks |
949
+
950
+ #### parseSSEEvents
951
+
952
+ Parse a complete SSE response body into an array of events.
953
+
954
+ **When to use:** Testing with Fastify's `inject()`, or when the full response is available (e.g., request-response style SSE like OpenAI completions):
955
+
956
+ ```ts
957
+ import { parseSSEEvents, type ParsedSSEEvent } from 'opinionated-machine'
958
+
959
+ const responseBody = `event: notification
960
+ data: {"id":"1","message":"Hello"}
961
+
962
+ event: notification
963
+ data: {"id":"2","message":"World"}
964
+
965
+ `
966
+
967
+ const events: ParsedSSEEvent[] = parseSSEEvents(responseBody)
968
+ // Result:
969
+ // [
970
+ // { event: 'notification', data: '{"id":"1","message":"Hello"}' },
971
+ // { event: 'notification', data: '{"id":"2","message":"World"}' }
972
+ // ]
973
+
974
+ // Access parsed data
975
+ const notifications = events.map(e => JSON.parse(e.data))
976
+ ```
977
+
978
+ #### parseSSEBuffer
979
+
980
+ Parse a streaming SSE buffer, handling incomplete events at chunk boundaries.
981
+
982
+ **When to use:** Production clients consuming real-time SSE streams (notifications, live feeds, chat) where events arrive incrementally:
983
+
984
+ ```ts
985
+ import { parseSSEBuffer, type ParseSSEBufferResult } from 'opinionated-machine'
986
+
987
+ let buffer = ''
988
+
989
+ // As chunks arrive from a stream...
990
+ for await (const chunk of stream) {
991
+ buffer += chunk
992
+ const result: ParseSSEBufferResult = parseSSEBuffer(buffer)
993
+
994
+ // Process complete events
995
+ for (const event of result.events) {
996
+ console.log('Received:', event.event, event.data)
997
+ }
998
+
999
+ // Keep incomplete data for next chunk
1000
+ buffer = result.remaining
1001
+ }
1002
+ ```
1003
+
1004
+ **Production example with fetch:**
1005
+
1006
+ ```ts
1007
+ const response = await fetch(url)
1008
+ const reader = response.body!.getReader()
1009
+ const decoder = new TextDecoder()
1010
+ let buffer = ''
1011
+
1012
+ while (true) {
1013
+ const { done, value } = await reader.read()
1014
+ if (done) break
1015
+
1016
+ buffer += decoder.decode(value, { stream: true })
1017
+ const { events, remaining } = parseSSEBuffer(buffer)
1018
+ buffer = remaining
1019
+
1020
+ for (const event of events) {
1021
+ console.log('Received:', event.event, JSON.parse(event.data))
1022
+ }
1023
+ }
1024
+ ```
1025
+
1026
+ #### ParsedSSEEvent Type
1027
+
1028
+ Both functions return events with this structure:
1029
+
1030
+ ```ts
1031
+ type ParsedSSEEvent = {
1032
+ id?: string // Event ID (from "id:" field)
1033
+ event?: string // Event type (from "event:" field)
1034
+ data: string // Event data (from "data:" field, always present)
1035
+ retry?: number // Reconnection interval (from "retry:" field)
1036
+ }
1037
+ ```
1038
+
1039
+ ### Testing SSE Controllers
1040
+
1041
+ Enable the connection spy for testing by passing `isTestMode: true` in diOptions:
1042
+
1043
+ ```ts
1044
+ import { createContainer } from 'awilix'
1045
+ import { DIContext, SSETestServer, SSEHttpClient } from 'opinionated-machine'
1046
+
1047
+ describe('NotificationsSSEController', () => {
1048
+ let server: SSETestServer
1049
+ let controller: NotificationsSSEController
1050
+
1051
+ beforeEach(async () => {
1052
+ // Create test server with isTestMode enabled
1053
+ server = await SSETestServer.create(
1054
+ async (app) => {
1055
+ // Register your SSE routes here
1056
+ },
1057
+ {
1058
+ setup: async () => {
1059
+ // Set up DI container and resources
1060
+ return { context }
1061
+ },
1062
+ }
1063
+ )
1064
+
1065
+ controller = server.resources.context.diContainer.cradle.notificationsSSEController
1066
+ })
1067
+
1068
+ afterEach(async () => {
1069
+ await server.resources.context.destroy()
1070
+ await server.close()
1071
+ })
1072
+
1073
+ it('receives notifications over SSE', async () => {
1074
+ // Connect with awaitServerConnection to eliminate race condition
1075
+ const { client, serverConnection } = await SSEHttpClient.connect(
1076
+ server.baseUrl,
1077
+ '/api/notifications/stream',
1078
+ {
1079
+ query: { userId: 'test-user' },
1080
+ awaitServerConnection: { controller },
1081
+ },
1082
+ )
1083
+
1084
+ expect(client.response.ok).toBe(true)
1085
+
1086
+ // Start collecting events
1087
+ const eventsPromise = client.collectEvents(2)
1088
+
1089
+ // Send events from server (serverConnection is ready immediately)
1090
+ await controller.sendEvent(serverConnection.id, {
1091
+ event: 'notification',
1092
+ data: { id: '1', message: 'Hello!' },
1093
+ })
1094
+
1095
+ await controller.sendEvent(serverConnection.id, {
1096
+ event: 'notification',
1097
+ data: { id: '2', message: 'World!' },
1098
+ })
1099
+
1100
+ // Wait for events
1101
+ const events = await eventsPromise
1102
+
1103
+ expect(events).toHaveLength(2)
1104
+ expect(JSON.parse(events[0].data)).toEqual({ id: '1', message: 'Hello!' })
1105
+ expect(JSON.parse(events[1].data)).toEqual({ id: '2', message: 'World!' })
1106
+
1107
+ // Clean up
1108
+ client.close()
1109
+ })
1110
+ })
1111
+ ```
1112
+
1113
+ ### SSESessionSpy API
1114
+
1115
+ The `connectionSpy` is available when `isTestMode: true` is passed to `asSSEControllerClass`:
1116
+
1117
+ ```ts
1118
+ // Wait for a session to be established (with timeout)
1119
+ const session = await controller.connectionSpy.waitForConnection({ timeout: 5000 })
1120
+
1121
+ // Wait for a session matching a predicate (useful for multiple sessions)
1122
+ const session = await controller.connectionSpy.waitForConnection({
1123
+ timeout: 5000,
1124
+ predicate: (s) => s.request.url.includes('/api/notifications'),
1125
+ })
1126
+
1127
+ // Check if a specific session is active
1128
+ const isConnected = controller.connectionSpy.isConnected(sessionId)
1129
+
1130
+ // Wait for a specific session to disconnect
1131
+ await controller.connectionSpy.waitForDisconnection(sessionId, { timeout: 5000 })
1132
+
1133
+ // Get all session events (connect/disconnect history)
1134
+ const events = controller.connectionSpy.getEvents()
1135
+
1136
+ // Clear event history and claimed sessions between tests
1137
+ controller.connectionSpy.clear()
1138
+ ```
1139
+
1140
+ **Note**: `waitForConnection` tracks "claimed" sessions internally. Each call returns a unique unclaimed session, allowing sequential waits for the same URL path without returning the same session twice. This is used internally by `SSEHttpClient.connect()` with `awaitServerConnection`.
1141
+
1142
+ ### Session Monitoring
1143
+
1144
+ Controllers have access to utility methods for monitoring sessions:
1145
+
1146
+ ```ts
1147
+ // Get count of active sessions
1148
+ const count = this.getConnectionCount()
1149
+
1150
+ // Get all active sessions (for iteration/inspection)
1151
+ const sessions = this.getConnections()
1152
+
1153
+ // Check if session spy is enabled (useful for conditional logic)
1154
+ if (this.hasConnectionSpy()) {
1155
+ // ...
1156
+ }
1157
+ ```
1158
+
1159
+ ### SSE Test Utilities
1160
+
1161
+ The library provides utilities for testing SSE endpoints.
1162
+
1163
+ **Two transport methods:**
1164
+ - **Inject** - Uses Fastify's built-in `inject()` to simulate HTTP requests directly in-memory, without network overhead. No `listen()` required. Handler must close the session for the request to complete.
1165
+ - **Real HTTP** - Actual HTTP via `fetch()`. Requires the server to be listening. Supports long-lived sessions.
1166
+
1167
+ #### Quick Reference
1168
+
1169
+ | Utility | Connection | Requires Contract | Use Case |
1170
+ |---------|------------|-------------------|----------|
1171
+ | `SSEInjectClient` | Inject (in-memory) | No | Request-response SSE without contracts |
1172
+ | `injectSSE` / `injectPayloadSSE` | Inject (in-memory) | **Yes** | Request-response SSE with type-safe contracts |
1173
+ | `SSEHttpClient` | Real HTTP | No | Long-lived SSE connections |
1174
+
1175
+ `SSEInjectClient` and `injectSSE`/`injectPayloadSSE` do the same thing (Fastify inject), but `injectSSE`/`injectPayloadSSE` provide type safety via contracts while `SSEInjectClient` works with raw URLs.
1176
+
1177
+ #### Inject vs HTTP Comparison
1178
+
1179
+ | Feature | Inject (`SSEInjectClient`, `injectSSE`) | HTTP (`SSEHttpClient`) |
1180
+ |---------|----------------------------------------|------------------------|
1181
+ | **Connection** | Fastify's `inject()` - in-memory | Real HTTP via `fetch()` |
1182
+ | **Event delivery** | All events returned at once (after handler closes) | Events arrive incrementally |
1183
+ | **Connection lifecycle** | Handler must close for request to complete | Can stay open indefinitely |
1184
+ | **Server requirement** | No `listen()` needed | Requires running server |
1185
+ | **Best for** | OpenAI-style streaming, batch exports | Notifications, live feeds, chat |
1186
+
1187
+ #### SSETestServer
1188
+
1189
+ Creates a test server with `@fastify/sse` pre-configured:
1190
+
1191
+ ```ts
1192
+ import { SSETestServer, SSEHttpClient } from 'opinionated-machine'
1193
+
1194
+ // Basic usage
1195
+ const server = await SSETestServer.create(async (app) => {
1196
+ app.get('/api/events', async (request, reply) => {
1197
+ reply.sse({ event: 'message', data: { hello: 'world' } })
1198
+ reply.sse.close()
1199
+ })
1200
+ })
1201
+
1202
+ // Connect and test
1203
+ const client = await SSEHttpClient.connect(server.baseUrl, '/api/events')
1204
+ const events = await client.collectEvents(1)
1205
+ expect(events[0].event).toBe('message')
1206
+
1207
+ // Cleanup
1208
+ client.close()
1209
+ await server.close()
1210
+ ```
1211
+
1212
+ With custom resources (DI container, controllers):
1213
+
1214
+ ```ts
1215
+ const server = await SSETestServer.create(
1216
+ async (app) => {
1217
+ // Register routes using resources from setup
1218
+ myController.registerRoutes(app)
1219
+ },
1220
+ {
1221
+ configureApp: async (app) => {
1222
+ app.setValidatorCompiler(validatorCompiler)
1223
+ },
1224
+ setup: async () => {
1225
+ // Resources are available via server.resources
1226
+ const container = createContainer()
1227
+ return { container }
1228
+ },
1229
+ }
1230
+ )
1231
+
1232
+ const { container } = server.resources
1233
+ ```
1234
+
1235
+ #### SSEHttpClient
1236
+
1237
+ For testing long-lived SSE connections using real HTTP:
1238
+
1239
+ ```ts
1240
+ import { SSEHttpClient } from 'opinionated-machine'
1241
+
1242
+ // Connect to SSE endpoint with awaitServerConnection (recommended)
1243
+ // This eliminates the race condition between client connect and server-side registration
1244
+ const { client, serverConnection } = await SSEHttpClient.connect(
1245
+ server.baseUrl,
1246
+ '/api/stream',
1247
+ {
1248
+ query: { userId: 'test' },
1249
+ headers: { authorization: 'Bearer token' },
1250
+ awaitServerConnection: { controller }, // Pass your SSE controller
1251
+ },
1252
+ )
1253
+
1254
+ // serverConnection is ready to use immediately
1255
+ expect(client.response.ok).toBe(true)
1256
+ await controller.sendEvent(serverConnection.id, { event: 'test', data: {} })
1257
+
1258
+ // Collect events by count with timeout
1259
+ const events = await client.collectEvents(3, 5000) // 3 events, 5s timeout
1260
+
1261
+ // Or collect until a predicate is satisfied
1262
+ const events = await client.collectEvents(
1263
+ (event) => event.event === 'done',
1264
+ 5000,
1265
+ )
1266
+
1267
+ // Iterate over events as they arrive
1268
+ for await (const event of client.events()) {
1269
+ console.log(event.event, event.data)
1270
+ if (event.event === 'done') break
1271
+ }
1272
+
1273
+ // Cleanup
1274
+ client.close()
1275
+ ```
1276
+
1277
+ **`collectEvents(countOrPredicate, timeout?)`**
1278
+
1279
+ Collects events until a count is reached or a predicate returns true.
1280
+
1281
+ | Parameter | Type | Description |
1282
+ |-----------|------|-------------|
1283
+ | `countOrPredicate` | `number \| (event) => boolean` | Number of events to collect, or predicate that returns `true` when collection should stop |
1284
+ | `timeout` | `number` | Maximum time to wait in milliseconds (default: 5000) |
1285
+
1286
+ Returns `Promise<ParsedSSEEvent[]>`. Throws an error if the timeout is reached before the condition is met.
1287
+
1288
+ ```ts
1289
+ // Collect exactly 3 events
1290
+ const events = await client.collectEvents(3)
1291
+
1292
+ // Collect with custom timeout
1293
+ const events = await client.collectEvents(5, 10000) // 10s timeout
1294
+
1295
+ // Collect until a specific event type (the matching event IS included)
1296
+ const events = await client.collectEvents((event) => event.event === 'done')
1297
+
1298
+ // Collect until condition with timeout
1299
+ const events = await client.collectEvents(
1300
+ (event) => JSON.parse(event.data).status === 'complete',
1301
+ 30000,
1302
+ )
1303
+ ```
1304
+
1305
+ **`events(signal?)`**
1306
+
1307
+ Async generator that yields events as they arrive. Accepts an optional `AbortSignal` for cancellation.
1308
+
1309
+ ```ts
1310
+ // Basic iteration
1311
+ for await (const event of client.events()) {
1312
+ console.log(event.event, event.data)
1313
+ if (event.event === 'done') break
1314
+ }
1315
+
1316
+ // With abort signal for timeout control
1317
+ const controller = new AbortController()
1318
+ const timeoutId = setTimeout(() => controller.abort(), 5000)
1319
+
1320
+ try {
1321
+ for await (const event of client.events(controller.signal)) {
1322
+ console.log(event)
1323
+ }
1324
+ } finally {
1325
+ clearTimeout(timeoutId)
1326
+ }
1327
+ ```
1328
+
1329
+ **When to omit `awaitServerConnection`**
1330
+
1331
+ Omit `awaitServerConnection` only in these cases:
1332
+ - Testing against external SSE endpoints (not your own controller)
1333
+ - When `isTestMode: false` (connectionSpy not available)
1334
+ - Simple smoke tests that only verify response headers/status without sending server events
1335
+
1336
+ **Consequence**: Without `awaitServerConnection`, `connect()` resolves as soon as HTTP headers are received. Server-side connection registration may not have completed yet, so you cannot reliably send events from the server immediately after `connect()` returns.
1337
+
1338
+ ```ts
1339
+ // Example: smoke test that only checks connection works
1340
+ const client = await SSEHttpClient.connect(server.baseUrl, '/api/stream')
1341
+ expect(client.response.ok).toBe(true)
1342
+ expect(client.response.headers.get('content-type')).toContain('text/event-stream')
1343
+ client.close()
1344
+ ```
1345
+
1346
+ #### SSEInjectClient
1347
+
1348
+ For testing request-response style SSE streams (like OpenAI completions):
1349
+
1350
+ ```ts
1351
+ import { SSEInjectClient } from 'opinionated-machine'
1352
+
1353
+ const client = new SSEInjectClient(app) // No server.listen() needed
1354
+
1355
+ // GET request
1356
+ const conn = await client.connect('/api/export/progress', {
1357
+ headers: { authorization: 'Bearer token' },
1358
+ })
1359
+
1360
+ // POST request with body (OpenAI-style)
1361
+ const conn = await client.connectWithBody(
1362
+ '/api/chat/completions',
1363
+ { model: 'gpt-4', messages: [...], stream: true },
1364
+ )
1365
+
1366
+ // All events are available immediately (inject waits for complete response)
1367
+ expect(conn.getStatusCode()).toBe(200)
1368
+ const events = conn.getReceivedEvents()
1369
+ const chunks = events.filter(e => e.event === 'chunk')
1370
+ ```
1371
+
1372
+ #### Contract-Aware Inject Helpers
1373
+
1374
+ For typed testing with SSE contracts:
1375
+
1376
+ ```ts
1377
+ import { injectSSE, injectPayloadSSE, parseSSEEvents } from 'opinionated-machine'
1378
+
1379
+ // For GET SSE endpoints with contracts
1380
+ const { closed } = injectSSE(app, notificationsContract, {
1381
+ query: { userId: 'test' },
1382
+ })
1383
+ const result = await closed
1384
+ const events = parseSSEEvents(result.body)
1385
+
1386
+ // For POST/PUT/PATCH SSE endpoints with contracts
1387
+ const { closed } = injectPayloadSSE(app, chatCompletionContract, {
1388
+ body: { message: 'Hello', stream: true },
1389
+ })
1390
+ const result = await closed
1391
+ const events = parseSSEEvents(result.body)
1392
+ ```
1393
+
1394
+ ## Dual-Mode Controllers (SSE + Sync)
1395
+
1396
+ Dual-mode controllers handle both SSE streaming and sync responses on the same route path, automatically branching based on the `Accept` header. This is ideal for APIs that support both real-time streaming and traditional request-response patterns.
1397
+
1398
+ ### Overview
1399
+
1400
+ | Accept Header | Response Mode |
1401
+ | ------------- | ------------- |
1402
+ | `text/event-stream` | SSE streaming |
1403
+ | `application/json` | Sync response |
1404
+ | `*/*` or missing | Sync (default, configurable) |
1405
+
1406
+ Dual-mode controllers extend `AbstractDualModeController` which inherits from `AbstractSSEController`, providing access to all SSE features (connection management, broadcasting, lifecycle hooks) while adding sync response support.
1407
+
1408
+ ### Defining Dual-Mode Contracts
1409
+
1410
+ Dual-mode contracts define endpoints that can return **either** a complete sync response **or** stream SSE events, based on the client's `Accept` header. Use dual-mode when:
1411
+
1412
+ - Clients may want immediate results (sync) or real-time updates (SSE)
1413
+ - You're building OpenAI-style APIs where `stream: true` triggers SSE
1414
+ - You need polling fallback for clients that don't support SSE
1415
+
1416
+ To create a dual-mode contract, include a `syncResponseBody` schema in your `buildSseContract` call:
1417
+ - Has `syncResponseBody` but no `requestBody` → GET dual-mode route
1418
+ - Has both `syncResponseBody` and `requestBody` → POST/PUT/PATCH dual-mode route
1419
+
1420
+ ```ts
1421
+ import { z } from 'zod'
1422
+ import { buildSseContract } from '@lokalise/api-contracts'
1423
+
1424
+ // GET dual-mode route (polling or streaming job status) - has syncResponseBody, no requestBody
1425
+ export const jobStatusContract = buildSseContract({
1426
+ pathResolver: (params) => `/api/jobs/${params.jobId}/status`,
1427
+ params: z.object({ jobId: z.string().uuid() }),
1428
+ query: z.object({ verbose: z.string().optional() }),
1429
+ requestHeaders: z.object({}),
1430
+ syncResponseBody: z.object({
1431
+ status: z.enum(['pending', 'running', 'completed', 'failed']),
1432
+ progress: z.number(),
1433
+ result: z.string().optional(),
1434
+ }),
1435
+ sseEvents: {
1436
+ progress: z.object({ percent: z.number(), message: z.string().optional() }),
1437
+ done: z.object({ result: z.string() }),
1438
+ },
1439
+ })
1440
+
1441
+ // POST dual-mode route (OpenAI-style chat completion) - has both syncResponseBody and requestBody
1442
+ export const chatCompletionContract = buildSseContract({
1443
+ method: 'post',
1444
+ pathResolver: (params) => `/api/chats/${params.chatId}/completions`,
1445
+ params: z.object({ chatId: z.string().uuid() }),
1446
+ query: z.object({}),
1447
+ requestHeaders: z.object({ authorization: z.string() }),
1448
+ requestBody: z.object({ message: z.string() }),
1449
+ syncResponseBody: z.object({
1450
+ reply: z.string(),
1451
+ usage: z.object({ tokens: z.number() }),
1452
+ }),
1453
+ sseEvents: {
1454
+ chunk: z.object({ delta: z.string() }),
1455
+ done: z.object({ usage: z.object({ total: z.number() }) }),
1456
+ },
1457
+ })
1458
+ ```
1459
+
1460
+ **Note**: Dual-mode contracts use `pathResolver` instead of static `path` for type-safe path construction. The `pathResolver` function receives typed params and returns the URL path.
1461
+
1462
+ ### Response Headers (Sync Mode)
1463
+
1464
+ Dual-mode contracts support an optional `responseHeaders` schema to define and validate headers sent with sync responses. This is useful for documenting expected headers (rate limits, pagination, cache control) and validating that your handlers set them correctly:
1465
+
1466
+ ```ts
1467
+ export const rateLimitedContract = buildSseContract({
1468
+ method: 'post',
1469
+ pathResolver: () => '/api/rate-limited',
1470
+ params: z.object({}),
1471
+ query: z.object({}),
1472
+ requestHeaders: z.object({}),
1473
+ requestBody: z.object({ data: z.string() }),
1474
+ syncResponseBody: z.object({ result: z.string() }),
1475
+ // Define expected response headers
1476
+ responseHeaders: z.object({
1477
+ 'x-ratelimit-limit': z.string(),
1478
+ 'x-ratelimit-remaining': z.string(),
1479
+ 'x-ratelimit-reset': z.string(),
1480
+ }),
1481
+ sseEvents: {
1482
+ result: z.object({ success: z.boolean() }),
1483
+ },
1484
+ })
1485
+ ```
1486
+
1487
+ In your handler, set headers using `reply.header()`:
1488
+
1489
+ ```ts
1490
+ handlers: buildHandler(rateLimitedContract, {
1491
+ sync: async (request, reply) => {
1492
+ reply.header('x-ratelimit-limit', '100')
1493
+ reply.header('x-ratelimit-remaining', '99')
1494
+ reply.header('x-ratelimit-reset', '1640000000')
1495
+ return { result: 'success' }
1496
+ },
1497
+ sse: async (request, sse) => {
1498
+ const session = sse.start('autoClose')
1499
+ // ... send events ...
1500
+ // Connection closes automatically when handler returns
1501
+ },
1502
+ })
1503
+ ```
1504
+
1505
+ If the handler doesn't set the required headers, validation will fail with a `RESPONSE_HEADERS_VALIDATION_FAILED` error.
1506
+
1507
+ ### Status-Specific Response Schemas (responseSchemasByStatusCode)
1508
+
1509
+ Dual-mode and SSE contracts support `responseSchemasByStatusCode` to define and validate responses for specific HTTP status codes. This is typically used for error responses (4xx, 5xx), but can define schemas for any status code where you need a different response shape:
1510
+
1511
+ ```ts
1512
+ export const resourceContract = buildSseContract({
1513
+ method: 'post',
1514
+ pathResolver: (params) => `/api/resources/${params.id}`,
1515
+ params: z.object({ id: z.string() }),
1516
+ query: z.object({}),
1517
+ requestHeaders: z.object({}),
1518
+ requestBody: z.object({ data: z.string() }),
1519
+ // Success response (2xx)
1520
+ syncResponseBody: z.object({
1521
+ success: z.boolean(),
1522
+ data: z.string(),
1523
+ }),
1524
+ // Responses by status code (typically used for errors)
1525
+ responseSchemasByStatusCode: {
1526
+ 400: z.object({ error: z.string(), details: z.array(z.string()) }),
1527
+ 404: z.object({ error: z.string(), resourceId: z.string() }),
1528
+ },
1529
+ sseEvents: {
1530
+ result: z.object({ success: z.boolean() }),
1531
+ },
1532
+ })
1533
+ ```
1534
+
1535
+ **Recommended: Use `sse.respond()` for strict type safety**
1536
+
1537
+ In SSE handlers, use `sse.respond(code, body)` for non-2xx responses. This provides strict compile-time type enforcement - TypeScript ensures the body matches the exact schema for that status code:
1538
+
1539
+ ```ts
1540
+ handlers: buildHandler(resourceContract, {
1541
+ sync: (request, reply) => {
1542
+ if (!isValid(request.body.data)) {
1543
+ reply.code(400)
1544
+ return { error: 'Bad Request', details: ['Invalid data format'] }
1545
+ }
1546
+ return { success: true, data: 'OK' }
1547
+ },
1548
+ sse: async (request, sse) => {
1549
+ const resource = findResource(request.params.id)
1550
+ if (!resource) {
1551
+ // Strict typing: TypeScript enforces exact schema for status 404
1552
+ return sse.respond(404, { error: 'Not Found', resourceId: request.params.id })
1553
+ }
1554
+ if (!isValid(resource)) {
1555
+ // Strict typing: TypeScript enforces exact schema for status 400
1556
+ return sse.respond(400, { error: 'Bad Request', details: ['Invalid resource'] })
1557
+ }
1558
+
1559
+ const session = sse.start('autoClose')
1560
+ await session.send('result', { success: true })
1561
+ },
1562
+ })
1563
+ ```
1564
+
1565
+ TypeScript enforces the exact schema for each status code at compile time:
1566
+
1567
+ ```ts
1568
+ sse.respond(404, { error: 'Not Found', resourceId: '123' }) // ✓ OK
1569
+ sse.respond(404, { error: 'Not Found' }) // Error - missing resourceId
1570
+ sse.respond(404, { error: 'Not Found', details: [] }) // ✗ Error - wrong schema for 404
1571
+ sse.respond(500, { message: 'error' }) // Error - 500 not defined in schema
1572
+ ```
1573
+
1574
+ Only status codes defined in `responseSchemasByStatusCode` are allowed. To use an undefined status code, add it to the schema or use a type assertion.
1575
+
1576
+ **Sync handlers (union typing with runtime validation):**
1577
+
1578
+ For sync handlers, use `reply.code()` to set the status code and return the response. However, since `reply.code()` and `return` are separate statements, TypeScript cannot correlate them. The return type is a union of all possible response shapes, and runtime validation catches mismatches:
1579
+
1580
+ ```ts
1581
+ sync: (request, reply) => {
1582
+ reply.code(404)
1583
+ return { error: 'Not Found', resourceId: '123' } // ✓ OK - matches one of the union types
1584
+ // Runtime validation ensures body matches the 404 schema
1585
+ }
1586
+
1587
+ // The sync handler return type is automatically:
1588
+ // { success: boolean; data: string } // from syncResponseBody
1589
+ // | { error: string; details: string[] } // from responseSchemasByStatusCode[400]
1590
+ // | { error: string; resourceId: string } // from responseSchemasByStatusCode[404]
1591
+ ```
1592
+
1593
+ **Validation behavior:**
1594
+
1595
+ - **Success responses (2xx)**: Validated against `syncResponseBody` schema
1596
+ - **Non-2xx responses**: Validated against the matching schema in `responseSchemasByStatusCode` (if defined)
1597
+ - **Validation failures**: Return 500 Internal Server Error (validation details are logged internally, not exposed to clients)
1598
+
1599
+ **Validation priority for 2xx status codes:**
1600
+
1601
+ - All 2xx responses (200, 201, 204, etc.) are validated against `syncResponseBody`
1602
+ - `responseSchemasByStatusCode` is only used for non-2xx status codes
1603
+ - If you define the same 2xx code in both, `syncResponseBody` takes precedence
1604
+
1605
+ ### Single Sync Handler
1606
+
1607
+ Dual-mode contracts use a single `sync` handler that returns the response data. The framework handles content-type negotiation automatically:
1608
+
1609
+ ```ts
1610
+ handlers: buildHandler(chatCompletionContract, {
1611
+ sync: async (request, reply) => {
1612
+ // Return the response data matching syncResponseBody schema
1613
+ const result = await aiService.complete(request.body.message)
1614
+ return {
1615
+ reply: result.text,
1616
+ usage: { tokens: result.tokenCount },
1617
+ }
1618
+ },
1619
+ sse: async (request, sse) => {
1620
+ // SSE streaming handler
1621
+ const session = sse.start('autoClose')
1622
+ // ... stream events ...
1623
+ },
1624
+ })
1625
+ ```
1626
+
1627
+ TypeScript enforces the correct handler structure:
1628
+ - `syncResponseBody` contracts must use `sync` handler (returns response data)
1629
+ - `sseEvents` contracts must use `sse` handler (streams events)
1630
+
1631
+ ### Implementing Dual-Mode Controllers
1632
+
1633
+ Dual-mode controllers use `buildHandler` to define both sync and SSE handlers. The handler is returned directly from `buildDualModeRoutes`, with options passed as the third parameter to `buildHandler`:
1634
+
1635
+ ```ts
1636
+ import {
1637
+ AbstractDualModeController,
1638
+ buildHandler,
1639
+ type BuildFastifyDualModeRoutesReturnType,
1640
+ type DualModeControllerConfig,
1641
+ } from 'opinionated-machine'
1642
+
1643
+ type Contracts = {
1644
+ chatCompletion: typeof chatCompletionContract
1645
+ }
1646
+
1647
+ type Dependencies = {
1648
+ aiService: AIService
1649
+ }
1650
+
1651
+ export class ChatDualModeController extends AbstractDualModeController<Contracts> {
1652
+ public static contracts = {
1653
+ chatCompletion: chatCompletionContract,
1654
+ } as const
1655
+
1656
+ private readonly aiService: AIService
1657
+
1658
+ constructor(deps: Dependencies, config?: DualModeControllerConfig) {
1659
+ super(deps, config)
1660
+ this.aiService = deps.aiService
1661
+ }
1662
+
1663
+ public buildDualModeRoutes(): BuildFastifyDualModeRoutesReturnType<Contracts> {
1664
+ return {
1665
+ chatCompletion: this.handleChatCompletion,
1666
+ }
1667
+ }
1668
+
1669
+ // Handler with options as third parameter
1670
+ private handleChatCompletion = buildHandler(chatCompletionContract, {
1671
+ // Sync mode - return complete response
1672
+ sync: async (request, _reply) => {
1673
+ const result = await this.aiService.complete(request.body.message)
1674
+ return {
1675
+ reply: result.text,
1676
+ usage: { tokens: result.tokenCount },
1677
+ }
1678
+ },
1679
+ // SSE mode - stream response chunks
1680
+ sse: async (request, sse) => {
1681
+ const session = sse.start('autoClose')
1682
+ let totalTokens = 0
1683
+ for await (const chunk of this.aiService.stream(request.body.message)) {
1684
+ await session.send('chunk', { delta: chunk.text })
1685
+ totalTokens += chunk.tokenCount ?? 0
1686
+ }
1687
+ await session.send('done', { usage: { total: totalTokens } })
1688
+ // Connection closes automatically when handler returns
1689
+ },
1690
+ }, {
1691
+ // Optional: set SSE as default mode (instead of sync)
1692
+ defaultMode: 'sse',
1693
+ // Optional: route-level authentication
1694
+ preHandler: (request, reply) => {
1695
+ if (!request.headers.authorization) {
1696
+ return Promise.resolve(reply.code(401).send({ error: 'Unauthorized' }))
1697
+ }
1698
+ },
1699
+ // Optional: SSE lifecycle hooks
1700
+ onConnect: (session) => console.log('Client connected:', session.id),
1701
+ onClose: (session, reason) => console.log(`Client disconnected (${reason}):`, session.id),
1702
+ })
1703
+ }
1704
+ ```
1705
+
1706
+ **Handler Signatures:**
1707
+
1708
+ | Mode | Signature |
1709
+ | ---- | --------- |
1710
+ | `sync` | `(request, reply) => Response` |
1711
+ | `sse` | `(request, sse) => SSEHandlerResult` |
1712
+
1713
+ The `sync` handler must return a value matching `syncResponseBody` schema. The `sse` handler uses `sse.start(mode)` to begin streaming (`'autoClose'` for request-response, `'keepAlive'` for long-lived sessions) and `session.send()` for type-safe event sending.
1714
+
1715
+ ### Registering Dual-Mode Controllers
1716
+
1717
+ Use `asDualModeControllerClass` in your module:
1718
+
1719
+ ```ts
1720
+ import {
1721
+ AbstractModule,
1722
+ asControllerClass,
1723
+ asDualModeControllerClass,
1724
+ asServiceClass,
1725
+ } from 'opinionated-machine'
1726
+
1727
+ export class ChatModule extends AbstractModule<Dependencies> {
1728
+ resolveDependencies() {
1729
+ return {
1730
+ aiService: asServiceClass(AIService),
1731
+ }
1732
+ }
1733
+
1734
+ resolveControllers(diOptions: DependencyInjectionOptions) {
1735
+ return {
1736
+ // REST controller
1737
+ usersController: asControllerClass(UsersController),
1738
+ // Dual-mode controller (auto-detected via isDualModeController flag)
1739
+ chatController: asDualModeControllerClass(ChatDualModeController, { diOptions }),
1740
+ }
1741
+ }
1742
+ }
1743
+ ```
1744
+
1745
+ Register dual-mode routes after the `@fastify/sse` plugin:
1746
+
1747
+ ```ts
1748
+ const app = fastify()
1749
+ app.setValidatorCompiler(validatorCompiler)
1750
+ app.setSerializerCompiler(serializerCompiler)
1751
+
1752
+ // Register @fastify/sse plugin
1753
+ await app.register(FastifySSEPlugin)
1754
+
1755
+ // Register routes
1756
+ context.registerRoutes(app) // REST routes
1757
+ context.registerSSERoutes(app) // SSE-only routes
1758
+ context.registerDualModeRoutes(app) // Dual-mode routes
1759
+
1760
+ // Check if controllers exist before registration (optional)
1761
+ if (context.hasDualModeControllers()) {
1762
+ context.registerDualModeRoutes(app)
1763
+ }
1764
+
1765
+ await app.ready()
1766
+ ```
1767
+
1768
+ ### Accept Header Routing
1769
+
1770
+ The `Accept` header determines response mode:
1771
+
1772
+ ```bash
1773
+ # JSON mode (complete response)
1774
+ curl -X POST http://localhost:3000/api/chats/123/completions \
1775
+ -H "Content-Type: application/json" \
1776
+ -H "Accept: application/json" \
1777
+ -d '{"message": "Hello world"}'
1778
+
1779
+ # SSE mode (streaming response)
1780
+ curl -X POST http://localhost:3000/api/chats/123/completions \
1781
+ -H "Content-Type: application/json" \
1782
+ -H "Accept: text/event-stream" \
1783
+ -d '{"message": "Hello world"}'
1784
+ ```
1785
+
1786
+ **Quality values** are supported for content negotiation:
1787
+
1788
+ ```bash
1789
+ # Prefer JSON (higher quality value)
1790
+ curl -H "Accept: text/event-stream;q=0.5, application/json;q=1.0" ...
1791
+
1792
+ # Prefer SSE (higher quality value)
1793
+ curl -H "Accept: application/json;q=0.5, text/event-stream;q=1.0" ...
1794
+ ```
1795
+
1796
+ **Subtype wildcards** are supported for flexible content negotiation:
1797
+
1798
+ ```bash
1799
+ # Accept any text format (matches text/plain, text/csv, etc.)
1800
+ curl -H "Accept: text/*" ...
1801
+
1802
+ # Accept any application format (matches application/json, application/xml, etc.)
1803
+ curl -H "Accept: application/*" ...
1804
+
1805
+ # Combine with quality values
1806
+ curl -H "Accept: text/event-stream;q=0.9, application/*;q=0.5" ...
1807
+ ```
1808
+
1809
+ The matching priority is: `text/event-stream` (SSE) > exact matches > subtype wildcards > `*/*` > fallback.
1810
+
1811
+ ### Testing Dual-Mode Controllers
1812
+
1813
+ Test both sync and SSE modes:
1814
+
1815
+ ```ts
1816
+ import { createContainer } from 'awilix'
1817
+ import { DIContext, SSETestServer, SSEInjectClient } from 'opinionated-machine'
1818
+
1819
+ describe('ChatDualModeController', () => {
1820
+ let server: SSETestServer
1821
+ let injectClient: SSEInjectClient
1822
+
1823
+ beforeEach(async () => {
1824
+ const container = createContainer({ injectionMode: 'PROXY' })
1825
+ const context = new DIContext(container, { isTestMode: true }, {})
1826
+ context.registerDependencies({ modules: [new ChatModule()] }, undefined)
1827
+
1828
+ server = await SSETestServer.create(
1829
+ (app) => {
1830
+ context.registerDualModeRoutes(app)
1831
+ },
1832
+ {
1833
+ configureApp: (app) => {
1834
+ app.setValidatorCompiler(validatorCompiler)
1835
+ app.setSerializerCompiler(serializerCompiler)
1836
+ },
1837
+ setup: () => ({ context }),
1838
+ },
1839
+ )
1840
+
1841
+ injectClient = new SSEInjectClient(server.app)
1842
+ })
1843
+
1844
+ afterEach(async () => {
1845
+ await server.resources.context.destroy()
1846
+ await server.close()
1847
+ })
1848
+
1849
+ it('returns sync response for Accept: application/json', async () => {
1850
+ const response = await server.app.inject({
1851
+ method: 'POST',
1852
+ url: '/api/chats/550e8400-e29b-41d4-a716-446655440000/completions',
1853
+ headers: {
1854
+ 'content-type': 'application/json',
1855
+ accept: 'application/json',
1856
+ authorization: 'Bearer token',
1857
+ },
1858
+ payload: { message: 'Hello' },
1859
+ })
1860
+
1861
+ expect(response.statusCode).toBe(200)
1862
+ expect(response.headers['content-type']).toContain('application/json')
1863
+
1864
+ const body = JSON.parse(response.body)
1865
+ expect(body).toHaveProperty('reply')
1866
+ expect(body).toHaveProperty('usage')
1867
+ })
1868
+
1869
+ it('streams SSE for Accept: text/event-stream', async () => {
1870
+ const conn = await injectClient.connectWithBody(
1871
+ '/api/chats/550e8400-e29b-41d4-a716-446655440000/completions',
1872
+ { message: 'Hello' },
1873
+ { headers: { authorization: 'Bearer token' } },
1874
+ )
1875
+
1876
+ expect(conn.getStatusCode()).toBe(200)
1877
+ expect(conn.getHeaders()['content-type']).toContain('text/event-stream')
1878
+
1879
+ const events = conn.getReceivedEvents()
1880
+ const chunks = events.filter((e) => e.event === 'chunk')
1881
+ const doneEvents = events.filter((e) => e.event === 'done')
1882
+
1883
+ expect(chunks.length).toBeGreaterThan(0)
1884
+ expect(doneEvents).toHaveLength(1)
1885
+ })
1886
+ })
1887
+