@workerstack/clients 1.0.0-rc.28 → 1.0.0-rc.30

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 (368) hide show
  1. package/README.md +403 -21
  2. package/assets/installers/examples/github.config.ts +17 -19
  3. package/assets/installers/examples/goreleaser.config.ts +16 -18
  4. package/assets/installers/examples/raw.config.ts +13 -15
  5. package/bin/clients.js +87 -66
  6. package/bin/installgen.js +19 -10
  7. package/dist/cli.d.ts +4 -4
  8. package/dist/cli.js +18 -12
  9. package/dist/emit/cli/channels.d.ts +2 -2
  10. package/dist/emit/cli/channels.js +18 -13
  11. package/dist/emit/cli/commands.d.ts +1 -1
  12. package/dist/emit/cli/commands.js +39 -13
  13. package/dist/emit/cli/discovery.d.ts +0 -6
  14. package/dist/emit/cli/discovery.js +9 -7
  15. package/dist/emit/cli/flags.d.ts +1 -3
  16. package/dist/emit/cli/flags.js +18 -8
  17. package/dist/emit/cli/install.d.ts +0 -8
  18. package/dist/emit/cli/install.js +3 -3
  19. package/dist/emit/cli/layout.d.ts +1 -1
  20. package/dist/emit/cli/layout.js +13 -10
  21. package/dist/emit/cli/module.d.ts +6 -6
  22. package/dist/emit/cli/module.js +10 -10
  23. package/dist/emit/cli/release.d.ts +0 -11
  24. package/dist/emit/cli/release.js +4 -4
  25. package/dist/emit/cli/skills.js +8 -4
  26. package/dist/emit/csharp/errors.js +4 -4
  27. package/dist/emit/csharp/json.js +8 -8
  28. package/dist/emit/csharp/realtime.d.ts +1 -8
  29. package/dist/emit/csharp/realtime.js +26 -26
  30. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  31. package/dist/emit/csharp/sdk-answer.js +4 -4
  32. package/dist/emit/csharp/sdk-body.js +8 -6
  33. package/dist/emit/csharp/sdk-client.d.ts +3 -3
  34. package/dist/emit/csharp/sdk-client.js +2 -2
  35. package/dist/emit/csharp/sdk-csproj.d.ts +7 -9
  36. package/dist/emit/csharp/sdk-csproj.js +10 -10
  37. package/dist/emit/csharp/sdk-doc.js +1 -1
  38. package/dist/emit/csharp/sdk-method.d.ts +0 -1
  39. package/dist/emit/csharp/sdk-method.js +19 -8
  40. package/dist/emit/csharp/sdk-plan.js +0 -1
  41. package/dist/emit/csharp/sdk.js +3 -3
  42. package/dist/emit/csharp/sse.d.ts +0 -13
  43. package/dist/emit/csharp/sse.js +92 -11
  44. package/dist/emit/csharp/transport.js +9 -9
  45. package/dist/emit/csharp/types-enum.js +3 -1
  46. package/dist/emit/csharp/types-messages.d.ts +47 -0
  47. package/dist/emit/csharp/types-messages.js +172 -0
  48. package/dist/emit/csharp/types-names.js +13 -14
  49. package/dist/emit/csharp/types-record.js +3 -3
  50. package/dist/emit/csharp/types-union.d.ts +1 -1
  51. package/dist/emit/csharp/types.d.ts +0 -1
  52. package/dist/emit/csharp/types.js +3 -3
  53. package/dist/emit/csharp/ws.d.ts +0 -15
  54. package/dist/emit/csharp/ws.js +26 -5
  55. package/dist/emit/go/errors.js +1 -1
  56. package/dist/emit/go/http.js +2 -2
  57. package/dist/emit/go/module-path.js +2 -2
  58. package/dist/emit/go/sdk-answer.d.ts +24 -1
  59. package/dist/emit/go/sdk-answer.js +1 -1
  60. package/dist/emit/go/sdk-body.js +11 -7
  61. package/dist/emit/go/sdk-client.js +1 -1
  62. package/dist/emit/go/sdk-method.d.ts +3 -0
  63. package/dist/emit/go/sdk-method.js +18 -12
  64. package/dist/emit/go/sdk-mirror.js +2 -2
  65. package/dist/emit/go/sdk-opts.d.ts +0 -2
  66. package/dist/emit/go/sdk-opts.js +3 -3
  67. package/dist/emit/go/sdk.d.ts +1 -1
  68. package/dist/emit/go/sdk.js +9 -9
  69. package/dist/emit/go/sse.d.ts +2 -10
  70. package/dist/emit/go/sse.js +88 -13
  71. package/dist/emit/go/types-names.js +5 -0
  72. package/dist/emit/go/types-struct.d.ts +2 -1
  73. package/dist/emit/go/types-struct.js +1 -1
  74. package/dist/emit/go/types-union.d.ts +3 -2
  75. package/dist/emit/go/types-union.js +2 -0
  76. package/dist/emit/go/types.d.ts +6 -0
  77. package/dist/emit/go/types.js +20 -9
  78. package/dist/emit/go/ws.d.ts +4 -11
  79. package/dist/emit/go/ws.js +215 -59
  80. package/dist/emit/java/gradle.d.ts +7 -9
  81. package/dist/emit/java/gradle.js +8 -8
  82. package/dist/emit/java/json.d.ts +3 -0
  83. package/dist/emit/java/json.js +1 -1
  84. package/dist/emit/java/layout-ast.d.ts +4 -1
  85. package/dist/emit/java/layout-ast.js +1 -1
  86. package/dist/emit/java/layout-decl.js +5 -4
  87. package/dist/emit/java/layout-doc.js +13 -7
  88. package/dist/emit/java/layout-dot.js +1 -1
  89. package/dist/emit/java/layout-strings.js +4 -5
  90. package/dist/emit/java/layout-types.js +7 -5
  91. package/dist/emit/java/layout-visitor.js +4 -3
  92. package/dist/emit/java/layout.js +5 -4
  93. package/dist/emit/java/models-names.d.ts +2 -0
  94. package/dist/emit/java/models-names.js +6 -4
  95. package/dist/emit/java/models-record.d.ts +0 -1
  96. package/dist/emit/java/models-record.js +3 -3
  97. package/dist/emit/java/models-union.d.ts +13 -2
  98. package/dist/emit/java/models-union.js +12 -6
  99. package/dist/emit/java/models.d.ts +5 -1
  100. package/dist/emit/java/models.js +44 -20
  101. package/dist/emit/java/realtime.d.ts +34 -26
  102. package/dist/emit/java/realtime.js +45 -10
  103. package/dist/emit/java/sdk-client.d.ts +6 -6
  104. package/dist/emit/java/sdk-client.js +1 -1
  105. package/dist/emit/java/sdk-decl.js +2 -2
  106. package/dist/emit/java/sdk-errors.js +1 -1
  107. package/dist/emit/java/sdk-headers.js +2 -2
  108. package/dist/emit/java/sdk-mirror.js +7 -6
  109. package/dist/emit/java/sdk-models.d.ts +1 -1
  110. package/dist/emit/java/sdk-models.js +7 -7
  111. package/dist/emit/java/sdk-op.d.ts +1 -10
  112. package/dist/emit/java/sdk-op.js +9 -9
  113. package/dist/emit/java/sdk-params.d.ts +5 -5
  114. package/dist/emit/java/sdk-params.js +3 -2
  115. package/dist/emit/java/sdk-plan.js +0 -1
  116. package/dist/emit/java/sdk.d.ts +1 -1
  117. package/dist/emit/java/sdk.js +14 -13
  118. package/dist/emit/java/sse.d.ts +12 -13
  119. package/dist/emit/java/sse.js +105 -6
  120. package/dist/emit/java/ws.d.ts +48 -9
  121. package/dist/emit/java/ws.js +88 -4
  122. package/dist/emit/mcp/annotations.js +8 -4
  123. package/dist/emit/mcp/files.js +9 -9
  124. package/dist/emit/mcp/mounted.js +2 -2
  125. package/dist/emit/mcp/output-schema.d.ts +4 -2
  126. package/dist/emit/mcp/output-schema.js +58 -14
  127. package/dist/emit/mcp/registry.d.ts +0 -2
  128. package/dist/emit/mcp/registry.js +5 -4
  129. package/dist/emit/mcp/runtime.js +2 -2
  130. package/dist/emit/mcp/schema.js +22 -11
  131. package/dist/emit/mcp/server.d.ts +7 -7
  132. package/dist/emit/mcp/server.js +7 -6
  133. package/dist/emit/mcp/tools.js +7 -6
  134. package/dist/emit/python/errors.js +3 -3
  135. package/dist/emit/python/realtime.d.ts +9 -6
  136. package/dist/emit/python/realtime.js +22 -20
  137. package/dist/emit/python/sdk-answer.d.ts +8 -8
  138. package/dist/emit/python/sdk-answer.js +2 -2
  139. package/dist/emit/python/sdk-body.js +4 -5
  140. package/dist/emit/python/sdk-client.js +5 -5
  141. package/dist/emit/python/sdk-doc.js +2 -2
  142. package/dist/emit/python/sdk-method.d.ts +1 -1
  143. package/dist/emit/python/sdk-method.js +38 -11
  144. package/dist/emit/python/sdk-plan.js +0 -1
  145. package/dist/emit/python/sdk-pyproject.d.ts +0 -2
  146. package/dist/emit/python/sdk-pyproject.js +8 -8
  147. package/dist/emit/python/sdk.d.ts +1 -1
  148. package/dist/emit/python/sdk.js +28 -8
  149. package/dist/emit/python/sse.d.ts +0 -7
  150. package/dist/emit/python/sse.js +36 -6
  151. package/dist/emit/python/transport.js +4 -4
  152. package/dist/emit/python/types-dict.d.ts +2 -2
  153. package/dist/emit/python/types-dict.js +1 -1
  154. package/dist/emit/python/types-names.js +2 -2
  155. package/dist/emit/python/types-union.js +1 -1
  156. package/dist/emit/python/types.d.ts +7 -0
  157. package/dist/emit/python/types.js +23 -6
  158. package/dist/emit/python/ws.d.ts +21 -10
  159. package/dist/emit/python/ws.js +69 -3
  160. package/dist/emit/rust/errors.js +3 -3
  161. package/dist/emit/rust/http.js +4 -4
  162. package/dist/emit/rust/realtime.d.ts +7 -5
  163. package/dist/emit/rust/realtime.js +15 -18
  164. package/dist/emit/rust/sdk-body.js +8 -5
  165. package/dist/emit/rust/sdk-cargo.d.ts +16 -18
  166. package/dist/emit/rust/sdk-cargo.js +12 -12
  167. package/dist/emit/rust/sdk-client.d.ts +1 -1
  168. package/dist/emit/rust/sdk-client.js +3 -3
  169. package/dist/emit/rust/sdk-method.js +3 -3
  170. package/dist/emit/rust/sdk-opts.d.ts +2 -1
  171. package/dist/emit/rust/sdk-opts.js +2 -2
  172. package/dist/emit/rust/sdk-plan.js +0 -1
  173. package/dist/emit/rust/sdk.d.ts +1 -1
  174. package/dist/emit/rust/sdk.js +5 -5
  175. package/dist/emit/rust/sse.d.ts +11 -12
  176. package/dist/emit/rust/sse.js +54 -8
  177. package/dist/emit/rust/types-names.js +3 -3
  178. package/dist/emit/rust/types-struct.js +1 -1
  179. package/dist/emit/rust/types-union.d.ts +10 -2
  180. package/dist/emit/rust/types-union.js +4 -0
  181. package/dist/emit/rust/types.d.ts +9 -0
  182. package/dist/emit/rust/types.js +20 -12
  183. package/dist/emit/rust/ws.d.ts +22 -15
  184. package/dist/emit/rust/ws.js +60 -10
  185. package/dist/emit/shared/escape.js +17 -17
  186. package/dist/emit/shared/format.js +1 -1
  187. package/dist/emit/shared/gofmt.js +1 -1
  188. package/dist/emit/shared/lang.js +10 -10
  189. package/dist/emit/shared/literals.d.ts +5 -0
  190. package/dist/emit/shared/literals.js +8 -0
  191. package/dist/emit/shared/metadata.d.ts +0 -6
  192. package/dist/emit/shared/metadata.js +8 -7
  193. package/dist/emit/shared/ruff.js +1 -1
  194. package/dist/emit/shared/rustfmt.js +1 -1
  195. package/dist/emit/shared/type-emitter.js +37 -20
  196. package/dist/emit/shared/unknown-type.constants.d.ts +2 -0
  197. package/dist/emit/shared/unknown-type.constants.js +2 -0
  198. package/dist/emit/ts/http.d.ts +0 -2
  199. package/dist/emit/ts/http.js +4 -4
  200. package/dist/emit/ts/package.d.ts +14 -12
  201. package/dist/emit/ts/package.js +9 -8
  202. package/dist/emit/ts/route-tree.js +2 -2
  203. package/dist/emit/ts/sdk-types-preamble.d.ts +1 -1
  204. package/dist/emit/ts/sdk-types-preamble.js +6 -2
  205. package/dist/emit/ts/sdk-types.js +59 -20
  206. package/dist/emit/ts/sdk.js +6 -6
  207. package/dist/emit/ts/service-map.d.ts +10 -3
  208. package/dist/emit/ts/service-map.js +30 -2
  209. package/dist/emit/ts/tanstack-query.js +6 -6
  210. package/dist/emit/ts/type-gen.js +36 -21
  211. package/dist/emit/ts/webhooks.d.ts +0 -2
  212. package/dist/emit/ts/webhooks.js +3 -3
  213. package/dist/extract/chain.js +5 -4
  214. package/dist/extract/extract.js +5 -5
  215. package/dist/extract/serialize.d.ts +0 -2
  216. package/dist/extract/serialize.js +14 -15
  217. package/dist/extract/walk.js +15 -12
  218. package/dist/gen/args.js +9 -5
  219. package/dist/gen/formatters.js +5 -3
  220. package/dist/gen/shipped.js +2 -2
  221. package/dist/gen/targets.d.ts +2 -4
  222. package/dist/gen/targets.js +8 -4
  223. package/dist/gen/write.js +4 -2
  224. package/dist/index.js +2 -2
  225. package/dist/installers/cli.d.ts +4 -4
  226. package/dist/installers/cli.js +24 -24
  227. package/dist/installers/commands/build.d.ts +4 -4
  228. package/dist/installers/commands/build.js +2 -3
  229. package/dist/installers/commands/check.d.ts +2 -2
  230. package/dist/installers/commands/check.js +11 -10
  231. package/dist/installers/commands/init.d.ts +2 -2
  232. package/dist/installers/commands/init.js +1 -2
  233. package/dist/installers/config/define-config.d.ts +16 -16
  234. package/dist/installers/config/define-config.js +1 -1
  235. package/dist/installers/config/hooks/bun.d.ts +6 -6
  236. package/dist/installers/config/hooks/node.js +1 -1
  237. package/dist/installers/config/load.d.ts +6 -8
  238. package/dist/installers/config/load.js +7 -8
  239. package/dist/installers/config/resolve.d.ts +1 -2
  240. package/dist/installers/config/resolve.js +28 -33
  241. package/dist/installers/config/types.d.ts +6 -6
  242. package/dist/installers/config/types.js +0 -1
  243. package/dist/installers/render/quote.js +3 -5
  244. package/dist/installers/render/render.d.ts +6 -6
  245. package/dist/installers/render/render.js +26 -26
  246. package/dist/installers/ui.d.ts +4 -4
  247. package/dist/installers/ui.js +3 -3
  248. package/dist/ir/build.d.ts +3 -3
  249. package/dist/ir/build.js +12 -5
  250. package/dist/ir/load.js +9 -10
  251. package/dist/ir/model.d.ts +16 -1
  252. package/dist/ir/model.js +0 -1
  253. package/dist/ir/resolve-refs.js +2 -2
  254. package/dist/ir/resource-tree.js +2 -1
  255. package/dist/ir/route-tree-intern.js +1 -1
  256. package/dist/ir/schema.js +3 -3
  257. package/dist/ir/sdk-model.d.ts +25 -1
  258. package/dist/ir/sdk-model.js +38 -8
  259. package/dist/ir/slots.d.ts +1 -1
  260. package/dist/ir/slots.js +22 -11
  261. package/dist/ir/streams.d.ts +16 -0
  262. package/dist/ir/streams.js +40 -0
  263. package/dist/release/bootstrap.d.ts +3 -3
  264. package/dist/release/bootstrap.js +7 -7
  265. package/dist/release/bump-args.js +4 -4
  266. package/dist/release/bump-command.d.ts +1 -1
  267. package/dist/release/bump-command.js +9 -10
  268. package/dist/release/bump.d.ts +5 -4
  269. package/dist/release/bump.js +2 -2
  270. package/dist/release/cli.d.ts +4 -4
  271. package/dist/release/cli.js +4 -4
  272. package/dist/release/codegen.js +1 -1
  273. package/dist/release/digest.js +5 -7
  274. package/dist/release/git.js +5 -8
  275. package/dist/release/load.js +3 -3
  276. package/dist/release/manifest.js +9 -10
  277. package/dist/release/oasdiff.d.ts +10 -15
  278. package/dist/release/oasdiff.js +5 -6
  279. package/dist/release/registries.d.ts +0 -11
  280. package/dist/release/registries.js +17 -17
  281. package/dist/release/release-state.d.ts +16 -13
  282. package/dist/release/release-workflow.js +5 -7
  283. package/dist/release/repo-settings.d.ts +2 -1
  284. package/dist/release/spec-gate.d.ts +0 -2
  285. package/dist/release/spec-gate.js +6 -10
  286. package/dist/release/sync-command.d.ts +2 -2
  287. package/dist/release/sync-command.js +1 -1
  288. package/dist/release/sync-tree.js +9 -13
  289. package/dist/release/sync.d.ts +6 -6
  290. package/dist/release/sync.js +12 -13
  291. package/dist/release/types.d.ts +22 -22
  292. package/dist/release/types.js +0 -1
  293. package/dist/release/version-files.d.ts +3 -4
  294. package/dist/release/version-files.js +4 -5
  295. package/dist/runtime/.oxfmtrc.jsonc +8 -0
  296. package/dist/runtime/cli/socket.go +107 -13
  297. package/dist/runtime/cli/stream.go +18 -11
  298. package/dist/runtime/csharp/Adapters.cs +12 -11
  299. package/dist/runtime/csharp/Events.cs +22 -17
  300. package/dist/runtime/csharp/Realtime.cs +50 -23
  301. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  302. package/dist/runtime/csharp/TransportSse.cs +3 -3
  303. package/dist/runtime/csharp/Ws.cs +1 -1
  304. package/dist/runtime/csharp/WsDial.cs +19 -1
  305. package/dist/runtime/csharp/WsTyped.cs +109 -0
  306. package/dist/runtime/go/realtime.go +125 -41
  307. package/dist/runtime/go/realtime_loop.go +21 -18
  308. package/dist/runtime/go/result.go +2 -1
  309. package/dist/runtime/go/sse.go +11 -0
  310. package/dist/runtime/go/stream.go +29 -13
  311. package/dist/runtime/go/transport.go +15 -21
  312. package/dist/runtime/go/transport_longpoll.go +3 -4
  313. package/dist/runtime/go/transport_sse.go +6 -6
  314. package/dist/runtime/go/ws.go +157 -61
  315. package/dist/runtime/java/EventStream.java +47 -29
  316. package/dist/runtime/java/Exchange.java +5 -5
  317. package/dist/runtime/java/Flight.java +3 -3
  318. package/dist/runtime/java/Realtime.java +45 -11
  319. package/dist/runtime/java/ResumableConnection.java +77 -32
  320. package/dist/runtime/java/Socket.java +8 -4
  321. package/dist/runtime/java/SseAdapter.java +1 -1
  322. package/dist/runtime/java/TypedWebSocket.java +81 -24
  323. package/dist/runtime/java/WsAdapter.java +4 -2
  324. package/dist/runtime/java/WsDial.java +12 -5
  325. package/dist/runtime/mcp/files.ts +1 -1
  326. package/dist/runtime/mcp/http.ts +6 -2
  327. package/dist/runtime/mcp/listen.ts +1 -1
  328. package/dist/runtime/mcp/mount.ts +2 -2
  329. package/dist/runtime/mcp/protocol.ts +1 -1
  330. package/dist/runtime/python/events.py +25 -11
  331. package/dist/runtime/python/operation.py +6 -1
  332. package/dist/runtime/python/realtime.py +47 -33
  333. package/dist/runtime/python/send_async.py +1 -0
  334. package/dist/runtime/python/transport_sse.py +2 -2
  335. package/dist/runtime/python/transport_ws.py +1 -1
  336. package/dist/runtime/python/ws.py +100 -39
  337. package/dist/runtime/rust/events.rs +64 -41
  338. package/dist/runtime/rust/realtime.rs +80 -34
  339. package/dist/runtime/rust/realtime_loop.rs +37 -12
  340. package/dist/runtime/rust/sse.rs +3 -2
  341. package/dist/runtime/rust/transport_sse.rs +1 -1
  342. package/dist/runtime/rust/transport_ws.rs +3 -2
  343. package/dist/runtime/rust/ws.rs +122 -50
  344. package/dist/runtime/ts/realtime-connection.ts +22 -0
  345. package/dist/runtime/ts/realtime-transports.ts +13 -4
  346. package/dist/runtime/ts/realtime.ts +27 -3
  347. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  348. package/dist/runtime/ts/sdk-sse.ts +31 -14
  349. package/dist/runtime/ts/sdk-ws.ts +2 -1
  350. package/dist/runtime/ts/sdk.ts +9 -2
  351. package/dist/runtime/ts/sse.ts +8 -0
  352. package/dist/runtime/ts/ws.ts +88 -50
  353. package/dist/runtime/ts-tanstack-query/query.ts +0 -2
  354. package/package.json +12 -40
  355. package/dist/emit/cli/index.d.ts +0 -1
  356. package/dist/emit/cli/index.js +0 -1
  357. package/dist/emit/csharp/index.d.ts +0 -1
  358. package/dist/emit/csharp/index.js +0 -1
  359. package/dist/emit/go/index.d.ts +0 -1
  360. package/dist/emit/go/index.js +0 -1
  361. package/dist/emit/java/index.d.ts +0 -2
  362. package/dist/emit/java/index.js +0 -2
  363. package/dist/emit/mcp/index.d.ts +0 -3
  364. package/dist/emit/mcp/index.js +0 -3
  365. package/dist/emit/python/index.d.ts +0 -1
  366. package/dist/emit/python/index.js +0 -1
  367. package/dist/emit/rust/index.d.ts +0 -1
  368. package/dist/emit/rust/index.js +0 -1
