@geekmidas/constructs 10.0.0-alpha.17 → 10.0.0-alpha.170

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 (485) hide show
  1. package/README.md +246 -158
  2. package/dist/Construct-127M7yrl.d.cts +231 -0
  3. package/dist/Construct-127M7yrl.d.cts.map +1 -0
  4. package/dist/Construct-BMk_CRSD.d.mts +231 -0
  5. package/dist/Construct-BMk_CRSD.d.mts.map +1 -0
  6. package/dist/{Construct-BeYVu_QF.mjs → Construct-CGuc_Ijk.mjs} +8 -9
  7. package/dist/Construct-CGuc_Ijk.mjs.map +1 -0
  8. package/dist/{Construct-DqdlARxq.cjs → Construct-DorKS0Ua.cjs} +8 -9
  9. package/dist/Construct-DorKS0Ua.cjs.map +1 -0
  10. package/dist/{Cron-l4Wlz6G9.d.mts → Cron-Ca_qHQu2.d.cts} +16 -9
  11. package/dist/Cron-Ca_qHQu2.d.cts.map +1 -0
  12. package/dist/{Cron-zsoSAwZo.d.cts → Cron-DPJiR7Lt.d.mts} +15 -8
  13. package/dist/Cron-DPJiR7Lt.d.mts.map +1 -0
  14. package/dist/CronBuilder-BC4za5Bx.d.mts +47 -0
  15. package/dist/CronBuilder-BC4za5Bx.d.mts.map +1 -0
  16. package/dist/{CronBuilder-D_0HNBTr.mjs → CronBuilder-BJ5LoadF.mjs} +28 -11
  17. package/dist/CronBuilder-BJ5LoadF.mjs.map +1 -0
  18. package/dist/{CronBuilder-BdnI6lxF.cjs → CronBuilder-B_NSP-Y5.cjs} +27 -10
  19. package/dist/CronBuilder-B_NSP-Y5.cjs.map +1 -0
  20. package/dist/CronBuilder-C3RrAF1-.d.cts +47 -0
  21. package/dist/CronBuilder-C3RrAF1-.d.cts.map +1 -0
  22. package/dist/Endpoint-52z1P0Ue.cjs +581 -0
  23. package/dist/Endpoint-52z1P0Ue.cjs.map +1 -0
  24. package/dist/{Endpoint-DBflWAe4.d.cts → Endpoint-BlIZLsBQ.d.cts} +101 -20
  25. package/dist/Endpoint-BlIZLsBQ.d.cts.map +1 -0
  26. package/dist/{Endpoint-oS-Fe3d_.d.mts → Endpoint-DC7mreOr.d.mts} +104 -23
  27. package/dist/Endpoint-DC7mreOr.d.mts.map +1 -0
  28. package/dist/Endpoint-sUOU7uLx.mjs +552 -0
  29. package/dist/Endpoint-sUOU7uLx.mjs.map +1 -0
  30. package/dist/{EndpointFactory-Bm3aKRdV.mjs → EndpointFactory-Bzi9Sl7r.mjs} +269 -53
  31. package/dist/EndpointFactory-Bzi9Sl7r.mjs.map +1 -0
  32. package/dist/{EndpointFactory-CLvWuHyt.cjs → EndpointFactory-Cf_Cs1ym.cjs} +309 -51
  33. package/dist/EndpointFactory-Cf_Cs1ym.cjs.map +1 -0
  34. package/dist/{index-Cc4kKPag.d.mts → EndpointFactory-DCmnCmkX.d.mts} +189 -106
  35. package/dist/EndpointFactory-DCmnCmkX.d.mts.map +1 -0
  36. package/dist/{index-C1ZwNOOk.d.cts → EndpointFactory-cVTb8kCc.d.cts} +187 -104
  37. package/dist/EndpointFactory-cVTb8kCc.d.cts.map +1 -0
  38. package/dist/Function-BIEsY0Hm.d.cts +76 -0
  39. package/dist/Function-BIEsY0Hm.d.cts.map +1 -0
  40. package/dist/Function-BKReud5p.d.mts +76 -0
  41. package/dist/Function-BKReud5p.d.mts.map +1 -0
  42. package/dist/{HonoEndpointAdaptor-92zavCsV.cjs → HonoEndpointAdaptor-BTbqfSaa.cjs} +115 -41
  43. package/dist/HonoEndpointAdaptor-BTbqfSaa.cjs.map +1 -0
  44. package/dist/{HonoEndpointAdaptor-yYaU7jVJ.mjs → HonoEndpointAdaptor-CBVey2cY.mjs} +112 -38
  45. package/dist/HonoEndpointAdaptor-CBVey2cY.mjs.map +1 -0
  46. package/dist/ObjectSubscriberBuilder-AwGKoUKy.d.mts +129 -0
  47. package/dist/ObjectSubscriberBuilder-AwGKoUKy.d.mts.map +1 -0
  48. package/dist/ObjectSubscriberBuilder-CB6imsX4.d.cts +129 -0
  49. package/dist/ObjectSubscriberBuilder-CB6imsX4.d.cts.map +1 -0
  50. package/dist/ProcessorBuilder-CeEZ2vCx.d.cts +216 -0
  51. package/dist/ProcessorBuilder-CeEZ2vCx.d.cts.map +1 -0
  52. package/dist/ProcessorBuilder-CwIlm75W.d.mts +216 -0
  53. package/dist/ProcessorBuilder-CwIlm75W.d.mts.map +1 -0
  54. package/dist/Queue-9Hh20ZCk.mjs +104 -0
  55. package/dist/Queue-9Hh20ZCk.mjs.map +1 -0
  56. package/dist/{Queue-D9X6OoON.d.mts → Queue-B8HGg439.d.mts} +42 -41
  57. package/dist/Queue-B8HGg439.d.mts.map +1 -0
  58. package/dist/{Queue-DYPB2KWL.d.cts → Queue-C4rijiM7.d.cts} +43 -42
  59. package/dist/Queue-C4rijiM7.d.cts.map +1 -0
  60. package/dist/Queue-W1wueijP.cjs +109 -0
  61. package/dist/Queue-W1wueijP.cjs.map +1 -0
  62. package/dist/QueueBuilder-BDcv9B71.cjs +135 -0
  63. package/dist/QueueBuilder-BDcv9B71.cjs.map +1 -0
  64. package/dist/QueueBuilder-CUERv8jt.d.mts +75 -0
  65. package/dist/QueueBuilder-CUERv8jt.d.mts.map +1 -0
  66. package/dist/QueueBuilder-CmB1vOgn.d.cts +75 -0
  67. package/dist/QueueBuilder-CmB1vOgn.d.cts.map +1 -0
  68. package/dist/QueueBuilder-CrZL8HHs.mjs +118 -0
  69. package/dist/QueueBuilder-CrZL8HHs.mjs.map +1 -0
  70. package/dist/Subscriber-5rCX1Nph.d.cts +83 -0
  71. package/dist/Subscriber-5rCX1Nph.d.cts.map +1 -0
  72. package/dist/Subscriber-CtQXhcL7.d.mts +83 -0
  73. package/dist/Subscriber-CtQXhcL7.d.mts.map +1 -0
  74. package/dist/SubscriberBuilder-CpFhShTJ.mjs +238 -0
  75. package/dist/SubscriberBuilder-CpFhShTJ.mjs.map +1 -0
  76. package/dist/SubscriberBuilder-DJEvNRdD.cjs +261 -0
  77. package/dist/SubscriberBuilder-DJEvNRdD.cjs.map +1 -0
  78. package/dist/Topic-BGoOeCT6.mjs +99 -0
  79. package/dist/Topic-BGoOeCT6.mjs.map +1 -0
  80. package/dist/Topic-DLCZBNwK.cjs +104 -0
  81. package/dist/Topic-DLCZBNwK.cjs.map +1 -0
  82. package/dist/adaptors/aws.cjs +147 -168
  83. package/dist/adaptors/aws.cjs.map +1 -1
  84. package/dist/adaptors/aws.d.cts +57 -48
  85. package/dist/adaptors/aws.d.cts.map +1 -1
  86. package/dist/adaptors/aws.d.mts +58 -49
  87. package/dist/adaptors/aws.d.mts.map +1 -1
  88. package/dist/adaptors/aws.mjs +142 -164
  89. package/dist/adaptors/aws.mjs.map +1 -1
  90. package/dist/adaptors/awsWebsocket.cjs +354 -0
  91. package/dist/adaptors/awsWebsocket.cjs.map +1 -0
  92. package/dist/adaptors/awsWebsocket.d.cts +156 -0
  93. package/dist/adaptors/awsWebsocket.d.cts.map +1 -0
  94. package/dist/adaptors/awsWebsocket.d.mts +156 -0
  95. package/dist/adaptors/awsWebsocket.d.mts.map +1 -0
  96. package/dist/adaptors/awsWebsocket.mjs +347 -0
  97. package/dist/adaptors/awsWebsocket.mjs.map +1 -0
  98. package/dist/adaptors/hono.cjs +1 -1
  99. package/dist/adaptors/hono.d.cts +8 -7
  100. package/dist/adaptors/hono.d.cts.map +1 -1
  101. package/dist/adaptors/hono.d.mts +10 -9
  102. package/dist/adaptors/hono.d.mts.map +1 -1
  103. package/dist/adaptors/hono.mjs +1 -1
  104. package/dist/adaptors/testing.cjs +1174 -41
  105. package/dist/adaptors/testing.cjs.map +1 -1
  106. package/dist/adaptors/testing.d.cts +517 -40
  107. package/dist/adaptors/testing.d.cts.map +1 -1
  108. package/dist/adaptors/testing.d.mts +517 -40
  109. package/dist/adaptors/testing.d.mts.map +1 -1
  110. package/dist/adaptors/testing.mjs +1140 -36
  111. package/dist/adaptors/testing.mjs.map +1 -1
  112. package/dist/auth-1yI2wR-4.d.cts +274 -0
  113. package/dist/auth-1yI2wR-4.d.cts.map +1 -0
  114. package/dist/auth-D4NMXgLt.d.mts +274 -0
  115. package/dist/auth-D4NMXgLt.d.mts.map +1 -0
  116. package/dist/auth.cjs +311 -26
  117. package/dist/auth.cjs.map +1 -1
  118. package/dist/auth.d.cts +2 -104
  119. package/dist/auth.d.mts +2 -104
  120. package/dist/auth.mjs +307 -28
  121. package/dist/auth.mjs.map +1 -1
  122. package/dist/cache-0VoeOTF9.d.mts +44 -0
  123. package/dist/cache-0VoeOTF9.d.mts.map +1 -0
  124. package/dist/cache-CW-sArzS.d.cts +44 -0
  125. package/dist/cache-CW-sArzS.d.cts.map +1 -0
  126. package/dist/cache.cjs +4 -20
  127. package/dist/cache.cjs.map +1 -1
  128. package/dist/cache.d.cts +2 -43
  129. package/dist/cache.d.mts +2 -43
  130. package/dist/cache.mjs +4 -20
  131. package/dist/cache.mjs.map +1 -1
  132. package/dist/cipher-C1lEFX63.mjs +225 -0
  133. package/dist/cipher-C1lEFX63.mjs.map +1 -0
  134. package/dist/cipher-CVxfwLjk.cjs +332 -0
  135. package/dist/cipher-CVxfwLjk.cjs.map +1 -0
  136. package/dist/cipher-DSDxPRIp.d.cts +106 -0
  137. package/dist/cipher-DSDxPRIp.d.cts.map +1 -0
  138. package/dist/cipher-DSDxPRIp.d.mts +106 -0
  139. package/dist/cipher-DSDxPRIp.d.mts.map +1 -0
  140. package/dist/{construct-interface-DPlxfpoS.d.mts → construct-interface-DhbaONW2.d.cts} +63 -8
  141. package/dist/construct-interface-DhbaONW2.d.cts.map +1 -0
  142. package/dist/{construct-interface-DgXTJcOD.d.cts → construct-interface-DxfkFxkl.d.mts} +63 -8
  143. package/dist/construct-interface-DxfkFxkl.d.mts.map +1 -0
  144. package/dist/construct-interface.cjs +47 -4
  145. package/dist/construct-interface.cjs.map +1 -1
  146. package/dist/construct-interface.d.cts +2 -2
  147. package/dist/construct-interface.d.mts +2 -2
  148. package/dist/construct-interface.mjs +45 -5
  149. package/dist/construct-interface.mjs.map +1 -1
  150. package/dist/credential-B80mOxwT.mjs +222 -0
  151. package/dist/credential-B80mOxwT.mjs.map +1 -0
  152. package/dist/credential-RlgbzZAc.cjs +257 -0
  153. package/dist/credential-RlgbzZAc.cjs.map +1 -0
  154. package/dist/credential.cjs +7 -129
  155. package/dist/credential.d.cts +2 -58
  156. package/dist/credential.d.mts +2 -58
  157. package/dist/credential.mjs +2 -128
  158. package/dist/crons/index.cjs +127 -1
  159. package/dist/crons/index.cjs.map +1 -1
  160. package/dist/crons/index.d.cts +43 -3
  161. package/dist/crons/index.d.cts.map +1 -1
  162. package/dist/crons/index.d.mts +43 -3
  163. package/dist/crons/index.d.mts.map +1 -1
  164. package/dist/crons/index.mjs +126 -2
  165. package/dist/crons/index.mjs.map +1 -1
  166. package/dist/database/kysely.cjs +3 -194
  167. package/dist/database/kysely.d.cts +2 -149
  168. package/dist/database/kysely.d.mts +2 -149
  169. package/dist/database/kysely.mjs +2 -192
  170. package/dist/email.cjs +24 -17
  171. package/dist/email.cjs.map +1 -1
  172. package/dist/email.d.cts +15 -5
  173. package/dist/email.d.cts.map +1 -1
  174. package/dist/email.d.mts +16 -6
  175. package/dist/email.d.mts.map +1 -1
  176. package/dist/email.mjs +23 -17
  177. package/dist/email.mjs.map +1 -1
  178. package/dist/encryption/kms.cjs +95 -0
  179. package/dist/encryption/kms.cjs.map +1 -0
  180. package/dist/encryption/kms.d.cts +7 -0
  181. package/dist/encryption/kms.d.cts.map +1 -0
  182. package/dist/encryption/kms.d.mts +7 -0
  183. package/dist/encryption/kms.d.mts.map +1 -0
  184. package/dist/encryption/kms.mjs +93 -0
  185. package/dist/encryption/kms.mjs.map +1 -0
  186. package/dist/encryption.cjs +116 -0
  187. package/dist/encryption.cjs.map +1 -0
  188. package/dist/encryption.d.cts +37 -0
  189. package/dist/encryption.d.cts.map +1 -0
  190. package/dist/encryption.d.mts +37 -0
  191. package/dist/encryption.d.mts.map +1 -0
  192. package/dist/encryption.mjs +101 -0
  193. package/dist/encryption.mjs.map +1 -0
  194. package/dist/endpoints/index.cjs +32 -10
  195. package/dist/endpoints/index.d.cts +106 -3
  196. package/dist/endpoints/index.d.cts.map +1 -0
  197. package/dist/endpoints/index.d.mts +106 -3
  198. package/dist/endpoints/index.d.mts.map +1 -0
  199. package/dist/endpoints/index.mjs +6 -4
  200. package/dist/expire-C586zznE.d.cts +38 -0
  201. package/dist/expire-C586zznE.d.cts.map +1 -0
  202. package/dist/expire-C586zznE.d.mts +38 -0
  203. package/dist/expire-C586zznE.d.mts.map +1 -0
  204. package/dist/expire-CieftS01.cjs +67 -0
  205. package/dist/expire-CieftS01.cjs.map +1 -0
  206. package/dist/expire-CpzUAfr9.mjs +50 -0
  207. package/dist/expire-CpzUAfr9.mjs.map +1 -0
  208. package/dist/external-api.cjs +106 -0
  209. package/dist/external-api.cjs.map +1 -0
  210. package/dist/external-api.d.cts +2 -0
  211. package/dist/external-api.d.mts +2 -0
  212. package/dist/external-api.mjs +103 -0
  213. package/dist/external-api.mjs.map +1 -0
  214. package/dist/fake-BvOXkZmj.d.mts +201 -0
  215. package/dist/fake-BvOXkZmj.d.mts.map +1 -0
  216. package/dist/fake-Djx8E0o1.d.cts +201 -0
  217. package/dist/fake-Djx8E0o1.d.cts.map +1 -0
  218. package/dist/file-server.cjs +200 -48
  219. package/dist/file-server.cjs.map +1 -1
  220. package/dist/file-server.d.cts +147 -15
  221. package/dist/file-server.d.cts.map +1 -1
  222. package/dist/file-server.d.mts +147 -15
  223. package/dist/file-server.d.mts.map +1 -1
  224. package/dist/file-server.mjs +198 -50
  225. package/dist/file-server.mjs.map +1 -1
  226. package/dist/functions/index.cjs +1 -1
  227. package/dist/functions/index.d.cts +2 -1
  228. package/dist/functions/index.d.mts +2 -1
  229. package/dist/functions/index.mjs +1 -1
  230. package/dist/{functions-C53GW2eQ.mjs → functions-BvIDQKAA.mjs} +117 -22
  231. package/dist/functions-BvIDQKAA.mjs.map +1 -0
  232. package/dist/{functions-B6qCvfmy.cjs → functions-DLF6-IK8.cjs} +122 -18
  233. package/dist/functions-DLF6-IK8.cjs.map +1 -0
  234. package/dist/inbox-BjvMs7EJ.d.cts +195 -0
  235. package/dist/inbox-BjvMs7EJ.d.cts.map +1 -0
  236. package/dist/inbox-C8bOR9UL.d.mts +195 -0
  237. package/dist/inbox-C8bOR9UL.d.mts.map +1 -0
  238. package/dist/inbox.cjs +291 -0
  239. package/dist/inbox.cjs.map +1 -0
  240. package/dist/inbox.d.cts +2 -0
  241. package/dist/inbox.d.mts +2 -0
  242. package/dist/inbox.mjs +283 -0
  243. package/dist/inbox.mjs.map +1 -0
  244. package/dist/index-DaK-C7N3.d.cts +115 -0
  245. package/dist/index-DaK-C7N3.d.cts.map +1 -0
  246. package/dist/{index-CeEtxDmK.d.cts → index-DdRjYhiJ.d.cts} +42 -2
  247. package/dist/{index-CeEtxDmK.d.cts.map → index-DdRjYhiJ.d.cts.map} +1 -1
  248. package/dist/{index-CeEtxDmK.d.mts → index-DdRjYhiJ.d.mts} +42 -2
  249. package/dist/{index-CeEtxDmK.d.mts.map → index-DdRjYhiJ.d.mts.map} +1 -1
  250. package/dist/index-vCS4HBEG.d.mts +115 -0
  251. package/dist/index-vCS4HBEG.d.mts.map +1 -0
  252. package/dist/index.cjs +4 -1
  253. package/dist/index.d.cts +26 -3
  254. package/dist/index.d.cts.map +1 -0
  255. package/dist/index.d.mts +26 -3
  256. package/dist/index.d.mts.map +1 -0
  257. package/dist/index.mjs +3 -2
  258. package/dist/kysely-2HqIQ2fC.d.cts +216 -0
  259. package/dist/kysely-2HqIQ2fC.d.cts.map +1 -0
  260. package/dist/kysely-BGvpd_ZH.d.mts +216 -0
  261. package/dist/kysely-BGvpd_ZH.d.mts.map +1 -0
  262. package/dist/kysely-Bc9xzaik.mjs +371 -0
  263. package/dist/kysely-Bc9xzaik.mjs.map +1 -0
  264. package/dist/kysely-D7f6J2lh.cjs +384 -0
  265. package/dist/kysely-D7f6J2lh.cjs.map +1 -0
  266. package/dist/{telemetry-DGcFlVpB.d.cts → lambdaTelemetry-8vnmVZQ5.d.cts} +2 -2
  267. package/dist/lambdaTelemetry-8vnmVZQ5.d.cts.map +1 -0
  268. package/dist/{telemetry-DGcFlVpB.d.mts → lambdaTelemetry-8vnmVZQ5.d.mts} +2 -2
  269. package/dist/lambdaTelemetry-8vnmVZQ5.d.mts.map +1 -0
  270. package/dist/mobile-app.cjs +78 -0
  271. package/dist/mobile-app.cjs.map +1 -0
  272. package/dist/mobile-app.d.cts +77 -0
  273. package/dist/mobile-app.d.cts.map +1 -0
  274. package/dist/mobile-app.d.mts +77 -0
  275. package/dist/mobile-app.d.mts.map +1 -0
  276. package/dist/mobile-app.mjs +77 -0
  277. package/dist/mobile-app.mjs.map +1 -0
  278. package/dist/object-storage.cjs +14 -7
  279. package/dist/object-storage.cjs.map +1 -1
  280. package/dist/object-storage.d.cts +12 -3
  281. package/dist/object-storage.d.cts.map +1 -1
  282. package/dist/object-storage.d.mts +12 -3
  283. package/dist/object-storage.d.mts.map +1 -1
  284. package/dist/object-storage.mjs +14 -9
  285. package/dist/object-storage.mjs.map +1 -1
  286. package/dist/optionalPeers-D7Wt6dnF.mjs +140 -0
  287. package/dist/optionalPeers-D7Wt6dnF.mjs.map +1 -0
  288. package/dist/optionalPeers-DuNQXXe1.cjs +223 -0
  289. package/dist/optionalPeers-DuNQXXe1.cjs.map +1 -0
  290. package/dist/origins-BjxYht13.cjs +96 -0
  291. package/dist/origins-BjxYht13.cjs.map +1 -0
  292. package/dist/origins-Boc9qbo-.mjs +73 -0
  293. package/dist/origins-Boc9qbo-.mjs.map +1 -0
  294. package/dist/pattern-C1CEcglD.mjs +241 -0
  295. package/dist/pattern-C1CEcglD.mjs.map +1 -0
  296. package/dist/pattern-QFaUIr77.cjs +288 -0
  297. package/dist/pattern-QFaUIr77.cjs.map +1 -0
  298. package/dist/privateAddress-Bg5fUsbp.mjs +21 -0
  299. package/dist/privateAddress-Bg5fUsbp.mjs.map +1 -0
  300. package/dist/privateAddress-CqGyuFHn.cjs +26 -0
  301. package/dist/privateAddress-CqGyuFHn.cjs.map +1 -0
  302. package/dist/processors/index.cjs +214 -0
  303. package/dist/processors/index.cjs.map +1 -0
  304. package/dist/processors/index.d.cts +78 -0
  305. package/dist/processors/index.d.cts.map +1 -0
  306. package/dist/processors/index.d.mts +78 -0
  307. package/dist/processors/index.d.mts.map +1 -0
  308. package/dist/processors/index.mjs +193 -0
  309. package/dist/processors/index.mjs.map +1 -0
  310. package/dist/queue/index.cjs +5 -192
  311. package/dist/queue/index.d.cts +3 -53
  312. package/dist/queue/index.d.mts +3 -53
  313. package/dist/queue/index.mjs +3 -190
  314. package/dist/random-password.cjs +86 -0
  315. package/dist/random-password.cjs.map +1 -0
  316. package/dist/random-password.d.cts +30 -0
  317. package/dist/random-password.d.cts.map +1 -0
  318. package/dist/random-password.d.mts +30 -0
  319. package/dist/random-password.d.mts.map +1 -0
  320. package/dist/random-password.mjs +84 -0
  321. package/dist/random-password.mjs.map +1 -0
  322. package/dist/readRequestBody-BmKnPl0a.mjs +293 -0
  323. package/dist/readRequestBody-BmKnPl0a.mjs.map +1 -0
  324. package/dist/{lazyAccessors-Dx9NLwJZ.cjs → readRequestBody-CN9GVdeE.cjs} +141 -47
  325. package/dist/readRequestBody-CN9GVdeE.cjs.map +1 -0
  326. package/dist/{processAudits-D_2W5x8k.cjs → requestLogger-CnoYd-Ah.cjs} +63 -3
  327. package/dist/requestLogger-CnoYd-Ah.cjs.map +1 -0
  328. package/dist/{processAudits-BpRlPQMW.mjs → requestLogger-D2JS7pPM.mjs} +51 -3
  329. package/dist/requestLogger-D2JS7pPM.mjs.map +1 -0
  330. package/dist/rest-api.cjs +100 -73
  331. package/dist/rest-api.cjs.map +1 -1
  332. package/dist/rest-api.d.cts +83 -59
  333. package/dist/rest-api.d.cts.map +1 -1
  334. package/dist/rest-api.d.mts +83 -59
  335. package/dist/rest-api.d.mts.map +1 -1
  336. package/dist/rest-api.mjs +97 -76
  337. package/dist/rest-api.mjs.map +1 -1
  338. package/dist/runSubscriber-HEqXkin1.mjs +117 -0
  339. package/dist/runSubscriber-HEqXkin1.mjs.map +1 -0
  340. package/dist/runSubscriber-sVJfLA0-.cjs +134 -0
  341. package/dist/runSubscriber-sVJfLA0-.cjs.map +1 -0
  342. package/dist/shutdown-BMJmAhSt.cjs +38 -0
  343. package/dist/shutdown-BMJmAhSt.cjs.map +1 -0
  344. package/dist/shutdown-C7xa8x9S.mjs +27 -0
  345. package/dist/shutdown-C7xa8x9S.mjs.map +1 -0
  346. package/dist/site.cjs +137 -10
  347. package/dist/site.cjs.map +1 -1
  348. package/dist/site.d.cts +153 -3
  349. package/dist/site.d.cts.map +1 -1
  350. package/dist/site.d.mts +153 -3
  351. package/dist/site.d.mts.map +1 -1
  352. package/dist/site.mjs +117 -13
  353. package/dist/site.mjs.map +1 -1
  354. package/dist/stages-DaTaoQei.d.cts +73 -0
  355. package/dist/stages-DaTaoQei.d.cts.map +1 -0
  356. package/dist/stages-DaTaoQei.d.mts +73 -0
  357. package/dist/stages-DaTaoQei.d.mts.map +1 -0
  358. package/dist/subscribers/index.cjs +134 -1
  359. package/dist/subscribers/index.cjs.map +1 -0
  360. package/dist/subscribers/index.d.cts +74 -3
  361. package/dist/subscribers/index.d.cts.map +1 -0
  362. package/dist/subscribers/index.d.mts +74 -3
  363. package/dist/subscribers/index.d.mts.map +1 -0
  364. package/dist/subscribers/index.mjs +132 -2
  365. package/dist/subscribers/index.mjs.map +1 -0
  366. package/dist/telemetry-BirKau0X.d.mts +40 -0
  367. package/dist/telemetry-BirKau0X.d.mts.map +1 -0
  368. package/dist/telemetry-DjJgtQ_N.d.cts +40 -0
  369. package/dist/telemetry-DjJgtQ_N.d.cts.map +1 -0
  370. package/dist/telemetry.cjs +56 -0
  371. package/dist/telemetry.cjs.map +1 -0
  372. package/dist/telemetry.d.cts +2 -0
  373. package/dist/telemetry.d.mts +2 -0
  374. package/dist/telemetry.mjs +55 -0
  375. package/dist/telemetry.mjs.map +1 -0
  376. package/dist/topic/index.cjs +2 -134
  377. package/dist/topic/index.d.cts +2 -3
  378. package/dist/topic/index.d.mts +2 -3
  379. package/dist/topic/index.mjs +2 -132
  380. package/dist/tracing-Bbj1uoFJ.mjs +127 -0
  381. package/dist/tracing-Bbj1uoFJ.mjs.map +1 -0
  382. package/dist/tracing-C0ooU0V2.cjs +150 -0
  383. package/dist/tracing-C0ooU0V2.cjs.map +1 -0
  384. package/dist/websocket-api-C6LGg9-D.mjs +1716 -0
  385. package/dist/websocket-api-C6LGg9-D.mjs.map +1 -0
  386. package/dist/websocket-api-CD-E5Ogr.d.cts +1207 -0
  387. package/dist/websocket-api-CD-E5Ogr.d.cts.map +1 -0
  388. package/dist/websocket-api-CoKPJJRl.cjs +1895 -0
  389. package/dist/websocket-api-CoKPJJRl.cjs.map +1 -0
  390. package/dist/websocket-api-pJJfeTcm.d.mts +1207 -0
  391. package/dist/websocket-api-pJJfeTcm.d.mts.map +1 -0
  392. package/dist/websocket-api.cjs +42 -0
  393. package/dist/websocket-api.d.cts +2 -0
  394. package/dist/websocket-api.d.mts +2 -0
  395. package/dist/websocket-api.mjs +3 -0
  396. package/dist/worker.cjs +174 -32
  397. package/dist/worker.cjs.map +1 -1
  398. package/dist/worker.d.cts +147 -47
  399. package/dist/worker.d.cts.map +1 -1
  400. package/dist/worker.d.mts +147 -47
  401. package/dist/worker.d.mts.map +1 -1
  402. package/dist/worker.mjs +175 -33
  403. package/dist/worker.mjs.map +1 -1
  404. package/package.json +180 -43
  405. package/dist/Construct-BeYVu_QF.mjs.map +0 -1
  406. package/dist/Construct-DfbwIntp.d.cts +0 -115
  407. package/dist/Construct-DfbwIntp.d.cts.map +0 -1
  408. package/dist/Construct-DqdlARxq.cjs.map +0 -1
  409. package/dist/Construct-l5aOn_jv.d.mts +0 -115
  410. package/dist/Construct-l5aOn_jv.d.mts.map +0 -1
  411. package/dist/Cron-l4Wlz6G9.d.mts.map +0 -1
  412. package/dist/Cron-zsoSAwZo.d.cts.map +0 -1
  413. package/dist/CronBuilder-BdnI6lxF.cjs.map +0 -1
  414. package/dist/CronBuilder-CyT71Nzg.d.cts +0 -41
  415. package/dist/CronBuilder-CyT71Nzg.d.cts.map +0 -1
  416. package/dist/CronBuilder-D_0HNBTr.mjs.map +0 -1
  417. package/dist/CronBuilder-UoNgFe8S.d.mts +0 -41
  418. package/dist/CronBuilder-UoNgFe8S.d.mts.map +0 -1
  419. package/dist/Endpoint-BpZHtJ2W.cjs +0 -1689
  420. package/dist/Endpoint-BpZHtJ2W.cjs.map +0 -1
  421. package/dist/Endpoint-DBflWAe4.d.cts.map +0 -1
  422. package/dist/Endpoint-ONsly_dq.mjs +0 -1671
  423. package/dist/Endpoint-ONsly_dq.mjs.map +0 -1
  424. package/dist/Endpoint-oS-Fe3d_.d.mts.map +0 -1
  425. package/dist/EndpointFactory-Bm3aKRdV.mjs.map +0 -1
  426. package/dist/EndpointFactory-CLvWuHyt.cjs.map +0 -1
  427. package/dist/HonoEndpointAdaptor-92zavCsV.cjs.map +0 -1
  428. package/dist/HonoEndpointAdaptor-yYaU7jVJ.mjs.map +0 -1
  429. package/dist/Queue-D9X6OoON.d.mts.map +0 -1
  430. package/dist/Queue-DYPB2KWL.d.cts.map +0 -1
  431. package/dist/Subscriber-C4heaAyO.d.mts +0 -51
  432. package/dist/Subscriber-C4heaAyO.d.mts.map +0 -1
  433. package/dist/Subscriber-CotDUELC.d.cts +0 -51
  434. package/dist/Subscriber-CotDUELC.d.cts.map +0 -1
  435. package/dist/SubscriberBuilder-BEv0eoHy.d.cts +0 -59
  436. package/dist/SubscriberBuilder-BEv0eoHy.d.cts.map +0 -1
  437. package/dist/SubscriberBuilder-C0ZEtGDI.cjs +0 -125
  438. package/dist/SubscriberBuilder-C0ZEtGDI.cjs.map +0 -1
  439. package/dist/SubscriberBuilder-h7B_cHMr.mjs +0 -114
  440. package/dist/SubscriberBuilder-h7B_cHMr.mjs.map +0 -1
  441. package/dist/SubscriberBuilder-tyH5yTk5.d.mts +0 -59
  442. package/dist/SubscriberBuilder-tyH5yTk5.d.mts.map +0 -1
  443. package/dist/Topic-DEVGo0Dm.d.cts +0 -89
  444. package/dist/Topic-DEVGo0Dm.d.cts.map +0 -1
  445. package/dist/Topic-zk_6Gthr.d.mts +0 -89
  446. package/dist/Topic-zk_6Gthr.d.mts.map +0 -1
  447. package/dist/auth.d.cts.map +0 -1
  448. package/dist/auth.d.mts.map +0 -1
  449. package/dist/cache.d.cts.map +0 -1
  450. package/dist/cache.d.mts.map +0 -1
  451. package/dist/construct-interface-DPlxfpoS.d.mts.map +0 -1
  452. package/dist/construct-interface-DgXTJcOD.d.cts.map +0 -1
  453. package/dist/credential.cjs.map +0 -1
  454. package/dist/credential.d.cts.map +0 -1
  455. package/dist/credential.d.mts.map +0 -1
  456. package/dist/credential.mjs.map +0 -1
  457. package/dist/database/kysely.cjs.map +0 -1
  458. package/dist/database/kysely.d.cts.map +0 -1
  459. package/dist/database/kysely.d.mts.map +0 -1
  460. package/dist/database/kysely.mjs.map +0 -1
  461. package/dist/functions-B6qCvfmy.cjs.map +0 -1
  462. package/dist/functions-C53GW2eQ.mjs.map +0 -1
  463. package/dist/index-B2urf3YI.d.cts +0 -26
  464. package/dist/index-B2urf3YI.d.cts.map +0 -1
  465. package/dist/index-C1ZwNOOk.d.cts.map +0 -1
  466. package/dist/index-Cc4kKPag.d.mts.map +0 -1
  467. package/dist/index-DMCDvnsM.d.mts +0 -26
  468. package/dist/index-DMCDvnsM.d.mts.map +0 -1
  469. package/dist/index-D_frT6MP.d.cts +0 -165
  470. package/dist/index-D_frT6MP.d.cts.map +0 -1
  471. package/dist/index-DcyIYbDS.d.mts +0 -165
  472. package/dist/index-DcyIYbDS.d.mts.map +0 -1
  473. package/dist/lazyAccessors-BHtcqgz2.mjs +0 -211
  474. package/dist/lazyAccessors-BHtcqgz2.mjs.map +0 -1
  475. package/dist/lazyAccessors-Dx9NLwJZ.cjs.map +0 -1
  476. package/dist/processAudits-BpRlPQMW.mjs.map +0 -1
  477. package/dist/processAudits-D_2W5x8k.cjs.map +0 -1
  478. package/dist/queue/index.cjs.map +0 -1
  479. package/dist/queue/index.d.cts.map +0 -1
  480. package/dist/queue/index.d.mts.map +0 -1
  481. package/dist/queue/index.mjs.map +0 -1
  482. package/dist/telemetry-DGcFlVpB.d.cts.map +0 -1
  483. package/dist/telemetry-DGcFlVpB.d.mts.map +0 -1
  484. package/dist/topic/index.cjs.map +0 -1
  485. package/dist/topic/index.mjs.map +0 -1
