ts-procedures 5.9.1 → 5.10.2

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