@@ -40,15 +40,8 @@ public sealed class TransportOptions
40
40
  /// <summary>The first reconnect's base delay, doubled per attempt up to 30 s; an SSE <c>retry</c> replaces it.</summary>
41
41
  public TimeSpan ReconnectDelay { get; init; } = TimeSpan.FromSeconds(1);
42
42
 
43
- internal static TransportOptions Of(string? lastEventId, string? reconnectToken, IReadOnlyList<string>? protocols, int? maxReconnectAttempts, TimeSpan? reconnectDelay) =>
44
- new()
45
- {
46
- LastEventId = lastEventId,
47
- ReconnectToken = reconnectToken,
48
- Protocols = protocols ?? [],
49
- MaxReconnectAttempts = maxReconnectAttempts ?? 5,
50
- ReconnectDelay = reconnectDelay ?? TimeSpan.FromSeconds(1),
51
- };
43
+ /* the connection's own copy: it advances the cursor, never the caller's value */
44
+ internal TransportOptions Copy() => (TransportOptions)MemberwiseClone();
52
45
 
53
46
  /* past a message: its SSE id, else the payload's id or last_event_id (a string or an integer), and its reconnect_token */
54
47
  internal void Advance(string? id, JsonElement payload)
@@ -162,12 +155,20 @@ internal sealed class Dial(Transport client, Operation op, Call call)
162
155
 
