@burdenoff/be-sdk 2026.1110.2 → 2026.1110.4

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 (497) hide show
  1. package/configs/eslint/index.js +1 -1
  2. package/configs/tsconfig/tsconfig.json +1 -1
  3. package/dist/EventQueueFactory-9NGZV9jl.js +1457 -0
  4. package/dist/EventQueueFactory-9NGZV9jl.js.map +1 -0
  5. package/dist/RedisStreamsConnection-CY8WySJy.js +283 -0
  6. package/dist/RedisStreamsConnection-CY8WySJy.js.map +1 -0
  7. package/dist/activity/index.d.ts +165 -0
  8. package/dist/activity/index.js +389 -0
  9. package/dist/activity/index.js.map +1 -0
  10. package/dist/ai-credits/index.d.ts +2 -3
  11. package/dist/ai-credits/index.js +3 -4
  12. package/dist/ai-credits/index.js.map +1 -1
  13. package/dist/ai-credits-xxfwGpHS.js +546 -0
  14. package/dist/ai-credits-xxfwGpHS.js.map +1 -0
  15. package/dist/{assistant-session-CJZhF4D6.d.ts → assistant-session-DA5ZKJOr.d.ts} +4 -5
  16. package/dist/auth/index.d.ts +2 -77
  17. package/dist/auth/index.js +3 -7
  18. package/dist/auth/index.js.map +1 -1
  19. package/dist/auth-C5ctwSLp.js +228 -0
  20. package/dist/auth-C5ctwSLp.js.map +1 -0
  21. package/dist/bootstrap/index.d.ts +74 -0
  22. package/dist/bootstrap/index.js +282 -0
  23. package/dist/bootstrap/index.js.map +1 -0
  24. package/dist/cache/index.d.ts +2 -3
  25. package/dist/cache/index.js +3 -7
  26. package/dist/cache/index.js.map +1 -1
  27. package/dist/cache-CU0uLwcS.js +1837 -0
  28. package/dist/cache-CU0uLwcS.js.map +1 -0
  29. package/dist/captcha/index.d.ts +2 -1
  30. package/dist/captcha/index.js +3 -3
  31. package/dist/captcha/index.js.map +1 -1
  32. package/dist/captcha-BT7yh1YS.js +77 -0
  33. package/dist/captcha-BT7yh1YS.js.map +1 -0
  34. package/dist/client/internal-client.d.ts +4 -7
  35. package/dist/client/internal-client.js +172 -4
  36. package/dist/client/internal-client.js.map +1 -1
  37. package/dist/client-BgAEvDC2.d.ts +86 -0
  38. package/dist/client-sAJTrb4i.js +565 -0
  39. package/dist/client-sAJTrb4i.js.map +1 -0
  40. package/dist/collector-endpoint-iyQYeI50.js +50 -0
  41. package/dist/collector-endpoint-iyQYeI50.js.map +1 -0
  42. package/dist/context/index.d.ts +35 -0
  43. package/dist/context/index.js +283 -0
  44. package/dist/context/index.js.map +1 -0
  45. package/dist/crypto/index.d.ts +2 -1
  46. package/dist/crypto/index.js +3 -3
  47. package/dist/crypto/index.js.map +1 -1
  48. package/dist/crypto-DO9fM0FO.js +145 -0
  49. package/dist/crypto-DO9fM0FO.js.map +1 -0
  50. package/dist/database/index.d.ts +104 -108
  51. package/dist/database/index.js +468 -6
  52. package/dist/database/index.js.map +1 -1
  53. package/dist/dataloader/index.d.ts +2 -1
  54. package/dist/dataloader/index.js +3 -3
  55. package/dist/dataloader/index.js.map +1 -1
  56. package/dist/dataloader-DwpT3YoS.js +294 -0
  57. package/dist/dataloader-DwpT3YoS.js.map +1 -0
  58. package/dist/deployed-environment-p_Tdl3sT.js +38 -0
  59. package/dist/deployed-environment-p_Tdl3sT.js.map +1 -0
  60. package/dist/dist-BGKdXVy3.js +1718 -0
  61. package/dist/dist-BGKdXVy3.js.map +1 -0
  62. package/dist/env-DdaoGjIt.js +74 -0
  63. package/dist/env-DdaoGjIt.js.map +1 -0
  64. package/dist/event-queue/index.d.ts +2 -7
  65. package/dist/event-queue/index.js +7 -9
  66. package/dist/event-queue/index.js.map +1 -1
  67. package/dist/event-queue-Cw-YJPY_.js +1384 -0
  68. package/dist/event-queue-Cw-YJPY_.js.map +1 -0
  69. package/dist/{explicit-activity-scope-CCoxVwAr.d.ts → explicit-activity-scope-D8VeGGpt.d.ts} +1 -2
  70. package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
  71. package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
  72. package/dist/export/index.d.ts +2 -2
  73. package/dist/export/index.js +3 -14
  74. package/dist/export/index.js.map +1 -1
  75. package/dist/export-DJXE3Osa.js +642 -0
  76. package/dist/export-DJXE3Osa.js.map +1 -0
  77. package/dist/feature-flags/index.d.ts +2 -10
  78. package/dist/feature-flags/index.js +3 -6
  79. package/dist/feature-flags/index.js.map +1 -1
  80. package/dist/feature-flags-CP1KRgwD.js +422 -0
  81. package/dist/feature-flags-CP1KRgwD.js.map +1 -0
  82. package/dist/files/index.d.ts +2 -3
  83. package/dist/files/index.js +3 -4
  84. package/dist/files/index.js.map +1 -1
  85. package/dist/files-h5U-D2AF.js +830 -0
  86. package/dist/files-h5U-D2AF.js.map +1 -0
  87. package/dist/gateway/index.d.ts +4 -6
  88. package/dist/gateway/index.js +7 -13
  89. package/dist/gateway/index.js.map +1 -1
  90. package/dist/gateway/security/index.d.ts +2 -2
  91. package/dist/gateway/security/index.js +3 -5
  92. package/dist/gateway/security/index.js.map +1 -1
  93. package/dist/gateway-ByVo-n37.js +50 -0
  94. package/dist/gateway-ByVo-n37.js.map +1 -0
  95. package/dist/graph/index.d.ts +3 -10
  96. package/dist/graph/index.js +4 -13
  97. package/dist/graph/index.js.map +1 -1
  98. package/dist/graph-CR7u4lpl.js +2152 -0
  99. package/dist/graph-CR7u4lpl.js.map +1 -0
  100. package/dist/graph-emitter-CdOXP7Tn.js +621 -0
  101. package/dist/graph-emitter-CdOXP7Tn.js.map +1 -0
  102. package/dist/graphql/index.d.ts +3 -2
  103. package/dist/graphql/index.js +4 -6
  104. package/dist/graphql/index.js.map +1 -1
  105. package/dist/graphql/services/index.d.ts +2 -24
  106. package/dist/graphql/services/index.js +3 -4
  107. package/dist/graphql/services/index.js.map +1 -1
  108. package/dist/graphql-CUDyhibV.d.ts +21 -0
  109. package/dist/graphql-DHAHHcww.js +161 -0
  110. package/dist/graphql-DHAHHcww.js.map +1 -0
  111. package/dist/i18n/index.d.ts +3 -3
  112. package/dist/i18n/index.js +3 -4
  113. package/dist/i18n/index.js.map +1 -1
  114. package/dist/i18n-BBMYFd0P.js +860 -0
  115. package/dist/i18n-BBMYFd0P.js.map +1 -0
  116. package/dist/import-optional-peer-B82VYxeX.js +18 -0
  117. package/dist/import-optional-peer-B82VYxeX.js.map +1 -0
  118. package/dist/index-3KOZ1zN9.d.ts +233 -0
  119. package/dist/index-ADmsX0BI.d.ts +646 -0
  120. package/dist/index-B2LCaK0R.d.ts +500 -0
  121. package/dist/index-BBqooJ52.d.ts +45 -0
  122. package/dist/index-BGzMYJsm.d.ts +209 -0
  123. package/dist/index-BMIMnp6T.d.ts +8 -0
  124. package/dist/index-BVOL7458.d.ts +10 -0
  125. package/dist/index-BcqQs-Uq.d.ts +69 -0
  126. package/dist/index-BeVtqGO-.d.ts +208 -0
  127. package/dist/index-BiTzGUZP.d.ts +114 -0
  128. package/dist/index-C0qLquY0.d.ts +150 -0
  129. package/dist/index-C5uEKchX.d.ts +60 -0
  130. package/dist/index-CDOqxSIi.d.ts +37 -0
  131. package/dist/index-CG6wj66Y.d.ts +148 -0
  132. package/dist/index-CHwMhK6v.d.ts +63 -0
  133. package/dist/index-CIgoeobA.d.ts +145 -0
  134. package/dist/index-CPQDMSFS.d.ts +103 -0
  135. package/dist/index-CSRcgkVi.d.ts +23 -0
  136. package/dist/index-CTTwo9av.d.ts +102 -0
  137. package/dist/index-CVCyKzhB.d.ts +207 -0
  138. package/dist/index-C_GXXF32.d.ts +704 -0
  139. package/dist/index-CaM9JUcc.d.ts +144 -0
  140. package/dist/index-CliOgq6L.d.ts +203 -0
  141. package/dist/index-Cot73bdh.d.ts +63 -0
  142. package/dist/index-DGgh9DWn.d.ts +59 -0
  143. package/dist/index-DY3dNhMN.d.ts +420 -0
  144. package/dist/index-DqbGqfAy.d.ts +127 -0
  145. package/dist/index-Dt1HJPTX.d.ts +12 -0
  146. package/dist/index-DtI6aBtB.d.ts +22 -0
  147. package/dist/index-FKohsiex.d.ts +38 -0
  148. package/dist/index-FRRaa6h2.d.ts +999 -0
  149. package/dist/index-FbXPfen7.d.ts +132 -0
  150. package/dist/index-MArCb8Aq.d.ts +306 -0
  151. package/dist/index-U_tu3zUl.d.ts +303 -0
  152. package/dist/index-YOShAwkq.d.ts +45 -0
  153. package/dist/index-cmR9k9ga.d.ts +26 -0
  154. package/dist/index-yBSjMY32.d.ts +24 -0
  155. package/dist/index-zd_NPGJo.d.ts +206 -0
  156. package/dist/index.d.ts +106 -609
  157. package/dist/index.js +769 -2590
  158. package/dist/index.js.map +1 -1
  159. package/dist/init/index.d.ts +2 -2
  160. package/dist/init/index.js +3 -16
  161. package/dist/init/index.js.map +1 -1
  162. package/dist/init-CQPFmOOe.js +325 -0
  163. package/dist/init-CQPFmOOe.js.map +1 -0
  164. package/dist/instrumentation/index.d.ts +3 -4
  165. package/dist/instrumentation/index.js +5 -5
  166. package/dist/instrumentation/index.js.map +1 -1
  167. package/dist/instrumentation-xkkmDgJ0.js +1678 -0
  168. package/dist/instrumentation-xkkmDgJ0.js.map +1 -0
  169. package/dist/lake/index.d.ts +50 -54
  170. package/dist/lake/index.js +169 -193
  171. package/dist/lake/index.js.map +1 -1
  172. package/dist/layer/index.d.ts +3 -2
  173. package/dist/layer/index.js +4 -5
  174. package/dist/layer/index.js.map +1 -1
  175. package/dist/layer-BZBZZWeV.d.ts +69 -0
  176. package/dist/layer-Bcix-WCl.js +105 -0
  177. package/dist/layer-Bcix-WCl.js.map +1 -0
  178. package/dist/layer-CEKy6cm8.js +252 -0
  179. package/dist/layer-CEKy6cm8.js.map +1 -0
  180. package/dist/lifecycle/index.d.ts +2 -1
  181. package/dist/lifecycle/index.js +3 -4
  182. package/dist/lifecycle/index.js.map +1 -1
  183. package/dist/lifecycle-DeoLSX0U.js +76 -0
  184. package/dist/lifecycle-DeoLSX0U.js.map +1 -0
  185. package/dist/logger/index.d.ts +2 -3
  186. package/dist/logger/index.js +3 -3
  187. package/dist/logger/index.js.map +1 -1
  188. package/dist/logger-B6rCpb7D.js +290 -0
  189. package/dist/logger-B6rCpb7D.js.map +1 -0
  190. package/dist/metrics/index.d.ts +13 -14
  191. package/dist/metrics/index.js +3 -4
  192. package/dist/metrics/index.js.map +1 -1
  193. package/dist/metrics-BrLwNUrb.js +52 -0
  194. package/dist/metrics-BrLwNUrb.js.map +1 -0
  195. package/dist/metrics-collector-C2eShrlW.js +922 -0
  196. package/dist/metrics-collector-C2eShrlW.js.map +1 -0
  197. package/dist/middleware/index.d.ts +3 -3
  198. package/dist/middleware/index.js +3 -4
  199. package/dist/middleware/index.js.map +1 -1
  200. package/dist/middleware-CUxJVUpD.js +1243 -0
  201. package/dist/middleware-CUxJVUpD.js.map +1 -0
  202. package/dist/middleware-Cq0zFMGp.js +253 -0
  203. package/dist/middleware-Cq0zFMGp.js.map +1 -0
  204. package/dist/notifications/index.d.ts +2 -5
  205. package/dist/notifications/index.js +3 -6
  206. package/dist/notifications/index.js.map +1 -1
  207. package/dist/notifications-DY_i37WN.js +869 -0
  208. package/dist/notifications-DY_i37WN.js.map +1 -0
  209. package/dist/observability/index.d.ts +2 -3
  210. package/dist/observability/index.js +3 -4
  211. package/dist/observability/index.js.map +1 -1
  212. package/dist/observability-DBDXipTU.js +272 -0
  213. package/dist/observability-DBDXipTU.js.map +1 -0
  214. package/dist/payments/index.d.ts +144 -0
  215. package/dist/payments/index.js +404 -0
  216. package/dist/payments/index.js.map +1 -0
  217. package/dist/platform/index.d.ts +2 -1
  218. package/dist/platform/index.js +3 -5
  219. package/dist/platform/index.js.map +1 -1
  220. package/dist/platform-DZwczW7v.js +1510 -0
  221. package/dist/platform-DZwczW7v.js.map +1 -0
  222. package/dist/prisma/generator/index.d.ts +1 -1
  223. package/dist/prisma/generator/index.js +97 -84
  224. package/dist/prisma/generator/index.js.map +1 -1
  225. package/dist/prisma/index.d.ts +4 -7
  226. package/dist/prisma/index.js +5 -12
  227. package/dist/prisma/index.js.map +1 -1
  228. package/dist/prisma-BzOOdt79.js +863 -0
  229. package/dist/prisma-BzOOdt79.js.map +1 -0
  230. package/dist/prisma-extension-Cfl09swM.d.ts +172 -0
  231. package/dist/product-alias/index.d.ts +2 -1
  232. package/dist/product-alias/index.js +3 -3
  233. package/dist/product-alias/index.js.map +1 -1
  234. package/dist/product-alias-BPqtskMq.js +273 -0
  235. package/dist/product-alias-BPqtskMq.js.map +1 -0
  236. package/dist/rate-limit-CBrK_U5H.js +142 -0
  237. package/dist/rate-limit-CBrK_U5H.js.map +1 -0
  238. package/dist/rbac/index.d.ts +2 -122
  239. package/dist/rbac/index.js +3 -6
  240. package/dist/rbac/index.js.map +1 -1
  241. package/dist/rbac-Dvz0YzEt.js +1486 -0
  242. package/dist/rbac-Dvz0YzEt.js.map +1 -0
  243. package/dist/resource-caps/index.d.ts +66 -72
  244. package/dist/resource-caps/index.js +430 -5
  245. package/dist/resource-caps/index.js.map +1 -1
  246. package/dist/rolldown-runtime-ad2WFvuA.js +17 -0
  247. package/dist/sdk-Dju9o-sq.js +124 -0
  248. package/dist/sdk-Dju9o-sq.js.map +1 -0
  249. package/dist/search/index.d.ts +112 -0
  250. package/dist/search/index.js +266 -0
  251. package/dist/search/index.js.map +1 -0
  252. package/dist/security/index.d.ts +2 -0
  253. package/dist/security/index.js +4 -0
  254. package/dist/security/index.js.map +1 -0
  255. package/dist/security/rate-limit/index.d.ts +2 -0
  256. package/dist/security/rate-limit/index.js +4 -0
  257. package/dist/security/rate-limit/index.js.map +1 -0
  258. package/dist/security-DIG-95Ic.js +1647 -0
  259. package/dist/security-DIG-95Ic.js.map +1 -0
  260. package/dist/server/index.d.ts +7 -164
  261. package/dist/server/index.js +2001 -1507
  262. package/dist/server/index.js.map +1 -1
  263. package/dist/service-jwt-Bu-WNA_-.js +80 -0
  264. package/dist/service-jwt-Bu-WNA_-.js.map +1 -0
  265. package/dist/services-BWzfz7vG.js +102 -0
  266. package/dist/services-BWzfz7vG.js.map +1 -0
  267. package/dist/sharding/index.d.ts +41 -44
  268. package/dist/sharding/index.js +156 -137
  269. package/dist/sharding/index.js.map +1 -1
  270. package/dist/sharing/index.d.ts +2 -1
  271. package/dist/sharing/index.js +3 -4
  272. package/dist/sharing/index.js.map +1 -1
  273. package/dist/sharing-CflDsSJ-.js +911 -0
  274. package/dist/sharing-CflDsSJ-.js.map +1 -0
  275. package/dist/stub-BUnfMiAS.js +577 -0
  276. package/dist/stub-BUnfMiAS.js.map +1 -0
  277. package/dist/tags/index.d.ts +2 -3
  278. package/dist/tags/index.js +3 -4
  279. package/dist/tags/index.js.map +1 -1
  280. package/dist/tags-CbijgoqR.js +868 -0
  281. package/dist/{chunk-PBZFAAOM.js.map → tags-CbijgoqR.js.map} +1 -1
  282. package/dist/telemetry/index.d.ts +64 -76
  283. package/dist/telemetry/index.js +369 -201
  284. package/dist/telemetry/index.js.map +1 -1
  285. package/dist/temporal/index.d.ts +2 -148
  286. package/dist/temporal/index.js +3 -5
  287. package/dist/temporal/index.js.map +1 -1
  288. package/dist/temporal-B534uYK8.js +706 -0
  289. package/dist/temporal-B534uYK8.js.map +1 -0
  290. package/dist/tracker/index.d.ts +5 -11
  291. package/dist/tracker/index.js +7 -20
  292. package/dist/tracker/index.js.map +1 -1
  293. package/dist/tracker-PQztSlhJ.js +458 -0
  294. package/dist/tracker-PQztSlhJ.js.map +1 -0
  295. package/dist/translation/index.d.ts +120 -0
  296. package/dist/translation/index.js +573 -0
  297. package/dist/translation/index.js.map +1 -0
  298. package/dist/types/index.d.ts +3 -0
  299. package/dist/types/index.js +90 -0
  300. package/dist/types/index.js.map +1 -0
  301. package/dist/types-BYMYND1L.js +44 -0
  302. package/dist/types-BYMYND1L.js.map +1 -0
  303. package/dist/types-C6EKaS3V.d.ts +106 -0
  304. package/dist/types-CWybW61E.d.ts +323 -0
  305. package/dist/types-C_yfu3XK.d.ts +34 -0
  306. package/dist/types-DgaQqvxo.d.ts +70 -0
  307. package/dist/usage/index.d.ts +2 -213
  308. package/dist/usage/index.js +3 -15
  309. package/dist/usage/index.js.map +1 -1
  310. package/dist/usage-BRqVP3CJ.js +682 -0
  311. package/dist/usage-BRqVP3CJ.js.map +1 -0
  312. package/dist/utils/index.d.ts +2 -1
  313. package/dist/utils/index.js +3 -3
  314. package/dist/utils/index.js.map +1 -1
  315. package/dist/utils-DL85Tnbn.js +500 -0
  316. package/dist/utils-DL85Tnbn.js.map +1 -0
  317. package/dist/validation/index.d.ts +2 -2
  318. package/dist/validation/index.js +3 -3
  319. package/dist/validation/index.js.map +1 -1
  320. package/dist/validation-CPUITdMk.js +762 -0
  321. package/dist/validation-CPUITdMk.js.map +1 -0
  322. package/dist/workspace-extension-COrC0dYi.js +979 -0
  323. package/dist/workspace-extension-COrC0dYi.js.map +1 -0
  324. package/dist/{workspace-extension-BGwTOV_r.d.ts → workspace-extension-DTFTdGVF.d.ts} +43 -45
  325. package/package.json +7 -10
  326. package/dist/EventQueueFactory-GXC3A7DH.js +0 -8
  327. package/dist/EventQueueFactory-GXC3A7DH.js.map +0 -1
  328. package/dist/chunk-4XIBXZ6J.js +0 -276
  329. package/dist/chunk-4XIBXZ6J.js.map +0 -1
  330. package/dist/chunk-554Z4C2K.js +0 -1006
  331. package/dist/chunk-554Z4C2K.js.map +0 -1
  332. package/dist/chunk-5CAFHK2Z.js +0 -107
  333. package/dist/chunk-5CAFHK2Z.js.map +0 -1
  334. package/dist/chunk-63ZXJ42X.js +0 -451
  335. package/dist/chunk-63ZXJ42X.js.map +0 -1
  336. package/dist/chunk-6XEXJATV.js +0 -304
  337. package/dist/chunk-6XEXJATV.js.map +0 -1
  338. package/dist/chunk-726AR6Q7.js +0 -1532
  339. package/dist/chunk-726AR6Q7.js.map +0 -1
  340. package/dist/chunk-A5F6Z5UE.js +0 -21
  341. package/dist/chunk-A5F6Z5UE.js.map +0 -1
  342. package/dist/chunk-A6DE32ZS.js +0 -1507
  343. package/dist/chunk-A6DE32ZS.js.map +0 -1
  344. package/dist/chunk-AXJDGQPE.js +0 -690
  345. package/dist/chunk-AXJDGQPE.js.map +0 -1
  346. package/dist/chunk-BJQOGOVW.js +0 -602
  347. package/dist/chunk-BJQOGOVW.js.map +0 -1
  348. package/dist/chunk-CFXWH2IS.js +0 -52
  349. package/dist/chunk-CFXWH2IS.js.map +0 -1
  350. package/dist/chunk-DRWH5XCJ.js +0 -876
  351. package/dist/chunk-DRWH5XCJ.js.map +0 -1
  352. package/dist/chunk-E4QNLVY4.js +0 -909
  353. package/dist/chunk-E4QNLVY4.js.map +0 -1
  354. package/dist/chunk-EBDHIL7V.js +0 -774
  355. package/dist/chunk-EBDHIL7V.js.map +0 -1
  356. package/dist/chunk-ELU7VL3E.js +0 -245
  357. package/dist/chunk-ELU7VL3E.js.map +0 -1
  358. package/dist/chunk-FZRODKIN.js +0 -31
  359. package/dist/chunk-FZRODKIN.js.map +0 -1
  360. package/dist/chunk-GCIB76AJ.js +0 -882
  361. package/dist/chunk-GCIB76AJ.js.map +0 -1
  362. package/dist/chunk-HC6MPUIH.js +0 -1571
  363. package/dist/chunk-HC6MPUIH.js.map +0 -1
  364. package/dist/chunk-HNMHPSAM.js +0 -272
  365. package/dist/chunk-HNMHPSAM.js.map +0 -1
  366. package/dist/chunk-HTLEGD3Q.js +0 -1480
  367. package/dist/chunk-HTLEGD3Q.js.map +0 -1
  368. package/dist/chunk-I3KOWRT3.js +0 -89
  369. package/dist/chunk-I3KOWRT3.js.map +0 -1
  370. package/dist/chunk-ID3WR4JS.js +0 -509
  371. package/dist/chunk-ID3WR4JS.js.map +0 -1
  372. package/dist/chunk-JS52ZHTK.js +0 -1346
  373. package/dist/chunk-JS52ZHTK.js.map +0 -1
  374. package/dist/chunk-JVMAQOA3.js +0 -521
  375. package/dist/chunk-JVMAQOA3.js.map +0 -1
  376. package/dist/chunk-KH4TRQCO.js +0 -1063
  377. package/dist/chunk-KH4TRQCO.js.map +0 -1
  378. package/dist/chunk-KJOSPVB2.js +0 -57
  379. package/dist/chunk-KJOSPVB2.js.map +0 -1
  380. package/dist/chunk-KO2ZXZ7W.js +0 -61
  381. package/dist/chunk-KO2ZXZ7W.js.map +0 -1
  382. package/dist/chunk-KS2HQCJR.js +0 -56
  383. package/dist/chunk-KS2HQCJR.js.map +0 -1
  384. package/dist/chunk-LA5KPWZ2.js +0 -413
  385. package/dist/chunk-LA5KPWZ2.js.map +0 -1
  386. package/dist/chunk-MESLAC5W.js +0 -574
  387. package/dist/chunk-MESLAC5W.js.map +0 -1
  388. package/dist/chunk-MWPYA2HD.js +0 -94
  389. package/dist/chunk-MWPYA2HD.js.map +0 -1
  390. package/dist/chunk-NUB5GQTU.js +0 -270
  391. package/dist/chunk-NUB5GQTU.js.map +0 -1
  392. package/dist/chunk-OBBCR6WY.js +0 -277
  393. package/dist/chunk-OBBCR6WY.js.map +0 -1
  394. package/dist/chunk-OQDSAOG3.js +0 -1908
  395. package/dist/chunk-OQDSAOG3.js.map +0 -1
  396. package/dist/chunk-OXNCBE7P.js +0 -971
  397. package/dist/chunk-OXNCBE7P.js.map +0 -1
  398. package/dist/chunk-PBZFAAOM.js +0 -941
  399. package/dist/chunk-PN6GIF3R.js +0 -1185
  400. package/dist/chunk-PN6GIF3R.js.map +0 -1
  401. package/dist/chunk-PYD44IHJ.js +0 -728
  402. package/dist/chunk-PYD44IHJ.js.map +0 -1
  403. package/dist/chunk-QVPIACWD.js +0 -679
  404. package/dist/chunk-QVPIACWD.js.map +0 -1
  405. package/dist/chunk-QWNNFE4P.js +0 -41
  406. package/dist/chunk-QWNNFE4P.js.map +0 -1
  407. package/dist/chunk-RU266375.js +0 -327
  408. package/dist/chunk-RU266375.js.map +0 -1
  409. package/dist/chunk-RYTSVGGA.js +0 -1624
  410. package/dist/chunk-RYTSVGGA.js.map +0 -1
  411. package/dist/chunk-RZOFS2BQ.js +0 -225
  412. package/dist/chunk-RZOFS2BQ.js.map +0 -1
  413. package/dist/chunk-SBS4S2PJ.js +0 -100
  414. package/dist/chunk-SBS4S2PJ.js.map +0 -1
  415. package/dist/chunk-SPRG6G6G.js +0 -530
  416. package/dist/chunk-SPRG6G6G.js.map +0 -1
  417. package/dist/chunk-STWFX5E2.js +0 -233
  418. package/dist/chunk-STWFX5E2.js.map +0 -1
  419. package/dist/chunk-UNASM5VJ.js +0 -419
  420. package/dist/chunk-UNASM5VJ.js.map +0 -1
  421. package/dist/chunk-VAT66FJA.js +0 -245
  422. package/dist/chunk-VAT66FJA.js.map +0 -1
  423. package/dist/chunk-VFCMR5GX.js +0 -49
  424. package/dist/chunk-VFCMR5GX.js.map +0 -1
  425. package/dist/chunk-VGAHZKNJ.js +0 -66
  426. package/dist/chunk-VGAHZKNJ.js.map +0 -1
  427. package/dist/chunk-VTJTAAXC.js +0 -627
  428. package/dist/chunk-VTJTAAXC.js.map +0 -1
  429. package/dist/chunk-VXVLKRU6.js +0 -758
  430. package/dist/chunk-VXVLKRU6.js.map +0 -1
  431. package/dist/chunk-WWUU5ETI.js +0 -163
  432. package/dist/chunk-WWUU5ETI.js.map +0 -1
  433. package/dist/chunk-XE4OXN2W.js +0 -10
  434. package/dist/chunk-XE4OXN2W.js.map +0 -1
  435. package/dist/chunk-XOJORS75.js +0 -1853
  436. package/dist/chunk-XOJORS75.js.map +0 -1
  437. package/dist/chunk-YMZEUTD2.js +0 -110
  438. package/dist/chunk-YMZEUTD2.js.map +0 -1
  439. package/dist/chunk-Z77BTSOK.js +0 -617
  440. package/dist/chunk-Z77BTSOK.js.map +0 -1
  441. package/dist/chunk-ZZK3WEDI.js +0 -181
  442. package/dist/chunk-ZZK3WEDI.js.map +0 -1
  443. package/dist/client-CCXpAZ2r.d.ts +0 -89
  444. package/dist/client-DSI_760t.d.ts +0 -36
  445. package/dist/client-JU6T3UPB.js +0 -11
  446. package/dist/client-JU6T3UPB.js.map +0 -1
  447. package/dist/dist-2X4Q7PJA.js +0 -1491
  448. package/dist/dist-2X4Q7PJA.js.map +0 -1
  449. package/dist/env-4UWSUS64.js +0 -4
  450. package/dist/env-4UWSUS64.js.map +0 -1
  451. package/dist/graph-emitter-r5TylDBm.d.ts +0 -47
  452. package/dist/graphql-CMHMQjvd.d.ts +0 -23
  453. package/dist/i18n-Qm2AkPC-.d.ts +0 -33
  454. package/dist/index--yvpa6ay.d.ts +0 -83
  455. package/dist/index-4gKQKZ2B.d.ts +0 -71
  456. package/dist/index-5x0XMKXN.d.ts +0 -149
  457. package/dist/index-B70b5mYS.d.ts +0 -33
  458. package/dist/index-B8KrxO4j.d.ts +0 -755
  459. package/dist/index-BOuDKnqD.d.ts +0 -201
  460. package/dist/index-BTMt4OjA.d.ts +0 -201
  461. package/dist/index-BejbszA7.d.ts +0 -39
  462. package/dist/index-BkeOYZye.d.ts +0 -198
  463. package/dist/index-BuAj5nXg.d.ts +0 -83
  464. package/dist/index-BvkVcW8I.d.ts +0 -349
  465. package/dist/index-CWmH_-RZ.d.ts +0 -247
  466. package/dist/index-CbgWNcus.d.ts +0 -258
  467. package/dist/index-CmfPeQza.d.ts +0 -166
  468. package/dist/index-CmpG-zak.d.ts +0 -607
  469. package/dist/index-CoMKgL-p.d.ts +0 -12
  470. package/dist/index-D8HGwglK.d.ts +0 -541
  471. package/dist/index-DCaVm66D.d.ts +0 -1101
  472. package/dist/index-DE2w7E0d.d.ts +0 -83
  473. package/dist/index-DSOpj8DI.d.ts +0 -17
  474. package/dist/index-DW9q22GH.d.ts +0 -75
  475. package/dist/index-DnjJ9CwI.d.ts +0 -347
  476. package/dist/index-DwMJZ8PP.d.ts +0 -317
  477. package/dist/index-PaojfSdd.d.ts +0 -71
  478. package/dist/index-aHtYvc3i.d.ts +0 -284
  479. package/dist/index-e_18DzAg.d.ts +0 -18
  480. package/dist/index-ffmipXSA.d.ts +0 -55
  481. package/dist/index-joONjwLt.d.ts +0 -33
  482. package/dist/index-kssw5ziY.d.ts +0 -250
  483. package/dist/index-lFffh5-G.d.ts +0 -125
  484. package/dist/index-pxYge_6k.d.ts +0 -79
  485. package/dist/layer-Cv9vSwBx.d.ts +0 -70
  486. package/dist/pino-logger-H4HPW5P6.js +0 -5
  487. package/dist/pino-logger-H4HPW5P6.js.map +0 -1
  488. package/dist/prisma-extension-gYhYriA0.d.ts +0 -174
  489. package/dist/sdk-L75WWUP3.js +0 -156
  490. package/dist/sdk-L75WWUP3.js.map +0 -1
  491. package/dist/shutdown-registry-CW9LryO8.d.ts +0 -10
  492. package/dist/types-Bo2wkjSP.d.ts +0 -35
  493. package/dist/types-DVpvrAhd.d.ts +0 -71
  494. package/dist/types-DgJ4lDYA.d.ts +0 -108
  495. package/dist/types-USOv09qy.d.ts +0 -327
  496. package/dist/workspace-guard-NXVYYBVJ.js +0 -5
  497. package/dist/workspace-guard-NXVYYBVJ.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notifications-DY_i37WN.js","names":["NotificationChannel","NotificationType"],"sources":["../src/notifications/tenant-notifications.ts","../src/notifications/index.ts"],"sourcesContent":["/**\n * Tenant-Backend Notifications Module\n * Comprehensive notification system supporting 10+ channels via tenant-backend\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { APIError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n// ========================================\n// Enums\n// ========================================\n\nexport enum NotificationChannel {\n EMAIL = 'EMAIL',\n SMS = 'SMS',\n PUSH = 'PUSH',\n IN_APP = 'IN_APP',\n WEBHOOK = 'WEBHOOK',\n WHATSAPP = 'WHATSAPP',\n TEAMS = 'TEAMS',\n SLACK = 'SLACK',\n TELEGRAM = 'TELEGRAM',\n DISCORD = 'DISCORD',\n}\n\nexport enum NotificationPriority {\n LOW = 'LOW',\n MEDIUM = 'MEDIUM',\n HIGH = 'HIGH',\n URGENT = 'URGENT',\n}\n\nexport enum NotificationType {\n TRANSACTIONAL = 'TRANSACTIONAL',\n MARKETING = 'MARKETING',\n SYSTEM = 'SYSTEM',\n ALERT = 'ALERT',\n}\n\n// ========================================\n// Types & Interfaces\n// ========================================\n\nexport interface RecipientInput {\n userId?: string;\n email?: string;\n phoneNumber?: string;\n pushToken?: string;\n whatsappNumber?: string;\n teamsUserId?: string;\n slackUserId?: string;\n webhookUrl?: string;\n name?: string;\n locale?: string;\n timezone?: string;\n}\n\nexport interface SendNotificationInput {\n recipient: RecipientInput;\n channel: NotificationChannel;\n type?: NotificationType;\n priority?: NotificationPriority;\n subject?: string;\n body: string;\n htmlBody?: string;\n data?: Record<string, unknown>;\n metadata?: Record<string, unknown>;\n scheduledFor?: Date;\n expiresAt?: Date;\n trackOpens?: boolean;\n trackClicks?: boolean;\n}\n\nexport interface SendWithTemplateInput {\n templateSlug: string;\n variables: Record<string, unknown>;\n recipient: RecipientInput;\n priority?: NotificationPriority;\n scheduledFor?: Date;\n expiresAt?: Date;\n trackOpens?: boolean;\n trackClicks?: boolean;\n /** Specific channel instance ID from channel service (takes precedence) */\n channelId?: string;\n /** Platform type for auto-failover (EMAIL, SMS, etc.) - used if channelId not provided */\n platform?: NotificationChannel;\n /** Timezone for scheduling */\n timezone?: string;\n}\n\nexport interface BatchNotificationInput {\n notifications: SendNotificationInput[];\n batchSize?: number;\n delayBetweenBatches?: number;\n priority?: NotificationPriority;\n}\n\nexport interface Notification {\n id: string;\n userId: string;\n channel: NotificationChannel;\n type: NotificationType;\n priority: NotificationPriority;\n status: string;\n deliveryStatus?: string;\n title: string;\n message: string;\n htmlMessage?: string;\n subject?: string;\n recipientEmail?: string;\n recipientPhone?: string;\n trackOpens: boolean;\n trackClicks: boolean;\n openedAt?: string;\n clickedAt?: string;\n sentAt?: string;\n deliveredAt?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface NotificationTemplate {\n id: string;\n name: string;\n slug: string;\n description?: string;\n channel: NotificationChannel;\n type: NotificationType;\n locale: string;\n subject?: string;\n bodyTemplate: string;\n htmlTemplate?: string;\n variables: Array<{\n name: string;\n type: string;\n required: boolean;\n defaultValue?: unknown;\n description?: string;\n example?: unknown;\n }>;\n enabled: boolean;\n version: number;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface NotificationStats {\n total: number;\n pending: number;\n /** @deprecated The owner does not publish a queued counter. */\n queued?: number;\n /** @deprecated The owner does not publish a processing counter. */\n processing?: number;\n triggered: number;\n scheduled: number;\n cancelled: number;\n sent: number;\n delivered: number;\n failed: number;\n byChannel: Record<string, number>;\n byType: Record<string, number>;\n}\n\n// ========================================\n// Tenant Notifications Module\n// ========================================\n\n/**\n * Tenant-Backend Notifications Module\n * Provides access to the centralized notification system\n */\nexport class TenantNotificationsModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Send a single notification\n */\n public async send(input: SendNotificationInput, context?: SDKContext): Promise<string> {\n this.validateSendInput(input);\n const notification = this.createNotificationInput(input);\n const callContext = { ...this.context, ...context };\n\n if (input.scheduledFor) {\n const response = await this.client.tenantQuery<{\n scheduleNotification: { notificationId: string; status: string };\n }>(\n `mutation ScheduleTenantNotification($input: ScheduleNotificationInput!) {\n scheduleNotification(input: $input) { notificationId status }\n }`,\n { input: { notification, scheduledFor: input.scheduledFor.toISOString(), timezone: input.recipient.timezone } },\n callContext\n );\n const result = response.scheduleNotification;\n if (!result?.notificationId || result.status !== 'PENDING') {\n throw new APIError('Notification scheduling was not acknowledged', { operation: 'scheduleNotification' });\n }\n return result.notificationId;\n }\n\n const response = await this.client.tenantQuery<{\n triggerNotification: { id: string; status: string; channel: NotificationChannel };\n }>(\n `mutation TriggerTenantNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) { id status channel }\n }`,\n { input: { notification, platform: input.channel, includeInApp: false } },\n callContext\n );\n const result = response.triggerNotification;\n if (\n !result?.id ||\n result.channel !== input.channel ||\n !['TRIGGERED', 'SENT', 'DELIVERED'].includes(result.status)\n ) {\n throw new APIError('Notification trigger was not acknowledged', {\n operation: 'triggerNotification',\n notificationId: result?.id,\n });\n }\n logger.info('[TenantNotifications] Notification accepted', {\n notificationId: result.id,\n channel: result.channel,\n status: result.status,\n });\n return result.id;\n }\n\n /** Owner input deliberately excludes scheduling, which has a separate API. */\n private createNotificationInput(input: SendNotificationInput, priority?: NotificationPriority) {\n return {\n recipient: input.recipient,\n channel: input.channel,\n type: input.type ?? NotificationType.TRANSACTIONAL,\n priority: input.priority ?? priority ?? NotificationPriority.MEDIUM,\n subject: input.subject,\n body: input.body,\n htmlBody: input.htmlBody,\n data: input.data,\n metadata: input.metadata,\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n };\n }\n\n /**\n * Send notification using a template\n */\n public async sendWithTemplate(input: SendWithTemplateInput, context?: SDKContext): Promise<string> {\n // Validate inputs\n if (!input.templateSlug || input.templateSlug.trim().length === 0) {\n throw new ValidationError('Template slug is required');\n }\n\n if (!input.variables || typeof input.variables !== 'object' || Array.isArray(input.variables)) {\n throw new ValidationError('Template variables must be an object');\n }\n\n if (!input.recipient || (!input.recipient.email && !input.recipient.userId)) {\n throw new ValidationError('Recipient email or userId is required');\n }\n\n this.validateDates(input);\n\n logger.info('[TenantNotifications] Sending notification with template', {\n templateSlug: input.templateSlug,\n priority: input.priority || NotificationPriority.MEDIUM,\n });\n\n const mutation = `\n mutation TriggerNotificationWithTemplate($input: TriggerNotificationWithTemplateInput!) {\n triggerNotificationWithTemplate(input: $input) {\n totalRequested\n totalTriggered\n totalFailed\n notifications {\n id\n status\n deliveryStatus\n }\n }\n }\n `;\n\n const variables = {\n input: {\n templateSlug: input.templateSlug,\n variables: input.variables,\n recipient: input.recipient,\n priority: input.priority || NotificationPriority.MEDIUM,\n scheduledFor: input.scheduledFor?.toISOString(),\n expiresAt: input.expiresAt?.toISOString(),\n trackOpens: input.trackOpens,\n trackClicks: input.trackClicks,\n // Platform is required for notification delivery routing\n // If channelId is specified, it takes precedence; otherwise platform determines delivery\n channelId: input.channelId,\n platform: input.platform || NotificationChannel.EMAIL,\n timezone: input.timezone,\n },\n };\n\n const response = await this.client.tenantQuery<{\n triggerNotificationWithTemplate: {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: Array<{ id: string; status: string; deliveryStatus?: string }>;\n };\n }>(mutation, variables, { ...this.context, ...context });\n\n const result = response.triggerNotificationWithTemplate;\n const firstNotification = result.notifications[0];\n\n if (result.totalTriggered === 0 || !firstNotification) {\n throw new ValidationError(\n `Notification trigger failed: requested=${result.totalRequested}, triggered=${result.totalTriggered}, failed=${result.totalFailed}`\n );\n }\n\n logger.info('[TenantNotifications] Notification sent with template', {\n notificationId: firstNotification.id,\n status: firstNotification.status,\n totalTriggered: result.totalTriggered,\n totalFailed: result.totalFailed,\n });\n\n return firstNotification.id;\n }\n\n /**\n * Send batch notifications\n */\n public async sendBatch(\n input: BatchNotificationInput,\n context?: SDKContext\n ): Promise<{\n totalRequested: number;\n /** Legacy name for the owner's accepted totalTriggered counter, not final delivery. */\n totalQueued: number;\n totalFailed: number;\n batchId: string;\n }> {\n if (!input.notifications?.length) throw new ValidationError('At least one notification is required');\n for (const notification of input.notifications) this.validateSendInput(notification);\n const schedules = new Set(\n input.notifications.map((notification) => notification.scheduledFor?.toISOString() ?? '')\n );\n if (schedules.size > 1) {\n throw new ValidationError('Batch notifications must share a schedule; use send() for distinct schedules');\n }\n if (input.batchSize !== undefined && (!Number.isInteger(input.batchSize) || input.batchSize <= 0)) {\n throw new ValidationError('Batch size must be a positive integer');\n }\n if (\n input.delayBetweenBatches !== undefined &&\n (!Number.isInteger(input.delayBetweenBatches) || input.delayBetweenBatches < 0)\n ) {\n throw new ValidationError('Batch delay must be a nonnegative integer');\n }\n const response = await this.client.tenantQuery<{\n triggerBatchNotifications: { totalRequested: number; totalQueued: number; totalFailed: number; batchId: string };\n }>(\n `mutation TriggerTenantBatchNotifications($input: TriggerBatchNotificationsInput!) {\n triggerBatchNotifications(input: $input) { totalRequested totalQueued: totalTriggered totalFailed batchId }\n }`,\n {\n input: {\n notifications: input.notifications.map((notification) =>\n this.createNotificationInput(notification, input.priority)\n ),\n priority: input.priority,\n scheduledFor: input.notifications[0]?.scheduledFor?.toISOString(),\n batchSize: input.batchSize,\n delayBetweenBatches: input.delayBetweenBatches,\n },\n },\n { ...this.context, ...context }\n );\n const result = response.triggerBatchNotifications;\n if (!result?.batchId)\n throw new APIError('Notification batch was not acknowledged', { operation: 'triggerBatchNotifications' });\n return result;\n }\n\n /**\n * Get a notification by ID\n */\n public async getNotification(id: string): Promise<Notification | null> {\n const query = `\n query GetNotification($id: ID!) {\n notification(id: $id) {\n id\n userId\n channel\n type\n priority\n status\n deliveryStatus\n title\n message\n htmlMessage\n subject\n recipientEmail\n recipientPhone\n trackOpens\n trackClicks\n openedAt\n clickedAt\n sentAt\n deliveredAt\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.tenantQuery<{\n notification: Notification | null;\n }>(query, { id }, this.context);\n\n return response.notification;\n }\n\n /**\n * Get notifications with filters\n */\n public async getNotifications(filter?: {\n userId?: string;\n channel?: NotificationChannel;\n type?: NotificationType;\n status?: string;\n priority?: NotificationPriority;\n startDate?: Date;\n endDate?: Date;\n limit?: number;\n offset?: number;\n }): Promise<Notification[]> {\n const query = `\n query GetNotifications($filter: NotificationFilterInput, $limit: Int, $offset: Int) {\n notifications(filter: $filter, limit: $limit, offset: $offset) {\n items {\n id\n userId\n channel\n type\n priority\n status\n deliveryStatus\n title\n message\n subject\n recipientEmail\n trackOpens\n trackClicks\n openedAt\n clickedAt\n sentAt\n deliveredAt\n createdAt\n updatedAt\n }\n }\n }\n `;\n\n const variables = {\n filter: filter\n ? {\n userId: filter.userId,\n channel: filter.channel,\n type: filter.type,\n status: filter.status,\n priority: filter.priority,\n startDate: filter.startDate?.toISOString(),\n endDate: filter.endDate?.toISOString(),\n }\n : undefined,\n limit: filter?.limit ?? 50,\n offset: filter?.offset ?? 0,\n };\n\n const response = await this.client.tenantQuery<{\n notifications: { items: Notification[] };\n }>(query, variables, this.context);\n\n return response.notifications.items;\n }\n\n /**\n * Get notification template\n */\n public async getTemplate(slug: string, locale?: string): Promise<NotificationTemplate | null> {\n const query = `\n query GetNotificationTemplate($slug: String!, $locale: String) {\n notificationTemplate(slug: $slug, locale: $locale) {\n id\n name\n slug\n description\n channel\n type\n locale\n subject\n bodyTemplate\n htmlTemplate\n variables\n enabled\n version\n createdAt\n updatedAt\n }\n }\n `;\n\n const response = await this.client.tenantQuery<{\n notificationTemplate: NotificationTemplate | null;\n }>(query, { slug, locale }, this.context);\n\n return response.notificationTemplate;\n }\n\n /**\n * Get all notification templates\n */\n public async getTemplates(filter?: {\n channel?: NotificationChannel;\n type?: NotificationType;\n enabled?: boolean;\n }): Promise<NotificationTemplate[]> {\n const query = `query GetNotificationTemplates($filter: TemplateFilterInput, $limit: Int!, $offset: Int!) {\n notificationTemplates(filter: $filter, limit: $limit, offset: $offset) {\n items { id name slug description channel type locale subject bodyTemplate htmlTemplate variables enabled version createdAt updatedAt }\n hasMore\n }\n }`;\n const templates: NotificationTemplate[] = [];\n const seen = new Set<string>();\n for (let page = 0; page < 100; page++) {\n const response = await this.client.tenantQuery<{\n notificationTemplates: { items: NotificationTemplate[]; hasMore: boolean };\n }>(query, { filter, limit: 100, offset: templates.length }, this.context);\n const result = response.notificationTemplates;\n if (!result || !Array.isArray(result.items) || typeof result.hasMore !== 'boolean') {\n throw new APIError('Notification template page was invalid', { operation: 'notificationTemplates' });\n }\n for (const template of result.items) {\n if (!template.id || seen.has(template.id)) {\n throw new APIError('Notification template pagination did not progress', {\n operation: 'notificationTemplates',\n });\n }\n seen.add(template.id);\n templates.push(template);\n }\n if (!result.hasMore) return templates;\n if (!result.items.length) {\n throw new APIError('Notification template pagination did not progress', { operation: 'notificationTemplates' });\n }\n }\n throw new APIError('Notification template pagination exceeded its bounded limit', {\n operation: 'notificationTemplates',\n });\n }\n\n /**\n * Get notification statistics\n */\n public async getStats(filter?: { userId?: string; startDate?: Date; endDate?: Date }): Promise<NotificationStats> {\n const query = `\n query GetNotificationStats($filter: NotificationFilterInput) {\n notificationStats(filter: $filter) {\n total\n pending\n triggered\n scheduled\n cancelled\n sent\n delivered\n failed\n byChannel\n byType\n }\n }\n `;\n\n const variables = {\n filter: filter\n ? {\n userId: filter.userId,\n startDate: filter.startDate?.toISOString(),\n endDate: filter.endDate?.toISOString(),\n }\n : undefined,\n };\n\n const response = await this.client.tenantQuery<{\n notificationStats: NotificationStats;\n }>(query, variables, this.context);\n\n return response.notificationStats;\n }\n\n /**\n * Mark notifications as read\n */\n public async markAsRead(notificationIds: string[]): Promise<boolean> {\n const mutation = `\n mutation MarkNotificationsAsRead($notificationIds: [ID!]!) {\n markNotificationsAsRead(notificationIds: $notificationIds) { success count failedIds }\n }\n `;\n\n const result = await this.client.tenantQuery<{ markNotificationsAsRead: { success: boolean } }>(\n mutation,\n { notificationIds },\n this.context\n );\n\n logger.info('[TenantNotifications] Read request completed', {\n success: result.markNotificationsAsRead.success,\n count: notificationIds.length,\n });\n\n return result.markNotificationsAsRead.success;\n }\n\n /**\n * Mark all notifications as read for the current user\n */\n public async markAllAsRead(): Promise<boolean> {\n const mutation = `\n mutation MarkAllMyNotificationsAsRead {\n markAllMyNotificationsAsRead { success count failedIds }\n }\n `;\n\n const result = await this.client.tenantQuery<{ markAllMyNotificationsAsRead: { success: boolean } }>(\n mutation,\n {},\n this.context\n );\n\n logger.info('[TenantNotifications] Read-all request completed', {\n success: result.markAllMyNotificationsAsRead.success,\n });\n\n return result.markAllMyNotificationsAsRead.success;\n }\n\n /**\n * Delete notifications\n */\n public async deleteNotifications(notificationIds: string[]): Promise<boolean> {\n const mutation = `\n mutation DeleteNotifications($notificationIds: [ID!]!) {\n deleteNotifications(notificationIds: $notificationIds)\n }\n `;\n\n const result = await this.client.tenantQuery<{ deleteNotifications: boolean }>(\n mutation,\n { notificationIds },\n this.context\n );\n\n logger.info('[TenantNotifications] Delete request completed', {\n success: result.deleteNotifications,\n count: notificationIds.length,\n });\n\n return result.deleteNotifications;\n }\n\n /**\n * Delete all read notifications for the current user\n */\n public async deleteAllReadNotifications(): Promise<boolean> {\n const mutation = `\n mutation DeleteMyReadNotifications {\n deleteMyReadNotifications\n }\n `;\n\n const result = await this.client.tenantQuery<{ deleteMyReadNotifications: boolean }>(mutation, {}, this.context);\n\n logger.info('[TenantNotifications] Delete-read request completed', { success: result.deleteMyReadNotifications });\n\n return result.deleteMyReadNotifications;\n }\n\n /**\n * Validate send notification input\n */\n private validateSendInput(input: SendNotificationInput): void {\n if (!Object.values(NotificationChannel).includes(input.channel)) {\n throw new ValidationError('A supported notification channel is required');\n }\n const recipientKeys: Record<NotificationChannel, Array<keyof RecipientInput>> = {\n EMAIL: ['email', 'userId'],\n SMS: ['phoneNumber', 'userId'],\n PUSH: ['pushToken', 'userId'],\n IN_APP: ['userId'],\n WEBHOOK: ['webhookUrl', 'userId'],\n WHATSAPP: ['whatsappNumber', 'phoneNumber', 'userId'],\n TEAMS: ['teamsUserId', 'userId'],\n SLACK: ['slackUserId', 'userId'],\n TELEGRAM: ['userId'],\n DISCORD: ['userId'],\n };\n if (\n !input.recipient ||\n !recipientKeys[input.channel].some((key) => {\n const value = input.recipient[key];\n return typeof value === 'string' && value.trim().length > 0;\n })\n )\n throw new ValidationError('A recipient address or userId appropriate for the channel is required');\n if (typeof input.body !== 'string' || input.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n this.validateDates(input);\n }\n\n private validateDates(input: { scheduledFor?: Date; expiresAt?: Date }): void {\n for (const value of [input.scheduledFor, input.expiresAt]) {\n if (value != null && (!(value instanceof Date) || !Number.isFinite(value.getTime()))) {\n throw new ValidationError('Notification dates must be valid Date values');\n }\n }\n if (input.scheduledFor && input.expiresAt && input.expiresAt <= input.scheduledFor) {\n throw new ValidationError('Notification expiry must follow its scheduled delivery');\n }\n }\n}\n","/**\n * Notifications Module\n * Send in-app, email, SMS, and push notifications via workspaces-backend\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\nexport enum NotificationType {\n INFO = 'info',\n SUCCESS = 'success',\n WARNING = 'warning',\n ERROR = 'error',\n}\n\nexport enum NotificationChannel {\n EMAIL = 'EMAIL',\n SMS = 'SMS',\n WHATSAPP = 'WHATSAPP',\n PUSH = 'PUSH',\n SLACK = 'SLACK',\n TEAMS = 'TEAMS',\n WEBHOOK = 'WEBHOOK',\n}\n\n// Re-export from tenant-notifications\nexport {\n NotificationChannel as TenantNotificationChannel,\n NotificationType as TenantNotificationType,\n NotificationPriority,\n TenantNotificationsModule,\n} from './tenant-notifications.js';\nexport type {\n SendNotificationInput as TenantSendNotificationInput,\n SendWithTemplateInput as TenantSendWithTemplateInput,\n BatchNotificationInput as TenantBatchNotificationInput,\n} from './tenant-notifications.js';\n\nexport interface SendNotificationOptions {\n /** Notification title */\n title: string;\n /** Notification message */\n message: string;\n /** Notification type */\n type?: NotificationType;\n /** Target user IDs */\n userIds: string[];\n /** Optional redirect URL */\n redirectUrl?: string;\n /** Application name */\n appName?: string;\n /** Send email notification */\n email?: boolean;\n /** Send SMS notification */\n sms?: boolean;\n /** Structured event metadata retained by the notification owner. */\n metadata?: Record<string, unknown>;\n /** Additional application data retained by the notification owner. */\n data?: Record<string, unknown>;\n /** Optional absolute expiration time. */\n expiresAt?: Date;\n}\n\nexport interface NotificationResponse {\n /** Number of successful notifications */\n successCount: number;\n /** Number of failed notifications */\n failureCount: number;\n /** Error messages if any */\n errors: string[];\n /** Created notification IDs */\n notificationIds?: string[];\n}\n\nexport interface GetNotificationsOptions {\n /** User ID to get notifications for */\n userId: string;\n /** Filter by status */\n status?: 'unread' | 'read' | 'all';\n /** Filter by type */\n type?: NotificationType;\n /** Filter by app name */\n appName?: string;\n /** Search term */\n search?: string;\n /** Limit number of results */\n limit?: number;\n /** Offset for pagination */\n offset?: number;\n}\n\nexport interface Notification {\n id: string;\n userId: string;\n title: string;\n message: string;\n type: NotificationType;\n status: 'unread' | 'read';\n redirectUrl?: string;\n appName?: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface RecipientInput {\n email?: string;\n locale?: string;\n name?: string;\n phoneNumber?: string;\n pushToken?: string;\n slackUserId?: string;\n teamsUserId?: string;\n timezone?: string;\n userId?: string;\n webhookUrl?: string;\n whatsappNumber?: string;\n}\n\nexport interface SendChannelNotificationOptions {\n /** Primary delivery channel (EMAIL, SMS, WHATSAPP, etc.) */\n platform: NotificationChannel;\n /** Recipient information for primary channel */\n recipient: RecipientInput;\n /** Multiple recipients for bulk delivery */\n recipients?: RecipientInput[];\n /** Notification subject (for EMAIL) */\n subject?: string;\n /** Notification body/message */\n body: string;\n /** HTML body (for EMAIL) */\n htmlBody?: string;\n /** Notification type */\n type?: NotificationType;\n /** Application name */\n appName?: string;\n /** Redirect URL */\n redirectUrl?: string;\n /** Also send as in-app notification */\n includeInApp?: boolean;\n /** User IDs for in-app notifications (required when includeInApp is true) */\n userIds?: string[];\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** Track email opens */\n trackOpens?: boolean;\n /** Track link clicks */\n trackClicks?: boolean;\n /** Expiration time */\n expiresAt?: Date;\n /** Specific channel instance ID (overrides platform) */\n channelId?: string;\n}\n\nexport interface SendTemplateNotificationOptions {\n /** Primary delivery channel (EMAIL, SMS, WHATSAPP, etc.) */\n platform: NotificationChannel;\n /** Template slug to use */\n templateSlug: string;\n /** Template variables */\n variables: Record<string, unknown>;\n /** Recipient information for primary channel */\n recipient?: RecipientInput;\n /** Multiple recipients for bulk delivery */\n recipients?: RecipientInput[];\n /** Also send as in-app notification */\n includeInApp?: boolean;\n /** User IDs for in-app notifications (required when includeInApp is true) */\n userIds?: string[];\n /** Application name */\n appName?: string;\n /** Track email opens */\n trackOpens?: boolean;\n /** Track link clicks */\n trackClicks?: boolean;\n /** Expiration time */\n expiresAt?: Date;\n /** Scheduled delivery time */\n scheduledFor?: Date;\n /** Timezone for scheduling */\n timezone?: string;\n /** Specific channel instance ID (overrides platform) */\n channelId?: string;\n}\n\n/**\n * Map the SDK's severity-flavoured `NotificationType` (info/success/warning/error) onto\n * global-notification-svc's delivery-intent `NotificationType`\n * (ALERT | MARKETING | SYSTEM | TRANSACTIONAL).\n *\n * The two enums describe different things and share no values, so an unmapped value would be\n * rejected by the owner. Warnings and errors are alerts; everything else is transactional.\n */\nfunction mapNotificationType(type?: NotificationType): 'ALERT' | 'TRANSACTIONAL' {\n return type === NotificationType.WARNING || type === NotificationType.ERROR ? 'ALERT' : 'TRANSACTIONAL';\n}\n\n/**\n * Choose the delivery channel required by `CreateNotificationInput.channel` (non-nullable).\n *\n * `SendNotificationOptions` expresses channel intent as the legacy `email`/`sms` booleans; the\n * owner expects a single `NotificationChannel`. In-app is the default so a caller that sets\n * neither flag still gets a delivered, visible notification.\n */\nfunction resolveChannel(options: SendNotificationOptions): 'EMAIL' | 'SMS' | 'IN_APP' {\n if (options.email) return 'EMAIL';\n if (options.sms) return 'SMS';\n return 'IN_APP';\n}\n\n/**\n * Notifications Module\n */\nexport class NotificationsModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Send notification to users\n */\n public async send(options: SendNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.title || options.title.trim().length === 0) {\n throw new ValidationError('Notification title is required');\n }\n\n if (!options.message || options.message.trim().length === 0) {\n throw new ValidationError('Notification message is required');\n }\n\n if (!options.userIds || options.userIds.length === 0) {\n throw new ValidationError('At least one user ID is required');\n }\n if (options.expiresAt && (!(options.expiresAt instanceof Date) || !Number.isFinite(options.expiresAt.getTime()))) {\n throw new ValidationError('Notification expiry must be a valid Date');\n }\n\n logger.info('[Notifications] Sending notification', {\n userCount: options.userIds.length,\n type: options.type || NotificationType.INFO,\n });\n\n // `triggerNotification` both creates AND delivers. `createNotification` only persists —\n // its own schema doc says \"without triggering - use triggerNotification to send\" — so sending\n // through it would silently never deliver.\n const mutation = `\n mutation TriggerNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) {\n id\n status\n }\n }\n `;\n\n // global-notification-svc addresses ONE recipient per notification, so a multi-user send fans\n // out into one mutation per user rather than passing a `userIds` array (which the input does\n // not have). Failures are collected per recipient instead of rejecting the whole batch.\n const channel = resolveChannel(options);\n const notificationIds: string[] = [];\n const errors: string[] = [];\n\n const results = await Promise.allSettled(\n options.userIds.map(async (userId) => {\n const variables = {\n input: {\n notification: {\n recipient: { userId },\n channel,\n type: mapNotificationType(options.type),\n subject: options.title,\n body: options.message,\n metadata: options.metadata,\n data: options.data,\n expiresAt: options.expiresAt?.toISOString(),\n ...(options.redirectUrl ? { redirectUrl: options.redirectUrl } : {}),\n ...(options.appName ? { appName: options.appName } : {}),\n },\n platform: channel,\n // Always leave an in-app trace when the primary channel is external, so the\n // notification is visible in the product even if email/SMS delivery fails.\n includeInApp: channel !== 'IN_APP',\n },\n };\n\n const response = await this.client.tenantQuery<{\n triggerNotification: { id: string; status?: string };\n }>(mutation, variables, this.context);\n\n const id = response.triggerNotification?.id;\n if (!id) {\n throw new Error(`notification service returned no id for user ${userId}`);\n }\n return id;\n })\n );\n\n for (const [index, settled] of results.entries()) {\n if (settled.status === 'fulfilled') {\n notificationIds.push(settled.value);\n } else {\n const reason = settled.reason instanceof Error ? settled.reason.message : String(settled.reason);\n errors.push(`${options.userIds[index] ?? 'unknown user'}: ${reason}`);\n }\n }\n\n const result: NotificationResponse = {\n successCount: notificationIds.length,\n failureCount: errors.length,\n errors,\n notificationIds,\n };\n\n logger.info('[Notifications] Notification sent', {\n successCount: result.successCount,\n failureCount: result.failureCount,\n });\n\n return result;\n }\n\n /**\n * Send notification to a single user (convenience method)\n */\n public async sendToUser(\n userId: string,\n title: string,\n message: string,\n options?: Omit<SendNotificationOptions, 'userIds' | 'title' | 'message'>\n ): Promise<NotificationResponse> {\n return this.send({\n title,\n message,\n userIds: [userId],\n ...options,\n });\n }\n\n /**\n * Get notifications for a user\n */\n public async getNotifications(options: GetNotificationsOptions): Promise<{\n notifications: Notification[];\n total: number;\n unreadCount: number;\n }> {\n logger.debug('[Notifications] Getting notifications', { userId: options.userId });\n\n const query = `\n query GetNotifications(\n $userId: ID!\n $status: NotificationStatus\n $type: NotificationType\n $appName: String\n $search: String\n $limit: Int\n $offset: Int\n ) {\n getNotifications(\n userId: $userId\n status: $status\n type: $type\n appName: $appName\n search: $search\n limit: $limit\n offset: $offset\n ) {\n notifications {\n id\n userId\n title\n message\n type\n status\n redirectUrl\n appName\n createdAt\n updatedAt\n }\n total\n unreadCount\n }\n }\n `;\n\n const variables = {\n userId: options.userId,\n status: options.status,\n type: options.type,\n appName: options.appName,\n search: options.search,\n limit: options.limit || 20,\n offset: options.offset || 0,\n };\n\n const response = await this.client.query<{\n getNotifications: {\n notifications: Notification[];\n total: number;\n unreadCount: number;\n };\n }>(query, variables, this.context);\n\n return response.getNotifications;\n }\n\n /**\n * Mark notification as read\n */\n public async markAsRead(notificationId: string): Promise<boolean> {\n logger.debug('[Notifications] Marking notification as read', { notificationId });\n\n const mutation = `\n mutation MarkNotificationAsRead($notificationId: ID!) {\n markNotificationAsRead(notificationId: $notificationId) {\n id\n status\n }\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationId }, this.context);\n\n logger.info('[Notifications] Notification marked as read', { notificationId });\n\n return true;\n }\n\n /**\n * Mark multiple notifications as read\n */\n public async markMultipleAsRead(notificationIds: string[]): Promise<number> {\n logger.debug('[Notifications] Marking multiple notifications as read', {\n count: notificationIds.length,\n });\n\n const mutation = `\n mutation MarkNotificationsAsRead($notificationIds: [ID!]!) {\n markNotificationsAsRead(notificationIds: $notificationIds) {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n markNotificationsAsRead: { count: number };\n }>(mutation, { notificationIds }, this.context);\n\n logger.info('[Notifications] Notifications marked as read', {\n count: response.markNotificationsAsRead.count,\n });\n\n return response.markNotificationsAsRead.count;\n }\n\n /**\n * Mark all notifications as read for the current user\n */\n public async markAllAsRead(): Promise<number> {\n logger.debug('[Notifications] Marking all notifications as read');\n\n const mutation = `\n mutation MarkAllMyNotificationsAsRead {\n markAllMyNotificationsAsRead {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n markAllMyNotificationsAsRead: { count: number };\n }>(mutation, {}, this.context);\n\n logger.info('[Notifications] All notifications marked as read', {\n count: response.markAllMyNotificationsAsRead.count,\n });\n\n return response.markAllMyNotificationsAsRead.count;\n }\n\n /**\n * Delete notification\n */\n public async deleteNotification(notificationId: string): Promise<boolean> {\n logger.debug('[Notifications] Deleting notification', { notificationId });\n\n const mutation = `\n mutation DeleteNotification($notificationId: ID!) {\n deleteNotification(notificationId: $notificationId) {\n success\n }\n }\n `;\n\n await this.client.tenantQuery(mutation, { notificationId }, this.context);\n\n logger.info('[Notifications] Notification deleted', { notificationId });\n\n return true;\n }\n\n /**\n * Delete multiple notifications\n */\n public async deleteMultiple(notificationIds: string[]): Promise<number> {\n logger.debug('[Notifications] Deleting multiple notifications', {\n count: notificationIds.length,\n });\n\n const mutation = `\n mutation DeleteNotifications($notificationIds: [ID!]!) {\n deleteNotifications(notificationIds: $notificationIds) {\n count\n }\n }\n `;\n\n const response = await this.client.query<{\n deleteNotifications: { count: number };\n }>(mutation, { notificationIds }, this.context);\n\n logger.info('[Notifications] Notifications deleted', {\n count: response.deleteNotifications.count,\n });\n\n return response.deleteNotifications.count;\n }\n\n /**\n * Get unread notification count for a user\n */\n public async getUnreadCount(userId: string): Promise<number> {\n const result = await this.getNotifications({\n userId,\n status: 'unread',\n limit: 0,\n });\n\n return result.unreadCount;\n }\n\n /**\n * Send notification via specific channel (EMAIL, SMS, WHATSAPP, etc.)\n * with optional in-app notification\n */\n public async sendChannelNotification(options: SendChannelNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.body || options.body.trim().length === 0) {\n throw new ValidationError('Notification body is required');\n }\n\n if (!options.recipient && !options.recipients) {\n throw new ValidationError('At least one recipient is required');\n }\n\n if (options.includeInApp && (!options.userIds || options.userIds.length === 0)) {\n throw new ValidationError('User IDs are required when includeInApp is true');\n }\n\n logger.info('[Notifications] Sending channel notification', {\n platform: options.platform,\n recipientCount: options.recipients ? options.recipients.length : 1,\n includeInApp: options.includeInApp,\n inAppUserCount: options.userIds ? options.userIds.length : 0,\n });\n\n const mutation = `\n mutation TriggerNotification($input: TriggerNotificationInput!) {\n triggerNotification(input: $input) {\n id\n status\n deliveryStatus\n }\n }\n `;\n\n const variables = {\n input: {\n platform: options.platform,\n channelId: options.channelId,\n includeInApp: options.includeInApp || false,\n userIds: options.userIds || [],\n notification: {\n subject: options.subject || '',\n body: options.body,\n htmlBody: options.htmlBody || '',\n channel: options.platform,\n type: options.type || NotificationType.INFO,\n recipient: options.recipient,\n appName: options.appName,\n redirectUrl: options.redirectUrl || '',\n metadata: options.metadata || {},\n trackOpens: options.trackOpens || false,\n trackClicks: options.trackClicks || false,\n expiresAt: options.expiresAt?.toISOString(),\n },\n },\n };\n\n // Handle bulk recipients\n if (options.recipients && options.recipients.length > 1) {\n const results = await Promise.allSettled(\n options.recipients.map((recipient) =>\n this.client.tenantQuery(\n mutation,\n {\n input: {\n ...variables.input,\n notification: {\n ...variables.input.notification,\n recipient,\n },\n },\n },\n this.context\n )\n )\n );\n\n let successCount = 0;\n let failureCount = 0;\n const errors: string[] = [];\n const notificationIds: string[] = [];\n\n results.forEach((result, index) => {\n if (result.status === 'fulfilled') {\n successCount++;\n const response = result.value as { triggerNotification: { id: string } };\n notificationIds.push(response.triggerNotification.id);\n } else {\n failureCount++;\n errors.push(\n `Recipient ${index + 1}: ${result.reason instanceof Error ? result.reason.message : 'Unknown error'}`\n );\n }\n });\n\n const response: NotificationResponse = {\n successCount,\n failureCount,\n errors,\n notificationIds,\n };\n\n logger.info('[Notifications] Channel notification sent (bulk)', {\n successCount,\n failureCount,\n });\n\n return response;\n } else {\n // Single recipient\n try {\n const response = await this.client.query<{\n triggerNotification: { id: string; status: string; deliveryStatus: string };\n }>(mutation, variables, this.context);\n\n const result: NotificationResponse = {\n successCount: 1,\n failureCount: 0,\n errors: [],\n notificationIds: [response.triggerNotification.id],\n };\n\n logger.info('[Notifications] Channel notification sent', {\n notificationId: response.triggerNotification.id,\n status: response.triggerNotification.status,\n });\n\n return result;\n } catch (error) {\n logger.error('[Notifications] Failed to send channel notification', { error });\n\n return {\n successCount: 0,\n failureCount: 1,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n notificationIds: [],\n };\n }\n }\n }\n\n /**\n * Send notification using a template with optional in-app notification\n */\n public async sendTemplateNotification(options: SendTemplateNotificationOptions): Promise<NotificationResponse> {\n // Validate inputs\n if (!options.templateSlug || options.templateSlug.trim().length === 0) {\n throw new ValidationError('Template slug is required');\n }\n\n if (!options.variables || typeof options.variables !== 'object') {\n throw new ValidationError('Template variables are required');\n }\n\n if (!options.recipient && !options.recipients) {\n throw new ValidationError('At least one recipient is required');\n }\n\n if (options.includeInApp && (!options.userIds || options.userIds.length === 0)) {\n throw new ValidationError('User IDs are required when includeInApp is true');\n }\n\n logger.info('[Notifications] Sending template notification', {\n templateSlug: options.templateSlug,\n platform: options.platform,\n recipientCount: options.recipients ? options.recipients.length : 1,\n includeInApp: options.includeInApp,\n inAppUserCount: options.userIds ? options.userIds.length : 0,\n });\n\n const mutation = `\n mutation TriggerNotificationWithTemplate($input: TriggerNotificationWithTemplateInput!) {\n triggerNotificationWithTemplate(input: $input) {\n totalRequested\n totalTriggered\n totalFailed\n notifications {\n id\n status\n deliveryStatus\n }\n }\n }\n `;\n\n const variables = {\n input: {\n platform: options.platform,\n channelId: options.channelId,\n includeInApp: options.includeInApp || false,\n userIds: options.userIds || [],\n templateSlug: options.templateSlug,\n variables: options.variables,\n recipient: options.recipient,\n recipients: options.recipients,\n trackOpens: options.trackOpens || false,\n trackClicks: options.trackClicks || false,\n expiresAt: options.expiresAt?.toISOString(),\n scheduledFor: options.scheduledFor?.toISOString(),\n timezone: options.timezone,\n },\n };\n\n try {\n const response = await this.client.query<{\n triggerNotificationWithTemplate: {\n totalRequested: number;\n totalTriggered: number;\n totalFailed: number;\n notifications: Array<{ id: string; status: string; deliveryStatus?: string }>;\n };\n }>(mutation, variables, this.context);\n\n const data = response.triggerNotificationWithTemplate;\n\n const result: NotificationResponse = {\n successCount: data.totalTriggered,\n failureCount: data.totalFailed,\n errors: [],\n notificationIds: data.notifications.map((n) => n.id),\n };\n\n logger.info('[Notifications] Template notification sent', {\n templateSlug: options.templateSlug,\n totalTriggered: data.totalTriggered,\n totalFailed: data.totalFailed,\n notificationIds: result.notificationIds,\n });\n\n return result;\n } catch (error) {\n logger.error('[Notifications] Failed to send template notification', { error });\n\n return {\n successCount: 0,\n failureCount: 1,\n errors: [error instanceof Error ? error.message : 'Unknown error'],\n notificationIds: [],\n };\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,IAAYA,wBAAL;CACL;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;AACF;AAEA,IAAY,uBAAL;CACL;CACA;CACA;CACA;;AACF;AAEA,IAAYC,qBAAL;CACL;CACA;CACA;CACA;;AACF;;;;;AAsIA,IAAa,4BAAb,MAAuC;CAE3B;CACA;CAFV,YACE,AAAQ,QACR,AAAQ,SACR;EAFQ;EACA;CACP;;;;CAKH,MAAa,KAAK,OAA8B,SAAuC;EACrF,KAAK,kBAAkB,KAAK;EAC5B,MAAM,eAAe,KAAK,wBAAwB,KAAK;EACvD,MAAM,cAAc;GAAE,GAAG,KAAK;GAAS,GAAG;EAAQ;EAElD,IAAI,MAAM,cAAc;GAUtB,MAAM,UAAS,MATQ,KAAK,OAAO,YAGjC;;YAGA,EAAE,OAAO;IAAE;IAAc,cAAc,MAAM,aAAa,YAAY;IAAG,UAAU,MAAM,UAAU;GAAS,EAAE,GAC9G,WACF,EACuB,CAAC;GACxB,IAAI,CAAC,QAAQ,kBAAkB,OAAO,WAAW,WAC/C,MAAM,IAAI,SAAS,gDAAgD,EAAE,WAAW,uBAAuB,CAAC;GAE1G,OAAO,OAAO;EAChB;EAWA,MAAM,UAAS,MATQ,KAAK,OAAO,YAGjC;;UAGA,EAAE,OAAO;GAAE;GAAc,UAAU,MAAM;GAAS,cAAc;EAAM,EAAE,GACxE,WACF,EACuB,CAAC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,eAAe;GACpC,WAAW,QAAQ,WAAW,YAAY;GAC1C,cAAc,QAAQ,cAAc,YAAY;GAChD,UAAU,QAAQ;EACpB,EACF;EAEA,IAAI;GAUF,MAAM,QAAO,MATU,KAAK,OAAO,MAOhC,UAAU,WAAW,KAAK,OAAO,EAEf,CAAC;GAEtB,MAAM,SAA+B;IACnC,cAAc,KAAK;IACnB,cAAc,KAAK;IACnB,QAAQ,CAAC;IACT,iBAAiB,KAAK,cAAc,KAAK,MAAM,EAAE,EAAE;GACrD;GAEA,OAAO,KAAK,8CAA8C;IACxD,cAAc,QAAQ;IACtB,gBAAgB,KAAK;IACrB,aAAa,KAAK;IAClB,iBAAiB,OAAO;GAC1B,CAAC;GAED,OAAO;EACT,SAAS,OAAO;GACd,OAAO,MAAM,wDAAwD,EAAE,MAAM,CAAC;GAE9E,OAAO;IACL,cAAc;IACd,cAAc;IACd,QAAQ,CAAC,iBAAiB,QAAQ,MAAM,UAAU,eAAe;IACjE,iBAAiB,CAAC;GACpB;EACF;CACF;AACF"}
@@ -1,3 +1,2 @@
1
- export { M as Metrics, a as MetricsCollector, c as createMetricsPlugin, g as getCurrentMetrics, b as getMetricsForWindow, m as metricsCollector } from '../index-4gKQKZ2B.js';
2
- import 'elysia';
3
- import '../types-Bo2wkjSP.js';
1
+ import { a as Metrics, i as getMetricsForWindow, n as createMetricsPlugin, o as MetricsCollector, r as getCurrentMetrics, s as metricsCollector } from "../index-C5uEKchX.js";
2
+ export { type Metrics, MetricsCollector, createMetricsPlugin, getCurrentMetrics, getMetricsForWindow, metricsCollector };
@@ -1,5 +1,4 @@
1
- export { MetricsCollector, createMetricsPlugin, getCurrentMetrics, getMetricsForWindow, metricsCollector } from '../chunk-VAT66FJA.js';
2
- import '../chunk-RU266375.js';
3
- import '../chunk-XE4OXN2W.js';
1
+ import { a as MetricsCollector, i as getMetricsForWindow, n as createMetricsPlugin, o as metricsCollector, r as getCurrentMetrics } from "../observability-DBDXipTU.js";
2
+
3
+ export { MetricsCollector, createMetricsPlugin, getCurrentMetrics, getMetricsForWindow, metricsCollector };
4
4
  //# sourceMappingURL=index.js.map
5
- //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
1
+ {"version":3,"file":"index.js","sources":[],"names":[],"mappings":""}
@@ -0,0 +1,272 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
+ import { a as logger } from "./logger-B6rCpb7D.js";
3
+ import { Elysia } from "elysia";
4
+
5
+ // src/observability/metrics.ts
6
+ var MetricsCollector = class MetricsCollector {
7
+ static instance = null;
8
+ requests = [];
9
+ MAX_REQUESTS = 1e4;
10
+ totalRequests = 0;
11
+ totalErrors = 0;
12
+ totalResponseTime = 0;
13
+ cleanupInterval = null;
14
+ CLEANUP_INTERVAL_MS = 3e5;
15
+ DATA_RETENTION_MS = 36e5;
16
+ constructor() {
17
+ this.startCleanupTimer();
18
+ }
19
+ /**
20
+ * Get singleton instance
21
+ */
22
+ static getInstance() {
23
+ if (!MetricsCollector.instance) MetricsCollector.instance = new MetricsCollector();
24
+ return MetricsCollector.instance;
25
+ }
26
+ /**
27
+ * Record a request metric
28
+ *
29
+ * @param responseTimeMs - Response time in milliseconds
30
+ * @param isError - Whether the request resulted in an error
31
+ */
32
+ recordRequest(responseTimeMs, isError) {
33
+ const metric = {
34
+ timestamp: Date.now(),
35
+ responseTime: responseTimeMs,
36
+ isError
37
+ };
38
+ this.requests.push(metric);
39
+ if (this.requests.length > this.MAX_REQUESTS) this.requests.shift();
40
+ this.totalRequests++;
41
+ this.totalResponseTime += responseTimeMs;
42
+ if (isError) this.totalErrors++;
43
+ }
44
+ /**
45
+ * Get current metrics
46
+ *
47
+ * Returns metrics for:
48
+ * - All time (since service start)
49
+ * - Last hour (recent activity)
50
+ */
51
+ getMetrics() {
52
+ const oneHourAgo = Date.now() - this.DATA_RETENTION_MS;
53
+ const recentRequests = this.requests.filter((r) => r.timestamp >= oneHourAgo);
54
+ const avgResponseTime = recentRequests.length > 0 ? recentRequests.reduce((sum, r) => sum + r.responseTime, 0) / recentRequests.length : 0;
55
+ const recentErrors = recentRequests.filter((r) => r.isError).length;
56
+ const errorRate = recentRequests.length > 0 ? recentErrors / recentRequests.length * 100 : 0;
57
+ return {
58
+ avgResponseTime: Math.round(avgResponseTime),
59
+ errorRate: parseFloat(errorRate.toFixed(2)),
60
+ totalRequests: this.totalRequests,
61
+ requestsLastHour: recentRequests.length,
62
+ errorsLastHour: recentErrors
63
+ };
64
+ }
65
+ /**
66
+ * Get metrics for a specific time window
67
+ *
68
+ * @param windowMs - Time window in milliseconds
69
+ * @returns Metrics for the specified time window
70
+ */
71
+ getMetricsForWindow(windowMs) {
72
+ const windowStart = Date.now() - windowMs;
73
+ const windowRequests = this.requests.filter((r) => r.timestamp >= windowStart);
74
+ const avgResponseTime = windowRequests.length > 0 ? windowRequests.reduce((sum, r) => sum + r.responseTime, 0) / windowRequests.length : 0;
75
+ const windowErrors = windowRequests.filter((r) => r.isError).length;
76
+ const errorRate = windowRequests.length > 0 ? windowErrors / windowRequests.length * 100 : 0;
77
+ return {
78
+ avgResponseTime: Math.round(avgResponseTime),
79
+ errorRate: parseFloat(errorRate.toFixed(2)),
80
+ totalRequests: windowRequests.length,
81
+ requestsLastHour: windowRequests.length,
82
+ errorsLastHour: windowErrors
83
+ };
84
+ }
85
+ /**
86
+ * Reset all metrics (useful for testing)
87
+ */
88
+ reset() {
89
+ this.requests = [];
90
+ this.totalRequests = 0;
91
+ this.totalErrors = 0;
92
+ this.totalResponseTime = 0;
93
+ }
94
+ /**
95
+ * Start automatic cleanup timer
96
+ * Removes metrics older than DATA_RETENTION_MS to prevent memory leaks
97
+ */
98
+ startCleanupTimer() {
99
+ this.cleanupInterval = setInterval(() => {
100
+ this.cleanup();
101
+ }, this.CLEANUP_INTERVAL_MS);
102
+ }
103
+ /**
104
+ * Stop automatic cleanup timer (useful for testing or shutdown)
105
+ */
106
+ stopCleanupTimer() {
107
+ if (this.cleanupInterval) {
108
+ clearInterval(this.cleanupInterval);
109
+ this.cleanupInterval = null;
110
+ }
111
+ }
112
+ /**
113
+ * Remove metrics older than DATA_RETENTION_MS
114
+ */
115
+ cleanup() {
116
+ const cutoff = Date.now() - this.DATA_RETENTION_MS;
117
+ const initialLength = this.requests.length;
118
+ this.requests = this.requests.filter((r) => r.timestamp >= cutoff);
119
+ if (initialLength - this.requests.length > 0) {}
120
+ }
121
+ /**
122
+ * Get detailed statistics (useful for debugging)
123
+ */
124
+ getStatistics() {
125
+ const now = Date.now();
126
+ const oldest = this.requests[0];
127
+ const newest = this.requests[this.requests.length - 1];
128
+ return {
129
+ bufferSize: this.requests.length,
130
+ oldestMetricAge: oldest ? now - oldest.timestamp : 0,
131
+ newestMetricAge: newest ? now - newest.timestamp : 0,
132
+ globalStats: {
133
+ totalRequests: this.totalRequests,
134
+ totalErrors: this.totalErrors,
135
+ avgResponseTime: this.totalRequests > 0 ? Math.round(this.totalResponseTime / this.totalRequests) : 0,
136
+ errorRate: this.totalRequests > 0 ? parseFloat((this.totalErrors / this.totalRequests * 100).toFixed(2)) : 0
137
+ }
138
+ };
139
+ }
140
+ };
141
+ const metricsCollector = MetricsCollector.getInstance();
142
+
143
+ // src/observability/elysia-middleware.ts
144
+ /**
145
+ * Elysia Metrics Middleware
146
+ *
147
+ * Elysia plugin for collecting request/response metrics.
148
+ * This is a generalizable module for all Burdenoff products.
149
+ *
150
+ * What it tracks:
151
+ * - Request count (total and per time window)
152
+ * - Response time (average across all requests)
153
+ * - Error rate (percentage of requests that failed)
154
+ *
155
+ * How it works:
156
+ * - `onRequest` hook: Records request start time
157
+ * - `onAfterHandle` hook: Calculates response time, records metrics
158
+ * - `onError` hook: Marks request as error
159
+ *
160
+ * Integration:
161
+ * Metrics are collected by MetricsCollector service and can be queried by:
162
+ * - ActivityAnalyticsService (for analytics dashboard)
163
+ * - Health check endpoints
164
+ * - Monitoring tools (future: Prometheus exporter)
165
+ *
166
+ * @example
167
+ * ```typescript
168
+ * import { createMetricsPlugin } from '@burdenoff/be-sdk';
169
+ *
170
+ * const app = new Elysia()
171
+ * .use(createMetricsPlugin({
172
+ * slowRequestThreshold: 2000, // Log requests slower than 2s
173
+ * enableDetailedLogging: true,
174
+ * }));
175
+ * ```
176
+ */
177
+ /**
178
+ * Default configuration for metrics middleware
179
+ */
180
+ const DEFAULT_CONFIG = {
181
+ slowRequestThreshold: 1e3,
182
+ enableDetailedLogging: false
183
+ };
184
+ /**
185
+ * Create Elysia metrics plugin
186
+ *
187
+ * Registers Elysia hooks to track request metrics:
188
+ * - Response time
189
+ * - Error rate
190
+ * - Request count
191
+ *
192
+ * @param config - Configuration options
193
+ * @returns Elysia plugin instance
194
+ */
195
+ function createMetricsPlugin(config) {
196
+ const finalConfig = {
197
+ ...DEFAULT_CONFIG,
198
+ ...config
199
+ };
200
+ return new Elysia({ name: "metrics" }).derive(() => ({
201
+ requestStartTime: 0,
202
+ requestHasError: false
203
+ })).onRequest(({ request, store }) => {
204
+ const metricsStore = store;
205
+ metricsStore.requestStartTime = Date.now();
206
+ metricsStore.requestHasError = false;
207
+ if (finalConfig.enableDetailedLogging) {
208
+ const url = new URL(request.url);
209
+ logger.debug("[Metrics] Request started", {
210
+ method: request.method,
211
+ url: url.pathname
212
+ });
213
+ }
214
+ }).onError(({ request, error, store }) => {
215
+ const metricsStore = store;
216
+ metricsStore.requestHasError = true;
217
+ const url = new URL(request.url);
218
+ const errorMessage = error instanceof Error ? error.message : String(error);
219
+ logger.debug("[Metrics] Request error", {
220
+ method: request.method,
221
+ url: url.pathname,
222
+ error: errorMessage
223
+ });
224
+ }).onAfterHandle(({ request, store, set }) => {
225
+ const metricsStore = store;
226
+ const startTime = metricsStore.requestStartTime;
227
+ if (!startTime) return;
228
+ const responseTime = Date.now() - startTime;
229
+ const hasError = metricsStore.requestHasError || false;
230
+ metricsCollector.recordRequest(responseTime, hasError);
231
+ const url = new URL(request.url);
232
+ if (responseTime > finalConfig.slowRequestThreshold) logger.warn("[Metrics] Slow request detected", {
233
+ method: request.method,
234
+ url: url.pathname,
235
+ responseTime: `${responseTime}ms`,
236
+ statusCode: set.status || 200,
237
+ threshold: `${finalConfig.slowRequestThreshold}ms`
238
+ });
239
+ if (finalConfig.enableDetailedLogging) logger.debug("[Metrics] Request completed", {
240
+ method: request.method,
241
+ url: url.pathname,
242
+ responseTime: `${responseTime}ms`,
243
+ statusCode: set.status || 200,
244
+ hasError
245
+ });
246
+ });
247
+ }
248
+ /**
249
+ * Get current metrics (utility function)
250
+ */
251
+ function getCurrentMetrics() {
252
+ return metricsCollector.getMetrics();
253
+ }
254
+ /**
255
+ * Get metrics for a specific time window (utility function)
256
+ */
257
+ function getMetricsForWindow(windowMs) {
258
+ return metricsCollector.getMetricsForWindow(windowMs);
259
+ }
260
+ logger.debug("[Metrics] Metrics middleware module loaded");
261
+
262
+ // src/observability/index.ts
263
+ var observability_exports = /* @__PURE__ */ __exportAll({
264
+ MetricsCollector: () => MetricsCollector,
265
+ createMetricsPlugin: () => createMetricsPlugin,
266
+ getCurrentMetrics: () => getCurrentMetrics,
267
+ getMetricsForWindow: () => getMetricsForWindow,
268
+ metricsCollector: () => metricsCollector
269
+ });
270
+
271
+ export { MetricsCollector as a, getMetricsForWindow as i, createMetricsPlugin as n, metricsCollector as o, getCurrentMetrics as r, observability_exports as t };
272
+ //# sourceMappingURL=observability-DBDXipTU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"observability-DBDXipTU.js","names":[],"sources":["../src/observability/metrics.ts","../src/observability/elysia-middleware.ts","../src/observability/index.ts"],"sourcesContent":["/**\n * Metrics Collection Module\n *\n * In-memory metrics collection for API monitoring and analytics.\n * This is a generalizable module for all Burdenoff products.\n *\n * Features:\n * - Request counting (total requests)\n * - Response time tracking (average response time)\n * - Error rate calculation (percentage of failed requests)\n * - Time-windowed metrics (last hour, last day, etc.)\n *\n * Architecture:\n * - Uses circular buffers to maintain recent metrics\n * - Automatically prunes old data to prevent memory leaks\n * - Thread-safe for concurrent request handling\n *\n * Future Enhancements:\n * - Replace with OpenTelemetry for distributed tracing\n * - Integrate Prometheus for metrics export\n * - Add per-endpoint metrics breakdown\n * - Persist metrics to ClickHouse for long-term storage\n *\n * @example\n * ```typescript\n * import { MetricsCollector } from '@burdenoff/be-sdk';\n *\n * const metrics = MetricsCollector.getInstance();\n *\n * // Record a successful request\n * metrics.recordRequest(150, false);\n *\n * // Record a failed request\n * metrics.recordRequest(50, true);\n *\n * // Get current metrics\n * const current = metrics.getMetrics();\n * console.log('Avg response time:', current.avgResponseTime);\n * console.log('Error rate:', current.errorRate);\n * ```\n */\n\ninterface RequestMetric {\n timestamp: number;\n responseTime: number;\n isError: boolean;\n}\n\nexport interface Metrics {\n avgResponseTime: number;\n errorRate: number;\n totalRequests: number;\n requestsLastHour: number;\n errorsLastHour: number;\n}\n\nexport class MetricsCollector {\n private static instance: MetricsCollector | null = null;\n\n // Circular buffer of recent requests (last 10,000 requests or 1 hour, whichever is smaller)\n private requests: RequestMetric[] = [];\n private readonly MAX_REQUESTS = 10000;\n\n // Global counters (since service start)\n private totalRequests = 0;\n private totalErrors = 0;\n private totalResponseTime = 0;\n\n // Cleanup interval\n private cleanupInterval: NodeJS.Timeout | null = null;\n private readonly CLEANUP_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\n private readonly DATA_RETENTION_MS = 60 * 60 * 1000; // 1 hour\n\n private constructor() {\n // Private constructor for singleton\n this.startCleanupTimer();\n }\n\n /**\n * Get singleton instance\n */\n static getInstance(): MetricsCollector {\n if (!MetricsCollector.instance) {\n MetricsCollector.instance = new MetricsCollector();\n }\n return MetricsCollector.instance;\n }\n\n /**\n * Record a request metric\n *\n * @param responseTimeMs - Response time in milliseconds\n * @param isError - Whether the request resulted in an error\n */\n recordRequest(responseTimeMs: number, isError: boolean): void {\n const metric: RequestMetric = {\n timestamp: Date.now(),\n responseTime: responseTimeMs,\n isError,\n };\n\n // Add to circular buffer\n this.requests.push(metric);\n if (this.requests.length > this.MAX_REQUESTS) {\n this.requests.shift(); // Remove oldest\n }\n\n // Update global counters\n this.totalRequests++;\n this.totalResponseTime += responseTimeMs;\n if (isError) {\n this.totalErrors++;\n }\n }\n\n /**\n * Get current metrics\n *\n * Returns metrics for:\n * - All time (since service start)\n * - Last hour (recent activity)\n */\n getMetrics(): Metrics {\n const now = Date.now();\n const oneHourAgo = now - this.DATA_RETENTION_MS;\n\n // Filter requests from last hour\n const recentRequests = this.requests.filter((r) => r.timestamp >= oneHourAgo);\n\n // Calculate average response time (last hour)\n const avgResponseTime =\n recentRequests.length > 0\n ? recentRequests.reduce((sum, r) => sum + r.responseTime, 0) / recentRequests.length\n : 0;\n\n // Calculate error rate (last hour)\n const recentErrors = recentRequests.filter((r) => r.isError).length;\n const errorRate = recentRequests.length > 0 ? (recentErrors / recentRequests.length) * 100 : 0;\n\n return {\n avgResponseTime: Math.round(avgResponseTime), // Round to nearest ms\n errorRate: parseFloat(errorRate.toFixed(2)), // Round to 2 decimal places\n totalRequests: this.totalRequests,\n requestsLastHour: recentRequests.length,\n errorsLastHour: recentErrors,\n };\n }\n\n /**\n * Get metrics for a specific time window\n *\n * @param windowMs - Time window in milliseconds\n * @returns Metrics for the specified time window\n */\n getMetricsForWindow(windowMs: number): Metrics {\n const now = Date.now();\n const windowStart = now - windowMs;\n\n // Filter requests within window\n const windowRequests = this.requests.filter((r) => r.timestamp >= windowStart);\n\n // Calculate average response time\n const avgResponseTime =\n windowRequests.length > 0\n ? windowRequests.reduce((sum, r) => sum + r.responseTime, 0) / windowRequests.length\n : 0;\n\n // Calculate error rate\n const windowErrors = windowRequests.filter((r) => r.isError).length;\n const errorRate = windowRequests.length > 0 ? (windowErrors / windowRequests.length) * 100 : 0;\n\n return {\n avgResponseTime: Math.round(avgResponseTime),\n errorRate: parseFloat(errorRate.toFixed(2)),\n totalRequests: windowRequests.length,\n requestsLastHour: windowRequests.length,\n errorsLastHour: windowErrors,\n };\n }\n\n /**\n * Reset all metrics (useful for testing)\n */\n reset(): void {\n this.requests = [];\n this.totalRequests = 0;\n this.totalErrors = 0;\n this.totalResponseTime = 0;\n }\n\n /**\n * Start automatic cleanup timer\n * Removes metrics older than DATA_RETENTION_MS to prevent memory leaks\n */\n private startCleanupTimer(): void {\n this.cleanupInterval = setInterval(() => {\n this.cleanup();\n }, this.CLEANUP_INTERVAL_MS);\n }\n\n /**\n * Stop automatic cleanup timer (useful for testing or shutdown)\n */\n stopCleanupTimer(): void {\n if (this.cleanupInterval) {\n clearInterval(this.cleanupInterval);\n this.cleanupInterval = null;\n }\n }\n\n /**\n * Remove metrics older than DATA_RETENTION_MS\n */\n private cleanup(): void {\n const now = Date.now();\n const cutoff = now - this.DATA_RETENTION_MS;\n const initialLength = this.requests.length;\n\n this.requests = this.requests.filter((r) => r.timestamp >= cutoff);\n\n const removedCount = initialLength - this.requests.length;\n if (removedCount > 0) {\n // Metrics cleaned up\n }\n }\n\n /**\n * Get detailed statistics (useful for debugging)\n */\n getStatistics(): {\n bufferSize: number;\n oldestMetricAge: number;\n newestMetricAge: number;\n globalStats: {\n totalRequests: number;\n totalErrors: number;\n avgResponseTime: number;\n errorRate: number;\n };\n } {\n const now = Date.now();\n const oldest = this.requests[0];\n const newest = this.requests[this.requests.length - 1];\n\n return {\n bufferSize: this.requests.length,\n oldestMetricAge: oldest ? now - oldest.timestamp : 0,\n newestMetricAge: newest ? now - newest.timestamp : 0,\n globalStats: {\n totalRequests: this.totalRequests,\n totalErrors: this.totalErrors,\n avgResponseTime: this.totalRequests > 0 ? Math.round(this.totalResponseTime / this.totalRequests) : 0,\n errorRate: this.totalRequests > 0 ? parseFloat(((this.totalErrors / this.totalRequests) * 100).toFixed(2)) : 0,\n },\n };\n }\n}\n\n// Export singleton instance\nexport const metricsCollector = MetricsCollector.getInstance();\n","/**\n * Elysia Metrics Middleware\n *\n * Elysia plugin for collecting request/response metrics.\n * This is a generalizable module for all Burdenoff products.\n *\n * What it tracks:\n * - Request count (total and per time window)\n * - Response time (average across all requests)\n * - Error rate (percentage of requests that failed)\n *\n * How it works:\n * - `onRequest` hook: Records request start time\n * - `onAfterHandle` hook: Calculates response time, records metrics\n * - `onError` hook: Marks request as error\n *\n * Integration:\n * Metrics are collected by MetricsCollector service and can be queried by:\n * - ActivityAnalyticsService (for analytics dashboard)\n * - Health check endpoints\n * - Monitoring tools (future: Prometheus exporter)\n *\n * @example\n * ```typescript\n * import { createMetricsPlugin } from '@burdenoff/be-sdk';\n *\n * const app = new Elysia()\n * .use(createMetricsPlugin({\n * slowRequestThreshold: 2000, // Log requests slower than 2s\n * enableDetailedLogging: true,\n * }));\n * ```\n */\n\nimport { Elysia, type AnyElysia } from 'elysia';\nimport { logger } from '../logger/index.js';\nimport type { MetricsMiddlewareConfig } from '../middleware/types.js';\nimport { metricsCollector } from './metrics.js';\n\n/**\n * Default configuration for metrics middleware\n */\nconst DEFAULT_CONFIG: Required<MetricsMiddlewareConfig> = {\n slowRequestThreshold: 1000, // 1 second\n enableDetailedLogging: false,\n};\n\n/**\n * Create Elysia metrics plugin\n *\n * Registers Elysia hooks to track request metrics:\n * - Response time\n * - Error rate\n * - Request count\n *\n * @param config - Configuration options\n * @returns Elysia plugin instance\n */\nexport function createMetricsPlugin(config?: MetricsMiddlewareConfig): AnyElysia {\n const finalConfig = { ...DEFAULT_CONFIG, ...config };\n\n return (\n new Elysia({ name: 'metrics' })\n // Store request start time and error status\n .derive(() => ({\n requestStartTime: 0,\n requestHasError: false,\n }))\n // Record request start time\n .onRequest(({ request, store }) => {\n const metricsStore = store as { requestStartTime: number; requestHasError: boolean };\n metricsStore.requestStartTime = Date.now();\n metricsStore.requestHasError = false;\n\n if (finalConfig.enableDetailedLogging) {\n const url = new URL(request.url);\n logger.debug('[Metrics] Request started', {\n method: request.method,\n url: url.pathname,\n });\n }\n })\n // Handle errors\n .onError(({ request, error, store }) => {\n const metricsStore = store as { requestHasError: boolean };\n metricsStore.requestHasError = true;\n\n const url = new URL(request.url);\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.debug('[Metrics] Request error', {\n method: request.method,\n url: url.pathname,\n error: errorMessage,\n });\n })\n // Record metrics after response\n .onAfterHandle(({ request, store, set }) => {\n const metricsStore = store as { requestStartTime: number; requestHasError: boolean };\n const startTime = metricsStore.requestStartTime;\n\n if (!startTime) {\n return;\n }\n\n const responseTime = Date.now() - startTime;\n const hasError = metricsStore.requestHasError || false;\n\n // Record metrics\n metricsCollector.recordRequest(responseTime, hasError);\n\n const url = new URL(request.url);\n\n // Log slow requests based on configured threshold\n if (responseTime > finalConfig.slowRequestThreshold) {\n logger.warn('[Metrics] Slow request detected', {\n method: request.method,\n url: url.pathname,\n responseTime: `${responseTime}ms`,\n statusCode: set.status || 200,\n threshold: `${finalConfig.slowRequestThreshold}ms`,\n });\n }\n\n if (finalConfig.enableDetailedLogging) {\n logger.debug('[Metrics] Request completed', {\n method: request.method,\n url: url.pathname,\n responseTime: `${responseTime}ms`,\n statusCode: set.status || 200,\n hasError,\n });\n }\n })\n );\n}\n\n/**\n * Get current metrics (utility function)\n */\nexport function getCurrentMetrics(): {\n avgResponseTime: number;\n errorRate: number;\n totalRequests: number;\n requestsLastHour: number;\n errorsLastHour: number;\n} {\n return metricsCollector.getMetrics();\n}\n\n/**\n * Get metrics for a specific time window (utility function)\n */\nexport function getMetricsForWindow(windowMs: number): {\n avgResponseTime: number;\n errorRate: number;\n totalRequests: number;\n requestsLastHour: number;\n errorsLastHour: number;\n} {\n return metricsCollector.getMetricsForWindow(windowMs);\n}\n\n// Log when metrics middleware is loaded\nlogger.debug('[Metrics] Metrics middleware module loaded');\n","/**\n * Observability Module\n *\n * Provides metrics collection and monitoring capabilities for Burdenoff products.\n * Uses Elysia plugins for request/response tracking.\n *\n * @module observability\n */\n\nexport { MetricsCollector, metricsCollector } from './metrics.js';\nexport type { Metrics } from './metrics.js';\n\nexport { createMetricsPlugin, getCurrentMetrics, getMetricsForWindow } from './elysia-middleware.js';\n"],"mappings":";;;;;AAwDA,I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Ae,KAAK,IAAI,IAAI;EAClC,MAAM,WAAW,aAAa,mBAAmB;EAGjD,iBAAiB,cAAc,cAAc,QAAQ;EAErD,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAG/B,IAAI,eAAe,YAAY,sBAC7B,OAAO,KAAK,mCAAmC;GAC7C,QAAQ,QAAQ;GAChB,KAAK,IAAI;GACT,cAAc,GAAG,aAAa;GAC9B,YAAY,IAAI,UAAU;GAC1B,WAAW,GAAG,YAAY,qBAAqB;EACjD,CAAC;EAGH,IAAI,YAAY,uBACd,OAAO,MAAM,+BAA+B;GAC1C,QAAQ,QAAQ;GAChB,KAAK,IAAI;GACT,cAAc,GAAG,aAAa;GAC9B,YAAY,IAAI,UAAU;GAC1B;EACF,CAAC;CAEL,CAAC;AAEP;;;;AAKA,SAAgB,oBAMd;CACA,OAAO,iBAAiB,WAAW;AACrC;;;;AAKA,SAAgB,oBAAoB,UAMlC;CACA,OAAO,iBAAiB,oBAAoB,QAAQ;AACtD;AAGA,OAAO,MAAM,4CAA4C"}
@@ -0,0 +1,144 @@
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-CUDyhibV.js";
2
+ import { p as SDKContext } from "../index-CTTwo9av.js";
3
+ export declare enum PaymentStatus {
4
+ PENDING = "pending",
5
+ PROCESSING = "processing",
6
+ SUCCEEDED = "succeeded",
7
+ FAILED = "failed",
8
+ CANCELLED = "cancelled",
9
+ REFUNDED = "refunded"
10
+ }
11
+ export declare enum PaymentMethod {
12
+ CREDIT_CARD = "credit_card",
13
+ DEBIT_CARD = "debit_card",
14
+ BANK_TRANSFER = "bank_transfer",
15
+ UPI = "upi",
16
+ WALLET = "wallet",
17
+ PAYPAL = "paypal",
18
+ STRIPE = "stripe"
19
+ }
20
+ export declare enum SubscriptionStatus {
21
+ ACTIVE = "active",
22
+ INACTIVE = "inactive",
23
+ CANCELLED = "cancelled",
24
+ EXPIRED = "expired",
25
+ PAST_DUE = "past_due",
26
+ TRIALING = "trialing"
27
+ }
28
+ export interface CreatePaymentOptions {
29
+ amount: number;
30
+ currency: string;
31
+ paymentMethod: PaymentMethod;
32
+ customerId: string;
33
+ description?: string;
34
+ metadata?: Record<string, unknown>;
35
+ workspaceId?: string;
36
+ organizationId?: string;
37
+ }
38
+ export interface Payment {
39
+ id: string;
40
+ amount: number;
41
+ currency: string;
42
+ status: PaymentStatus;
43
+ paymentMethod: PaymentMethod;
44
+ customerId: string;
45
+ description?: string;
46
+ metadata?: Record<string, unknown>;
47
+ workspaceId?: string;
48
+ organizationId?: string;
49
+ transactionId?: string;
50
+ failureReason?: string;
51
+ createdAt: string;
52
+ updatedAt: string;
53
+ }
54
+ export interface CreateSubscriptionOptions {
55
+ customerId: string;
56
+ planId: string;
57
+ paymentMethod: PaymentMethod;
58
+ trialDays?: number;
59
+ metadata?: Record<string, unknown>;
60
+ workspaceId?: string;
61
+ organizationId?: string;
62
+ }
63
+ export interface Subscription {
64
+ id: string;
65
+ customerId: string;
66
+ planId: string;
67
+ status: SubscriptionStatus;
68
+ currentPeriodStart: string;
69
+ currentPeriodEnd: string;
70
+ trialEnd?: string;
71
+ cancelledAt?: string;
72
+ endedAt?: string;
73
+ metadata?: Record<string, unknown>;
74
+ workspaceId?: string;
75
+ organizationId?: string;
76
+ createdAt: string;
77
+ updatedAt: string;
78
+ }
79
+ export interface Plan {
80
+ id: string;
81
+ name: string;
82
+ description?: string;
83
+ amount: number;
84
+ currency: string;
85
+ interval: 'day' | 'week' | 'month' | 'year';
86
+ intervalCount: number;
87
+ features?: string[];
88
+ metadata?: Record<string, unknown>;
89
+ active: boolean;
90
+ createdAt: string;
91
+ }
92
+ export interface GetPaymentsOptions {
93
+ customerId?: string;
94
+ status?: PaymentStatus;
95
+ workspaceId?: string;
96
+ organizationId?: string;
97
+ startDate?: string;
98
+ endDate?: string;
99
+ limit?: number;
100
+ offset?: number;
101
+ }
102
+ export declare class PaymentsModule {
103
+ private client;
104
+ private context;
105
+ constructor(client: BurdenoffGraphQLClient, context: SDKContext);
106
+ createPayment(options: CreatePaymentOptions): Promise<Payment>;
107
+ getPayment(paymentId: string): Promise<Payment>;
108
+ getPayments(options: GetPaymentsOptions): Promise<{
109
+ payments: Payment[];
110
+ total: number;
111
+ }>;
112
+ refundPayment(paymentId: string, amount?: number, reason?: string): Promise<Payment>;
113
+ verifyPayment(paymentId: string, verificationData: Record<string, unknown>): Promise<{
114
+ verified: boolean;
115
+ status: PaymentStatus;
116
+ }>;
117
+ createSubscription(options: CreateSubscriptionOptions): Promise<Subscription>;
118
+ getSubscription(subscriptionId: string): Promise<Subscription>;
119
+ cancelSubscription(subscriptionId: string, cancelAtPeriodEnd?: boolean): Promise<Subscription>;
120
+ getCustomerSubscriptions(customerId: string): Promise<Subscription[]>;
121
+ getPlans(activeOnly?: boolean): Promise<Plan[]>;
122
+ createPaymentIntent(options: {
123
+ amount: number;
124
+ currency: string;
125
+ customerId: string;
126
+ paymentMethod?: PaymentMethod;
127
+ metadata?: Record<string, unknown>;
128
+ }): Promise<{
129
+ clientSecret: string;
130
+ paymentIntentId: string;
131
+ }>;
132
+ getPaymentStats(options?: {
133
+ startDate?: string;
134
+ endDate?: string;
135
+ workspaceId?: string;
136
+ }): Promise<{
137
+ totalRevenue: number;
138
+ totalPayments: number;
139
+ successfulPayments: number;
140
+ failedPayments: number;
141
+ refundedAmount: number;
142
+ averagePaymentAmount: number;
143
+ }>;
144
+ }