@geekmidas/constructs 10.0.0-alpha.155 → 10.0.0-alpha.156

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 (220) hide show
  1. package/README.md +23 -0
  2. package/dist/{Construct-DorKS0Ua.cjs → Construct-B8yWxGlR.cjs} +2 -2
  3. package/dist/{Construct-DorKS0Ua.cjs.map → Construct-B8yWxGlR.cjs.map} +1 -1
  4. package/dist/{Construct-DySlwh8o.d.mts → Construct-BMk_CRSD.d.mts} +2 -2
  5. package/dist/{Construct-DySlwh8o.d.mts.map → Construct-BMk_CRSD.d.mts.map} +1 -1
  6. package/dist/{Construct-CGuc_Ijk.mjs → Construct-CRV3RN2U.mjs} +11 -2
  7. package/dist/{Construct-CGuc_Ijk.mjs.map → Construct-CRV3RN2U.mjs.map} +1 -1
  8. package/dist/{Cron-D8mB_cPX.d.mts → Cron-D6Y7BBt3.d.mts} +5 -5
  9. package/dist/{Cron-D8mB_cPX.d.mts.map → Cron-D6Y7BBt3.d.mts.map} +1 -1
  10. package/dist/{CronBuilder-Cmajva3g.d.mts → CronBuilder-4BZhkChG.d.mts} +5 -5
  11. package/dist/{CronBuilder-Cmajva3g.d.mts.map → CronBuilder-4BZhkChG.d.mts.map} +1 -1
  12. package/dist/{CronBuilder-B_NSP-Y5.cjs → CronBuilder-B4DYaEjl.cjs} +4 -4
  13. package/dist/{CronBuilder-B_NSP-Y5.cjs.map → CronBuilder-B4DYaEjl.cjs.map} +1 -1
  14. package/dist/{CronBuilder-BJ5LoadF.mjs → CronBuilder-CukJuL3b.mjs} +3 -3
  15. package/dist/{CronBuilder-BJ5LoadF.mjs.map → CronBuilder-CukJuL3b.mjs.map} +1 -1
  16. package/dist/{Endpoint-BbHh3Qoc.d.mts → Endpoint-BUoDD96P.d.mts} +5 -5
  17. package/dist/{Endpoint-BbHh3Qoc.d.mts.map → Endpoint-BUoDD96P.d.mts.map} +1 -1
  18. package/dist/{Endpoint-sUOU7uLx.mjs → Endpoint-BuKHHVZc.mjs} +3 -3
  19. package/dist/{Endpoint-sUOU7uLx.mjs.map → Endpoint-BuKHHVZc.mjs.map} +1 -1
  20. package/dist/{Endpoint-52z1P0Ue.cjs → Endpoint-D2ckHqIx.cjs} +3 -3
  21. package/dist/{Endpoint-52z1P0Ue.cjs.map → Endpoint-D2ckHqIx.cjs.map} +1 -1
  22. package/dist/{EndpointFactory-qcLzi4f-.d.mts → EndpointFactory-BbVOeryo.d.mts} +5 -5
  23. package/dist/{EndpointFactory-qcLzi4f-.d.mts.map → EndpointFactory-BbVOeryo.d.mts.map} +1 -1
  24. package/dist/{EndpointFactory-Bzi9Sl7r.mjs → EndpointFactory-BsJUlUyL.mjs} +4 -4
  25. package/dist/{EndpointFactory-Bzi9Sl7r.mjs.map → EndpointFactory-BsJUlUyL.mjs.map} +1 -1
  26. package/dist/{EndpointFactory-Cf_Cs1ym.cjs → EndpointFactory-c4tHjQKM.cjs} +5 -5
  27. package/dist/{EndpointFactory-Cf_Cs1ym.cjs.map → EndpointFactory-c4tHjQKM.cjs.map} +1 -1
  28. package/dist/{Function-DfMzTGS4.d.mts → Function-BKReud5p.d.mts} +3 -3
  29. package/dist/{Function-DfMzTGS4.d.mts.map → Function-BKReud5p.d.mts.map} +1 -1
  30. package/dist/{HonoEndpointAdaptor-DR3j7S35.mjs → HonoEndpointAdaptor-BC7CZ7Cr.mjs} +7 -6
  31. package/dist/HonoEndpointAdaptor-BC7CZ7Cr.mjs.map +1 -0
  32. package/dist/{HonoEndpointAdaptor-BXBdb2Bt.cjs → HonoEndpointAdaptor-BGEW1Tu8.cjs} +9 -8
  33. package/dist/HonoEndpointAdaptor-BGEW1Tu8.cjs.map +1 -0
  34. package/dist/{ObjectSubscriberBuilder-Cv8C7yS1.d.mts → ObjectSubscriberBuilder-DfzXQEKW.d.mts} +4 -4
  35. package/dist/{ObjectSubscriberBuilder-Cv8C7yS1.d.mts.map → ObjectSubscriberBuilder-DfzXQEKW.d.mts.map} +1 -1
  36. package/dist/ObjectSubscriberBuilder-LWkey_oq.d.cts.map +1 -1
  37. package/dist/{ProcessorBuilder-CwfP-M33.d.mts → ProcessorBuilder-D4oYvZeG.d.mts} +2 -2
  38. package/dist/{ProcessorBuilder-CwfP-M33.d.mts.map → ProcessorBuilder-D4oYvZeG.d.mts.map} +1 -1
  39. package/dist/{Queue-u8w8_HpE.mjs → Queue-0FpvxdOa.mjs} +2 -2
  40. package/dist/{Queue-u8w8_HpE.mjs.map → Queue-0FpvxdOa.mjs.map} +1 -1
  41. package/dist/{Queue-BnK3UH8r.d.mts → Queue-B8HGg439.d.mts} +3 -3
  42. package/dist/{Queue-BnK3UH8r.d.mts.map → Queue-B8HGg439.d.mts.map} +1 -1
  43. package/dist/{Queue-D4Iaidrs.cjs → Queue-DZpV13LN.cjs} +2 -2
  44. package/dist/{Queue-D4Iaidrs.cjs.map → Queue-DZpV13LN.cjs.map} +1 -1
  45. package/dist/{QueueBuilder-2wP5lEC8.mjs → QueueBuilder-Bmyay_Di.mjs} +2 -2
  46. package/dist/{QueueBuilder-2wP5lEC8.mjs.map → QueueBuilder-Bmyay_Di.mjs.map} +1 -1
  47. package/dist/{QueueBuilder-DmwFtLzQ.d.mts → QueueBuilder-CVS_qPuo.d.mts} +2 -2
  48. package/dist/{QueueBuilder-DmwFtLzQ.d.mts.map → QueueBuilder-CVS_qPuo.d.mts.map} +1 -1
  49. package/dist/{QueueBuilder-BxsZ9o5z.cjs → QueueBuilder-FXkSDah1.cjs} +2 -2
  50. package/dist/{QueueBuilder-BxsZ9o5z.cjs.map → QueueBuilder-FXkSDah1.cjs.map} +1 -1
  51. package/dist/{Subscriber-CW_Dl-YR.d.mts → Subscriber-CtQXhcL7.d.mts} +3 -3
  52. package/dist/{Subscriber-CW_Dl-YR.d.mts.map → Subscriber-CtQXhcL7.d.mts.map} +1 -1
  53. package/dist/{SubscriberBuilder-CWzKwX1p.cjs → SubscriberBuilder-Bfn-iDSk.cjs} +4 -3
  54. package/dist/SubscriberBuilder-Bfn-iDSk.cjs.map +1 -0
  55. package/dist/{SubscriberBuilder-BL_GTcwh.mjs → SubscriberBuilder-CxG1OOug.mjs} +4 -3
  56. package/dist/SubscriberBuilder-CxG1OOug.mjs.map +1 -0
  57. package/dist/{Topic-DN2gYJ-p.mjs → Topic-DoEdDgh7.mjs} +2 -2
  58. package/dist/{Topic-DN2gYJ-p.mjs.map → Topic-DoEdDgh7.mjs.map} +1 -1
  59. package/dist/{Topic-Dp9Q7Lj2.cjs → Topic-t5GhqaeT.cjs} +2 -2
  60. package/dist/{Topic-Dp9Q7Lj2.cjs.map → Topic-t5GhqaeT.cjs.map} +1 -1
  61. package/dist/adaptors/aws.cjs +28 -16
  62. package/dist/adaptors/aws.cjs.map +1 -1
  63. package/dist/adaptors/aws.d.cts +141 -0
  64. package/dist/adaptors/aws.d.cts.map +1 -1
  65. package/dist/adaptors/aws.d.mts +147 -6
  66. package/dist/adaptors/aws.d.mts.map +1 -1
  67. package/dist/adaptors/aws.mjs +21 -15
  68. package/dist/adaptors/aws.mjs.map +1 -1
  69. package/dist/adaptors/hono.cjs +1 -1
  70. package/dist/adaptors/hono.d.mts +2 -2
  71. package/dist/adaptors/hono.mjs +1 -1
  72. package/dist/adaptors/testing.cjs +25 -15
  73. package/dist/adaptors/testing.cjs.map +1 -1
  74. package/dist/adaptors/testing.d.cts +1 -1
  75. package/dist/adaptors/testing.d.cts.map +1 -1
  76. package/dist/adaptors/testing.d.mts +9 -9
  77. package/dist/adaptors/testing.d.mts.map +1 -1
  78. package/dist/adaptors/testing.mjs +21 -11
  79. package/dist/adaptors/testing.mjs.map +1 -1
  80. package/dist/apigateway-Dyjy_JwI.mjs +329 -0
  81. package/dist/apigateway-Dyjy_JwI.mjs.map +1 -0
  82. package/dist/apigateway-zHDoMwlI.cjs +370 -0
  83. package/dist/apigateway-zHDoMwlI.cjs.map +1 -0
  84. package/dist/auth-BqWz2JxC.d.cts.map +1 -1
  85. package/dist/auth-DnB9H9KL.d.mts.map +1 -1
  86. package/dist/auth.cjs +7 -21
  87. package/dist/auth.cjs.map +1 -1
  88. package/dist/auth.mjs +6 -20
  89. package/dist/auth.mjs.map +1 -1
  90. package/dist/{cache-e3tfMQ9g.d.mts → cache-CCHcO9Oo.d.mts} +2 -2
  91. package/dist/cache-CCHcO9Oo.d.mts.map +1 -0
  92. package/dist/cache-CQjMNPrC.d.cts.map +1 -1
  93. package/dist/cache.cjs +3 -19
  94. package/dist/cache.cjs.map +1 -1
  95. package/dist/cache.d.mts +1 -1
  96. package/dist/cache.mjs +2 -18
  97. package/dist/cache.mjs.map +1 -1
  98. package/dist/crons/index.cjs +4 -3
  99. package/dist/crons/index.cjs.map +1 -1
  100. package/dist/crons/index.d.cts.map +1 -1
  101. package/dist/crons/index.d.mts +2 -2
  102. package/dist/crons/index.d.mts.map +1 -1
  103. package/dist/crons/index.mjs +4 -3
  104. package/dist/crons/index.mjs.map +1 -1
  105. package/dist/database/kysely.cjs +1 -1
  106. package/dist/database/kysely.d.mts +1 -1
  107. package/dist/email.cjs +4 -16
  108. package/dist/email.cjs.map +1 -1
  109. package/dist/email.d.cts.map +1 -1
  110. package/dist/email.d.mts.map +1 -1
  111. package/dist/email.mjs +2 -14
  112. package/dist/email.mjs.map +1 -1
  113. package/dist/endpoints/index.cjs +4 -4
  114. package/dist/endpoints/index.d.cts +1 -1
  115. package/dist/endpoints/index.d.cts.map +1 -1
  116. package/dist/endpoints/index.d.mts +4 -4
  117. package/dist/endpoints/index.d.mts.map +1 -1
  118. package/dist/endpoints/index.mjs +4 -4
  119. package/dist/file-server.cjs +1 -1
  120. package/dist/file-server.d.mts +1 -1
  121. package/dist/file-server.mjs +1 -1
  122. package/dist/functions/index.cjs +1 -1
  123. package/dist/functions/index.d.mts +2 -2
  124. package/dist/functions/index.mjs +1 -1
  125. package/dist/{functions-BvIDQKAA.mjs → functions-BF039DT8.mjs} +2 -2
  126. package/dist/{functions-BvIDQKAA.mjs.map → functions-BF039DT8.mjs.map} +1 -1
  127. package/dist/{functions-DLF6-IK8.cjs → functions-BqAq_0xQ.cjs} +3 -3
  128. package/dist/{functions-DLF6-IK8.cjs.map → functions-BqAq_0xQ.cjs.map} +1 -1
  129. package/dist/{inbox-CjxpLVkH.d.mts → inbox-YOdxlyfj.d.mts} +2 -2
  130. package/dist/{inbox-CjxpLVkH.d.mts.map → inbox-YOdxlyfj.d.mts.map} +1 -1
  131. package/dist/inbox.cjs +1 -1
  132. package/dist/inbox.d.mts +1 -1
  133. package/dist/inbox.mjs +1 -1
  134. package/dist/{index-DCkDQkwj.d.mts → index-BoQ3-M-K.d.mts} +4 -4
  135. package/dist/{index-DCkDQkwj.d.mts.map → index-BoQ3-M-K.d.mts.map} +1 -1
  136. package/dist/index.cjs +1 -1
  137. package/dist/index.d.mts +1 -1
  138. package/dist/index.mjs +1 -1
  139. package/dist/{kysely-CukArHJ0.cjs → kysely-CeoQdAkg.cjs} +2 -2
  140. package/dist/{kysely-CukArHJ0.cjs.map → kysely-CeoQdAkg.cjs.map} +1 -1
  141. package/dist/{kysely-DE4kADWD.d.mts → kysely-De5rAC-E.d.mts} +2 -2
  142. package/dist/{kysely-DE4kADWD.d.mts.map → kysely-De5rAC-E.d.mts.map} +1 -1
  143. package/dist/optionalPeers-D7Wt6dnF.mjs +140 -0
  144. package/dist/optionalPeers-D7Wt6dnF.mjs.map +1 -0
  145. package/dist/optionalPeers-DuNQXXe1.cjs +223 -0
  146. package/dist/optionalPeers-DuNQXXe1.cjs.map +1 -0
  147. package/dist/origins-C7T9covD.cjs +24 -0
  148. package/dist/origins-C7T9covD.cjs.map +1 -0
  149. package/dist/origins-CX6Ot7ax.mjs +19 -0
  150. package/dist/origins-CX6Ot7ax.mjs.map +1 -0
  151. package/dist/{pattern-QFaUIr77.cjs → pattern-HnNOPhE2.cjs} +2 -2
  152. package/dist/{pattern-QFaUIr77.cjs.map → pattern-HnNOPhE2.cjs.map} +1 -1
  153. package/dist/{pattern-C1CEcglD.mjs → pattern-YSqfAhXm.mjs} +2 -2
  154. package/dist/{pattern-C1CEcglD.mjs.map → pattern-YSqfAhXm.mjs.map} +1 -1
  155. package/dist/privateAddress-Bg5fUsbp.mjs +21 -0
  156. package/dist/privateAddress-Bg5fUsbp.mjs.map +1 -0
  157. package/dist/privateAddress-CqGyuFHn.cjs +26 -0
  158. package/dist/privateAddress-CqGyuFHn.cjs.map +1 -0
  159. package/dist/processors/index.cjs +1 -1
  160. package/dist/processors/index.d.mts +1 -1
  161. package/dist/processors/index.mjs +1 -1
  162. package/dist/queue/index.cjs +2 -2
  163. package/dist/queue/index.d.mts +2 -2
  164. package/dist/queue/index.mjs +2 -2
  165. package/dist/{readRequestBody-BTIl3k-D.mjs → readRequestBody-BmKnPl0a.mjs} +26 -4
  166. package/dist/readRequestBody-BmKnPl0a.mjs.map +1 -0
  167. package/dist/{readRequestBody-Dej_L3c4.cjs → readRequestBody-CN9GVdeE.cjs} +26 -4
  168. package/dist/readRequestBody-CN9GVdeE.cjs.map +1 -0
  169. package/dist/{requestLogger-BZcXwdBs.cjs → requestLogger-CnoYd-Ah.cjs} +4 -63
  170. package/dist/requestLogger-CnoYd-Ah.cjs.map +1 -0
  171. package/dist/{requestLogger-pA4gi3E1.mjs → requestLogger-D2JS7pPM.mjs} +3 -56
  172. package/dist/requestLogger-D2JS7pPM.mjs.map +1 -0
  173. package/dist/rest-api.cjs +1 -1
  174. package/dist/rest-api.d.mts +2 -2
  175. package/dist/rest-api.mjs +1 -1
  176. package/dist/{rolldown-runtime-y5ARvAq5.cjs → rolldown-runtime-Ctb5zv51.cjs} +15 -0
  177. package/dist/{runSubscriber-DyHWp_Lf.mjs → runSubscriber-HEqXkin1.mjs} +3 -2
  178. package/dist/runSubscriber-HEqXkin1.mjs.map +1 -0
  179. package/dist/{runSubscriber-CC_2C9F2.cjs → runSubscriber-sVJfLA0-.cjs} +3 -2
  180. package/dist/runSubscriber-sVJfLA0-.cjs.map +1 -0
  181. package/dist/subscribers/index.cjs +6 -6
  182. package/dist/subscribers/index.cjs.map +1 -1
  183. package/dist/subscribers/index.d.cts +1 -1
  184. package/dist/subscribers/index.d.mts +3 -3
  185. package/dist/subscribers/index.mjs +3 -3
  186. package/dist/subscribers/index.mjs.map +1 -1
  187. package/dist/topic/index.cjs +1 -1
  188. package/dist/topic/index.d.mts +1 -1
  189. package/dist/topic/index.mjs +1 -1
  190. package/dist/{websocket-api-Dn_3Y2fI.mjs → websocket-api-BvKS9x-l.mjs} +453 -44
  191. package/dist/websocket-api-BvKS9x-l.mjs.map +1 -0
  192. package/dist/{websocket-api-CLnV_7CB.d.cts → websocket-api-C3dWKNxO.d.cts} +481 -208
  193. package/dist/websocket-api-C3dWKNxO.d.cts.map +1 -0
  194. package/dist/{websocket-api-9bXfgrqd.cjs → websocket-api-CAQA_QOE.cjs} +494 -43
  195. package/dist/websocket-api-CAQA_QOE.cjs.map +1 -0
  196. package/dist/{websocket-api-DSWDhZph.d.mts → websocket-api-CDAxOTQZ.d.mts} +481 -208
  197. package/dist/websocket-api-CDAxOTQZ.d.mts.map +1 -0
  198. package/dist/websocket-api.cjs +8 -1
  199. package/dist/websocket-api.d.cts +2 -2
  200. package/dist/websocket-api.d.mts +2 -2
  201. package/dist/websocket-api.mjs +2 -2
  202. package/dist/worker.cjs +4 -4
  203. package/dist/worker.d.mts +9 -9
  204. package/dist/worker.mjs +4 -4
  205. package/package.json +41 -31
  206. package/dist/HonoEndpointAdaptor-BXBdb2Bt.cjs.map +0 -1
  207. package/dist/HonoEndpointAdaptor-DR3j7S35.mjs.map +0 -1
  208. package/dist/SubscriberBuilder-BL_GTcwh.mjs.map +0 -1
  209. package/dist/SubscriberBuilder-CWzKwX1p.cjs.map +0 -1
  210. package/dist/cache-e3tfMQ9g.d.mts.map +0 -1
  211. package/dist/readRequestBody-BTIl3k-D.mjs.map +0 -1
  212. package/dist/readRequestBody-Dej_L3c4.cjs.map +0 -1
  213. package/dist/requestLogger-BZcXwdBs.cjs.map +0 -1
  214. package/dist/requestLogger-pA4gi3E1.mjs.map +0 -1
  215. package/dist/runSubscriber-CC_2C9F2.cjs.map +0 -1
  216. package/dist/runSubscriber-DyHWp_Lf.mjs.map +0 -1
  217. package/dist/websocket-api-9bXfgrqd.cjs.map +0 -1
  218. package/dist/websocket-api-CLnV_7CB.d.cts.map +0 -1
  219. package/dist/websocket-api-DSWDhZph.d.mts.map +0 -1
  220. package/dist/websocket-api-Dn_3Y2fI.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"cache-e3tfMQ9g.d.mts","names":["Cache","CacheClient"],"sources":["../src/cache.ts"],"mappings":";;;;;UA6BiB;;;;;;;;EAQhB;;EAEA;;cAGYA,QAAM,0CACP,UAAU,OAAOC;mBAaV;WAXT,IAAI;WACJ,SAAS,QAAQ,aAAa,QAAQA;;;;;mBAM9B;EAEjB,YACC,IAAI,cAAc,QACD,UAAS;EAc3B,WAAW;;;;;;;;;;;;UAuBG"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"readRequestBody-BTIl3k-D.mjs","names":[],"sources":["../src/endpoints/lazyAccessors.ts","../src/endpoints/readRequestBody.ts"],"sourcesContent":["/**\n * Lazy header and cookie accessors for different adaptors.\n *\n * Instead of parsing all headers/cookies upfront, these accessors\n * use native adaptor methods for single lookups and only parse\n * everything when `header()` or `cookie()` is called without arguments.\n */\nimport type { Context } from 'hono';\nimport { getCookie } from 'hono/cookie';\nimport type { CookieFn, HeaderFn } from './Endpoint';\n\n/**\n * Create a lazy header accessor for Hono.\n * Uses `c.req.header(name)` for single lookups (native, case-insensitive).\n * Only calls `c.req.header()` to get all headers when needed.\n */\nexport function createHonoHeaders(c: Context): HeaderFn {\n\tlet allHeaders: Record<string, string> | null = null;\n\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) {\n\t\t\t// Single header lookup - use native Hono method (case-insensitive)\n\t\t\treturn c.req.header(key);\n\t\t}\n\t\t// Get all headers - cache the result\n\t\tif (!allHeaders) {\n\t\t\tallHeaders = c.req.header();\n\t\t}\n\t\treturn allHeaders;\n\t}) as HeaderFn;\n}\n\n/**\n * Create a lazy cookie accessor for Hono.\n * Uses `getCookie(c, name)` for single lookups (native).\n * Only parses the cookie header when all cookies are requested.\n */\nexport function createHonoCookies(c: Context): CookieFn {\n\tlet allCookies: Record<string, string> | null = null;\n\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) {\n\t\t\t// Single cookie lookup - use native Hono method\n\t\t\treturn getCookie(c, name);\n\t\t}\n\t\t// Get all cookies - parse and cache\n\t\tif (!allCookies) {\n\t\t\tallCookies = {};\n\t\t\tconst cookieHeader = c.req.header('cookie');\n\t\t\tif (cookieHeader) {\n\t\t\t\tfor (const part of cookieHeader.split(';')) {\n\t\t\t\t\tconst trimmed = part.trim();\n\t\t\t\t\tconst eqIndex = trimmed.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = trimmed.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = trimmed.slice(eqIndex + 1);\n\t\t\t\t\t\tallCookies[key] = value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allCookies;\n\t}) as CookieFn;\n}\n\n/**\n * Create a lazy header accessor for API Gateway events.\n * Handles case-insensitive lookups.\n */\nexport function createApiGatewayHeaders(\n\theaders: Record<string, string | undefined> | null | undefined,\n): HeaderFn {\n\tlet normalizedHeaders: Record<string, string> | null = null;\n\n\tconst normalize = () => {\n\t\tif (!normalizedHeaders) {\n\t\t\tnormalizedHeaders = {};\n\t\t\tif (headers) {\n\t\t\t\tfor (const [k, v] of Object.entries(headers)) {\n\t\t\t\t\tif (v !== undefined) {\n\t\t\t\t\t\tnormalizedHeaders[k.toLowerCase()] = v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn normalizedHeaders;\n\t};\n\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) {\n\t\t\t// Try direct lookup first (common case: headers already lowercase)\n\t\t\tif (headers) {\n\t\t\t\tconst direct = headers[key] ?? headers[key.toLowerCase()];\n\t\t\t\tif (direct !== undefined) return direct;\n\t\t\t\t// Fall back to normalized lookup\n\t\t\t\treturn normalize()[key.toLowerCase()];\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn normalize();\n\t}) as HeaderFn;\n}\n\n/**\n * Create a lazy cookie accessor for API Gateway events.\n * Decodes URL-encoded values to match browser behavior.\n */\nexport function createApiGatewayCookies(\n\tcookies: string[] | undefined,\n\tcookieHeader: string | undefined,\n): CookieFn {\n\tlet parsed: Record<string, string> | null = null;\n\n\tconst parse = () => {\n\t\tif (!parsed) {\n\t\t\tparsed = {};\n\t\t\t// API Gateway v2 provides cookies as array\n\t\t\tif (cookies) {\n\t\t\t\tfor (const cookie of cookies) {\n\t\t\t\t\tconst eqIndex = cookie.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = cookie.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = cookie.slice(eqIndex + 1);\n\t\t\t\t\t\tparsed[key] = decodeURIComponent(value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (cookieHeader) {\n\t\t\t\t// Fall back to parsing cookie header\n\t\t\t\tfor (const part of cookieHeader.split(';')) {\n\t\t\t\t\tconst trimmed = part.trim();\n\t\t\t\t\tconst eqIndex = trimmed.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = trimmed.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = trimmed.slice(eqIndex + 1);\n\t\t\t\t\t\tparsed[key] = decodeURIComponent(value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn parsed;\n\t};\n\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) {\n\t\t\treturn parse()[name];\n\t\t}\n\t\treturn parse();\n\t}) as CookieFn;\n}\n\n/**\n * Create a lazy header accessor for plain object headers (test adaptor, etc).\n * Headers are already available as an object, just provide lazy access.\n */\nexport function createObjectHeaders(\n\theaders: Record<string, string> | undefined,\n): HeaderFn {\n\tlet normalized: Record<string, string> | null = null;\n\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) {\n\t\t\t// Try direct lookup first (common case)\n\t\t\tif (headers) {\n\t\t\t\tconst direct = headers[key] ?? headers[key.toLowerCase()];\n\t\t\t\tif (direct !== undefined) return direct;\n\t\t\t}\n\t\t\t// Fall back to normalized lookup for case-insensitivity\n\t\t\tif (!normalized && headers) {\n\t\t\t\tnormalized = {};\n\t\t\t\tfor (const [k, v] of Object.entries(headers)) {\n\t\t\t\t\tnormalized[k.toLowerCase()] = v;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn normalized?.[key.toLowerCase()];\n\t\t}\n\t\t// Return all headers\n\t\tif (!normalized && headers) {\n\t\t\tnormalized = {};\n\t\t\tfor (const [k, v] of Object.entries(headers)) {\n\t\t\t\tnormalized[k.toLowerCase()] = v;\n\t\t\t}\n\t\t}\n\t\treturn normalized ?? {};\n\t}) as HeaderFn;\n}\n\n/**\n * Create a lazy cookie accessor from a cookie header string.\n * Decodes URL-encoded values to match browser behavior.\n */\nexport function createCookieHeaderAccessor(\n\tcookieHeader: string | undefined,\n): CookieFn {\n\tlet parsed: Record<string, string> | null = null;\n\n\tconst parse = () => {\n\t\tif (!parsed) {\n\t\t\tparsed = {};\n\t\t\tif (cookieHeader) {\n\t\t\t\tfor (const part of cookieHeader.split(';')) {\n\t\t\t\t\tconst trimmed = part.trim();\n\t\t\t\t\tconst eqIndex = trimmed.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = trimmed.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = trimmed.slice(eqIndex + 1);\n\t\t\t\t\t\t// Decode URL-encoded values to match Endpoint.createCookies behavior\n\t\t\t\t\t\tparsed[key] = decodeURIComponent(value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn parsed;\n\t};\n\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) {\n\t\t\treturn parse()[name];\n\t\t}\n\t\treturn parse();\n\t}) as CookieFn;\n}\n\n/**\n * Create a no-op header accessor (for minimal endpoints that don't use headers).\n */\nexport function createNoopHeaders(): HeaderFn {\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) return undefined;\n\t\treturn {};\n\t}) as HeaderFn;\n}\n\n/**\n * Create a no-op cookie accessor (for minimal endpoints that don't use cookies).\n */\nexport function createNoopCookies(): CookieFn {\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) return undefined;\n\t\treturn {};\n\t}) as CookieFn;\n}\n","import { HttpError } from '@geekmidas/errors';\n\n/**\n * The media types an endpoint's `.body()` schema can be handed — as written\n * in the 415 a request in any other type is answered with.\n */\nexport const SUPPORTED_BODY_TYPES = [\n\t'application/json',\n\t'application/x-www-form-urlencoded',\n\t'multipart/form-data',\n\t'text/*',\n] as const;\n\n/**\n * A request whose body is in a media type no endpoint reads — XML, a bare\n * octet stream. Answered with a 415, before the body schema runs.\n */\nexport class UnsupportedRequestContentType extends HttpError {\n\tconstructor(readonly contentType: string) {\n\t\tsuper(\n\t\t\t415,\n\t\t\t`A body sent as '${contentType}' can't be read. Send it as ${SUPPORTED_BODY_TYPES.join(', ')}.`,\n\t\t\t{\n\t\t\t\tstatusMessage: 'Unsupported Media Type',\n\t\t\t\tdetails: { contentType, supported: [...SUPPORTED_BODY_TYPES] },\n\t\t\t},\n\t\t);\n\t\tthis.name = 'UnsupportedRequestContentType';\n\t}\n}\n\n/**\n * A body that says it is JSON and is not. Answered with a 400 — the request\n * is broken, not merely invalid against the schema.\n */\nexport class MalformedRequestBody extends HttpError {\n\tconstructor(\n\t\treadonly contentType: string,\n\t\tcause?: Error,\n\t) {\n\t\tsuper(\n\t\t\t400,\n\t\t\t`The body says it is '${contentType}' but can't be parsed as that. Send a well-formed body, with the Content-Type it is written in.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'MalformedRequestBody';\n\t}\n}\n\n/**\n * What a body is read from: a `Request`, or Hono's request — which caches\n * what it read, so a later reader is not handed a spent stream.\n */\nexport interface RequestBodySource {\n\tjson(): Promise<unknown>;\n\ttext(): Promise<string>;\n\tformData(): Promise<FormData>;\n}\n\nexport interface ReadRequestBodyOptions {\n\t/**\n\t * A body with no Content-Type: read as JSON (`'json'`, what API Gateway\n\t * has always done), or not read at all and handed to the schema as `{}`\n\t * (`'empty'`, what a Hono server has always done).\n\t */\n\tuntyped: 'json' | 'empty';\n}\n\n/**\n * A request body, read by its Content-Type into what an endpoint's `.body()`\n * schema validates — the one place every adaptor reads a body:\n *\n * - `application/json` (and `application/*+json`) — the parsed JSON.\n * - `application/x-www-form-urlencoded` and `multipart/form-data` — a plain\n * object of fields, as an HTML form posts them. A repeated field, or one\n * named `field[]`, is an array; a file part is a `File`.\n * - `text/*` — the text.\n *\n * Anything else is an {@link UnsupportedRequestContentType}.\n */\nexport async function readRequestBody(\n\tsource: RequestBodySource,\n\tcontentType: string | null | undefined,\n\toptions: ReadRequestBodyOptions,\n): Promise<unknown> {\n\tconst mediaType = contentType?.split(';')[0]?.trim().toLowerCase();\n\n\tif (!mediaType) {\n\t\tif (options.untyped === 'empty') return {};\n\t\treturn readJson(source, 'application/json');\n\t}\n\n\tif (isJson(mediaType)) return readJson(source, mediaType);\n\n\tif (\n\t\tmediaType === 'application/x-www-form-urlencoded' ||\n\t\tmediaType === 'multipart/form-data'\n\t) {\n\t\treturn formFields(await readForm(source, mediaType));\n\t}\n\n\tif (mediaType.startsWith('text/')) return source.text();\n\n\tthrow new UnsupportedRequestContentType(mediaType);\n}\n\nfunction isJson(mediaType: string): boolean {\n\treturn (\n\t\tmediaType === 'application/json' ||\n\t\t(mediaType.startsWith('application/') && mediaType.endsWith('+json'))\n\t);\n}\n\nasync function readJson(\n\tsource: RequestBodySource,\n\tmediaType: string,\n): Promise<unknown> {\n\ttry {\n\t\treturn await source.json();\n\t} catch (error) {\n\t\tthrow new MalformedRequestBody(mediaType, error as Error);\n\t}\n}\n\nasync function readForm(\n\tsource: RequestBodySource,\n\tmediaType: string,\n): Promise<FormData> {\n\ttry {\n\t\treturn await source.formData();\n\t} catch (error) {\n\t\tthrow new MalformedRequestBody(mediaType, error as Error);\n\t}\n}\n\n/** A form field's value: its text, or a `File` for a file part. */\ntype FormValue = NonNullable<ReturnType<FormData['get']>>;\n\n/**\n * A form's fields as an object, the way Hono's `parseBody({ all: true })`\n * reads them. Without a prototype, so a field named `__proto__` is a field.\n */\nfunction formFields(form: FormData): Record<string, FormValue | FormValue[]> {\n\tconst fields: Record<string, FormValue | FormValue[]> = Object.create(null);\n\n\tfor (const [key, value] of form.entries()) {\n\t\tconst existing = fields[key];\n\t\tif (existing === undefined) {\n\t\t\tfields[key] = key.endsWith('[]') ? [value] : value;\n\t\t} else if (Array.isArray(existing)) {\n\t\t\texisting.push(value);\n\t\t} else {\n\t\t\tfields[key] = [existing, value];\n\t\t}\n\t}\n\n\treturn fields;\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,kBAAkB,GAAsB;CACvD,IAAI,aAA4C;CAEhD,SAAS,QAAiB;EACzB,IAAI,QAAQ,KAAA,GAEX,OAAO,EAAE,IAAI,OAAO,GAAG;EAGxB,IAAI,CAAC,YACJ,aAAa,EAAE,IAAI,OAAO;EAE3B,OAAO;CACR;AACD;;;;;;AAOA,SAAgB,kBAAkB,GAAsB;CACvD,IAAI,aAA4C;CAEhD,SAAS,SAAkB;EAC1B,IAAI,SAAS,KAAA,GAEZ,OAAO,UAAU,GAAG,IAAI;EAGzB,IAAI,CAAC,YAAY;GAChB,aAAa,CAAC;GACd,MAAM,eAAe,EAAE,IAAI,OAAO,QAAQ;GAC1C,IAAI,cACH,KAAK,MAAM,QAAQ,aAAa,MAAM,GAAG,GAAG;IAC3C,MAAM,UAAU,KAAK,KAAK;IAC1B,MAAM,UAAU,QAAQ,QAAQ,GAAG;IACnC,IAAI,UAAU,GAAG;KAChB,MAA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4B;CAC3C,OACC,cAAc,sBACb,UAAU,WAAW,cAAc,KAAK,UAAU,SAAS,OAAO;AAErE;AAEA,eAAe,SACd,QACA,WACmB;CACnB,IAAI;EACH,OAAO,MAAM,OAAO,KAAK;CAC1B,SAAS,OAAO;EACf,MAAM,IAAI,qBAAqB,WAAW,KAAc;CACzD;AACD;AAEA,eAAe,SACd,QACA,WACoB;CACpB,IAAI;EACH,OAAO,MAAM,OAAO,SAAS;CAC9B,SAAS,OAAO;EACf,MAAM,IAAI,qBAAqB,WAAW,KAAc;CACzD;AACD;;;;;AASA,SAAS,WAAW,MAAyD;CAC5E,MAAM,SAAkD,OAAO,OAAO,IAAI;CAE1E,KAAK,MAAM,CAAC,KAAK,UAAU,KAAK,QAAQ,GAAG;EAC1C,MAAM,WAAW,OAAO;EACxB,IAAI,aAAa,KAAA,GAChB,OAAO,OAAO,IAAI,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI;OACvC,IAAI,MAAM,QAAQ,QAAQ,GAChC,SAAS,KAAK,KAAK;OAEnB,OAAO,OAAO,CAAC,UAAU,KAAK;CAEhC;CAEA,OAAO;AACR"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"readRequestBody-Dej_L3c4.cjs","names":["getCookie","HttpError"],"sources":["../src/endpoints/lazyAccessors.ts","../src/endpoints/readRequestBody.ts"],"sourcesContent":["/**\n * Lazy header and cookie accessors for different adaptors.\n *\n * Instead of parsing all headers/cookies upfront, these accessors\n * use native adaptor methods for single lookups and only parse\n * everything when `header()` or `cookie()` is called without arguments.\n */\nimport type { Context } from 'hono';\nimport { getCookie } from 'hono/cookie';\nimport type { CookieFn, HeaderFn } from './Endpoint';\n\n/**\n * Create a lazy header accessor for Hono.\n * Uses `c.req.header(name)` for single lookups (native, case-insensitive).\n * Only calls `c.req.header()` to get all headers when needed.\n */\nexport function createHonoHeaders(c: Context): HeaderFn {\n\tlet allHeaders: Record<string, string> | null = null;\n\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) {\n\t\t\t// Single header lookup - use native Hono method (case-insensitive)\n\t\t\treturn c.req.header(key);\n\t\t}\n\t\t// Get all headers - cache the result\n\t\tif (!allHeaders) {\n\t\t\tallHeaders = c.req.header();\n\t\t}\n\t\treturn allHeaders;\n\t}) as HeaderFn;\n}\n\n/**\n * Create a lazy cookie accessor for Hono.\n * Uses `getCookie(c, name)` for single lookups (native).\n * Only parses the cookie header when all cookies are requested.\n */\nexport function createHonoCookies(c: Context): CookieFn {\n\tlet allCookies: Record<string, string> | null = null;\n\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) {\n\t\t\t// Single cookie lookup - use native Hono method\n\t\t\treturn getCookie(c, name);\n\t\t}\n\t\t// Get all cookies - parse and cache\n\t\tif (!allCookies) {\n\t\t\tallCookies = {};\n\t\t\tconst cookieHeader = c.req.header('cookie');\n\t\t\tif (cookieHeader) {\n\t\t\t\tfor (const part of cookieHeader.split(';')) {\n\t\t\t\t\tconst trimmed = part.trim();\n\t\t\t\t\tconst eqIndex = trimmed.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = trimmed.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = trimmed.slice(eqIndex + 1);\n\t\t\t\t\t\tallCookies[key] = value;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allCookies;\n\t}) as CookieFn;\n}\n\n/**\n * Create a lazy header accessor for API Gateway events.\n * Handles case-insensitive lookups.\n */\nexport function createApiGatewayHeaders(\n\theaders: Record<string, string | undefined> | null | undefined,\n): HeaderFn {\n\tlet normalizedHeaders: Record<string, string> | null = null;\n\n\tconst normalize = () => {\n\t\tif (!normalizedHeaders) {\n\t\t\tnormalizedHeaders = {};\n\t\t\tif (headers) {\n\t\t\t\tfor (const [k, v] of Object.entries(headers)) {\n\t\t\t\t\tif (v !== undefined) {\n\t\t\t\t\t\tnormalizedHeaders[k.toLowerCase()] = v;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn normalizedHeaders;\n\t};\n\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) {\n\t\t\t// Try direct lookup first (common case: headers already lowercase)\n\t\t\tif (headers) {\n\t\t\t\tconst direct = headers[key] ?? headers[key.toLowerCase()];\n\t\t\t\tif (direct !== undefined) return direct;\n\t\t\t\t// Fall back to normalized lookup\n\t\t\t\treturn normalize()[key.toLowerCase()];\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\treturn normalize();\n\t}) as HeaderFn;\n}\n\n/**\n * Create a lazy cookie accessor for API Gateway events.\n * Decodes URL-encoded values to match browser behavior.\n */\nexport function createApiGatewayCookies(\n\tcookies: string[] | undefined,\n\tcookieHeader: string | undefined,\n): CookieFn {\n\tlet parsed: Record<string, string> | null = null;\n\n\tconst parse = () => {\n\t\tif (!parsed) {\n\t\t\tparsed = {};\n\t\t\t// API Gateway v2 provides cookies as array\n\t\t\tif (cookies) {\n\t\t\t\tfor (const cookie of cookies) {\n\t\t\t\t\tconst eqIndex = cookie.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = cookie.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = cookie.slice(eqIndex + 1);\n\t\t\t\t\t\tparsed[key] = decodeURIComponent(value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (cookieHeader) {\n\t\t\t\t// Fall back to parsing cookie header\n\t\t\t\tfor (const part of cookieHeader.split(';')) {\n\t\t\t\t\tconst trimmed = part.trim();\n\t\t\t\t\tconst eqIndex = trimmed.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = trimmed.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = trimmed.slice(eqIndex + 1);\n\t\t\t\t\t\tparsed[key] = decodeURIComponent(value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn parsed;\n\t};\n\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) {\n\t\t\treturn parse()[name];\n\t\t}\n\t\treturn parse();\n\t}) as CookieFn;\n}\n\n/**\n * Create a lazy header accessor for plain object headers (test adaptor, etc).\n * Headers are already available as an object, just provide lazy access.\n */\nexport function createObjectHeaders(\n\theaders: Record<string, string> | undefined,\n): HeaderFn {\n\tlet normalized: Record<string, string> | null = null;\n\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) {\n\t\t\t// Try direct lookup first (common case)\n\t\t\tif (headers) {\n\t\t\t\tconst direct = headers[key] ?? headers[key.toLowerCase()];\n\t\t\t\tif (direct !== undefined) return direct;\n\t\t\t}\n\t\t\t// Fall back to normalized lookup for case-insensitivity\n\t\t\tif (!normalized && headers) {\n\t\t\t\tnormalized = {};\n\t\t\t\tfor (const [k, v] of Object.entries(headers)) {\n\t\t\t\t\tnormalized[k.toLowerCase()] = v;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn normalized?.[key.toLowerCase()];\n\t\t}\n\t\t// Return all headers\n\t\tif (!normalized && headers) {\n\t\t\tnormalized = {};\n\t\t\tfor (const [k, v] of Object.entries(headers)) {\n\t\t\t\tnormalized[k.toLowerCase()] = v;\n\t\t\t}\n\t\t}\n\t\treturn normalized ?? {};\n\t}) as HeaderFn;\n}\n\n/**\n * Create a lazy cookie accessor from a cookie header string.\n * Decodes URL-encoded values to match browser behavior.\n */\nexport function createCookieHeaderAccessor(\n\tcookieHeader: string | undefined,\n): CookieFn {\n\tlet parsed: Record<string, string> | null = null;\n\n\tconst parse = () => {\n\t\tif (!parsed) {\n\t\t\tparsed = {};\n\t\t\tif (cookieHeader) {\n\t\t\t\tfor (const part of cookieHeader.split(';')) {\n\t\t\t\t\tconst trimmed = part.trim();\n\t\t\t\t\tconst eqIndex = trimmed.indexOf('=');\n\t\t\t\t\tif (eqIndex > 0) {\n\t\t\t\t\t\tconst key = trimmed.slice(0, eqIndex);\n\t\t\t\t\t\tconst value = trimmed.slice(eqIndex + 1);\n\t\t\t\t\t\t// Decode URL-encoded values to match Endpoint.createCookies behavior\n\t\t\t\t\t\tparsed[key] = decodeURIComponent(value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn parsed;\n\t};\n\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) {\n\t\t\treturn parse()[name];\n\t\t}\n\t\treturn parse();\n\t}) as CookieFn;\n}\n\n/**\n * Create a no-op header accessor (for minimal endpoints that don't use headers).\n */\nexport function createNoopHeaders(): HeaderFn {\n\treturn ((key?: string) => {\n\t\tif (key !== undefined) return undefined;\n\t\treturn {};\n\t}) as HeaderFn;\n}\n\n/**\n * Create a no-op cookie accessor (for minimal endpoints that don't use cookies).\n */\nexport function createNoopCookies(): CookieFn {\n\treturn ((name?: string) => {\n\t\tif (name !== undefined) return undefined;\n\t\treturn {};\n\t}) as CookieFn;\n}\n","import { HttpError } from '@geekmidas/errors';\n\n/**\n * The media types an endpoint's `.body()` schema can be handed — as written\n * in the 415 a request in any other type is answered with.\n */\nexport const SUPPORTED_BODY_TYPES = [\n\t'application/json',\n\t'application/x-www-form-urlencoded',\n\t'multipart/form-data',\n\t'text/*',\n] as const;\n\n/**\n * A request whose body is in a media type no endpoint reads — XML, a bare\n * octet stream. Answered with a 415, before the body schema runs.\n */\nexport class UnsupportedRequestContentType extends HttpError {\n\tconstructor(readonly contentType: string) {\n\t\tsuper(\n\t\t\t415,\n\t\t\t`A body sent as '${contentType}' can't be read. Send it as ${SUPPORTED_BODY_TYPES.join(', ')}.`,\n\t\t\t{\n\t\t\t\tstatusMessage: 'Unsupported Media Type',\n\t\t\t\tdetails: { contentType, supported: [...SUPPORTED_BODY_TYPES] },\n\t\t\t},\n\t\t);\n\t\tthis.name = 'UnsupportedRequestContentType';\n\t}\n}\n\n/**\n * A body that says it is JSON and is not. Answered with a 400 — the request\n * is broken, not merely invalid against the schema.\n */\nexport class MalformedRequestBody extends HttpError {\n\tconstructor(\n\t\treadonly contentType: string,\n\t\tcause?: Error,\n\t) {\n\t\tsuper(\n\t\t\t400,\n\t\t\t`The body says it is '${contentType}' but can't be parsed as that. Send a well-formed body, with the Content-Type it is written in.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'MalformedRequestBody';\n\t}\n}\n\n/**\n * What a body is read from: a `Request`, or Hono's request — which caches\n * what it read, so a later reader is not handed a spent stream.\n */\nexport interface RequestBodySource {\n\tjson(): Promise<unknown>;\n\ttext(): Promise<string>;\n\tformData(): Promise<FormData>;\n}\n\nexport interface ReadRequestBodyOptions {\n\t/**\n\t * A body with no Content-Type: read as JSON (`'json'`, what API Gateway\n\t * has always done), or not read at all and handed to the schema as `{}`\n\t * (`'empty'`, what a Hono server has always done).\n\t */\n\tuntyped: 'json' | 'empty';\n}\n\n/**\n * A request body, read by its Content-Type into what an endpoint's `.body()`\n * schema validates — the one place every adaptor reads a body:\n *\n * - `application/json` (and `application/*+json`) — the parsed JSON.\n * - `application/x-www-form-urlencoded` and `multipart/form-data` — a plain\n * object of fields, as an HTML form posts them. A repeated field, or one\n * named `field[]`, is an array; a file part is a `File`.\n * - `text/*` — the text.\n *\n * Anything else is an {@link UnsupportedRequestContentType}.\n */\nexport async function readRequestBody(\n\tsource: RequestBodySource,\n\tcontentType: string | null | undefined,\n\toptions: ReadRequestBodyOptions,\n): Promise<unknown> {\n\tconst mediaType = contentType?.split(';')[0]?.trim().toLowerCase();\n\n\tif (!mediaType) {\n\t\tif (options.untyped === 'empty') return {};\n\t\treturn readJson(source, 'application/json');\n\t}\n\n\tif (isJson(mediaType)) return readJson(source, mediaType);\n\n\tif (\n\t\tmediaType === 'application/x-www-form-urlencoded' ||\n\t\tmediaType === 'multipart/form-data'\n\t) {\n\t\treturn formFields(await readForm(source, mediaType));\n\t}\n\n\tif (mediaType.startsWith('text/')) return source.text();\n\n\tthrow new UnsupportedRequestContentType(mediaType);\n}\n\nfunction isJson(mediaType: string): boolean {\n\treturn (\n\t\tmediaType === 'application/json' ||\n\t\t(mediaType.startsWith('application/') && mediaType.endsWith('+json'))\n\t);\n}\n\nasync function readJson(\n\tsource: RequestBodySource,\n\tmediaType: string,\n): Promise<unknown> {\n\ttry {\n\t\treturn await source.json();\n\t} catch (error) {\n\t\tthrow new MalformedRequestBody(mediaType, error as Error);\n\t}\n}\n\nasync function readForm(\n\tsource: RequestBodySource,\n\tmediaType: string,\n): Promise<FormData> {\n\ttry {\n\t\treturn await source.formData();\n\t} catch (error) {\n\t\tthrow new MalformedRequestBody(mediaType, error as Error);\n\t}\n}\n\n/** A form field's value: its text, or a `File` for a file part. */\ntype FormValue = NonNullable<ReturnType<FormData['get']>>;\n\n/**\n * A form's fields as an object, the way Hono's `parseBody({ all: true })`\n * reads them. Without a prototype, so a field named `__proto__` is a field.\n */\nfunction formFields(form: FormData): Record<string, FormValue | FormValue[]> {\n\tconst fields: Record<string, FormValue | FormValue[]> = Object.create(null);\n\n\tfor (const [key, value] of form.entries()) {\n\t\tconst existing = fields[key];\n\t\tif (existing === undefined) {\n\t\t\tfields[key] = key.endsWith('[]') ? [value] : value;\n\t\t} else if (Array.isArray(existing)) {\n\t\t\texisting.push(value);\n\t\t} else {\n\t\t\tfields[key] = [existing, value];\n\t\t}\n\t}\n\n\treturn fields;\n}\n"],"mappings":";;;;;;;;AAgBA,SAAgB,kBAAkB,GAAsB;CACvD,IAAI,aAA4C;CAEhD,SAAS,QAAiB;EACzB,IAAI,QAAQ,KAAA,GAEX,OAAO,EAAE,IAAI,OAAO,GAAG;EAGxB,IAAI,CAAC,YACJ,aAAa,EAAE,IAAI,OAAO;EAE3B,OAAO;CACR;AACD;;;;;;AAOA,SAAgB,kBAAkB,GAAsB;CACvD,IAAI,aAA4C;CAEhD,SAAS,SAAkB;EAC1B,IAAI,SAAS,KAAA,GAEZ,QAAA,GAAOA,YAAAA,UAAAA,CAAU,GAAG,IAAI;EAGzB,IAAI,CAAC,YAAY;GAChB,aAAa,CAAC;GACd,MAAM,eAAe,EAAE,IAAI,OAAO,QAAQ;GAC1C,IAAI,c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Ac,uBAEd,OAAO,WAAW,MAAM,SAAS,QAAQ,SAAS,CAAC;CAGpD,IAAI,UAAU,WAAW,OAAO,GAAG,OAAO,OAAO,KAAK;CAEtD,MAAM,IAAI,8BAA8B,SAAS;AAClD;AAEA,SAAS,OAAO,WAA4B;CAC3C,OACC,cAAc,sBACb,UAAU,WAAW,cAAc,KAAK,UAAU,SAAS,OAAO;AAErE;AAEA,eAAe,SACd,QACA,WACmB;CACnB,IAAI;EACH,OAAO,MAAM,OAAO,KAAK;CAC1B,SAAS,OAAO;EACf,MAAM,IAAI,qBAAqB,WAAW,KAAc;CACzD;AACD;AAEA,eAAe,SACd,QACA,WACoB;CACpB,IAAI;EACH,OAAO,MAAM,OAAO,SAAS;CAC9B,SAAS,OAAO;EACf,MAAM,IAAI,qBAAqB,WAAW,KAAc;CACzD;AACD;;;;;AASA,SAAS,WAAW,MAAyD;CAC5E,MAAM,SAAkD,OAAO,OAAO,IAAI;CAE1E,KAAK,MAAM,CAAC,KAAK,UAAU,KAAK,QAAQ,GAAG;EAC1C,MAAM,WAAW,OAAO;EACxB,IAAI,aAAa,KAAA,GAChB,OAAO,OAAO,IAAI,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI;OACvC,IAAI,MAAM,QAAQ,QAAQ,GAChC,SAAS,KAAK,KAAK;OAEnB,OAAO,OAAO,CAAC,UAAU,KAAK;CAEhC;CAEA,OAAO;AACR"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"requestLogger-BZcXwdBs.cjs","names":[],"sources":["../src/endpoints/optionalPeers.ts","../src/endpoints/processAudits.ts","../src/endpoints/rateLimit.ts","../src/endpoints/requestLogger.ts"],"sourcesContent":["/**\n * The optional peers an endpoint needs only for a feature it opted into.\n *\n * `@geekmidas/audit`, `@geekmidas/rate-limit` and `@geekmidas/db` are optional\n * peers of this package: an app that audits nothing, limits nothing and sets\n * no row-level security need not install them. The adaptor every endpoint is\n * served by used to import them at the top, so serving any endpoint needed\n * them all — and a production bundle of an app without them failed to build.\n * They are loaded here, when an endpoint that uses one is served, which is\n * also when the app declaring that endpoint has installed it: an auditor's\n * storage, a rate limit's store and an RLS policy's database come from these\n * packages.\n *\n * The `try` is load-bearing beyond the error it names: a bundler leaves an\n * import it cannot resolve to run time when the import is guarded, and fails\n * the build when it is not.\n */\n\n/** An endpoint uses a feature whose optional peer is not installed. */\nexport class OptionalPeerMissing extends Error {\n\tconstructor(\n\t\treadonly packageName: string,\n\t\treadonly feature: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`${feature} needs '${packageName}', which could not be loaded. ` +\n\t\t\t\t`Add it to the dependencies of the app that serves this endpoint.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'OptionalPeerMissing';\n\t}\n}\n\n/** `@geekmidas/audit`, for an endpoint with an auditor. */\nexport async function loadAudit(): Promise<typeof import('@geekmidas/audit')> {\n\ttry {\n\t\treturn await import('@geekmidas/audit');\n\t} catch (cause) {\n\t\tthrow new OptionalPeerMissing(\n\t\t\t'@geekmidas/audit',\n\t\t\t'An endpoint with an auditor',\n\t\t\tcause,\n\t\t);\n\t}\n}\n\n/** `@geekmidas/rate-limit`, for an endpoint with a rate limit. */\nexport async function loadRateLimit(): Promise<\n\ttypeof import('@geekmidas/rate-limit')\n> {\n\ttry {\n\t\treturn await import('@geekmidas/rate-limit');\n\t} catch (cause) {\n\t\tthrow new OptionalPeerMissing(\n\t\t\t'@geekmidas/rate-limit',\n\t\t\t'An endpoint with a rate limit',\n\t\t\tcause,\n\t\t);\n\t}\n}\n\n/** `@geekmidas/db/rls`, for an endpoint with row-level security. */\nexport async function loadRls(): Promise<typeof import('@geekmidas/db/rls')> {\n\ttry {\n\t\treturn await import('@geekmidas/db/rls');\n\t} catch (cause) {\n\t\tthrow new OptionalPeerMissing(\n\t\t\t'@geekmidas/db',\n\t\t\t'An endpoint with row-level security',\n\t\t\tcause,\n\t\t);\n\t}\n}\n","import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditor,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type { CookieFn, Endpoint, HeaderFn } from './Endpoint';\nimport { loadAudit } from './optionalPeers';\n\n/**\n * Process declarative audit definitions after successful endpoint execution.\n * Similar to publishConstructEvents for events.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param response - The handler response to generate audit payloads from\n * @param serviceDiscovery - Service discovery for registering audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context (session, headers, cookies, services)\n * @param existingAuditor - Optional existing auditor instance (e.g., from handler context).\n * If provided, uses this auditor (with its stored transaction).\n * If not provided, creates a new auditor.\n */\nexport async function processEndpointAudits<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction\n\t>,\n\tresponse: InferStandardSchema<OutSchema>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n\texistingAuditor?: Auditor<TAuditAction>,\n): Promise<void> {\n\ttry {\n\t\tconst audits = endpoint.audits as MappedAudit<TAuditAction, OutSchema>[];\n\n\t\t// If we have an existing auditor (from handler context), we need to flush\n\t\t// any manual audits it collected, even if there are no declarative audits\n\t\tconst hasExistingRecords =\n\t\t\texistingAuditor && existingAuditor.getRecords().length > 0;\n\n\t\t// Skip if no declarative audits and no existing records to flush\n\t\tif (!audits?.length && !hasExistingRecords) {\n\t\t\tlogger.debug('No audits to process');\n\t\t\treturn;\n\t\t}\n\n\t\t// If no auditor storage service and we have things to process, warn\n\t\tif (!endpoint.auditorStorageService) {\n\t\t\tif (hasExistingRecords || audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Get or create auditor\n\t\tlet auditor: Auditor<TAuditAction>;\n\n\t\tif (existingAuditor) {\n\t\t\t// Use existing auditor (preserves stored transaction and manual audits)\n\t\t\tauditor = existingAuditor;\n\t\t\tlogger.debug('Using existing auditor from handler context');\n\t\t} else {\n\t\t\t// Create new auditor (backward compatibility)\n\t\t\tconst services = await serviceDiscovery.register([\n\t\t\t\tendpoint.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = services[\n\t\t\t\tendpoint.auditorStorageService.serviceName\n\t\t\t] as AuditStorage;\n\n\t\t\t// Extract actor if configured\n\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\tif (endpoint.actorExtractor) {\n\t\t\t\ttry {\n\t\t\t\t\tactor = await (\n\t\t\t\t\t\tendpoint.actorExtractor as ActorExtractor<\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\tTLogger\n\t\t\t\t\t\t>\n\t\t\t\t\t)({\n\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\theader: ctx.header,\n\t\t\t\t\t\tcookie: ctx.cookie,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t// Continue with system actor\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { DefaultAuditor } = await loadAudit();\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor,\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tendpoint: endpoint.route,\n\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Process each declarative audit\n\t\tif (audits?.length) {\n\t\t\tfor (const audit of audits) {\n\t\t\t\tlogger.debug({ audit: audit.type }, 'Processing declarative audit');\n\n\t\t\t\t// Check when condition\n\t\t\t\tif (audit.when && !audit.when(response as any)) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ audit: audit.type },\n\t\t\t\t\t\t'Audit skipped due to when condition',\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Extract payload\n\t\t\t\tconst payload = audit.payload(response as any);\n\n\t\t\t\t// Extract entityId if configured\n\t\t\t\tconst entityId = audit.entityId?.(response as any);\n\n\t\t\t\t// Record the audit\n\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\ttable: audit.table,\n\t\t\t\t\tentityId,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush audits to storage\n\t\t// Note: If existingAuditor has a stored transaction (via setTransaction),\n\t\t// flush() will use it automatically\n\t\tconst recordCount = auditor.getRecords().length;\n\t\tif (recordCount > 0) {\n\t\t\t// Check if auditor has a stored transaction (for logging purposes)\n\t\t\tconst trx =\n\t\t\t\t'getTransaction' in auditor\n\t\t\t\t\t? (auditor as { getTransaction(): unknown }).getTransaction()\n\t\t\t\t\t: undefined;\n\t\t\tlogger.debug(\n\t\t\t\t{ auditCount: recordCount, hasTransaction: !!trx },\n\t\t\t\t'Flushing audits',\n\t\t\t);\n\t\t\tawait auditor.flush();\n\t\t}\n\t} catch (error) {\n\t\tlogger.error(error as Error, 'Failed to process audits');\n\t\t// Don't rethrow - audit failures shouldn't fail the request\n\t}\n}\n\n/**\n * Context for audit-aware handler execution.\n */\nexport interface AuditExecutionContext<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\t/** The auditor instance for recording audits */\n\tauditor: Auditor<TAuditAction>;\n\t/** The audit storage instance */\n\tstorage: AuditStorage;\n}\n\n/**\n * Create audit context for handler execution.\n * Returns the auditor and storage for use in the handler.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param serviceDiscovery - Service discovery for getting audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context for actor extraction\n * @returns Audit context with auditor and storage, or undefined if not configured\n */\nexport async function createAuditContext<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n): Promise<AuditExecutionContext<TAuditAction> | undefined> {\n\tif (!endpoint.auditorStorageService) {\n\t\treturn undefined;\n\t}\n\n\tconst services = await serviceDiscovery.register([\n\t\tendpoint.auditorStorageService,\n\t]);\n\tconst storage = services[\n\t\tendpoint.auditorStorageService.serviceName\n\t] as AuditStorage;\n\n\t// Extract actor if configured\n\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\tif (endpoint.actorExtractor) {\n\t\ttry {\n\t\t\tactor = await (\n\t\t\t\tendpoint.actorExtractor as ActorExtractor<TServices, TSession, TLogger>\n\t\t\t)({\n\t\t\t\tservices: ctx.services as any,\n\t\t\t\tsession: ctx.session,\n\t\t\t\theader: ctx.header,\n\t\t\t\tcookie: ctx.cookie,\n\t\t\t\tlogger,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t}\n\t}\n\n\tconst { DefaultAuditor } = await loadAudit();\n\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\tactor,\n\t\tstorage,\n\t\tmetadata: {\n\t\t\tendpoint: endpoint.route,\n\t\t\tmethod: endpoint.method,\n\t\t},\n\t});\n\n\treturn { auditor, storage };\n}\n\n/**\n * Options for executeWithAuditTransaction.\n */\nexport interface ExecuteWithAuditTransactionOptions {\n\t/**\n\t * Database connection to use for the transaction.\n\t * If this is already a transaction, it will be reused instead of creating a nested one.\n\t * If not provided, the storage's internal database is used.\n\t */\n\tdb?: unknown;\n}\n\n/**\n * Execute a handler with automatic audit transaction support.\n * If the audit storage provides a withTransaction method, wraps execution\n * in a transaction so audits are atomic with handler's database operations.\n *\n * This is database-agnostic - each storage implementation provides its own\n * transaction handling based on the underlying database (Kysely, Drizzle, etc.).\n *\n * If the db parameter is provided and is already a transaction, the storage\n * will reuse it instead of creating a nested transaction (similar to\n * packages/db/src/kysely.ts#withTransaction).\n *\n * @param auditContext - The audit context from createAuditContext\n * @param handler - The handler function to execute (receives auditor)\n * @param onComplete - Called after handler with response, to process declarative audits\n * @param options - Optional configuration including database connection\n * @returns The handler result\n */\nexport async function executeWithAuditTransaction<\n\tT,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tauditContext: AuditExecutionContext<TAuditAction> | undefined,\n\thandler: (auditor?: Auditor<TAuditAction>) => Promise<T>,\n\tonComplete?: (response: T, auditor: Auditor<TAuditAction>) => Promise<void>,\n\toptions?: ExecuteWithAuditTransactionOptions,\n): Promise<T> {\n\t// No audit context - just run handler\n\tif (!auditContext) {\n\t\treturn handler(undefined);\n\t}\n\n\tconst { auditor, storage } = auditContext;\n\n\t// Check if storage provides a transaction wrapper\n\tif (storage.withTransaction) {\n\t\t// Wrap in transaction - audits are atomic with handler operations\n\t\t// The storage's withTransaction handles setTransaction and flush\n\t\t// Pass db so existing transactions are reused\n\t\treturn storage.withTransaction(\n\t\t\tauditor,\n\t\t\tasync () => {\n\t\t\t\tconst response = await handler(auditor);\n\n\t\t\t\t// Process declarative audits within the transaction\n\t\t\t\tif (onComplete) {\n\t\t\t\t\tawait onComplete(response, auditor);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t},\n\t\t\toptions?.db,\n\t\t);\n\t}\n\n\t// No transaction support - run handler and flush audits after\n\tconst response = await handler(auditor);\n\n\tif (onComplete) {\n\t\tawait onComplete(response, auditor);\n\t}\n\n\t// Flush audits (no transaction)\n\tawait auditor.flush();\n\n\treturn response;\n}\n","import type { RateLimitConfig, RateLimitContext } from '@geekmidas/rate-limit';\nimport { loadRateLimit } from './optionalPeers';\n\n/**\n * An endpoint's `.rateLimit()`, checked the one way every adaptor checks it —\n * Hono, Lambda and the test adaptor — after the request is authorized.\n *\n * Under the limit, it answers the headers the response carries:\n * `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (and\n * `Retry-After` on the last request the window allows).\n *\n * @throws {TooManyRequestsError} over the limit — `@geekmidas/errors`' 429,\n * whose `headers` hold `Retry-After` (seconds until the window resets) and the\n * same `X-RateLimit-*`, which every adaptor sets on the error response.\n */\nexport async function enforceRateLimit(\n\tconfig: RateLimitConfig,\n\tctx: RateLimitContext<any, any, any>,\n): Promise<Record<string, string>> {\n\tconst { checkRateLimit, getRateLimitHeaders } = await loadRateLimit();\n\tconst info = await checkRateLimit(config, ctx);\n\n\tconst headers: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(\n\t\tgetRateLimitHeaders(info, config),\n\t)) {\n\t\tif (value !== undefined) headers[key] = value;\n\t}\n\treturn headers;\n}\n","import type { Logger } from '@geekmidas/logger';\n\n/** What an endpoint contributes to every line logged for one of its requests. */\ninterface LoggingEndpoint {\n\tlogger: Logger;\n\tfullPath: string;\n\troute: string;\n\tmethod: string;\n}\n\n/**\n * The logger for one request to `endpoint`: the surface's, bound with which\n * request it is and what it was for — the request id, the endpoint, its route\n * and method — plus whatever the adaptor knows of the request itself (host,\n * path, the Lambda and API Gateway context).\n *\n * One per request, made once, and the one the request context carries: the\n * handler logs through it, a service reaches it through the context, and\n * identifying the request (`identifyRequest`) derives the signed-in user's\n * logger from it — so a line says whose request it was without losing which\n * route it came from. A field the request does not have is left out rather\n * than logged as `undefined`.\n */\nexport function requestLogger<TLogger extends Logger>(\n\tendpoint: LoggingEndpoint,\n\tfields: { requestId: string } & Record<string, unknown>,\n): TLogger {\n\tconst { requestId, ...request } = fields;\n\tconst bindings: Record<string, unknown> = {\n\t\trequestId,\n\t\tendpoint: endpoint.fullPath,\n\t\troute: endpoint.route,\n\t\tmethod: endpoint.method,\n\t};\n\tfor (const [key, value] of Object.entries(request)) {\n\t\tif (value !== undefined) bindings[key] = value;\n\t}\n\treturn endpoint.logger.child(bindings) as TLogger;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,IAAa,sBAAb,cAAyC,MAAM;CAEpC;CACA;CAFV,YACC,aACA,SACA,OACC;EACD,MACC,GAAG,QAAQ,UAAU,YAAY,iGAEjC,EAAE,MAAM,CACT;EARS,KAAA,cAAA;EACA,KAAA,UAAA;EAQT,KAAK,OAAO;CACb;AACD;;AAGA,eAAsB,YAAwD;CAC7E,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,SAAS,OAAO;EACf,MAAM,IAAI,oBACT,oBACA,+BACA,KACD;CACD;AACD;;AAGA,eAAsB,gBAEpB;CACD,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,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;;;;;;;;;ACjWA,eAAsB,iBACrB,QACA,KACkC;CAClC,MAAM,EAAE,gBAAgB,wBAAwB,MAAM,cAAc;CACpE,MAAM,OAAO,MAAM,eAAe,QAAQ,GAAG;CAE7C,MAAM,UAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QACjC,oBAAoB,MAAM,MAAM,CACjC,GACC,IAAI,UAAU,KAAA,GAAW,QAAQ,OAAO;CAEzC,OAAO;AACR;;;;;;;;;;;;;;;;ACNA,SAAgB,cACf,UACA,QACU;CACV,MAAM,EAAE,WAAW,GAAG,YAAY;CAClC,MAAM,WAAoC;EACzC;EACA,UAAU,SAAS;EACnB,OAAO,SAAS;EAChB,QAAQ,SAAS;CAClB;CACA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAChD,IAAI,UAAU,KAAA,GAAW,SAAS,OAAO;CAE1C,OAAO,SAAS,OAAO,MAAM,QAAQ;AACtC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"requestLogger-pA4gi3E1.mjs","names":[],"sources":["../src/endpoints/optionalPeers.ts","../src/endpoints/processAudits.ts","../src/endpoints/rateLimit.ts","../src/endpoints/requestLogger.ts"],"sourcesContent":["/**\n * The optional peers an endpoint needs only for a feature it opted into.\n *\n * `@geekmidas/audit`, `@geekmidas/rate-limit` and `@geekmidas/db` are optional\n * peers of this package: an app that audits nothing, limits nothing and sets\n * no row-level security need not install them. The adaptor every endpoint is\n * served by used to import them at the top, so serving any endpoint needed\n * them all — and a production bundle of an app without them failed to build.\n * They are loaded here, when an endpoint that uses one is served, which is\n * also when the app declaring that endpoint has installed it: an auditor's\n * storage, a rate limit's store and an RLS policy's database come from these\n * packages.\n *\n * The `try` is load-bearing beyond the error it names: a bundler leaves an\n * import it cannot resolve to run time when the import is guarded, and fails\n * the build when it is not.\n */\n\n/** An endpoint uses a feature whose optional peer is not installed. */\nexport class OptionalPeerMissing extends Error {\n\tconstructor(\n\t\treadonly packageName: string,\n\t\treadonly feature: string,\n\t\tcause: unknown,\n\t) {\n\t\tsuper(\n\t\t\t`${feature} needs '${packageName}', which could not be loaded. ` +\n\t\t\t\t`Add it to the dependencies of the app that serves this endpoint.`,\n\t\t\t{ cause },\n\t\t);\n\t\tthis.name = 'OptionalPeerMissing';\n\t}\n}\n\n/** `@geekmidas/audit`, for an endpoint with an auditor. */\nexport async function loadAudit(): Promise<typeof import('@geekmidas/audit')> {\n\ttry {\n\t\treturn await import('@geekmidas/audit');\n\t} catch (cause) {\n\t\tthrow new OptionalPeerMissing(\n\t\t\t'@geekmidas/audit',\n\t\t\t'An endpoint with an auditor',\n\t\t\tcause,\n\t\t);\n\t}\n}\n\n/** `@geekmidas/rate-limit`, for an endpoint with a rate limit. */\nexport async function loadRateLimit(): Promise<\n\ttypeof import('@geekmidas/rate-limit')\n> {\n\ttry {\n\t\treturn await import('@geekmidas/rate-limit');\n\t} catch (cause) {\n\t\tthrow new OptionalPeerMissing(\n\t\t\t'@geekmidas/rate-limit',\n\t\t\t'An endpoint with a rate limit',\n\t\t\tcause,\n\t\t);\n\t}\n}\n\n/** `@geekmidas/db/rls`, for an endpoint with row-level security. */\nexport async function loadRls(): Promise<typeof import('@geekmidas/db/rls')> {\n\ttry {\n\t\treturn await import('@geekmidas/db/rls');\n\t} catch (cause) {\n\t\tthrow new OptionalPeerMissing(\n\t\t\t'@geekmidas/db',\n\t\t\t'An endpoint with row-level security',\n\t\t\tcause,\n\t\t);\n\t}\n}\n","import type {\n\tAuditActor,\n\tAuditableAction,\n\tAuditor,\n\tAuditStorage,\n} from '@geekmidas/audit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { ActorExtractor, MappedAudit } from './audit';\nimport type { CookieFn, Endpoint, HeaderFn } from './Endpoint';\nimport { loadAudit } from './optionalPeers';\n\n/**\n * Process declarative audit definitions after successful endpoint execution.\n * Similar to publishConstructEvents for events.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param response - The handler response to generate audit payloads from\n * @param serviceDiscovery - Service discovery for registering audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context (session, headers, cookies, services)\n * @param existingAuditor - Optional existing auditor instance (e.g., from handler context).\n * If provided, uses this auditor (with its stored transaction).\n * If not provided, creates a new auditor.\n */\nexport async function processEndpointAudits<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tOutSchema extends StandardSchemaV1 | undefined = undefined,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tOutSchema,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction\n\t>,\n\tresponse: InferStandardSchema<OutSchema>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n\texistingAuditor?: Auditor<TAuditAction>,\n): Promise<void> {\n\ttry {\n\t\tconst audits = endpoint.audits as MappedAudit<TAuditAction, OutSchema>[];\n\n\t\t// If we have an existing auditor (from handler context), we need to flush\n\t\t// any manual audits it collected, even if there are no declarative audits\n\t\tconst hasExistingRecords =\n\t\t\texistingAuditor && existingAuditor.getRecords().length > 0;\n\n\t\t// Skip if no declarative audits and no existing records to flush\n\t\tif (!audits?.length && !hasExistingRecords) {\n\t\t\tlogger.debug('No audits to process');\n\t\t\treturn;\n\t\t}\n\n\t\t// If no auditor storage service and we have things to process, warn\n\t\tif (!endpoint.auditorStorageService) {\n\t\t\tif (hasExistingRecords || audits?.length) {\n\t\t\t\tlogger.warn('No auditor storage service available');\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// Get or create auditor\n\t\tlet auditor: Auditor<TAuditAction>;\n\n\t\tif (existingAuditor) {\n\t\t\t// Use existing auditor (preserves stored transaction and manual audits)\n\t\t\tauditor = existingAuditor;\n\t\t\tlogger.debug('Using existing auditor from handler context');\n\t\t} else {\n\t\t\t// Create new auditor (backward compatibility)\n\t\t\tconst services = await serviceDiscovery.register([\n\t\t\t\tendpoint.auditorStorageService,\n\t\t\t]);\n\t\t\tconst storage = services[\n\t\t\t\tendpoint.auditorStorageService.serviceName\n\t\t\t] as AuditStorage;\n\n\t\t\t// Extract actor if configured\n\t\t\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\t\t\tif (endpoint.actorExtractor) {\n\t\t\t\ttry {\n\t\t\t\t\tactor = await (\n\t\t\t\t\t\tendpoint.actorExtractor as ActorExtractor<\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTSession,\n\t\t\t\t\t\t\tTLogger\n\t\t\t\t\t\t>\n\t\t\t\t\t)({\n\t\t\t\t\t\tservices: ctx.services as any,\n\t\t\t\t\t\tsession: ctx.session,\n\t\t\t\t\t\theader: ctx.header,\n\t\t\t\t\t\tcookie: ctx.cookie,\n\t\t\t\t\t\tlogger,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t\t\t\t// Continue with system actor\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst { DefaultAuditor } = await loadAudit();\n\t\t\tauditor = new DefaultAuditor<TAuditAction>({\n\t\t\t\tactor,\n\t\t\t\tstorage,\n\t\t\t\tmetadata: {\n\t\t\t\t\tendpoint: endpoint.route,\n\t\t\t\t\tmethod: endpoint.method,\n\t\t\t\t},\n\t\t\t});\n\t\t}\n\n\t\t// Process each declarative audit\n\t\tif (audits?.length) {\n\t\t\tfor (const audit of audits) {\n\t\t\t\tlogger.debug({ audit: audit.type }, 'Processing declarative audit');\n\n\t\t\t\t// Check when condition\n\t\t\t\tif (audit.when && !audit.when(response as any)) {\n\t\t\t\t\tlogger.debug(\n\t\t\t\t\t\t{ audit: audit.type },\n\t\t\t\t\t\t'Audit skipped due to when condition',\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Extract payload\n\t\t\t\tconst payload = audit.payload(response as any);\n\n\t\t\t\t// Extract entityId if configured\n\t\t\t\tconst entityId = audit.entityId?.(response as any);\n\n\t\t\t\t// Record the audit\n\t\t\t\tauditor.audit(audit.type as any, payload as any, {\n\t\t\t\t\ttable: audit.table,\n\t\t\t\t\tentityId,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Flush audits to storage\n\t\t// Note: If existingAuditor has a stored transaction (via setTransaction),\n\t\t// flush() will use it automatically\n\t\tconst recordCount = auditor.getRecords().length;\n\t\tif (recordCount > 0) {\n\t\t\t// Check if auditor has a stored transaction (for logging purposes)\n\t\t\tconst trx =\n\t\t\t\t'getTransaction' in auditor\n\t\t\t\t\t? (auditor as { getTransaction(): unknown }).getTransaction()\n\t\t\t\t\t: undefined;\n\t\t\tlogger.debug(\n\t\t\t\t{ auditCount: recordCount, hasTransaction: !!trx },\n\t\t\t\t'Flushing audits',\n\t\t\t);\n\t\t\tawait auditor.flush();\n\t\t}\n\t} catch (error) {\n\t\tlogger.error(error as Error, 'Failed to process audits');\n\t\t// Don't rethrow - audit failures shouldn't fail the request\n\t}\n}\n\n/**\n * Context for audit-aware handler execution.\n */\nexport interface AuditExecutionContext<\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n> {\n\t/** The auditor instance for recording audits */\n\tauditor: Auditor<TAuditAction>;\n\t/** The audit storage instance */\n\tstorage: AuditStorage;\n}\n\n/**\n * Create audit context for handler execution.\n * Returns the auditor and storage for use in the handler.\n *\n * @param endpoint - The endpoint with audit configuration\n * @param serviceDiscovery - Service discovery for getting audit storage\n * @param logger - Logger for debug/error messages\n * @param ctx - Request context for actor extraction\n * @returns Audit context with auditor and storage, or undefined if not configured\n */\nexport async function createAuditContext<\n\tTServices extends Service[] = [],\n\tTSession = unknown,\n\tTLogger extends Logger = Logger,\n\tTAuditStorage extends AuditStorage | undefined = undefined,\n\tTAuditStorageServiceName extends string = string,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n\tTDatabase = undefined,\n\tTDatabaseServiceName extends string = string,\n>(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tTServices,\n\t\tTLogger,\n\t\tTSession,\n\t\tTAuditStorage,\n\t\tTAuditStorageServiceName,\n\t\tTAuditAction,\n\t\tTDatabase,\n\t\tTDatabaseServiceName\n\t>,\n\tserviceDiscovery: ServiceDiscovery<any>,\n\tlogger: TLogger,\n\tctx: {\n\t\tsession: TSession;\n\t\theader: HeaderFn;\n\t\tcookie: CookieFn;\n\t\tservices: Record<string, unknown>;\n\t},\n): Promise<AuditExecutionContext<TAuditAction> | undefined> {\n\tif (!endpoint.auditorStorageService) {\n\t\treturn undefined;\n\t}\n\n\tconst services = await serviceDiscovery.register([\n\t\tendpoint.auditorStorageService,\n\t]);\n\tconst storage = services[\n\t\tendpoint.auditorStorageService.serviceName\n\t] as AuditStorage;\n\n\t// Extract actor if configured\n\tlet actor: AuditActor = { id: 'system', type: 'system' };\n\tif (endpoint.actorExtractor) {\n\t\ttry {\n\t\t\tactor = await (\n\t\t\t\tendpoint.actorExtractor as ActorExtractor<TServices, TSession, TLogger>\n\t\t\t)({\n\t\t\t\tservices: ctx.services as any,\n\t\t\t\tsession: ctx.session,\n\t\t\t\theader: ctx.header,\n\t\t\t\tcookie: ctx.cookie,\n\t\t\t\tlogger,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tlogger.error(error as Error, 'Failed to extract actor for audits');\n\t\t}\n\t}\n\n\tconst { DefaultAuditor } = await loadAudit();\n\tconst auditor = new DefaultAuditor<TAuditAction>({\n\t\tactor,\n\t\tstorage,\n\t\tmetadata: {\n\t\t\tendpoint: endpoint.route,\n\t\t\tmethod: endpoint.method,\n\t\t},\n\t});\n\n\treturn { auditor, storage };\n}\n\n/**\n * Options for executeWithAuditTransaction.\n */\nexport interface ExecuteWithAuditTransactionOptions {\n\t/**\n\t * Database connection to use for the transaction.\n\t * If this is already a transaction, it will be reused instead of creating a nested one.\n\t * If not provided, the storage's internal database is used.\n\t */\n\tdb?: unknown;\n}\n\n/**\n * Execute a handler with automatic audit transaction support.\n * If the audit storage provides a withTransaction method, wraps execution\n * in a transaction so audits are atomic with handler's database operations.\n *\n * This is database-agnostic - each storage implementation provides its own\n * transaction handling based on the underlying database (Kysely, Drizzle, etc.).\n *\n * If the db parameter is provided and is already a transaction, the storage\n * will reuse it instead of creating a nested transaction (similar to\n * packages/db/src/kysely.ts#withTransaction).\n *\n * @param auditContext - The audit context from createAuditContext\n * @param handler - The handler function to execute (receives auditor)\n * @param onComplete - Called after handler with response, to process declarative audits\n * @param options - Optional configuration including database connection\n * @returns The handler result\n */\nexport async function executeWithAuditTransaction<\n\tT,\n\tTAuditAction extends AuditableAction<string, unknown> = AuditableAction<\n\t\tstring,\n\t\tunknown\n\t>,\n>(\n\tauditContext: AuditExecutionContext<TAuditAction> | undefined,\n\thandler: (auditor?: Auditor<TAuditAction>) => Promise<T>,\n\tonComplete?: (response: T, auditor: Auditor<TAuditAction>) => Promise<void>,\n\toptions?: ExecuteWithAuditTransactionOptions,\n): Promise<T> {\n\t// No audit context - just run handler\n\tif (!auditContext) {\n\t\treturn handler(undefined);\n\t}\n\n\tconst { auditor, storage } = auditContext;\n\n\t// Check if storage provides a transaction wrapper\n\tif (storage.withTransaction) {\n\t\t// Wrap in transaction - audits are atomic with handler operations\n\t\t// The storage's withTransaction handles setTransaction and flush\n\t\t// Pass db so existing transactions are reused\n\t\treturn storage.withTransaction(\n\t\t\tauditor,\n\t\t\tasync () => {\n\t\t\t\tconst response = await handler(auditor);\n\n\t\t\t\t// Process declarative audits within the transaction\n\t\t\t\tif (onComplete) {\n\t\t\t\t\tawait onComplete(response, auditor);\n\t\t\t\t}\n\n\t\t\t\treturn response;\n\t\t\t},\n\t\t\toptions?.db,\n\t\t);\n\t}\n\n\t// No transaction support - run handler and flush audits after\n\tconst response = await handler(auditor);\n\n\tif (onComplete) {\n\t\tawait onComplete(response, auditor);\n\t}\n\n\t// Flush audits (no transaction)\n\tawait auditor.flush();\n\n\treturn response;\n}\n","import type { RateLimitConfig, RateLimitContext } from '@geekmidas/rate-limit';\nimport { loadRateLimit } from './optionalPeers';\n\n/**\n * An endpoint's `.rateLimit()`, checked the one way every adaptor checks it —\n * Hono, Lambda and the test adaptor — after the request is authorized.\n *\n * Under the limit, it answers the headers the response carries:\n * `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset` (and\n * `Retry-After` on the last request the window allows).\n *\n * @throws {TooManyRequestsError} over the limit — `@geekmidas/errors`' 429,\n * whose `headers` hold `Retry-After` (seconds until the window resets) and the\n * same `X-RateLimit-*`, which every adaptor sets on the error response.\n */\nexport async function enforceRateLimit(\n\tconfig: RateLimitConfig,\n\tctx: RateLimitContext<any, any, any>,\n): Promise<Record<string, string>> {\n\tconst { checkRateLimit, getRateLimitHeaders } = await loadRateLimit();\n\tconst info = await checkRateLimit(config, ctx);\n\n\tconst headers: Record<string, string> = {};\n\tfor (const [key, value] of Object.entries(\n\t\tgetRateLimitHeaders(info, config),\n\t)) {\n\t\tif (value !== undefined) headers[key] = value;\n\t}\n\treturn headers;\n}\n","import type { Logger } from '@geekmidas/logger';\n\n/** What an endpoint contributes to every line logged for one of its requests. */\ninterface LoggingEndpoint {\n\tlogger: Logger;\n\tfullPath: string;\n\troute: string;\n\tmethod: string;\n}\n\n/**\n * The logger for one request to `endpoint`: the surface's, bound with which\n * request it is and what it was for — the request id, the endpoint, its route\n * and method — plus whatever the adaptor knows of the request itself (host,\n * path, the Lambda and API Gateway context).\n *\n * One per request, made once, and the one the request context carries: the\n * handler logs through it, a service reaches it through the context, and\n * identifying the request (`identifyRequest`) derives the signed-in user's\n * logger from it — so a line says whose request it was without losing which\n * route it came from. A field the request does not have is left out rather\n * than logged as `undefined`.\n */\nexport function requestLogger<TLogger extends Logger>(\n\tendpoint: LoggingEndpoint,\n\tfields: { requestId: string } & Record<string, unknown>,\n): TLogger {\n\tconst { requestId, ...request } = fields;\n\tconst bindings: Record<string, unknown> = {\n\t\trequestId,\n\t\tendpoint: endpoint.fullPath,\n\t\troute: endpoint.route,\n\t\tmethod: endpoint.method,\n\t};\n\tfor (const [key, value] of Object.entries(request)) {\n\t\tif (value !== undefined) bindings[key] = value;\n\t}\n\treturn endpoint.logger.child(bindings) as TLogger;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmBA,IAAa,sBAAb,cAAyC,MAAM;CAEpC;CACA;CAFV,YACC,aACA,SACA,OACC;EACD,MACC,GAAG,QAAQ,UAAU,YAAY,iGAEjC,EAAE,MAAM,CACT;EARS,KAAA,cAAA;EACA,KAAA,UAAA;EAQT,KAAK,OAAO;CACb;AACD;;AAGA,eAAsB,YAAwD;CAC7E,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,SAAS,OAAO;EACf,MAAM,IAAI,oBACT,oBACA,+BACA,KACD;CACD;AACD;;AAGA,eAAsB,gBAEpB;CACD,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,SAAS,OAAO;EACf,MAAM,IAAI,oBACT,yBACA,iCACA,KACD;CACD;AACD;;AAGA,eAAsB,UAAuD;CAC5E,IAAI;EACH,OAAO,MAAM,OAAO;CACrB,SAAS,OAAO;EACf,MAAM,IAAI,oBACT,iBACA,uCACA,KACD;CACD;AACD;;;;;;;;;;;;;ACwIA,eAAsB,mBAarB,UAcA,kBACA,QACA,KAM2D;CAC3D,IAAI,CAAC,SA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,OAAO;CAEzC,OAAO;AACR;;;;;;;;;;;;;;;;ACNA,SAAgB,cACf,UACA,QACU;CACV,MAAM,EAAE,WAAW,GAAG,YAAY;CAClC,MAAM,WAAoC;EACzC;EACA,UAAU,SAAS;EACnB,OAAO,SAAS;EAChB,QAAQ,SAAS;CAClB;CACA,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAChD,IAAI,UAAU,KAAA,GAAW,SAAS,OAAO;CAE1C,OAAO,SAAS,OAAO,MAAM,QAAQ;AACtC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runSubscriber-CC_2C9F2.cjs","names":["INBOX_EVENT","ServiceDiscovery"],"sources":["../src/subscribers/runSubscriber.ts"],"sourcesContent":["/**\n * What a subscriber does with a batch of records, however they arrived: parse\n * them into events, keep the ones it subscribed to, and run its handler with\n * its services and database.\n *\n * Shared by the Lambda adaptor, which wraps it in middy, and the SNS push\n * adaptor, which a server runs and which must not need middy to load.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { INBOX_EVENT } from '@geekmidas/manifest';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { SNSEvent, SNSEventRecord, SQSEvent, SQSRecord } from 'aws-lambda';\nimport type { Subscriber } from './Subscriber';\n\ntype AnySubscriber = Subscriber<any, any, any, any, any, any, any>;\n\n/** The subscriber's output did not match its `.output()` schema. */\nexport class SubscriberOutputInvalid extends Error {\n\tconstructor(readonly issues: ReadonlyArray<unknown>) {\n\t\tsuper(\n\t\t\t\"Subscriber output validation failed: the handler's result does not match its .output() schema.\",\n\t\t);\n\t\tthis.name = 'SubscriberOutputInvalid';\n\t}\n}\n\n/** The events in an SQS or SNS batch (a Lambda event's `Records`) that `subscriber` subscribed to. */\nexport async function subscribedEvents(\n\tsubscriber: AnySubscriber,\n\trawEvent: { Records?: readonly unknown[] },\n\tlogger: Logger,\n): Promise<any[]> {\n\tconst events: any[] = [];\n\tconst records = rawEvent.Records ?? [];\n\tconst first = records[0] as any;\n\tconst parse =\n\t\tfirst?.eventSource === 'aws:sqs'\n\t\t\t? (record: any) => parseSQSRecord(record)\n\t\t\t: first?.EventSource === 'aws:sns'\n\t\t\t\t? (record: any) => parseSNSRecord(record)\n\t\t\t\t: undefined;\n\tif (!parse) return events;\n\n\t// A bucket's subscriber is sent what the storage sends — a notification\n\t// of records — and reads it as object events. Loaded only then: an app\n\t// with no bucket never installs the storage package.\n\tconst toObjectEvents = subscriber.bucketName\n\t\t? (await import('@geekmidas/storage/events')).toObjectEvents\n\t\t: undefined;\n\n\tfor (const record of records) {\n\t\ttry {\n\t\t\tconst event = parse(record);\n\t\t\tconst untyped = !(typeof event === 'object' && event?.type);\n\t\t\t// An inbox's subscriber is sent SES's receipt notification as SES\n\t\t\t// wrote it, with no type of ours on it.\n\t\t\tconst parsed =\n\t\t\t\tsubscriber.inboxName && untyped\n\t\t\t\t\t? [{ type: INBOX_EVENT, payload: event }]\n\t\t\t\t\t: toObjectEvents && untyped\n\t\t\t\t\t\t? toObjectEvents(event)\n\t\t\t\t\t\t: [event];\n\t\t\tfor (const one of parsed) {\n\t\t\t\tif (isSubscribed(subscriber, one)) events.push(one);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error({ err: error, record }, 'Failed to parse record');\n\t\t}\n\t}\n\treturn events;\n}\n\n/** The subscriber's services and database, registered as functions do. */\nexport async function subscriberContext(\n\tsubscriber: AnySubscriber,\n\tenvParser: EnvironmentParser<{}>,\n): Promise<{ services: Record<string, unknown>; db: unknown }> {\n\tconst discovery = ServiceDiscovery.getInstance(envParser);\n\tconst services =\n\t\tsubscriber.services.length > 0\n\t\t\t? await discovery.register(subscriber.services)\n\t\t\t: {};\n\tconst service = subscriber.databaseService;\n\tconst db = service\n\t\t? (await discovery.register([service]))[service.serviceName]\n\t\t: undefined;\n\treturn { services, db };\n}\n\n/** Runs the handler on `events`, and checks its output against its schema. */\nexport async function runSubscriber(\n\tsubscriber: AnySubscriber,\n\tcontext: {\n\t\tevents: any[];\n\t\tservices: Record<string, unknown>;\n\t\tdb: unknown;\n\t\tlogger: Logger;\n\t},\n): Promise<unknown> {\n\tif (context.events.length === 0) {\n\t\tcontext.logger.info('No subscribed events to process');\n\t\treturn { batchItemFailures: [] };\n\t}\n\n\tconst { events, services, db, logger } = context;\n\tconst result = await subscriber.handler({\n\t\tevents,\n\t\tservices,\n\t\tlogger,\n\t\tdb,\n\t} as any);\n\n\tif (subscriber.outputSchema && result) {\n\t\tconst validation =\n\t\t\tawait subscriber.outputSchema['~standard'].validate(result);\n\t\tif (validation.issues) {\n\t\t\tcontext.logger.error(\n\t\t\t\t{ issues: validation.issues },\n\t\t\t\t'Subscriber output validation failed',\n\t\t\t);\n\t\t\tthrow new SubscriberOutputInvalid(validation.issues);\n\t\t}\n\t\treturn validation.value;\n\t}\n\n\treturn result;\n}\n\nfunction isSubscribed(subscriber: AnySubscriber, event: any): boolean {\n\t// No event type (raw string/non-object) — always include\n\tif (typeof event !== 'object' || !event?.type) return true;\n\t// No filter configured — accept all\n\tif (!subscriber.subscribedEvents) return true;\n\treturn subscriber.subscribedEvents.includes(event.type);\n}\n\nfunction parseSNSRecord(record: SNSEventRecord): any {\n\tconst message = safeJsonParse(record.Sns.Message);\n\tconst messageType = record.Sns.MessageAttributes?.type?.Value;\n\n\t// Not JSON — wrap raw string with type from MessageAttributes if available\n\tif (message === null) {\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: record.Sns.Message }\n\t\t\t: record.Sns.Message;\n\t}\n\n\tif (message.type) {\n\t\treturn message; // Full event format: { type, payload }\n\t}\n\n\t// Payload-only format: type is in MessageAttributes\n\treturn messageType ? { type: messageType, payload: message } : message;\n}\n\nfunction parseSQSRecord(record: SQSRecord): any {\n\tconst body = safeJsonParse(record.body);\n\n\t// Not JSON — return raw body as-is\n\tif (body === null) {\n\t\treturn record.body;\n\t}\n\n\t// Check if this is an SNS message wrapped in SQS\n\tif (body.Type === 'Notification' && body.Message) {\n\t\tconst snsMessage = safeJsonParse(body.Message);\n\t\tconst messageType = body.MessageAttributes?.type?.Value;\n\n\t\t// SNS Message not JSON — wrap with type from MessageAttributes if available\n\t\tif (snsMessage === null) {\n\t\t\treturn messageType\n\t\t\t\t? { type: messageType, payload: body.Message }\n\t\t\t\t: body.Message;\n\t\t}\n\n\t\tif (snsMessage.type) {\n\t\t\treturn snsMessage; // Full event format: { type, payload }\n\t\t}\n\n\t\t// Payload-only format: type is in MessageAttributes\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: snsMessage }\n\t\t\t: snsMessage;\n\t}\n\n\t// Direct SQS message\n\treturn body;\n}\n\nfunction safeJsonParse(value: string): any | null {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;AAmBA,IAAa,0BAAb,cAA6C,MAAM;CAC7B;CAArB,YAAY,QAAyC;EACpD,MACC,gGACD;EAHoB,KAAA,SAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,eAAsB,iBACrB,YACA,UACA,QACiB;CACjB,MAAM,SAAgB,CAAC;CACvB,MAAM,UAAU,SAAS,WAAW,CAAC;CACrC,MAAM,QAAQ,QAAQ;CACtB,MAAM,QACL,OAAO,gBAAgB,aACnB,WAAgB,eAAe,MAAM,IACtC,OAAO,gBAAgB,aACrB,WAAgB,eAAe,MAAM,IACtC,KAAA;CACL,IAAI,CAAC,OAAO,OAAO;CAKnB,MAAM,iBAAiB,WAAW,cAC9B,MAAM,OAAO,6BAAA,CAA8B,iBAC5C,KAAA;CAEH,KAAK,MAAM,UAAU,SACpB,IAAI;EACH,MAAM,QAAQ,MAAM,MAAM;EAC1B,MAAM,UAAU,EAAE,OAAO,UAAU,YAAY,OAAO;EAGtD,MAAM,SACL,WAAW,aAAa,UACrB,CAAC;GAAE,MAAMA,oBAAAA;GAAa,SAAS;EAAM,CAAC,IACtC,kBAAkB,UACjB,eAAe,KAAK,IACpB,CAAC,KAAK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Ac,OAAO,IAAI,OAAO;CAChD,MAAM,cAAc,OAAO,IAAI,mBAAmB,MAAM;CAGxD,IAAI,YAAY,MACf,OAAO,cACJ;EAAE,MAAM;EAAa,SAAS,OAAO,IAAI;CAAQ,IACjD,OAAO,IAAI;CAGf,IAAI,QAAQ,MACX,OAAO;CAIR,OAAO,cAAc;EAAE,MAAM;EAAa,SAAS;CAAQ,IAAI;AAChE;AAEA,SAAS,eAAe,QAAwB;CAC/C,MAAM,OAAO,cAAc,OAAO,IAAI;CAGtC,IAAI,SAAS,MACZ,OAAO,OAAO;CAIf,IAAI,KAAK,SAAS,kBAAkB,KAAK,SAAS;EACjD,MAAM,aAAa,cAAc,KAAK,OAAO;EAC7C,MAAM,cAAc,KAAK,mBAAmB,MAAM;EAGlD,IAAI,eAAe,MAClB,OAAO,cACJ;GAAE,MAAM;GAAa,SAAS,KAAK;EAAQ,IAC3C,KAAK;EAGT,IAAI,WAAW,MACd,OAAO;EAIR,OAAO,cACJ;GAAE,MAAM;GAAa,SAAS;EAAW,IACzC;CACJ;CAGA,OAAO;AACR;AAEA,SAAS,cAAc,OAA2B;CACjD,IAAI;EACH,OAAO,KAAK,MAAM,KAAK;CACxB,QAAQ;EACP,OAAO;CACR;AACD"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runSubscriber-DyHWp_Lf.mjs","names":[],"sources":["../src/subscribers/runSubscriber.ts"],"sourcesContent":["/**\n * What a subscriber does with a batch of records, however they arrived: parse\n * them into events, keep the ones it subscribed to, and run its handler with\n * its services and database.\n *\n * Shared by the Lambda adaptor, which wraps it in middy, and the SNS push\n * adaptor, which a server runs and which must not need middy to load.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { INBOX_EVENT } from '@geekmidas/manifest';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { SNSEvent, SNSEventRecord, SQSEvent, SQSRecord } from 'aws-lambda';\nimport type { Subscriber } from './Subscriber';\n\ntype AnySubscriber = Subscriber<any, any, any, any, any, any, any>;\n\n/** The subscriber's output did not match its `.output()` schema. */\nexport class SubscriberOutputInvalid extends Error {\n\tconstructor(readonly issues: ReadonlyArray<unknown>) {\n\t\tsuper(\n\t\t\t\"Subscriber output validation failed: the handler's result does not match its .output() schema.\",\n\t\t);\n\t\tthis.name = 'SubscriberOutputInvalid';\n\t}\n}\n\n/** The events in an SQS or SNS batch (a Lambda event's `Records`) that `subscriber` subscribed to. */\nexport async function subscribedEvents(\n\tsubscriber: AnySubscriber,\n\trawEvent: { Records?: readonly unknown[] },\n\tlogger: Logger,\n): Promise<any[]> {\n\tconst events: any[] = [];\n\tconst records = rawEvent.Records ?? [];\n\tconst first = records[0] as any;\n\tconst parse =\n\t\tfirst?.eventSource === 'aws:sqs'\n\t\t\t? (record: any) => parseSQSRecord(record)\n\t\t\t: first?.EventSource === 'aws:sns'\n\t\t\t\t? (record: any) => parseSNSRecord(record)\n\t\t\t\t: undefined;\n\tif (!parse) return events;\n\n\t// A bucket's subscriber is sent what the storage sends — a notification\n\t// of records — and reads it as object events. Loaded only then: an app\n\t// with no bucket never installs the storage package.\n\tconst toObjectEvents = subscriber.bucketName\n\t\t? (await import('@geekmidas/storage/events')).toObjectEvents\n\t\t: undefined;\n\n\tfor (const record of records) {\n\t\ttry {\n\t\t\tconst event = parse(record);\n\t\t\tconst untyped = !(typeof event === 'object' && event?.type);\n\t\t\t// An inbox's subscriber is sent SES's receipt notification as SES\n\t\t\t// wrote it, with no type of ours on it.\n\t\t\tconst parsed =\n\t\t\t\tsubscriber.inboxName && untyped\n\t\t\t\t\t? [{ type: INBOX_EVENT, payload: event }]\n\t\t\t\t\t: toObjectEvents && untyped\n\t\t\t\t\t\t? toObjectEvents(event)\n\t\t\t\t\t\t: [event];\n\t\t\tfor (const one of parsed) {\n\t\t\t\tif (isSubscribed(subscriber, one)) events.push(one);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tlogger.error({ err: error, record }, 'Failed to parse record');\n\t\t}\n\t}\n\treturn events;\n}\n\n/** The subscriber's services and database, registered as functions do. */\nexport async function subscriberContext(\n\tsubscriber: AnySubscriber,\n\tenvParser: EnvironmentParser<{}>,\n): Promise<{ services: Record<string, unknown>; db: unknown }> {\n\tconst discovery = ServiceDiscovery.getInstance(envParser);\n\tconst services =\n\t\tsubscriber.services.length > 0\n\t\t\t? await discovery.register(subscriber.services)\n\t\t\t: {};\n\tconst service = subscriber.databaseService;\n\tconst db = service\n\t\t? (await discovery.register([service]))[service.serviceName]\n\t\t: undefined;\n\treturn { services, db };\n}\n\n/** Runs the handler on `events`, and checks its output against its schema. */\nexport async function runSubscriber(\n\tsubscriber: AnySubscriber,\n\tcontext: {\n\t\tevents: any[];\n\t\tservices: Record<string, unknown>;\n\t\tdb: unknown;\n\t\tlogger: Logger;\n\t},\n): Promise<unknown> {\n\tif (context.events.length === 0) {\n\t\tcontext.logger.info('No subscribed events to process');\n\t\treturn { batchItemFailures: [] };\n\t}\n\n\tconst { events, services, db, logger } = context;\n\tconst result = await subscriber.handler({\n\t\tevents,\n\t\tservices,\n\t\tlogger,\n\t\tdb,\n\t} as any);\n\n\tif (subscriber.outputSchema && result) {\n\t\tconst validation =\n\t\t\tawait subscriber.outputSchema['~standard'].validate(result);\n\t\tif (validation.issues) {\n\t\t\tcontext.logger.error(\n\t\t\t\t{ issues: validation.issues },\n\t\t\t\t'Subscriber output validation failed',\n\t\t\t);\n\t\t\tthrow new SubscriberOutputInvalid(validation.issues);\n\t\t}\n\t\treturn validation.value;\n\t}\n\n\treturn result;\n}\n\nfunction isSubscribed(subscriber: AnySubscriber, event: any): boolean {\n\t// No event type (raw string/non-object) — always include\n\tif (typeof event !== 'object' || !event?.type) return true;\n\t// No filter configured — accept all\n\tif (!subscriber.subscribedEvents) return true;\n\treturn subscriber.subscribedEvents.includes(event.type);\n}\n\nfunction parseSNSRecord(record: SNSEventRecord): any {\n\tconst message = safeJsonParse(record.Sns.Message);\n\tconst messageType = record.Sns.MessageAttributes?.type?.Value;\n\n\t// Not JSON — wrap raw string with type from MessageAttributes if available\n\tif (message === null) {\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: record.Sns.Message }\n\t\t\t: record.Sns.Message;\n\t}\n\n\tif (message.type) {\n\t\treturn message; // Full event format: { type, payload }\n\t}\n\n\t// Payload-only format: type is in MessageAttributes\n\treturn messageType ? { type: messageType, payload: message } : message;\n}\n\nfunction parseSQSRecord(record: SQSRecord): any {\n\tconst body = safeJsonParse(record.body);\n\n\t// Not JSON — return raw body as-is\n\tif (body === null) {\n\t\treturn record.body;\n\t}\n\n\t// Check if this is an SNS message wrapped in SQS\n\tif (body.Type === 'Notification' && body.Message) {\n\t\tconst snsMessage = safeJsonParse(body.Message);\n\t\tconst messageType = body.MessageAttributes?.type?.Value;\n\n\t\t// SNS Message not JSON — wrap with type from MessageAttributes if available\n\t\tif (snsMessage === null) {\n\t\t\treturn messageType\n\t\t\t\t? { type: messageType, payload: body.Message }\n\t\t\t\t: body.Message;\n\t\t}\n\n\t\tif (snsMessage.type) {\n\t\t\treturn snsMessage; // Full event format: { type, payload }\n\t\t}\n\n\t\t// Payload-only format: type is in MessageAttributes\n\t\treturn messageType\n\t\t\t? { type: messageType, payload: snsMessage }\n\t\t\t: snsMessage;\n\t}\n\n\t// Direct SQS message\n\treturn body;\n}\n\nfunction safeJsonParse(value: string): any | null {\n\ttry {\n\t\treturn JSON.parse(value);\n\t} catch {\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;AAmBA,IAAa,0BAAb,cAA6C,MAAM;CAC7B;CAArB,YAAY,QAAyC;EACpD,MACC,gGACD;EAHoB,KAAA,SAAA;EAIpB,KAAK,OAAO;CACb;AACD;;AAGA,eAAsB,iBACrB,YACA,UACA,QACiB;CACjB,MAAM,SAAgB,CAAC;CACvB,MAAM,UAAU,SAAS,WAAW,CAAC;CACrC,MAAM,QAAQ,QAAQ;CACtB,MAAM,QACL,OAAO,gBAAgB,aACnB,WAAgB,eAAe,MAAM,IAC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","HttpError","runWithRequestContext","ServiceDiscovery","servicesOf","idsOf","randomBytes","trustsOrigin","canonicalId","provideKey","DEFAULT_LOGGER","envParserFor","serviceKey","edgeTo"],"sources":["../src/websocket/frame.ts","../src/websocket/publisher.ts","../src/websocket/core.ts","../src/websocket/testing.ts","../src/websocket/route.ts","../src/websocket/transport.ts","../src/websocket/server.ts","../src/websocket-api.ts"],"sourcesContent":["/**\n * The shape a surface's frames take on the wire.\n *\n * By default a frame is `{ \"action\": …, \"id\"?: …, \"data\": … }` — API\n * Gateway's shape. A surface that names a discriminator — `frame: {\n * discriminator: 'type' }` — sends and reads flat frames instead: the action\n * under that key, and the data's own fields beside it.\n *\n * ```json\n * {\"type\":\"chat.message.created\",\"chatId\":\"c1\",\"message\":{…}}\n * ```\n *\n * A flat frame has no `id` of its own: every field but the discriminator is\n * the data, so a reply is paired by its action, not an echoed id.\n */\n\nimport { toJsonSchema } from '@geekmidas/schema/conversion';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { WebSocketMessages } from './publisher';\n\n/** `WebSocketApiConfig.frame`: where a flat frame keeps its action. */\nexport interface WebSocketFrame {\n\t/** The key a frame's action lives in — `type` for `{ \"type\": … }`. */\n\tdiscriminator: string;\n}\n\n/** A frame as the server reads it, whatever shape it arrived in. */\nexport interface DecodedFrame {\n\taction: string;\n\t/** Echoed on the reply. Only an `{ action, data }` frame carries one. */\n\tid?: string | number;\n\tdata?: unknown;\n}\n\n/** A declared message whose schema does not describe an object. */\nexport class WebSocketMessageNotAnObject extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\treadonly discriminator: string,\n\t) {\n\t\tsuper(\n\t\t\t`${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 }.`,\n\t\t);\n\t\tthis.name = 'WebSocketMessageNotAnObject';\n\t}\n}\n\n/** A declared message whose schema has a field named the discriminator. */\nexport class WebSocketMessageDeclaresDiscriminator extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\treadonly discriminator: string,\n\t) {\n\t\tsuper(\n\t\t\t`${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.`,\n\t\t);\n\t\tthis.name = 'WebSocketMessageDeclaresDiscriminator';\n\t}\n}\n\n/** Data sent in a flat frame that is not an object. */\nexport class WebSocketDataNotAnObject extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\treadonly discriminator: string,\n\t) {\n\t\tsuper(\n\t\t\t`${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.`,\n\t\t);\n\t\tthis.name = 'WebSocketDataNotAnObject';\n\t}\n}\n\n/** Data sent in a flat frame that carries the discriminator itself. */\nexport class WebSocketDataHasDiscriminator extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\treadonly discriminator: string,\n\t) {\n\t\tsuper(\n\t\t\t`'${action}''s data on ${surface} has a '${discriminator}' field, which is where its flat frames keep the action. Rename the field. Nothing was sent.`,\n\t\t);\n\t\tthis.name = 'WebSocketDataHasDiscriminator';\n\t}\n}\n\n/** How one surface writes and reads its frames. */\nexport class FrameShape {\n\tconstructor(\n\t\treadonly surface: string,\n\t\t/** The flat frame's key; absent, frames are `{ action, data }`. */\n\t\treadonly discriminator?: string,\n\t) {}\n\n\t/** The key an inbound frame names its action under. */\n\tget key(): string {\n\t\treturn this.discriminator ?? 'action';\n\t}\n\n\t/**\n\t * The frame for `action`'s `data`, serialised.\n\t *\n\t * @throws {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator} for\n\t * a flat frame whose data cannot sit beside the discriminator.\n\t */\n\tencode(action: string, data: unknown, id?: string | number): string {\n\t\tconst { discriminator } = this;\n\t\tif (discriminator === undefined) {\n\t\t\treturn JSON.stringify({\n\t\t\t\taction,\n\t\t\t\t...(id !== undefined ? { id } : {}),\n\t\t\t\tdata,\n\t\t\t});\n\t\t}\n\t\tif (!isRecord(data)) {\n\t\t\tthrow new WebSocketDataNotAnObject(this.surface, action, discriminator);\n\t\t}\n\t\tif (Object.hasOwn(data, discriminator)) {\n\t\t\tthrow new WebSocketDataHasDiscriminator(\n\t\t\t\tthis.surface,\n\t\t\t\taction,\n\t\t\t\tdiscriminator,\n\t\t\t);\n\t\t}\n\t\treturn JSON.stringify({ [discriminator]: action, ...data });\n\t}\n\n\t/** A parsed frame's action, id and data — `undefined` when it names none. */\n\tdecode(frame: unknown): DecodedFrame | undefined {\n\t\tif (!isRecord(frame)) return undefined;\n\t\tconst { discriminator } = this;\n\t\tif (discriminator === undefined) {\n\t\t\tif (typeof frame.action !== 'string') return undefined;\n\t\t\treturn {\n\t\t\t\taction: frame.action,\n\t\t\t\t...(isId(frame.id) ? { id: frame.id } : {}),\n\t\t\t\tdata: frame.data,\n\t\t\t};\n\t\t}\n\t\tconst { [discriminator]: action, ...data } = frame;\n\t\tif (typeof action !== 'string') return undefined;\n\t\treturn { action, data };\n\t}\n\n\t/** The id a frame that names no action carried, to echo on its error. */\n\tidOf(frame: unknown): string | number | undefined {\n\t\tif (this.discriminator !== undefined || !isRecord(frame)) return undefined;\n\t\treturn isId(frame.id) ? frame.id : undefined;\n\t}\n\n\t/**\n\t * Refuse a declared message a flat frame cannot carry: one that is not an\n\t * object, or that has a field named the discriminator.\n\t *\n\t * @throws {WebSocketMessageNotAnObject}, {WebSocketMessageDeclaresDiscriminator}\n\t */\n\tcheck(messages: WebSocketMessages): void {\n\t\tconst { discriminator } = this;\n\t\tif (discriminator === undefined) return;\n\t\tfor (const [action, schema] of Object.entries(messages)) {\n\t\t\tconst shape = objectShape(toJsonSchema(schema as StandardSchemaV1));\n\t\t\tif (!shape) {\n\t\t\t\tthrow new WebSocketMessageNotAnObject(\n\t\t\t\t\tthis.surface,\n\t\t\t\t\taction,\n\t\t\t\t\tdiscriminator,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (shape.has(discriminator)) {\n\t\t\t\tthrow new WebSocketMessageDeclaresDiscriminator(\n\t\t\t\t\tthis.surface,\n\t\t\t\t\taction,\n\t\t\t\t\tdiscriminator,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * The fields a JSON Schema's object declares, or `undefined` when it is not\n * an object. A union or intersection is one when each of its members is.\n */\nfunction objectShape(schema: unknown): Set<string> | undefined {\n\tif (!isRecord(schema)) return undefined;\n\n\tconst members = (schema.anyOf ?? schema.oneOf ?? schema.allOf) as\n\t\t| unknown[]\n\t\t| undefined;\n\tif (Array.isArray(members) && members.length > 0) {\n\t\tconst fields = new Set<string>();\n\t\tfor (const member of members) {\n\t\t\tconst shape = objectShape(member);\n\t\t\tif (!shape) return undefined;\n\t\t\tfor (const field of shape) fields.add(field);\n\t\t}\n\t\treturn fields;\n\t}\n\n\tif (schema.type !== 'object') return undefined;\n\treturn new Set(\n\t\tisRecord(schema.properties) ? Object.keys(schema.properties) : [],\n\t);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isId(value: unknown): value is string | number {\n\treturn typeof value === 'string' || typeof value === 'number';\n}\n","import type { StandardSchemaV1 } from '@standard-schema/spec';\nimport { FrameShape } from './frame';\n\n/**\n * Where a publisher's frames go once they are encoded — the one thing a\n * runtime supplies to send to its sockets.\n *\n * On Node it is a `TransportSink`: each id's process, over Redis or memory.\n * On API Gateway it would be the management API's `postToConnection`; under\n * test, a recording. A payload is the frame already serialised, once, however\n * many ids it goes to. An id that is gone is dropped, not an error.\n */\nexport interface WebSocketSink {\n\tsend(ids: readonly string[], payload: string): Promise<void>;\n\t/** Every open connection but `except`. */\n\tbroadcast(payload: string, except?: readonly string[]): Promise<void>;\n\tclose(ids: readonly string[], code: number, reason: string): Promise<void>;\n}\n\n/**\n * What a surface sends its sockets, by action — `WebSocketApiConfig.messages`.\n */\nexport type WebSocketMessages = Record<string, StandardSchemaV1>;\n\n/** A surface that declares no messages: any action, any data. */\nexport type NoMessages = Record<never, never>;\n\n/** The actions a publisher sends: the declared ones, or any. */\nexport type MessageAction<TMessages extends WebSocketMessages> = [\n\tkeyof TMessages,\n] extends [never]\n\t? string\n\t: keyof TMessages & string;\n\n/** What `action`'s data is, as its schema takes it. */\nexport type MessageData<\n\tTMessages extends WebSocketMessages,\n\tTAction extends string,\n> = TAction extends keyof TMessages\n\t? StandardSchemaV1.InferInput<TMessages[TAction]>\n\t: unknown;\n\n/** A message sent on an action the surface does not declare. */\nexport class UnknownWebSocketMessage extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\treadonly declared: readonly string[],\n\t) {\n\t\tsuper(\n\t\t\t`${surface} sends no '${action}' message. It declares ${declared\n\t\t\t\t.map((a) => `'${a}'`)\n\t\t\t\t.join(', ')} — send one of them, or add '${action}' to its messages.`,\n\t\t);\n\t\tthis.name = 'UnknownWebSocketMessage';\n\t}\n}\n\n/** A message whose data its action's schema refused. */\nexport class InvalidWebSocketMessage extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\treadonly issues: readonly StandardSchemaV1.Issue[],\n\t) {\n\t\tsuper(\n\t\t\t`${surface}'s '${action}' message was refused by its schema: ${issues\n\t\t\t\t.map((issue) => issue.message)\n\t\t\t\t.join('; ')}. Nothing was sent.`,\n\t\t);\n\t\tthis.name = 'InvalidWebSocketMessage';\n\t}\n}\n\n/**\n * How anything reaches a socket — `services.realtime` in an endpoint, and\n * `sockets` in a route of the surface itself.\n *\n * A message is `{ action, data }`, the shape a client's frames arrive in —\n * or, where the surface names a `frame.discriminator`, flat: `{ [key]: action,\n * ...data }`.\n * Where the surface declares its messages, `action` is one of them and\n * `data` is typed and checked by its schema before anything is sent; where it\n * declares none, any action and any JSON value go. A message is serialised\n * once, whatever the number of sockets it goes to. An id whose process has\n * gone is dropped silently, as API Gateway's `postToConnection` to a closed\n * connection is a no-op the sender rarely wants to handle.\n */\nexport class WebSocketPublisher<\n\tTMessages extends WebSocketMessages = NoMessages,\n> {\n\tconstructor(\n\t\t/** Where an encoded frame goes. */\n\t\tprivate readonly sink: WebSocketSink,\n\t\t/** The surface's declared messages, which every send is checked by. */\n\t\tprivate readonly declared?: { surface: string; messages: TMessages },\n\t\t/** How the surface writes a frame. Absent, `{ action, data }`. */\n\t\tprivate readonly frame: FrameShape = new FrameShape(\n\t\t\tdeclared?.surface ?? '',\n\t\t),\n\t) {}\n\n\t/** Send `action`'s message to each connection. */\n\tasync send<TAction extends MessageAction<TMessages>>(\n\t\tids: string | readonly string[],\n\t\taction: TAction,\n\t\tdata: MessageData<TMessages, TAction>,\n\t): Promise<void> {\n\t\tconst payload = await this.payload(action, data);\n\t\tawait this.sink.send(listOf(ids), payload);\n\t}\n\n\t/** Send `action`'s message to every open connection, on every process. */\n\tasync broadcast<TAction extends MessageAction<TMessages>>(\n\t\taction: TAction,\n\t\tdata: MessageData<TMessages, TAction>,\n\t\toptions: { except?: readonly string[] } = {},\n\t): Promise<void> {\n\t\tconst payload = await this.payload(action, data);\n\t\tawait this.sink.broadcast(\n\t\t\tpayload,\n\t\t\toptions.except?.length ? options.except : undefined,\n\t\t);\n\t}\n\n\t/** Close each connection, with a close code and reason its client sees. */\n\tasync close(\n\t\tids: string | readonly string[],\n\t\tcode = 1000,\n\t\treason = '',\n\t): Promise<void> {\n\t\tawait this.sink.close(listOf(ids), code, reason);\n\t}\n\n\t/**\n\t * The frame, checked by the action's schema where the surface declares\n\t * its messages.\n\t *\n\t * @throws {UnknownWebSocketMessage}, {InvalidWebSocketMessage}, and for a\n\t * flat frame {WebSocketDataNotAnObject}, {WebSocketDataHasDiscriminator}\n\t */\n\tprivate async payload(action: string, data: unknown): Promise<string> {\n\t\tif (!this.declared) return this.frame.encode(action, data);\n\n\t\tconst { surface, messages } = this.declared;\n\t\tconst schema = messages[action];\n\t\tif (!schema) {\n\t\t\tthrow new UnknownWebSocketMessage(surface, action, Object.keys(messages));\n\t\t}\n\t\tconst result = await schema['~standard'].validate(data);\n\t\tif (result.issues) {\n\t\t\tthrow new InvalidWebSocketMessage(surface, action, result.issues);\n\t\t}\n\t\treturn this.frame.encode(action, result.value);\n\t}\n}\n\nfunction listOf(ids: string | readonly string[]): readonly string[] {\n\treturn typeof ids === 'string' ? [ids] : ids;\n}\n","/**\n * A WebSocket surface with no socket in it.\n *\n * Everything a surface does that is not the transport: which route answers\n * an action, a frame decoded and checked against its route's `body`, the\n * connect handler's verdict and the `data` it keeps, the disconnect handler,\n * each handler's services and `sockets`. A runtime — an adaptor — owns the\n * socket, or the absence of one, and calls in with a connection id:\n *\n * - Node (`WebSocketSurfaceServer`) upgrades on its HTTP server, holds the\n * sockets, pings them and writes what the core hands back;\n * - API Gateway accepts the socket itself, and a Lambda calls `connect()`,\n * `message()` and `disconnect()` per event;\n * - a test calls them directly.\n *\n * What reaches a socket from a handler goes through `sockets`, a publisher\n * over the adaptor's `WebSocketSink`.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport { HttpError } from '@geekmidas/errors';\nimport type { Logger } from '@geekmidas/logger';\nimport { runWithRequestContext, ServiceDiscovery } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { Authenticator } from '../construct-interface';\nimport { FrameShape, type WebSocketFrame } from './frame';\nimport {\n\ttype NoMessages,\n\ttype WebSocketMessages,\n\tWebSocketPublisher,\n\ttype WebSocketSink,\n} from './publisher';\nimport type { Connection, WebSocketRoute } from './route';\n\n/** Two routes answer one action. */\nexport class DuplicateWebSocketRoute extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t) {\n\t\tsuper(\n\t\t\t`Two routes on ${surface} answer '${action}'. Each action has one handler — rename one of them.`,\n\t\t);\n\t\tthis.name = 'DuplicateWebSocketRoute';\n\t}\n}\n\nexport interface WebSocketCoreOptions<\n\tTMessages extends WebSocketMessages = NoMessages,\n> {\n\tsurface: string;\n\t/** Every route handed in; those built from another surface are skipped. */\n\troutes: readonly WebSocketRoute[];\n\t/** What the surface sends its sockets — see `WebSocketApiConfig.messages`. */\n\tmessages?: TMessages;\n\t/** The shape its frames take — see `WebSocketApiConfig.frame`. */\n\tframe?: WebSocketFrame;\n\t/** Where `sockets` sends, in every handler: the adaptor's own. */\n\tsink: WebSocketSink;\n\tenvParser: EnvironmentParser<{}>;\n\tlogger: Logger;\n\t/** What turns a handshake's headers into the `session` connect sees. */\n\tauthenticator?: Authenticator;\n}\n\n/** A handshake, as the adaptor that received it saw it. */\nexport interface ConnectRequest {\n\t/** The id the adaptor gives the connection — sends address it by this. */\n\tconnectionId: string;\n\theaders: Headers;\n\tquery: URLSearchParams;\n\t/**\n\t * Whose connection it is, when the adaptor already knows (a test).\n\t * Absent, the surface's authenticator verifies `headers`; `null` is no\n\t * session.\n\t */\n\tsession?: unknown;\n}\n\n/**\n * For one call: services to use in place of registering them — a test's\n * transaction for `database`. Only those the route depends on are handed in.\n */\nexport interface WebSocketCallOptions {\n\tservices?: Record<string, unknown>;\n}\n\n/** Whether a handshake may become a connection. */\nexport type ConnectOutcome =\n\t| { accepted: true; connection: Connection }\n\t| {\n\t\t\taccepted: false;\n\t\t\t/** The status a refused upgrade answers with: the `HttpError`'s, or 500. */\n\t\t\tstatus: number;\n\t\t\tstatusText: string;\n\t\t\t/** What the connect handler, or the authenticator, threw. */\n\t\t\terror: unknown;\n\t };\n\n/** Writes one serialised frame to the connection a message arrived on. */\nexport type WriteFrame = (payload: string) => void;\n\n/** What became of one inbound frame. Whatever it wrote went through `write`. */\nexport type MessageOutcome =\n\t| {\n\t\t\tok: true;\n\t\t\taction: string;\n\t\t\tid?: string | number;\n\t\t\t/** The handler's return — sent back as the reply when defined. */\n\t\t\treturned: unknown;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\t/** Absent when the frame named no action. */\n\t\t\taction?: string;\n\t\t\tid?: string | number;\n\t\t\t/** What the `$error` frame said. */\n\t\t\tmessage: string;\n\t\t\tissues?: readonly StandardSchemaV1.Issue[];\n\t\t\t/** What the handler threw, when it got that far. */\n\t\t\terror?: unknown;\n\t };\n\nexport type DisconnectOutcome = { ok: true } | { ok: false; error: unknown };\n\nexport class WebSocketCore<TMessages extends WebSocketMessages = NoMessages> {\n\treadonly surface: string;\n\t/** How frames are read and written — what an adaptor decodes replies by. */\n\treadonly frame: FrameShape;\n\t/** `sockets` in every handler. */\n\treadonly sockets: WebSocketPublisher<TMessages>;\n\n\tprivate readonly routes = new Map<string, WebSocketRoute>();\n\tprivate readonly lifecycle: {\n\t\tconnect?: WebSocketRoute;\n\t\tdisconnect?: WebSocketRoute;\n\t} = {};\n\n\t/**\n\t * @throws {DuplicateWebSocketRoute} when two routes answer one action, and\n\t * the frame checks of `FrameShape.check` for declared messages.\n\t */\n\tconstructor(private readonly options: WebSocketCoreOptions<TMessages>) {\n\t\tthis.surface = options.surface;\n\t\tfor (const route of options.routes) {\n\t\t\tif (route.surface.id !== options.surface) continue;\n\t\t\tif (route.kind === 'message') {\n\t\t\t\tif (this.routes.has(route.action)) {\n\t\t\t\t\tthrow new DuplicateWebSocketRoute(options.surface, route.action);\n\t\t\t\t}\n\t\t\t\tthis.routes.set(route.action, route);\n\t\t\t} else {\n\t\t\t\tif (this.lifecycle[route.kind]) {\n\t\t\t\t\tthrow new DuplicateWebSocketRoute(options.surface, route.action);\n\t\t\t\t}\n\t\t\t\tthis.lifecycle[route.kind] = route;\n\t\t\t}\n\t\t}\n\n\t\tthis.frame = new FrameShape(options.surface, options.frame?.discriminator);\n\t\tif (options.messages) this.frame.check(options.messages);\n\t\tthis.sockets = new WebSocketPublisher<TMessages>(\n\t\t\toptions.sink,\n\t\t\toptions.messages\n\t\t\t\t? { surface: options.surface, messages: options.messages }\n\t\t\t\t: undefined,\n\t\t\tthis.frame,\n\t\t);\n\t}\n\n\t/**\n\t * Run the connect handler for a handshake: accepted with the connection's\n\t * `data` (what the handler returned, `{}` for nothing), or refused with\n\t * the status of the `HttpError` it threw — 500 for anything else. A surface\n\t * with no connect handler accepts every handshake, and verifies no session.\n\t */\n\tasync connect(\n\t\trequest: ConnectRequest,\n\t\toptions: WebSocketCallOptions = {},\n\t): Promise<ConnectOutcome> {\n\t\tconst { connectionId, headers, query } = request;\n\t\tconst route = this.lifecycle.connect;\n\t\tif (!route)\n\t\t\treturn { accepted: true, connection: { id: connectionId, data: {} } };\n\n\t\ttry {\n\t\t\tconst session =\n\t\t\t\t'session' in request\n\t\t\t\t\t? request.session\n\t\t\t\t\t: this.options.authenticator\n\t\t\t\t\t\t? await this.options.authenticator.verify(\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tthis.options.envParser,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: null;\n\t\t\tconst returned = await this.run(\n\t\t\t\troute,\n\t\t\t\tconnectionId,\n\t\t\t\t(base) => ({ ...base, connectionId, headers, query, session }),\n\t\t\t\toptions,\n\t\t\t);\n\t\t\tconst data =\n\t\t\t\treturned && typeof returned === 'object'\n\t\t\t\t\t? (returned as Record<string, unknown>)\n\t\t\t\t\t: {};\n\t\t\treturn { accepted: true, connection: { id: connectionId, data } };\n\t\t} catch (error) {\n\t\t\tif (error instanceof HttpError) {\n\t\t\t\treturn {\n\t\t\t\t\taccepted: false,\n\t\t\t\t\tstatus: error.statusCode,\n\t\t\t\t\tstatusText: error.statusMessage,\n\t\t\t\t\terror,\n\t\t\t\t};\n\t\t\t}\n\t\t\tthis.options.logger.error(\n\t\t\t\t{ err: error, connectionId },\n\t\t\t\t'WebSocket connect handler failed',\n\t\t\t);\n\t\t\treturn {\n\t\t\t\taccepted: false,\n\t\t\t\tstatus: 500,\n\t\t\t\tstatusText: 'Internal Server Error',\n\t\t\t\terror,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Parse, validate and run one inbound frame. The reply — the handler's\n\t * return, encoded — and every `$error` are written with `write`; an error\n\t * is a frame, never a close. A binary frame is refused: frames are text.\n\t */\n\tasync message(\n\t\tconnection: Connection,\n\t\traw: string | Uint8Array,\n\t\twrite: WriteFrame,\n\t\toptions: WebSocketCallOptions = {},\n\t): Promise<MessageOutcome> {\n\t\tif (typeof raw !== 'string') {\n\t\t\treturn this.error(write, {}, 'Frames are JSON text.');\n\t\t}\n\n\t\tlet parsed: unknown;\n\t\ttry {\n\t\t\tparsed = JSON.parse(raw);\n\t\t} catch {\n\t\t\treturn this.error(write, {}, 'Frames are JSON.');\n\t\t}\n\t\tconst frame = this.frame.decode(parsed);\n\t\tif (!frame) {\n\t\t\treturn this.error(\n\t\t\t\twrite,\n\t\t\t\t{ id: this.frame.idOf(parsed) },\n\t\t\t\t`A frame names its \\`${this.frame.key}\\`.`,\n\t\t\t);\n\t\t}\n\n\t\tconst { action, id } = frame;\n\t\tconst route = this.routes.get(action) ?? this.routes.get('$default');\n\t\tif (!route) {\n\t\t\treturn this.error(write, { action, id }, `No route answers '${action}'.`);\n\t\t}\n\n\t\tlet body = frame.data;\n\t\tif (route.schema) {\n\t\t\tconst result = await route.schema['~standard'].validate(frame.data);\n\t\t\tif (result.issues) {\n\t\t\t\treturn this.error(\n\t\t\t\t\twrite,\n\t\t\t\t\t{ action, id },\n\t\t\t\t\t'The frame was invalid.',\n\t\t\t\t\tresult.issues,\n\t\t\t\t);\n\t\t\t}\n\t\t\tbody = result.value;\n\t\t}\n\n\t\ttry {\n\t\t\tconst returned = await this.run(\n\t\t\t\troute,\n\t\t\t\tconnection.id,\n\t\t\t\t(base) => ({\n\t\t\t\t\t...base,\n\t\t\t\t\tconnection,\n\t\t\t\t\tbody,\n\t\t\t\t\treply: (message: unknown) => write(JSON.stringify(message)),\n\t\t\t\t}),\n\t\t\t\toptions,\n\t\t\t);\n\t\t\tif (returned !== undefined) {\n\t\t\t\twrite(this.frame.encode(action, returned, id));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\taction,\n\t\t\t\t...(id !== undefined ? { id } : {}),\n\t\t\t\treturned,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (error instanceof HttpError) {\n\t\t\t\treturn this.error(\n\t\t\t\t\twrite,\n\t\t\t\t\t{ action, id },\n\t\t\t\t\terror.message,\n\t\t\t\t\tundefined,\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis.options.logger.error(\n\t\t\t\t{ err: error, connectionId: connection.id, action },\n\t\t\t\t'WebSocket route failed',\n\t\t\t);\n\t\t\treturn this.error(\n\t\t\t\twrite,\n\t\t\t\t{ action, id },\n\t\t\t\t'The route failed.',\n\t\t\t\tundefined,\n\t\t\t\terror,\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Run the disconnect handler for a connection that has closed. What it\n\t * throws is logged and returned, never thrown: the socket is gone either\n\t * way.\n\t */\n\tasync disconnect(\n\t\tconnection: Connection,\n\t\tclose: { code: number; reason: string },\n\t\toptions: WebSocketCallOptions = {},\n\t): Promise<DisconnectOutcome> {\n\t\tconst route = this.lifecycle.disconnect;\n\t\tif (!route) return { ok: true };\n\t\ttry {\n\t\t\tawait this.run(\n\t\t\t\troute,\n\t\t\t\tconnection.id,\n\t\t\t\t(base) => ({ ...base, connection, ...close }),\n\t\t\t\toptions,\n\t\t\t);\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\tthis.options.logger.error(\n\t\t\t\t{ err: error, connectionId: connection.id },\n\t\t\t\t'WebSocket disconnect handler failed',\n\t\t\t);\n\t\t\treturn { ok: false, error };\n\t\t}\n\t}\n\n\t/** Run a handler with its services, inside a request context of its own. */\n\tprivate async run(\n\t\troute: WebSocketRoute,\n\t\tconnectionId: string,\n\t\tcontext: (base: {\n\t\t\tservices: unknown;\n\t\t\tlogger: Logger;\n\t\t\tsockets: WebSocketPublisher<TMessages>;\n\t\t}) => object,\n\t\toptions: WebSocketCallOptions,\n\t): Promise<unknown> {\n\t\tconst logger = this.options.logger.child({\n\t\t\tconnectionId,\n\t\t\taction: route.action,\n\t\t});\n\t\treturn runWithRequestContext(\n\t\t\t{\n\t\t\t\tlogger,\n\t\t\t\trequestId: connectionId,\n\t\t\t\tstartTime: Date.now(),\n\t\t\t\toperation: `ws ${route.action}`,\n\t\t\t},\n\t\t\tasync () => {\n\t\t\t\tconst services = await this.services(route, options.services);\n\t\t\t\treturn (route.handler as (context: object) => unknown)(\n\t\t\t\t\tcontext({ services, logger, sockets: this.sockets }),\n\t\t\t\t);\n\t\t\t},\n\t\t);\n\t}\n\n\t/** The route's services: the overrides it names, the rest registered. */\n\tprivate async services(\n\t\troute: WebSocketRoute,\n\t\toverrides: Record<string, unknown> = {},\n\t): Promise<Record<string, unknown>> {\n\t\tconst given: Record<string, unknown> = {};\n\t\tconst wanted = route.services.filter((service) => {\n\t\t\tif (!Object.hasOwn(overrides, service.serviceName)) return true;\n\t\t\tgiven[service.serviceName] = overrides[service.serviceName];\n\t\t\treturn false;\n\t\t});\n\t\tconst registered = wanted.length\n\t\t\t? await ServiceDiscovery.getInstance(this.options.envParser).register([\n\t\t\t\t\t...wanted,\n\t\t\t\t])\n\t\t\t: {};\n\t\treturn { ...registered, ...given };\n\t}\n\n\tprivate error(\n\t\twrite: WriteFrame,\n\t\tat: { action?: string; id?: string | number },\n\t\tmessage: string,\n\t\tissues?: readonly StandardSchemaV1.Issue[],\n\t\terror?: unknown,\n\t): MessageOutcome {\n\t\twrite(\n\t\t\tthis.frame.encode(\n\t\t\t\t'$error',\n\t\t\t\t{ message, ...(issues ? { issues } : {}) },\n\t\t\t\tat.id,\n\t\t\t),\n\t\t);\n\t\treturn {\n\t\t\tok: false,\n\t\t\t...(at.action !== undefined ? { action: at.action } : {}),\n\t\t\t...(at.id !== undefined ? { id: at.id } : {}),\n\t\t\tmessage,\n\t\t\t...(issues ? { issues } : {}),\n\t\t\t...(error !== undefined ? { error } : {}),\n\t\t};\n\t}\n}\n","/**\n * The Test adaptor: a surface's routes called directly, with no server and\n * no socket — what `route.request()` and `surface.testPublisher()` are built\n * on.\n *\n * A route's `request()` builds a core over just that route and calls\n * `connect()`, `message()` or `disconnect()` on it, as the Node adaptor does\n * for a socket. What its handler sends through `sockets` goes to a recording\n * publisher, the same one `surface.testPublisher()` hands an endpoint's spec.\n */\n\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport type { WebSocketCore } from './core';\nimport type { FrameShape } from './frame';\nimport {\n\ttype NoMessages,\n\ttype WebSocketMessages,\n\tWebSocketPublisher,\n\ttype WebSocketSink,\n} from './publisher';\nimport type { Connection, WebSocketRoute } from './route';\n\n/** One recorded message: its action and data, and the frame on the wire. */\nexport type RecordedMessage<TMessages extends WebSocketMessages = NoMessages> =\n\t[keyof TMessages] extends [never]\n\t\t? { action: string; data: unknown; frame: Record<string, unknown> }\n\t\t: {\n\t\t\t\t[A in keyof TMessages & string]: {\n\t\t\t\t\taction: A;\n\t\t\t\t\t/** As its schema returned it — what the client receives. */\n\t\t\t\t\tdata: StandardSchemaV1.InferOutput<TMessages[A]>;\n\t\t\t\t\t/** The frame as the client parses it — the wire shape. */\n\t\t\t\t\tframe: Record<string, unknown>;\n\t\t\t\t};\n\t\t\t}[keyof TMessages & string];\n\n/** A `send(ids, …)`, as it was recorded. */\nexport type RecordedSend<TMessages extends WebSocketMessages = NoMessages> =\n\tRecordedMessage<TMessages> & { ids: string[] };\n\n/** A `broadcast(…)`, as it was recorded. */\nexport type RecordedBroadcast<\n\tTMessages extends WebSocketMessages = NoMessages,\n> = RecordedMessage<TMessages> & { except: string[] };\n\n/** A `close(ids, code, reason)`, as it was recorded. */\nexport interface RecordedClose {\n\tids: string[];\n\tcode: number;\n\treason: string;\n}\n\n/**\n * A sink that keeps what it is handed, decoded by the surface's frame shape,\n * and sends it nowhere.\n */\nexport class RecordingSink implements WebSocketSink {\n\treadonly sent: RecordedSend<any>[] = [];\n\treadonly broadcasts: RecordedBroadcast<any>[] = [];\n\treadonly closed: RecordedClose[] = [];\n\n\tconstructor(private readonly frame: FrameShape) {}\n\n\tasync send(ids: readonly string[], payload: string): Promise<void> {\n\t\tthis.sent.push({ ids: [...ids], ...this.decode(payload) });\n\t}\n\n\tasync broadcast(payload: string, except?: readonly string[]): Promise<void> {\n\t\tthis.broadcasts.push({\n\t\t\texcept: [...(except ?? [])],\n\t\t\t...this.decode(payload),\n\t\t});\n\t}\n\n\tasync close(\n\t\tids: readonly string[],\n\t\tcode: number,\n\t\treason: string,\n\t): Promise<void> {\n\t\tthis.closed.push({ ids: [...ids], code, reason });\n\t}\n\n\tclear(): void {\n\t\tthis.sent.length = 0;\n\t\tthis.broadcasts.length = 0;\n\t\tthis.closed.length = 0;\n\t}\n\n\tprivate decode(payload: string): RecordedMessage {\n\t\tconst frame = JSON.parse(payload) as Record<string, unknown>;\n\t\t// A publisher only ever hands over a frame it encoded itself.\n\t\tconst { action, data } = this.frame.decode(frame)!;\n\t\treturn { action, data, frame };\n\t}\n}\n\n/**\n * A surface's publisher that records rather than sends — what\n * `surface.testPublisher()` returns, of the type `services.<surface>` is.\n *\n * Every send is still checked by the declared `messages` and encoded by the\n * surface's `frame`, so an invalid push fails the spec as it would fail\n * deployed, and `frame` on each record is what the client would parse.\n */\nexport class TestWebSocketPublisher<\n\tTMessages extends WebSocketMessages = NoMessages,\n> extends WebSocketPublisher<TMessages> {\n\t/** Where the records are kept — what `route.request()` builds its core on. */\n\treadonly recording: RecordingSink;\n\n\tconstructor(\n\t\tframe: FrameShape,\n\t\tdeclared?: { surface: string; messages: TMessages },\n\t) {\n\t\tconst recording = new RecordingSink(frame);\n\t\tsuper(recording, declared, frame);\n\t\tthis.recording = recording;\n\t}\n\n\t/** Each `send(ids, action, data)`, in order. */\n\tget sent(): readonly RecordedSend<TMessages>[] {\n\t\treturn this.recording.sent;\n\t}\n\n\t/** Each `broadcast(action, data, { except })`, in order. */\n\tget broadcasts(): readonly RecordedBroadcast<TMessages>[] {\n\t\treturn this.recording.broadcasts;\n\t}\n\n\t/** Each `close(ids, code, reason)`, in order. */\n\tget closed(): readonly RecordedClose[] {\n\t\treturn this.recording.closed;\n\t}\n\n\t/** Forget everything recorded so far. */\n\tclear(): void {\n\t\tthis.recording.clear();\n\t}\n}\n\n/** A frame `route.request()` sent was refused before its handler ran. */\nexport class InvalidWebSocketRequest extends Error {\n\tconstructor(\n\t\treadonly surface: string,\n\t\treadonly action: string,\n\t\t/** What the `$error` frame said. */\n\t\treadonly reason: string,\n\t\treadonly issues?: readonly StandardSchemaV1.Issue[],\n\t) {\n\t\tsuper(\n\t\t\t`${surface}'s '${action}' route refused the request: ${reason}${\n\t\t\t\tissues?.length\n\t\t\t\t\t? ` ${issues.map((issue) => issue.message).join('; ')}.`\n\t\t\t\t\t: ''\n\t\t\t} Send a body its schema accepts.`,\n\t\t);\n\t\tthis.name = 'InvalidWebSocketRequest';\n\t}\n}\n\n/** What a surface hands its routes' `request()`. */\nexport interface WebSocketTestSurface {\n\treadonly id: string;\n\tcore(options: {\n\t\tenvParser: EnvironmentParser<{}>;\n\t\tsink: WebSocketSink;\n\t\tmodules?: readonly object[];\n\t}): WebSocketCore<any>;\n\treadonly envParser: EnvironmentParser<{}>;\n\ttestPublisher(): TestWebSocketPublisher<any>;\n}\n\n/** Overrides every `request()` takes. */\nexport interface WebSocketTestCallOptions {\n\t/**\n\t * Instances for the route's dependencies, by service name — a test's\n\t * transaction for `database`. Any it depends on and is not handed here is\n\t * registered, as deployed.\n\t */\n\tservices?: Record<string, unknown>;\n\t/**\n\t * The handler's `sockets`. Pass `surface.testPublisher()` to assert what\n\t * it sent; absent, a fresh one that nobody reads.\n\t */\n\tsockets?: TestWebSocketPublisher<any>;\n}\n\nexport interface TestConnectRequest extends WebSocketTestCallOptions {\n\t/** The id the connection is given. Absent, `test.<n>`. */\n\tconnectionId?: string;\n\t/** The handshake's headers — what `.auth()` verifies without a `session`. */\n\theaders?: ConstructorParameters<typeof Headers>[0];\n\t/** The upgrade URL's query. */\n\tquery?: string | Record<string, string> | URLSearchParams;\n\t/**\n\t * What the surface's `.auth()` would have resolved — `null` for no\n\t * session. Absent, `.auth()` verifies `headers`, as on a real upgrade.\n\t */\n\tsession?: unknown;\n}\n\nexport interface TestMessageRequest<TBody = unknown>\n\textends WebSocketTestCallOptions {\n\t/** The connection the frame arrives on. Absent, `test.<n>` with no data. */\n\tconnection?: TestConnection;\n\t/** The frame's data — checked by the route's `body`, as a frame's is. */\n\tbody: TBody;\n\t/** The frame's `id`, echoed on its reply. Only `{ action, data }` frames. */\n\tid?: string | number;\n}\n\nexport interface TestDisconnectRequest extends WebSocketTestCallOptions {\n\t/** The connection that closed. Absent, `test.<n>` with no data. */\n\tconnection?: TestConnection;\n\t/** Default 1000. */\n\tcode?: number;\n\t/** Default ''. */\n\treason?: string;\n}\n\n/** A connection a test names: either part may be left to its default. */\nexport interface TestConnection {\n\tid?: string;\n\tdata?: Record<string, unknown>;\n}\n\n/** What a message route's `fullRequest()` resolves with. */\nexport interface TestMessageResponse<TReturned = unknown> {\n\t/** The handler's return — the reply, before it was encoded. */\n\treturned: TReturned;\n\t/**\n\t * Every frame written back to the connection, parsed, in order: each\n\t * `reply()` and the reply to the frame itself.\n\t */\n\tframes: unknown[];\n}\n\nlet issued = 0;\n\n/** A connection id no other test call is using. */\nfunction nextConnectionId(): string {\n\tissued += 1;\n\treturn `test.${issued}`;\n}\n\nfunction connectionOf(given?: TestConnection): Connection {\n\treturn { id: given?.id ?? nextConnectionId(), data: given?.data ?? {} };\n}\n\nfunction coreFor(\n\troute: WebSocketRoute<any, any, any, any, any>,\n\tsurface: WebSocketTestSurface,\n\tsockets: TestWebSocketPublisher<any> | undefined,\n): WebSocketCore<any> {\n\treturn surface.core({\n\t\tenvParser: surface.envParser,\n\t\tsink: (sockets ?? surface.testPublisher()).recording,\n\t\tmodules: [{ route }],\n\t});\n}\n\n/** `connect.request()`: the connection's `data`, or what refused it. */\nexport async function requestConnect(\n\troute: WebSocketRoute<any, any, any, any, any>,\n\tsurface: WebSocketTestSurface,\n\trequest: TestConnectRequest = {},\n): Promise<Record<string, unknown>> {\n\tconst core = coreFor(route, surface, request.sockets);\n\tconst outcome = await core.connect(\n\t\t{\n\t\t\tconnectionId: request.connectionId ?? nextConnectionId(),\n\t\t\theaders: new Headers(request.headers),\n\t\t\tquery: new URLSearchParams(request.query),\n\t\t\t...('session' in request ? { session: request.session } : {}),\n\t\t},\n\t\trequest.services ? { services: request.services } : {},\n\t);\n\tif (!outcome.accepted) throw outcome.error;\n\treturn outcome.connection.data;\n}\n\n/** A message route's `fullRequest()`: what it returned and wrote. */\nexport async function requestMessage(\n\troute: WebSocketRoute<any, any, any, any, any>,\n\tsurface: WebSocketTestSurface,\n\trequest: TestMessageRequest,\n): Promise<TestMessageResponse> {\n\tconst core = coreFor(route, surface, request.sockets);\n\tconst frames: unknown[] = [];\n\tconst outcome = await core.message(\n\t\tconnectionOf(request.connection),\n\t\tcore.frame.encode(route.action, request.body, request.id),\n\t\t(payload) => frames.push(JSON.parse(payload)),\n\t\trequest.services ? { services: request.services } : {},\n\t);\n\tif (outcome.ok) return { returned: outcome.returned, frames };\n\tif ('error' in outcome) throw outcome.error;\n\tthrow new InvalidWebSocketRequest(\n\t\tsurface.id,\n\t\troute.action,\n\t\toutcome.message,\n\t\toutcome.issues,\n\t);\n}\n\n/** `disconnect.request()`: resolves once the handler has run. */\nexport async function requestDisconnect(\n\troute: WebSocketRoute<any, any, any, any, any>,\n\tsurface: WebSocketTestSurface,\n\trequest: TestDisconnectRequest = {},\n): Promise<void> {\n\tconst core = coreFor(route, surface, request.sockets);\n\tconst outcome = await core.disconnect(\n\t\tconnectionOf(request.connection),\n\t\t{ code: request.code ?? 1000, reason: request.reason ?? '' },\n\t\trequest.services ? { services: request.services } : {},\n\t);\n\tif (!outcome.ok) throw outcome.error;\n}\n","import type { Logger } from '@geekmidas/logger';\nimport type { InferStandardSchema } from '@geekmidas/schema';\nimport type { Service, ServiceRecord } from '@geekmidas/services';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\nimport {\n\ttype Consumable,\n\tidsOf,\n\ttype ServicesOf,\n\tservicesOf,\n} from '../construct-interface';\nimport type {\n\tNoMessages,\n\tWebSocketMessages,\n\tWebSocketPublisher,\n} from './publisher';\nimport {\n\trequestConnect,\n\trequestDisconnect,\n\trequestMessage,\n\ttype TestConnectRequest,\n\ttype TestDisconnectRequest,\n\ttype TestMessageRequest,\n\ttype TestMessageResponse,\n\ttype TestWebSocketPublisher,\n\ttype WebSocketTestSurface,\n} from './testing';\n\n/** One open connection, as a handler sees it. */\nexport interface Connection {\n\treadonly id: string;\n\t/**\n\t * What the connect handler returned — who the connection is for, the room\n\t * it joined. `{}` when it returned nothing.\n\t */\n\treadonly data: Record<string, unknown>;\n}\n\ninterface BaseContext<\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages,\n> {\n\tservices: ServiceRecord<TServices>;\n\tlogger: Logger;\n\t/** Every socket this surface holds, on whichever process holds it. */\n\tsockets: WebSocketPublisher<TMessages>;\n}\n\nexport interface ConnectContext<\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages = NoMessages,\n> extends BaseContext<TServices, TMessages> {\n\tconnectionId: string;\n\theaders: Headers;\n\tquery: URLSearchParams;\n\t/**\n\t * Whose connection it is, from the surface's `.auth()` — `null` when the\n\t * upgrade carried no session, and when the surface names no authenticator.\n\t * Throw an `UnauthorizedError` to refuse it.\n\t */\n\tsession: unknown;\n}\n\nexport interface MessageContext<\n\tTBody,\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages = NoMessages,\n> extends BaseContext<TServices, TMessages> {\n\tconnection: Connection;\n\tbody: TBody;\n\t/** Send to this connection alone. */\n\treply(message: unknown): void;\n}\n\nexport interface DisconnectContext<\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages = NoMessages,\n> extends BaseContext<TServices, TMessages> {\n\tconnection: Connection;\n\tcode: number;\n\treason: string;\n}\n\n/** What a frame is dispatched on: an action, or the connection's lifecycle. */\nexport type RouteKind = 'connect' | 'disconnect' | 'message';\n\n/**\n * A handler bound to a WebSocket surface — what `realtime.route('chat.send')\n * …handle()` returns, and what a file exports.\n *\n * Carries `surface` and `constructs` the way an endpoint does, so discovery\n * records what its process reaches without knowing what a route is.\n */\nexport class WebSocketRoute<\n\tTKind extends RouteKind = RouteKind,\n\tTSchema extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined,\n\tTServices extends Service[] = Service[],\n\t/** What the handler returns. */\n\tTReturn = unknown,\n\tTMessages extends WebSocketMessages = WebSocketMessages,\n> {\n\treadonly __IS_WEBSOCKET_ROUTE__ = true;\n\n\tstatic isRoute(value: unknown): value is WebSocketRoute {\n\t\treturn Boolean(\n\t\t\tvalue &&\n\t\t\t\t(value as { __IS_WEBSOCKET_ROUTE__?: unknown })\n\t\t\t\t\t.__IS_WEBSOCKET_ROUTE__ === true,\n\t\t);\n\t}\n\n\tconstructor(\n\t\treadonly kind: TKind,\n\t\t/** The `action` it answers; `$connect` and `$disconnect` for the lifecycle. */\n\t\treadonly action: string,\n\t\t/** The surface it was built from — what `request()` builds a core on. */\n\t\treadonly surface: WebSocketTestSurface,\n\t\treadonly services: readonly Service[],\n\t\t/** Construct ids it depends on — its edges in the manifest. */\n\t\treadonly constructs: readonly string[],\n\t\treadonly handler: (context: never) => unknown,\n\t\treadonly schema?: TSchema,\n\t) {}\n\n\t/**\n\t * Run the handler as its surface would, with no server and no socket —\n\t * as `endpoint.request()` runs an endpoint.\n\t *\n\t * - `connect`: resolves with the connection's `data`, or rejects with what\n\t * refused it (an `UnauthorizedError` stays a 401).\n\t * - a message route: `body` is encoded as a frame and checked by the\n\t * route's schema; resolves with the handler's return, or rejects with\n\t * what it threw or an `InvalidWebSocketRequest`.\n\t * - `disconnect`: resolves once the handler has run, or rejects with what\n\t * it threw.\n\t */\n\trequest(\n\t\t...[request]: RequestArgs<TKind, TSchema, TServices, TMessages>\n\t): Promise<WebSocketRouteResult<TKind, TReturn>> {\n\t\tconst route = this as AnyRoute;\n\t\tconst given = (request ?? {}) as TestConnectRequest & TestDisconnectRequest;\n\t\tif (this.kind === 'connect') {\n\t\t\treturn requestConnect(route, this.surface, given) as never;\n\t\t}\n\t\tif (this.kind === 'disconnect') {\n\t\t\treturn requestDisconnect(route, this.surface, given) as never;\n\t\t}\n\t\treturn requestMessage(\n\t\t\troute,\n\t\t\tthis.surface,\n\t\t\tgiven as unknown as TestMessageRequest,\n\t\t).then(({ returned }) => returned) as never;\n\t}\n\n\t/**\n\t * A message route's `request()`, with every frame it wrote back to the\n\t * connection — each `reply()` and the reply itself — beside its return.\n\t */\n\tfullRequest(\n\t\tthis: WebSocketRoute<'message', TSchema, TServices, TReturn, TMessages>,\n\t\trequest: WebSocketRouteRequest<'message', TSchema, TServices, TMessages>,\n\t): Promise<TestMessageResponse<Awaited<TReturn>>> {\n\t\treturn requestMessage(\n\t\t\tthis as AnyRoute,\n\t\t\tthis.surface,\n\t\t\trequest as unknown as TestMessageRequest,\n\t\t) as Promise<TestMessageResponse<Awaited<TReturn>>>;\n\t}\n}\n\ntype AnyRoute = WebSocketRoute<any, any, any, any, any>;\n\n/** A message route needs a body; the lifecycle's request may be left out. */\ntype RequestArgs<\n\tTKind extends RouteKind,\n\tTSchema extends StandardSchemaV1 | undefined,\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages,\n> = TKind extends 'message'\n\t? [request: WebSocketRouteRequest<TKind, TSchema, TServices, TMessages>]\n\t: [request?: WebSocketRouteRequest<TKind, TSchema, TServices, TMessages>];\n\n/** What `request()` takes for each kind of route. */\nexport type WebSocketRouteRequest<\n\tTKind extends RouteKind,\n\tTSchema extends StandardSchemaV1 | undefined,\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages,\n> = TestCallOverrides<TServices, TMessages> &\n\t(TKind extends 'connect'\n\t\t? Omit<TestConnectRequest, 'services' | 'sockets'>\n\t\t: TKind extends 'disconnect'\n\t\t\t? Omit<TestDisconnectRequest, 'services' | 'sockets'>\n\t\t\t: Omit<\n\t\t\t\t\tTestMessageRequest<\n\t\t\t\t\t\tTSchema extends StandardSchemaV1\n\t\t\t\t\t\t\t? StandardSchemaV1.InferInput<TSchema>\n\t\t\t\t\t\t\t: unknown\n\t\t\t\t\t>,\n\t\t\t\t\t'services' | 'sockets'\n\t\t\t\t>);\n\n/** `services` typed by what the route depends on; `sockets` by the surface. */\nexport interface TestCallOverrides<\n\tTServices extends Service[],\n\tTMessages extends WebSocketMessages,\n> {\n\t/**\n\t * Instances for the route's dependencies — a test's transaction for\n\t * `database`. Any it depends on and is not handed here is registered.\n\t */\n\tservices?: Partial<ServiceRecord<TServices>>;\n\t/** The handler's `sockets` — `surface.testPublisher()` to assert on. */\n\tsockets?: TestWebSocketPublisher<TMessages>;\n}\n\n/** What `request()` resolves with for each kind of route. */\nexport type WebSocketRouteResult<\n\tTKind extends RouteKind,\n\tTReturn,\n> = TKind extends 'connect'\n\t? ConnectData<Awaited<TReturn>>\n\t: TKind extends 'disconnect'\n\t\t? undefined\n\t\t: Awaited<TReturn>;\n\n/** A connect handler's return as the connection keeps it: `{}` for nothing. */\ntype ConnectData<T> = T extends undefined ? {} : T;\n\n/** What a handler may return, by kind: connect's becomes `data`. */\ntype HandlerReturn<TKind extends RouteKind> = TKind extends 'connect'\n\t?\n\t\t\t| Record<string, unknown>\n\t\t\t| undefined\n\t\t\t| Promise<Record<string, unknown> | undefined>\n\t: unknown;\n\n/** The builder `connect()`, `disconnect()` and `route()` start. */\nexport class WebSocketRouteBuilder<\n\tTKind extends RouteKind,\n\tTSchema extends StandardSchemaV1 | undefined = undefined,\n\tTServices extends Service[] = [],\n\t/** The surface's declared messages, which `sockets` sends. */\n\tTMessages extends WebSocketMessages = NoMessages,\n> {\n\tconstructor(\n\t\tprivate readonly kind: TKind,\n\t\tprivate readonly action: string,\n\t\tprivate readonly surface: WebSocketTestSurface,\n\t\tprivate readonly _services: readonly Service[] = [],\n\t\tprivate readonly _constructs: readonly string[] = [],\n\t\tprivate readonly schema?: TSchema,\n\t) {}\n\n\t/** The schema a frame's `data` must satisfy before the handler runs. */\n\tbody<S extends StandardSchemaV1>(\n\t\tschema: S,\n\t): WebSocketRouteBuilder<TKind, S, TServices, TMessages> {\n\t\treturn new WebSocketRouteBuilder(\n\t\t\tthis.kind,\n\t\t\tthis.action,\n\t\t\tthis.surface,\n\t\t\tthis._services,\n\t\t\tthis._constructs,\n\t\t\tschema,\n\t\t);\n\t}\n\n\t/** What the handler reaches, as `services.<id>` — per route, as an endpoint's. */\n\tdependsOn<const T extends readonly Consumable[]>(\n\t\tconstructs: T,\n\t): WebSocketRouteBuilder<\n\t\tTKind,\n\t\tTSchema,\n\t\t[...TServices, ...ServicesOf<T>],\n\t\tTMessages\n\t> {\n\t\treturn new WebSocketRouteBuilder(\n\t\t\tthis.kind,\n\t\t\tthis.action,\n\t\t\tthis.surface,\n\t\t\t[...this._services, ...(servicesOf(constructs) as Service[])],\n\t\t\tidsOf(constructs, this._constructs),\n\t\t\tthis.schema,\n\t\t) as never;\n\t}\n\n\t/**\n\t * The handler. A message handler's return value, when there is one, is\n\t * sent back to the connection as the reply to that frame; a connect\n\t * handler's is kept as the connection's `data`.\n\t */\n\thandle<TReturn extends HandlerReturn<TKind>>(\n\t\thandler: TKind extends 'connect'\n\t\t\t? (context: ConnectContext<TServices, TMessages>) => TReturn\n\t\t\t: TKind extends 'disconnect'\n\t\t\t\t? (context: DisconnectContext<TServices, TMessages>) => TReturn\n\t\t\t\t: (\n\t\t\t\t\t\tcontext: MessageContext<\n\t\t\t\t\t\t\tTSchema extends StandardSchemaV1\n\t\t\t\t\t\t\t\t? InferStandardSchema<TSchema>\n\t\t\t\t\t\t\t\t: unknown,\n\t\t\t\t\t\t\tTServices,\n\t\t\t\t\t\t\tTMessages\n\t\t\t\t\t\t>,\n\t\t\t\t\t) => TReturn,\n\t): WebSocketRoute<TKind, TSchema, TServices, TReturn, TMessages> {\n\t\treturn new WebSocketRoute(\n\t\t\tthis.kind,\n\t\t\tthis.action,\n\t\t\tthis.surface,\n\t\t\tthis._services,\n\t\t\tthis._constructs,\n\t\t\thandler as (context: never) => unknown,\n\t\t\tthis.schema,\n\t\t);\n\t}\n}\n","/**\n * How a send reaches the process holding the socket.\n *\n * A connection id names the process it lives on — `<instance>.<n>` — so a send\n * needs no registry: it is published to that instance's channel and nowhere\n * else. A broadcast goes to every instance. On a stack the channels are Redis\n * pub/sub, so an endpoint in another container reaches a socket the same way a\n * route beside it does; in one process (a test, a single dev server) they are\n * a map.\n */\n\nimport type { WebSocketSink } from './publisher';\n\n/** What one process is asked to do with the sockets it holds. */\nexport type Delivery =\n\t| { kind: 'send'; ids: readonly string[]; payload: string }\n\t| { kind: 'broadcast'; payload: string; except?: readonly string[] }\n\t| { kind: 'close'; ids: readonly string[]; code: number; reason: string };\n\nexport interface WebSocketTransport {\n\t/** Deliver to one instance, or to every instance when it is `'*'`. */\n\tpublish(instance: string, delivery: Delivery): Promise<void>;\n\t/** Receive what is published to `instance`, and every broadcast. */\n\tsubscribe(\n\t\tinstance: string,\n\t\treceive: (delivery: Delivery) => void,\n\t): Promise<void>;\n\tclose(): Promise<void>;\n}\n\n/** Every instance — what a broadcast is published to. */\nexport const EVERY_INSTANCE = '*';\n\n/** The instance a connection id was issued by: everything before its dot. */\nexport function instanceOf(connectionId: string): string | undefined {\n\tconst dot = connectionId.indexOf('.');\n\treturn dot > 0 ? connectionId.slice(0, dot) : undefined;\n}\n\n/**\n * A publisher's sink over a transport: a send goes to the instance each\n * connection id names, a broadcast to every instance. What `services.<id>`\n * sends through, and what the Node adaptor's own `sockets` do.\n */\nexport class TransportSink implements WebSocketSink {\n\tconstructor(\n\t\tprivate readonly transport: WebSocketTransport,\n\t\t/**\n\t\t * Delivers to this process's own sockets without a round trip through\n\t\t * the transport — set by the process that holds them.\n\t\t */\n\t\tprivate readonly local?: {\n\t\t\tinstance: string;\n\t\t\tdeliver(delivery: Delivery): void;\n\t\t},\n\t) {}\n\n\tsend(ids: readonly string[], payload: string): Promise<void> {\n\t\treturn this.each(ids, (group) => ({ kind: 'send', ids: group, payload }));\n\t}\n\n\tasync broadcast(payload: string, except?: readonly string[]): Promise<void> {\n\t\tawait this.transport.publish(EVERY_INSTANCE, {\n\t\t\tkind: 'broadcast',\n\t\t\tpayload,\n\t\t\t...(except?.length ? { except } : {}),\n\t\t});\n\t}\n\n\tclose(ids: readonly string[], code: number, reason: string): Promise<void> {\n\t\treturn this.each(ids, (group) => ({\n\t\t\tkind: 'close',\n\t\t\tids: group,\n\t\t\tcode,\n\t\t\treason,\n\t\t}));\n\t}\n\n\t/** One delivery per process that holds any of `ids`. */\n\tprivate async each(\n\t\tids: readonly string[],\n\t\tdelivery: (group: string[]) => Delivery,\n\t): Promise<void> {\n\t\tconst byInstance = new Map<string, string[]>();\n\t\tfor (const id of ids) {\n\t\t\tconst instance = instanceOf(id);\n\t\t\tif (!instance) continue;\n\t\t\tconst group = byInstance.get(instance) ?? [];\n\t\t\tgroup.push(id);\n\t\t\tbyInstance.set(instance, group);\n\t\t}\n\n\t\tawait Promise.all(\n\t\t\t[...byInstance].map(([instance, group]) =>\n\t\t\t\tthis.local?.instance === instance\n\t\t\t\t\t? this.local.deliver(delivery(group))\n\t\t\t\t\t: this.transport.publish(instance, delivery(group)),\n\t\t\t),\n\t\t);\n\t}\n}\n\n/** A connection string names no transport this package knows. */\nexport class UnsupportedWebSocketTransport extends Error {\n\tconstructor(readonly connectionString: string) {\n\t\tsuper(\n\t\t\t`'${redact(connectionString)}' is not a WebSocket publisher connection string. ` +\n\t\t\t\t'Use redis://, rediss:// or memory:// — gkm composes it as <ID>_PUBLISHER_CONNECTION_STRING.',\n\t\t);\n\t\tthis.name = 'UnsupportedWebSocketTransport';\n\t}\n}\n\n/** The scheme alone, so an error never prints a password. */\nfunction redact(connectionString: string): string {\n\tconst scheme = connectionString.split('://')[0];\n\treturn scheme && scheme !== connectionString\n\t\t? `${scheme}://…`\n\t\t: connectionString.slice(0, 12);\n}\n\n// On globalThis, as the shutdown hooks are: a package loaded as ESM and CJS\n// would otherwise hold two maps, and a publisher would talk to the empty one.\nconst key = Symbol.for('@geekmidas/constructs/websocket/memory');\nconst registry = globalThis as Record<\n\tsymbol,\n\tMap<string, Map<string, (delivery: Delivery) => void>> | undefined\n>;\nregistry[key] ??= new Map();\nconst channels = registry[key];\n\n/**\n * In one process: the server and whoever sends meet in a map, keyed by the\n * channel the connection string names.\n */\nexport class MemoryTransport implements WebSocketTransport {\n\tprivate readonly subscribed = new Set<string>();\n\n\tconstructor(private readonly channel: string) {}\n\n\tasync publish(instance: string, delivery: Delivery): Promise<void> {\n\t\tconst instances = channels.get(this.channel);\n\t\tif (!instances) return;\n\t\tif (instance === EVERY_INSTANCE) {\n\t\t\tfor (const receive of instances.values()) receive(delivery);\n\t\t\treturn;\n\t\t}\n\t\tinstances.get(instance)?.(delivery);\n\t}\n\n\tasync subscribe(\n\t\tinstance: string,\n\t\treceive: (delivery: Delivery) => void,\n\t): Promise<void> {\n\t\tlet instances = channels.get(this.channel);\n\t\tif (!instances) {\n\t\t\tinstances = new Map();\n\t\t\tchannels.set(this.channel, instances);\n\t\t}\n\t\tinstances.set(instance, receive);\n\t\tthis.subscribed.add(instance);\n\t}\n\n\tasync close(): Promise<void> {\n\t\tconst instances = channels.get(this.channel);\n\t\tfor (const instance of this.subscribed) instances?.delete(instance);\n\t\tthis.subscribed.clear();\n\t}\n}\n\n/** The subset of an ioredis client the transport uses. */\ninterface RedisClient {\n\tpublish(channel: string, message: string): Promise<number>;\n\tsubscribe(...channels: string[]): Promise<unknown>;\n\ton(\n\t\tevent: 'message',\n\t\tlistener: (channel: string, message: string) => void,\n\t): unknown;\n\tduplicate(): RedisClient;\n\tquit(): Promise<unknown>;\n}\n\n/**\n * Over Redis pub/sub: one channel per instance and one for broadcasts, under\n * a prefix that keeps two surfaces — or two projects on one Redis — apart.\n * Channels are not scoped by database index, so the prefix is what does it.\n *\n * Publishing and subscribing take separate connections, because a connection\n * that has subscribed can do nothing else.\n */\nexport class RedisTransport implements WebSocketTransport {\n\tprivate subscriber?: RedisClient;\n\tprivate closed?: Promise<void>;\n\n\tconstructor(\n\t\tprivate readonly client: RedisClient,\n\t\tprivate readonly prefix: string,\n\t) {}\n\n\tprivate channel(instance: string): string {\n\t\treturn `${this.prefix}:${instance}`;\n\t}\n\n\tasync publish(instance: string, delivery: Delivery): Promise<void> {\n\t\tawait this.client.publish(this.channel(instance), JSON.stringify(delivery));\n\t}\n\n\tasync subscribe(\n\t\tinstance: string,\n\t\treceive: (delivery: Delivery) => void,\n\t): Promise<void> {\n\t\tconst subscriber = this.client.duplicate();\n\t\tthis.subscriber = subscriber;\n\t\tconst own = this.channel(instance);\n\t\tconst every = this.channel(EVERY_INSTANCE);\n\t\tsubscriber.on('message', (channel, message) => {\n\t\t\tif (channel !== own && channel !== every) return;\n\t\t\treceive(JSON.parse(message) as Delivery);\n\t\t});\n\t\tawait subscriber.subscribe(own, every);\n\t}\n\n\t/** Idempotent: the server and a shutdown hook may both close it. */\n\tclose(): Promise<void> {\n\t\tthis.closed ??= Promise.all([\n\t\t\tthis.subscriber?.quit(),\n\t\t\tthis.client.quit(),\n\t\t]).then(() => undefined);\n\t\treturn this.closed;\n\t}\n}\n\n/**\n * The transport a connection string names.\n *\n * `redis://` and `rediss://` take an optional `channel` query parameter, the\n * prefix every channel is named under; `memory://<channel>` is in-process.\n * Absent, the channel is `fallback` — the surface's own.\n */\nexport async function transportFromConnectionString(\n\tconnectionString: string,\n\tfallback: string,\n): Promise<WebSocketTransport> {\n\t// Not parsed as a URL: a channel is `gkm:ws:<id>`, colons and all.\n\tif (connectionString.startsWith('memory://')) {\n\t\treturn new MemoryTransport(\n\t\t\tconnectionString.slice('memory://'.length) || fallback,\n\t\t);\n\t}\n\n\tconst url = URL.canParse(connectionString)\n\t\t? new URL(connectionString)\n\t\t: undefined;\n\tif (!url) throw new UnsupportedWebSocketTransport(connectionString);\n\n\tif (url.protocol === 'redis:' || url.protocol === 'rediss:') {\n\t\tconst channel = url.searchParams.get('channel') || fallback;\n\t\turl.searchParams.delete('channel');\n\t\tconst { Redis } = await import('ioredis');\n\t\tconst client = new Redis(url.toString(), {\n\t\t\t// A publish while Redis restarts waits for it rather than failing the\n\t\t\t// request that sent it.\n\t\t\tmaxRetriesPerRequest: null,\n\t\t\tlazyConnect: false,\n\t\t});\n\t\treturn new RedisTransport(client as unknown as RedisClient, channel);\n\t}\n\n\tthrow new UnsupportedWebSocketTransport(connectionString);\n}\n","/**\n * The Node adaptor: the process that holds a WebSocket surface's sockets.\n *\n * Node's own `http` server and `ws`, nothing between them. This owns what\n * only a real socket has — the upgrade, the Origin check, connection ids,\n * the heartbeat, backpressure — and hands the rest to the surface's\n * `WebSocketCore`: a handshake to `connect()`, each frame to `message()`, a\n * close to `disconnect()`. The HTTP server is whatever the entry started —\n * the generated one serves `/health` on the same port — and this attaches to\n * its `upgrade` event.\n */\n\nimport { randomBytes } from 'node:crypto';\nimport type { IncomingMessage, Server } from 'node:http';\nimport type { Duplex } from 'node:stream';\nimport { trustsOrigin } from '@geekmidas/manifest';\nimport type { RawData, WebSocket, WebSocketServer } from 'ws';\nimport type { WebSocketCore } from './core';\nimport type {\n\tNoMessages,\n\tWebSocketMessages,\n\tWebSocketPublisher,\n\tWebSocketSink,\n} from './publisher';\nimport type { Connection } from './route';\nimport {\n\ttype Delivery,\n\tTransportSink,\n\ttype WebSocketTransport,\n} from './transport';\n\n/** Close codes a client sees. */\nexport const CLOSE = {\n\tnormal: 1000,\n\t/** The process is stopping; reconnect and land on another. */\n\tserviceRestart: 1012,\n\t/** It stopped reading, and what was queued for it passed the limit. */\n\ttooSlow: 1013,\n} as const;\n\nexport interface WebSocketServerOptions<\n\tTMessages extends WebSocketMessages = NoMessages,\n> {\n\t/**\n\t * The surface's core, over the sink this process sends through — its own\n\t * sockets directly, every other process's over `transport`.\n\t */\n\tcore(sink: WebSocketSink): WebSocketCore<TMessages>;\n\ttransport: WebSocketTransport;\n\t/**\n\t * Origins a browser may open a socket from. A request with an `Origin`\n\t * not in the list is refused with 403; one with none — a server, a load\n\t * generator — is not a browser, and is let through.\n\t */\n\ttrustedOrigins: readonly string[];\n\t/**\n\t * The surface's own public address, `<ID>_URL`. Its origin is always\n\t * trusted: a native client (React Native's `WebSocket`) sends the socket's\n\t * own origin as its `Origin`.\n\t */\n\turl?: string;\n\t/** How often each socket is pinged; one that missed the last is dropped. */\n\theartbeatMs?: number;\n\t/** The largest frame accepted, in bytes. */\n\tmaxPayload?: number;\n\t/** Queued bytes a socket may hold before it is closed as too slow. */\n\tmaxBufferedBytes?: number;\n}\n\ninterface Held {\n\tsocket: WebSocket;\n\tconnection: Connection;\n\talive: boolean;\n}\n\nexport class WebSocketSurfaceServer<\n\tTMessages extends WebSocketMessages = NoMessages,\n> {\n\t/** This process, as connection ids name it. */\n\treadonly instance = randomBytes(6).toString('hex');\n\t/** Where each handshake, frame and close is handed. */\n\treadonly core: WebSocketCore<TMessages>;\n\n\tprivate readonly held = new Map<string, Held>();\n\tprivate readonly heartbeat: NodeJS.Timeout;\n\tprivate readonly trusted: readonly string[];\n\tprivate next = 0;\n\tprivate closing = false;\n\n\tprivate constructor(\n\t\tprivate readonly wss: WebSocketServer,\n\t\tprivate readonly options: WebSocketServerOptions<TMessages>,\n\t) {\n\t\t// Local sends skip the transport.\n\t\tthis.core = options.core(\n\t\t\tnew TransportSink(options.transport, {\n\t\t\t\tinstance: this.instance,\n\t\t\t\tdeliver: (delivery) => this.deliver(delivery),\n\t\t\t}),\n\t\t);\n\t\tthis.trusted = [...options.trustedOrigins, ...ownOrigins(options.url)];\n\n\t\tthis.heartbeat = setInterval(\n\t\t\t() => this.beat(),\n\t\t\toptions.heartbeatMs ?? 30_000,\n\t\t);\n\t\tthis.heartbeat.unref();\n\t}\n\n\tstatic async start<TMessages extends WebSocketMessages = NoMessages>(\n\t\toptions: WebSocketServerOptions<TMessages>,\n\t): Promise<WebSocketSurfaceServer<TMessages>> {\n\t\tconst { WebSocketServer } = await import('ws');\n\t\tconst wss = new WebSocketServer({\n\t\t\tnoServer: true,\n\t\t\tmaxPayload: options.maxPayload ?? 1024 * 1024,\n\t\t\t// Compression costs a zlib context per socket — tens of KB each,\n\t\t\t// the largest share of a connection's memory — for frames that are\n\t\t\t// mostly small JSON.\n\t\t\tperMessageDeflate: false,\n\t\t\tclientTracking: false,\n\t\t});\n\t\tconst server = new WebSocketSurfaceServer<TMessages>(wss, options);\n\t\tawait options.transport.subscribe(server.instance, (delivery) =>\n\t\t\tserver.deliver(delivery),\n\t\t);\n\t\treturn server;\n\t}\n\n\t/** `sockets` in a route: local sends skip the transport. */\n\tget publisher(): WebSocketPublisher<TMessages> {\n\t\treturn this.core.sockets;\n\t}\n\n\t/** How many sockets this process holds. */\n\tget size(): number {\n\t\treturn this.held.size;\n\t}\n\n\t/** Take over `server`'s upgrades. */\n\tattach(server: Server): void {\n\t\tserver.on('upgrade', (request, socket, head) => {\n\t\t\tvoid this.upgrade(request, socket, head);\n\t\t});\n\t}\n\n\t/** Upgrade one request, or refuse it with a status line. */\n\tasync upgrade(\n\t\trequest: IncomingMessage,\n\t\tsocket: Duplex,\n\t\thead: Buffer,\n\t): Promise<void> {\n\t\tif (this.closing) return refuse(socket, 503, 'Service Unavailable');\n\n\t\tconst origin = request.headers.origin;\n\t\tif (origin && !trustsOrigin(origin, this.trusted)) {\n\t\t\treturn refuse(socket, 403, 'Forbidden');\n\t\t}\n\n\t\tconst outcome = await this.core.connect({\n\t\t\tconnectionId: `${this.instance}.${(this.next++).toString(36)}`,\n\t\t\theaders: headersOf(request),\n\t\t\tquery: new URL(request.url ?? '/', 'http://localhost').searchParams,\n\t\t});\n\t\tif (!outcome.accepted) {\n\t\t\treturn refuse(socket, outcome.status, outcome.statusText);\n\t\t}\n\n\t\t// The client may have gone while the connect handler ran.\n\t\tif (socket.destroyed) return;\n\n\t\tthis.wss.handleUpgrade(request, socket, head, (ws) =>\n\t\t\tthis.open(ws, outcome.connection),\n\t\t);\n\t}\n\n\tprivate open(socket: WebSocket, connection: Connection): void {\n\t\tconst held: Held = { socket, connection, alive: true };\n\t\tthis.held.set(connection.id, held);\n\t\tconst write = (payload: string) => this.write(held, payload);\n\n\t\tsocket.on('pong', () => {\n\t\t\theld.alive = true;\n\t\t});\n\t\tsocket.on('message', (raw, isBinary) => {\n\t\t\theld.alive = true;\n\t\t\tvoid this.core.message(\n\t\t\t\tconnection,\n\t\t\t\tisBinary ? bytesOf(raw) : raw.toString(),\n\t\t\t\twrite,\n\t\t\t);\n\t\t});\n\t\tsocket.on('error', () => socket.terminate());\n\t\tsocket.on('close', (code, reason) => {\n\t\t\tthis.held.delete(connection.id);\n\t\t\tvoid this.core.disconnect(connection, {\n\t\t\t\tcode,\n\t\t\t\treason: reason.toString(),\n\t\t\t});\n\t\t});\n\t}\n\n\t/** Write, unless the socket has stopped reading and its queue is full. */\n\tprivate write(held: Held, payload: string): void {\n\t\tconst { socket } = held;\n\t\tif (socket.readyState !== socket.OPEN) return;\n\t\tif (\n\t\t\tsocket.bufferedAmount > (this.options.maxBufferedBytes ?? 4 * 1024 * 1024)\n\t\t) {\n\t\t\tsocket.close(CLOSE.tooSlow, 'Too slow');\n\t\t\treturn;\n\t\t}\n\t\tsocket.send(payload);\n\t}\n\n\t/** What the transport, or a local publisher, asked of this process. */\n\tprivate deliver(delivery: Delivery): void {\n\t\tswitch (delivery.kind) {\n\t\t\tcase 'send':\n\t\t\t\tfor (const id of delivery.ids) {\n\t\t\t\t\tconst held = this.held.get(id);\n\t\t\t\t\tif (held) this.write(held, delivery.payload);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase 'broadcast': {\n\t\t\t\tconst except = delivery.except ? new Set(delivery.except) : undefined;\n\t\t\t\tfor (const [id, held] of this.held) {\n\t\t\t\t\tif (!except?.has(id)) this.write(held, delivery.payload);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'close':\n\t\t\t\tfor (const id of delivery.ids) {\n\t\t\t\t\tthis.held.get(id)?.socket.close(delivery.code, delivery.reason);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t}\n\t}\n\n\t/** Drop every socket that missed the last ping, and ping the rest. */\n\tprivate beat(): void {\n\t\tfor (const [id, held] of this.held) {\n\t\t\tif (!held.alive) {\n\t\t\t\theld.socket.terminate();\n\t\t\t\tthis.held.delete(id);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\theld.alive = false;\n\t\t\theld.socket.ping();\n\t\t}\n\t}\n\n\t/**\n\t * Stop: refuse new upgrades, close every socket with `code` — 1012 tells\n\t * a client to reconnect, and it lands on a process that is still up — and\n\t * leave the transport.\n\t */\n\tasync close(\n\t\tcode: number = CLOSE.serviceRestart,\n\t\treason = 'Restarting',\n\t): Promise<void> {\n\t\tif (this.closing) return;\n\t\tthis.closing = true;\n\t\tclearInterval(this.heartbeat);\n\n\t\tconst closed = [...this.held.values()].map(\n\t\t\t({ socket }) =>\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\tif (socket.readyState === socket.CLOSED) return resolve();\n\t\t\t\t\tsocket.once('close', () => resolve());\n\t\t\t\t\tsocket.close(code, reason);\n\t\t\t\t\t// A client that never answers the close is cut off.\n\t\t\t\t\tsetTimeout(() => {\n\t\t\t\t\t\tsocket.terminate();\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}, 2_000).unref();\n\t\t\t\t}),\n\t\t);\n\t\tawait Promise.all(closed);\n\t\tawait this.options.transport.close();\n\t\tthis.wss.close();\n\t}\n}\n\n/**\n * The origins a client of the surface's own address sends: the `https://`\n * one a native socket derives from `wss://`, and the address's own.\n */\nfunction ownOrigins(url: string | undefined): string[] {\n\tif (!url || !URL.canParse(url)) return [];\n\tconst own = new URL(url);\n\tconst web = new URL(url.replace(/^ws(s?):/i, 'http$1:'));\n\treturn [...new Set([`${own.protocol}//${own.host}`, web.origin])];\n}\n\n/** A binary frame's bytes, however `ws` delivered them. */\nfunction bytesOf(raw: RawData): Uint8Array {\n\tif (Array.isArray(raw)) return Buffer.concat(raw);\n\treturn raw instanceof ArrayBuffer ? new Uint8Array(raw) : raw;\n}\n\nfunction headersOf(request: IncomingMessage): Headers {\n\tconst headers = new Headers();\n\tfor (const [name, value] of Object.entries(request.headers)) {\n\t\tif (value === undefined) continue;\n\t\tfor (const one of Array.isArray(value) ? value : [value]) {\n\t\t\theaders.append(name, one);\n\t\t}\n\t}\n\treturn headers;\n}\n\nfunction refuse(socket: Duplex, status: number, message: string): void {\n\tif (!socket.destroyed) {\n\t\tsocket.end(\n\t\t\t`HTTP/1.1 ${status} ${message}\\r\\nConnection: close\\r\\nContent-Length: 0\\r\\n\\r\\n`,\n\t\t);\n\t}\n}\n","/**\n * `WebSocketApi` — a surface that holds long-lived connections.\n *\n * A process of its own, like a `RestApi`: it owns an address, its routes are\n * built from it, and they run in its container and nowhere else. A frame is\n * routed on its `action` — `{ \"action\": \"chat.send\", \"data\": … }`, API\n * Gateway's shape — and the connection's lifecycle on `$connect` and\n * `$disconnect`. A surface whose clients already parse flat frames names the\n * key the action lives in instead — `frame: { discriminator: 'type' }` reads\n * and writes `{ \"type\": \"chat.send\", …data }`.\n *\n * Anything else reaches a socket through the surface's publisher:\n * `.dependsOn([realtime])` puts `services.realtime` in an endpoint, a cron or\n * a subscriber, and whichever replica holds the socket delivers. What it\n * sends is declared in `messages`, which the publisher is typed by.\n *\n * ```ts\n * export const realtime = new WebSocketApi('Realtime', {\n * path: 'apps/realtime',\n * messages: { 'chat.sent': z.object({ text: z.string() }) },\n * logger,\n * });\n *\n * export const send = realtime\n * .route('chat.send')\n * .body(z.object({ text: z.string() }))\n * .handle(async ({ body, sockets }) => sockets.broadcast('chat.sent', body));\n * ```\n */\n\nimport type { Server } from 'node:http';\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { DEFAULT_LOGGER } from '@geekmidas/logger/console';\nimport {\n\ttype ConstructName,\n\tcanonicalId,\n\ttype Declaration,\n\tprovideKey,\n\tserviceKey,\n} from '@geekmidas/manifest';\nimport type { Service, ServiceRegisterOptions } from '@geekmidas/services';\nimport type { Hono } from 'hono';\nimport {\n\ttype Authenticator,\n\ttype Declarable,\n\tedgeTo,\n} from './construct-interface';\nimport { envParserFor } from './endpoints/surfaceEnv';\nimport { onShutdown } from './shutdown';\nimport type { Telemetry } from './telemetry';\nimport { WebSocketCore } from './websocket/core';\nimport { FrameShape, type WebSocketFrame } from './websocket/frame';\nimport {\n\ttype NoMessages,\n\ttype WebSocketMessages,\n\tWebSocketPublisher,\n\ttype WebSocketSink,\n} from './websocket/publisher';\nimport { WebSocketRoute, WebSocketRouteBuilder } from './websocket/route';\nimport { WebSocketSurfaceServer } from './websocket/server';\nimport { TestWebSocketPublisher } from './websocket/testing';\nimport {\n\tTransportSink,\n\ttransportFromConnectionString,\n} from './websocket/transport';\n\nexport {\n\ttype ConnectOutcome,\n\ttype ConnectRequest,\n\ttype DisconnectOutcome,\n\tDuplicateWebSocketRoute,\n\ttype MessageOutcome,\n\ttype WebSocketCallOptions,\n\tWebSocketCore,\n\ttype WebSocketCoreOptions,\n\ttype WriteFrame,\n} from './websocket/core';\nexport {\n\tWebSocketDataHasDiscriminator,\n\tWebSocketDataNotAnObject,\n\ttype WebSocketFrame,\n\tWebSocketMessageDeclaresDiscriminator,\n\tWebSocketMessageNotAnObject,\n} from './websocket/frame';\nexport {\n\tInvalidWebSocketMessage,\n\ttype MessageAction,\n\ttype MessageData,\n\ttype NoMessages,\n\tUnknownWebSocketMessage,\n\ttype WebSocketMessages,\n\tWebSocketPublisher,\n\ttype WebSocketSink,\n} from './websocket/publisher';\nexport type {\n\tConnectContext,\n\tConnection,\n\tDisconnectContext,\n\tMessageContext,\n\tRouteKind,\n\tTestCallOverrides,\n\tWebSocketRouteRequest,\n\tWebSocketRouteResult,\n} from './websocket/route';\nexport { WebSocketRoute, WebSocketRouteBuilder } from './websocket/route';\nexport {\n\tCLOSE,\n\ttype WebSocketServerOptions,\n\tWebSocketSurfaceServer,\n} from './websocket/server';\nexport {\n\tInvalidWebSocketRequest,\n\ttype RecordedBroadcast,\n\ttype RecordedClose,\n\ttype RecordedMessage,\n\ttype RecordedSend,\n\tRecordingSink,\n\ttype TestConnection,\n\ttype TestConnectRequest,\n\ttype TestDisconnectRequest,\n\ttype TestMessageRequest,\n\ttype TestMessageResponse,\n\tTestWebSocketPublisher,\n\ttype WebSocketTestSurface,\n} from './websocket/testing';\nexport {\n\ttype Delivery,\n\tMemoryTransport,\n\tRedisTransport,\n\tTransportSink,\n\ttransportFromConnectionString,\n\tUnsupportedWebSocketTransport,\n\ttype WebSocketTransport,\n} from './websocket/transport';\n\nexport interface WebSocketApiConfig<\n\tTMessages extends WebSocketMessages = NoMessages,\n> {\n\t/** The app that serves it, relative to the workspace root. */\n\tpath: string;\n\t/**\n\t * What it sends its sockets, by action — each with the schema its `data`\n\t * is checked by before it is sent.\n\t *\n\t * ```ts\n\t * messages: {\n\t * announcement: z.object({ text: z.string() }),\n\t * 'chat.said': z.object({ from: z.string(), text: z.string() }),\n\t * }\n\t * ```\n\t *\n\t * The publisher is typed by it — `services.realtime.broadcast(\n\t * 'announcement', { text })` — in an endpoint and in a route's `sockets`\n\t * alike. Absent, any action and any data go, unchecked.\n\t */\n\tmessages?: TMessages;\n\t/**\n\t * The shape its frames take. Absent, `{ \"action\": …, \"id\"?: …, \"data\": … }`.\n\t *\n\t * With a `discriminator`, frames are flat — the action under that key and\n\t * the data's fields beside it, both ways, `$error` replies included:\n\t *\n\t * ```ts\n\t * frame: { discriminator: 'type' },\n\t * // realtime.send(ids, 'chat.message.created', { chatId, message })\n\t * // wire: {\"type\":\"chat.message.created\",\"chatId\":\"…\",\"message\":{…}}\n\t * ```\n\t *\n\t * Every message must then be an object schema that has no field of that\n\t * name; one that is not is refused when the surface is built. A flat frame\n\t * carries no `id`: every other field is the data.\n\t */\n\tframe?: WebSocketFrame;\n\t/** The label it answers on. Absent, its id kebab-cased. */\n\tsubdomain?: string;\n\t/** How many processes serve it on one machine. Default 1. */\n\treplicas?: number;\n\tlogger?: Logger;\n\tenvParser?: EnvironmentParser<{}>;\n\ttelemetry?: Telemetry;\n\t/** Seconds between pings; a socket that misses one is dropped. Default 30. */\n\theartbeat?: number;\n\t/** The largest frame accepted, in bytes. Default 1 MiB. */\n\tmaxPayload?: number;\n}\n\n/** A replica count that is not a whole number of at least one. */\nexport class InvalidReplicaCount extends Error {\n\tconstructor(\n\t\treadonly id: string,\n\t\treadonly replicas: number,\n\t) {\n\t\tsuper(\n\t\t\t`${id} asks for ${replicas} replicas. A surface runs on at least one process — give a whole number of 1 or more.`,\n\t\t);\n\t\tthis.name = 'InvalidReplicaCount';\n\t}\n}\n\nexport class WebSocketApi<\n\tTName extends string = string,\n\tTMessages extends WebSocketMessages = NoMessages,\n> implements Declarable<TName>\n{\n\treadonly id: TName;\n\n\treadonly keys: {\n\t\turl: string;\n\t\ttrustedOrigins: string;\n\t\tpublisherConnectionString: string;\n\t};\n\n\treadonly logger: Logger;\n\treadonly envParser: EnvironmentParser<{}>;\n\treadonly telemetry?: Telemetry;\n\t/**\n\t * The shape its frames take — `{ action, data }`, or flat under\n\t * `discriminator`. What a client of the surface decodes by.\n\t */\n\treadonly frame: { readonly discriminator?: string };\n\n\t/**\n\t * The surface as a dependency: `services.<id>` is its publisher, so an\n\t * endpoint sends to a socket the way a route beside it does.\n\t */\n\treadonly service: Service<Uncapitalize<TName>, WebSocketPublisher<TMessages>>;\n\n\tconstructor(\n\t\tid: ConstructName<TName>,\n\t\tprivate readonly config: WebSocketApiConfig<TMessages>,\n\t\t/** Internal: how `.auth()` carries the authenticator into its copy. */\n\t\treadonly authenticator?: Authenticator,\n\t) {\n\t\tconst canonical = canonicalId(id as string);\n\t\tthis.id = canonical as TName;\n\n\t\tconst replicas = config.replicas ?? 1;\n\t\tif (!Number.isInteger(replicas) || replicas < 1) {\n\t\t\tthrow new InvalidReplicaCount(canonical, replicas);\n\t\t}\n\n\t\tconst frame = new FrameShape(canonical, config.frame?.discriminator);\n\t\tif (config.messages) frame.check(config.messages);\n\t\tthis.frame = config.frame\n\t\t\t? { discriminator: config.frame.discriminator }\n\t\t\t: {};\n\n\t\tthis.keys = {\n\t\t\turl: provideKey(canonical, 'url'),\n\t\t\ttrustedOrigins: provideKey(canonical, 'trustedOrigins'),\n\t\t\tpublisherConnectionString: provideKey(\n\t\t\t\tcanonical,\n\t\t\t\t'publisherConnectionString',\n\t\t\t),\n\t\t};\n\t\tthis.logger = config.logger ?? DEFAULT_LOGGER;\n\t\tthis.telemetry = config.telemetry;\n\t\tthis.envParser = envParserFor(\n\t\t\tconfig.envParser\n\t\t\t\t? { id: canonical, envParser: config.envParser }\n\t\t\t\t: undefined,\n\t\t);\n\n\t\tconst envVar = this.keys.publisherConnectionString;\n\t\tconst channel = channelOf(canonical);\n\t\tconst declared = this.declared;\n\t\tthis.service = {\n\t\t\tserviceName: serviceKey(canonical) as Uncapitalize<TName>,\n\t\t\tasync register({ envParser }) {\n\t\t\t\tconst { connectionString } = envParser\n\t\t\t\t\t.create((get) => ({ connectionString: get(envVar).string() }))\n\t\t\t\t\t.parse();\n\t\t\t\tconst transport = await transportFromConnectionString(\n\t\t\t\t\tconnectionString,\n\t\t\t\t\tchannel,\n\t\t\t\t);\n\t\t\t\tonShutdown(() => transport.close());\n\t\t\t\treturn new WebSocketPublisher<TMessages>(\n\t\t\t\t\tnew TransportSink(transport),\n\t\t\t\t\tdeclared,\n\t\t\t\t\tframe,\n\t\t\t\t);\n\t\t\t},\n\t\t};\n\t}\n\n\t/** The handler a connection's upgrade runs: refuse it, or say who it is. */\n\tconnect(): WebSocketRouteBuilder<'connect', undefined, [], TMessages> {\n\t\treturn new WebSocketRouteBuilder('connect', '$connect', this);\n\t}\n\n\t/** The handler a closed connection runs. */\n\tdisconnect(): WebSocketRouteBuilder<'disconnect', undefined, [], TMessages> {\n\t\treturn new WebSocketRouteBuilder('disconnect', '$disconnect', this);\n\t}\n\n\t/**\n\t * The handler for frames whose `action` — or, for flat frames, whose\n\t * discriminator — is `action`. `$default` answers\n\t * any action nothing else does.\n\t */\n\troute(\n\t\taction: string,\n\t): WebSocketRouteBuilder<'message', undefined, [], TMessages> {\n\t\treturn new WebSocketRouteBuilder('message', action, this);\n\t}\n\n\t/** What authenticates a connection — its session reaches `connect()`. */\n\tauth(construct: Authenticator): WebSocketApi<TName, TMessages> {\n\t\treturn new WebSocketApi<TName, TMessages>(\n\t\t\tthis.id as ConstructName<TName>,\n\t\t\tthis.config,\n\t\t\tconstruct,\n\t\t);\n\t}\n\n\t/**\n\t * Serve it: the routes exported by `modules` that were built from this\n\t * surface, on whatever HTTP server `attach` is handed.\n\t *\n\t * `app` answers plain HTTP — the generated entry puts `/health` in front\n\t * of it — and `attach` takes over the server's upgrades. The sockets are\n\t * closed with 1012 when the server shuts down.\n\t */\n\tasync server(\n\t\toptions: ServiceRegisterOptions & { modules?: readonly object[] },\n\t): Promise<{\n\t\tapp: Hono;\n\t\tattach(server: Server): void;\n\t\t/** Close every socket with 1012, so the HTTP server can close. */\n\t\trelease(): Promise<void>;\n\t\tserver: WebSocketSurfaceServer<TMessages>;\n\t}> {\n\t\tconst { Hono } = await import('hono');\n\n\t\tconst { connectionString, origins, url } = options.envParser\n\t\t\t.create((get) => ({\n\t\t\t\tconnectionString: get(this.keys.publisherConnectionString)\n\t\t\t\t\t.string()\n\t\t\t\t\t// One process with nobody else sending: the sockets and the\n\t\t\t\t\t// routes meet in memory.\n\t\t\t\t\t.default(`memory://${channelOf(this.id)}`),\n\t\t\t\torigins: get(this.keys.trustedOrigins)\n\t\t\t\t\t.string()\n\t\t\t\t\t.default('')\n\t\t\t\t\t.transform((value: string) =>\n\t\t\t\t\t\tvalue\n\t\t\t\t\t\t\t.split(',')\n\t\t\t\t\t\t\t.map((origin) => origin.trim())\n\t\t\t\t\t\t\t.filter(Boolean),\n\t\t\t\t\t),\n\t\t\t\t// Its own address: a native client sends that origin.\n\t\t\t\turl: get(this.keys.url).string().optional(),\n\t\t\t}))\n\t\t\t.parse();\n\n\t\tconst server = await WebSocketSurfaceServer.start<TMessages>({\n\t\t\tcore: (sink) =>\n\t\t\t\tthis.core({\n\t\t\t\t\tenvParser: options.envParser,\n\t\t\t\t\tsink,\n\t\t\t\t\t...(options.modules ? { modules: options.modules } : {}),\n\t\t\t\t}),\n\t\t\ttransport: await transportFromConnectionString(\n\t\t\t\tconnectionString,\n\t\t\t\tchannelOf(this.id),\n\t\t\t),\n\t\t\ttrustedOrigins: origins,\n\t\t\t...(url ? { url } : {}),\n\t\t\t...(this.config.heartbeat\n\t\t\t\t? { heartbeatMs: this.config.heartbeat * 1000 }\n\t\t\t\t: {}),\n\t\t\t...(this.config.maxPayload ? { maxPayload: this.config.maxPayload } : {}),\n\t\t});\n\t\tonShutdown(() => server.close());\n\n\t\tconst app = new Hono();\n\t\t// Its own, so a process with nothing in front of it — `gkm dev`'s —\n\t\t// answers a probe too. A production entry puts one before it anyway.\n\t\tapp.get('/health', (c) =>\n\t\t\tc.json({ status: 'ok', connections: server.size }),\n\t\t);\n\t\tapp.get('/', (c) =>\n\t\t\tc.json({ surface: this.id, connections: server.size }, 426, {\n\t\t\t\tUpgrade: 'websocket',\n\t\t\t}),\n\t\t);\n\n\t\treturn {\n\t\t\tapp,\n\t\t\tattach: (http) => server.attach(http),\n\t\t\trelease: () => server.close(),\n\t\t\tserver,\n\t\t};\n\t}\n\n\t/**\n\t * The surface with no socket in it — what every runtime serves. The\n\t * routes exported by `modules` that were built from this surface answer\n\t * its frames; `sink` is where its handlers' `sockets` send.\n\t *\n\t * `server()` is the Node adaptor over it. Another runtime (a Lambda\n\t * behind API Gateway, a test) builds one with a sink of its own and\n\t * calls `connect()`, `message()` and `disconnect()` per connection id.\n\t *\n\t * @throws {DuplicateWebSocketRoute} when two routes answer one action.\n\t */\n\tcore(options: {\n\t\tenvParser: EnvironmentParser<{}>;\n\t\tsink: WebSocketSink;\n\t\tmodules?: readonly object[];\n\t}): WebSocketCore<TMessages> {\n\t\treturn new WebSocketCore<TMessages>({\n\t\t\tsurface: this.id,\n\t\t\troutes: (options.modules ?? []).flatMap((module) =>\n\t\t\t\tObject.values(module).filter(WebSocketRoute.isRoute),\n\t\t\t),\n\t\t\tsink: options.sink,\n\t\t\tenvParser: options.envParser,\n\t\t\tlogger: this.logger,\n\t\t\t...(this.config.frame ? { frame: this.config.frame } : {}),\n\t\t\t...(this.declared ? { messages: this.declared.messages } : {}),\n\t\t\t...(this.authenticator ? { authenticator: this.authenticator } : {}),\n\t\t});\n\t}\n\n\t/**\n\t * The surface's publisher over `sink` — typed, checked and encoded as\n\t * `services.<id>` is. What an adaptor with a sink of its own (MSW, a\n\t * Lambda) hands the code that sends to its connections.\n\t */\n\tpublisher(sink: WebSocketSink): WebSocketPublisher<TMessages> {\n\t\treturn new WebSocketPublisher<TMessages>(\n\t\t\tsink,\n\t\t\tthis.declared,\n\t\t\tnew FrameShape(this.id, this.config.frame?.discriminator),\n\t\t);\n\t}\n\n\t/**\n\t * A publisher of the type `services.<id>` is, that records rather than\n\t * sends — hand it to an endpoint's spec, or to a route's `request()` as\n\t * `sockets`, and assert on `sent`, `broadcasts` and `closed`.\n\t *\n\t * Every send is checked by the declared `messages` and encoded by `frame`,\n\t * as deployed: an invalid push rejects, and each record carries the\n\t * frame a client would parse.\n\t *\n\t * ```ts\n\t * const realtime = surface.testPublisher();\n\t * await sendMessage.request({ services: { realtime }, … });\n\t * expect(realtime.sent).toEqual([\n\t * { ids: ['a.1'], action: 'chat.sent', data: { text: 'hi' }, frame: … },\n\t * ]);\n\t * ```\n\t */\n\ttestPublisher(): TestWebSocketPublisher<TMessages> {\n\t\treturn new TestWebSocketPublisher<TMessages>(\n\t\t\tnew FrameShape(this.id, this.config.frame?.discriminator),\n\t\t\tthis.declared,\n\t\t);\n\t}\n\n\t/** The declared messages, with the surface they are checked for. */\n\tprivate get declared(): { surface: string; messages: TMessages } | undefined {\n\t\treturn this.config.messages\n\t\t\t? { surface: this.id, messages: this.config.messages }\n\t\t\t: undefined;\n\t}\n\n\tdeclare(): Declaration[] {\n\t\treturn [\n\t\t\t{\n\t\t\t\tkind: 'websocket-api',\n\t\t\t\tid: this.id,\n\t\t\t\tpath: this.config.path,\n\t\t\t\t...(this.config.subdomain ? { subdomain: this.config.subdomain } : {}),\n\t\t\t\t...(this.authenticator ? { auth: edgeTo(this.authenticator) } : {}),\n\t\t\t\t...(this.config.telemetry\n\t\t\t\t\t? { telemetry: this.config.telemetry.id }\n\t\t\t\t\t: {}),\n\t\t\t\t...(this.config.replicas && this.config.replicas > 1\n\t\t\t\t\t? { replicas: this.config.replicas }\n\t\t\t\t\t: {}),\n\t\t\t\tprovides: [\n\t\t\t\t\tthis.keys.url,\n\t\t\t\t\tthis.keys.trustedOrigins,\n\t\t\t\t\tthis.keys.publisherConnectionString,\n\t\t\t\t],\n\t\t\t},\n\t\t];\n\t}\n}\n\n/** The prefix a surface's channels are named under. */\nfunction channelOf(id: string): string {\n\treturn `gkm:ws:${id}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,IAAa,8BAAb,cAAiD,MAAM;CAE5C;CACA;CACA;CAHV,YACC,SACA,QACA,eACC;EACD,MACC,GAAG,QAAQ,gCAAgC,cAAc,mDAAmD,OAAO,kHACpH;EANS,KAAA,UAAA;EACA,KAAA,SAAA;EACA,KAAA,gBAAA;EAKT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,wCAAb,cAA2D,MAAM;CAEtD;CACA;CACA;CAHV,YACC,SACA,QACA,eACC;EACD,MACC,GAAG,QAAQ,MAAM,OAAO,wBAAwB,cAAc,kIAC/D;EANS,KAAA,UAAA;EACA,KAAA,SAAA;EACA,KAAA,gBAAA;EAKT,KAAK,OAAO;CACb;AACD;;AAGA,IAAa,2BAAb,cAA8C,MAAM;CAEzC;CACA;CACA;CAHV,YACC,SACA,QACA,eACC;EACD,MACC,GAAG,QAAQ,gCAAgC,cAAc,UAAU,OAAO,mGAC3E;EANS,K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OAAO,OAAO,aAAa,GACxD,KAAK,QACN;CACD;;CAGA,IAAY,WAAiE;EAC5E,OAAO,KAAK,OAAO,WAChB;GAAE,SAAS,KAAK;GAAI,UAAU,KAAK,OAAO;EAAS,IACnD,KAAA;CACJ;CAEA,UAAyB;EACxB,OAAO,CACN;GACC,MAAM;GACN,IAAI,KAAK;GACT,MAAM,KAAK,OAAO;GAClB,GAAI,KAAK,OAAO,YAAY,EAAE,WAAW,KAAK,OAAO,UAAU,IAAI,CAAC;GACpE,GAAI,KAAK,gBAAgB,EAAE,MAAMC,4BAAAA,OAAO,KAAK,aAAa,EAAE,IAAI,CAAC;GACjE,GAAI,KAAK,OAAO,YACb,EAAE,WAAW,KAAK,OAAO,UAAU,GAAG,IACtC,CAAC;GACJ,GAAI,KAAK,OAAO,YAAY,KAAK,OAAO,WAAW,IAChD,EAAE,UAAU,KAAK,OAAO,SAAS,IACjC,CAAC;GACJ,UAAU;IACT,KAAK,KAAK;IACV,KAAK,KAAK;IACV,KAAK,KAAK;GACX;EACD,CACD;CACD;AACD;;AAGA,SAAS,UAAU,IAAoB;CACtC,OAAO,UAAU;AAClB"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"websocket-api-CLnV_7CB.d.cts","names":[],"sources":["../src/websocket/frame.ts","../src/websocket/publisher.ts","../src/websocket/route.ts","../src/websocket/core.ts","../src/websocket/testing.ts","../src/websocket/transport.ts","../src/websocket/server.ts","../src/websocket-api.ts"],"mappings":";;;;;;;;;;;;;UAqBiB;;EAEhB;;;UAIgB;EAChB;;EAEA;EACA;;;cAIY,oCAAoC;WAEtC;WACA;WACA;EAHV,YACU,iBACA,gBACA;;;cAUE,8CAA8C;WAEhD;WACA;WACA;EAHV,YACU,iBACA,gBACA;;;cAUE,iCAAiC;WAEnC;WACA;WACA;EAHV,YACU,iBACA,gBACA;;;cAUE,sCAAsC;WAExC;WACA;WACA;EAHV,YACU,iBACA,gBACA;;;cAUE;WAEF;;WAEA;EAHV,YACU,iBAEA;;EA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AAM,SACJ;UAyBK;;UA2BA;;UAaA;;UAwBA;;;;;;EAiBF,MACL,eACA,kBACE;;;;UC5Ha,mBAChB,kBAAkB,oBAAoB;;EAGtC;;;;;;;;;;;;;;;;EAgBA,WAAW;;;;;;;;;;;;;;;;;EAiBX,QAAQ;;EAER;;EAEA;EACA,SAAS;EACT,YAAY;EACZ,YAAY;;EAEZ;;EAEA;;;cAIY,4BAA4B;WAE9B;WACA;EAFV,YACU,YACA;;cASE,aACZ,+BACA,kBAAkB,oBAAoB,uBAC1B,WAAW;mBA2BL;;WAER,gBAAgB;WA3BjB,IAAI;WAEJ;IACR;IACA;IACA;;WAGQ,QAAQ;WACR,WAAW;WACX,YAAY;;;;;WAKZ;aAAkB;;;;;;WAMlB,SAAS,QAAQ,aAAa,QAAQ,mBAAmB;EAElE,YACC,IAAI,cAAc,QACD,QAAQ,mBAAmB,YAEnC;;EAAA,gBAAgB;;EAwD1B,WAAW,gDAAgD;;EAK3D,cAAc,mDAAmD;;;;;;EASjE,MACC,iBACE,gDAAgD;;EAKnD,KAAK,WAAW,gBAAgB,aAAa,OAAO;;;;;;;;;EAgB9C,OACL,SAAS;IAA2B;MAClC;IACF,KAAK;IACL,OAAO,QAAQ;;IAEf,WAAW;IACX,QAAQ,uBAAuB;;;;;;;;;;;;;EA4EhC,KAAK;IACJ,WAAW;IACX,MAAM;IACN;MACG,cAAc;;;;;;EAoBlB,UAAU,MAAM,gBAAgB,mBAAmB;;;;;;;;;;;;;;;;;;EAyBnD,iBAAiB,uBAAuB;;cAQ5B;EAMZ,WAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"websocket-api-DSWDhZph.d.mts","names":[],"sources":["../src/websocket/frame.ts","../src/websocket/publisher.ts","../src/websocket/route.ts","../src/websocket/core.ts","../src/websocket/testing.ts","../src/websocket/transport.ts","../src/websocket/server.ts","../src/websocket-api.ts"],"mappings":";;;;;;;;;;;;;UAqBiB;;EAEhB;;;UAIgB;EAChB;;EAEA;EACA;;;cA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