163
156
  internal sealed partial class Transport
164
157
  {
165
- public async Task<ResumableConnection<T>> RealtimeAsync<T>(Operation op, Call call, TransportOptions options, JsonTypeInfo<T> info, CancellationToken cancellationToken)
158
+ /* a connection whose operation declares no messages: a message that is no JSON reads as a JSON string */
159
+ public Task<ResumableConnection<TIn, TOut>> RealtimeAsync<TIn, TOut>(Operation op, Call call, TransportOptions options, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, CancellationToken cancellationToken) =>
160
+ OpenRealtimeAsync(op, call, options, read, write, false, cancellationToken);
161
+
162
+ /* a connection whose operation declares its messages: a message that is no JSON throws */
163
+ public Task<ResumableConnection<TIn, TOut>> TypedRealtimeAsync<TIn, TOut>(Operation op, Call call, TransportOptions options, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, CancellationToken cancellationToken) =>
164
+ OpenRealtimeAsync(op, call, options, read, write, true, cancellationToken);
165
+
166
+ private async Task<ResumableConnection<TIn, TOut>> OpenRealtimeAsync<TIn, TOut>(Operation op, Call call, TransportOptions options, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, bool strict, CancellationToken cancellationToken)
166
167
  {
167
168
  var dial = new Dial(this, op, call);
168
169
  var url = dial.Url();
169
170
  cancellationToken.ThrowIfCancellationRequested();
170
- var connection = new ResumableConnection<T>(url.ToString(), [new WsAdapter(dial), new SseAdapter(dial), new LongPollAdapter(dial)], info, options);
171
+ var connection = new ResumableConnection<TIn, TOut>(url.ToString(), [new WsAdapter(dial), new SseAdapter(dial), new LongPollAdapter(dial)], read, write, options) { Strict = strict };
171
172
  using var bound = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
172
173
  bound.CancelAfter(RealtimeLoop.OpenLimit);
173
174
  try
@@ -10,21 +10,22 @@ using System.Threading.Tasks;
10
10
 
11
11
  namespace Http.Runtime;
12
12
 
13
- /// <summary>One server-sent event: its decoded data, its type, the stream's last event id when it came, and its <c>retry</c>.</summary>
13
+ /// <summary>One server-sent event: its data, its type, the stream's last event id when it came, and its <c>retry</c>.</summary>
14
14
  public sealed record SseEvent<T>(T Data, string? Event, string? Id, TimeSpan? Retry);
15
15
 
16
16
  /// <summary>
17
- /// An open event stream, read once by <c>await foreach</c>. No timeout bounds it. An event that does not decode, a
18
- /// cap or a failed read is thrown once and ends it. The method's token or the read's own token ends it with an
17
+ /// An open event stream, read once by <c>await foreach</c>, each event decoded whole into <typeparamref name="TEvent"/>:
18
+ /// an <see cref="SseEvent{T}"/>, or a named-event operation's own record. No timeout bounds it. An event that does not
19
+ /// decode, a cap or a failed read is thrown once and ends it. The method's token or the read's own token ends it with an
19
20
  /// OperationCanceledException; leaving the loop or <see cref="DisposeAsync"/> ends it quietly. Each end lets the
20
21
  /// connection go: dispose it, or read it to its end.
21
22
  /// </summary>
22
- public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDisposable
23
+ public sealed class EventStream<TEvent> : IAsyncEnumerable<TEvent>, IAsyncDisposable
23
24
  {
24
25
  private const int ReadBuffer = 65_536;
25
26
 
26
27
  private readonly HttpResponseMessage _response;
27
- private readonly Func<string, T> _decode;
28
+ private readonly Func<SseEvent<string>, TEvent> _decode;
28
29
  private readonly CancellationToken _call;
29
30
  private readonly CancellationTokenSource _end = new();
30
31
  private readonly CancellationTokenRegistration _registration;
@@ -36,19 +37,19 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
36
37
  private int _taken;
37
38
  private int _released;
38
39
 
39
- internal EventStream(HttpResponseMessage response, Func<string, T> decode, CancellationToken call)
40
+ internal EventStream(HttpResponseMessage response, Func<SseEvent<string>, TEvent> decode, CancellationToken call)
40
41
  {
41
42
  _response = response;
42
43
  _decode = decode;
43
44
  _call = call;
44
- _registration = call.Register(static stream => ((EventStream<T>)stream!).Release(), this);
45
+ _registration = call.Register(static stream => ((EventStream<TEvent>)stream!).Release(), this);
45
46
  }
46
47
 
47
- /// <summary>The id of the last event read, to resume from; empty before any.</summary>
48
+ /// <summary>The id of the last event read, to resume from, taken before the event decodes; empty before any.</summary>
48
49
  public string LastEventId { get; private set; } = "";
49
50
 
50
51
  /// <summary>The stream's events in order; a second enumeration throws InvalidOperationException.</summary>
51
- public IAsyncEnumerator<SseEvent<T>> GetAsyncEnumerator(CancellationToken cancellationToken = default) =>
52
+ public IAsyncEnumerator<TEvent> GetAsyncEnumerator(CancellationToken cancellationToken = default) =>
52
53
  Interlocked.Exchange(ref _taken, 1) == 0
53
54
  ? EventsAsync(cancellationToken)
54
55
  : throw new InvalidOperationException("an EventStream is read once");
@@ -71,7 +72,7 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
71
72
  }
72
73
  }
73
74
 
74
- private async IAsyncEnumerator<SseEvent<T>> EventsAsync(CancellationToken token)
75
+ private async IAsyncEnumerator<TEvent> EventsAsync(CancellationToken token)
75
76
  {
76
77
  using var read = CancellationTokenSource.CreateLinkedTokenSource(token, _end.Token);
77
78
  try
@@ -81,9 +82,8 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
81
82
  var cap = await PullAsync(token, read.Token).ConfigureAwait(false);
82
83
  foreach (var raw in _pending)
83
84
  {
84
- var data = _decode(raw.Data);
85
85
  LastEventId = raw.Id ?? "";
86
- yield return new SseEvent<T>(data, raw.Event, raw.Id, raw.Retry);
86
+ yield return _decode(new SseEvent<string>(raw.Data, raw.Event, raw.Id, raw.Retry));
87
87
  }
88
88
  _pending.Clear();
89
89
  if (cap is not null)
@@ -132,16 +132,21 @@ public sealed class EventStream<T> : IAsyncEnumerable<SseEvent<T>>, IAsyncDispos
132
132
 
133
133
  internal sealed partial class Transport
134
134
  {
135
- public async Task<EventStream<T>> EventsAsync<T>(Operation op, Call call, string? lastEventId, JsonTypeInfo<T> info, CancellationToken cancellationToken) =>
136
- new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), data => Event(data, info), cancellationToken);
135
+ public async Task<EventStream<SseEvent<T>>> EventsAsync<T>(Operation op, Call call, string? lastEventId, JsonTypeInfo<T> info, CancellationToken cancellationToken) =>
136
+ new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), e => new(EventData(e.Data, info), e.Event, e.Id, e.Retry), cancellationToken);
137
137
 
