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,1383 +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 } 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({ onError: 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 when the default taxonomy is engaged (via `errors: {}`)', async () => {
452
- // Opting into the taxonomy (even an empty one) engages the framework
453
- // default entries — ProcedureValidationError → 400.
454
- const builder = new HonoStreamAppBuilder({ errors: {} });
455
- const RPC = Procedures();
456
- RPC.CreateStream('ValidatedStream', {
457
- scope: 'validated',
458
- version: 1,
459
- schema: {
460
- params: v.object({ count: v.number() }),
461
- },
462
- }, async function* (ctx, params) {
463
- yield { count: params.count };
464
- });
465
- builder.register(RPC, () => ({}));
466
- const app = builder.build();
467
- const res = await app.request('/validated/validated-stream/1?count=not-a-number');
468
- expect(res.status).toBe(400);
469
- const body = await res.json();
470
- expect(body.name).toBe('ProcedureValidationError');
471
- });
472
- test('validation errors return 500 by default with no builder config (hard-default path)', async () => {
473
- // With no taxonomy and no onError configured, every error falls through
474
- // to the flat 500 hard default — consistent with the other three
475
- // builders. Previously hono-stream special-cased ProcedureValidationError
476
- // to 400; that predated the taxonomy and was removed in v6.
477
- const builder = new HonoStreamAppBuilder();
478
- const RPC = Procedures();
479
- RPC.CreateStream('ValidatedStream', {
480
- scope: 'validated',
481
- version: 1,
482
- schema: {
483
- params: v.object({ count: v.number() }),
484
- },
485
- }, async function* (ctx, params) {
486
- yield { count: params.count };
487
- });
488
- builder.register(RPC, () => ({}));
489
- const app = builder.build();
490
- const res = await app.request('/validated/validated-stream/1?count=not-a-number');
491
- expect(res.status).toBe(500);
492
- const body = await res.json();
493
- expect(body.error).toContain('Validation error');
494
- });
495
- // Tests for onError and onMidStreamError callbacks
496
- test('onError handles validation errors with custom Response', async () => {
497
- const onError = vi.fn((procedure, c, error) => {
498
- return c.json({ customError: true, procedureName: procedure.name, details: error.message }, 422);
499
- });
500
- const builder = new HonoStreamAppBuilder({ onError });
501
- const RPC = Procedures();
502
- RPC.CreateStream('ValidatedStream', {
503
- scope: 'validated',
504
- version: 1,
505
- schema: {
506
- params: v.object({ count: v.number() }),
507
- },
508
- }, async function* (ctx, params) {
509
- yield { count: params.count };
510
- });
511
- builder.register(RPC, () => ({}));
512
- const app = builder.build();
513
- const res = await app.request('/validated/validated-stream/1?count=not-a-number');
514
- expect(res.status).toBe(422);
515
- const body = await res.json();
516
- expect(body.customError).toBe(true);
517
- expect(body.procedureName).toBe('ValidatedStream');
518
- expect(body.details).toContain('Validation error');
519
- expect(onError).toHaveBeenCalledTimes(1);
520
- });
521
- test('onError handles context resolution errors', async () => {
522
- const onError = vi.fn((procedure, c, error) => {
523
- return c.json({ contextError: error.message }, 401);
524
- });
525
- const builder = new HonoStreamAppBuilder({ onError });
526
- const RPC = Procedures();
527
- RPC.CreateStream('SecureStream', { scope: 'secure', version: 1 }, async function* (ctx) {
528
- yield { userId: ctx.userId };
529
- });
530
- builder.register(RPC, () => {
531
- throw new Error('Authentication required');
532
- });
533
- const app = builder.build();
534
- const res = await app.request('/secure/secure-stream/1');
535
- expect(res.status).toBe(401);
536
- const body = await res.json();
537
- expect(body.contextError).toBe('Authentication required');
538
- expect(onError).toHaveBeenCalledTimes(1);
539
- });
540
- test('onMidStreamError returns custom value written to SSE stream', async () => {
541
- const onMidStreamError = vi.fn((procedure, c, error) => {
542
- return {
543
- data: {
544
- type: 'error',
545
- code: 'STREAM_FAILED',
546
- message: error.message,
547
- retryable: false,
548
- },
549
- closeStream: true,
550
- };
551
- });
552
- const builder = new HonoStreamAppBuilder({ onMidStreamError });
553
- const RPC = Procedures();
554
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
555
- yield { type: 'data', value: 1 };
556
- throw new Error('Something broke');
557
- });
558
- builder.register(RPC, () => ({}));
559
- const app = builder.build();
560
- const res = await app.request('/error/error-stream/1');
561
- const text = await res.text();
562
- // First yield should be present
563
- expect(text).toContain('data: {"type":"data","value":1}');
564
- // Error should use custom format from onMidStreamError
565
- expect(text).toContain('data: {"type":"error","code":"STREAM_FAILED"');
566
- expect(text).toContain('"retryable":false');
567
- // Event should use procedure name (not 'error') since custom value provided
568
- expect(text).toContain('event: ErrorStream');
569
- expect(onMidStreamError).toHaveBeenCalledTimes(1);
570
- });
571
- test('onMidStreamError returns custom value written to text stream', async () => {
572
- const onMidStreamError = vi.fn((procedure, c, error) => {
573
- return {
574
- data: { type: 'error', message: error.message },
575
- };
576
- });
577
- const builder = new HonoStreamAppBuilder({
578
- defaultStreamMode: 'text',
579
- onMidStreamError,
580
- });
581
- const RPC = Procedures();
582
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
583
- yield { type: 'data', value: 'hello' };
584
- throw new Error('Stream failed');
585
- });
586
- builder.register(RPC, () => ({}));
587
- const app = builder.build();
588
- const res = await app.request('/error/error-stream/1');
589
- const text = await res.text();
590
- const lines = text.trim().split('\n');
591
- expect(JSON.parse(lines[0])).toEqual({ type: 'data', value: 'hello' });
592
- // Error message may be wrapped by Procedures with "Error in streaming handler for X - " prefix
593
- const errorLine = JSON.parse(lines[1]);
594
- expect(errorLine.type).toBe('error');
595
- expect(errorLine.message).toContain('Stream failed');
596
- expect(onMidStreamError).toHaveBeenCalledTimes(1);
597
- });
598
- test('onMidStreamError returning undefined falls back to default error format', async () => {
599
- const onMidStreamError = vi.fn(() => undefined);
600
- const builder = new HonoStreamAppBuilder({
601
- defaultStreamMode: 'text',
602
- onMidStreamError,
603
- });
604
- const RPC = Procedures();
605
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
606
- yield { value: 1 };
607
- throw new Error('Fallback test');
608
- });
609
- builder.register(RPC, () => ({}));
610
- const app = builder.build();
611
- const res = await app.request('/error/error-stream/1');
612
- const text = await res.text();
613
- const lines = text.trim().split('\n');
614
- expect(JSON.parse(lines[0])).toEqual({ value: 1 });
615
- // Falls back to default { error: message } format
616
- expect(JSON.parse(lines[1]).error).toContain('Fallback test');
617
- expect(onMidStreamError).toHaveBeenCalledTimes(1);
618
- });
619
- });
620
- // --------------------------------------------------------------------------
621
- // Context Resolution Tests
622
- // --------------------------------------------------------------------------
623
- describe('context resolution', () => {
624
- test('context can be a static object', async () => {
625
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
626
- const RPC = Procedures();
627
- RPC.CreateStream('GetId', { scope: 'get-id', version: 1 }, async function* (ctx) {
628
- yield { id: ctx.requestId };
629
- });
630
- builder.register(RPC, { requestId: 'static-123' });
631
- const app = builder.build();
632
- const res = await app.request('/get-id/get-id/1');
633
- const text = await res.text();
634
- expect(JSON.parse(text.trim())).toEqual({ id: 'static-123' });
635
- });
636
- test('context can be sync function', async () => {
637
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
638
- const RPC = Procedures();
639
- RPC.CreateStream('GetId', { scope: 'get-id', version: 1 }, async function* (ctx) {
640
- yield { id: ctx.requestId };
641
- });
642
- builder.register(RPC, (c) => ({ requestId: c.req.header('x-request-id') || 'unknown' }));
643
- const app = builder.build();
644
- const res = await app.request('/get-id/get-id/1', {
645
- headers: { 'X-Request-Id': 'req-456' },
646
- });
647
- const text = await res.text();
648
- expect(JSON.parse(text.trim())).toEqual({ id: 'req-456' });
649
- });
650
- test('context can be async function', async () => {
651
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
652
- const RPC = Procedures();
653
- RPC.CreateStream('GetId', { scope: 'get-id', version: 1 }, async function* (ctx) {
654
- yield { id: ctx.requestId };
655
- });
656
- builder.register(RPC, async () => {
657
- await new Promise((r) => setTimeout(r, 10));
658
- return { requestId: 'async-789' };
659
- });
660
- const app = builder.build();
661
- const res = await app.request('/get-id/get-id/1');
662
- const text = await res.text();
663
- expect(JSON.parse(text.trim())).toEqual({ id: 'async-789' });
664
- });
665
- });
666
- // --------------------------------------------------------------------------
667
- // Documentation Tests
668
- // --------------------------------------------------------------------------
669
- describe('documentation', () => {
670
- test('generates complete route documentation', () => {
671
- const paramsSchema = v.object({ id: v.string() });
672
- const yieldSchema = v.object({ message: v.string() });
673
- const returnSchema = v.object({ total: v.number() });
674
- const builder = new HonoStreamAppBuilder();
675
- const RPC = Procedures();
676
- RPC.CreateStream('StreamMessages', {
677
- scope: 'messages',
678
- version: 1,
679
- schema: { params: paramsSchema, yieldType: yieldSchema, returnType: returnSchema },
680
- }, async function* () {
681
- yield { message: 'test' };
682
- });
683
- builder.register(RPC, () => ({}));
684
- builder.build();
685
- const doc = builder.docs[0];
686
- expect(doc.path).toBe('/messages/stream-messages/1');
687
- expect(doc.methods).toEqual(['post', 'get']);
688
- expect(doc.streamMode).toBe('sse');
689
- expect(doc.jsonSchema.params).toBeDefined();
690
- expect(doc.jsonSchema.returnType).toBeDefined();
691
- // yieldType is nested under SSE envelope's data property
692
- const yt = doc.jsonSchema.yieldType;
693
- expect(yt.description).toBe('SSE message envelope. The data field contains the procedure yield value.');
694
- expect(yt.required).toEqual(['data', 'event', 'id']);
695
- expect(yt.properties.event).toEqual({ type: 'string' });
696
- expect(yt.properties.id).toEqual({ type: 'string' });
697
- expect(yt.properties.retry).toEqual({ type: 'number' });
698
- // Developer's yieldType is nested under data
699
- expect(yt.properties.data.properties.message).toBeDefined();
700
- });
701
- test('SSE mode generates SSE envelope even when no yieldType is defined', () => {
702
- const builder = new HonoStreamAppBuilder();
703
- const RPC = Procedures();
704
- RPC.CreateStream('NoYield', { scope: 'test', version: 1 }, async function* () {
705
- yield {};
706
- });
707
- builder.register(RPC, () => ({}));
708
- builder.build();
709
- const yt = builder.docs[0].jsonSchema.yieldType;
710
- expect(yt).toBeDefined();
711
- expect(yt.type).toBe('object');
712
- expect(yt.description).toBe('SSE message envelope. The data field contains the procedure yield value.');
713
- expect(yt.required).toEqual(['data', 'event', 'id']);
714
- // data is empty schema when no yieldType defined
715
- expect(yt.properties.data).toEqual({});
716
- expect(yt.properties.event).toEqual({ type: 'string' });
717
- expect(yt.properties.id).toEqual({ type: 'string' });
718
- expect(yt.properties.retry).toEqual({ type: 'number' });
719
- });
720
- test('text mode passes yieldType through as-is', () => {
721
- const yieldSchema = v.object({ chunk: v.string() });
722
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
723
- const RPC = Procedures();
724
- RPC.CreateStream('TextStream', { scope: 'test', version: 1, schema: { yieldType: yieldSchema } }, async function* () {
725
- yield { chunk: 'hi' };
726
- });
727
- builder.register(RPC, () => ({}));
728
- builder.build();
729
- const yt = builder.docs[0].jsonSchema.yieldType;
730
- expect(yt).toBeDefined();
731
- // Text mode should NOT have SSE envelope fields injected
732
- expect(yt.properties?.event).toBeUndefined();
733
- expect(yt.properties?.id).toBeUndefined();
734
- expect(yt.properties?.retry).toBeUndefined();
735
- });
736
- test('yieldType with id property does not collide with SSE id field', () => {
737
- // User's yieldType has an `id` field (number) — this should be nested under
738
- // the SSE envelope's `data` property, not collide with the SSE `id` (string)
739
- const yieldSchema = v.object({
740
- id: v.number(),
741
- message: v.string(),
742
- });
743
- const builder = new HonoStreamAppBuilder();
744
- const RPC = Procedures();
745
- RPC.CreateStream('Notifications', { scope: 'test', version: 1, schema: { yieldType: yieldSchema } }, async function* () {
746
- yield { id: 42, message: 'hello' };
747
- });
748
- builder.register(RPC, () => ({}));
749
- builder.build();
750
- const yt = builder.docs[0].jsonSchema.yieldType;
751
- expect(yt.required).toEqual(['data', 'event', 'id']);
752
- // SSE envelope id is a string
753
- expect(yt.properties.id).toEqual({ type: 'string' });
754
- // User's id (number) is safely nested under data
755
- expect(yt.properties.data.properties.id.type).toBe('number');
756
- expect(yt.properties.data.properties.message.type).toBe('string');
757
- });
758
- test('streamMode is recorded in docs', () => {
759
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
760
- const RPC = Procedures();
761
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
762
- yield {};
763
- });
764
- builder.register(RPC, () => ({}));
765
- builder.build();
766
- expect(builder.docs[0].streamMode).toBe('text');
767
- });
768
- test('per-factory streamMode is recorded in docs', () => {
769
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'sse' });
770
- const RPC = Procedures();
771
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
772
- yield {};
773
- });
774
- builder.register(RPC, () => ({}), { streamMode: 'text' });
775
- builder.build();
776
- expect(builder.docs[0].streamMode).toBe('text');
777
- });
778
- test("doc.kind is 'stream'", () => {
779
- const builder = new HonoStreamAppBuilder();
780
- const RPC = Procedures();
781
- RPC.CreateStream('StreamEvents', { scope: 'events', version: 1 }, async function* () {
782
- yield {};
783
- });
784
- builder.register(RPC, () => ({}));
785
- builder.build();
786
- const doc = builder.docs[0];
787
- expect(doc.kind).toBe('stream');
788
- });
789
- });
790
- // --------------------------------------------------------------------------
791
- // Filter Tests (Only Streaming Procedures)
792
- // --------------------------------------------------------------------------
793
- describe('procedure filtering', () => {
794
- test('only registers streaming procedures', async () => {
795
- const builder = new HonoStreamAppBuilder();
796
- const RPC = Procedures();
797
- // Regular procedure (should be ignored)
798
- RPC.Create('NonStream', { scope: 'non-stream', version: 1 }, async () => ({
799
- ok: true,
800
- }));
801
- // Streaming procedure (should be registered)
802
- RPC.CreateStream('Stream', { scope: 'stream', version: 1 }, async function* () {
803
- yield { ok: true };
804
- });
805
- builder.register(RPC, () => ({}));
806
- const app = builder.build();
807
- // Only streaming procedure should be in docs
808
- expect(builder.docs).toHaveLength(1);
809
- expect(builder.docs[0].name).toBe('Stream');
810
- // Non-streaming route should 404
811
- const nonStreamRes = await app.request('/non-stream/non-stream/1', { method: 'POST' });
812
- expect(nonStreamRes.status).toBe(404);
813
- // Streaming route should work
814
- const streamRes = await app.request('/stream/stream/1');
815
- expect(streamRes.status).toBe(200);
816
- });
817
- });
818
- // --------------------------------------------------------------------------
819
- // extendProcedureDoc Tests
820
- // --------------------------------------------------------------------------
821
- describe('extendProcedureDoc', () => {
822
- test('adds custom properties to generated documentation', () => {
823
- const builder = new HonoStreamAppBuilder();
824
- const RPC = Procedures();
825
- RPC.CreateStream('StreamEvents', { scope: 'events', version: 1 }, async function* () {
826
- yield {};
827
- });
828
- builder.register(RPC, () => ({}), {
829
- extendProcedureDoc: ({ procedure }) => ({
830
- summary: `Stream events endpoint`,
831
- tags: ['events'],
832
- operationId: procedure.name,
833
- }),
834
- });
835
- builder.build();
836
- const doc = builder.docs[0];
837
- expect(doc).toHaveProperty('summary', 'Stream events endpoint');
838
- expect(doc).toHaveProperty('tags', ['events']);
839
- expect(doc).toHaveProperty('operationId', 'StreamEvents');
840
- });
841
- test('base properties take precedence over extended properties', () => {
842
- const builder = new HonoStreamAppBuilder();
843
- const RPC = Procedures();
844
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
845
- yield {};
846
- });
847
- builder.register(RPC, () => ({}), {
848
- extendProcedureDoc: () => ({
849
- name: 'OverriddenName',
850
- path: '/overridden/path',
851
- methods: ['put'],
852
- customField: 'custom-value',
853
- }),
854
- });
855
- builder.build();
856
- const doc = builder.docs[0];
857
- // Base properties should NOT be overridden
858
- expect(doc.name).toBe('Test');
859
- expect(doc.path).toBe('/test/test/1');
860
- expect(doc.methods).toEqual(['post', 'get']);
861
- // Custom field should be present
862
- expect(doc).toHaveProperty('customField', 'custom-value');
863
- });
864
- });
865
- // --------------------------------------------------------------------------
866
- // Multiple Factory Tests
867
- // --------------------------------------------------------------------------
868
- describe('multiple factories', () => {
869
- test('supports registering multiple factories', async () => {
870
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
871
- const PublicRPC = Procedures();
872
- const PrivateRPC = Procedures();
873
- PublicRPC.CreateStream('PublicStream', { scope: 'public', version: 1 }, async function* (ctx) {
874
- yield { isPublic: ctx.public };
875
- });
876
- PrivateRPC.CreateStream('PrivateStream', { scope: 'private', version: 1 }, async function* (ctx) {
877
- yield { isPrivate: ctx.private };
878
- });
879
- builder
880
- .register(PublicRPC, () => ({ public: true }))
881
- .register(PrivateRPC, () => ({ private: true }));
882
- const app = builder.build();
883
- const publicRes = await app.request('/public/public-stream/1');
884
- const publicText = await publicRes.text();
885
- expect(JSON.parse(publicText.trim())).toEqual({ isPublic: true });
886
- const privateRes = await app.request('/private/private-stream/1');
887
- const privateText = await privateRes.text();
888
- expect(JSON.parse(privateText.trim())).toEqual({ isPrivate: true });
889
- });
890
- test('different factories can have different stream modes', async () => {
891
- const builder = new HonoStreamAppBuilder();
892
- const SSERPC = Procedures();
893
- const TextRPC = Procedures();
894
- SSERPC.CreateStream('SSEStream', { scope: 'sse', version: 1 }, async function* () {
895
- yield { mode: 'sse' };
896
- });
897
- TextRPC.CreateStream('TextStream', { scope: 'text', version: 1 }, async function* () {
898
- yield { mode: 'text' };
899
- });
900
- builder
901
- .register(SSERPC, () => ({}), { streamMode: 'sse' })
902
- .register(TextRPC, () => ({}), { streamMode: 'text' });
903
- const app = builder.build();
904
- const sseRes = await app.request('/sse/sse-stream/1');
905
- expect(sseRes.headers.get('content-type')).toContain('text/event-stream');
906
- const textRes = await app.request('/text/text-stream/1');
907
- expect(textRes.headers.get('content-type')).toContain('text/plain');
908
- });
909
- });
910
- // --------------------------------------------------------------------------
911
- // Path Generation Tests
912
- // --------------------------------------------------------------------------
913
- describe('makeStreamHttpRoutePath', () => {
914
- let builder;
915
- beforeEach(() => {
916
- builder = new HonoStreamAppBuilder();
917
- });
918
- test("simple scope: 'events' + 'StreamUpdates' → /events/stream-updates/1", () => {
919
- const path = builder.makeStreamHttpRoutePath('StreamUpdates', { scope: 'events', version: 1 });
920
- expect(path).toBe('/events/stream-updates/1');
921
- });
922
- test("array scope: ['events', 'live'] + 'Watch' → /events/live/watch/1", () => {
923
- const path = builder.makeStreamHttpRoutePath('Watch', {
924
- scope: ['events', 'live'],
925
- version: 1,
926
- });
927
- expect(path).toBe('/events/live/watch/1');
928
- });
929
- test('version number included in path', () => {
930
- const pathV1 = builder.makeStreamHttpRoutePath('Test', { scope: 'test', version: 1 });
931
- const pathV2 = builder.makeStreamHttpRoutePath('Test', { scope: 'test', version: 2 });
932
- expect(pathV1).toBe('/test/test/1');
933
- expect(pathV2).toBe('/test/test/2');
934
- });
935
- });
936
- // --------------------------------------------------------------------------
937
- // isPrevalidated Tests
938
- // --------------------------------------------------------------------------
939
- describe('isPrevalidated context property', () => {
940
- test('skips procedure-level validation since HonoStreamAppBuilder already validated', async () => {
941
- let handlerCalled = false;
942
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
943
- const RPC = Procedures();
944
- RPC.CreateStream('CheckPrevalidated', {
945
- scope: 'check',
946
- version: 1,
947
- schema: {
948
- params: v.object({ name: v.string() }),
949
- },
950
- }, async function* () {
951
- handlerCalled = true;
952
- yield { ok: true };
953
- });
954
- builder.register(RPC, () => ({}));
955
- const app = builder.build();
956
- // Valid params pass HonoStreamAppBuilder validation, handler runs without double validation
957
- const res = await app.request('/check/check-prevalidated/1?name=test');
958
- await res.text();
959
- expect(res.status).toBe(200);
960
- expect(handlerCalled).toBe(true);
961
- });
962
- test('valid params work correctly with pre-validation flow', async () => {
963
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
964
- const RPC = Procedures();
965
- RPC.CreateStream('ValidParams', {
966
- scope: 'valid',
967
- version: 1,
968
- schema: {
969
- params: v.object({ count: v.number() }),
970
- },
971
- }, async function* (ctx, params) {
972
- const count = params.count ?? 0;
973
- for (let i = 0; i < count; i++) {
974
- yield { index: i };
975
- }
976
- });
977
- builder.register(RPC, () => ({}));
978
- const app = builder.build();
979
- // With valid params, both HonoStreamAppBuilder validation and procedure validation should work
980
- const res = await app.request('/valid/valid-params/1?count=2');
981
- expect(res.status).toBe(200);
982
- const text = await res.text();
983
- const lines = text.trim().split('\n');
984
- expect(lines).toHaveLength(2);
985
- expect(JSON.parse(lines[0])).toEqual({ index: 0 });
986
- expect(JSON.parse(lines[1])).toEqual({ index: 1 });
987
- });
988
- test('invalid params are caught by HonoStreamAppBuilder before handler runs', async () => {
989
- let handlerCalled = false;
990
- // Opt into the taxonomy (empty) so the default ProcedureValidationError
991
- // entry returns 400 — the recommended way to get a structured validation
992
- // response now that the hard default is a flat 500.
993
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text', errors: {} });
994
- const RPC = Procedures();
995
- RPC.CreateStream('InvalidParams', {
996
- scope: 'invalid',
997
- version: 1,
998
- schema: {
999
- params: v.object({ count: v.number() }),
1000
- },
1001
- }, async function* () {
1002
- handlerCalled = true;
1003
- yield { ok: true };
1004
- });
1005
- builder.register(RPC, () => ({}));
1006
- const app = builder.build();
1007
- // With invalid params, HonoStreamAppBuilder catches the error before streaming starts
1008
- const res = await app.request('/invalid/invalid-params/1?count=not-a-number');
1009
- expect(res.status).toBe(400);
1010
- const body = await res.json();
1011
- expect(body.name).toBe('ProcedureValidationError');
1012
- // Handler should never be called since validation fails before streaming
1013
- expect(handlerCalled).toBe(false);
1014
- });
1015
- });
1016
- // --------------------------------------------------------------------------
1017
- // SSE Yield Shape Tests
1018
- // --------------------------------------------------------------------------
1019
- describe('SSE yield shape', () => {
1020
- test('custom event names via sse() helper', async () => {
1021
- const builder = new HonoStreamAppBuilder();
1022
- const RPC = Procedures();
1023
- RPC.CreateStream('Events', { scope: 'events', version: 1 }, async function* () {
1024
- yield sse({ type: 'user_joined' }, { event: 'join' });
1025
- yield sse({ type: 'message' }, { event: 'chat' });
1026
- });
1027
- builder.register(RPC, () => ({}));
1028
- const app = builder.build();
1029
- const res = await app.request('/events/events/1');
1030
- const text = await res.text();
1031
- expect(text).toContain('event: join');
1032
- expect(text).toContain('event: chat');
1033
- expect(text).not.toContain('event: Events');
1034
- });
1035
- test('custom id via sse() helper', async () => {
1036
- const builder = new HonoStreamAppBuilder();
1037
- const RPC = Procedures();
1038
- RPC.CreateStream('Events', { scope: 'events', version: 1 }, async function* () {
1039
- yield sse({ msg: 'first' }, { id: 'msg-001' });
1040
- yield sse({ msg: 'second' }, { id: 'msg-002' });
1041
- });
1042
- builder.register(RPC, () => ({}));
1043
- const app = builder.build();
1044
- const res = await app.request('/events/events/1');
1045
- const text = await res.text();
1046
- expect(text).toContain('id: msg-001');
1047
- expect(text).toContain('id: msg-002');
1048
- });
1049
- test('string data pass-through without double-stringify', async () => {
1050
- const builder = new HonoStreamAppBuilder();
1051
- const RPC = Procedures();
1052
- RPC.CreateStream('Events', { scope: 'events', version: 1 }, async function* () {
1053
- yield 'already a string';
1054
- yield { needs: 'stringify' };
1055
- });
1056
- builder.register(RPC, () => ({}));
1057
- const app = builder.build();
1058
- const res = await app.request('/events/events/1');
1059
- const text = await res.text();
1060
- // String data should be passed through as-is (not JSON-stringified again)
1061
- expect(text).toContain('data: already a string');
1062
- // Object data should be JSON-stringified
1063
- expect(text).toContain('data: {"needs":"stringify"}');
1064
- });
1065
- test('default event falls back to procedure name when omitted', async () => {
1066
- const builder = new HonoStreamAppBuilder();
1067
- const RPC = Procedures();
1068
- RPC.CreateStream('MyProcedure', { scope: 'test', version: 1 }, async function* () {
1069
- yield { value: 1 };
1070
- yield sse({ value: 2 }, { event: 'custom' });
1071
- yield { value: 3 };
1072
- });
1073
- builder.register(RPC, () => ({}));
1074
- const app = builder.build();
1075
- const res = await app.request('/test/my-procedure/1');
1076
- const text = await res.text();
1077
- // Split into individual SSE messages
1078
- const messages = text.split('\n\n').filter(Boolean);
1079
- // First and third should use procedure name as event
1080
- expect(messages[0]).toContain('event: MyProcedure');
1081
- // Second should use custom event
1082
- expect(messages[1]).toContain('event: custom');
1083
- // Third should fall back to procedure name
1084
- expect(messages[2]).toContain('event: MyProcedure');
1085
- });
1086
- });
1087
- // --------------------------------------------------------------------------
1088
- // sse() Helper Tests
1089
- // --------------------------------------------------------------------------
1090
- describe('sse() helper', () => {
1091
- test('tagged yields with custom event/id/retry', async () => {
1092
- const builder = new HonoStreamAppBuilder();
1093
- const RPC = Procedures();
1094
- RPC.CreateStream('Tagged', { scope: 'tagged', version: 1 }, async function* () {
1095
- yield sse({ count: 1 }, { event: 'tick', id: 'evt-1', retry: 5000 });
1096
- });
1097
- builder.register(RPC, () => ({}));
1098
- const app = builder.build();
1099
- const res = await app.request('/tagged/tagged/1');
1100
- const text = await res.text();
1101
- expect(text).toContain('event: tick');
1102
- expect(text).toContain('id: evt-1');
1103
- expect(text).toContain('retry: 5000');
1104
- expect(text).toContain('data: {"count":1}');
1105
- });
1106
- test('plain domain objects use procedure name and auto-incremented id', async () => {
1107
- const builder = new HonoStreamAppBuilder();
1108
- const RPC = Procedures();
1109
- RPC.CreateStream('Plain', { scope: 'plain', version: 1 }, async function* () {
1110
- yield { a: 1 };
1111
- yield { a: 2 };
1112
- });
1113
- builder.register(RPC, () => ({}));
1114
- const app = builder.build();
1115
- const res = await app.request('/plain/plain/1');
1116
- const text = await res.text();
1117
- const messages = text.split('\n\n').filter(Boolean);
1118
- expect(messages[0]).toContain('event: Plain');
1119
- expect(messages[0]).toContain('id: 0');
1120
- expect(messages[0]).toContain('data: {"a":1}');
1121
- expect(messages[1]).toContain('event: Plain');
1122
- expect(messages[1]).toContain('id: 1');
1123
- expect(messages[1]).toContain('data: {"a":2}');
1124
- });
1125
- test('sse() metadata is invisible in text mode', async () => {
1126
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text' });
1127
- const RPC = Procedures();
1128
- RPC.CreateStream('TextTagged', { scope: 'text', version: 1 }, async function* () {
1129
- yield sse({ count: 1 }, { event: 'tick' });
1130
- yield { count: 2 };
1131
- });
1132
- builder.register(RPC, () => ({}));
1133
- const app = builder.build();
1134
- const res = await app.request('/text/text-tagged/1');
1135
- const text = await res.text();
1136
- const lines = text.trim().split('\n');
1137
- // Text mode just JSON-stringifies — sse() metadata is not visible
1138
- expect(JSON.parse(lines[0])).toEqual({ count: 1 });
1139
- expect(JSON.parse(lines[1])).toEqual({ count: 2 });
1140
- });
1141
- test('sse() with partial options', async () => {
1142
- const builder = new HonoStreamAppBuilder();
1143
- const RPC = Procedures();
1144
- RPC.CreateStream('Partial', { scope: 'partial', version: 1 }, async function* () {
1145
- yield sse({ v: 1 }, { event: 'custom' });
1146
- yield sse({ v: 2 }, { id: 'my-id' });
1147
- yield sse({ v: 3 });
1148
- });
1149
- builder.register(RPC, () => ({}));
1150
- const app = builder.build();
1151
- const res = await app.request('/partial/partial/1');
1152
- const text = await res.text();
1153
- const messages = text.split('\n\n').filter(Boolean);
1154
- // First: custom event, auto id
1155
- expect(messages[0]).toContain('event: custom');
1156
- expect(messages[0]).toContain('id: 0');
1157
- // Second: default event, custom id
1158
- expect(messages[1]).toContain('event: Partial');
1159
- expect(messages[1]).toContain('id: my-id');
1160
- // Third: sse() with no options — same as plain object (defaults)
1161
- expect(messages[2]).toContain('event: Partial');
1162
- expect(messages[2]).toContain('id: 2');
1163
- });
1164
- });
1165
- // --------------------------------------------------------------------------
1166
- // streamMode in Lifecycle Hooks
1167
- // --------------------------------------------------------------------------
1168
- describe('streamMode in lifecycle hooks', () => {
1169
- test('onStreamStart receives sse streamMode', async () => {
1170
- const onStreamStart = vi.fn();
1171
- const builder = new HonoStreamAppBuilder({ onStreamStart });
1172
- const RPC = Procedures();
1173
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
1174
- yield { ok: true };
1175
- });
1176
- builder.register(RPC, () => ({}));
1177
- const app = builder.build();
1178
- await app.request('/test/test/1');
1179
- expect(onStreamStart).toHaveBeenCalledTimes(1);
1180
- const [, , streamMode] = onStreamStart.mock.calls[0];
1181
- expect(streamMode).toBe('sse');
1182
- });
1183
- test('onStreamEnd receives text streamMode', async () => {
1184
- const onStreamEnd = vi.fn();
1185
- const builder = new HonoStreamAppBuilder({ defaultStreamMode: 'text', onStreamEnd });
1186
- const RPC = Procedures();
1187
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
1188
- yield { ok: true };
1189
- });
1190
- builder.register(RPC, () => ({}));
1191
- const app = builder.build();
1192
- const res = await app.request('/test/test/1');
1193
- await res.text();
1194
- expect(onStreamEnd).toHaveBeenCalledTimes(1);
1195
- const [, , streamMode] = onStreamEnd.mock.calls[0];
1196
- expect(streamMode).toBe('text');
1197
- });
1198
- test('onStreamStart and onStreamEnd receive matching streamMode', async () => {
1199
- const modes = {};
1200
- const builder = new HonoStreamAppBuilder({
1201
- defaultStreamMode: 'text',
1202
- onStreamStart: (_proc, _c, mode) => { modes.start = mode; },
1203
- onStreamEnd: (_proc, _c, mode) => { modes.end = mode; },
1204
- });
1205
- const RPC = Procedures();
1206
- RPC.CreateStream('Test', { scope: 'test', version: 1 }, async function* () {
1207
- yield { ok: true };
1208
- });
1209
- builder.register(RPC, () => ({}));
1210
- const app = builder.build();
1211
- const res = await app.request('/test/test/1');
1212
- await res.text();
1213
- expect(modes.start).toBe('text');
1214
- expect(modes.end).toBe('text');
1215
- });
1216
- });
1217
- // --------------------------------------------------------------------------
1218
- // sse() in onMidStreamError
1219
- // --------------------------------------------------------------------------
1220
- describe('sse() in onMidStreamError', () => {
1221
- test('sse() wraps error data with custom event and id', async () => {
1222
- const builder = new HonoStreamAppBuilder({
1223
- onMidStreamError: (procedure, c, error) => {
1224
- return {
1225
- data: sse({ type: 'error', message: error.message }, { event: 'custom-error', id: 'err-1' }),
1226
- };
1227
- },
1228
- });
1229
- const RPC = Procedures();
1230
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
1231
- yield { type: 'data', value: 1 };
1232
- throw new Error('Something broke');
1233
- });
1234
- builder.register(RPC, () => ({}));
1235
- const app = builder.build();
1236
- const res = await app.request('/error/error-stream/1');
1237
- const text = await res.text();
1238
- // Normal yield
1239
- expect(text).toContain('data: {"type":"data","value":1}');
1240
- // Error yield with sse() metadata
1241
- expect(text).toContain('event: custom-error');
1242
- expect(text).toContain('id: err-1');
1243
- expect(text).toContain('"type":"error"');
1244
- });
1245
- test('string error data without sse() uses default event and id', async () => {
1246
- const builder = new HonoStreamAppBuilder({
1247
- onMidStreamError: () => {
1248
- return { data: 'plain error string' };
1249
- },
1250
- });
1251
- const RPC = Procedures();
1252
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
1253
- yield { count: 1 };
1254
- throw new Error('fail');
1255
- });
1256
- builder.register(RPC, () => ({}));
1257
- const app = builder.build();
1258
- const res = await app.request('/error/error-stream/1');
1259
- const text = await res.text();
1260
- // String data can't use sse() (not an object), so defaults apply
1261
- expect(text).toContain('data: plain error string');
1262
- // event defaults to procedure name when data is provided
1263
- expect(text).toContain('event: ErrorStream');
1264
- });
1265
- });
1266
- // --------------------------------------------------------------------------
1267
- // Generic TErrorData
1268
- // --------------------------------------------------------------------------
1269
- describe('generic TErrorData', () => {
1270
- test('typed builder constrains onMidStreamError return type', async () => {
1271
- const builder = new HonoStreamAppBuilder({
1272
- onMidStreamError: (_procedure, _c, error) => {
1273
- // This satisfies MidStreamErrorResult<ErrorPayload>
1274
- return {
1275
- data: { type: 'error', code: 'STREAM_FAILED', message: error.message },
1276
- };
1277
- },
1278
- });
1279
- const RPC = Procedures();
1280
- RPC.CreateStream('ErrorStream', { scope: 'error', version: 1 }, async function* () {
1281
- yield { value: 1 };
1282
- throw new Error('typed error');
1283
- });
1284
- builder.register(RPC, () => ({}));
1285
- const app = builder.build();
1286
- const res = await app.request('/error/error-stream/1');
1287
- const text = await res.text();
1288
- expect(text).toContain('"code":"STREAM_FAILED"');
1289
- // Error message may be wrapped by Procedures with prefix
1290
- expect(text).toContain('typed error');
1291
- });
1292
- });
1293
- // --------------------------------------------------------------------------
1294
- // ProcedureValidationError narrowing in onError
1295
- // --------------------------------------------------------------------------
1296
- describe('ProcedureValidationError narrowing', () => {
1297
- test('instanceof check works in onError', async () => {
1298
- let wasValidationError = false;
1299
- const builder = new HonoStreamAppBuilder({
1300
- onError: (procedure, c, error) => {
1301
- if (error instanceof ProcedureValidationError) {
1302
- wasValidationError = true;
1303
- return c.json({ validation: true, errors: error.errors }, 422);
1304
- }
1305
- return c.json({ error: error.message }, 500);
1306
- },
1307
- });
1308
- const RPC = Procedures();
1309
- RPC.CreateStream('Validated', {
1310
- scope: 'validated',
1311
- version: 1,
1312
- schema: { params: v.object({ count: v.number() }) },
1313
- }, async function* (ctx, params) {
1314
- yield { count: params.count };
1315
- });
1316
- builder.register(RPC, () => ({}));
1317
- const app = builder.build();
1318
- const res = await app.request('/validated/validated/1?count=not-a-number');
1319
- expect(res.status).toBe(422);
1320
- expect(wasValidationError).toBe(true);
1321
- const body = await res.json();
1322
- expect(body.validation).toBe(true);
1323
- expect(body.errors).toBeDefined();
1324
- });
1325
- });
1326
- // --------------------------------------------------------------------------
1327
- // Integration Test
1328
- // --------------------------------------------------------------------------
1329
- describe('integration', () => {
1330
- test('full workflow with streaming procedures', async () => {
1331
- const RPC = Procedures();
1332
- RPC.CreateStream('WatchNotifications', {
1333
- scope: ['user', 'notifications'],
1334
- version: 1,
1335
- schema: {
1336
- params: v.object({ limit: v.number() }),
1337
- yieldType: v.object({ id: v.number(), message: v.string() }),
1338
- },
1339
- }, async function* (ctx, params) {
1340
- const limit = params?.limit ?? 3;
1341
- for (let i = 1; i <= limit; i++) {
1342
- yield { id: i, message: `Notification ${i} for ${ctx.userId}` };
1343
- }
1344
- });
1345
- // Also create a non-streaming procedure to ensure it's filtered out
1346
- RPC.Create('GetNotificationCount', { scope: ['user', 'notifications'], version: 1 }, async () => ({
1347
- count: 10,
1348
- }));
1349
- const events = [];
1350
- const builder = new HonoStreamAppBuilder({
1351
- defaultStreamMode: 'text',
1352
- onRequestStart: () => events.push('request-start'),
1353
- onRequestEnd: () => events.push('request-end'),
1354
- onStreamStart: () => events.push('stream-start'),
1355
- onStreamEnd: () => events.push('stream-end'),
1356
- });
1357
- builder.register(RPC, (c) => ({
1358
- userId: c.req.header('x-user-id') || 'anonymous',
1359
- }));
1360
- const app = builder.build();
1361
- // Only streaming procedure should be registered
1362
- expect(builder.docs).toHaveLength(1);
1363
- expect(builder.docs[0].name).toBe('WatchNotifications');
1364
- expect(builder.docs[0].methods).toEqual(['post', 'get']);
1365
- // Test streaming
1366
- const res = await app.request('/user/notifications/watch-notifications/1?limit=2', {
1367
- headers: { 'X-User-Id': 'user-123' },
1368
- });
1369
- expect(res.status).toBe(200);
1370
- const text = await res.text();
1371
- const lines = text.trim().split('\n');
1372
- expect(lines).toHaveLength(2);
1373
- expect(JSON.parse(lines[0])).toEqual({ id: 1, message: 'Notification 1 for user-123' });
1374
- expect(JSON.parse(lines[1])).toEqual({ id: 2, message: 'Notification 2 for user-123' });
1375
- // Verify hooks were called
1376
- expect(events).toContain('request-start');
1377
- expect(events).toContain('stream-start');
1378
- expect(events).toContain('stream-end');
1379
- expect(events).toContain('request-end');
1380
- });
1381
- });
1382
- });
1383
- //# sourceMappingURL=index.test.js.map