@@ -0,0 +1,1716 @@
1
+ import { t as onShutdown } from "./shutdown-C7xa8x9S.mjs";
2
+ import { edgeTo, idsOf, servicesOf } from "./construct-interface.mjs";
3
+ import { c as loadHono, m as loadWs, u as loadIoredis } from "./optionalPeers-D7Wt6dnF.mjs";
4
+ import { t as isPrivateAddress } from "./privateAddress-Bg5fUsbp.mjs";
5
+ import { n as envParserFor } from "./surfaceEnv-wMT5QzgZ.mjs";
6
+ import { i as webSocketSinkDriverFor, n as UnregisteredWebSocketScheme, t as ownOrigins } from "./origins-Boc9qbo-.mjs";
7
+ import { API_GATEWAY_WEBSOCKET_SCHEME, InvalidHostLabel, assertHostLabels, canonicalId, providedKeyFor, serviceKey, trustsOrigin } from "@geekmidas/manifest";
8
+ import { DEFAULT_LOGGER } from "@geekmidas/logger/console";
9
+ import { randomBytes } from "node:crypto";
10
+ import { ServiceDiscovery, runWithRequestContext } from "@geekmidas/services";
11
+ import { HttpError } from "@geekmidas/errors";
12
+ import { toJsonSchema } from "@geekmidas/schema/conversion";
13
+ //#region src/websocket/frame.ts
14
+ /**
15
+ * The shape a surface's frames take on the wire.
16
+ *
17
+ * By default a frame is `{ "action": …, "id"?: …, "data": … }` — API
18
+ * Gateway's shape. A surface that names a discriminator — `frame: {
19
+ * discriminator: 'type' }` — sends and reads flat frames instead: the action
20
+ * under that key, and the data's own fields beside it.
21
+ *
22
+ * ```json
23
+ * {"type":"chat.message.created","chatId":"c1","message":{…}}
24
+ * ```
25
+ *
26
+ * A flat frame has no `id` of its own: every field but the discriminator is
27
+ * the data, so a reply is paired by its action, not an echoed id.
28
+ */
29
+ /** A declared message whose schema does not describe an object. */
30
+ var WebSocketMessageNotAnObject = class extends Error {
31
+ surface;
32
+ action;
33
+ discriminator;
34
+ constructor(surface, action, discriminator) {
35
+ super(`${surface} sends flat frames, keyed by '${discriminator}', so each message's fields sit beside it — but '${action}' is not an object schema. Declare it as an object (z.object({ … })), or drop \`frame\` to send { action, data }.`);
36
+ this.surface = surface;
37
+ this.action = action;
38
+ this.discriminator = discriminator;
39
+ this.name = "WebSocketMessageNotAnObject";
40
+ }
41
+ };
42
+ /** A declared message whose schema has a field named the discriminator. */
43
+ var WebSocketMessageDeclaresDiscriminator = class extends Error {
44
+ surface;
45
+ action;
46
+ discriminator;
47
+ constructor(surface, action, discriminator) {
48
+ super(`${surface}'s '${action}' message declares a '${discriminator}' field, which is where its flat frames keep the action. Rename the field, or give \`frame.discriminator\` a key no message uses.`);
49
+ this.surface = surface;
50
+ this.action = action;
51
+ this.discriminator = discriminator;
52
+ this.name = "WebSocketMessageDeclaresDiscriminator";
53
+ }
54
+ };
55
+ /** Data sent in a flat frame that is not an object. */
56
+ var WebSocketDataNotAnObject = class extends Error {
57
+ surface;
58
+ action;
59
+ discriminator;
60
+ constructor(surface, action, discriminator) {
61
+ super(`${surface} sends flat frames, keyed by '${discriminator}', and '${action}''s data is not an object, so it has no fields to put beside it. Send an object. Nothing was sent.`);
62
+ this.surface = surface;
63
+ this.action = action;
64
+ this.discriminator = discriminator;
65
+ this.name = "WebSocketDataNotAnObject";
66
+ }
67
+ };
68
+ /** Data sent in a flat frame that carries the discriminator itself. */
69
+ var WebSocketDataHasDiscriminator = class extends Error {
70
+ surface;
71
+ action;
72
+ discriminator;
73
+ constructor(surface, action, discriminator) {
74
+ super(`'${action}''s data on ${surface} has a '${discriminator}' field, which is where its flat frames keep the action. Rename the field. Nothing was sent.`);
75
+ this.surface = surface;
76
+ this.action = action;
77
+ this.discriminator = discriminator;
78
+ this.name = "WebSocketDataHasDiscriminator";
79
+ }
80
+ };
81
+ /** How one surface writes and reads its frames. */
82
+ var FrameShape = class {
83
+ surface;
84
+ discriminator;
85
+ constructor(surface, discriminator) {
86
+ this.surface = surface;
87
+ this.discriminator = discriminator;
88
+ }
89
+ /** The key an inbound frame names its action under. */
90
+ get key() {
91
+ return this.discriminator ?? "action";
92
+ }
93
+ /**
94
+ * The frame for `action`'s `data`, serialised.
95
+ *
96
+ * @throws {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator} for
97
+ * a flat frame whose data cannot sit beside the discriminator.
98
+ */
99
+ encode(action, data, id) {
100
+ const { discriminator } = this;
101
+ if (discriminator === void 0) return JSON.stringify({
102
+ action,
103
+ ...id !== void 0 ? { id } : {},
104
+ data
105
+ });
106
+ if (!isRecord(data)) throw new WebSocketDataNotAnObject(this.surface, action, discriminator);
107
+ if (Object.hasOwn(data, discriminator)) throw new WebSocketDataHasDiscriminator(this.surface, action, discriminator);
108
+ return JSON.stringify({
109
+ [discriminator]: action,
110
+ ...data
111
+ });
112
+ }
113
+ /** A parsed frame's action, id and data — `undefined` when it names none. */
114
+ decode(frame) {
115
+ if (!isRecord(frame)) return void 0;
116
+ const { discriminator } = this;
117
+ if (discriminator === void 0) {
118
+ if (typeof frame.action !== "string") return void 0;
119
+ return {
120
+ action: frame.action,
121
+ ...isId(frame.id) ? { id: frame.id } : {},
122
+ data: frame.data
123
+ };
124
+ }
125
+ const { [discriminator]: action, ...data } = frame;
126
+ if (typeof action !== "string") return void 0;
127
+ return {
128
+ action,
129
+ data
130
+ };
131
+ }
132
+ /** The id a frame that names no action carried, to echo on its error. */
133
+ idOf(frame) {
134
+ if (this.discriminator !== void 0 || !isRecord(frame)) return void 0;
135
+ return isId(frame.id) ? frame.id : void 0;
136
+ }
137
+ /**
138
+ * Refuse a declared message a flat frame cannot carry: one that is not an
139
+ * object, or that has a field named the discriminator.
140
+ *
141
+ * @throws {WebSocketMessageNotAnObject}, {WebSocketMessageDeclaresDiscriminator}
142
+ */
143
+ check(messages) {
144
+ const { discriminator } = this;
145
+ if (discriminator === void 0) return;
146
+ for (const [action, schema] of Object.entries(messages)) {
147
+ const shape = objectShape(toJsonSchema(schema));
148
+ if (!shape) throw new WebSocketMessageNotAnObject(this.surface, action, discriminator);
149
+ if (shape.has(discriminator)) throw new WebSocketMessageDeclaresDiscriminator(this.surface, action, discriminator);
150
+ }
151
+ }
152
+ };
153
+ /**
154
+ * The fields a JSON Schema's object declares, or `undefined` when it is not
155
+ * an object. A union or intersection is one when each of its members is.
156
+ */
157
+ function objectShape(schema) {
158
+ if (!isRecord(schema)) return void 0;
159
+ const members = schema.anyOf ?? schema.oneOf ?? schema.allOf;
160
+ if (Array.isArray(members) && members.length > 0) {
161
+ const fields = /* @__PURE__ */ new Set();
162
+ for (const member of members) {
163
+ const shape = objectShape(member);
164
+ if (!shape) return void 0;
165
+ for (const field of shape) fields.add(field);
166
+ }
167
+ return fields;
168
+ }
169
+ if (schema.type !== "object") return void 0;
170
+ return new Set(isRecord(schema.properties) ? Object.keys(schema.properties) : []);
171
+ }
172
+ function isRecord(value) {
173
+ return typeof value === "object" && value !== null && !Array.isArray(value);
174
+ }
175
+ function isId(value) {
176
+ return typeof value === "string" || typeof value === "number";
177
+ }
178
+ //#endregion
179
+ //#region src/websocket/publisher.ts
180
+ /** A message sent on an action the surface does not declare. */
181
+ var UnknownWebSocketMessage = class extends Error {
182
+ surface;
183
+ action;
184
+ declared;
185
+ constructor(surface, action, declared) {
186
+ super(`${surface} sends no '${action}' message. It declares ${declared.map((a) => `'${a}'`).join(", ")} — send one of them, or add '${action}' to its messages.`);
187
+ this.surface = surface;
188
+ this.action = action;
189
+ this.declared = declared;
190
+ this.name = "UnknownWebSocketMessage";
191
+ }
192
+ };
193
+ /** A message whose data its action's schema refused. */
194
+ var InvalidWebSocketMessage = class extends Error {
195
+ surface;
196
+ action;
197
+ issues;
198
+ constructor(surface, action, issues) {
199
+ super(`${surface}'s '${action}' message was refused by its schema: ${issues.map((issue) => issue.message).join("; ")}. Nothing was sent.`);
200
+ this.surface = surface;
201
+ this.action = action;
202
+ this.issues = issues;
203
+ this.name = "InvalidWebSocketMessage";
204
+ }
205
+ };
206
+ /**
207
+ * How anything reaches a socket — `services.realtime` in an endpoint, and
208
+ * `sockets` in a route of the surface itself.
209
+ *
210
+ * A message is `{ action, data }`, the shape a client's frames arrive in —
211
+ * or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,
212
+ * ...data }`.
213
+ * Where the surface declares its messages, `action` is one of them and
214
+ * `data` is typed and checked by its schema before anything is sent; where it
215
+ * declares none, any action and any JSON value go. A message is serialised
216
+ * once, whatever the number of sockets it goes to. An id whose process has
217
+ * gone is dropped silently, as API Gateway's `postToConnection` to a closed
218
+ * connection is a no-op the sender rarely wants to handle.
219
+ */
220
+ var WebSocketPublisher = class {
221
+ sink;
222
+ declared;
223
+ frame;
224
+ constructor(sink, declared, frame = new FrameShape(declared?.surface ?? "")) {
225
+ this.sink = sink;
226
+ this.declared = declared;
227
+ this.frame = frame;
228
+ }
229
+ /** Send `action`'s message to each connection. */
230
+ async send(ids, action, data) {
231
+ const payload = await this.payload(action, data);
232
+ await this.sink.send(listOf(ids), payload);
233
+ }
234
+ /** Send `action`'s message to every open connection, on every process. */
235
+ async broadcast(action, data, options = {}) {
236
+ const payload = await this.payload(action, data);
237
+ await this.sink.broadcast(payload, options.except?.length ? options.except : void 0);
238
+ }
239
+ /** Close each connection, with a close code and reason its client sees. */
240
+ async close(ids, code = 1e3, reason = "") {
241
+ await this.sink.close(listOf(ids), code, reason);
242
+ }
243
+ /**
244
+ * The frame, checked by the action's schema where the surface declares
245
+ * its messages.
246
+ *
247
+ * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a
248
+ * flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}
249
+ */
250
+ async payload(action, data) {
251
+ if (!this.declared) return this.frame.encode(action, data);
252
+ const { surface, messages } = this.declared;
253
+ const schema = messages[action];
254
+ if (!schema) throw new UnknownWebSocketMessage(surface, action, Object.keys(messages));
255
+ const result = await schema["~standard"].validate(data);
256
+ if (result.issues) throw new InvalidWebSocketMessage(surface, action, result.issues);
257
+ return this.frame.encode(action, result.value);
258
+ }
259
+ };
260
+ function listOf(ids) {
261
+ return typeof ids === "string" ? [ids] : ids;
262
+ }
263
+ //#endregion
264
+ //#region src/websocket/core.ts
265
+ /** Two routes answer one action. */
266
+ var DuplicateWebSocketRoute = class extends Error {
267
+ surface;
268
+ action;
269
+ constructor(surface, action) {
270
+ super(`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`);
271
+ this.surface = surface;
272
+ this.action = action;
273
+ this.name = "DuplicateWebSocketRoute";
274
+ }
275
+ };
276
+ var WebSocketCore = class {
277
+ options;
278
+ surface;
279
+ /** How frames are read and written — what an adaptor decodes replies by. */
280
+ frame;
281
+ /** `sockets` in every handler. */
282
+ sockets;
283
+ routes = /* @__PURE__ */ new Map();
284
+ lifecycle = {};
285
+ /**
286
+ * @throws {DuplicateWebSocketRoute} when two routes answer one action, and
287
+ * the frame checks of `FrameShape.check` for declared messages.
288
+ */
289
+ constructor(options) {
290
+ this.options = options;
291
+ this.surface = options.surface;
292
+ for (const route of options.routes) {
293
+ if (route.surface.id !== options.surface) continue;
294
+ if (route.kind === "message") {
295
+ if (this.routes.has(route.action)) throw new DuplicateWebSocketRoute(options.surface, route.action);
296
+ this.routes.set(route.action, route);
297
+ } else {
298
+ if (this.lifecycle[route.kind]) throw new DuplicateWebSocketRoute(options.surface, route.action);
299
+ this.lifecycle[route.kind] = route;
300
+ }
301
+ }
302
+ this.frame = new FrameShape(options.surface, options.frame?.discriminator);
303
+ if (options.messages) this.frame.check(options.messages);
304
+ this.sockets = new WebSocketPublisher(options.sink, options.messages ? {
305
+ surface: options.surface,
306
+ messages: options.messages
307
+ } : void 0, this.frame);
308
+ }
309
+ /**
310
+ * Run the connect handler for a handshake: accepted with the connection's
311
+ * `data` (what the handler returned, `{}` for nothing), or refused with
312
+ * the status of the `HttpError` it threw — 500 for anything else. A surface
313
+ * with no connect handler accepts every handshake, and verifies no session.
314
+ */
315
+ async connect(request, options = {}) {
316
+ const { connectionId, headers, query } = request;
317
+ const route = this.lifecycle.connect;
318
+ if (!route) return {
319
+ accepted: true,
320
+ connection: {
321
+ id: connectionId,
322
+ data: {}
323
+ }
324
+ };
325
+ try {
326
+ const session = "session" in request ? request.session : this.options.authenticator ? await this.options.authenticator.verify(headers, this.options.envParser) : null;
327
+ const returned = await this.run(route, connectionId, (base) => ({
328
+ ...base,
329
+ connectionId,
330
+ headers,
331
+ query,
332
+ session
333
+ }), options);
334
+ return {
335
+ accepted: true,
336
+ connection: {
337
+ id: connectionId,
338
+ data: returned && typeof returned === "object" ? returned : {}
339
+ }
340
+ };
341
+ } catch (error) {
342
+ if (error instanceof HttpError) return {
343
+ accepted: false,
344
+ status: error.statusCode,
345
+ statusText: error.statusMessage,
346
+ error
347
+ };
348
+ this.options.logger.error({
349
+ err: error,
350
+ connectionId
351
+ }, "WebSocket connect handler failed");
352
+ return {
353
+ accepted: false,
354
+ status: 500,
355
+ statusText: "Internal Server Error",
356
+ error
357
+ };
358
+ }
359
+ }
360
+ /**
361
+ * Parse, validate and run one inbound frame. The reply — the handler's
362
+ * return, encoded — and every `$error` are written with `write`; an error
363
+ * is a frame, never a close. A binary frame is refused: frames are text.
364
+ */
365
+ async message(connection, raw, write, options = {}) {
366
+ if (typeof raw !== "string") return this.error(write, {}, "Frames are JSON text.");
367
+ let parsed;
368
+ try {
369
+ parsed = JSON.parse(raw);
370
+ } catch {
371
+ return this.error(write, {}, "Frames are JSON.");
372
+ }
373
+ const frame = this.frame.decode(parsed);
374
+ if (!frame) return this.error(write, { id: this.frame.idOf(parsed) }, `A frame names its \`${this.frame.key}\`.`);
375
+ const { action, id } = frame;
376
+ const route = this.routes.get(action) ?? this.routes.get("$default");
377
+ if (!route) return this.error(write, {
378
+ action,
379
+ id
380
+ }, `No route answers '${action}'.`);
381
+ let body = frame.data;
382
+ if (route.schema) {
383
+ const result = await route.schema["~standard"].validate(frame.data);
384
+ if (result.issues) return this.error(write, {
385
+ action,
386
+ id
387
+ }, "The frame was invalid.", result.issues);
388
+ body = result.value;
389
+ }
390
+ try {
391
+ const returned = await this.run(route, connection.id, (base) => ({
392
+ ...base,
393
+ connection,
394
+ body,
395
+ reply: (message) => write(JSON.stringify(message))
396
+ }), options);
397
+ if (returned !== void 0) write(this.frame.encode(action, returned, id));
398
+ return {
399
+ ok: true,
400
+ action,
401
+ ...id !== void 0 ? { id } : {},
402
+ returned
403
+ };
404
+ } catch (error) {
405
+ if (error instanceof HttpError) return this.error(write, {
406
+ action,
407
+ id
408
+ }, error.message, void 0, error);
409
+ this.options.logger.error({
410
+ err: error,
411
+ connectionId: connection.id,
412
+ action
413
+ }, "WebSocket route failed");
414
+ return this.error(write, {
415
+ action,
416
+ id
417
+ }, "The route failed.", void 0, error);
418
+ }
419
+ }
420
+ /**
421
+ * Run the disconnect handler for a connection that has closed. What it
422
+ * throws is logged and returned, never thrown: the socket is gone either
423
+ * way.
424
+ */
425
+ async disconnect(connection, close, options = {}) {
426
+ const route = this.lifecycle.disconnect;
427
+ if (!route) return { ok: true };
428
+ try {
429
+ await this.run(route, connection.id, (base) => ({
430
+ ...base,
431
+ connection,
432
+ ...close
433
+ }), options);
434
+ return { ok: true };
435
+ } catch (error) {
436
+ this.options.logger.error({
437
+ err: error,
438
+ connectionId: connection.id
439
+ }, "WebSocket disconnect handler failed");
440
+ return {
441
+ ok: false,
442
+ error
443
+ };
444
+ }
445
+ }
446
+ /** Run a handler with its services, inside a request context of its own. */
447
+ async run(route, connectionId, context, options) {
448
+ const logger = this.options.logger.child({
449
+ connectionId,
450
+ action: route.action
451
+ });
452
+ return runWithRequestContext({
453
+ logger,
454
+ requestId: connectionId,
455
+ startTime: Date.now(),
456
+ operation: `ws ${route.action}`
457
+ }, async () => {
458
+ const services = await this.services(route, options.services);
459
+ return route.handler(context({
460
+ services,
461
+ logger,
462
+ sockets: this.sockets
463
+ }));
464
+ });
465
+ }
466
+ /** The route's services: the overrides it names, the rest registered. */
467
+ async services(route, overrides = {}) {
468
+ const given = {};
469
+ const wanted = route.services.filter((service) => {
470
+ if (!Object.hasOwn(overrides, service.serviceName)) return true;
471
+ given[service.serviceName] = overrides[service.serviceName];
472
+ return false;
473
+ });
474
+ return {
475
+ ...wanted.length ? await ServiceDiscovery.getInstance(this.options.envParser).register([...wanted]) : {},
476
+ ...given
477
+ };
478
+ }
479
+ error(write, at, message, issues, error) {
480
+ write(this.frame.encode("$error", {
481
+ message,
482
+ ...issues ? { issues } : {}
483
+ }, at.id));
484
+ return {
485
+ ok: false,
486
+ ...at.action !== void 0 ? { action: at.action } : {},
487
+ ...at.id !== void 0 ? { id: at.id } : {},
488
+ message,
489
+ ...issues ? { issues } : {},
490
+ ...error !== void 0 ? { error } : {}
491
+ };
492
+ }
493
+ };
494
+ //#endregion
495
+ //#region src/websocket/limits.ts
496
+ /** Close codes the limits close a socket with. */
497
+ const LIMIT_CLOSE = {
498
+ /** Policy violation: it kept sending past its rate, or its identity has too many sockets. */
499
+ policy: 1008 };
500
+ const DEFAULT_WEBSOCKET_LIMITS = {
501
+ handshakesPerMinute: 120,
502
+ inFlightHandshakes: 16,
503
+ connectionsPerIp: 256,
504
+ messagesPerSecond: 50,
505
+ burst: 100,
506
+ maxConnections: 16
507
+ };
508
+ /** A limit that is not a whole number of at least one. */
509
+ var InvalidWebSocketLimit = class extends Error {
510
+ surface;
511
+ limit;
512
+ value;
513
+ constructor(surface, limit, value) {
514
+ super(`${surface} sets limits.${limit} to ${String(value)}. A limit is a whole number of 1 or more — or false, to lift it.`);
515
+ this.surface = surface;
516
+ this.limit = limit;
517
+ this.value = value;
518
+ this.name = "InvalidWebSocketLimit";
519
+ }
520
+ };
521
+ /**
522
+ * Fill in the defaults.
523
+ *
524
+ * @throws {InvalidWebSocketLimit} for a limit that is not a positive integer.
525
+ */
526
+ function resolveLimits(surface, limits = {}) {
527
+ const pick = (name, value) => {
528
+ if (value === false) return void 0;
529
+ const resolved = value ?? DEFAULT_WEBSOCKET_LIMITS[name];
530
+ if (!Number.isInteger(resolved) || resolved < 1) throw new InvalidWebSocketLimit(surface, name, value);
531
+ return resolved;
532
+ };
533
+ const messagesPerSecond = pick("messagesPerSecond", limits.messagesPerSecond);
534
+ return {
535
+ ...optional("handshakesPerMinute", pick("handshakesPerMinute", limits.handshakesPerMinute)),
536
+ ...optional("inFlightHandshakes", pick("inFlightHandshakes", limits.inFlightHandshakes)),
537
+ ...optional("connectionsPerIp", pick("connectionsPerIp", limits.connectionsPerIp)),
538
+ ...optional("messagesPerSecond", messagesPerSecond),
539
+ burst: pick("burst", limits.burst) ?? DEFAULT_WEBSOCKET_LIMITS.burst,
540
+ ...limits.maxConnectionsPer ? { maxConnectionsPer: limits.maxConnectionsPer } : {},
541
+ maxConnections: pick("maxConnections", limits.maxConnections) ?? DEFAULT_WEBSOCKET_LIMITS.maxConnections,
542
+ overflow: limits.overflow ?? "refuse"
543
+ };
544
+ }
545
+ function optional(key, value) {
546
+ return value === void 0 ? {} : { [key]: value };
547
+ }
548
+ /**
549
+ * In one process. Two servers on one `memory://` channel — replicas in a
550
+ * test — share it, as they share the channel.
551
+ */
552
+ var MemoryLimitStore = class {
553
+ windows = /* @__PURE__ */ new Map();
554
+ /** key → member → [opened, expires] */
555
+ sets = /* @__PURE__ */ new Map();
556
+ async hit(key, windowMs) {
557
+ const now = Date.now();
558
+ let window = this.windows.get(key);
559
+ if (!window || window.resetAt <= now) {
560
+ window = {
561
+ count: 0,
562
+ resetAt: now + windowMs
563
+ };
564
+ this.windows.set(key, window);
565
+ }
566
+ window.count++;
567
+ return {
568
+ count: window.count,
569
+ resetMs: window.resetAt - now
570
+ };
571
+ }
572
+ async hold(key, member, ttlMs) {
573
+ const now = Date.now();
574
+ let set = this.sets.get(key);
575
+ if (!set) {
576
+ set = /* @__PURE__ */ new Map();
577
+ this.sets.set(key, set);
578
+ }
579
+ for (const [held, [, expires]] of set) if (expires <= now) set.delete(held);
580
+ const opened = set.get(member)?.[0] ?? now;
581
+ set.set(member, [opened, now + ttlMs]);
582
+ return [...set].sort((a, b) => a[1][0] - b[1][0]).map(([held]) => held);
583
+ }
584
+ async release(key, member) {
585
+ const set = this.sets.get(key);
586
+ set?.delete(member);
587
+ if (set?.size === 0) this.sets.delete(key);
588
+ }
589
+ async renew(held, ttlMs) {
590
+ const expires = Date.now() + ttlMs;
591
+ for (const { key, member } of held) {
592
+ const entry = this.sets.get(key)?.get(member);
593
+ if (entry) entry[1] = expires;
594
+ }
595
+ }
596
+ };
597
+ const HIT = `
598
+ local count = redis.call('INCR', KEYS[1])
599
+ if count == 1 then redis.call('PEXPIRE', KEYS[1], ARGV[1]) end
600
+ local ttl = redis.call('PTTL', KEYS[1])
601
+ if ttl < 0 then
602
+ redis.call('PEXPIRE', KEYS[1], ARGV[1])
603
+ ttl = tonumber(ARGV[1])
604
+ end
605
+ return { count, ttl }
606
+ `;
607
+ const HOLD = `
608
+ redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1])
609
+ redis.call('ZADD', KEYS[1], ARGV[2], ARGV[3])
610
+ redis.call('PEXPIRE', KEYS[1], ARGV[4])
611
+ return redis.call('ZRANGE', KEYS[1], 0, -1)
612
+ `;
613
+ const RENEW = `
614
+ for i, key in ipairs(KEYS) do
615
+ redis.call('ZADD', key, 'XX', ARGV[1], ARGV[i + 2])
616
+ redis.call('PEXPIRE', key, ARGV[2])
617
+ end
618
+ return 0
619
+ `;
620
+ /**
621
+ * Over Redis — the transport's own — so every replica counts in one place.
622
+ * Each operation is one script, so concurrent handshakes on any replica are
623
+ * each counted.
624
+ */
625
+ var RedisLimitStore = class {
626
+ client;
627
+ prefix;
628
+ /** member as handed in → member as stored, with its opening time. */
629
+ stored = /* @__PURE__ */ new Map();
630
+ constructor(client, prefix) {
631
+ this.client = client;
632
+ this.prefix = prefix;
633
+ }
634
+ key(key) {
635
+ return `${this.prefix}:limits:${key}`;
636
+ }
637
+ storedAs(key, member) {
638
+ const id = `${key}\n${member}`;
639
+ let stored = this.stored.get(id);
640
+ if (!stored) {
641
+ stored = `${Date.now().toString(36).padStart(9, "0")}|${member}`;
642
+ this.stored.set(id, stored);
643
+ }
644
+ return stored;
645
+ }
646
+ async hit(key, windowMs) {
647
+ const [count, resetMs] = await this.client.eval(HIT, 1, this.key(key), windowMs);
648
+ return {
649
+ count: Number(count),
650
+ resetMs: Number(resetMs)
651
+ };
652
+ }
653
+ async hold(key, member, ttlMs) {
654
+ const now = Date.now();
655
+ return (await this.client.eval(HOLD, 1, this.key(key), now, now + ttlMs, this.storedAs(key, member), ttlMs)).sort().map((stored) => stored.slice(stored.indexOf("|") + 1));
656
+ }
657
+ async release(key, member) {
658
+ const id = `${key}\n${member}`;
659
+ const stored = this.stored.get(id);
660
+ this.stored.delete(id);
661
+ if (!stored) return;
662
+ await this.client.eval("return redis.call('ZREM', KEYS[1], ARGV[1])", 1, this.key(key), stored);
663
+ }
664
+ async renew(held, ttlMs) {
665
+ const known = held.flatMap(({ key, member }) => {
666
+ const stored = this.stored.get(`${key}\n${member}`);
667
+ return stored ? [{
668
+ key: this.key(key),
669
+ stored
670
+ }] : [];
671
+ });
672
+ if (known.length === 0) return;
673
+ await this.client.eval(RENEW, known.length, ...known.map(({ key }) => key), Date.now() + ttlMs, ttlMs, ...known.map(({ stored }) => stored));
674
+ }
675
+ };
676
+ /**
677
+ * A socket's inbound budget: `burst` frames at once, refilled at `rate` a
678
+ * second.
679
+ */
680
+ var TokenBucket = class {
681
+ rate;
682
+ burst;
683
+ tokens;
684
+ at = Date.now();
685
+ constructor(rate, burst) {
686
+ this.rate = rate;
687
+ this.burst = burst;
688
+ this.tokens = burst;
689
+ }
690
+ /** Spend one token, if there is one. */
691
+ take(now = Date.now()) {
692
+ this.tokens = Math.min(this.burst, this.tokens + (now - this.at) / 1e3 * this.rate);
693
+ this.at = now;
694
+ if (this.tokens < 1) return false;
695
+ this.tokens -= 1;
696
+ return true;
697
+ }
698
+ /** Whether it has refilled completely since it last ran dry. */
699
+ get full() {
700
+ return this.tokens >= this.burst - 1;
701
+ }
702
+ };
703
+ /**
704
+ * The client a handshake is counted against. Behind the stack's edge — a
705
+ * private peer — the address the edge put last in `X-Forwarded-For`, the one
706
+ * it saw; Traefik and Caddy both replace what an outside client sent there.
707
+ * From anywhere else, the peer itself: a header a client could set never
708
+ * picks the bucket it is counted in.
709
+ */
710
+ function clientAddress(request) {
711
+ const peer = request.socket.remoteAddress ?? "unknown";
712
+ const forwarded = request.headers["x-forwarded-for"];
713
+ if (!forwarded || !isPrivateAddress(peer)) return peer;
714
+ return (Array.isArray(forwarded) ? forwarded.join(",") : forwarded).split(",").map((hop) => hop.trim()).filter(Boolean).at(-1) ?? peer;
715
+ }
716
+ //#endregion
717
+ //#region src/websocket/testing.ts
718
+ /**
719
+ * A sink that keeps what it is handed, decoded by the surface's frame shape,
720
+ * and sends it nowhere.
721
+ */
722
+ var RecordingSink = class {
723
+ frame;
724
+ sent = [];
725
+ broadcasts = [];
726
+ closed = [];
727
+ constructor(frame) {
728
+ this.frame = frame;
729
+ }
730
+ async send(ids, payload) {
731
+ this.sent.push({
732
+ ids: [...ids],
733
+ ...this.decode(payload)
734
+ });
735
+ }
736
+ async broadcast(payload, except) {
737
+ this.broadcasts.push({
738
+ except: [...except ?? []],
739
+ ...this.decode(payload)
740
+ });
741
+ }
742
+ async close(ids, code, reason) {
743
+ this.closed.push({
744
+ ids: [...ids],
745
+ code,
746
+ reason
747
+ });
748
+ }
749
+ clear() {
750
+ this.sent.length = 0;
751
+ this.broadcasts.length = 0;
752
+ this.closed.length = 0;
753
+ }
754
+ decode(payload) {
755
+ const frame = JSON.parse(payload);
756
+ const { action, data } = this.frame.decode(frame);
757
+ return {
758
+ action,
759
+ data,
760
+ frame
761
+ };
762
+ }
763
+ };
764
+ /**
765
+ * A surface's publisher that records rather than sends — what
766
+ * `surface.testPublisher()` returns, of the type `services.<surface>` is.
767
+ *
768
+ * Every send is still checked by the declared `messages` and encoded by the
769
+ * surface's `frame`, so an invalid push fails the spec as it would fail
770
+ * deployed, and `frame` on each record is what the client would parse.
771
+ */
772
+ var TestWebSocketPublisher = class extends WebSocketPublisher {
773
+ /** Where the records are kept — what `route.request()` builds its core on. */
774
+ recording;
775
+ constructor(frame, declared) {
776
+ const recording = new RecordingSink(frame);
777
+ super(recording, declared, frame);
778
+ this.recording = recording;
779
+ }
780
+ /** Each `send(ids, action, data)`, in order. */
781
+ get sent() {
782
+ return this.recording.sent;
783
+ }
784
+ /** Each `broadcast(action, data, { except })`, in order. */
785
+ get broadcasts() {
786
+ return this.recording.broadcasts;
787
+ }
788
+ /** Each `close(ids, code, reason)`, in order. */
789
+ get closed() {
790
+ return this.recording.closed;
791
+ }
792
+ /** Forget everything recorded so far. */
793
+ clear() {
794
+ this.recording.clear();
795
+ }
796
+ };
797
+ /** A frame `route.request()` sent was refused before its handler ran. */
798
+ var InvalidWebSocketRequest = class extends Error {
799
+ surface;
800
+ action;
801
+ reason;
802
+ issues;
803
+ constructor(surface, action, reason, issues) {
804
+ super(`${surface}'s '${action}' route refused the request: ${reason}${issues?.length ? ` ${issues.map((issue) => issue.message).join("; ")}.` : ""} Send a body its schema accepts.`);
805
+ this.surface = surface;
806
+ this.action = action;
807
+ this.reason = reason;
808
+ this.issues = issues;
809
+ this.name = "InvalidWebSocketRequest";
810
+ }
811
+ };
812
+ let issued = 0;
813
+ /** A connection id no other test call is using. */
814
+ function nextConnectionId() {
815
+ issued += 1;
816
+ return `test.${issued}`;
817
+ }
818
+ function connectionOf(given) {
819
+ return {
820
+ id: given?.id ?? nextConnectionId(),
821
+ data: given?.data ?? {}
822
+ };
823
+ }
824
+ function coreFor(route, surface, sockets) {
825
+ return surface.core({
826
+ envParser: surface.envParser,
827
+ sink: (sockets ?? surface.testPublisher()).recording,
828
+ modules: [{ route }]
829
+ });
830
+ }
831
+ /** `connect.request()`: the connection's `data`, or what refused it. */
832
+ async function requestConnect(route, surface, request = {}) {
833
+ const outcome = await coreFor(route, surface, request.sockets).connect({
834
+ connectionId: request.connectionId ?? nextConnectionId(),
835
+ headers: new Headers(request.headers),
836
+ query: new URLSearchParams(request.query),
837
+ ..."session" in request ? { session: request.session } : {}
838
+ }, request.services ? { services: request.services } : {});
839
+ if (!outcome.accepted) throw outcome.error;
840
+ return outcome.connection.data;
841
+ }
842
+ /** A message route's `fullRequest()`: what it returned and wrote. */
843
+ async function requestMessage(route, surface, request) {
844
+ const core = coreFor(route, surface, request.sockets);
845
+ const frames = [];
846
+ const outcome = await core.message(connectionOf(request.connection), core.frame.encode(route.action, request.body, request.id), (payload) => frames.push(JSON.parse(payload)), request.services ? { services: request.services } : {});
847
+ if (outcome.ok) return {
848
+ returned: outcome.returned,
849
+ frames
850
+ };
851
+ if ("error" in outcome) throw outcome.error;
852
+ throw new InvalidWebSocketRequest(surface.id, route.action, outcome.message, outcome.issues);
853
+ }
854
+ /** `disconnect.request()`: resolves once the handler has run. */
855
+ async function requestDisconnect(route, surface, request = {}) {
856
+ const outcome = await coreFor(route, surface, request.sockets).disconnect(connectionOf(request.connection), {
857
+ code: request.code ?? 1e3,
858
+ reason: request.reason ?? ""
859
+ }, request.services ? { services: request.services } : {});
860
+ if (!outcome.ok) throw outcome.error;
861
+ }
862
+ //#endregion
863
+ //#region src/websocket/route.ts
864
+ /**
865
+ * A handler bound to a WebSocket surface — what `realtime.route('chat.send')
866
+ * …handle()` returns, and what a file exports.
867
+ *
868
+ * Carries `surface` and `constructs` the way an endpoint does, so discovery
869
+ * records what its process reaches without knowing what a route is.
870
+ */
871
+ var WebSocketRoute = class {
872
+ kind;
873
+ action;
874
+ surface;
875
+ services;
876
+ constructs;
877
+ handler;
878
+ schema;
879
+ __IS_WEBSOCKET_ROUTE__ = true;
880
+ static isRoute(value) {
881
+ return Boolean(value && value.__IS_WEBSOCKET_ROUTE__ === true);
882
+ }
883
+ constructor(kind, action, surface, services, constructs, handler, schema) {
884
+ this.kind = kind;
885
+ this.action = action;
886
+ this.surface = surface;
887
+ this.services = services;
888
+ this.constructs = constructs;
889
+ this.handler = handler;
890
+ this.schema = schema;
891
+ }
892
+ /**
893
+ * Run the handler as its surface would, with no server and no socket —
894
+ * as `endpoint.request()` runs an endpoint.
895
+ *
896
+ * - `connect`: resolves with the connection's `data`, or rejects with what
897
+ * refused it (an `UnauthorizedError` stays a 401).
898
+ * - a message route: `body` is encoded as a frame and checked by the
899
+ * route's schema; resolves with the handler's return, or rejects with
900
+ * what it threw or an `InvalidWebSocketRequest`.
901
+ * - `disconnect`: resolves once the handler has run, or rejects with what
902
+ * it threw.
903
+ */
904
+ request(...[request]) {
905
+ const route = this;
906
+ const given = request ?? {};
907
+ if (this.kind === "connect") return requestConnect(route, this.surface, given);
908
+ if (this.kind === "disconnect") return requestDisconnect(route, this.surface, given);
909
+ return requestMessage(route, this.surface, given).then(({ returned }) => returned);
910
+ }
911
+ /**
912
+ * A message route's `request()`, with every frame it wrote back to the
913
+ * connection — each `reply()` and the reply itself — beside its return.
914
+ */
915
+ fullRequest(request) {
916
+ return requestMessage(this, this.surface, request);
917
+ }
918
+ };
919
+ /** The builder `connect()`, `disconnect()` and `route()` start. */
920
+ var WebSocketRouteBuilder = class WebSocketRouteBuilder {
921
+ kind;
922
+ action;
923
+ surface;
924
+ _services;
925
+ _constructs;
926
+ schema;
927
+ constructor(kind, action, surface, _services = [], _constructs = [], schema) {
928
+ this.kind = kind;
929
+ this.action = action;
930
+ this.surface = surface;
931
+ this._services = _services;
932
+ this._constructs = _constructs;
933
+ this.schema = schema;
934
+ }
935
+ /** The schema a frame's `data` must satisfy before the handler runs. */
936
+ body(schema) {
937
+ return new WebSocketRouteBuilder(this.kind, this.action, this.surface, this._services, this._constructs, schema);
938
+ }
939
+ /** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */
940
+ dependsOn(constructs) {
941
+ return new WebSocketRouteBuilder(this.kind, this.action, this.surface, [...this._services, ...servicesOf(constructs)], idsOf(constructs, this._constructs), this.schema);
942
+ }
943
+ /**
944
+ * The handler. A message handler's return value, when there is one, is
945
+ * sent back to the connection as the reply to that frame; a connect
946
+ * handler's is kept as the connection's `data`.
947
+ */
948
+ handle(handler) {
949
+ return new WebSocketRoute(this.kind, this.action, this.surface, this._services, this._constructs, handler, this.schema);
950
+ }
951
+ };
952
+ /** The instance a connection id was issued by: everything before its dot. */
953
+ function instanceOf(connectionId) {
954
+ const dot = connectionId.indexOf(".");
955
+ return dot > 0 ? connectionId.slice(0, dot) : void 0;
956
+ }
957
+ /**
958
+ * A publisher's sink over a transport: a send goes to the instance each
959
+ * connection id names, a broadcast to every instance. What `services.<id>`
960
+ * sends through, and what the Node adaptor's own `sockets` do.
961
+ */
962
+ var TransportSink = class {
963
+ transport;
964
+ local;
965
+ constructor(transport, local) {
966
+ this.transport = transport;
967
+ this.local = local;
968
+ }
969
+ send(ids, payload) {
970
+ return this.each(ids, (group) => ({
971
+ kind: "send",
972
+ ids: group,
973
+ payload
974
+ }));
975
+ }
976
+ async broadcast(payload, except) {
977
+ await this.transport.publish("*", {
978
+ kind: "broadcast",
979
+ payload,
980
+ ...except?.length ? { except } : {}
981
+ });
982
+ }
983
+ close(ids, code, reason) {
984
+ return this.each(ids, (group) => ({
985
+ kind: "close",
986
+ ids: group,
987
+ code,
988
+ reason
989
+ }));
990
+ }
991
+ /** One delivery per process that holds any of `ids`. */
992
+ async each(ids, delivery) {
993
+ const byInstance = /* @__PURE__ */ new Map();
994
+ for (const id of ids) {
995
+ const instance = instanceOf(id);
996
+ if (!instance) continue;
997
+ const group = byInstance.get(instance) ?? [];
998
+ group.push(id);
999
+ byInstance.set(instance, group);
1000
+ }
1001
+ await Promise.all([...byInstance].map(([instance, group]) => this.local?.instance === instance ? this.local.deliver(delivery(group)) : this.transport.publish(instance, delivery(group))));
1002
+ }
1003
+ };
1004
+ /** A connection string names no transport this package knows. */
1005
+ var UnsupportedWebSocketTransport = class extends Error {
1006
+ connectionString;
1007
+ constructor(connectionString) {
1008
+ super(`'${redact(connectionString)}' is not a WebSocket publisher connection string. Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.`);
1009
+ this.connectionString = connectionString;
1010
+ this.name = "UnsupportedWebSocketTransport";
1011
+ }
1012
+ };
1013
+ /** The scheme alone, so an error never prints a password. */
1014
+ function redact(connectionString) {
1015
+ const scheme = connectionString.split("://")[0];
1016
+ return scheme && scheme !== connectionString ? `${scheme}://…` : connectionString.slice(0, 12);
1017
+ }
1018
+ const key = Symbol.for("@geekmidas/constructs/websocket/memory");
1019
+ const registry = globalThis;
1020
+ registry[key] ??= /* @__PURE__ */ new Map();
1021
+ const channels = registry[key];
1022
+ const limitsKey = Symbol.for("@geekmidas/constructs/websocket/memory-limits");
1023
+ const limitRegistry = globalThis;
1024
+ limitRegistry[limitsKey] ??= /* @__PURE__ */ new Map();
1025
+ const limitStores = limitRegistry[limitsKey];
1026
+ /**
1027
+ * In one process: the server and whoever sends meet in a map, keyed by the
1028
+ * channel the connection string names.
1029
+ */
1030
+ var MemoryTransport = class {
1031
+ channel;
1032
+ subscribed = /* @__PURE__ */ new Set();
1033
+ constructor(channel) {
1034
+ this.channel = channel;
1035
+ }
1036
+ async publish(instance, delivery) {
1037
+ const instances = channels.get(this.channel);
1038
+ if (!instances) return;
1039
+ if (instance === "*") {
1040
+ for (const receive of instances.values()) receive(delivery);
1041
+ return;
1042
+ }
1043
+ instances.get(instance)?.(delivery);
1044
+ }
1045
+ async subscribe(instance, receive) {
1046
+ let instances = channels.get(this.channel);
1047
+ if (!instances) {
1048
+ instances = /* @__PURE__ */ new Map();
1049
+ channels.set(this.channel, instances);
1050
+ }
1051
+ instances.set(instance, receive);
1052
+ this.subscribed.add(instance);
1053
+ }
1054
+ async close() {
1055
+ const instances = channels.get(this.channel);
1056
+ for (const instance of this.subscribed) instances?.delete(instance);
1057
+ this.subscribed.clear();
1058
+ if (!instances?.size) limitStores.delete(this.channel);
1059
+ }
1060
+ limits() {
1061
+ let store = limitStores.get(this.channel);
1062
+ if (!store) {
1063
+ store = new MemoryLimitStore();
1064
+ limitStores.set(this.channel, store);
1065
+ }
1066
+ return store;
1067
+ }
1068
+ };
1069
+ /**
1070
+ * Over Redis pub/sub: one channel per instance and one for broadcasts, under
1071
+ * a prefix that keeps two surfaces — or two projects on one Redis — apart.
1072
+ * Channels are not scoped by database index, so the prefix is what does it.
1073
+ *
1074
+ * Publishing and subscribing take separate connections, because a connection
1075
+ * that has subscribed can do nothing else.
1076
+ */
1077
+ var RedisTransport = class {
1078
+ client;
1079
+ prefix;
1080
+ subscriber;
1081
+ closed;
1082
+ constructor(client, prefix) {
1083
+ this.client = client;
1084
+ this.prefix = prefix;
1085
+ }
1086
+ channel(instance) {
1087
+ return `${this.prefix}:${instance}`;
1088
+ }
1089
+ async publish(instance, delivery) {
1090
+ await this.client.publish(this.channel(instance), JSON.stringify(delivery));
1091
+ }
1092
+ async subscribe(instance, receive) {
1093
+ const subscriber = this.client.duplicate();
1094
+ this.subscriber = subscriber;
1095
+ const own = this.channel(instance);
1096
+ const every = this.channel("*");
1097
+ subscriber.on("message", (channel, message) => {
1098
+ if (channel !== own && channel !== every) return;
1099
+ receive(JSON.parse(message));
1100
+ });
1101
+ await subscriber.subscribe(own, every);
1102
+ }
1103
+ /** Counted in this Redis, under the transport's prefix. */
1104
+ limits() {
1105
+ return new RedisLimitStore(this.client, this.prefix);
1106
+ }
1107
+ /** Idempotent: the server and a shutdown hook may both close it. */
1108
+ close() {
1109
+ this.closed ??= Promise.all([this.subscriber?.quit(), this.client.quit()]).then(() => void 0);
1110
+ return this.closed;
1111
+ }
1112
+ };
1113
+ /**
1114
+ * The transport a connection string names.
1115
+ *
1116
+ * `redis://` and `rediss://` take an optional `channel` query parameter, the
1117
+ * prefix every channel is named under; `memory://<channel>` is in-process.
1118
+ * Absent, the channel is `fallback` — the surface's own.
1119
+ */
1120
+ async function transportFromConnectionString(connectionString, fallback) {
1121
+ if (connectionString.startsWith("memory://")) return new MemoryTransport(connectionString.slice(9) || fallback);
1122
+ const url = URL.canParse(connectionString) ? new URL(connectionString) : void 0;
1123
+ if (!url) throw new UnsupportedWebSocketTransport(connectionString);
1124
+ if (url.protocol === "redis:" || url.protocol === "rediss:") {
1125
+ const channel = url.searchParams.get("channel") || fallback;
1126
+ url.searchParams.delete("channel");
1127
+ const { Redis } = await loadIoredis();
1128
+ return new RedisTransport(new Redis(url.toString(), {
1129
+ maxRetriesPerRequest: null,
1130
+ lazyConnect: false
1131
+ }), channel);
1132
+ }
1133
+ throw new UnsupportedWebSocketTransport(connectionString);
1134
+ }
1135
+ //#endregion
1136
+ //#region src/websocket/server.ts
1137
+ /**
1138
+ * The Node adaptor: the process that holds a WebSocket surface's sockets.
1139
+ *
1140
+ * Node's own `http` server and `ws`, nothing between them. This owns what
1141
+ * only a real socket has — the upgrade, the Origin check, connection ids,
1142
+ * the heartbeat, backpressure, and the limits on what one client may ask of
1143
+ * it (`limits.ts`) — and hands the rest to the surface's `WebSocketCore`: a
1144
+ * handshake to `connect()`, each frame to `message()`, a close to
1145
+ * `disconnect()`. The HTTP server is whatever the entry started — the
1146
+ * generated one serves `/health` on the same port — and this attaches to its
1147
+ * `upgrade` event.
1148
+ */
1149
+ /** Close codes a client sees. */
1150
+ const CLOSE = {
1151
+ normal: 1e3,
1152
+ /**
1153
+ * It kept sending past its message rate, or its identity opened more
1154
+ * sockets than `limits.maxConnections` and this was the oldest.
1155
+ */
1156
+ policy: LIMIT_CLOSE.policy,
1157
+ /** The process is stopping; reconnect and land on another. */
1158
+ serviceRestart: 1012,
1159
+ /** It stopped reading, and what was queued for it passed the limit. */
1160
+ tooSlow: 1013
1161
+ };
1162
+ /** A handshake is counted as in flight for at most this long. */
1163
+ const IN_FLIGHT_TTL_MS = 3e4;
1164
+ var WebSocketSurfaceServer = class WebSocketSurfaceServer {
1165
+ wss;
1166
+ options;
1167
+ /** This process, as connection ids name it. */
1168
+ instance = randomBytes(6).toString("hex");
1169
+ /** Where each handshake, frame and close is handed. */
1170
+ core;
1171
+ held = /* @__PURE__ */ new Map();
1172
+ heartbeat;
1173
+ heartbeatMs;
1174
+ trusted;
1175
+ sink;
1176
+ limits;
1177
+ store;
1178
+ next = 0;
1179
+ closing = false;
1180
+ constructor(wss, options) {
1181
+ this.wss = wss;
1182
+ this.options = options;
1183
+ this.sink = new TransportSink(options.transport, {
1184
+ instance: this.instance,
1185
+ deliver: (delivery) => this.deliver(delivery)
1186
+ });
1187
+ this.core = options.core(this.sink);
1188
+ this.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];
1189
+ this.limits = options.limits ?? resolveLimits(this.core.surface);
1190
+ this.store = options.transport.limits?.() ?? new MemoryLimitStore();
1191
+ this.heartbeatMs = options.heartbeatMs ?? 3e4;
1192
+ this.heartbeat = setInterval(() => this.beat(), this.heartbeatMs);
1193
+ this.heartbeat.unref();
1194
+ }
1195
+ static async start(options) {
1196
+ const { WebSocketServer } = await loadWs();
1197
+ const wss = new WebSocketServer({
1198
+ noServer: true,
1199
+ maxPayload: options.maxPayload ?? 1048576,
1200
+ perMessageDeflate: false,
1201
+ clientTracking: false
1202
+ });
1203
+ const server = new WebSocketSurfaceServer(wss, options);
1204
+ await options.transport.subscribe(server.instance, (delivery) => server.deliver(delivery));
1205
+ return server;
1206
+ }
1207
+ /** `sockets` in a route: local sends skip the transport. */
1208
+ get publisher() {
1209
+ return this.core.sockets;
1210
+ }
1211
+ /** How many sockets this process holds. */
1212
+ get size() {
1213
+ return this.held.size;
1214
+ }
1215
+ /** Take over `server`'s upgrades. */
1216
+ attach(server) {
1217
+ server.on("upgrade", (request, socket, head) => {
1218
+ this.upgrade(request, socket, head);
1219
+ });
1220
+ }
1221
+ /**
1222
+ * Upgrade one request, or refuse it with a status line. The cheap checks
1223
+ * come first — the Origin, the client's handshake rate, its handshakes in
1224
+ * flight and its open sockets — so a flood is refused before the connect
1225
+ * handler, and the session lookup it makes, runs.
1226
+ */
1227
+ async upgrade(request, socket, head) {
1228
+ if (this.closing) return refuse(socket, 503, "Service Unavailable");
1229
+ const origin = request.headers.origin;
1230
+ if (origin ? !trustsOrigin(origin, this.trusted) : this.options.requireOrigin) return refuse(socket, 403, "Forbidden");
1231
+ const { limits } = this;
1232
+ const client = clientAddress(request);
1233
+ const connectionId = `${this.instance}.${(this.next++).toString(36)}`;
1234
+ if (limits.handshakesPerMinute) {
1235
+ const window = await this.guard(() => this.store.hit(`handshakes:${client}`, 6e4));
1236
+ if (window && window.count > limits.handshakesPerMinute) return tooMany(socket, window.resetMs);
1237
+ }
1238
+ const inFlight = {
1239
+ key: `in-flight:${client}`,
1240
+ member: connectionId
1241
+ };
1242
+ if (limits.inFlightHandshakes && !await this.claim(inFlight, limits.inFlightHandshakes, IN_FLIGHT_TTL_MS)) return tooMany(socket);
1243
+ const leases = [];
1244
+ const releaseAll = () => {
1245
+ for (const lease of leases.splice(0)) this.release(lease);
1246
+ };
1247
+ try {
1248
+ if (limits.connectionsPerIp) {
1249
+ const lease = {
1250
+ key: `ip:${client}`,
1251
+ member: connectionId
1252
+ };
1253
+ if (!await this.claim(lease, limits.connectionsPerIp)) return tooMany(socket);
1254
+ leases.push(lease);
1255
+ }
1256
+ const outcome = await this.core.connect({
1257
+ connectionId,
1258
+ headers: headersOf(request),
1259
+ query: new URL(request.url ?? "/", "http://localhost").searchParams
1260
+ });
1261
+ if (!outcome.accepted) {
1262
+ releaseAll();
1263
+ return refuse(socket, outcome.status, outcome.statusText);
1264
+ }
1265
+ const identity = limits.maxConnectionsPer?.(outcome.connection.data);
1266
+ if (identity !== void 0) {
1267
+ const lease = {
1268
+ key: `identity:${identity}`,
1269
+ member: connectionId
1270
+ };
1271
+ leases.push(lease);
1272
+ const held = await this.guard(() => this.store.hold(lease.key, lease.member, this.connectionTtl));
1273
+ if (held && held.length > limits.maxConnections) {
1274
+ if (limits.overflow === "refuse") {
1275
+ releaseAll();
1276
+ return tooMany(socket);
1277
+ }
1278
+ const oldest = held.filter((id) => id !== connectionId).slice(0, held.length - limits.maxConnections);
1279
+ for (const id of oldest) this.release({
1280
+ key: lease.key,
1281
+ member: id
1282
+ });
1283
+ await this.guard(() => this.sink.close(oldest, CLOSE.policy, "Too many connections"));
1284
+ }
1285
+ }
1286
+ if (socket.destroyed) return releaseAll();
1287
+ const opened = leases.splice(0);
1288
+ this.wss.handleUpgrade(request, socket, head, (ws) => this.open(ws, outcome.connection, opened));
1289
+ } finally {
1290
+ if (limits.inFlightHandshakes) this.release(inFlight);
1291
+ }
1292
+ }
1293
+ open(socket, connection, leases) {
1294
+ const { messagesPerSecond, burst } = this.limits;
1295
+ const held = {
1296
+ socket,
1297
+ connection,
1298
+ alive: true,
1299
+ leases,
1300
+ warned: false,
1301
+ ...messagesPerSecond ? { bucket: new TokenBucket(messagesPerSecond, burst) } : {}
1302
+ };
1303
+ this.held.set(connection.id, held);
1304
+ const write = (payload) => this.write(held, payload);
1305
+ socket.on("pong", () => {
1306
+ held.alive = true;
1307
+ });
1308
+ socket.on("message", (raw, isBinary) => {
1309
+ held.alive = true;
1310
+ if (!this.admit(held)) return;
1311
+ this.core.message(connection, isBinary ? bytesOf(raw) : raw.toString(), write);
1312
+ });
1313
+ socket.on("error", () => socket.terminate());
1314
+ socket.on("close", (code, reason) => {
1315
+ this.held.delete(connection.id);
1316
+ for (const lease of held.leases.splice(0)) this.release(lease);
1317
+ this.core.disconnect(connection, {
1318
+ code,
1319
+ reason: reason.toString()
1320
+ });
1321
+ });
1322
+ }
1323
+ /**
1324
+ * Whether a frame is within its socket's budget. The first past it is
1325
+ * answered with one `$error`; another before the budget has refilled
1326
+ * closes the socket with 1008.
1327
+ */
1328
+ admit(held) {
1329
+ const { bucket } = held;
1330
+ if (!bucket) return true;
1331
+ if (bucket.take()) {
1332
+ if (held.warned && bucket.full) held.warned = false;
1333
+ return true;
1334
+ }
1335
+ if (held.socket.readyState !== held.socket.OPEN) return false;
1336
+ if (held.warned) {
1337
+ held.socket.close(CLOSE.policy, "Too many messages");
1338
+ return false;
1339
+ }
1340
+ held.warned = true;
1341
+ this.write(held, this.core.frame.encode("$error", { message: `Too many messages: at most ${this.limits.messagesPerSecond} a second, ${this.limits.burst} at once. Frames are dropped until the socket slows down, and it is closed if it keeps sending.` }));
1342
+ return false;
1343
+ }
1344
+ /**
1345
+ * Take a place in `lease`'s count — or none, when that would put it past
1346
+ * `max`. A store that cannot be reached lets the handshake through.
1347
+ */
1348
+ async claim(lease, max, ttlMs = this.connectionTtl) {
1349
+ const held = await this.guard(() => this.store.hold(lease.key, lease.member, ttlMs));
1350
+ if (!held || held.length <= max) return true;
1351
+ this.release(lease);
1352
+ return false;
1353
+ }
1354
+ release(lease) {
1355
+ this.guard(() => this.store.release(lease.key, lease.member));
1356
+ }
1357
+ /**
1358
+ * How long a socket's place in a count outlives its process, should it
1359
+ * die without giving it back: three heartbeats, each of which renews it.
1360
+ */
1361
+ get connectionTtl() {
1362
+ return this.heartbeatMs * 3;
1363
+ }
1364
+ /** The store's answer — or nothing, logged, when it fails. */
1365
+ async guard(call) {
1366
+ try {
1367
+ return await call();
1368
+ } catch (err) {
1369
+ this.options.logger?.warn({ err }, "WebSocket limit store failed; the limit was not applied");
1370
+ return;
1371
+ }
1372
+ }
1373
+ /** Write, unless the socket has stopped reading and its queue is full. */
1374
+ write(held, payload) {
1375
+ const { socket } = held;
1376
+ if (socket.readyState !== socket.OPEN) return;
1377
+ if (socket.bufferedAmount > (this.options.maxBufferedBytes ?? 4194304)) {
1378
+ socket.close(CLOSE.tooSlow, "Too slow");
1379
+ return;
1380
+ }
1381
+ socket.send(payload);
1382
+ }
1383
+ /** What the transport, or a local publisher, asked of this process. */
1384
+ deliver(delivery) {
1385
+ switch (delivery.kind) {
1386
+ case "send":
1387
+ for (const id of delivery.ids) {
1388
+ const held = this.held.get(id);
1389
+ if (held) this.write(held, delivery.payload);
1390
+ }
1391
+ return;
1392
+ case "broadcast": {
1393
+ const except = delivery.except ? new Set(delivery.except) : void 0;
1394
+ for (const [id, held] of this.held) if (!except?.has(id)) this.write(held, delivery.payload);
1395
+ return;
1396
+ }
1397
+ case "close":
1398
+ for (const id of delivery.ids) this.held.get(id)?.socket.close(delivery.code, delivery.reason);
1399
+ return;
1400
+ }
1401
+ }
1402
+ /**
1403
+ * Drop every socket that missed the last ping, and ping the rest — whose
1404
+ * places in the limits' counts are renewed.
1405
+ */
1406
+ beat() {
1407
+ const renewed = [];
1408
+ for (const [id, held] of this.held) {
1409
+ if (!held.alive) {
1410
+ held.socket.terminate();
1411
+ this.held.delete(id);
1412
+ continue;
1413
+ }
1414
+ held.alive = false;
1415
+ held.socket.ping();
1416
+ renewed.push(...held.leases);
1417
+ }
1418
+ if (renewed.length > 0) this.guard(() => this.store.renew(renewed, this.connectionTtl));
1419
+ }
1420
+ /**
1421
+ * Stop: refuse new upgrades, close every socket with `code` — 1012 tells
1422
+ * a client to reconnect, and it lands on a process that is still up — and
1423
+ * leave the transport.
1424
+ */
1425
+ async close(code = CLOSE.serviceRestart, reason = "Restarting") {
1426
+ if (this.closing) return;
1427
+ this.closing = true;
1428
+ clearInterval(this.heartbeat);
1429
+ const closed = [...this.held.values()].map(({ socket }) => new Promise((resolve) => {
1430
+ if (socket.readyState === socket.CLOSED) return resolve();
1431
+ socket.once("close", () => resolve());
1432
+ socket.close(code, reason);
1433
+ setTimeout(() => {
1434
+ socket.terminate();
1435
+ resolve();
1436
+ }, 2e3).unref();
1437
+ }));
1438
+ await Promise.all(closed);
1439
+ await this.options.transport.close();
1440
+ this.wss.close();
1441
+ }
1442
+ };
1443
+ /** A binary frame's bytes, however `ws` delivered them. */
1444
+ function bytesOf(raw) {
1445
+ if (Array.isArray(raw)) return Buffer.concat(raw);
1446
+ return raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;
1447
+ }
1448
+ function headersOf(request) {
1449
+ const headers = new Headers();
1450
+ for (const [name, value] of Object.entries(request.headers)) {
1451
+ if (value === void 0) continue;
1452
+ for (const one of Array.isArray(value) ? value : [value]) headers.append(name, one);
1453
+ }
1454
+ return headers;
1455
+ }
1456
+ function refuse(socket, status, message, headers = {}) {
1457
+ if (!socket.destroyed) {
1458
+ const extra = Object.entries(headers).map(([name, value]) => `${name}: ${value}\r\n`).join("");
1459
+ socket.end(`HTTP/1.1 ${status} ${message}\r\n${extra}Connection: close\r\nContent-Length: 0\r\n\r\n`);
1460
+ }
1461
+ }
1462
+ /** 429 — with when to come back, where a window says. */
1463
+ function tooMany(socket, retryAfterMs) {
1464
+ refuse(socket, 429, "Too Many Requests", retryAfterMs === void 0 ? {} : { "Retry-After": String(Math.max(1, Math.ceil(retryAfterMs / 1e3))) });
1465
+ }
1466
+ //#endregion
1467
+ //#region src/websocket-api.ts
1468
+ /** A replica count that is not a whole number of at least one. */
1469
+ var InvalidReplicaCount = class extends Error {
1470
+ id;
1471
+ replicas;
1472
+ constructor(id, replicas) {
1473
+ super(`${id} asks for ${replicas} replicas. A surface runs on at least one process — give a whole number of 1 or more.`);
1474
+ this.id = id;
1475
+ this.replicas = replicas;
1476
+ this.name = "InvalidReplicaCount";
1477
+ }
1478
+ };
1479
+ var WebSocketApi = class WebSocketApi {
1480
+ config;
1481
+ authenticator;
1482
+ id;
1483
+ keys;
1484
+ logger;
1485
+ envParser;
1486
+ telemetry;
1487
+ /**
1488
+ * The shape its frames take — `{ action, data }`, or flat under
1489
+ * `discriminator`. What a client of the surface decodes by.
1490
+ */
1491
+ frame;
1492
+ /** What one client may ask of it, defaults filled in. */
1493
+ limits;
1494
+ /**
1495
+ * The surface as a dependency: `services.<id>` is its publisher, so an
1496
+ * endpoint sends to a socket the way a route beside it does.
1497
+ */
1498
+ service;
1499
+ constructor(id, config, authenticator) {
1500
+ this.config = config;
1501
+ this.authenticator = authenticator;
1502
+ const canonical = canonicalId(id);
1503
+ this.id = canonical;
1504
+ assertHostLabels({
1505
+ id: canonical,
1506
+ ...config.subdomain ? { subdomain: config.subdomain } : {},
1507
+ ...config.aliases ? { aliases: config.aliases } : {}
1508
+ });
1509
+ const replicas = config.replicas ?? 1;
1510
+ if (!Number.isInteger(replicas) || replicas < 1) throw new InvalidReplicaCount(canonical, replicas);
1511
+ const frame = new FrameShape(canonical, config.frame?.discriminator);
1512
+ if (config.messages) frame.check(config.messages);
1513
+ this.frame = config.frame ? { discriminator: config.frame.discriminator } : {};
1514
+ this.limits = resolveLimits(canonical, config.limits);
1515
+ this.keys = {
1516
+ url: providedKeyFor(canonical, "websocket-api", "url"),
1517
+ trustedOrigins: providedKeyFor(canonical, "websocket-api", "trustedOrigins"),
1518
+ publisherConnectionString: providedKeyFor(canonical, "websocket-api", "publisherConnectionString")
1519
+ };
1520
+ this.logger = config.logger ?? DEFAULT_LOGGER;
1521
+ this.telemetry = config.telemetry;
1522
+ this.envParser = envParserFor(config.envParser ? {
1523
+ id: canonical,
1524
+ envParser: config.envParser
1525
+ } : void 0);
1526
+ const envVar = this.keys.publisherConnectionString;
1527
+ const channel = channelOf(canonical);
1528
+ this.service = {
1529
+ serviceName: serviceKey(canonical),
1530
+ register: async ({ envParser }) => {
1531
+ const { connectionString } = envParser.create((get) => ({ connectionString: get(envVar).string() })).parse();
1532
+ return this.publisher(await sinkFromConnectionString(this.id, connectionString, channel));
1533
+ }
1534
+ };
1535
+ }
1536
+ /** The handler a connection's upgrade runs: refuse it, or say who it is. */
1537
+ connect() {
1538
+ return new WebSocketRouteBuilder("connect", "$connect", this);
1539
+ }
1540
+ /** The handler a closed connection runs. */
1541
+ disconnect() {
1542
+ return new WebSocketRouteBuilder("disconnect", "$disconnect", this);
1543
+ }
1544
+ /**
1545
+ * The handler for frames whose `action` — or, for flat frames, whose
1546
+ * discriminator — is `action`. `$default` answers
1547
+ * any action nothing else does.
1548
+ */
1549
+ route(action) {
1550
+ return new WebSocketRouteBuilder("message", action, this);
1551
+ }
1552
+ /** What authenticates a connection — its session reaches `connect()`. */
1553
+ auth(construct) {
1554
+ return new WebSocketApi(this.id, this.config, construct);
1555
+ }
1556
+ /**
1557
+ * Serve it: the routes exported by `modules` that were built from this
1558
+ * surface, on whatever HTTP server `attach` is handed.
1559
+ *
1560
+ * `app` answers plain HTTP — the generated entry puts `/health` in front
1561
+ * of it — and `attach` takes over the server's upgrades. The sockets are
1562
+ * closed with 1012 when the server shuts down.
1563
+ */
1564
+ async server(options) {
1565
+ const { Hono } = await loadHono("A WebSocketApi");
1566
+ const { connectionString, origins, url } = options.envParser.create((get) => ({
1567
+ connectionString: get(this.keys.publisherConnectionString).string().default(`memory://${channelOf(this.id)}`),
1568
+ origins: get(this.keys.trustedOrigins).string().default("").transform((value) => value.split(",").map((origin) => origin.trim()).filter(Boolean)),
1569
+ url: get(this.keys.url).string().optional()
1570
+ })).parse();
1571
+ const server = await WebSocketSurfaceServer.start({
1572
+ core: (sink) => this.core({
1573
+ envParser: options.envParser,
1574
+ sink,
1575
+ ...options.modules ? { modules: options.modules } : {}
1576
+ }),
1577
+ transport: await transportFromConnectionString(connectionString, channelOf(this.id)),
1578
+ trustedOrigins: origins,
1579
+ ...this.config.requireOrigin ? { requireOrigin: true } : {},
1580
+ limits: this.limits,
1581
+ logger: this.logger,
1582
+ ...url ? { url } : {},
1583
+ ...this.config.heartbeat ? { heartbeatMs: this.config.heartbeat * 1e3 } : {},
1584
+ ...this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}
1585
+ });
1586
+ onShutdown(() => server.close());
1587
+ const app = new Hono();
1588
+ app.get("/health", (c) => c.json({
1589
+ status: "ok",
1590
+ connections: server.size
1591
+ }));
1592
+ app.get("/", (c) => c.json({
1593
+ surface: this.id,
1594
+ connections: server.size
1595
+ }, 426, { Upgrade: "websocket" }));
1596
+ return {
1597
+ app,
1598
+ attach: (http) => server.attach(http),
1599
+ release: () => server.close(),
1600
+ server
1601
+ };
1602
+ }
1603
+ /**
1604
+ * The surface with no socket in it — what every runtime serves. The
1605
+ * routes exported by `modules` that were built from this surface answer
1606
+ * its frames; `sink` is where its handlers' `sockets` send.
1607
+ *
1608
+ * `server()` is the Node adaptor over it. Another runtime (a Lambda
1609
+ * behind API Gateway, a test) builds one with a sink of its own and
1610
+ * calls `connect()`, `message()` and `disconnect()` per connection id.
1611
+ *
1612
+ * @throws {DuplicateWebSocketRoute} when two routes answer one action.
1613
+ */
1614
+ core(options) {
1615
+ return new WebSocketCore({
1616
+ surface: this.id,
1617
+ routes: (options.modules ?? []).flatMap((module) => Object.values(module).filter(WebSocketRoute.isRoute)),
1618
+ sink: options.sink,
1619
+ envParser: options.envParser,
1620
+ logger: this.logger,
1621
+ ...this.config.frame ? { frame: this.config.frame } : {},
1622
+ ...this.declared ? { messages: this.declared.messages } : {},
1623
+ ...this.authenticator ? { authenticator: this.authenticator } : {}
1624
+ });
1625
+ }
1626
+ /**
1627
+ * The surface's publisher over `sink` — typed, checked and encoded as
1628
+ * `services.<id>` is. What an adaptor with a sink of its own (MSW, a
1629
+ * Lambda) hands the code that sends to its connections.
1630
+ */
1631
+ publisher(sink) {
1632
+ return new WebSocketPublisher(sink, this.declared, new FrameShape(this.id, this.config.frame?.discriminator));
1633
+ }
1634
+ /**
1635
+ * A publisher of the type `services.<id>` is, that records rather than
1636
+ * sends — hand it to an endpoint's spec, or to a route's `request()` as
1637
+ * `sockets`, and assert on `sent`, `broadcasts` and `closed`.
1638
+ *
1639
+ * Every send is checked by the declared `messages` and encoded by `frame`,
1640
+ * as deployed: an invalid push rejects, and each record carries the
1641
+ * frame a client would parse.
1642
+ *
1643
+ * ```ts
1644
+ * const realtime = surface.testPublisher();
1645
+ * await sendMessage.request({ services: { realtime }, … });
1646
+ * expect(realtime.sent).toEqual([
1647
+ * { ids: ['a.1'], action: 'chat.sent', data: { text: 'hi' }, frame: … },
1648
+ * ]);
1649
+ * ```
1650
+ */
1651
+ testPublisher() {
1652
+ return new TestWebSocketPublisher(new FrameShape(this.id, this.config.frame?.discriminator), this.declared);
1653
+ }
1654
+ /**
1655
+ * The per-address limits the edge in front of it enforces too, so a
1656
+ * flood is refused before it reaches a replica.
1657
+ */
1658
+ get edgeLimits() {
1659
+ const { handshakesPerMinute, connectionsPerIp } = this.limits;
1660
+ if (!handshakesPerMinute && !connectionsPerIp) return void 0;
1661
+ return {
1662
+ ...handshakesPerMinute ? { handshakesPerMinute } : {},
1663
+ ...connectionsPerIp ? { connectionsPerIp } : {}
1664
+ };
1665
+ }
1666
+ /** The declared messages, with the surface they are checked for. */
1667
+ get declared() {
1668
+ return this.config.messages ? {
1669
+ surface: this.id,
1670
+ messages: this.config.messages
1671
+ } : void 0;
1672
+ }
1673
+ declare() {
1674
+ return [{
1675
+ kind: "websocket-api",
1676
+ id: this.id,
1677
+ path: this.config.path,
1678
+ ...this.config.subdomain ? { subdomain: this.config.subdomain } : {},
1679
+ ...this.config.aliases?.length ? { aliases: [...this.config.aliases] } : {},
1680
+ ...this.config.frame?.discriminator ? { discriminator: this.config.frame.discriminator } : {},
1681
+ ...this.authenticator ? { auth: edgeTo(this.authenticator) } : {},
1682
+ ...this.config.telemetry ? { telemetry: this.config.telemetry.id } : {},
1683
+ ...this.config.replicas && this.config.replicas > 1 ? { replicas: this.config.replicas } : {},
1684
+ ...this.edgeLimits ? { limits: this.edgeLimits } : {},
1685
+ provides: [
1686
+ this.keys.url,
1687
+ this.keys.trustedOrigins,
1688
+ this.keys.publisherConnectionString
1689
+ ]
1690
+ }];
1691
+ }
1692
+ };
1693
+ /**
1694
+ * Where `services.<surface>` sends, by the publisher string's scheme: a
1695
+ * registered driver's sink — API Gateway's management API on an AWS stage,
1696
+ * registered by the build's entry — or else whichever process holds the
1697
+ * sockets (`redis://`, `memory://`).
1698
+ *
1699
+ * @throws {UnregisteredWebSocketScheme} for `apigateway://` with no driver.
1700
+ */
1701
+ async function sinkFromConnectionString(surface, connectionString, channel) {
1702
+ const driver = webSocketSinkDriverFor(connectionString);
1703
+ if (driver) return driver.sink(connectionString);
1704
+ if (connectionString.startsWith(API_GATEWAY_WEBSOCKET_SCHEME)) throw new UnregisteredWebSocketScheme(surface, API_GATEWAY_WEBSOCKET_SCHEME);
1705
+ const transport = await transportFromConnectionString(connectionString, channel);
1706
+ onShutdown(() => transport.close());
1707
+ return new TransportSink(transport);
1708
+ }
1709
+ /** The prefix a surface's channels are named under. */
1710
+ function channelOf(id) {
1711
+ return `gkm:ws:${id}`;
1712
+ }
1713
+ //#endregion
1714
+ export { WebSocketMessageDeclaresDiscriminator as A, DuplicateWebSocketRoute as C, WebSocketPublisher as D, UnknownWebSocketMessage as E, WebSocketDataHasDiscriminator as O, resolveLimits as S, InvalidWebSocketMessage as T, InvalidWebSocketLimit as _, WebSocketSurfaceServer as a, RedisLimitStore as b, TransportSink as c, WebSocketRoute as d, WebSocketRouteBuilder as f, DEFAULT_WEBSOCKET_LIMITS as g, TestWebSocketPublisher as h, CLOSE as i, WebSocketMessageNotAnObject as j, WebSocketDataNotAnObject as k, UnsupportedWebSocketTransport as l, RecordingSink as m, InvalidReplicaCount as n, MemoryTransport as o, InvalidWebSocketRequest as p, WebSocketApi as r, RedisTransport as s, InvalidHostLabel as t, transportFromConnectionString as u, LIMIT_CLOSE as v, WebSocketCore as w, TokenBucket as x, MemoryLimitStore as y };
1715
+
1716
+ //# sourceMappingURL=websocket-api-C6LGg9-D.mjs.map