138
- public async Task<EventStream<string>> TextEventsAsync(Operation op, Call call, string? lastEventId, CancellationToken cancellationToken) =>
139
- new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), data => data, cancellationToken);
138
+ public async Task<EventStream<SseEvent<string>>> TextEventsAsync(Operation op, Call call, string? lastEventId, CancellationToken cancellationToken) =>
139
+ new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), e => e, cancellationToken);
140
+
141
+ /* a named-event operation's events, each decoded by its name through the context's options */
142
+ public async Task<EventStream<TEvent>> NamedEventsAsync<TEvent>(Operation op, Call call, string? lastEventId, Func<SseEvent<string>, JsonSerializerOptions, TEvent> named, CancellationToken cancellationToken) =>
143
+ new(await OpenedAsync(op, call, lastEventId, cancellationToken).ConfigureAwait(false), e => named(e, Json), cancellationToken);
140
144
 
141
145
  private Task<HttpResponseMessage> OpenedAsync(Operation op, Call call, string? lastEventId, CancellationToken cancellationToken) =>
142
146
  new Exchange(this, op, call with { Headers = [.. call.Headers, Arg.Text("Last-Event-ID", lastEventId)] }, stream: true).OpenAsync(cancellationToken);
143
147
 
144
- private static T Event<T>(string data, JsonTypeInfo<T> info)
148
+ /// <summary>An event's data decoded into <typeparamref name="T"/>; a misfit or null is a <see cref="DecodeException"/>.</summary>
149
+ internal static T EventData<T>(string data, JsonTypeInfo<T> info)
145
150
  {
146
151
  try
147
152
  {
@@ -23,24 +23,33 @@ public enum ConnectionState
23
23
 
24
24
  /// <summary>
25
25
  /// A connection over a chain of transports, tried in order, read by <c>await foreach</c>: each message decoded as
26
- /// <typeparamref name="T"/> (a message that does not decode throws once, the connection kept), the cursor in
27
- /// <see cref="Options"/> advanced past it. After a drop it reopens the chain from the cursor, backing off from the
28
- /// delay (an SSE <c>retry</c> first), doubling to 30 s, for up to <c>MaxReconnectAttempts</c> in a row; giving up
29
- /// throws the last failure once, and the enumeration then ends. Leaving a loop keeps the connection; a canceled read
30
- /// leaves it reconnecting. <see cref="CloseAsync"/> from any task ends a pending read with no message.
26
+ /// <typeparamref name="TIn"/>, what the server sends, the cursor in <see cref="Options"/> advanced past it first, and
27
+ /// <see cref="Message"/> fired before it is yielded; <see cref="SendAsync(TOut, CancellationToken)"/> sends the JSON
28
+ /// of a <typeparamref name="TOut"/>, what the server receives. A message that does not decode throws
29
+ /// <see cref="DecodeException"/> once and ends that enumeration, the connection kept, and a new <c>await foreach</c>
30
+ /// reads the next one; a connection of declared messages reads only JSON, any other reads a message that is no JSON
31
+ /// as a JSON string. After a drop it reopens the chain from the cursor, backing off from the delay (an SSE
32
+ /// <c>retry</c> first), doubling to 30 s, for up to <c>MaxReconnectAttempts</c> in a row; giving up throws the last
33
+ /// failure once, and the enumeration then ends. Leaving a loop keeps the connection; a canceled read leaves it
34
+ /// reconnecting. <see cref="CloseAsync"/> from any task ends a pending read with no message.
31
35
  /// </summary>
32
- public sealed class ResumableConnection<T> : IAsyncEnumerable<T>, IAsyncDisposable
36
+ public sealed class ResumableConnection<TIn, TOut> : IAsyncEnumerable<TIn>, IAsyncDisposable
33
37
  {
34
- private readonly JsonTypeInfo<T> _info;
38
+ private readonly JsonTypeInfo<TIn> _read;
39
+ private readonly JsonTypeInfo<TOut> _write;
35
40
  private readonly RealtimeLoop _loop;
36
41
 
37
- /// <summary>A connection to <paramref name="url"/> over <paramref name="adapters"/>, its messages read through <paramref name="info"/>; it opens at <see cref="ConnectAsync"/>.</summary>
38
- public ResumableConnection(string url, IReadOnlyList<ITransportAdapter> adapters, JsonTypeInfo<T> info, TransportOptions? options = null)
42
+ /// <summary>
43
+ /// A connection to <paramref name="url"/> over <paramref name="adapters"/>, its messages read through
44
+ /// <paramref name="read"/> and sent through <paramref name="write"/>; it opens at <see cref="ConnectAsync"/>.
45
+ /// </summary>
46
+ public ResumableConnection(string url, IReadOnlyList<ITransportAdapter> adapters, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, TransportOptions? options = null)
39
47
  {
40
48
  Url = url;
41
49
  Adapters = adapters;
42
50
  Options = options ?? new TransportOptions();
43
- _info = info;
51
+ _read = read;
52
+ _write = write;
44
53
  _loop = new RealtimeLoop(adapters, Options, url);
45
54
  }
46
55
 
@@ -59,60 +68,78 @@ public sealed class ResumableConnection<T> : IAsyncEnumerable<T>, IAsyncDisposab
59
68
  /// <summary>The transport that last opened; null after a drop, until the next open.</summary>
60
69
  public TransportKind? ProvenTransport => _loop.Proven;
61
70
 
71
+ /// <summary>Each message as it is decoded, before the enumeration yields it; a handler that throws is ignored.</summary>
72
+ public event Action<TIn>? Message;
73
+
74
+ /* the operation declares its messages: a message that is no JSON is no message */
75
+ internal bool Strict { get; init; }
76
+
62
77
  /// <summary>Opens the first adapter in order that opens; the last failure when none does.</summary>
63
78
  public Task ConnectAsync(CancellationToken cancellationToken = default) => _loop.ConnectAsync(cancellationToken);
64
79
 
65
80
  /// <summary>The messages in order; its token, once fired, leaves the connection reconnecting.</summary>
66
- public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default) => MessagesAsync(cancellationToken);
81
+ public IAsyncEnumerator<TIn> GetAsyncEnumerator(CancellationToken cancellationToken = default) => MessagesAsync(cancellationToken);
82
+
83
+ /// <summary>Sends <paramref name="value"/> as its JSON text over the open transport.</summary>
84
+ public Task SendAsync(TOut value, CancellationToken cancellationToken = default) =>
85
+ _loop.SendAsync(JsonSerializer.Serialize(value, _write), cancellationToken);
67
86
 
68
87
  /// <summary>Sends <paramref name="text"/> as it is over the open transport (an SSE or long-poll one POSTs it).</summary>
69
88
  public Task SendAsync(string text, CancellationToken cancellationToken = default) => _loop.SendAsync(text, cancellationToken);
70
89
 
71
- /// <summary>Sends <paramref name="value"/> as its JSON text.</summary>
72
- public Task SendAsync<TValue>(TValue value, JsonTypeInfo<TValue> info, CancellationToken cancellationToken = default) =>
73
- _loop.SendAsync(JsonSerializer.Serialize(value, info), cancellationToken);
74
-
75
90
  /// <summary>Closes the open transport and ends a pending read in any task with no message.</summary>
76
91
  public Task CloseAsync() => _loop.CloseAsync();
77
92
 
78
93
  /// <summary>Closes the connection, as <see cref="CloseAsync"/> does.</summary>
79
94
  public ValueTask DisposeAsync() => new(CloseAsync());
80
95
 
81
- internal ResumableConnection<T> Bound(CancellationToken call)
96
+ internal ResumableConnection<TIn, TOut> Bound(CancellationToken call)
82
97
  {
83
98
  _loop.Bind(call);
84
99
  return this;
85
100
  }
86
101
 
87
- private async IAsyncEnumerator<T> MessagesAsync(CancellationToken token)
102
+ private async IAsyncEnumerator<TIn> MessagesAsync(CancellationToken token)
88
103
  {
89
104
  while (await _loop.NextAsync(token).ConfigureAwait(false) is { } message)
90
105
  {
91
- yield return Deliver(message);
106
+ var value = Deliver(message);
107
+ TypedWebSocket.Fire(Message, value);
108
+ yield return value;
92
109
  }
93
110
  }
94
111
 
95
- /* the message as JSON, else as a JSON string of its text; the cursor advanced before it decodes */
96
- private T Deliver(TransportMessage message)
112
+ /* the message as JSON, else (unless strict) as a JSON string of its text; the cursor advanced before it decodes */
113
+ private TIn Deliver(TransportMessage message)
97
114
  {
98
- JsonElement payload;
115
+ JsonElement payload = default;
116
+ JsonException? malformed = null;
99
117
  try
100
118
  {
101
119
  using var document = JsonDocument.Parse(message.Text);
102
120
  payload = document.RootElement.Clone();
103
121
  }
122
+ catch (JsonException e) when (Strict)
123
+ {
124
+ malformed = e;
125
+ }
104
126
  catch (JsonException)
105
127
  {
106
128
  payload = JsonSerializer.SerializeToElement(message.Text, Arg.StringInfo);
107
129
  }
108
130
  Options.Advance(message.Id, payload);
131
+ if (malformed is not null)
132
+ {
133
+ throw new DecodeException($"realtime message is not valid JSON: {malformed.Message}", malformed);
134
+ }
135
+ var what = Strict ? "realtime message" : "a message";
109
136
  try
110
137
  {
111
- return JsonSerializer.Deserialize(payload, _info) ?? throw new DecodeException("a message does not decode: it is null");
138
+ return JsonSerializer.Deserialize(payload, _read) ?? throw new DecodeException($"{what} does not decode: it is null");
112
139
  }
113
140
  catch (JsonException e)
114
141
  {
115
- throw new DecodeException($"a message does not decode: {e.Message}", e);
142
+ throw new DecodeException($"{what} does not decode: {e.Message}", e);
116
143
  }
117
144
  }
118
145
  }
@@ -10,7 +10,7 @@ using System.Threading.Tasks;
10
10
 
11
11
  namespace Http.Runtime;
12
12
 
13
- /* ResumableConnection<T>'s loop (Python's realtime.py), its behavior documented there */
13
+ /* ResumableConnection<TIn, TOut>'s loop (Python's realtime.py), its behavior documented there */
14
14
  internal sealed class RealtimeLoop(IReadOnlyList<ITransportAdapter> adapters, TransportOptions options, string url)
15
15
  {
16
16
  public static readonly TimeSpan OpenLimit = TimeSpan.FromSeconds(30);
@@ -26,11 +26,11 @@ public sealed class SseAdapter : ITransportAdapter, IDialed
26
26
  var x = _dial.Stream(options);
27
27
  var live = await x.OpenAsync(cancellationToken).ConfigureAwait(false);
28
28
  _dial.Opened(x.Raw!);
29
- return new SseConnection(new EventStream<string>(live, data => data, CancellationToken.None), _dial);
29
+ return new SseConnection(new EventStream<SseEvent<string>>(live, e => e, CancellationToken.None), _dial);
30
30
  }
31
31
  }
