@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
@@ -1,21 +1,64 @@
1
- import { t as FunctionBuilder } from "../functions-C53GW2eQ.mjs";
2
- import { n as ResponseBuilder, t as Endpoint } from "../Endpoint-ONsly_dq.mjs";
3
- import { c as createObjectHeaders, l as publishConstructEvents, r as createCookieHeaderAccessor, u as publishEvents } from "../lazyAccessors-BHtcqgz2.mjs";
4
- import { t as HonoEndpoint } from "../HonoEndpointAdaptor-yYaU7jVJ.mjs";
5
- import { n as executeWithAuditTransaction } from "../processAudits-BpRlPQMW.mjs";
1
+ import { isConsumable } from "../construct-interface.mjs";
2
+ import { n as loadAudit, t as OptionalPeerMissing } from "../optionalPeers-D7Wt6dnF.mjs";
3
+ import { BetterAuth } from "../auth.mjs";
4
+ import { a as publishEvents, i as publishConstructEvents, t as FunctionBuilder } from "../functions-BvIDQKAA.mjs";
5
+ import { r as ResponseBuilder, t as Endpoint } from "../Endpoint-sUOU7uLx.mjs";
6
+ import { c as TransportSink, h as TestWebSocketPublisher, o as MemoryTransport, p as InvalidWebSocketRequest, r as WebSocketApi } from "../websocket-api-C6LGg9-D.mjs";
7
+ import { t as Queue } from "../Queue-9Hh20ZCk.mjs";
8
+ import { Email } from "../email.mjs";
9
+ import { t as Topic } from "../Topic-BGoOeCT6.mjs";
10
+ import { t as KyselyDatabase } from "../kysely-Bc9xzaik.mjs";
11
+ import { f as createObjectHeaders, s as createCookieHeaderAccessor } from "../readRequestBody-BmKnPl0a.mjs";
12
+ import { t as HonoEndpoint } from "../HonoEndpointAdaptor-CBVey2cY.mjs";
13
+ import { i as executeWithAuditTransaction, n as enforceRateLimit, t as requestLogger } from "../requestLogger-D2JS7pPM.mjs";
14
+ import { INBOX_EVENT, WILDCARD_SUBDOMAIN, inboxRecipient, providedKeyFor } from "@geekmidas/manifest";
15
+ import { randomUUID } from "node:crypto";
16
+ import { ServiceDiscovery, currentRequestContext, runWithRequestContext, serviceContext } from "@geekmidas/services";
6
17
  import { ForbiddenError } from "@geekmidas/errors";
7
18
  import { EnvironmentParser } from "@geekmidas/envkit";
8
- import { ServiceDiscovery, runWithRequestContext } from "@geekmidas/services";
9
19
  import { Hono } from "hono";
10
- import { DefaultAuditor } from "@geekmidas/audit";
11
- import { http } from "msw";
12
- //#region src/endpoints/MswEndpointAdaptor.ts
20
+ import { TEST_CONTEXT_HEADER, currentTestContext, installContextFetch, runAsServer, runInTestContext, testContextOf } from "@geekmidas/testkit/context";
21
+ import { http, ws } from "msw";
22
+ import { Browser } from "@geekmidas/testkit/browser";
23
+ import { faker } from "@geekmidas/testkit/faker";
24
+ import { createMailbox } from "@geekmidas/testkit/mailbox";
25
+ import { TransactionRegistry } from "@geekmidas/testkit/transactions";
26
+ import { setupServer } from "msw/node";
27
+ import { afterAll, beforeAll, test } from "vitest";
28
+ import { existsSync, readFileSync } from "node:fs";
29
+ import tls from "node:tls";
30
+ import { fileURLToPath } from "node:url";
31
+ //#region src/testing/peer.ts
13
32
  /**
14
- * Header used to identify which test context a request belongs to.
15
- * Each concurrent test registers its own context (services, db transaction, etc.)
16
- * and the MSW handler looks it up by this header value.
33
+ * The TCP peer a test's in-process requests arrive from.
34
+ *
35
+ * A feature test hands a request straight to a surface's Hono app — no
36
+ * socket, no server — so the app's bindings have no peer to read. Deployed,
37
+ * every request has one, and what a surface trusts follows from it: the auth
38
+ * server honours `x-gkm-client-ip` only from an internal caller, a loopback
39
+ * or private peer with no `Origin` and no forwarding header. With no peer at
40
+ * all the header was dropped, and every test's session check became the same
41
+ * client to Better Auth's rate limiter.
42
+ *
43
+ * So an in-process dispatch says where it came from, the way
44
+ * `@hono/node-server` does: its bindings carry `incoming.socket.remoteAddress`.
45
+ * The address is loopback because that is the truth — the request came from
46
+ * this process. A browser's own address still travels in its
47
+ * `x-forwarded-for`, which makes it outside traffic exactly as it would be
48
+ * behind the stack's proxy.
49
+ *
50
+ * Only a test's dispatch passes these. A runtime with no socket of its own
51
+ * (Lambda, Bun) still has no peer, and a request with no peer is still not an
52
+ * internal caller's.
17
53
  */
18
- const TEST_CONTEXT_HEADER = "x-test-context-id";
54
+ /** The address an in-process request presents as its peer. */
55
+ const IN_PROCESS_PEER_ADDRESS = "127.0.0.1";
56
+ /** Bindings for `app.fetch(request, bindings)` from inside this process. */
57
+ function inProcessBindings() {
58
+ return { incoming: { socket: { remoteAddress: IN_PROCESS_PEER_ADDRESS } } };
59
+ }
60
+ //#endregion
61
+ //#region src/endpoints/MswEndpointAdaptor.ts
19
62
  const MSW_HTTP_METHODS = [
20
63
  "get",
21
64
  "post",
@@ -63,7 +106,6 @@ function createMswHandlers(endpoints, options) {
63
106
  break;
64
107
  }
65
108
  }
