ts-procedures 7.2.0 → 8.0.0

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