32
32
 
33
- internal sealed class SseConnection(EventStream<string> stream, Dial dial) : ITransportConnection
33
+ internal sealed class SseConnection(EventStream<SseEvent<string>> stream, Dial dial) : ITransportConnection
34
34
  {
35
35
  private IAsyncEnumerator<SseEvent<string>>? _events;
36
36
 
@@ -38,7 +38,7 @@ internal sealed class SseConnection(EventStream<string> stream, Dial dial) : ITr
38
38
  public async Task<TransportMessage?> ReceiveAsync(CancellationToken cancellationToken)
39
39
  {
40
40
  _events ??= stream.GetAsyncEnumerator();
41
- using var ended = cancellationToken.Register(static stream => ((EventStream<string>)stream!).DisposeAsync(), stream);
41
+ using var ended = cancellationToken.Register(static stream => ((EventStream<SseEvent<string>>)stream!).DisposeAsync(), stream);
42
42
  if (!await _events.MoveNextAsync().ConfigureAwait(false))
43
43
  {
44
44
  cancellationToken.ThrowIfCancellationRequested();
@@ -283,7 +283,7 @@ public sealed class TypedWebSocket : IAsyncDisposable
283
283
  return reason[..end];
284
284
  }
285
285
 
286
- private static void Fire<T>(Action<T>? handlers, T value)
286
+ internal static void Fire<T>(Action<T>? handlers, T value)
287
287
  {
288
288
  foreach (var handler in handlers?.GetInvocationList() ?? [])
289
289
  {
@@ -2,12 +2,14 @@
2
2
  using System;
3
3
  using System.Collections.Generic;
4
4
  using System.IO;
5
+ using System.IO.Compression;
5
6
  using System.Linq;
6
7
  using System.Net;
7
8
  using System.Net.Http;
8
9
  using System.Net.WebSockets;
9
10
  using System.Security.Cryptography;
10
11
  using System.Text;
12
+ using System.Text.Json.Serialization.Metadata;
11
13
  using System.Threading;
12
14
  using System.Threading.Tasks;
13
15
 
@@ -18,6 +20,10 @@ internal sealed partial class Transport
18
20
  public async Task<TypedWebSocket> SocketAsync(Operation op, Call call, IReadOnlyList<string>? protocols, string? reconnectToken, CancellationToken cancellationToken) =>
19
21
  (await WsDial.DialAsync(this, new Exchange(this, op, call with { Query = [.. call.Query, Arg.Text("reconnect_token", reconnectToken)] }, stream: true), protocols ?? [], cancellationToken).ConfigureAwait(false))
20
22
  .Bound(cancellationToken);
23
+
24
+ /* a socket whose messages are declared: read as TIn, sent as TOut */
25
+ public async Task<TypedWebSocket<TIn, TOut>> TypedSocketAsync<TIn, TOut>(Operation op, Call call, IReadOnlyList<string>? protocols, string? reconnectToken, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write, CancellationToken cancellationToken) =>
26
+ new(await SocketAsync(op, call, protocols, reconnectToken, cancellationToken).ConfigureAwait(false), read, write);
21
27
  }
22
28
 
23
29
  internal static class WsDial
@@ -42,7 +48,7 @@ internal static class WsDial
42
48
  throw new ApiConnectionException($"the WebSocket handshake failed: {refusal}");
43
49
  }
44
50
  x.Raw?.Fill(101, headers, [], SocketUrl(url));
45
- var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
51
+ var stream = Connection(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false));
46
52
  var options = new WebSocketCreationOptions { SubProtocol = chosen, KeepAliveInterval = KeepAlive, KeepAliveTimeout = KeepAlive };
47
53
  return new TypedWebSocket(WebSocket.CreateFromStream(stream, options), chosen, response);
48
54
  }
