ts-procedures 5.3.0 → 5.4.1

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.
Files changed (60) hide show
  1. package/README.md +90 -0
  2. package/agent_config/claude-code/agents/ts-procedures-architect.md +15 -0
  3. package/agent_config/claude-code/skills/guide/anti-patterns.md +106 -0
  4. package/agent_config/claude-code/skills/guide/api-reference.md +150 -4
  5. package/agent_config/claude-code/skills/guide/patterns.md +155 -0
  6. package/agent_config/claude-code/skills/review/checklist.md +22 -0
  7. package/agent_config/claude-code/skills/scaffold/SKILL.md +3 -1
  8. package/agent_config/claude-code/skills/scaffold/templates/hono-api.md +169 -0
  9. package/agent_config/copilot/copilot-instructions.md +35 -0
  10. package/agent_config/cursor/cursorrules +35 -0
  11. package/build/implementations/http/hono-api/index.d.ts +102 -0
  12. package/build/implementations/http/hono-api/index.js +339 -0
  13. package/build/implementations/http/hono-api/index.js.map +1 -0
  14. package/build/implementations/http/hono-api/index.test.d.ts +1 -0
  15. package/build/implementations/http/hono-api/index.test.js +983 -0
  16. package/build/implementations/http/hono-api/index.test.js.map +1 -0
  17. package/build/implementations/http/hono-api/types.d.ts +13 -0
  18. package/build/implementations/http/hono-api/types.js +2 -0
  19. package/build/implementations/http/hono-api/types.js.map +1 -0
  20. package/build/implementations/types.d.ts +44 -0
  21. package/build/index.d.ts +28 -6
  22. package/build/index.js +28 -0
  23. package/build/index.js.map +1 -1
  24. package/build/schema/compute-schema.d.ts +5 -0
  25. package/build/schema/compute-schema.js +8 -1
  26. package/build/schema/compute-schema.js.map +1 -1
  27. package/build/schema/parser.d.ts +6 -5
  28. package/build/schema/parser.js +54 -0
  29. package/build/schema/parser.js.map +1 -1
  30. package/package.json +8 -4
  31. package/src/errors.test.ts +0 -163
  32. package/src/errors.ts +0 -107
  33. package/src/exports.ts +0 -7
  34. package/src/implementations/http/README.md +0 -217
  35. package/src/implementations/http/express-rpc/README.md +0 -281
  36. package/src/implementations/http/express-rpc/index.test.ts +0 -957
  37. package/src/implementations/http/express-rpc/index.ts +0 -265
  38. package/src/implementations/http/express-rpc/types.ts +0 -16
  39. package/src/implementations/http/hono-rpc/README.md +0 -358
  40. package/src/implementations/http/hono-rpc/index.test.ts +0 -1075
  41. package/src/implementations/http/hono-rpc/index.ts +0 -237
  42. package/src/implementations/http/hono-rpc/types.ts +0 -16
  43. package/src/implementations/http/hono-stream/README.md +0 -526
  44. package/src/implementations/http/hono-stream/index.test.ts +0 -1676
  45. package/src/implementations/http/hono-stream/index.ts +0 -435
  46. package/src/implementations/http/hono-stream/types.ts +0 -29
  47. package/src/implementations/types.ts +0 -75
  48. package/src/index.test.ts +0 -1194
  49. package/src/index.ts +0 -435
  50. package/src/schema/compute-schema.test.ts +0 -128
  51. package/src/schema/compute-schema.ts +0 -67
  52. package/src/schema/extract-json-schema.test.ts +0 -25
  53. package/src/schema/extract-json-schema.ts +0 -15
  54. package/src/schema/parser.test.ts +0 -182
  55. package/src/schema/parser.ts +0 -148
  56. package/src/schema/resolve-schema-lib.test.ts +0 -19
  57. package/src/schema/resolve-schema-lib.ts +0 -29
  58. package/src/schema/types.ts +0 -20
  59. package/src/stack-utils.test.ts +0 -94
  60. package/src/stack-utils.ts +0 -129