66
- if (ctxOptions.publisher) serviceDefs.push(ctxOptions.publisher);
67
109
  if (ctxOptions.auditorStorage !== void 0) {
68
110
  for (const endpoint of endpoints) if (endpoint.auditorStorageService) {
69
111
  serviceDefs.push({
@@ -94,7 +136,7 @@ function createMswHandlers(endpoints, options) {
94
136
  });
95
137
  const app = new Hono();
96
138
  HonoEndpoint.addRoute(endpoint, ctx.serviceDiscovery, app);
97
- const response = await app.request(request);
139
+ const response = await app.request(request, void 0, inProcessBindings());
98
140
  return new Response(response.body, {
99
141
  status: response.status,
100
142
  statusText: response.statusText,
@@ -143,17 +185,17 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
143
185
  const cookie = createCookieHeaderAccessor(ctx.headers.cookie);
144
186
  const startTime = Date.now();
145
187
  const requestId = ctx.requestId ?? ctx.headers["x-request-id"] ?? crypto.randomUUID();
146
- const logger = this.endpoint.logger.child({
188
+ let logger = requestLogger(this.endpoint, {
147
189
  requestId,
148
- route: this.endpoint.route,
149
- host: ctx.headers.host,
150
- method: this.endpoint.method
190
+ host: ctx.headers.host
151
191
  });
152
192
  const rawDb = ctx.database;
193
+ const operation = `${this.endpoint.method} ${this.endpoint.route}`;
153
194
  return runWithRequestContext({
154
195
  logger,
155
196
  requestId,
156
- startTime
197
+ startTime,
198
+ operation
157
199
  }, async () => {
158
200
  const session = await this.endpoint.getSession({
159
201
  logger,
@@ -162,6 +204,7 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
162
204
  cookie,
163
205
  ...rawDb !== void 0 && { db: rawDb }
164
206
  });
207
+ logger = currentRequestContext()?.logger ?? logger;
165
208
  if (!await this.endpoint.authorize({
166
209
  header,
167
210
  cookie,
@@ -176,6 +219,14 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
176
219
  logger.warn("Forbidden access attempt");
177
220
  throw new ForbiddenError("Forbidden access to the endpoint", "You do not have permission to access this resource.");
178
221
  }
222
+ const rateLimitHeaders = this.endpoint.rateLimit ? await enforceRateLimit(this.endpoint.rateLimit, {
223
+ header,
224
+ services: ctx.services,
225
+ logger,
226
+ session,
227
+ path: this.endpoint.route,
228
+ method: this.endpoint.method
229
+ }) : {};
179
230
  const auditorStorage = ctx.auditorStorage;
180
231
  let auditContext;
181
232
  if (auditorStorage) {
@@ -194,6 +245,7 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
194
245
  } catch (error) {
195
246
  logger.error(error, "Failed to extract actor for audits");
196
247
  }
248
+ const { DefaultAuditor } = await loadAudit();
197
249
  auditContext = {
198
250
  auditor: new DefaultAuditor({
199
251
  actor,
@@ -208,7 +260,7 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
208
260
  }
209
261
  const audits = this.endpoint.audits;
210
262
  if (!auditContext && audits?.length) logger.warn("No auditor storage service available");
211
- const { output, metadata } = await executeWithAuditTransaction(auditContext, async (auditor) => {
263
+ const { output, metadata, redirect } = await executeWithAuditTransaction(auditContext, async (auditor) => {
212
264
  const db = auditor?.getTransaction?.() ?? rawDb;
213
265
  const responseBuilder = new ResponseBuilder();
214
266
  const response = await this.endpoint.handler({
@@ -229,13 +281,15 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
229
281
  data = response.data;
230
282
  metadata = response.metadata;
231
283
  }
284
+ const redirect = Endpoint.isRedirectStatus(metadata.status ?? this.endpoint.status);
232
285
  return {
233
- output: await this.endpoint.parseOutput(data),
286
+ output: redirect ? void 0 : await this.endpoint.parseOutput(data),
234
287
  metadata,
235
- responseBuilder
288
+ responseBuilder,
289
+ redirect
236
290
  };
237
291
  }, async (result, auditor) => {
238
- if (!audits?.length) return;
292
+ if (!audits?.length || result.redirect) return;
239
293
  for (const audit of audits) {
240
294
  if (audit.when && !audit.when(result.output)) continue;
241
295
  const payload = audit.payload(result.output);
@@ -246,9 +300,11 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
246
300
  });
247
301
  }
248
302
  }, { db: rawDb });
249
- ctx.publisher && await this.serviceDiscovery.register([ctx.publisher]);
250
- await publishConstructEvents(this.endpoint, output, this.serviceDiscovery);
251
- const headers = { ...metadata.headers || {} };
303
+ if (!redirect) await publishConstructEvents(this.endpoint, output, this.serviceDiscovery, this.endpoint.logger, ctx.services);
304
+ const headers = {
305
+ ...rateLimitHeaders,
306
+ ...metadata.headers || {}
307
+ };
252
308
  if (metadata.cookies && metadata.cookies.size > 0) {
253
309
  const setCookieValues = [];
254
310
  for (const [name, cookie] of metadata.cookies.entries()) setCookieValues.push(serializeCookie(name, cookie.value, cookie.options));
@@ -256,7 +312,7 @@ var TestEndpointAdaptor = class TestEndpointAdaptor {
256
312
  }
257
313
  return {
258
314
  body: output,
259
- status: metadata.status || 200,
315
+ status: metadata.status ?? this.endpoint.status,
260
316
  headers
261
317
  };
262
318
  });
@@ -290,6 +346,7 @@ var TestFunctionAdaptor = class TestFunctionAdaptor {
290
346
  if ("auditor" in ctx && ctx.auditor !== void 0) auditor = ctx.auditor;
291
347
  else if (this.fn.auditorStorageService) {
292
348
  const storage = (await this.serviceDiscovery.register([this.fn.auditorStorageService]))[this.fn.auditorStorageService.serviceName];
349
+ const { DefaultAuditor } = await loadAudit();
293
350
  auditor = new DefaultAuditor({
294
351
  actor: {
295
352
  id: "system",
@@ -323,7 +380,7 @@ var TestFunctionAdaptor = class TestFunctionAdaptor {
323
380
  await auditor.flush();
324
381
  }
325
382
  }
326
- await publishEvents(logger, this.serviceDiscovery, this.fn.events, output, this.fn.publisherService);
383
+ await publishEvents(logger, this.serviceDiscovery, this.fn.events, output, services);
327
384
  return output;
328
385
  });
329
386
  }
@@ -333,7 +390,8 @@ var TestFunctionAdaptor = class TestFunctionAdaptor {
333
390
  /**
334
391
  * In-memory test driver for a {@link Queue} worker. Hand it a batch of messages
335
392
  * and it registers the queue's services, runs the handler in a request context,
336
- * and returns the handler result — no SQS/pg-boss required.
393
+ * and returns the handler result — no SQS/pg-boss required. A queue with a
394
+ * database gets `db` registered from it, or the one the request passes.
337
395
  *
338
396
  * @example
339
397
  * const adapter = new TestQueueAdaptor(ordersQueue);
@@ -352,17 +410,27 @@ var TestQueueAdaptor = class TestQueueAdaptor {
352
410
  async invoke(request) {
353
411
  const logger = this.queue.logger.child({ test: true });
354
412
  const services = request.services ?? await this.serviceDiscovery.register(this.queue.services);
413
+ const db = request.db !== void 0 ? request.db : await this.getDatabase();
355
414
  const requestId = `test-${Date.now()}`;
415
+ const startTime = Date.now();
416
+ const operation = `queue ${this.queue.name}`;
356
417
  return runWithRequestContext({
357
418
  logger,
358
419
  requestId,
359
- startTime: Date.now()
420
+ startTime,
421
+ operation
360
422
  }, () => this.queue.handler({
361
423
  messages: request.messages,
362
424
  services,
363
- logger
425
+ logger,
426
+ db
364
427
  }));
365
428
  }
429
+ async getDatabase() {
430
+ const service = this.queue.databaseService;
431
+ if (!service) return void 0;
432
+ return (await this.serviceDiscovery.register([service]))[service.serviceName];
433
+ }
366
434
  };
367
435
  //#endregion
368
436
  //#region src/subscribers/TestSubscriberAdaptor.ts
@@ -381,18 +449,23 @@ var TestSubscriberAdaptor = class TestSubscriberAdaptor {
381
449
  let services;
382
450
  if (request.services) services = request.services;
383
451
  else services = await this.serviceDiscovery.register(this.subscriber.services);
452
+ const db = request.db !== void 0 ? request.db : await this.getDatabase();
384
453
  const filteredEvents = this.filterEvents(request.events);
385
454
  if (filteredEvents.length === 0) return { batchItemFailures: [] };
386
455
  const requestId = `test-${Date.now()}`;
456
+ const startTime = Date.now();
457
+ const operation = `subscriber ${this.subscriber.topicName ?? "test"}`;
387
458
  return runWithRequestContext({
388
459
  logger,
389
460
  requestId,
390
- startTime: Date.now()
461
+ startTime,
462
+ operation
391
463
  }, async () => {
392
464
  const result = await this.subscriber.handler({
393
465
  events: filteredEvents,
394
466
  services,
395
- logger
467
+ logger,
468
+ db
396
469
  });
397
470
  let output = result;
398
471
  if (this.subscriber.outputSchema && result) {
@@ -400,16 +473,1047 @@ var TestSubscriberAdaptor = class TestSubscriberAdaptor {
400
473
  if (validationResult.issues) throw new Error("Subscriber output validation failed");
401
474
  output = validationResult.value;
402
475
  }
403
- await publishEvents(logger, this.serviceDiscovery, this.subscriber.events, output, this.subscriber.publisherService);
404
476
  return output;
405
477
  });
406
478
  }
479
+ async getDatabase() {
480
+ const service = this.subscriber.databaseService;
481
+ if (!service) return void 0;
482
+ return (await this.serviceDiscovery.register([service]))[service.serviceName];
483
+ }
407
484
  filterEvents(events) {
408
485
  if (!this.subscriber.subscribedEvents) return events;
409
486
  return events.filter((event) => this.subscriber.subscribedEvents.includes(event.type));
410
487
  }
411
488
  };
412
489
  //#endregion
413
- export { TEST_CONTEXT_HEADER, TestEndpointAdaptor, TestFunctionAdaptor, TestQueueAdaptor, TestSubscriberAdaptor, createMswHandlers };
490
+ //#region src/testing/manifest.ts
491
+ /**
492
+ * The test manifest: what `gkm test` knows about an app, written down for the
493
+ * suite it starts.
494
+ *
495
+ * `gkm test` discovers the constructs, reconciles the test stage and resolves
496
+ * its environment — then, until this existed, threw all of it away and left a
497
+ * test to declare it again by hand. The manifest keeps it: which construct and
498
+ * endpoint is exported where, and the environment the test stage resolved,
499
+ * under the keys the constructs themselves derive. A feature test is built from
500
+ * it, so nothing a test says can drift from what the app declares.
501
+ */
502
+ /** The environment variable `gkm test` names the manifest in. */
503
+ const TEST_MANIFEST_ENV = "GKM_TEST_MANIFEST";
504
+ /**
505
+ * Read a test manifest: from a path, a `file:` URL, or — given nothing — the
506
+ * one `gkm test` named in `GKM_TEST_MANIFEST`.
507
+ */
508
+ function loadTestManifest(from) {
509
+ const location = from ?? process.env["GKM_TEST_MANIFEST"];
510
+ if (!location) throw new NoTestManifest();
511
+ trustLocalEdge();
512
+ const path = location instanceof URL || location.startsWith("file:") ? fileURLToPath(location) : location;
513
+ return JSON.parse(readFileSync(path, "utf-8"));
514
+ }
515
+ let trusted = false;
516
+ /**
517
+ * Trust the local edge's certificate authority in this thread.
518
+ *
519
+ * `NODE_EXTRA_CA_CERTS` does it for a process started with it — which a
520
+ * suite started by `gkm test` is, and one started by plain `vitest` or an
521
+ * editor is not: its setup only learns the path once Vitest is running, and a
522
+ * worker *thread* shares that process and keeps a TLS store of its own. Every
523
+ * feature test loads the manifest, so this is the one place each worker passes
524
+ * through.
525
+ */
526
+ function trustLocalEdge() {
527
+ const certificate = process.env.NODE_EXTRA_CA_CERTS;
528
+ if (trusted || !certificate || !existsSync(certificate)) return;
529
+ trusted = true;
530
+ tls.setDefaultCACertificates([...tls.getCACertificates("default"), readFileSync(certificate, "utf-8")]);
531
+ }
532
+ /** A feature test ran without a manifest to build itself from. */
533
+ var NoTestManifest = class extends Error {
534
+ constructor() {
535
+ super(`No test manifest: run the suite with \`gkm test\`, or add \`globalSetup: ['@geekmidas/cli/vitest']\` to the root vitest config — either writes one and names it in ${TEST_MANIFEST_ENV}.`);
536
+ this.name = "NoTestManifest";
537
+ }
538
+ };
539
+ //#endregion
540
+ //#region src/testing/receive.ts
541
+ /** `mailbox.receive` named no recipient. */
542
+ var ReceiveNeedsRecipient = class extends Error {
543
+ constructor() {
544
+ super("mailbox.receive needs `to`: the envelope recipient routes the message to an inbox, and nothing else does.");
545
+ this.name = "ReceiveNeedsRecipient";
546
+ }
547
+ };
548
+ /** `mailbox.receive` was given fields and a raw message, or neither a sender nor raw. */
549
+ var ReceiveFieldsOrRaw = class extends Error {
550
+ reason;
551
+ constructor(reason) {
552
+ super(reason === "both" ? "mailbox.receive takes either a raw message or the fields to build one (subject, text, html, attachments, headers…), not both: the raw message already says them." : "mailbox.receive needs `from` when it builds the message — or a `raw` message, whose From: it uses.");
553
+ this.reason = reason;
554
+ this.name = "ReceiveFieldsOrRaw";
555
+ }
556
+ };
557
+ /** No declared inbox receives at the address `mailbox.receive` was given. */
558
+ var NoInboxForAddress = class extends Error {
559
+ address;
560
+ inboxes;
561
+ constructor(address, inboxes) {
562
+ super(inboxes.length === 0 ? `No inbox is declared, so nothing receives at '${address}'.` : `No inbox receives at '${address}'. ${inboxes.map((i) => `'${i}'`).join(", ")} take only their declared addresses on this stage's domain — as the deployed receipt rule does.`);
563
+ this.address = address;
564
+ this.inboxes = inboxes;
565
+ this.name = "NoInboxForAddress";
566
+ }
567
+ };
568
+ /** An inbox the test can receive for: no Mailpit to deliver to. */
569
+ var InboxNotLocal = class extends Error {
570
+ inbox;
571
+ constructor(inbox) {
572
+ super(`'${inbox}' has no ${providedKeyFor(inbox, "inbox", "smtpUrl")} in this test's environment, so there is no Mailpit to deliver to. Run it under \`gkm test\`, which resolves it.`);
573
+ this.inbox = inbox;
574
+ this.name = "InboxNotLocal";
575
+ }
576
+ };
577
+ /** Whether `value` is an inbox construct — by what it declares, so nothing imports one. */
578
+ function isInboxConstruct(value) {
579
+ const candidate = value;
580
+ return typeof candidate?.declare === "function" && typeof candidate.id === "string" && candidate.addressing !== void 0 && candidate.topic !== void 0 && candidate.declare().some((d) => d.kind === "inbox" && d.id === candidate.id);
581
+ }
582
+ /**
583
+ * Deliver `mail` to Mailpit and receive it: each inbox its envelope
584
+ * recipient is addressed to gets the receipt notification, through
585
+ * `publish`.
586
+ */
587
+ async function receiveInTest(mail, inboxes, env, publish) {
588
+ if (!mail.to) throw new ReceiveNeedsRecipient();
589
+ const fields = mail;
590
+ const built = fields.subject !== void 0 || fields.text !== void 0 || fields.html !== void 0 || fields.attachments !== void 0 || fields.headers !== void 0 || fields.headerTo !== void 0 || fields.cc !== void 0 || fields.replyTo !== void 0;
591
+ if (mail.raw !== void 0 && built) throw new ReceiveFieldsOrRaw("both");
592
+ const addressed = inboxes.filter((inbox) => {
593
+ const domain = env[providedKeyFor(inbox.id, "inbox", "domain")];
594
+ return domain && inboxRecipient(mail.to, inbox.addressing, domain);
595
+ });
596
+ if (addressed.length === 0) throw new NoInboxForAddress(mail.to, inboxes.map((inbox) => inbox.id));
597
+ let inbound;
598
+ let inbox;
599
+ try {
600
+ inbound = await import("@geekmidas/emailkit/inbound");
601
+ inbox = await import("../inbox.mjs");
602
+ } catch (cause) {
603
+ throw new OptionalPeerMissing("@geekmidas/emailkit and @geekmidas/storage", "Receiving mail into an Inbox", cause);
604
+ }
605
+ const { composeEmail, deliverRaw, parseEmail } = inbound;
606
+ const { receiveMail } = inbox;
607
+ let raw;
608
+ let from;
609
+ if (mail.raw !== void 0) {
610
+ raw = mail.raw;
611
+ const sender = mail.from ?? (await parseEmail(raw)).from?.address;
612
+ if (!sender) throw new ReceiveFieldsOrRaw("no-sender");
613
+ from = sender;
614
+ } else {
615
+ if (!fields.from) throw new ReceiveFieldsOrRaw("no-sender");
616
+ from = fields.from;
617
+ raw = await composeEmail({
618
+ from: fields.from,
619
+ to: fields.headerTo ?? mail.to,
620
+ ...fields.cc !== void 0 ? { cc: fields.cc } : {},
621
+ ...fields.replyTo ? { replyTo: fields.replyTo } : {},
622
+ ...fields.subject !== void 0 ? { subject: fields.subject } : {},
623
+ ...fields.text !== void 0 ? { text: fields.text } : {},
624
+ ...fields.html !== void 0 ? { html: fields.html } : {},
625
+ ...fields.attachments ? { attachments: fields.attachments } : {},
626
+ ...fields.headers ? { headers: fields.headers } : {}
627
+ });
628
+ }
629
+ const smtp = env[providedKeyFor(addressed[0].id, "inbox", "smtpUrl")];
630
+ if (!smtp) throw new InboxNotLocal(addressed[0].id);
631
+ return receiveMail({
632
+ key: await deliverRaw(smtp, {
633
+ from,
634
+ to: [mail.to]
635
+ }, raw),
636
+ store: "mailpit",
637
+ from,
638
+ recipients: [mail.to],
639
+ ...mail.verdicts ? { verdicts: mail.verdicts } : {}
640
+ }, addressed.map((inbox) => ({
641
+ id: inbox.id,
642
+ addressing: inbox.addressing,
643
+ domain: env[providedKeyFor(inbox.id, "inbox", "domain")],
644
+ publish: (notification) => publish(inbox, notification)
645
+ })));
646
+ }
647
+ //#endregion
648
+ //#region src/testing/featureTest.ts
649
+ /**
650
+ * `featureTest`: an app, driven the way it runs deployed.
651
+ *
652
+ * A browser signs in and calls the API; the API calls the auth server; each
653
+ * over its URL, each database in its own transaction. Nothing runs as a server:
654
+ * every URL an app's constructs answer on is served in-process through MSW,
655
+ * from the real handler, for the test that made the request. Everything else
656
+ * with a real local equivalent — Postgres, Mailpit, MinIO — is used directly.
657
+ *
658
+ * It is built from the test manifest `gkm test` writes — the constructs and
659
+ * endpoints the app exports, and the environment the test stage resolved — so
660
+ * a test declares none of it. `gkm test` also generates the configured `it`
661
+ * and a `Browser` with a typed client per surface:
662
+ *
663
+ * ```ts
664
+ * import { it } from '#test';
665
+ *
666
+ * it('shows the signed-in user their profile', async ({ browser, mailbox }) => {
667
+ * await browser.auth.signIn.magicLink({ email: 'ada@shop.test' });
668
+ * await browser.visit((await mailbox('ada@shop.test').last()).link!);
669
+ * expect(await browser.api.get('/profile')).toMatchObject({ email: 'ada@shop.test' });
670
+ * });
671
+ * ```
672
+ */
673
+ /** Every test in flight in this process, by id. */
674
+ const contexts = /* @__PURE__ */ new Map();
675
+ /** Databases already resolving to test transactions — patched once each. */
676
+ const bound = /* @__PURE__ */ new WeakSet();
677
+ function featureTest(options = {}) {
678
+ const manifest = options.manifest ?? loadTestManifest();
679
+ const BrowserClass = options.browser ?? Browser;
680
+ const site = wildcardSiteUrl(manifest);
681
+ let app;
682
+ let factoryDatabases = [];
683
+ let owned = [];
684
+ let network;
685
+ let restoreFetch = () => {};
686
+ beforeAll(async () => {
687
+ app = await load(manifest, options.modules ?? {});
688
+ owned = ownDatabases(app, manifest);
689
+ factoryDatabases = databasesFor(options.factories ?? {}, owned);
690
+ for (const database of app.databases) bindToTests(database);
691
+ network = setupServer(...surfaceHandlers(app.endpoints, manifest.env), ...app.auths.map((auth) => authHandler(auth, manifest.env, app.envParser)), ...Object.entries(options.fakes ?? {}).flatMap(([id, fake]) => fakeHandler(id, fake, manifest.env)));
692
+ network.listen({ onUnhandledRequest(request, print) {
693
+ if (isLocal(new URL(request.url))) return;
694
+ print.error();
695
+ } });
696
+ const restoreStamp = installContextFetch();
697
+ const stamped = globalThis.fetch;
698
+ globalThis.fetch = deliveringFetch(stamped, (id) => {
699
+ const state = contexts.get(id);
700
+ return state ? deliver(app, state, id) : Promise.resolve();
701
+ });
702
+ restoreFetch = () => {
703
+ globalThis.fetch = stamped;
704
+ restoreStamp();
705
+ };
706
+ });
707
+ afterAll(() => {
708
+ restoreFetch();
709
+ network?.close();
710
+ });
711
+ const run = (name, fn) => async () => {
712
+ const id = randomUUID();
713
+ faker.seed(seedOf(name));
714
+ const state = {
715
+ transactions: new TransactionRegistry(),
716
+ discovery: new ServiceDiscovery(app.envParser),
717
+ surfaces: /* @__PURE__ */ new Map(),
718
+ auth: /* @__PURE__ */ new Map(),
719
+ addresses: /* @__PURE__ */ new Set(),
720
+ published: /* @__PURE__ */ new Map(),
721
+ sockets: /* @__PURE__ */ new Map(),
722
+ pending: [],
723
+ delivering: false
724
+ };
725
+ const readMail = app.readMail;
726
+ if (readMail) state.mailbox = (address) => {
727
+ state.addresses.add(address);
728
+ return readMail(address);
729
+ };
730
+ contexts.set(id, state);
731
+ await state.discovery.register(recorders(app.channels, state));
732
+ await state.discovery.register(socketRecorders(app.surfaces, state));
733
+ await state.discovery.register(watchers(app, state));
734
+ try {
735
+ await runInTestContext(id, async () => {
736
+ const browser = new BrowserClass(site ? { site } : {});
737
+ const restore = browser.install();
738
+ try {
739
+ const transaction = (database) => state.transactions.get(database.id, urlOf(database, app.envParser), database.clientConfig);
740
+ const db = { get: (name) => {
741
+ const database = owned.find((candidate) => candidate.service.serviceName === name);
742
+ if (!database) throw new UnknownDatabase(name, owned.map((candidate) => candidate.service.serviceName));
743
+ return transaction(database);
744
+ } };
745
+ const built = /* @__PURE__ */ new Map();
746
+ await fn({
747
+ browser,
748
+ db,
749
+ factories: { get: (name) => {
750
+ const database = factoryDatabases.find(([candidate]) => candidate === name)?.[1];
751
+ if (!database) throw new UnknownFactory(name, factoryDatabases.map(([candidate]) => candidate));
752
+ let factory = built.get(name);
753
+ if (!factory) {
754
+ factory = transaction(database).then(options.factories[name]);
755
+ built.set(name, factory);
756
+ }
757
+ return factory;
758
+ } },
759
+ faker,
760
+ mailbox: Object.assign((address) => {
761
+ if (!state.mailbox) throw new NoInbox();
762
+ return state.mailbox(address);
763
+ }, { receive: async (mail) => {
764
+ await receiveInTest(mail, app.inboxes, app.env, async (inbox, notification) => {
765
+ state.pending.push({
766
+ channel: inbox.topic,
767
+ messages: [{
768
+ type: INBOX_EVENT,
769
+ payload: notification
770
+ }]
771
+ });
772
+ });
773
+ await deliver(app, state, id);
774
+ } }),
775
+ published: (channel) => [...state.published.get(channel.id) ?? []],
776
+ sockets: (surface) => {
777
+ const recorder = state.sockets.get(surface.id);
778
+ if (!recorder) throw new UnknownWebSocketApi(surface.id, [...state.sockets.keys()]);
779
+ return recorder;
780
+ },
781
+ services: { get: (name) => resolveService(app, state, name) },
782
+ subscriber: (subscriber) => thenDeliver(new TestSubscriberAdaptor(subscriber, state.discovery), () => deliver(app, state, id)),
783
+ queue: (queue) => thenDeliver(new TestQueueAdaptor(queue, state.discovery), () => deliver(app, state, id)),
784
+ objects: (bucket) => ({ emit: async (...events) => {
785
+ const watched = app.watched.find((candidate) => candidate.id === bucket.id);
786
+ if (!watched) throw new BucketNotWatched(bucket.id);
787
+ const name = bucketName(watched, app.envParser);
788
+ state.pending.push({
789
+ channel: watched,
790
+ messages: events.map(({ type, ...object }) => ({
791
+ type,
792
+ payload: {
793
+ bucket: name,
794
+ ...object
795
+ }
796
+ }))
797
+ });
798
+ await deliver(app, state, id);
799
+ } })
800
+ });
801
+ } finally {
802
+ restore();
803
+ }
804
+ });
805
+ } finally {
806
+ contexts.delete(id);
807
+ await Promise.all([state.transactions.rollbackAll(), ...[...state.addresses].map((address) => app.readMail?.(address).clear())]);
808
+ }
809
+ };
810
+ const it = ((name, fn, timeout) => test(name, run(name, fn), timeout));
811
+ it.only = (name, fn, timeout) => test.only(name, run(name, fn), timeout);
812
+ it.skip = (name, fn, timeout) => test.skip(name, run(name, fn), timeout);
813
+ return it;
814
+ }
815
+ /**
816
+ * A test's faker seed, from its name: the same test draws the same data on
817
+ * every run, and two tests draw different data.
818
+ */
819
+ function seedOf(name) {
820
+ let hash = 0;
821
+ for (const char of name) hash = Math.imul(hash, 31) + char.charCodeAt(0) | 0;
822
+ return hash >>> 0;
823
+ }
824
+ /**
825
+ * Import what the manifest points at.
826
+ *
827
+ * The same modules the app runs, so a construct here *is* the app's construct —
828
+ * the one its endpoints were built from — never a copy declared again.
829
+ */
830
+ async function load(manifest, modules) {
831
+ const envParser = new EnvironmentParser({ ...manifest.env });
832
+ const imported = async ({ file, export: name }) => (modules[file] ?? await import(file))[name];
833
+ const constructs = await Promise.all(Object.values(manifest.constructs).map(({ source }) => imported(source)));
834
+ const endpoints = (await Promise.all(manifest.endpoints.map(({ source }) => imported(source)))).filter((value) => Endpoint.isEndpoint(value));
835
+ const subscribers = (await Promise.all((manifest.subscribers ?? []).map(async ({ source }) => ({
836
+ name: source.export,
837
+ subscriber: await imported(source)
838
+ })))).filter((entry) => entry.subscriber?.__IS_SUBSCRIBER__ === true);
839
+ const unique = (values) => [...new Set(values)];
840
+ const databases = unique(constructs.filter((value) => value instanceof KyselyDatabase));
841
+ const auths = unique(constructs.filter((value) => value instanceof BetterAuth));
842
+ const emails = unique(constructs.filter((value) => value instanceof Email));
843
+ const consumables = unique(constructs.filter(isConsumable));
844
+ const channels = unique(constructs.filter((value) => value instanceof Topic || value instanceof Queue));
845
+ const watched = unique(constructs.filter((value) => isBucket(value) && subscribers.some(({ subscriber }) => subscriber.bucketName === value.id)));
846
+ const inboxes = unique(constructs.filter(isInboxConstruct));
847
+ const surfaces = unique(constructs.filter((value) => value instanceof WebSocketApi));
848
+ const inbox = emails.map((email) => manifest.env[providedKeyFor(email.id, "email", "inboxUrl")]).find(Boolean);
849
+ return {
850
+ envParser,
851
+ endpoints,
852
+ databases,
853
+ auths,
854
+ emails,
855
+ channels,
856
+ watched,
857
+ inboxes,
858
+ surfaces,
859
+ env: manifest.env,
860
+ consumables,
861
+ subscribers,
862
+ ...inbox ? { readMail: createMailbox({ inbox }) } : {}
863
+ };
864
+ }
865
+ /**
866
+ * A publisher that records rather than sends, under the name a topic or queue
867
+ * is injected by — `services.users` — which is also the one `.event(users, …)`
868
+ * publishes through.
869
+ */
870
+ function recorders(channels, state) {
871
+ return channels.map((channel) => {
872
+ const publisher = { async publish(messages) {
873
+ const sent = messages.map(({ type, payload }) => ({
874
+ type,
875
+ payload
876
+ }));
877
+ state.published.set(channel.id, [...state.published.get(channel.id) ?? [], ...sent]);
878
+ state.pending.push({
879
+ channel,
880
+ messages: sent
881
+ });
882
+ } };
883
+ return {
884
+ serviceName: channel.service.serviceName,
885
+ register: () => publisher
886
+ };
887
+ });
888
+ }
889
+ /**
890
+ * A WebSocket surface's publisher that records rather than sends, under the
891
+ * name `.dependsOn([realtime])` injects it by — one per surface per test.
892
+ */
893
+ function socketRecorders(surfaces, state) {
894
+ return surfaces.map((surface) => {
895
+ const recorder = surface.testPublisher();
896
+ state.sockets.set(surface.id, recorder);
897
+ return {
898
+ serviceName: surface.service.serviceName,
899
+ register: () => recorder
900
+ };
901
+ });
902
+ }
903
+ /**
904
+ * The databases a test is handed: the app's own. A schema tenant an auth server
905
+ * owns is reached through that server, as the app reaches it, and a reader is
906
+ * the same database through a read-only role — neither is another database to
907
+ * test against.
908
+ */
909
+ function ownDatabases(app, manifest) {
910
+ const owners = new Set(app.auths.map((auth) => auth.databaseId));
911
+ return app.databases.filter((database) => !owners.has(database.id) && manifest.constructs[database.id]?.kind !== "database-reader");
912
+ }
913
+ /** Each factory's database, found by the service name it is keyed by. */
914
+ function databasesFor(factories, databases) {
915
+ return Object.keys(factories).map((name) => {
916
+ const database = databases.find((candidate) => candidate.service.serviceName === name);
917
+ if (!database) throw new UnknownFactory(name, databases.map((candidate) => candidate.service.serviceName));
918
+ return [name, database];
919
+ });
920
+ }
921
+ /**
922
+ * Make a database resolve, inside a test, to that test's transaction.
923
+ *
924
+ * Everything reaches a database through its service — an endpoint through
925
+ * service discovery, the auth server through its tenant directly — so this is
926
+ * the one place a test's connection can be handed over. Outside a test it is
927
+ * the database it always was.
928
+ */
929
+ /** Rounds of delivery before a chain of consumers is called a loop. */
930
+ const MAX_DELIVERY_ROUNDS = 25;
931
+ /**
932
+ * Deliver what this test published, in-process, as the broker would — and
933
+ * keep delivering what the consumers publish in turn, until nothing is left.
934
+ *
935
+ * - A queue's messages go to its one consumer, as a batch.
936
+ * - A topic's events go to every subscriber that named their type, and only
937
+ * those: fan-out, as the filter policy (SNS) or the per-subscriber queue
938
+ * (pg-boss) does it.
939
+ * - Each payload is checked against the consumer's schema first. Turning an
940
+ * SNS envelope or an SQS record into `{ type, payload }` is each adaptor's
941
+ * job and tested there; what is tested here is what the handler is handed.
942
+ * - Consumers run as the server side of this test, so their databases are
943
+ * this test's transactions and their writes roll back with it.
944
+ * - A consumer that throws fails the test. Deployed, the message would be
945
+ * retried; here a retry would only hide the bug.
946
+ */
947
+ async function deliver(app, state, id) {
948
+ if (state.delivering) return;
949
+ state.delivering = true;
950
+ try {
951
+ for (let round = 0; state.pending.length > 0; round++) {
952
+ if (round === MAX_DELIVERY_ROUNDS) throw new DeliveryDidNotSettle(MAX_DELIVERY_ROUNDS, [...new Set(state.pending.map(({ channel }) => channel.id))]);
953
+ for (const { channel, messages } of state.pending.splice(0)) if (channel instanceof Queue) await toQueue(channel, messages, state, id);
954
+ else if (channel instanceof Topic) await toSubscribers(channel, messages, app, state, id);
955
+ else await toObjectSubscribers(channel, messages, app, state, id);
956
+ }
957
+ } finally {
958
+ state.delivering = false;
959
+ }
960
+ }
961
+ async function toQueue(queue, messages, state, id) {
962
+ const payloads = [];
963
+ for (const message of messages) payloads.push(await accepted(queue.messageSchema, message, `queue '${queue.name}'`));
964
+ await runAsServer(id, () => new TestQueueAdaptor(queue, state.discovery).invoke({ messages: payloads })).catch((error) => {
965
+ throw new DeliveryFailed(`queue '${queue.name}'`, messages, error);
966
+ });
967
+ }
968
+ async function toSubscribers(topic, messages, app, state, id) {
969
+ for (const { name, subscriber } of app.subscribers) {
970
+ if (subscriber.topicName !== topic.name) continue;
971
+ const named = messages.filter(({ type }) => (subscriber.subscribedEvents ?? []).includes(type));
972
+ if (named.length === 0) continue;
973
+ const consumer = `subscriber '${name}'`;
974
+ const events = [];
975
+ for (const message of named) {
976
+ const schema = topic.eventSchemas[message.type];
977
+ events.push({
978
+ type: message.type,
979
+ payload: await accepted(schema, message, consumer)
980
+ });
981
+ }
982
+ await runAsServer(id, () => new TestSubscriberAdaptor(subscriber, state.discovery).invoke({ events })).catch((error) => {
983
+ throw new DeliveryFailed(consumer, named, error);
984
+ });
985
+ }
986
+ }
987
+ /**
988
+ * A bucket's changes to each subscriber bound to it that named their type —
989
+ * the subscriber keeps the keys it watches, as it does deployed.
990
+ */
991
+ async function toObjectSubscribers(bucket, messages, app, state, id) {
992
+ for (const { name, subscriber } of app.subscribers) {
993
+ if (subscriber.bucketName !== bucket.id) continue;
994
+ const named = messages.filter(({ type }) => (subscriber.subscribedEvents ?? []).includes(type));
995
+ if (named.length === 0) continue;
996
+ const consumer = `subscriber '${name}'`;
997
+ await runAsServer(id, () => new TestSubscriberAdaptor(subscriber, state.discovery).invoke({ events: named })).catch((error) => {
998
+ throw new DeliveryFailed(consumer, named, error);
999
+ });
1000
+ }
1001
+ }
1002
+ /**
1003
+ * A client for each watched bucket that reports what it writes: the real
1004
+ * client — the test's MinIO — under the name the bucket is injected by, so
1005
+ * an upload a handler makes reaches the bucket's subscribers as the storage
1006
+ * would report it.
1007
+ */
1008
+ function watchers(app, state) {
1009
+ return app.watched.map((bucket) => ({
1010
+ serviceName: bucket.service.serviceName,
1011
+ register: async (options) => {
1012
+ const client = await bucket.service.register(options);
1013
+ const name = bucketName(bucket, app.envParser);
1014
+ const report = async (message) => {
1015
+ state.pending.push({
1016
+ channel: bucket,
1017
+ messages: [message]
1018
+ });
1019
+ const context = currentTestContext();
1020
+ if (context?.side === "client") await deliver(app, state, context.id);
1021
+ };
1022
+ const watching = Object.create(client);
1023
+ watching.upload = async (key, data, contentType) => {
1024
+ await client.upload(key, data, contentType);
1025
+ await report({
1026
+ type: "object.created",
1027
+ payload: {
1028
+ bucket: name,
1029
+ key,
1030
+ size: byteLength(data)
1031
+ }
1032
+ });
1033
+ };
1034
+ watching.delete = async (key) => {
1035
+ await client.delete(key);
1036
+ await report({
1037
+ type: "object.deleted",
1038
+ payload: {
1039
+ bucket: name,
1040
+ key
1041
+ }
1042
+ });
1043
+ };
1044
+ return watching;
1045
+ }
1046
+ }));
1047
+ }
1048
+ /** The bucket's name as the storage knows it — the host of its URL. */
1049
+ function bucketName(bucket, envParser) {
1050
+ const { url } = envParser.create((get) => ({ url: get(providedKeyFor(bucket.id, "objects", "connectionString")).string() })).parse();
1051
+ try {
1052
+ return new URL(url).hostname || bucket.id;
1053
+ } catch {
1054
+ return bucket.id;
1055
+ }
1056
+ }
1057
+ function byteLength(data) {
1058
+ return typeof data === "string" ? Buffer.byteLength(data) : data.length;
1059
+ }
1060
+ /** An `ObjectStorage`, recognised by what it declares — never by importing it. */
1061
+ function isBucket(value) {
1062
+ const declare = value?.declare;
1063
+ return typeof declare === "function" && declare.call(value)[0]?.kind === "objects";
1064
+ }
1065
+ /** `objects(bucket)` named a bucket no subscriber in the app is bound to. */
1066
+ /** `sockets(surface)` for a surface the test manifest does not declare. */
1067
+ var UnknownWebSocketApi = class extends Error {
1068
+ surface;
1069
+ declared;
1070
+ constructor(surface, declared) {
1071
+ super(`The test manifest declares no WebSocketApi '${surface}'` + (declared.length ? ` — it declares ${declared.map((id) => `'${id}'`).join(", ")}.` : ", and no WebSocketApi at all.") + " Export the surface from the app so `gkm test` records it.");
1072
+ this.surface = surface;
1073
+ this.declared = declared;
1074
+ this.name = "UnknownWebSocketApi";
1075
+ }
1076
+ };
1077
+ var BucketNotWatched = class extends Error {
1078
+ bucket;
1079
+ constructor(bucket) {
1080
+ super(`No subscriber is bound to '${bucket}', so nothing receives what is emitted on it. Bind one — worker.objects(${bucket.charAt(0).toLowerCase()}${bucket.slice(1)}) — or check the test manifest lists it.`);
1081
+ this.bucket = bucket;
1082
+ this.name = "BucketNotWatched";
1083
+ }
1084
+ };
1085
+ /** The payload, if the consumer's schema takes it — what the handler is handed. */
1086
+ async function accepted(schema, message, consumer) {
1087
+ const standard = schema?.["~standard"];
1088
+ if (!standard) return message.payload;
1089
+ const result = await standard.validate(message.payload);
1090
+ if (result.issues) throw new MessageRejected(consumer, message, result.issues);
1091
+ return result.value;
1092
+ }
1093
+ /** `fetch`, delivering what the test published once each of its requests answers. */
1094
+ function deliveringFetch(inner, settle) {
1095
+ return async (input, init) => {
1096
+ const context = currentTestContext();
1097
+ const response = await inner(input, init);
1098
+ if (context?.side === "client") await settle(context.id);
1099
+ return response;
1100
+ };
1101
+ }
1102
+ /** An adaptor whose `invoke` delivers what it published before returning. */
1103
+ function thenDeliver(adaptor, settle) {
1104
+ const invoke = adaptor.invoke.bind(adaptor);
1105
+ adaptor.invoke = (async (...args) => {
1106
+ const result = await invoke(...args);
1107
+ await settle();
1108
+ return result;
1109
+ });
1110
+ return adaptor;
1111
+ }
1112
+ function bindToTests(database) {
1113
+ if (bound.has(database)) return;
1114
+ bound.add(database);
1115
+ const service = database.service;
1116
+ const register = service.register;
1117
+ service.register = (options) => {
1118
+ const context = currentTestContext();
1119
+ const state = context && contexts.get(context.id);
1120
+ if (!state) return register(options);
1121
+ return state.transactions.get(database.id, urlOf(database, options.envParser), database.clientConfig);
1122
+ };
1123
+ }
1124
+ function urlOf(database, envParser) {
1125
+ return envParser.create((get) => ({ url: get(providedKeyFor(database.id, "database", "url")).string() })).parse().url;
1126
+ }
1127
+ /** Each surface's endpoints, served at its URL for the test that asked. */
1128
+ function surfaceHandlers(endpoints, env) {
1129
+ const bySurface = /* @__PURE__ */ new Map();
1130
+ for (const endpoint of endpoints) {
1131
+ const surface = endpoint.surface?.id;
1132
+ if (!surface) continue;
1133
+ bySurface.set(surface, [...bySurface.get(surface) ?? [], endpoint]);
1134
+ }
1135
+ return [...bySurface].flatMap(([surface, served]) => {
1136
+ const base = env[providedKeyFor(surface, "rest-api", "url")];
1137
+ if (!base) return [];
1138
+ return http.all(`${trim(base)}/*`, ({ request }) => serve(request, async (state) => {
1139
+ let app = state.surfaces.get(surface);
1140
+ if (!app) {
1141
+ app = Promise.resolve().then(() => {
1142
+ const hono = new Hono();
1143
+ HonoEndpoint.addRoutes(served, state.discovery, hono);
1144
+ return hono;
1145
+ });
1146
+ state.surfaces.set(surface, app);
1147
+ }
1148
+ return (await app).fetch(request, inProcessBindings());
1149
+ }));
1150
+ });
1151
+ }
1152
+ /**
1153
+ * An external API's app fake, answering at the URL the test stage resolved for
1154
+ * it — so a handler that calls Polar calls the fake, and the test sets up
1155
+ * nothing.
1156
+ *
1157
+ * Not per test, unlike a surface: a fake stands in for somebody else's server,
1158
+ * which no test's transaction reaches. An image fake has no handler here — its
1159
+ * container answers on localhost, which is let through.
1160
+ */
1161
+ function fakeHandler(id, fake, env) {
1162
+ const base = env[providedKeyFor(id, "external-api", "url")];
1163
+ if (fake.kind !== "app" || !base) return [];
1164
+ return [http.all(`${trim(base)}/*`, ({ request }) => fake.handler.fetch(request))];
1165
+ }
1166
+ /**
1167
+ * A construct's client for this test, by service name — through the test's own
1168
+ * discovery, so a topic or queue is its recorder and a database its
1169
+ * transaction, exactly as the test's endpoints get them.
1170
+ */
1171
+ async function resolveService(app, state, name) {
1172
+ const construct = app.consumables.find((candidate) => candidate.service.serviceName === name);
1173
+ if (!construct) throw new UnknownService(name, app.consumables.map((candidate) => candidate.service.serviceName));
1174
+ return (await state.discovery.register([construct.service]))[name];
1175
+ }
1176
+ /** An auth server, served at its URL, on the transaction of the test that asked. */
1177
+ function authHandler(auth, env, envParser) {
1178
+ const base = trim(env[providedKeyFor(auth.id, "rest-api", "url")] ?? "");
1179
+ return http.all(`${base}/*`, ({ request }) => serve(request, async (state) => {
1180
+ let app = state.auth.get(auth);
1181
+ if (!app) {
1182
+ app = auth.server({
1183
+ envParser,
1184
+ context: serviceContext
1185
+ }).then(({ app }) => app);
1186
+ state.auth.set(auth, app);
1187
+ }
1188
+ return (await app).fetch(request, inProcessBindings());
1189
+ }));
1190
+ }
1191
+ /** Handle a request as the server side of the test it was made for. */
1192
+ async function serve(request, handle) {
1193
+ const id = testContextOf(request);
1194
+ const state = id ? contexts.get(id) : void 0;
1195
+ if (!id || !state) throw new UnknownTestContext(request.url, id);
1196
+ return runAsServer(id, () => handle(state));
1197
+ }
1198
+ function trim(url) {
1199
+ return url.replace(/\/$/, "");
1200
+ }
1201
+ function isLocal(url) {
1202
+ return url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname.endsWith(".localhost");
1203
+ }
1204
+ /**
1205
+ * The test stage's address for the app's site on every subdomain —
1206
+ * `https://*.test.shop.localhost:8443` — which `browser.on(slug)` puts a
1207
+ * tenant into, or `undefined` when the app declares none.
1208
+ */
1209
+ function wildcardSiteUrl(manifest) {
1210
+ for (const [id, construct] of Object.entries(manifest.constructs)) {
1211
+ if (construct.kind !== "site") continue;
1212
+ const url = manifest.env[providedKeyFor(id, construct.kind, "url")];
1213
+ if (url && new URL(url).hostname.startsWith(`${WILDCARD_SUBDOMAIN}.`)) return url;
1214
+ }
1215
+ }
1216
+ /**
1217
+ * Sign a test's browser in the way a person does: ask the auth server for a
1218
+ * magic link, open the email it sent, follow the link.
1219
+ *
1220
+ * What the generated `browser.signIn(email)` calls. The address's mail is
1221
+ * cleared first — so the link is this request's, not one an earlier test left
1222
+ * — and cleared again after the test, like any address a test reads. Returns
1223
+ * the session the auth server then reports, as better-auth hands it back.
1224
+ */
1225
+ async function signInWithMagicLink(browser, auth, email = freshAddress()) {
1226
+ const context = currentTestContext();
1227
+ const state = context && contexts.get(context.id);
1228
+ if (!state) throw new UnknownTestContext("signIn", context?.id);
1229
+ if (!state.mailbox) throw new NoInbox();
1230
+ const inbox = state.mailbox(email);
1231
+ await inbox.clear();
1232
+ const requested = await auth.signIn.magicLink({ email });
1233
+ if (requested.error) throw new SignInFailed(email, `the auth server refused the magic link: ${requested.error.message ?? "no reason given"}`);
1234
+ const mail = await inbox.last();
1235
+ if (!mail.link) throw new SignInFailed(email, "its email held no link");
1236
+ await browser.visit(mail.link);
1237
+ const { data } = await auth.getSession();
1238
+ if (!data) throw new SignInFailed(email, "the auth server reported no session after the link was opened");
1239
+ return data;
1240
+ }
1241
+ /**
1242
+ * An address nobody else signs in as — what `browser.signIn()` uses when the
1243
+ * test does not care who it is.
1244
+ *
1245
+ * Unique rather than only seeded: tests in other files run at the same time,
1246
+ * against the same Mailpit and the same unique columns, and a seeded address
1247
+ * repeats wherever two tests share a name. The readable half is the seeded
1248
+ * faker's, so a failure still names somebody.
1249
+ */
1250
+ function freshAddress() {
1251
+ return `${faker.internet.username().toLowerCase().replace(/[^a-z0-9]/g, "")}.${randomUUID().slice(0, 8)}@example.test`;
1252
+ }
1253
+ /** `browser.signIn` finished without a session. */
1254
+ var SignInFailed = class extends Error {
1255
+ email;
1256
+ reason;
1257
+ constructor(email, reason) {
1258
+ super(`Signing ${email} in failed: ${reason}.`);
1259
+ this.email = email;
1260
+ this.reason = reason;
1261
+ this.name = "SignInFailed";
1262
+ }
1263
+ };
1264
+ /** A request reached an in-process server without a test to belong to. */
1265
+ var UnknownTestContext = class extends Error {
1266
+ url;
1267
+ id;
1268
+ constructor(url, id) {
1269
+ super(id ? `${url} was requested for test ${id}, which is not running. A request that outlives its test — an un-awaited call — lands here.` : `${url} was requested outside any test. Make the request inside a featureTest, so it reaches that test's transactions.`);
1270
+ this.url = url;
1271
+ this.id = id;
1272
+ this.name = "UnknownTestContext";
1273
+ }
1274
+ };
1275
+ /** `mailbox` was used in an app that declares no Email construct. */
1276
+ var NoInbox = class extends Error {
1277
+ constructor() {
1278
+ super("mailbox() reads the inbox of the app's Email construct, and none was found in featureTest's modules — or `gkm test` did not inject its <ID>_INBOX_URL.");
1279
+ this.name = "NoInbox";
1280
+ }
1281
+ };
1282
+ /** `db.get(name)` named no database the test is handed. */
1283
+ var UnknownDatabase = class extends Error {
1284
+ database;
1285
+ known;
1286
+ constructor(database, known) {
1287
+ super(`db.get('${database}') names no database of this app's. ` + (known.length > 0 ? `Its databases: ${known.join(", ")}. ` : "It declares no database of its own. ") + "A tenant an auth server owns is reached through that server, and a reader through the database it reads.");
1288
+ this.database = database;
1289
+ this.known = known;
1290
+ this.name = "UnknownDatabase";
1291
+ }
1292
+ };
1293
+ /** A factory keyed by a service name no database the app declares has. */
1294
+ var UnknownFactory = class extends Error {
1295
+ factory;
1296
+ known;
1297
+ constructor(factory, known) {
1298
+ super(`There is a test factory for '${factory}', and no database this app declares is called that. ` + (known.length > 0 ? `Its databases: ${known.join(", ")}. ` : "It declares no database. ") + `Name the file after the database construct: test/factories/<construct>.ts.`);
1299
+ this.factory = factory;
1300
+ this.known = known;
1301
+ this.name = "UnknownFactory";
1302
+ }
1303
+ };
1304
+ /** A published message the consumer's own schema refuses. */
1305
+ var MessageRejected = class extends Error {
1306
+ consumer;
1307
+ published;
1308
+ issues;
1309
+ constructor(consumer, published, issues) {
1310
+ super(`${consumer} refuses '${published.type}': ${issues.map((issue) => issue.message).join("; ")}. What is published must be what the consumer's schema takes — fix the producer, or the schema.`);
1311
+ this.consumer = consumer;
1312
+ this.published = published;
1313
+ this.issues = issues;
1314
+ this.name = "MessageRejected";
1315
+ }
1316
+ };
1317
+ /** A consumer that threw while handling what the test published. */
1318
+ var DeliveryFailed = class extends Error {
1319
+ consumer;
1320
+ messages;
1321
+ cause;
1322
+ constructor(consumer, messages, cause) {
1323
+ super(`${consumer} failed handling ${messages.map(({ type }) => `'${type}'`).join(", ")}: ${cause?.message ?? String(cause)}. Deployed, the message would be retried; here the failure is the result.`, { cause });
1324
+ this.consumer = consumer;
1325
+ this.messages = messages;
1326
+ this.cause = cause;
1327
+ this.name = "DeliveryFailed";
1328
+ }
1329
+ };
1330
+ /** Consumers that kept publishing to each other without settling. */
1331
+ var DeliveryDidNotSettle = class extends Error {
1332
+ rounds;
1333
+ channels;
1334
+ constructor(rounds, channels) {
1335
+ super(`Delivery did not settle after ${rounds} rounds — consumers are still publishing to ${channels.join(", ")}. A consumer that publishes to what triggers it loops forever deployed too.`);
1336
+ this.rounds = rounds;
1337
+ this.channels = channels;
1338
+ this.name = "DeliveryDidNotSettle";
1339
+ }
1340
+ };
1341
+ /** `services.get(name)` for a name no construct of the app is served by. */
1342
+ var UnknownService = class extends Error {
1343
+ serviceName;
1344
+ available;
1345
+ constructor(serviceName, available) {
1346
+ super(`The app declares no construct served as '${serviceName}'. Its services are: ${available.join(", ") || "none"}.`);
1347
+ this.serviceName = serviceName;
1348
+ this.available = available;
1349
+ this.name = "UnknownService";
1350
+ }
1351
+ };
1352
+ //#endregion
1353
+ //#region src/websocket/msw.ts
1354
+ /**
1355
+ * The MSW adaptor: a surface's real routes behind MSW's `ws.link()`, so code
1356
+ * that holds a `WebSocket` — a client, its reconnects, its decoding — runs
1357
+ * unchanged against them, in one process, with no server.
1358
+ *
1359
+ * MSW intercepts the client's `WebSocket` and hands each connection here.
1360
+ * The adaptor gives it an id, runs `connect()`, then each frame the client
1361
+ * sends through `message()`, and `disconnect()` when either side closes.
1362
+ * What reaches a socket from elsewhere — an endpoint's `services.<surface>` —
1363
+ * goes over an in-process `memory://` channel, as it does between a route
1364
+ * and the Node adaptor in one dev process, and is written to MSW's `client`.
1365
+ *
1366
+ * ```ts
1367
+ * const realtime = createMswWebSocketHandlers(surface, [routes], {
1368
+ * url: 'wss://realtime.test',
1369
+ * });
1370
+ * server.use(...realtime.handlers);
1371
+ *
1372
+ * realtime.registerContext(id, { session, services: { database: trx } });
1373
+ * const socket = new WebSocket(`wss://realtime.test/?${TEST_CONTEXT_PARAM}=${id}`);
1374
+ * await sendMessage.request({ services: { realtime: realtime.publisher }, … });
1375
+ * ```
1376
+ *
1377
+ * There is no handshake to see: a browser-style `WebSocket` sends no headers
1378
+ * a test can set, so the session comes from the registered context (no
1379
+ * context is no session). The Origin check, the heartbeat and close codes
1380
+ * on a real upgrade stay the Node adaptor's.
1381
+ */
1382
+ /**
1383
+ * The query parameter that names a connection's test context. Read and
1384
+ * removed before `connect()` sees `query`, so the handler never does.
1385
+ */
1386
+ const TEST_CONTEXT_PARAM = "__gkm_test_context";
1387
+ /**
1388
+ * The close code a refused connection gets: `4000 + status`, so a 401 is
1389
+ * 4401. MSW cannot answer an upgrade with a status line, as a server does.
1390
+ */
1391
+ const REFUSED_CLOSE_BASE = 4e3;
1392
+ /** A connection whose query names a context no test registered. */
1393
+ var UnknownWebSocketTestContext = class extends Error {
1394
+ id;
1395
+ constructor(id) {
1396
+ super(`No test registered the WebSocket context '${id}'. Call registerContext('${id}', …) before opening the socket, and keep it until it closes.`);
1397
+ this.id = id;
1398
+ this.name = "UnknownWebSocketTestContext";
1399
+ }
1400
+ };
1401
+ /** The close code a connection with an unknown context is closed with. */
1402
+ const UNKNOWN_CONTEXT_CLOSE = 1011;
1403
+ function createMswWebSocketHandlers(surface, modules, options) {
1404
+ const instance = `msw${randomUUID().slice(0, 8)}`;
1405
+ const channel = options.channel ?? `gkm:ws:${surface.id}:${instance}`;
1406
+ const transport = new MemoryTransport(channel);
1407
+ const contexts = /* @__PURE__ */ new Map();
1408
+ const open = /* @__PURE__ */ new Map();
1409
+ const deliver = (delivery) => {
1410
+ if (delivery.kind === "broadcast") {
1411
+ const except = new Set(delivery.except ?? []);
1412
+ for (const [id, { client }] of open) if (!except.has(id)) client.send(delivery.payload);
1413
+ return;
1414
+ }
1415
+ for (const id of delivery.ids) {
1416
+ const client = open.get(id)?.client;
1417
+ if (!client) continue;
1418
+ if (delivery.kind === "send") client.send(delivery.payload);
1419
+ else client.close(delivery.code, delivery.reason);
1420
+ }
1421
+ };
1422
+ const subscribed = transport.subscribe(instance, deliver);
1423
+ const sink = new TransportSink(transport, {
1424
+ instance,
1425
+ deliver
1426
+ });
1427
+ const core = surface.core({
1428
+ envParser: options.envParser ?? surface.envParser,
1429
+ sink,
1430
+ modules
1431
+ });
1432
+ let issued = 0;
1433
+ async function accept(client) {
1434
+ const query = new URLSearchParams(client.url.searchParams);
1435
+ const contextId = query.get(TEST_CONTEXT_PARAM);
1436
+ query.delete(TEST_CONTEXT_PARAM);
1437
+ const context = contextId ? contexts.get(contextId) : {};
1438
+ issued += 1;
1439
+ const connectionId = `${instance}.${issued}`;
1440
+ let accepted = Promise.resolve(void 0);
1441
+ let queue = Promise.resolve();
1442
+ let closed = false;
1443
+ const call = context?.services ? { services: context.services } : {};
1444
+ client.addEventListener("message", (event) => {
1445
+ queue = queue.then(async () => {
1446
+ const connection = await accepted;
1447
+ if (!connection) return;
1448
+ await core.message(connection, await textOrBytes(event.data), (payload) => client.send(payload), call);
1449
+ });
1450
+ });
1451
+ client.addEventListener("close", (event) => {
1452
+ if (closed) return;
1453
+ closed = true;
1454
+ queue = queue.then(async () => {
1455
+ const connection = await accepted;
1456
+ if (!connection) return;
1457
+ open.delete(connection.id);
1458
+ await core.disconnect(connection, {
1459
+ code: event.code,
1460
+ reason: event.reason
1461
+ }, call);
1462
+ });
1463
+ });
1464
+ if (!context) {
1465
+ const error = new UnknownWebSocketTestContext(contextId);
1466
+ client.close(UNKNOWN_CONTEXT_CLOSE, error.message.slice(0, 123));
1467
+ return;
1468
+ }
1469
+ accepted = (async () => {
1470
+ await subscribed;
1471
+ const outcome = await core.connect({
1472
+ connectionId,
1473
+ headers: new Headers(),
1474
+ query,
1475
+ session: context.session ?? null
1476
+ }, call);
1477
+ if (!outcome.accepted) {
1478
+ client.close(REFUSED_CLOSE_BASE + outcome.status, outcome.statusText);
1479
+ return;
1480
+ }
1481
+ if (closed) return void 0;
1482
+ open.set(connectionId, {
1483
+ connection: outcome.connection,
1484
+ client
1485
+ });
1486
+ return outcome.connection;
1487
+ })();
1488
+ await accepted;
1489
+ }
1490
+ return {
1491
+ handlers: [ws.link(options.url).addEventListener("connection", ({ client }) => {
1492
+ accept(client);
1493
+ })],
1494
+ registerContext: (id, context) => {
1495
+ contexts.set(id, context);
1496
+ },
1497
+ removeContext: (id) => {
1498
+ contexts.delete(id);
1499
+ },
1500
+ publisher: surface.publisher(new TransportSink(new MemoryTransport(channel))),
1501
+ connectionString: `memory://${channel}`,
1502
+ get connections() {
1503
+ return [...open.values()].map(({ connection }) => connection);
1504
+ },
1505
+ close: () => transport.close()
1506
+ };
1507
+ }
1508
+ /** A frame as the core takes it: text, or the bytes it refuses. */
1509
+ async function textOrBytes(data) {
1510
+ if (typeof data === "string") return data;
1511
+ if (data instanceof ArrayBuffer) return new Uint8Array(data);
1512
+ if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
1513
+ if (data instanceof Blob) return new Uint8Array(await data.arrayBuffer());
1514
+ return String(data);
1515
+ }
1516
+ //#endregion
1517
+ export { DeliveryDidNotSettle, DeliveryFailed, IN_PROCESS_PEER_ADDRESS, InboxNotLocal, InvalidWebSocketRequest, MessageRejected, NoInbox, NoInboxForAddress, NoTestManifest, REFUSED_CLOSE_BASE, ReceiveFieldsOrRaw, ReceiveNeedsRecipient, SignInFailed, TEST_CONTEXT_HEADER, TEST_CONTEXT_PARAM, TEST_MANIFEST_ENV, TestEndpointAdaptor, TestFunctionAdaptor, TestQueueAdaptor, TestSubscriberAdaptor, TestWebSocketPublisher, UnknownDatabase, UnknownFactory, UnknownService, UnknownTestContext, UnknownWebSocketApi, UnknownWebSocketTestContext, createMswHandlers, createMswWebSocketHandlers, featureTest, inProcessBindings, loadTestManifest, signInWithMagicLink };
414
1518
 
415
1519
  //# sourceMappingURL=testing.mjs.map