@@ -53,6 +59,18 @@ internal static class WsDial
53
59
  }
54
60
  }
55
61
 
62
+ /*
63
+ * a 101's content is the connection, no coded body: a handler's decoder over it for a Content-Encoding is
64
+ * read-only, so the dial takes what lies beneath; .NET's deflate decoder exposes nothing beneath it
65
+ */
66
+ private static Stream Connection(Stream stream) => stream switch
67
+ {
68
+ GZipStream gzip => gzip.BaseStream,
69
+ BrotliStream brotli => brotli.BaseStream,
70
+ { CanWrite: false } => throw new ApiConnectionException("the WebSocket handshake failed: the handler decoded the 101's content, so the connection is read-only"),
71
+ _ => stream,
72
+ };
73
+
56
74
  private static Uri SocketUrl(Uri url) => new UriBuilder(url) { Scheme = url.Scheme == Uri.UriSchemeHttps ? "wss" : "ws" }.Uri;
57
75
 
58
76
  private static HttpRequestMessage Request(Uri url, Dictionary<string, string> headers, string key, IReadOnlyList<string> protocols)
@@ -0,0 +1,109 @@
1
+ // @generated by clients. DO NOT EDIT.
2
+ using System;
3
+ using System.Net.WebSockets;
4
+ using System.Text.Json;
5
+ using System.Text.Json.Serialization.Metadata;
6
+ using System.Threading;
7
+ using System.Threading.Tasks;
8
+
9
+ namespace Http.Runtime;
10
+
11
+ /// <summary>
12
+ /// An open WebSocket whose messages are declared: each read is the JSON of a <typeparamref name="TIn"/>, each
13
+ /// <see cref="SendAsync(TOut, CancellationToken)"/> the JSON of a <typeparamref name="TOut"/>, over the socket it
14
+ /// wraps, which ends, closes and caps as <see cref="TypedWebSocket"/> does. A frame that is no JSON, or JSON that is
15
+ /// no <typeparamref name="TIn"/>, throws <see cref="DecodeException"/> from <see cref="ReceiveAsync"/> and fires
16
+ /// <see cref="Error"/>, and the next read reads on.
17
+ /// </summary>
18
+ public sealed class TypedWebSocket<TIn, TOut> : IAsyncDisposable
19
+ {
20
+ private readonly TypedWebSocket _socket;
21
+ private readonly JsonTypeInfo<TIn> _read;
22
+ private readonly JsonTypeInfo<TOut> _write;
23
+
24
+ internal TypedWebSocket(TypedWebSocket socket, JsonTypeInfo<TIn> read, JsonTypeInfo<TOut> write)
25
+ {
26
+ _socket = socket;
27
+ _read = read;
28
+ _write = write;
29
+ socket.Error += e => TypedWebSocket.Fire(Error, e);
30
+ }
31
+
32
+ /// <summary>The subprotocol the server chose; null when it chose none.</summary>
33
+ public string? Subprotocol => _socket.Subprotocol;
34
+
35
+ /// <summary>The server's close frame, once it closed the socket.</summary>
36
+ public WsClose? ClosedBy => _socket.ClosedBy;
37
+
38
+ /// <summary>Each message as it is read and decoded; a handler that throws is ignored.</summary>
39
+ public event Action<TIn>? Message;
40
+
41
+ /// <summary>The socket's close, the server's or the client's own; a handler that throws is ignored.</summary>
42
+ public event Action<WsClose>? Closed
43
+ {
44
+ add => _socket.Closed += value;
45
+ remove => _socket.Closed -= value;
46
+ }
47
+
48
+ /// <summary>The failure that ended the socket, or a frame that does not decode; a handler that throws is ignored.</summary>
49
+ public event Action<Exception>? Error;
50
+
51
+ /// <summary>
52
+ /// The next message, decoded; once the socket ended, the default: null, or a <see cref="JsonElement"/> whose
53
+ /// <see cref="JsonElement.ValueKind"/> is <see cref="JsonValueKind.Undefined"/>. Its token, once fired, closes
54
+ /// the socket.
55
+ /// </summary>
56
+ public async Task<TIn?> ReceiveAsync(CancellationToken cancellationToken = default)
57
+ {
58
+ if (await _socket.ReceiveAsync(cancellationToken).ConfigureAwait(false) is not { } message)
59
+ {
60
+ return default;
61
+ }
62
+ var value = Decoded(message.Data);
63
+ TypedWebSocket.Fire(Message, value);
64
+ return value;
65
+ }
66
+
67
+ /// <summary>Sends <paramref name="value"/> as one text message of its JSON.</summary>
68
+ public Task SendAsync(TOut value, CancellationToken cancellationToken = default) =>
69
+ _socket.SendAsync(value, _write, cancellationToken);
70
+
71
+ /// <summary>Sends <paramref name="text"/> as one text message, as it is.</summary>
72
+ public Task SendAsync(string text, CancellationToken cancellationToken = default) =>
73
+ _socket.SendAsync(text, cancellationToken);
74
+
75
+ /// <summary>Closes the socket as <see cref="TypedWebSocket.CloseAsync"/> does.</summary>
76
+ public Task CloseAsync(WebSocketCloseStatus status = WebSocketCloseStatus.NormalClosure, string reason = "", CancellationToken cancellationToken = default) =>
77
+ _socket.CloseAsync(status, reason, cancellationToken);
78
+
79
+ /// <summary>Closes the socket with 1000, as <see cref="CloseAsync"/> does.</summary>
80
+ public ValueTask DisposeAsync() => _socket.DisposeAsync();
81
+
82
+ /* parsed first, so a frame that is no JSON is told from JSON that is no TIn; a null TIn is no message */
83
+ private TIn Decoded(byte[] data)
84
+ {
85
+ try
86
+ {
87
+ using var parsed = JsonDocument.Parse(data);
88
+ }
89
+ catch (JsonException e)
90
+ {
91
+ throw Failed($"WebSocket frame is not valid JSON: {e.Message}", e);
92
+ }
93
+ try
94
+ {
95
+ return JsonSerializer.Deserialize(data, _read) ?? throw Failed("WebSocket frame does not decode: it is null", null);
96
+ }
97
+ catch (JsonException e)
98
+ {
99
+ throw Failed($"WebSocket frame does not decode: {e.Message}", e);
100
+ }
101
+ }
102
+
103
+ private DecodeException Failed(string message, Exception? inner)
104
+ {
105
+ var error = new DecodeException(message, inner);
106
+ TypedWebSocket.Fire(Error, error);
107
+ return error;
108
+ }
109
+ }