@@ -1,1676 +0,0 @@
1
- /* eslint-disable @typescript-eslint/no-empty-object-type, @typescript-eslint/explicit-function-return-type */
2
- import { describe, expect, test, vi, beforeEach } from 'vitest'
3
- import { Hono } from 'hono'
4
- import { v } from 'suretype'
5
- import { Procedures } from '../../../index.js'
6
- import { HonoStreamAppBuilder, sse, MidStreamErrorResult } from './index.js'
7
- import { RPCConfig, StreamMode } from '../../types.js'
8
- import { ProcedureValidationError } from '../../../errors.js'
9
-
10
- /**
11
- * HonoStreamAppBuilder Test Suite
12
- *
13
- * Tests the streaming Hono integration for ts-procedures.
14
- * This builder creates GET and POST routes for streaming procedures (SSE and text modes).
15
- */
16
- describe('HonoStreamAppBuilder', () => {
17
- // --------------------------------------------------------------------------
18
- // Constructor Tests
19
- // --------------------------------------------------------------------------
20
- describe('constructor', () => {
21
- test('creates default Hono app', async () => {
22
- const builder = new HonoStreamAppBuilder()
23
- const RPC = Procedures<{ userId: string }, RPCConfig>()
24
-
25
- RPC.CreateStream('StreamMessages', { scope: 'messages', version: 1 }, async function* () {
26
- yield { message: 'hello' }
27
- yield { message: 'world' }
28
- })
29
-
30
- builder.register(RPC, () => ({ userId: '123' }))
31
- const app = builder.build()
32
-
33
- const res = await app.request('/messages/stream-messages/1', {
34
- method: 'GET',
35
- })
36
-
37
- expect(res.status).toBe(200)
38
- expect(res.headers.get('content-type')).toContain('text/event-stream')
39
- })
40
-
41
- test('uses provided Hono app', async () => {
42
- const customApp = new Hono()
43
- customApp.get('/custom', (c) => c.json({ custom: true }))
44
-
45
- const builder = new HonoStreamAppBuilder({ app: customApp })
46
- const RPC = Procedures<{ userId: string }, RPCConfig>()
47
-
48
- RPC.CreateStream('StreamData', { scope: 'data', version: 1 }, async function* () {
49
- yield { data: 1 }
50
- })
51
-
52
- builder.register(RPC, () => ({ userId: '123' }))
53
- const app = builder.build()
54
-
55
- // Custom route should still work
56
- const customRes = await app.request('/custom')
57
- expect(customRes.status).toBe(200)
58
- const customBody = await customRes.json()
59
- expect(customBody).toEqual({ custom: true })
60
-
61
- // Stream route should also work
62
- const streamRes = await app.request('/data/stream-data/1')
63
- expect(streamRes.status).toBe(200)
64
- })
65
-
66
- test('handles empty config', () => {
67
- const builder = new HonoStreamAppBuilder({})
68
- expect(builder.app).toBeDefined()
69
- expect(builder.docs).toEqual([])
70
- })
71
-
72
- test('handles undefined config', () => {
73
- const builder = new HonoStreamAppBuilder(undefined)
74
- expect(builder.app).toBeDefined()
75
- expect(builder.docs).toEqual([])
76
- })
77
- })
78
-
79
- // --------------------------------------------------------------------------
80
- // SSE Streaming Tests
81
- // --------------------------------------------------------------------------
82
- describe('SSE streaming mode', () => {
83
- test('streams multiple values as SSE events', async () => {
84
- const builder = new HonoStreamAppBuilder()
85
- const RPC = Procedures<{}, RPCConfig>()
86
-
87
- RPC.CreateStream('Counter', { scope: 'counter', version: 1 }, async function* () {
88
- yield { count: 1 }
89
- yield { count: 2 }
90
- yield { count: 3 }
91
- })
92
-
93
- builder.register(RPC, () => ({}))
94
- const app = builder.build()
95
-
96
- const res = await app.request('/counter/counter/1')
97
- expect(res.status).toBe(200)
98
- expect(res.headers.get('content-type')).toContain('text/event-stream')
99
-
100
- const text = await res.text()
101
- expect(text).toContain('event: Counter')
102
- expect(text).toContain('data: {"count":1}')
103
- expect(text).toContain('data: {"count":2}')
104
- expect(text).toContain('data: {"count":3}')
105
- expect(text).toContain('id: 0')
106
- expect(text).toContain('id: 1')
107
- expect(text).toContain('id: 2')
108
- })
109
-
110
- test('uses SSE mode by default', async () => {
111
- const builder = new HonoStreamAppBuilder()
112
- const RPC = Procedures<{}, RPCConfig>()
113
-
114
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
115
- yield { ok: true }
116
- })
117
-
118
- builder.register(RPC, () => ({}))
119
- const app = builder.build()
120
-
121
- const res = await app.request('/test/test/1')
122
- expect(res.headers.get('content-type')).toContain('text/event-stream')
123
- })
124
-
125
- test('explicitly set SSE mode works', async () => {
126
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'sse' })
127
- const RPC = Procedures<{}, RPCConfig>()
128
-
129
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
130
- yield { ok: true }
131
- })
132
-
133
- builder.register(RPC, () => ({}))
134
- const app = builder.build()
135
-
136
- const res = await app.request('/test/test/1')
137
- expect(res.headers.get('content-type')).toContain('text/event-stream')
138
- })
139
- })
140
-
141
- // --------------------------------------------------------------------------
142
- // Text Streaming Tests
143
- // --------------------------------------------------------------------------
144
- describe('text streaming mode', () => {
145
- test('streams multiple values as newline-delimited JSON', async () => {
146
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
147
- const RPC = Procedures<{}, RPCConfig>()
148
-
149
- RPC.CreateStream('Counter', { scope: 'counter', version: 1 }, async function* () {
150
- yield { count: 1 }
151
- yield { count: 2 }
152
- yield { count: 3 }
153
- })
154
-
155
- builder.register(RPC, () => ({}))
156
- const app = builder.build()
157
-
158
- const res = await app.request('/counter/counter/1')
159
- expect(res.status).toBe(200)
160
- expect(res.headers.get('content-type')).toContain('text/plain')
161
-
162
- const text = await res.text()
163
- const lines = text.trim().split('\n')
164
- expect(lines).toHaveLength(3)
165
- expect(JSON.parse(lines[0]!)).toEqual({ count: 1 })
166
- expect(JSON.parse(lines[1]!)).toEqual({ count: 2 })
167
- expect(JSON.parse(lines[2]!)).toEqual({ count: 3 })
168
- })
169
-
170
- test('per-factory streamMode overrides default', async () => {
171
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'sse' })
172
- const RPC = Procedures<{}, RPCConfig>()
173
-
174
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
175
- yield { ok: true }
176
- })
177
-
178
- builder.register(RPC, () => ({}), { streamMode: 'text' })
179
- const app = builder.build()
180
-
181
- const res = await app.request('/test/test/1')
182
- expect(res.headers.get('content-type')).toContain('text/plain')
183
- })
184
- })
185
-
186
- // --------------------------------------------------------------------------
187
- // HTTP Method Tests (GET and POST)
188
- // --------------------------------------------------------------------------
189
- describe('HTTP methods', () => {
190
- test('GET request works', async () => {
191
- const builder = new HonoStreamAppBuilder()
192
- const RPC = Procedures<{}, RPCConfig>()
193
-
194
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
195
- yield { method: 'works' }
196
- })
197
-
198
- builder.register(RPC, () => ({}))
199
- const app = builder.build()
200
-
201
- const res = await app.request('/test/test/1', { method: 'GET' })
202
- expect(res.status).toBe(200)
203
- })
204
-
205
- test('POST request works', async () => {
206
- const builder = new HonoStreamAppBuilder()
207
- const RPC = Procedures<{}, RPCConfig>()
208
-
209
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
210
- yield { method: 'works' }
211
- })
212
-
213
- builder.register(RPC, () => ({}))
214
- const app = builder.build()
215
-
216
- const res = await app.request('/test/test/1', {
217
- method: 'POST',
218
- headers: { 'Content-Type': 'application/json' },
219
- body: JSON.stringify({}),
220
- })
221
- expect(res.status).toBe(200)
222
- })
223
-
224
- test('GET request passes query params to handler', async () => {
225
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
226
- const RPC = Procedures<{}, RPCConfig>()
227
-
228
- RPC.CreateStream('Echo', { scope: 'echo', version: 1 }, async function* (ctx, params) {
229
- yield { received: params }
230
- })
231
-
232
- builder.register(RPC, () => ({}))
233
- const app = builder.build()
234
-
235
- const res = await app.request('/echo/echo/1?foo=bar&baz=qux')
236
- const text = await res.text()
237
- const data = JSON.parse(text.trim())
238
- expect(data.received).toEqual({ foo: 'bar', baz: 'qux' })
239
- })
240
-
241
- test('POST request passes JSON body to handler', async () => {
242
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
243
- const RPC = Procedures<{}, RPCConfig>()
244
-
245
- RPC.CreateStream('Echo', { scope: 'echo', version: 1 }, async function* (ctx, params) {
246
- yield { received: params }
247
- })
248
-
249
- builder.register(RPC, () => ({}))
250
- const app = builder.build()
251
-
252
- const res = await app.request('/echo/echo/1', {
253
- method: 'POST',
254
- headers: { 'Content-Type': 'application/json' },
255
- body: JSON.stringify({ complex: { nested: 'data' }, array: [1, 2, 3] }),
256
- })
257
- const text = await res.text()
258
- const data = JSON.parse(text.trim())
259
- expect(data.received).toEqual({ complex: { nested: 'data' }, array: [1, 2, 3] })
260
- })
261
- })
262
-
263
- // --------------------------------------------------------------------------
264
- // pathPrefix Option Tests
265
- // --------------------------------------------------------------------------
266
- describe('pathPrefix option', () => {
267
- test('uses custom pathPrefix for all routes', async () => {
268
- const builder = new HonoStreamAppBuilder({ pathPrefix: '/api/v1' })
269
- const RPC = Procedures<{}, RPCConfig>()
270
-
271
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
272
- yield { ok: true }
273
- })
274
-
275
- builder.register(RPC, () => ({}))
276
- const app = builder.build()
277
-
278
- const res = await app.request('/api/v1/test/test/1')
279
- expect(res.status).toBe(200)
280
- })
281
-
282
- test('pathPrefix without leading slash gets normalized', async () => {
283
- const builder = new HonoStreamAppBuilder({ pathPrefix: 'custom' })
284
- const RPC = Procedures<{}, RPCConfig>()
285
-
286
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
287
- yield { ok: true }
288
- })
289
-
290
- builder.register(RPC, () => ({}))
291
- const app = builder.build()
292
-
293
- const res = await app.request('/custom/test/test/1')
294
- expect(res.status).toBe(200)
295
- })
296
-
297
- test('pathPrefix appears in generated docs', () => {
298
- const builder = new HonoStreamAppBuilder({ pathPrefix: '/api' })
299
- const RPC = Procedures<{}, RPCConfig>()
300
-
301
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
302
- yield {}
303
- })
304
-
305
- builder.register(RPC, () => ({}))
306
- builder.build()
307
-
308
- expect(builder.docs[0]!.path).toBe('/api/test/test/1')
309
- })
310
- })
311
-
312
- // --------------------------------------------------------------------------
313
- // Lifecycle Hooks Tests
314
- // --------------------------------------------------------------------------
315
- describe('lifecycle hooks', () => {
316
- test('onRequestStart is called with context object', async () => {
317
- const onRequestStart = vi.fn()
318
- const builder = new HonoStreamAppBuilder({ onRequestStart })
319
- const RPC = Procedures<{}, RPCConfig>()
320
-
321
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
322
- yield { ok: true }
323
- })
324
-
325
- builder.register(RPC, () => ({}))
326
- const app = builder.build()
327
-
328
- await app.request('/test/test/1')
329
-
330
- expect(onRequestStart).toHaveBeenCalledTimes(1)
331
- expect(onRequestStart.mock.calls[0]![0]).toHaveProperty('req')
332
- })
333
-
334
- test('onRequestEnd is called after response', async () => {
335
- const onRequestEnd = vi.fn()
336
- const builder = new HonoStreamAppBuilder({ onRequestEnd })
337
- const RPC = Procedures<{}, RPCConfig>()
338
-
339
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
340
- yield { ok: true }
341
- })
342
-
343
- builder.register(RPC, () => ({}))
344
- const app = builder.build()
345
-
346
- const response = await app.request('/test/test/1')
347
- await response.text() // Consume stream to trigger onRequestEnd
348
-
349
- expect(onRequestEnd).toHaveBeenCalledTimes(1)
350
- expect(onRequestEnd.mock.calls[0]![0]).toHaveProperty('req')
351
- })
352
-
353
- test('onStreamStart is called before streaming begins with streamMode', async () => {
354
- const onStreamStart = vi.fn()
355
- const builder = new HonoStreamAppBuilder({ onStreamStart })
356
- const RPC = Procedures<{}, RPCConfig>()
357
-
358
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
359
- yield { ok: true }
360
- })
361
-
362
- builder.register(RPC, () => ({}))
363
- const app = builder.build()
364
-
365
- await app.request('/test/test/1')
366
-
367
- expect(onStreamStart).toHaveBeenCalledTimes(1)
368
- expect(onStreamStart.mock.calls[0]![0]).toHaveProperty('name', 'Test')
369
- expect(onStreamStart.mock.calls[0]![2]).toBe('sse')
370
- })
371
-
372
- test('onStreamEnd is called after stream completes with streamMode', async () => {
373
- const onStreamEnd = vi.fn()
374
- const builder = new HonoStreamAppBuilder({ onStreamEnd })
375
- const RPC = Procedures<{}, RPCConfig>()
376
-
377
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
378
- yield { ok: true }
379
- })
380
-
381
- builder.register(RPC, () => ({}))
382
- const app = builder.build()
383
-
384
- const res = await app.request('/test/test/1')
385
- // Consume the stream to ensure it completes
386
- await res.text()
387
-
388
- expect(onStreamEnd).toHaveBeenCalledTimes(1)
389
- expect(onStreamEnd.mock.calls[0]![0]).toHaveProperty('name', 'Test')
390
- expect(onStreamEnd.mock.calls[0]![2]).toBe('sse')
391
- })
392
-
393
- test('hooks execute in correct order', async () => {
394
- const order: string[] = []
395
-
396
- const builder = new HonoStreamAppBuilder({
397
- onRequestStart: () => order.push('request-start'),
398
- onRequestEnd: () => order.push('request-end'),
399
- onStreamStart: () => order.push('stream-start'),
400
- onStreamEnd: () => order.push('stream-end'),
401
- })
402
- const RPC = Procedures<{}, RPCConfig>()
403
-
404
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
405
- order.push('handler')
406
- yield { ok: true }
407
- })
408
-
409
- builder.register(RPC, () => ({}))
410
- const app = builder.build()
411
-
412
- const res = await app.request('/test/test/1')
413
- // Consume the stream to ensure it completes
414
- await res.text()
415
-
416
- // Note: onRequestEnd middleware runs when response starts (before stream completes)
417
- // while onStreamEnd runs when the stream finishes
418
- expect(order).toContain('request-start')
419
- expect(order).toContain('stream-start')
420
- expect(order).toContain('handler')
421
- expect(order).toContain('stream-end')
422
- expect(order).toContain('request-end')
423
- // request-start should be first
424
- expect(order[0]).toBe('request-start')
425
- // stream-start should be before handler
426
- expect(order.indexOf('stream-start')).toBeLessThan(order.indexOf('handler'))
427
- // request-end should be last
428
- expect(order[order.length - 1]).toBe('request-end')
429
- })
430
- })
431
-
432
- // --------------------------------------------------------------------------
433
- // Error Handling Tests
434
- // --------------------------------------------------------------------------
435
- describe('error handling', () => {
436
- test('custom error handler receives procedure, context, and error', async () => {
437
- const errorHandler = vi.fn((procedure, c, error) => {
438
- return c.json({ customError: error.message }, 400)
439
- })
440
-
441
- const builder = new HonoStreamAppBuilder({ onPreStreamError: errorHandler })
442
- const RPC = Procedures<{}, RPCConfig>()
443
-
444
- RPC.CreateStream(
445
- 'ValidatedStream',
446
- {
447
- scope: 'validated',
448
- version: 1,
449
- schema: {
450
- params: v.object({ count: v.number() }),
451
- },
452
- },
453
- async function* (ctx, params) {
454
- yield { count: params.count }
455
- }
456
- )
457
-
458
- builder.register(RPC, () => ({}))
459
- const app = builder.build()
460
-
461
- const res = await app.request('/validated/validated-stream/1?count=not-a-number')
462
-
463
- expect(res.status).toBe(400)
464
- const body = await res.json()
465
- expect(body.customError).toContain('Validation error')
466
-
467
- expect(errorHandler).toHaveBeenCalledTimes(1)
468
- expect(errorHandler.mock.calls[0]![0].name).toBe('ValidatedStream')
469
- expect(errorHandler.mock.calls[0]![2].message).toContain('Validation error')
470
- })
471
-
472
- test('errors during streaming are sent as error events (SSE mode)', async () => {
473
- const builder = new HonoStreamAppBuilder()
474
- const RPC = Procedures<{}, RPCConfig>()
475
-
476
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
477
- yield { count: 1 }
478
- throw new Error('Stream error')
479
- })
480
-
481
- builder.register(RPC, () => ({}))
482
- const app = builder.build()
483
-
484
- const res = await app.request('/error/error-stream/1')
485
- const text = await res.text()
486
-
487
- expect(text).toContain('data: {"count":1}')
488
- expect(text).toContain('event: error')
489
- expect(text).toContain('Stream error')
490
- })
491
-
492
- test('errors during streaming are sent as JSON lines (text mode)', async () => {
493
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
494
- const RPC = Procedures<{}, RPCConfig>()
495
-
496
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
497
- yield { count: 1 }
498
- throw new Error('Stream error')
499
- })
500
-
501
- builder.register(RPC, () => ({}))
502
- const app = builder.build()
503
-
504
- const res = await app.request('/error/error-stream/1')
505
- const text = await res.text()
506
- const lines = text.trim().split('\n')
507
-
508
- expect(JSON.parse(lines[0]!)).toEqual({ count: 1 })
509
- // Error is wrapped by Procedures with "Error in streaming handler for {name}" prefix
510
- expect(JSON.parse(lines[1]!).error).toContain('Stream error')
511
- })
512
-
513
- test('validation errors return 400 by default when no error handler', async () => {
514
- const builder = new HonoStreamAppBuilder()
515
- const RPC = Procedures<{}, RPCConfig>()
516
-
517
- RPC.CreateStream(
518
- 'ValidatedStream',
519
- {
520
- scope: 'validated',
521
- version: 1,
522
- schema: {
523
- params: v.object({ count: v.number() }),
524
- },
525
- },
526
- async function* (ctx, params) {
527
- yield { count: params.count }
528
- }
529
- )
530
-
531
- builder.register(RPC, () => ({}))
532
- const app = builder.build()
533
-
534
- const res = await app.request('/validated/validated-stream/1?count=not-a-number')
535
-
536
- // Default: returns 400 JSON error
537
- expect(res.status).toBe(400)
538
- const body = await res.json()
539
- expect(body.error).toContain('Validation error')
540
- })
541
-
542
- // Tests for onPreStreamError and onMidStreamError callbacks
543
-
544
- test('onPreStreamError handles validation errors with custom Response', async () => {
545
- const onPreStreamError = vi.fn((procedure, c, error) => {
546
- return c.json(
547
- { customError: true, procedureName: procedure.name, details: error.message },
548
- 422
549
- )
550
- })
551
- const builder = new HonoStreamAppBuilder({ onPreStreamError })
552
- const RPC = Procedures<{}, RPCConfig>()
553
-
554
- RPC.CreateStream(
555
- 'ValidatedStream',
556
- {
557
- scope: 'validated',
558
- version: 1,
559
- schema: {
560
- params: v.object({ count: v.number() }),
561
- },
562
- },
563
- async function* (ctx, params) {
564
- yield { count: params.count }
565
- }
566
- )
567
-
568
- builder.register(RPC, () => ({}))
569
- const app = builder.build()
570
-
571
- const res = await app.request('/validated/validated-stream/1?count=not-a-number')
572
-
573
- expect(res.status).toBe(422)
574
- const body = await res.json()
575
- expect(body.customError).toBe(true)
576
- expect(body.procedureName).toBe('ValidatedStream')
577
- expect(body.details).toContain('Validation error')
578
-
579
- expect(onPreStreamError).toHaveBeenCalledTimes(1)
580
- })
581
-
582
- test('onPreStreamError handles context resolution errors', async () => {
583
- const onPreStreamError = vi.fn((procedure, c, error) => {
584
- return c.json({ contextError: error.message }, 401)
585
- })
586
- const builder = new HonoStreamAppBuilder({ onPreStreamError })
587
- const RPC = Procedures<{ userId: string }, RPCConfig>()
588
-
589
- RPC.CreateStream('SecureStream', { scope: 'secure', version: 1 }, async function* (ctx) {
590
- yield { userId: ctx.userId }
591
- })
592
-
593
- builder.register(RPC, () => {
594
- throw new Error('Authentication required')
595
- })
596
- const app = builder.build()
597
-
598
- const res = await app.request('/secure/secure-stream/1')
599
-
600
- expect(res.status).toBe(401)
601
- const body = await res.json()
602
- expect(body.contextError).toBe('Authentication required')
603
-
604
- expect(onPreStreamError).toHaveBeenCalledTimes(1)
605
- })
606
-
607
- test('onMidStreamError returns custom value written to SSE stream', async () => {
608
- const onMidStreamError = vi.fn((procedure, c, error) => {
609
- return {
610
- data: {
611
- type: 'error',
612
- code: 'STREAM_FAILED',
613
- message: error.message,
614
- retryable: false,
615
- },
616
- closeStream: true,
617
- }
618
- })
619
-
620
- const builder = new HonoStreamAppBuilder({ onMidStreamError })
621
- const RPC = Procedures<{}, RPCConfig>()
622
-
623
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
624
- yield { type: 'data', value: 1 }
625
- throw new Error('Something broke')
626
- })
627
-
628
- builder.register(RPC, () => ({}))
629
- const app = builder.build()
630
-
631
- const res = await app.request('/error/error-stream/1')
632
- const text = await res.text()
633
-
634
- // First yield should be present
635
- expect(text).toContain('data: {"type":"data","value":1}')
636
- // Error should use custom format from onMidStreamError
637
- expect(text).toContain('data: {"type":"error","code":"STREAM_FAILED"')
638
- expect(text).toContain('"retryable":false')
639
- // Event should use procedure name (not 'error') since custom value provided
640
- expect(text).toContain('event: ErrorStream')
641
-
642
- expect(onMidStreamError).toHaveBeenCalledTimes(1)
643
- })
644
-
645
- test('onMidStreamError returns custom value written to text stream', async () => {
646
- const onMidStreamError = vi.fn((procedure, c, error) => {
647
- return {
648
- data: { type: 'error', message: error.message },
649
- }
650
- })
651
-
652
- const builder = new HonoStreamAppBuilder({
653
- defaultStreamMode: 'text',
654
- onMidStreamError,
655
- })
656
- const RPC = Procedures<{}, RPCConfig>()
657
-
658
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
659
- yield { type: 'data', value: 'hello' }
660
- throw new Error('Stream failed')
661
- })
662
-
663
- builder.register(RPC, () => ({}))
664
- const app = builder.build()
665
-
666
- const res = await app.request('/error/error-stream/1')
667
- const text = await res.text()
668
- const lines = text.trim().split('\n')
669
-
670
- expect(JSON.parse(lines[0]!)).toEqual({ type: 'data', value: 'hello' })
671
- // Error message may be wrapped by Procedures with "Error in streaming handler for X - " prefix
672
- const errorLine = JSON.parse(lines[1]!)
673
- expect(errorLine.type).toBe('error')
674
- expect(errorLine.message).toContain('Stream failed')
675
-
676
- expect(onMidStreamError).toHaveBeenCalledTimes(1)
677
- })
678
-
679
- test('onMidStreamError returning undefined falls back to default error format', async () => {
680
- const onMidStreamError = vi.fn(() => undefined)
681
-
682
- const builder = new HonoStreamAppBuilder({
683
- defaultStreamMode: 'text',
684
- onMidStreamError,
685
- })
686
- const RPC = Procedures<{}, RPCConfig>()
687
-
688
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
689
- yield { value: 1 }
690
- throw new Error('Fallback test')
691
- })
692
-
693
- builder.register(RPC, () => ({}))
694
- const app = builder.build()
695
-
696
- const res = await app.request('/error/error-stream/1')
697
- const text = await res.text()
698
- const lines = text.trim().split('\n')
699
-
700
- expect(JSON.parse(lines[0]!)).toEqual({ value: 1 })
701
- // Falls back to default { error: message } format
702
- expect(JSON.parse(lines[1]!).error).toContain('Fallback test')
703
-
704
- expect(onMidStreamError).toHaveBeenCalledTimes(1)
705
- })
706
- })
707
-
708
- // --------------------------------------------------------------------------
709
- // Context Resolution Tests
710
- // --------------------------------------------------------------------------
711
- describe('context resolution', () => {
712
- test('context can be a static object', async () => {
713
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
714
- const RPC = Procedures<{ requestId: string }, RPCConfig>()
715
-
716
- RPC.CreateStream('GetId', { scope: 'get-id', version: 1 }, async function* (ctx) {
717
- yield { id: ctx.requestId }
718
- })
719
-
720
- builder.register(RPC, { requestId: 'static-123' })
721
- const app = builder.build()
722
-
723
- const res = await app.request('/get-id/get-id/1')
724
- const text = await res.text()
725
- expect(JSON.parse(text.trim())).toEqual({ id: 'static-123' })
726
- })
727
-
728
- test('context can be sync function', async () => {
729
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
730
- const RPC = Procedures<{ requestId: string }, RPCConfig>()
731
-
732
- RPC.CreateStream('GetId', { scope: 'get-id', version: 1 }, async function* (ctx) {
733
- yield { id: ctx.requestId }
734
- })
735
-
736
- builder.register(RPC, (c) => ({ requestId: c.req.header('x-request-id') || 'unknown' }))
737
- const app = builder.build()
738
-
739
- const res = await app.request('/get-id/get-id/1', {
740
- headers: { 'X-Request-Id': 'req-456' },
741
- })
742
- const text = await res.text()
743
- expect(JSON.parse(text.trim())).toEqual({ id: 'req-456' })
744
- })
745
-
746
- test('context can be async function', async () => {
747
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
748
- const RPC = Procedures<{ requestId: string }, RPCConfig>()
749
-
750
- RPC.CreateStream('GetId', { scope: 'get-id', version: 1 }, async function* (ctx) {
751
- yield { id: ctx.requestId }
752
- })
753
-
754
- builder.register(RPC, async () => {
755
- await new Promise((r) => setTimeout(r, 10))
756
- return { requestId: 'async-789' }
757
- })
758
- const app = builder.build()
759
-
760
- const res = await app.request('/get-id/get-id/1')
761
- const text = await res.text()
762
- expect(JSON.parse(text.trim())).toEqual({ id: 'async-789' })
763
- })
764
- })
765
-
766
- // --------------------------------------------------------------------------
767
- // Documentation Tests
768
- // --------------------------------------------------------------------------
769
- describe('documentation', () => {
770
- test('generates complete route documentation', () => {
771
- const paramsSchema = v.object({ id: v.string() })
772
- const yieldSchema = v.object({ message: v.string() })
773
- const returnSchema = v.object({ total: v.number() })
774
-
775
- const builder = new HonoStreamAppBuilder()
776
- const RPC = Procedures<{}, RPCConfig>()
777
-
778
- RPC.CreateStream(
779
- 'StreamMessages',
780
- {
781
- scope: 'messages',
782
- version: 1,
783
- schema: { params: paramsSchema, yieldType: yieldSchema, returnType: returnSchema },
784
- },
785
- async function* () {
786
- yield { message: 'test' }
787
- }
788
- )
789
-
790
- builder.register(RPC, () => ({}))
791
- builder.build()
792
-
793
- const doc = builder.docs[0]!
794
- expect(doc.path).toBe('/messages/stream-messages/1')
795
- expect(doc.methods).toEqual(['get', 'post'])
796
- expect(doc.streamMode).toBe('sse')
797
- expect(doc.jsonSchema.params).toBeDefined()
798
- expect(doc.jsonSchema.returnType).toBeDefined()
799
-
800
- // yieldType is nested under SSE envelope's data property
801
- const yt = doc.jsonSchema.yieldType as Record<string, any>
802
- expect(yt.description).toBe('SSE message envelope. The data field contains the procedure yield value.')
803
- expect(yt.required).toEqual(['data', 'event', 'id'])
804
- expect(yt.properties.event).toEqual({ type: 'string' })
805
- expect(yt.properties.id).toEqual({ type: 'string' })
806
- expect(yt.properties.retry).toEqual({ type: 'number' })
807
- // Developer's yieldType is nested under data
808
- expect(yt.properties.data.properties.message).toBeDefined()
809
- })
810
-
811
- test('SSE mode generates SSE envelope even when no yieldType is defined', () => {
812
- const builder = new HonoStreamAppBuilder()
813
- const RPC = Procedures<{}, RPCConfig>()
814
-
815
- RPC.CreateStream('NoYield', { scope: 'test', version: 1 }, async function* () {
816
- yield {}
817
- })
818
-
819
- builder.register(RPC, () => ({}))
820
- builder.build()
821
-
822
- const yt = builder.docs[0]!.jsonSchema.yieldType as Record<string, any>
823
- expect(yt).toBeDefined()
824
- expect(yt.type).toBe('object')
825
- expect(yt.description).toBe('SSE message envelope. The data field contains the procedure yield value.')
826
- expect(yt.required).toEqual(['data', 'event', 'id'])
827
- // data is empty schema when no yieldType defined
828
- expect(yt.properties.data).toEqual({})
829
- expect(yt.properties.event).toEqual({ type: 'string' })
830
- expect(yt.properties.id).toEqual({ type: 'string' })
831
- expect(yt.properties.retry).toEqual({ type: 'number' })
832
- })
833
-
834
- test('text mode passes yieldType through as-is', () => {
835
- const yieldSchema = v.object({ chunk: v.string() })
836
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
837
- const RPC = Procedures<{}, RPCConfig>()
838
-
839
- RPC.CreateStream(
840
- 'TextStream',
841
- { scope: 'test', version: 1, schema: { yieldType: yieldSchema } },
842
- async function* () {
843
- yield { chunk: 'hi' }
844
- }
845
- )
846
-
847
- builder.register(RPC, () => ({}))
848
- builder.build()
849
-
850
- const yt = builder.docs[0]!.jsonSchema.yieldType as Record<string, any>
851
- expect(yt).toBeDefined()
852
- // Text mode should NOT have SSE envelope fields injected
853
- expect(yt.properties?.event).toBeUndefined()
854
- expect(yt.properties?.id).toBeUndefined()
855
- expect(yt.properties?.retry).toBeUndefined()
856
- })
857
-
858
- test('yieldType with id property does not collide with SSE id field', () => {
859
- // User's yieldType has an `id` field (number) — this should be nested under
860
- // the SSE envelope's `data` property, not collide with the SSE `id` (string)
861
- const yieldSchema = v.object({
862
- id: v.number(),
863
- message: v.string(),
864
- })
865
- const builder = new HonoStreamAppBuilder()
866
- const RPC = Procedures<{}, RPCConfig>()
867
-
868
- RPC.CreateStream(
869
- 'Notifications',
870
- { scope: 'test', version: 1, schema: { yieldType: yieldSchema } },
871
- async function* () {
872
- yield { id: 42, message: 'hello' }
873
- }
874
- )
875
-
876
- builder.register(RPC, () => ({}))
877
- builder.build()
878
-
879
- const yt = builder.docs[0]!.jsonSchema.yieldType as Record<string, any>
880
- expect(yt.required).toEqual(['data', 'event', 'id'])
881
- // SSE envelope id is a string
882
- expect(yt.properties.id).toEqual({ type: 'string' })
883
- // User's id (number) is safely nested under data
884
- expect(yt.properties.data.properties.id.type).toBe('number')
885
- expect(yt.properties.data.properties.message.type).toBe('string')
886
- })
887
-
888
- test('streamMode is recorded in docs', () => {
889
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
890
- const RPC = Procedures<{}, RPCConfig>()
891
-
892
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
893
- yield {}
894
- })
895
-
896
- builder.register(RPC, () => ({}))
897
- builder.build()
898
-
899
- expect(builder.docs[0]!.streamMode).toBe('text')
900
- })
901
-
902
- test('per-factory streamMode is recorded in docs', () => {
903
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'sse' })
904
- const RPC = Procedures<{}, RPCConfig>()
905
-
906
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
907
- yield {}
908
- })
909
-
910
- builder.register(RPC, () => ({}), { streamMode: 'text' })
911
- builder.build()
912
-
913
- expect(builder.docs[0]!.streamMode).toBe('text')
914
- })
915
- })
916
-
917
- // --------------------------------------------------------------------------
918
- // Filter Tests (Only Streaming Procedures)
919
- // --------------------------------------------------------------------------
920
- describe('procedure filtering', () => {
921
- test('only registers streaming procedures', async () => {
922
- const builder = new HonoStreamAppBuilder()
923
- const RPC = Procedures<{}, RPCConfig>()
924
-
925
- // Regular procedure (should be ignored)
926
- RPC.Create('NonStream', { scope: 'non-stream', version: 1 }, async () => ({
927
- ok: true,
928
- }))
929
-
930
- // Streaming procedure (should be registered)
931
- RPC.CreateStream('Stream', { scope: 'stream', version: 1 }, async function* () {
932
- yield { ok: true }
933
- })
934
-
935
- builder.register(RPC, () => ({}))
936
- const app = builder.build()
937
-
938
- // Only streaming procedure should be in docs
939
- expect(builder.docs).toHaveLength(1)
940
- expect(builder.docs[0]!.name).toBe('Stream')
941
-
942
- // Non-streaming route should 404
943
- const nonStreamRes = await app.request('/non-stream/non-stream/1', { method: 'POST' })
944
- expect(nonStreamRes.status).toBe(404)
945
-
946
- // Streaming route should work
947
- const streamRes = await app.request('/stream/stream/1')
948
- expect(streamRes.status).toBe(200)
949
- })
950
- })
951
-
952
- // --------------------------------------------------------------------------
953
- // extendProcedureDoc Tests
954
- // --------------------------------------------------------------------------
955
- describe('extendProcedureDoc', () => {
956
- test('adds custom properties to generated documentation', () => {
957
- const builder = new HonoStreamAppBuilder()
958
- const RPC = Procedures<{}, RPCConfig>()
959
-
960
- RPC.CreateStream('StreamEvents', { scope: 'events', version: 1 }, async function* () {
961
- yield {}
962
- })
963
-
964
- builder.register(RPC, () => ({}), {
965
- extendProcedureDoc: ({ procedure }) => ({
966
- summary: `Stream events endpoint`,
967
- tags: ['events'],
968
- operationId: procedure.name,
969
- }),
970
- })
971
- builder.build()
972
-
973
- const doc = builder.docs[0]!
974
- expect(doc).toHaveProperty('summary', 'Stream events endpoint')
975
- expect(doc).toHaveProperty('tags', ['events'])
976
- expect(doc).toHaveProperty('operationId', 'StreamEvents')
977
- })
978
-
979
- test('base properties take precedence over extended properties', () => {
980
- const builder = new HonoStreamAppBuilder()
981
- const RPC = Procedures<{}, RPCConfig>()
982
-
983
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
984
- yield {}
985
- })
986
-
987
- builder.register(RPC, () => ({}), {
988
- extendProcedureDoc: () => ({
989
- name: 'OverriddenName',
990
- path: '/overridden/path',
991
- methods: ['put'],
992
- customField: 'custom-value',
993
- }),
994
- })
995
- builder.build()
996
-
997
- const doc = builder.docs[0]!
998
- // Base properties should NOT be overridden
999
- expect(doc.name).toBe('Test')
1000
- expect(doc.path).toBe('/test/test/1')
1001
- expect(doc.methods).toEqual(['get', 'post'])
1002
- // Custom field should be present
1003
- expect(doc).toHaveProperty('customField', 'custom-value')
1004
- })
1005
- })
1006
-
1007
- // --------------------------------------------------------------------------
1008
- // Multiple Factory Tests
1009
- // --------------------------------------------------------------------------
1010
- describe('multiple factories', () => {
1011
- test('supports registering multiple factories', async () => {
1012
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
1013
-
1014
- const PublicRPC = Procedures<{ public: true }, RPCConfig>()
1015
- const PrivateRPC = Procedures<{ private: true }, RPCConfig>()
1016
-
1017
- PublicRPC.CreateStream(
1018
- 'PublicStream',
1019
- { scope: 'public', version: 1 },
1020
- async function* (ctx) {
1021
- yield { isPublic: ctx.public }
1022
- }
1023
- )
1024
-
1025
- PrivateRPC.CreateStream(
1026
- 'PrivateStream',
1027
- { scope: 'private', version: 1 },
1028
- async function* (ctx) {
1029
- yield { isPrivate: ctx.private }
1030
- }
1031
- )
1032
-
1033
- builder
1034
- .register(PublicRPC, () => ({ public: true as const }))
1035
- .register(PrivateRPC, () => ({ private: true as const }))
1036
-
1037
- const app = builder.build()
1038
-
1039
- const publicRes = await app.request('/public/public-stream/1')
1040
- const publicText = await publicRes.text()
1041
- expect(JSON.parse(publicText.trim())).toEqual({ isPublic: true })
1042
-
1043
- const privateRes = await app.request('/private/private-stream/1')
1044
- const privateText = await privateRes.text()
1045
- expect(JSON.parse(privateText.trim())).toEqual({ isPrivate: true })
1046
- })
1047
-
1048
- test('different factories can have different stream modes', async () => {
1049
- const builder = new HonoStreamAppBuilder()
1050
-
1051
- const SSERPC = Procedures<{}, RPCConfig>()
1052
- const TextRPC = Procedures<{}, RPCConfig>()
1053
-
1054
- SSERPC.CreateStream('SSEStream', { scope: 'sse', version: 1 }, async function* () {
1055
- yield { mode: 'sse' }
1056
- })
1057
-
1058
- TextRPC.CreateStream('TextStream', { scope: 'text', version: 1 }, async function* () {
1059
- yield { mode: 'text' }
1060
- })
1061
-
1062
- builder
1063
- .register(SSERPC, () => ({}), { streamMode: 'sse' })
1064
- .register(TextRPC, () => ({}), { streamMode: 'text' })
1065
-
1066
- const app = builder.build()
1067
-
1068
- const sseRes = await app.request('/sse/sse-stream/1')
1069
- expect(sseRes.headers.get('content-type')).toContain('text/event-stream')
1070
-
1071
- const textRes = await app.request('/text/text-stream/1')
1072
- expect(textRes.headers.get('content-type')).toContain('text/plain')
1073
- })
1074
- })
1075
-
1076
- // --------------------------------------------------------------------------
1077
- // Path Generation Tests
1078
- // --------------------------------------------------------------------------
1079
- describe('makeStreamHttpRoutePath', () => {
1080
- let builder: HonoStreamAppBuilder
1081
-
1082
- beforeEach(() => {
1083
- builder = new HonoStreamAppBuilder()
1084
- })
1085
-
1086
- test("simple scope: 'events' + 'StreamUpdates' → /events/stream-updates/1", () => {
1087
- const path = builder.makeStreamHttpRoutePath('StreamUpdates', { scope: 'events', version: 1 })
1088
- expect(path).toBe('/events/stream-updates/1')
1089
- })
1090
-
1091
- test("array scope: ['events', 'live'] + 'Watch' → /events/live/watch/1", () => {
1092
- const path = builder.makeStreamHttpRoutePath('Watch', {
1093
- scope: ['events', 'live'],
1094
- version: 1,
1095
- })
1096
- expect(path).toBe('/events/live/watch/1')
1097
- })
1098
-
1099
- test('version number included in path', () => {
1100
- const pathV1 = builder.makeStreamHttpRoutePath('Test', { scope: 'test', version: 1 })
1101
- const pathV2 = builder.makeStreamHttpRoutePath('Test', { scope: 'test', version: 2 })
1102
-
1103
- expect(pathV1).toBe('/test/test/1')
1104
- expect(pathV2).toBe('/test/test/2')
1105
- })
1106
- })
1107
-
1108
- // --------------------------------------------------------------------------
1109
- // isPrevalidated Tests
1110
- // --------------------------------------------------------------------------
1111
- describe('isPrevalidated context property', () => {
1112
- test('passes isPrevalidated: true to procedure handler to skip double validation', async () => {
1113
- let receivedIsPrevalidated: boolean | undefined
1114
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
1115
- const RPC = Procedures<{}, RPCConfig>()
1116
-
1117
- RPC.CreateStream('CheckPrevalidated', { scope: 'check', version: 1 }, async function* (ctx) {
1118
- receivedIsPrevalidated = ctx.isPrevalidated
1119
- yield { ok: true }
1120
- })
1121
-
1122
- builder.register(RPC, () => ({}))
1123
- const app = builder.build()
1124
-
1125
- const res = await app.request('/check/check-prevalidated/1')
1126
- await res.text()
1127
-
1128
- expect(receivedIsPrevalidated).toBe(true)
1129
- })
1130
-
1131
- test('valid params work correctly with pre-validation flow', async () => {
1132
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
1133
- const RPC = Procedures<{}, RPCConfig>()
1134
-
1135
- RPC.CreateStream(
1136
- 'ValidParams',
1137
- {
1138
- scope: 'valid',
1139
- version: 1,
1140
- schema: {
1141
- params: v.object({ count: v.number() }),
1142
- },
1143
- },
1144
- async function* (ctx, params) {
1145
- const count = params.count ?? 0
1146
- for (let i = 0; i < count; i++) {
1147
- yield { index: i }
1148
- }
1149
- }
1150
- )
1151
-
1152
- builder.register(RPC, () => ({}))
1153
- const app = builder.build()
1154
-
1155
- // With valid params, both HonoStreamAppBuilder validation and procedure validation should work
1156
- const res = await app.request('/valid/valid-params/1?count=2')
1157
- expect(res.status).toBe(200)
1158
-
1159
- const text = await res.text()
1160
- const lines = text.trim().split('\n')
1161
- expect(lines).toHaveLength(2)
1162
- expect(JSON.parse(lines[0]!)).toEqual({ index: 0 })
1163
- expect(JSON.parse(lines[1]!)).toEqual({ index: 1 })
1164
- })
1165
-
1166
- test('invalid params are caught by HonoStreamAppBuilder before handler runs', async () => {
1167
- let handlerCalled = false
1168
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
1169
- const RPC = Procedures<{}, RPCConfig>()
1170
-
1171
- RPC.CreateStream(
1172
- 'InvalidParams',
1173
- {
1174
- scope: 'invalid',
1175
- version: 1,
1176
- schema: {
1177
- params: v.object({ count: v.number() }),
1178
- },
1179
- },
1180
- async function* () {
1181
- handlerCalled = true
1182
- yield { ok: true }
1183
- }
1184
- )
1185
-
1186
- builder.register(RPC, () => ({}))
1187
- const app = builder.build()
1188
-
1189
- // With invalid params, HonoStreamAppBuilder catches the error before streaming starts
1190
- const res = await app.request('/invalid/invalid-params/1?count=not-a-number')
1191
- expect(res.status).toBe(400)
1192
-
1193
- const body = await res.json()
1194
- expect(body.error).toContain('Validation error')
1195
-
1196
- // Handler should never be called since validation fails before streaming
1197
- expect(handlerCalled).toBe(false)
1198
- })
1199
- })
1200
-
1201
- // --------------------------------------------------------------------------
1202
- // SSE Yield Shape Tests
1203
- // --------------------------------------------------------------------------
1204
- describe('SSE yield shape', () => {
1205
- test('custom event names via sse() helper', async () => {
1206
- const builder = new HonoStreamAppBuilder()
1207
- const RPC = Procedures<{}, RPCConfig>()
1208
-
1209
- RPC.CreateStream('Events', { scope: 'events', version: 1 }, async function* () {
1210
- yield sse({ type: 'user_joined' }, { event: 'join' })
1211
- yield sse({ type: 'message' }, { event: 'chat' })
1212
- })
1213
-
1214
- builder.register(RPC, () => ({}))
1215
- const app = builder.build()
1216
-
1217
- const res = await app.request('/events/events/1')
1218
- const text = await res.text()
1219
-
1220
- expect(text).toContain('event: join')
1221
- expect(text).toContain('event: chat')
1222
- expect(text).not.toContain('event: Events')
1223
- })
1224
-
1225
- test('custom id via sse() helper', async () => {
1226
- const builder = new HonoStreamAppBuilder()
1227
- const RPC = Procedures<{}, RPCConfig>()
1228
-
1229
- RPC.CreateStream('Events', { scope: 'events', version: 1 }, async function* () {
1230
- yield sse({ msg: 'first' }, { id: 'msg-001' })
1231
- yield sse({ msg: 'second' }, { id: 'msg-002' })
1232
- })
1233
-
1234
- builder.register(RPC, () => ({}))
1235
- const app = builder.build()
1236
-
1237
- const res = await app.request('/events/events/1')
1238
- const text = await res.text()
1239
-
1240
- expect(text).toContain('id: msg-001')
1241
- expect(text).toContain('id: msg-002')
1242
- })
1243
-
1244
- test('string data pass-through without double-stringify', async () => {
1245
- const builder = new HonoStreamAppBuilder()
1246
- const RPC = Procedures<{}, RPCConfig>()
1247
-
1248
- RPC.CreateStream('Events', { scope: 'events', version: 1 }, async function* () {
1249
- yield 'already a string'
1250
- yield { needs: 'stringify' }
1251
- })
1252
-
1253
- builder.register(RPC, () => ({}))
1254
- const app = builder.build()
1255
-
1256
- const res = await app.request('/events/events/1')
1257
- const text = await res.text()
1258
-
1259
- // String data should be passed through as-is (not JSON-stringified again)
1260
- expect(text).toContain('data: already a string')
1261
- // Object data should be JSON-stringified
1262
- expect(text).toContain('data: {"needs":"stringify"}')
1263
- })
1264
-
1265
- test('default event falls back to procedure name when omitted', async () => {
1266
- const builder = new HonoStreamAppBuilder()
1267
- const RPC = Procedures<{}, RPCConfig>()
1268
-
1269
- RPC.CreateStream('MyProcedure', { scope: 'test', version: 1 }, async function* () {
1270
- yield { value: 1 }
1271
- yield sse({ value: 2 }, { event: 'custom' })
1272
- yield { value: 3 }
1273
- })
1274
-
1275
- builder.register(RPC, () => ({}))
1276
- const app = builder.build()
1277
-
1278
- const res = await app.request('/test/my-procedure/1')
1279
- const text = await res.text()
1280
-
1281
- // Split into individual SSE messages
1282
- const messages = text.split('\n\n').filter(Boolean)
1283
-
1284
- // First and third should use procedure name as event
1285
- expect(messages[0]).toContain('event: MyProcedure')
1286
- // Second should use custom event
1287
- expect(messages[1]).toContain('event: custom')
1288
- // Third should fall back to procedure name
1289
- expect(messages[2]).toContain('event: MyProcedure')
1290
- })
1291
- })
1292
-
1293
- // --------------------------------------------------------------------------
1294
- // sse() Helper Tests
1295
- // --------------------------------------------------------------------------
1296
- describe('sse() helper', () => {
1297
- test('tagged yields with custom event/id/retry', async () => {
1298
- const builder = new HonoStreamAppBuilder()
1299
- const RPC = Procedures<{}, RPCConfig>()
1300
-
1301
- RPC.CreateStream('Tagged', { scope: 'tagged', version: 1 }, async function* () {
1302
- yield sse({ count: 1 }, { event: 'tick', id: 'evt-1', retry: 5000 })
1303
- })
1304
-
1305
- builder.register(RPC, () => ({}))
1306
- const app = builder.build()
1307
-
1308
- const res = await app.request('/tagged/tagged/1')
1309
- const text = await res.text()
1310
-
1311
- expect(text).toContain('event: tick')
1312
- expect(text).toContain('id: evt-1')
1313
- expect(text).toContain('retry: 5000')
1314
- expect(text).toContain('data: {"count":1}')
1315
- })
1316
-
1317
- test('plain domain objects use procedure name and auto-incremented id', async () => {
1318
- const builder = new HonoStreamAppBuilder()
1319
- const RPC = Procedures<{}, RPCConfig>()
1320
-
1321
- RPC.CreateStream('Plain', { scope: 'plain', version: 1 }, async function* () {
1322
- yield { a: 1 }
1323
- yield { a: 2 }
1324
- })
1325
-
1326
- builder.register(RPC, () => ({}))
1327
- const app = builder.build()
1328
-
1329
- const res = await app.request('/plain/plain/1')
1330
- const text = await res.text()
1331
-
1332
- const messages = text.split('\n\n').filter(Boolean)
1333
- expect(messages[0]).toContain('event: Plain')
1334
- expect(messages[0]).toContain('id: 0')
1335
- expect(messages[0]).toContain('data: {"a":1}')
1336
- expect(messages[1]).toContain('event: Plain')
1337
- expect(messages[1]).toContain('id: 1')
1338
- expect(messages[1]).toContain('data: {"a":2}')
1339
- })
1340
-
1341
- test('sse() metadata is invisible in text mode', async () => {
1342
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' })
1343
- const RPC = Procedures<{}, RPCConfig>()
1344
-
1345
- RPC.CreateStream('TextTagged', { scope: 'text', version: 1 }, async function* () {
1346
- yield sse({ count: 1 }, { event: 'tick' })
1347
- yield { count: 2 }
1348
- })
1349
-
1350
- builder.register(RPC, () => ({}))
1351
- const app = builder.build()
1352
-
1353
- const res = await app.request('/text/text-tagged/1')
1354
- const text = await res.text()
1355
- const lines = text.trim().split('\n')
1356
-
1357
- // Text mode just JSON-stringifies — sse() metadata is not visible
1358
- expect(JSON.parse(lines[0]!)).toEqual({ count: 1 })
1359
- expect(JSON.parse(lines[1]!)).toEqual({ count: 2 })
1360
- })
1361
-
1362
- test('sse() with partial options', async () => {
1363
- const builder = new HonoStreamAppBuilder()
1364
- const RPC = Procedures<{}, RPCConfig>()
1365
-
1366
- RPC.CreateStream('Partial', { scope: 'partial', version: 1 }, async function* () {
1367
- yield sse({ v: 1 }, { event: 'custom' })
1368
- yield sse({ v: 2 }, { id: 'my-id' })
1369
- yield sse({ v: 3 })
1370
- })
1371
-
1372
- builder.register(RPC, () => ({}))
1373
- const app = builder.build()
1374
-
1375
- const res = await app.request('/partial/partial/1')
1376
- const text = await res.text()
1377
- const messages = text.split('\n\n').filter(Boolean)
1378
-
1379
- // First: custom event, auto id
1380
- expect(messages[0]).toContain('event: custom')
1381
- expect(messages[0]).toContain('id: 0')
1382
-
1383
- // Second: default event, custom id
1384
- expect(messages[1]).toContain('event: Partial')
1385
- expect(messages[1]).toContain('id: my-id')
1386
-
1387
- // Third: sse() with no options — same as plain object (defaults)
1388
- expect(messages[2]).toContain('event: Partial')
1389
- expect(messages[2]).toContain('id: 2')
1390
- })
1391
- })
1392
-
1393
- // --------------------------------------------------------------------------
1394
- // streamMode in Lifecycle Hooks
1395
- // --------------------------------------------------------------------------
1396
- describe('streamMode in lifecycle hooks', () => {
1397
- test('onStreamStart receives sse streamMode', async () => {
1398
- const onStreamStart = vi.fn()
1399
- const builder = new HonoStreamAppBuilder({ onStreamStart })
1400
- const RPC = Procedures<{}, RPCConfig>()
1401
-
1402
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
1403
- yield { ok: true }
1404
- })
1405
-
1406
- builder.register(RPC, () => ({}))
1407
- const app = builder.build()
1408
-
1409
- await app.request('/test/test/1')
1410
-
1411
- expect(onStreamStart).toHaveBeenCalledTimes(1)
1412
- const [, , streamMode] = onStreamStart.mock.calls[0]!
1413
- expect(streamMode).toBe('sse')
1414
- })
1415
-
1416
- test('onStreamEnd receives text streamMode', async () => {
1417
- const onStreamEnd = vi.fn()
1418
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text', onStreamEnd })
1419
- const RPC = Procedures<{}, RPCConfig>()
1420
-
1421
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
1422
- yield { ok: true }
1423
- })
1424
-
1425
- builder.register(RPC, () => ({}))
1426
- const app = builder.build()
1427
-
1428
- const res = await app.request('/test/test/1')
1429
- await res.text()
1430
-
1431
- expect(onStreamEnd).toHaveBeenCalledTimes(1)
1432
- const [, , streamMode] = onStreamEnd.mock.calls[0]!
1433
- expect(streamMode).toBe('text')
1434
- })
1435
-
1436
- test('onStreamStart and onStreamEnd receive matching streamMode', async () => {
1437
- const modes: { start?: StreamMode; end?: StreamMode } = {}
1438
- const builder = new HonoStreamAppBuilder({
1439
- defaultStreamMode: 'text',
1440
- onStreamStart: (_proc, _c, mode) => { modes.start = mode },
1441
- onStreamEnd: (_proc, _c, mode) => { modes.end = mode },
1442
- })
1443
- const RPC = Procedures<{}, RPCConfig>()
1444
-
1445
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
1446
- yield { ok: true }
1447
- })
1448
-
1449
- builder.register(RPC, () => ({}))
1450
- const app = builder.build()
1451
-
1452
- const res = await app.request('/test/test/1')
1453
- await res.text()
1454
-
1455
- expect(modes.start).toBe('text')
1456
- expect(modes.end).toBe('text')
1457
- })
1458
- })
1459
-
1460
- // --------------------------------------------------------------------------
1461
- // sse() in onMidStreamError
1462
- // --------------------------------------------------------------------------
1463
- describe('sse() in onMidStreamError', () => {
1464
- test('sse() wraps error data with custom event and id', async () => {
1465
- const builder = new HonoStreamAppBuilder({
1466
- onMidStreamError: (procedure, c, error) => {
1467
- return {
1468
- data: sse(
1469
- { type: 'error', message: error.message },
1470
- { event: 'custom-error', id: 'err-1' }
1471
- ),
1472
- }
1473
- },
1474
- })
1475
- const RPC = Procedures<{}, RPCConfig>()
1476
-
1477
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
1478
- yield { type: 'data', value: 1 }
1479
- throw new Error('Something broke')
1480
- })
1481
-
1482
- builder.register(RPC, () => ({}))
1483
- const app = builder.build()
1484
-
1485
- const res = await app.request('/error/error-stream/1')
1486
- const text = await res.text()
1487
-
1488
- // Normal yield
1489
- expect(text).toContain('data: {"type":"data","value":1}')
1490
- // Error yield with sse() metadata
1491
- expect(text).toContain('event: custom-error')
1492
- expect(text).toContain('id: err-1')
1493
- expect(text).toContain('"type":"error"')
1494
- })
1495
-
1496
- test('string error data without sse() uses default event and id', async () => {
1497
- const builder = new HonoStreamAppBuilder({
1498
- onMidStreamError: () => {
1499
- return { data: 'plain error string' }
1500
- },
1501
- })
1502
- const RPC = Procedures<{}, RPCConfig>()
1503
-
1504
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
1505
- yield { count: 1 }
1506
- throw new Error('fail')
1507
- })
1508
-
1509
- builder.register(RPC, () => ({}))
1510
- const app = builder.build()
1511
-
1512
- const res = await app.request('/error/error-stream/1')
1513
- const text = await res.text()
1514
-
1515
- // String data can't use sse() (not an object), so defaults apply
1516
- expect(text).toContain('data: plain error string')
1517
- // event defaults to procedure name when data is provided
1518
- expect(text).toContain('event: ErrorStream')
1519
- })
1520
- })
1521
-
1522
- // --------------------------------------------------------------------------
1523
- // Generic TErrorData
1524
- // --------------------------------------------------------------------------
1525
- describe('generic TErrorData', () => {
1526
- test('typed builder constrains onMidStreamError return type', async () => {
1527
- type ErrorPayload = { type: 'error'; code: string; message: string }
1528
-
1529
- const builder = new HonoStreamAppBuilder<ErrorPayload>({
1530
- onMidStreamError: (_procedure, _c, error) => {
1531
- // This satisfies MidStreamErrorResult<ErrorPayload>
1532
- return {
1533
- data: { type: 'error', code: 'STREAM_FAILED', message: error.message },
1534
- }
1535
- },
1536
- })
1537
- const RPC = Procedures<{}, RPCConfig>()
1538
-
1539
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
1540
- yield { value: 1 }
1541
- throw new Error('typed error')
1542
- })
1543
-
1544
- builder.register(RPC, () => ({}))
1545
- const app = builder.build()
1546
-
1547
- const res = await app.request('/error/error-stream/1')
1548
- const text = await res.text()
1549
-
1550
- expect(text).toContain('"code":"STREAM_FAILED"')
1551
- // Error message may be wrapped by Procedures with prefix
1552
- expect(text).toContain('typed error')
1553
- })
1554
- })
1555
-
1556
- // --------------------------------------------------------------------------
1557
- // ProcedureValidationError narrowing in onPreStreamError
1558
- // --------------------------------------------------------------------------
1559
- describe('ProcedureValidationError narrowing', () => {
1560
- test('instanceof check works in onPreStreamError', async () => {
1561
- let wasValidationError = false
1562
-
1563
- const builder = new HonoStreamAppBuilder({
1564
- onPreStreamError: (procedure, c, error) => {
1565
- if (error instanceof ProcedureValidationError) {
1566
- wasValidationError = true
1567
- return c.json({ validation: true, errors: error.errors }, 422)
1568
- }
1569
- return c.json({ error: error.message }, 500)
1570
- },
1571
- })
1572
- const RPC = Procedures<{}, RPCConfig>()
1573
-
1574
- RPC.CreateStream(
1575
- 'Validated',
1576
- {
1577
- scope: 'validated',
1578
- version: 1,
1579
- schema: { params: v.object({ count: v.number() }) },
1580
- },
1581
- async function* (ctx, params) {
1582
- yield { count: params.count }
1583
- }
1584
- )
1585
-
1586
- builder.register(RPC, () => ({}))
1587
- const app = builder.build()
1588
-
1589
- const res = await app.request('/validated/validated/1?count=not-a-number')
1590
-
1591
- expect(res.status).toBe(422)
1592
- expect(wasValidationError).toBe(true)
1593
- const body = await res.json()
1594
- expect(body.validation).toBe(true)
1595
- expect(body.errors).toBeDefined()
1596
- })
1597
- })
1598
-
1599
- // --------------------------------------------------------------------------
1600
- // Integration Test
1601
- // --------------------------------------------------------------------------
1602
- describe('integration', () => {
1603
- test('full workflow with streaming procedures', async () => {
1604
- type StreamContext = { userId: string }
1605
-
1606
- const RPC = Procedures<StreamContext, RPCConfig>()
1607
-
1608
- RPC.CreateStream(
1609
- 'WatchNotifications',
1610
- {
1611
- scope: ['user', 'notifications'],
1612
- version: 1,
1613
- schema: {
1614
- params: v.object({ limit: v.number() }),
1615
- yieldType: v.object({ id: v.number(), message: v.string() }),
1616
- },
1617
- },
1618
- async function* (ctx, params) {
1619
- const limit = params?.limit ?? 3
1620
- for (let i = 1; i <= limit; i++) {
1621
- yield { id: i, message: `Notification ${i} for ${ctx.userId}` }
1622
- }
1623
- }
1624
- )
1625
-
1626
- // Also create a non-streaming procedure to ensure it's filtered out
1627
- RPC.Create(
1628
- 'GetNotificationCount',
1629
- { scope: ['user', 'notifications'], version: 1 },
1630
- async () => ({
1631
- count: 10,
1632
- })
1633
- )
1634
-
1635
- const events: string[] = []
1636
-
1637
- const builder = new HonoStreamAppBuilder({
1638
- defaultStreamMode: 'text',
1639
- onRequestStart: () => events.push('request-start'),
1640
- onRequestEnd: () => events.push('request-end'),
1641
- onStreamStart: () => events.push('stream-start'),
1642
- onStreamEnd: () => events.push('stream-end'),
1643
- })
1644
-
1645
- builder.register(RPC, (c) => ({
1646
- userId: c.req.header('x-user-id') || 'anonymous',
1647
- }))
1648
-
1649
- const app = builder.build()
1650
-
1651
- // Only streaming procedure should be registered
1652
- expect(builder.docs).toHaveLength(1)
1653
- expect(builder.docs[0]!.name).toBe('WatchNotifications')
1654
- expect(builder.docs[0]!.methods).toEqual(['get', 'post'])
1655
-
1656
- // Test streaming
1657
- const res = await app.request('/user/notifications/watch-notifications/1?limit=2', {
1658
- headers: { 'X-User-Id': 'user-123' },
1659
- })
1660
-
1661
- expect(res.status).toBe(200)
1662
-
1663
- const text = await res.text()
1664
- const lines = text.trim().split('\n')
1665
- expect(lines).toHaveLength(2)
1666
- expect(JSON.parse(lines[0]!)).toEqual({ id: 1, message: 'Notification 1 for user-123' })
1667
- expect(JSON.parse(lines[1]!)).toEqual({ id: 2, message: 'Notification 2 for user-123' })
1668
-
1669
- // Verify hooks were called
1670
- expect(events).toContain('request-start')
1671
- expect(events).toContain('stream-start')
1672
- expect(events).toContain('stream-end')
1673
- expect(events).toContain('request-end')
1674
- })
1675
- })
1676
- })