@burdenoff/be-sdk 2026.1110.2 → 2026.1110.3

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 (469) 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/ai-credits/index.d.ts +2 -3
  8. package/dist/ai-credits/index.js +3 -4
  9. package/dist/ai-credits/index.js.map +1 -1
  10. package/dist/ai-credits-Ca-NNcVx.js +546 -0
  11. package/dist/ai-credits-Ca-NNcVx.js.map +1 -0
  12. package/dist/{assistant-session-CJZhF4D6.d.ts → assistant-session-DA5ZKJOr.d.ts} +4 -5
  13. package/dist/auth/index.d.ts +2 -77
  14. package/dist/auth/index.js +3 -7
  15. package/dist/auth/index.js.map +1 -1
  16. package/dist/auth-CEuBEBQN.js +228 -0
  17. package/dist/auth-CEuBEBQN.js.map +1 -0
  18. package/dist/cache/index.d.ts +2 -3
  19. package/dist/cache/index.js +3 -7
  20. package/dist/cache/index.js.map +1 -1
  21. package/dist/cache-CU0uLwcS.js +1837 -0
  22. package/dist/cache-CU0uLwcS.js.map +1 -0
  23. package/dist/captcha/index.d.ts +2 -1
  24. package/dist/captcha/index.js +3 -3
  25. package/dist/captcha/index.js.map +1 -1
  26. package/dist/captcha-BT7yh1YS.js +77 -0
  27. package/dist/captcha-BT7yh1YS.js.map +1 -0
  28. package/dist/client/internal-client.d.ts +4 -7
  29. package/dist/client/internal-client.js +172 -4
  30. package/dist/client/internal-client.js.map +1 -1
  31. package/dist/client-BgAEvDC2.d.ts +86 -0
  32. package/dist/client-DcZ3iGES.js +565 -0
  33. package/dist/client-DcZ3iGES.js.map +1 -0
  34. package/dist/collector-endpoint-iyQYeI50.js +50 -0
  35. package/dist/collector-endpoint-iyQYeI50.js.map +1 -0
  36. package/dist/context-CZnXf2yb.js +247 -0
  37. package/dist/context-CZnXf2yb.js.map +1 -0
  38. package/dist/crypto/index.d.ts +2 -1
  39. package/dist/crypto/index.js +3 -3
  40. package/dist/crypto/index.js.map +1 -1
  41. package/dist/crypto-DO9fM0FO.js +145 -0
  42. package/dist/crypto-DO9fM0FO.js.map +1 -0
  43. package/dist/database/index.d.ts +104 -108
  44. package/dist/database/index.js +468 -6
  45. package/dist/database/index.js.map +1 -1
  46. package/dist/dataloader/index.d.ts +2 -1
  47. package/dist/dataloader/index.js +3 -3
  48. package/dist/dataloader/index.js.map +1 -1
  49. package/dist/dataloader-DwpT3YoS.js +294 -0
  50. package/dist/dataloader-DwpT3YoS.js.map +1 -0
  51. package/dist/deployed-environment-p_Tdl3sT.js +38 -0
  52. package/dist/deployed-environment-p_Tdl3sT.js.map +1 -0
  53. package/dist/dist-BGKdXVy3.js +1718 -0
  54. package/dist/dist-BGKdXVy3.js.map +1 -0
  55. package/dist/env-DdaoGjIt.js +74 -0
  56. package/dist/env-DdaoGjIt.js.map +1 -0
  57. package/dist/event-queue/index.d.ts +2 -7
  58. package/dist/event-queue/index.js +7 -9
  59. package/dist/event-queue/index.js.map +1 -1
  60. package/dist/event-queue-Cw-YJPY_.js +1384 -0
  61. package/dist/event-queue-Cw-YJPY_.js.map +1 -0
  62. package/dist/{explicit-activity-scope-CCoxVwAr.d.ts → explicit-activity-scope-D8VeGGpt.d.ts} +1 -2
  63. package/dist/export/index.d.ts +2 -2
  64. package/dist/export/index.js +3 -14
  65. package/dist/export/index.js.map +1 -1
  66. package/dist/export-B6fphx8a.js +642 -0
  67. package/dist/export-B6fphx8a.js.map +1 -0
  68. package/dist/feature-flags/index.d.ts +2 -10
  69. package/dist/feature-flags/index.js +3 -6
  70. package/dist/feature-flags/index.js.map +1 -1
  71. package/dist/feature-flags-71oDkrUe.js +422 -0
  72. package/dist/feature-flags-71oDkrUe.js.map +1 -0
  73. package/dist/files/index.d.ts +2 -3
  74. package/dist/files/index.js +3 -4
  75. package/dist/files/index.js.map +1 -1
  76. package/dist/files-DjH0099H.js +830 -0
  77. package/dist/files-DjH0099H.js.map +1 -0
  78. package/dist/gateway/index.d.ts +4 -6
  79. package/dist/gateway/index.js +7 -13
  80. package/dist/gateway/index.js.map +1 -1
  81. package/dist/gateway/security/index.d.ts +2 -2
  82. package/dist/gateway/security/index.js +3 -5
  83. package/dist/gateway/security/index.js.map +1 -1
  84. package/dist/gateway-DBFmxWks.js +50 -0
  85. package/dist/gateway-DBFmxWks.js.map +1 -0
  86. package/dist/graph/index.d.ts +3 -10
  87. package/dist/graph/index.js +4 -13
  88. package/dist/graph/index.js.map +1 -1
  89. package/dist/graph-DDYgIryR.js +2152 -0
  90. package/dist/graph-DDYgIryR.js.map +1 -0
  91. package/dist/graph-emitter-CdOXP7Tn.js +621 -0
  92. package/dist/graph-emitter-CdOXP7Tn.js.map +1 -0
  93. package/dist/graphql/index.d.ts +3 -2
  94. package/dist/graphql/index.js +4 -6
  95. package/dist/graphql/index.js.map +1 -1
  96. package/dist/graphql/services/index.d.ts +2 -24
  97. package/dist/graphql/services/index.js +3 -4
  98. package/dist/graphql/services/index.js.map +1 -1
  99. package/dist/graphql-DHAHHcww.js +161 -0
  100. package/dist/graphql-DHAHHcww.js.map +1 -0
  101. package/dist/graphql-DNkMkGBZ.d.ts +21 -0
  102. package/dist/i18n/index.d.ts +3 -3
  103. package/dist/i18n/index.js +3 -4
  104. package/dist/i18n/index.js.map +1 -1
  105. package/dist/i18n-BBMYFd0P.js +860 -0
  106. package/dist/i18n-BBMYFd0P.js.map +1 -0
  107. package/dist/import-optional-peer-B82VYxeX.js +18 -0
  108. package/dist/import-optional-peer-B82VYxeX.js.map +1 -0
  109. package/dist/index-3KOZ1zN9.d.ts +233 -0
  110. package/dist/index-BBqooJ52.d.ts +45 -0
  111. package/dist/index-BGzMYJsm.d.ts +209 -0
  112. package/dist/index-BKwHQtHQ.d.ts +63 -0
  113. package/dist/index-BMIMnp6T.d.ts +8 -0
  114. package/dist/index-BQDsNAMR.d.ts +81 -0
  115. package/dist/index-BVOL7458.d.ts +10 -0
  116. package/dist/index-BcqQs-Uq.d.ts +69 -0
  117. package/dist/index-BeVtqGO-.d.ts +208 -0
  118. package/dist/index-BiTzGUZP.d.ts +114 -0
  119. package/dist/index-BqYfCQSP.d.ts +500 -0
  120. package/dist/index-C0qLquY0.d.ts +150 -0
  121. package/dist/index-C5uEKchX.d.ts +60 -0
  122. package/dist/index-CDOqxSIi.d.ts +37 -0
  123. package/dist/index-CG6wj66Y.d.ts +148 -0
  124. package/dist/index-CIgoeobA.d.ts +145 -0
  125. package/dist/index-CPQDMSFS.d.ts +103 -0
  126. package/dist/index-CSRcgkVi.d.ts +23 -0
  127. package/dist/index-CZTnQIRU.d.ts +341 -0
  128. package/dist/index-CaM9JUcc.d.ts +144 -0
  129. package/dist/index-CkT2aUr3.d.ts +704 -0
  130. package/dist/index-CliOgq6L.d.ts +203 -0
  131. package/dist/index-CnzbJZP7.d.ts +999 -0
  132. package/dist/index-D6UeLAye.d.ts +63 -0
  133. package/dist/index-DGgh9DWn.d.ts +59 -0
  134. package/dist/index-DY3dNhMN.d.ts +420 -0
  135. package/dist/index-DZC-2o9R.d.ts +207 -0
  136. package/dist/index-DqbGqfAy.d.ts +127 -0
  137. package/dist/index-Dt1HJPTX.d.ts +12 -0
  138. package/dist/index-DtI6aBtB.d.ts +22 -0
  139. package/dist/index-FKohsiex.d.ts +38 -0
  140. package/dist/index-FbXPfen7.d.ts +132 -0
  141. package/dist/index-MArCb8Aq.d.ts +306 -0
  142. package/dist/index-N-huORcj.d.ts +303 -0
  143. package/dist/index-YOShAwkq.d.ts +45 -0
  144. package/dist/index-bZKZUvBu.d.ts +646 -0
  145. package/dist/index-yBSjMY32.d.ts +24 -0
  146. package/dist/index.d.ts +501 -544
  147. package/dist/index.js +1820 -2171
  148. package/dist/index.js.map +1 -1
  149. package/dist/init/index.d.ts +2 -2
  150. package/dist/init/index.js +3 -16
  151. package/dist/init/index.js.map +1 -1
  152. package/dist/init-Dy3KhT6Y.js +325 -0
  153. package/dist/init-Dy3KhT6Y.js.map +1 -0
  154. package/dist/instrumentation/index.d.ts +3 -4
  155. package/dist/instrumentation/index.js +5 -5
  156. package/dist/instrumentation/index.js.map +1 -1
  157. package/dist/instrumentation-xkkmDgJ0.js +1678 -0
  158. package/dist/instrumentation-xkkmDgJ0.js.map +1 -0
  159. package/dist/lake/index.d.ts +50 -54
  160. package/dist/lake/index.js +169 -193
  161. package/dist/lake/index.js.map +1 -1
  162. package/dist/layer/index.d.ts +3 -2
  163. package/dist/layer/index.js +4 -5
  164. package/dist/layer/index.js.map +1 -1
  165. package/dist/layer-BZBZZWeV.d.ts +69 -0
  166. package/dist/layer-Bcix-WCl.js +105 -0
  167. package/dist/layer-Bcix-WCl.js.map +1 -0
  168. package/dist/layer-CEKy6cm8.js +252 -0
  169. package/dist/layer-CEKy6cm8.js.map +1 -0
  170. package/dist/lifecycle/index.d.ts +2 -1
  171. package/dist/lifecycle/index.js +3 -4
  172. package/dist/lifecycle/index.js.map +1 -1
  173. package/dist/lifecycle-DeoLSX0U.js +76 -0
  174. package/dist/lifecycle-DeoLSX0U.js.map +1 -0
  175. package/dist/logger/index.d.ts +2 -3
  176. package/dist/logger/index.js +3 -3
  177. package/dist/logger/index.js.map +1 -1
  178. package/dist/logger-B6rCpb7D.js +290 -0
  179. package/dist/logger-B6rCpb7D.js.map +1 -0
  180. package/dist/metrics/index.d.ts +13 -14
  181. package/dist/metrics/index.js +3 -4
  182. package/dist/metrics/index.js.map +1 -1
  183. package/dist/metrics-BrLwNUrb.js +52 -0
  184. package/dist/metrics-BrLwNUrb.js.map +1 -0
  185. package/dist/metrics-collector-C2eShrlW.js +922 -0
  186. package/dist/metrics-collector-C2eShrlW.js.map +1 -0
  187. package/dist/middleware/index.d.ts +3 -3
  188. package/dist/middleware/index.js +3 -4
  189. package/dist/middleware/index.js.map +1 -1
  190. package/dist/middleware-CUxJVUpD.js +1243 -0
  191. package/dist/middleware-CUxJVUpD.js.map +1 -0
  192. package/dist/middleware-Cq0zFMGp.js +253 -0
  193. package/dist/middleware-Cq0zFMGp.js.map +1 -0
  194. package/dist/notifications/index.d.ts +2 -5
  195. package/dist/notifications/index.js +3 -6
  196. package/dist/notifications/index.js.map +1 -1
  197. package/dist/notifications-CdETrtFK.js +869 -0
  198. package/dist/notifications-CdETrtFK.js.map +1 -0
  199. package/dist/observability/index.d.ts +2 -3
  200. package/dist/observability/index.js +3 -4
  201. package/dist/observability/index.js.map +1 -1
  202. package/dist/observability-DBDXipTU.js +272 -0
  203. package/dist/observability-DBDXipTU.js.map +1 -0
  204. package/dist/platform/index.d.ts +2 -1
  205. package/dist/platform/index.js +3 -5
  206. package/dist/platform/index.js.map +1 -1
  207. package/dist/platform-DZwczW7v.js +1510 -0
  208. package/dist/platform-DZwczW7v.js.map +1 -0
  209. package/dist/prisma/generator/index.d.ts +1 -1
  210. package/dist/prisma/generator/index.js +97 -84
  211. package/dist/prisma/generator/index.js.map +1 -1
  212. package/dist/prisma/index.d.ts +4 -7
  213. package/dist/prisma/index.js +5 -12
  214. package/dist/prisma/index.js.map +1 -1
  215. package/dist/prisma-BzOOdt79.js +863 -0
  216. package/dist/prisma-BzOOdt79.js.map +1 -0
  217. package/dist/prisma-extension-Cfl09swM.d.ts +172 -0
  218. package/dist/product-alias/index.d.ts +2 -1
  219. package/dist/product-alias/index.js +3 -3
  220. package/dist/product-alias/index.js.map +1 -1
  221. package/dist/product-alias-BPqtskMq.js +273 -0
  222. package/dist/product-alias-BPqtskMq.js.map +1 -0
  223. package/dist/rbac/index.d.ts +2 -122
  224. package/dist/rbac/index.js +3 -6
  225. package/dist/rbac/index.js.map +1 -1
  226. package/dist/rbac-BB9l9Xph.js +1486 -0
  227. package/dist/rbac-BB9l9Xph.js.map +1 -0
  228. package/dist/resource-caps/index.d.ts +66 -72
  229. package/dist/resource-caps/index.js +430 -5
  230. package/dist/resource-caps/index.js.map +1 -1
  231. package/dist/rolldown-runtime-ad2WFvuA.js +17 -0
  232. package/dist/sdk-Dju9o-sq.js +124 -0
  233. package/dist/sdk-Dju9o-sq.js.map +1 -0
  234. package/dist/security-DIG-95Ic.js +1647 -0
  235. package/dist/security-DIG-95Ic.js.map +1 -0
  236. package/dist/server/index.d.ts +7 -164
  237. package/dist/server/index.js +2000 -1507
  238. package/dist/server/index.js.map +1 -1
  239. package/dist/service-jwt-Bu-WNA_-.js +80 -0
  240. package/dist/service-jwt-Bu-WNA_-.js.map +1 -0
  241. package/dist/services-BWzfz7vG.js +102 -0
  242. package/dist/services-BWzfz7vG.js.map +1 -0
  243. package/dist/sharding/index.d.ts +41 -44
  244. package/dist/sharding/index.js +156 -137
  245. package/dist/sharding/index.js.map +1 -1
  246. package/dist/sharing/index.d.ts +2 -1
  247. package/dist/sharing/index.js +3 -4
  248. package/dist/sharing/index.js.map +1 -1
  249. package/dist/sharing-CflDsSJ-.js +911 -0
  250. package/dist/sharing-CflDsSJ-.js.map +1 -0
  251. package/dist/stub-BqwKn4eh.js +630 -0
  252. package/dist/stub-BqwKn4eh.js.map +1 -0
  253. package/dist/tags/index.d.ts +2 -3
  254. package/dist/tags/index.js +3 -4
  255. package/dist/tags/index.js.map +1 -1
  256. package/dist/tags-B5xpbgsk.js +868 -0
  257. package/dist/{chunk-PBZFAAOM.js.map → tags-B5xpbgsk.js.map} +1 -1
  258. package/dist/telemetry/index.d.ts +64 -76
  259. package/dist/telemetry/index.js +369 -201
  260. package/dist/telemetry/index.js.map +1 -1
  261. package/dist/temporal/index.d.ts +2 -148
  262. package/dist/temporal/index.js +3 -5
  263. package/dist/temporal/index.js.map +1 -1
  264. package/dist/temporal-B534uYK8.js +706 -0
  265. package/dist/temporal-B534uYK8.js.map +1 -0
  266. package/dist/tracker/index.d.ts +5 -11
  267. package/dist/tracker/index.js +5 -20
  268. package/dist/tracker/index.js.map +1 -1
  269. package/dist/tracker-BQVoEFUo.js +839 -0
  270. package/dist/tracker-BQVoEFUo.js.map +1 -0
  271. package/dist/types-BYMYND1L.js +44 -0
  272. package/dist/types-BYMYND1L.js.map +1 -0
  273. package/dist/types-C6EKaS3V.d.ts +106 -0
  274. package/dist/types-CWybW61E.d.ts +323 -0
  275. package/dist/types-C_yfu3XK.d.ts +34 -0
  276. package/dist/types-Cj2RWXbz.js +90 -0
  277. package/dist/types-Cj2RWXbz.js.map +1 -0
  278. package/dist/types-DgaQqvxo.d.ts +70 -0
  279. package/dist/usage/index.d.ts +2 -213
  280. package/dist/usage/index.js +3 -15
  281. package/dist/usage/index.js.map +1 -1
  282. package/dist/usage-BKFZiWQn.js +682 -0
  283. package/dist/usage-BKFZiWQn.js.map +1 -0
  284. package/dist/utils/index.d.ts +2 -1
  285. package/dist/utils/index.js +3 -3
  286. package/dist/utils/index.js.map +1 -1
  287. package/dist/utils-DL85Tnbn.js +500 -0
  288. package/dist/utils-DL85Tnbn.js.map +1 -0
  289. package/dist/validation/index.d.ts +2 -2
  290. package/dist/validation/index.js +3 -3
  291. package/dist/validation/index.js.map +1 -1
  292. package/dist/validation-CPUITdMk.js +762 -0
  293. package/dist/validation-CPUITdMk.js.map +1 -0
  294. package/dist/workspace-extension-COrC0dYi.js +979 -0
  295. package/dist/workspace-extension-COrC0dYi.js.map +1 -0
  296. package/dist/{workspace-extension-BGwTOV_r.d.ts → workspace-extension-DTFTdGVF.d.ts} +43 -45
  297. package/package.json +7 -10
  298. package/dist/EventQueueFactory-GXC3A7DH.js +0 -8
  299. package/dist/EventQueueFactory-GXC3A7DH.js.map +0 -1
  300. package/dist/chunk-4XIBXZ6J.js +0 -276
  301. package/dist/chunk-4XIBXZ6J.js.map +0 -1
  302. package/dist/chunk-554Z4C2K.js +0 -1006
  303. package/dist/chunk-554Z4C2K.js.map +0 -1
  304. package/dist/chunk-5CAFHK2Z.js +0 -107
  305. package/dist/chunk-5CAFHK2Z.js.map +0 -1
  306. package/dist/chunk-63ZXJ42X.js +0 -451
  307. package/dist/chunk-63ZXJ42X.js.map +0 -1
  308. package/dist/chunk-6XEXJATV.js +0 -304
  309. package/dist/chunk-6XEXJATV.js.map +0 -1
  310. package/dist/chunk-726AR6Q7.js +0 -1532
  311. package/dist/chunk-726AR6Q7.js.map +0 -1
  312. package/dist/chunk-A5F6Z5UE.js +0 -21
  313. package/dist/chunk-A5F6Z5UE.js.map +0 -1
  314. package/dist/chunk-A6DE32ZS.js +0 -1507
  315. package/dist/chunk-A6DE32ZS.js.map +0 -1
  316. package/dist/chunk-AXJDGQPE.js +0 -690
  317. package/dist/chunk-AXJDGQPE.js.map +0 -1
  318. package/dist/chunk-BJQOGOVW.js +0 -602
  319. package/dist/chunk-BJQOGOVW.js.map +0 -1
  320. package/dist/chunk-CFXWH2IS.js +0 -52
  321. package/dist/chunk-CFXWH2IS.js.map +0 -1
  322. package/dist/chunk-DRWH5XCJ.js +0 -876
  323. package/dist/chunk-DRWH5XCJ.js.map +0 -1
  324. package/dist/chunk-E4QNLVY4.js +0 -909
  325. package/dist/chunk-E4QNLVY4.js.map +0 -1
  326. package/dist/chunk-EBDHIL7V.js +0 -774
  327. package/dist/chunk-EBDHIL7V.js.map +0 -1
  328. package/dist/chunk-ELU7VL3E.js +0 -245
  329. package/dist/chunk-ELU7VL3E.js.map +0 -1
  330. package/dist/chunk-FZRODKIN.js +0 -31
  331. package/dist/chunk-FZRODKIN.js.map +0 -1
  332. package/dist/chunk-GCIB76AJ.js +0 -882
  333. package/dist/chunk-GCIB76AJ.js.map +0 -1
  334. package/dist/chunk-HC6MPUIH.js +0 -1571
  335. package/dist/chunk-HC6MPUIH.js.map +0 -1
  336. package/dist/chunk-HNMHPSAM.js +0 -272
  337. package/dist/chunk-HNMHPSAM.js.map +0 -1
  338. package/dist/chunk-HTLEGD3Q.js +0 -1480
  339. package/dist/chunk-HTLEGD3Q.js.map +0 -1
  340. package/dist/chunk-I3KOWRT3.js +0 -89
  341. package/dist/chunk-I3KOWRT3.js.map +0 -1
  342. package/dist/chunk-ID3WR4JS.js +0 -509
  343. package/dist/chunk-ID3WR4JS.js.map +0 -1
  344. package/dist/chunk-JS52ZHTK.js +0 -1346
  345. package/dist/chunk-JS52ZHTK.js.map +0 -1
  346. package/dist/chunk-JVMAQOA3.js +0 -521
  347. package/dist/chunk-JVMAQOA3.js.map +0 -1
  348. package/dist/chunk-KH4TRQCO.js +0 -1063
  349. package/dist/chunk-KH4TRQCO.js.map +0 -1
  350. package/dist/chunk-KJOSPVB2.js +0 -57
  351. package/dist/chunk-KJOSPVB2.js.map +0 -1
  352. package/dist/chunk-KO2ZXZ7W.js +0 -61
  353. package/dist/chunk-KO2ZXZ7W.js.map +0 -1
  354. package/dist/chunk-KS2HQCJR.js +0 -56
  355. package/dist/chunk-KS2HQCJR.js.map +0 -1
  356. package/dist/chunk-LA5KPWZ2.js +0 -413
  357. package/dist/chunk-LA5KPWZ2.js.map +0 -1
  358. package/dist/chunk-MESLAC5W.js +0 -574
  359. package/dist/chunk-MESLAC5W.js.map +0 -1
  360. package/dist/chunk-MWPYA2HD.js +0 -94
  361. package/dist/chunk-MWPYA2HD.js.map +0 -1
  362. package/dist/chunk-NUB5GQTU.js +0 -270
  363. package/dist/chunk-NUB5GQTU.js.map +0 -1
  364. package/dist/chunk-OBBCR6WY.js +0 -277
  365. package/dist/chunk-OBBCR6WY.js.map +0 -1
  366. package/dist/chunk-OQDSAOG3.js +0 -1908
  367. package/dist/chunk-OQDSAOG3.js.map +0 -1
  368. package/dist/chunk-OXNCBE7P.js +0 -971
  369. package/dist/chunk-OXNCBE7P.js.map +0 -1
  370. package/dist/chunk-PBZFAAOM.js +0 -941
  371. package/dist/chunk-PN6GIF3R.js +0 -1185
  372. package/dist/chunk-PN6GIF3R.js.map +0 -1
  373. package/dist/chunk-PYD44IHJ.js +0 -728
  374. package/dist/chunk-PYD44IHJ.js.map +0 -1
  375. package/dist/chunk-QVPIACWD.js +0 -679
  376. package/dist/chunk-QVPIACWD.js.map +0 -1
  377. package/dist/chunk-QWNNFE4P.js +0 -41
  378. package/dist/chunk-QWNNFE4P.js.map +0 -1
  379. package/dist/chunk-RU266375.js +0 -327
  380. package/dist/chunk-RU266375.js.map +0 -1
  381. package/dist/chunk-RYTSVGGA.js +0 -1624
  382. package/dist/chunk-RYTSVGGA.js.map +0 -1
  383. package/dist/chunk-RZOFS2BQ.js +0 -225
  384. package/dist/chunk-RZOFS2BQ.js.map +0 -1
  385. package/dist/chunk-SBS4S2PJ.js +0 -100
  386. package/dist/chunk-SBS4S2PJ.js.map +0 -1
  387. package/dist/chunk-SPRG6G6G.js +0 -530
  388. package/dist/chunk-SPRG6G6G.js.map +0 -1
  389. package/dist/chunk-STWFX5E2.js +0 -233
  390. package/dist/chunk-STWFX5E2.js.map +0 -1
  391. package/dist/chunk-UNASM5VJ.js +0 -419
  392. package/dist/chunk-UNASM5VJ.js.map +0 -1
  393. package/dist/chunk-VAT66FJA.js +0 -245
  394. package/dist/chunk-VAT66FJA.js.map +0 -1
  395. package/dist/chunk-VFCMR5GX.js +0 -49
  396. package/dist/chunk-VFCMR5GX.js.map +0 -1
  397. package/dist/chunk-VGAHZKNJ.js +0 -66
  398. package/dist/chunk-VGAHZKNJ.js.map +0 -1
  399. package/dist/chunk-VTJTAAXC.js +0 -627
  400. package/dist/chunk-VTJTAAXC.js.map +0 -1
  401. package/dist/chunk-VXVLKRU6.js +0 -758
  402. package/dist/chunk-VXVLKRU6.js.map +0 -1
  403. package/dist/chunk-WWUU5ETI.js +0 -163
  404. package/dist/chunk-WWUU5ETI.js.map +0 -1
  405. package/dist/chunk-XE4OXN2W.js +0 -10
  406. package/dist/chunk-XE4OXN2W.js.map +0 -1
  407. package/dist/chunk-XOJORS75.js +0 -1853
  408. package/dist/chunk-XOJORS75.js.map +0 -1
  409. package/dist/chunk-YMZEUTD2.js +0 -110
  410. package/dist/chunk-YMZEUTD2.js.map +0 -1
  411. package/dist/chunk-Z77BTSOK.js +0 -617
  412. package/dist/chunk-Z77BTSOK.js.map +0 -1
  413. package/dist/chunk-ZZK3WEDI.js +0 -181
  414. package/dist/chunk-ZZK3WEDI.js.map +0 -1
  415. package/dist/client-CCXpAZ2r.d.ts +0 -89
  416. package/dist/client-DSI_760t.d.ts +0 -36
  417. package/dist/client-JU6T3UPB.js +0 -11
  418. package/dist/client-JU6T3UPB.js.map +0 -1
  419. package/dist/dist-2X4Q7PJA.js +0 -1491
  420. package/dist/dist-2X4Q7PJA.js.map +0 -1
  421. package/dist/env-4UWSUS64.js +0 -4
  422. package/dist/env-4UWSUS64.js.map +0 -1
  423. package/dist/graph-emitter-r5TylDBm.d.ts +0 -47
  424. package/dist/graphql-CMHMQjvd.d.ts +0 -23
  425. package/dist/i18n-Qm2AkPC-.d.ts +0 -33
  426. package/dist/index--yvpa6ay.d.ts +0 -83
  427. package/dist/index-4gKQKZ2B.d.ts +0 -71
  428. package/dist/index-5x0XMKXN.d.ts +0 -149
  429. package/dist/index-B70b5mYS.d.ts +0 -33
  430. package/dist/index-B8KrxO4j.d.ts +0 -755
  431. package/dist/index-BOuDKnqD.d.ts +0 -201
  432. package/dist/index-BTMt4OjA.d.ts +0 -201
  433. package/dist/index-BejbszA7.d.ts +0 -39
  434. package/dist/index-BkeOYZye.d.ts +0 -198
  435. package/dist/index-BuAj5nXg.d.ts +0 -83
  436. package/dist/index-BvkVcW8I.d.ts +0 -349
  437. package/dist/index-CWmH_-RZ.d.ts +0 -247
  438. package/dist/index-CbgWNcus.d.ts +0 -258
  439. package/dist/index-CmfPeQza.d.ts +0 -166
  440. package/dist/index-CmpG-zak.d.ts +0 -607
  441. package/dist/index-CoMKgL-p.d.ts +0 -12
  442. package/dist/index-D8HGwglK.d.ts +0 -541
  443. package/dist/index-DCaVm66D.d.ts +0 -1101
  444. package/dist/index-DE2w7E0d.d.ts +0 -83
  445. package/dist/index-DSOpj8DI.d.ts +0 -17
  446. package/dist/index-DW9q22GH.d.ts +0 -75
  447. package/dist/index-DnjJ9CwI.d.ts +0 -347
  448. package/dist/index-DwMJZ8PP.d.ts +0 -317
  449. package/dist/index-PaojfSdd.d.ts +0 -71
  450. package/dist/index-aHtYvc3i.d.ts +0 -284
  451. package/dist/index-e_18DzAg.d.ts +0 -18
  452. package/dist/index-ffmipXSA.d.ts +0 -55
  453. package/dist/index-joONjwLt.d.ts +0 -33
  454. package/dist/index-kssw5ziY.d.ts +0 -250
  455. package/dist/index-lFffh5-G.d.ts +0 -125
  456. package/dist/index-pxYge_6k.d.ts +0 -79
  457. package/dist/layer-Cv9vSwBx.d.ts +0 -70
  458. package/dist/pino-logger-H4HPW5P6.js +0 -5
  459. package/dist/pino-logger-H4HPW5P6.js.map +0 -1
  460. package/dist/prisma-extension-gYhYriA0.d.ts +0 -174
  461. package/dist/sdk-L75WWUP3.js +0 -156
  462. package/dist/sdk-L75WWUP3.js.map +0 -1
  463. package/dist/shutdown-registry-CW9LryO8.d.ts +0 -10
  464. package/dist/types-Bo2wkjSP.d.ts +0 -35
  465. package/dist/types-DVpvrAhd.d.ts +0 -71
  466. package/dist/types-DgJ4lDYA.d.ts +0 -108
  467. package/dist/types-USOv09qy.d.ts +0 -327
  468. package/dist/workspace-guard-NXVYYBVJ.js +0 -5
  469. package/dist/workspace-guard-NXVYYBVJ.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,366 +1,266 @@
1
- export { NAME_MAX_LENGTH, NAME_MIN_LENGTH, RbacCoverageError, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, validation_exports as Validation, analyzeRbacCoverage, assertRbacCoverage, lengthInCodePoints, validateName, validateUserFields, validateUsername } from './chunk-PYD44IHJ.js';
2
- export { sharing_exports as Sharing } from './chunk-554Z4C2K.js';
3
- export { tags_exports as Tags } from './chunk-PBZFAAOM.js';
4
- export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-VXVLKRU6.js';
5
- import { ActivityModule, TrackerModule } from './chunk-DRWH5XCJ.js';
6
- export { ActivityModule, ActivityOperationUnsupportedError, TrackerModule } from './chunk-DRWH5XCJ.js';
7
- import './chunk-JVMAQOA3.js';
8
- import { UsageModule } from './chunk-QVPIACWD.js';
9
- export { BillingUsageClient, UsageModule } from './chunk-QVPIACWD.js';
10
- export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
11
- import { TenantNotificationsModule, NotificationsModule } from './chunk-KH4TRQCO.js';
12
- export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-KH4TRQCO.js';
13
- export { observability_exports as Observability } from './chunk-VAT66FJA.js';
14
- export { platform_exports as Platform } from './chunk-HC6MPUIH.js';
15
- export { prisma_exports as Prisma } from './chunk-AXJDGQPE.js';
16
- import './chunk-E4QNLVY4.js';
17
- export { PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, product_alias_exports as ProductAlias, RENAME_CONCERNS, billingIdVariants, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, templateKeyVariants, toCurrentName, toLegacyName } from './chunk-OBBCR6WY.js';
18
- import { RBACModule } from './chunk-A6DE32ZS.js';
19
- export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-A6DE32ZS.js';
20
- export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
21
- export { init_exports as Init } from './chunk-HNMHPSAM.js';
22
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-63ZXJ42X.js';
23
- export { instrumentation_exports as Instrumentation } from './chunk-RYTSVGGA.js';
24
- import './chunk-GCIB76AJ.js';
25
- export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
26
- export { export_exports as Export } from './chunk-VTJTAAXC.js';
27
- export { feature_flags_exports as FeatureFlags } from './chunk-UNASM5VJ.js';
28
- export { files_exports as Files } from './chunk-OXNCBE7P.js';
29
- export { gateway_exports as Gateway } from './chunk-CFXWH2IS.js';
30
- import './chunk-726AR6Q7.js';
31
- import { GatewayClient } from './chunk-SPRG6G6G.js';
32
- import './chunk-FZRODKIN.js';
33
- export { layer_exports as Layer } from './chunk-STWFX5E2.js';
34
- import './chunk-VFCMR5GX.js';
35
- import { ContextManager } from './chunk-RZOFS2BQ.js';
36
- export { ContextManager } from './chunk-RZOFS2BQ.js';
37
- import { GatewayError, GatewayErrorType } from './chunk-QWNNFE4P.js';
38
- import { GraphModule } from './chunk-OQDSAOG3.js';
39
- export { graph_exports as Graph, GraphModule } from './chunk-OQDSAOG3.js';
40
- import './chunk-PN6GIF3R.js';
41
- import { EventsModule } from './chunk-JS52ZHTK.js';
42
- export { event_queue_exports as EventQueue, EventsModule } from './chunk-JS52ZHTK.js';
43
- import './chunk-Z77BTSOK.js';
44
- import { QueueType, EventQueueFactory } from './chunk-HTLEGD3Q.js';
45
- import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
46
- export { graphql_exports as GraphQL } from './chunk-ZZK3WEDI.js';
47
- import './chunk-MWPYA2HD.js';
48
- import './chunk-6XEXJATV.js';
49
- export { ai_credits_exports as AiCredits } from './chunk-MESLAC5W.js';
50
- import { AuthModule } from './chunk-4XIBXZ6J.js';
51
- export { AuthModule } from './chunk-4XIBXZ6J.js';
52
- export { utils_exports as Utils } from './chunk-LA5KPWZ2.js';
53
- export { cache_exports as Cache } from './chunk-XOJORS75.js';
54
- import './chunk-A5F6Z5UE.js';
55
- import { disposeAll } from './chunk-KO2ZXZ7W.js';
56
- export { lifecycle_exports as Lifecycle, disposeAll, getRegisteredDisposableCount, registerDisposable, unregisterDisposable } from './chunk-KO2ZXZ7W.js';
57
- export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
58
- export { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from './chunk-KJOSPVB2.js';
59
- export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
60
- import { DatabaseModule } from './chunk-ID3WR4JS.js';
61
- export { DatabaseModule } from './chunk-ID3WR4JS.js';
62
- import { APIError, NetworkError, TimeoutError, ValidationError } from './chunk-I3KOWRT3.js';
63
- export { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS } from './chunk-5CAFHK2Z.js';
64
- import { logger } from './chunk-RU266375.js';
65
- export { logger_exports as Logger } from './chunk-RU266375.js';
66
- import { __name } from './chunk-XE4OXN2W.js';
67
- import { GraphQLClient } from 'graphql-request';
1
+ import { t as GatewayClient } from "./client-DcZ3iGES.js";
2
+ import { a as DEFAULT_LAYER_STREAMS, i as DEFAULT_LAYER_RESOURCES, n as DEFAULT_GATEWAY_RETRY_CONFIG, r as DEFAULT_GATEWAY_ROUTING, t as DEFAULT_CIRCUIT_BREAKER_CONFIG } from "./layer-Bcix-WCl.js";
3
+ import { n as GatewayError, r as GatewayErrorType } from "./types-BYMYND1L.js";
4
+ import { c as ValidationError, r as NetworkError, s as TimeoutError, t as APIError } from "./types-Cj2RWXbz.js";
5
+ import { a as logger, o as logger_exports } from "./logger-B6rCpb7D.js";
6
+ import { t as ContextManager } from "./context-CZnXf2yb.js";
7
+ import { t as AuthModule } from "./auth-CEuBEBQN.js";
8
+ import { c as tenant_notifications_exports, r as NotificationsModule, s as TenantNotificationsModule } from "./notifications-CdETrtFK.js";
9
+ import { a as createRBACDirectiveForLayer, i as createRBACDirective, o as createRBACDirectiveFromEnv, t as RBACModule } from "./rbac-BB9l9Xph.js";
10
+ import { a as ActivityModule, o as ActivityOperationUnsupportedError, t as TrackerModule } from "./tracker-BQVoEFUo.js";
11
+ import { a as UsageModule, c as BillingUsageClient } from "./usage-BKFZiWQn.js";
12
+ import { DatabaseModule } from "./database/index.js";
13
+ import { T as EventsModule, t as event_queue_exports } from "./event-queue-Cw-YJPY_.js";
14
+ import { a as unregisterDisposable, i as registerDisposable, n as disposeAll, r as getRegisteredDisposableCount, t as lifecycle_exports } from "./lifecycle-DeoLSX0U.js";
15
+ import { n as graph_exports, t as GraphModule } from "./graph-DDYgIryR.js";
16
+ import { l as QueueType, t as EventQueueFactory } from "./EventQueueFactory-9NGZV9jl.js";
17
+ import { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from "./client/internal-client.js";
18
+ import { a as resolveEventStreamsUrl } from "./env-DdaoGjIt.js";
19
+ import { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from "./resource-caps/index.js";
20
+ import { t as sharing_exports } from "./sharing-CflDsSJ-.js";
21
+ import { t as tags_exports } from "./tags-B5xpbgsk.js";
22
+ import { t as files_exports } from "./files-DjH0099H.js";
23
+ import { t as ai_credits_exports } from "./ai-credits-Ca-NNcVx.js";
24
+ import { a as TemporalClient, i as TemporalWorkerManager, n as TemporalWorker, o as TemporalClientFactory, r as TemporalWorkerFactory, t as TemporalModule } from "./temporal-B534uYK8.js";
25
+ import { t as cache_exports } from "./cache-CU0uLwcS.js";
26
+ import { t as middleware_exports } from "./middleware-Cq0zFMGp.js";
27
+ import { t as observability_exports } from "./observability-DBDXipTU.js";
28
+ import { t as graphql_exports } from "./graphql-DHAHHcww.js";
29
+ import { t as prisma_exports } from "./prisma-BzOOdt79.js";
30
+ import { _ as utils_exports } from "./utils-DL85Tnbn.js";
31
+ import { a as getLanguage, c as t, i as createTranslator, o as getLocale, r as i18n_exports, s as hasI18n } from "./i18n-BBMYFd0P.js";
32
+ import { t as export_exports } from "./export-B6fphx8a.js";
33
+ import { n as init_exports } from "./init-Dy3KhT6Y.js";
34
+ import { s as dataloader_exports } from "./dataloader-DwpT3YoS.js";
35
+ import { r as instrumentation_exports } from "./instrumentation-xkkmDgJ0.js";
36
+ import { a as layer_exports } from "./layer-CEKy6cm8.js";
37
+ import { t as crypto_exports } from "./crypto-DO9fM0FO.js";
38
+ import { t as gateway_exports } from "./gateway-DBFmxWks.js";
39
+ import { t as feature_flags_exports } from "./feature-flags-71oDkrUe.js";
40
+ import { i as verifyCaptchaIfEnabled, n as isCaptchaEnabled, r as verifyCaptcha, t as captcha_exports } from "./captcha-BT7yh1YS.js";
41
+ import { t as platform_exports } from "./platform-DZwczW7v.js";
42
+ import { C as NAME_MIN_LENGTH, S as NAME_MAX_LENGTH, T as validateName, b as USERNAME_MIN_LENGTH, f as RbacCoverageError, m as assertRbacCoverage, p as analyzeRbacCoverage, t as validation_exports, v as validateUserFields, w as lengthInCodePoints, x as validateUsername, y as USERNAME_MAX_LENGTH } from "./validation-CPUITdMk.js";
43
+ import { A as rbacResourceVariants, C as normalizeProductSlug, D as productSlugVariants, E as normalizeTemplateKey, M as templateKeyVariants, N as toCurrentName, O as product_alias_exports, P as toLegacyName, S as normalizeGraphQLName, T as normalizeRbacResource, _ as isSameQuotaKey, a as billingIdVariants, b as nameVariants, c as emitProductSlug, d as emitTemplateKey, f as isLegacyName, g as isSameProductSlug, h as isSameName, i as RENAME_CONCERNS, j as readRenamedEnv, k as quotaKeyVariants, l as emitQuotaKey, m as isSameGraphQLName, n as PRODUCT_RENAME_EMIT, o as emitBillingId, p as isSameBillingId, r as PRODUCT_SLUG_ALIASES, s as emitName, t as PRODUCT_RENAMES, u as emitRbacResource, v as isSameRbacResource, w as normalizeQuotaKey, x as normalizeBillingId, y as isSameTemplateKey } from "./product-alias-BPqtskMq.js";
44
+ import { GraphQLClient } from "graphql-request";
68
45
 
46
+ // src/client/graphql.ts
69
47
  function isServiceLayer(value) {
70
- return value === "wspace" || value === "global";
48
+ return value === "wspace" || value === "global";
71
49
  }
72
- __name(isServiceLayer, "isServiceLayer");
50
+ /**
51
+ * GraphQL client wrapper with retry logic and error handling
52
+ */
73
53
  var BurdenoffGraphQLClient = class {
74
- static {
75
- __name(this, "BurdenoffGraphQLClient");
76
- }
77
- workspacesClient;
78
- /**
79
- * Cross-layer (tenant) calls go through the unified GatewayClient, which
80
- * targets the peer layer's PUBLIC gateway and mints a short-lived `service`
81
- * actor JWT (via signServiceJwt) so the gateway admits the M2M call and the
82
- * subgraph sees a trusted service context. This is the same mechanism used by
83
- * `GatewayClient.crossLayerQuery` everywhere else — kept consistent here so
84
- * tenant SDK calls (notifications, tenant lookups) authenticate identically.
85
- */
86
- tenantGateway;
87
- config;
88
- defaultContext;
89
- constructor(config, defaultContext = {}) {
90
- this.config = config;
91
- this.defaultContext = defaultContext;
92
- this.workspacesClient = new GraphQLClient(config.workspacesApiUrl, {
93
- headers: this.getHeaders(defaultContext)
94
- });
95
- if (config.tenantApiUrl) {
96
- this.tenantGateway = new GatewayClient({
97
- layer: config.serviceLayer ?? (isServiceLayer(process.env["SERVICE_LAYER"]) ? process.env["SERVICE_LAYER"] : "wspace"),
98
- serviceName: config.serviceName ?? process.env["SERVICE_NAME"] ?? "burdenoff-be-sdk",
99
- crossLayerGatewayUrl: config.tenantApiUrl,
100
- timeout: config.timeout,
101
- // Honor the SDK's retry config (same field shape) so callers that lower
102
- // maxAttempts for non-idempotent tenant mutations (e.g. notification
103
- // sends) are respected instead of falling back to the gateway default.
104
- retry: config.retry
105
- });
106
- }
107
- }
108
- /**
109
- * Get headers for GraphQL request
110
- * Includes actor context headers for RBAC authorization
111
- */
112
- getHeaders(context) {
113
- const headers = {
114
- "Content-Type": "application/json"
115
- };
116
- if (context.token) {
117
- headers["Authorization"] = `Bearer ${context.token}`;
118
- }
119
- if (context.actorId) {
120
- headers["x-actor-id"] = context.actorId;
121
- }
122
- if (context.actorType) {
123
- headers["x-actor-type"] = context.actorType;
124
- }
125
- if (context.workspaceId) {
126
- headers["x-workspace-id"] = context.workspaceId;
127
- }
128
- if (context.productId) {
129
- headers["x-product-id"] = context.productId;
130
- }
131
- return headers;
132
- }
133
- /**
134
- * Update context for future requests
135
- */
136
- updateContext(context) {
137
- this.defaultContext = {
138
- ...this.defaultContext,
139
- ...context
140
- };
141
- this.workspacesClient.setHeaders(this.getHeaders(this.defaultContext));
142
- }
143
- /**
144
- * Execute GraphQL query/mutation against workspaces API
145
- */
146
- async query(query, variables, context) {
147
- return this.executeWithRetry(() => this.executeQuery(this.workspacesClient, query, variables, context), "workspaces");
148
- }
149
- /**
150
- * Execute GraphQL query/mutation against the tenant (cross-layer) API.
151
- *
152
- * Routed through GatewayClient.crossLayerQuery: targets the peer layer's
153
- * PUBLIC gateway and mints a short-lived `service` actor JWT. Only routing
154
- * context (workspace / product) is forwarded — the end-user identity is not,
155
- * because cross-layer tenant operations are service-to-service M2M. Retry and
156
- * circuit-breaking are handled inside GatewayClient.
157
- */
158
- async tenantQuery(query, variables, context) {
159
- if (!this.tenantGateway) {
160
- throw new APIError("Tenant API URL not configured", {
161
- operation: "tenantQuery"
162
- });
163
- }
164
- const mergedContext = {
165
- ...this.defaultContext,
166
- ...context
167
- };
168
- const headers = {};
169
- if (mergedContext.workspaceId) {
170
- headers["x-workspace-id"] = mergedContext.workspaceId;
171
- }
172
- if (mergedContext.productId) {
173
- headers["x-product-id"] = mergedContext.productId;
174
- }
175
- if (mergedContext.organizationId) {
176
- headers["x-org-id"] = mergedContext.organizationId;
177
- }
178
- try {
179
- const response = await this.tenantGateway.crossLayerQuery({
180
- query,
181
- variables,
182
- headers
183
- });
184
- if (response.data == null) {
185
- throw new APIError("Tenant query returned no data", {
186
- api: "tenant"
187
- });
188
- }
189
- return response.data;
190
- } catch (error) {
191
- throw this.mapTenantError(error);
192
- }
193
- }
194
- /**
195
- * Map a GatewayClient failure back to the SDK's APIError contract so existing
196
- * tenant callers (which inspect `error.message` / extensions, e.g. "Forbidden")
197
- * keep working unchanged.
198
- */
199
- mapTenantError(error) {
200
- if (error instanceof APIError) {
201
- return error;
202
- }
203
- if (error instanceof GatewayError) {
204
- const first = error.graphqlErrors?.[0];
205
- if (first) {
206
- return new APIError(first.message, {
207
- graphqlErrors: error.graphqlErrors,
208
- extensions: first.extensions
209
- });
210
- }
211
- if (error.type === GatewayErrorType.NETWORK_ERROR) {
212
- return new NetworkError(error.message, {
213
- gatewayErrorType: error.type
214
- });
215
- }
216
- if (error.type === GatewayErrorType.TIMEOUT_ERROR) {
217
- return new TimeoutError(error.message, {
218
- gatewayErrorType: error.type
219
- });
220
- }
221
- return new APIError(error.message, {
222
- gatewayErrorType: error.type
223
- });
224
- }
225
- return this.handleError(error);
226
- }
227
- /**
228
- * Execute GraphQL request
229
- */
230
- async executeQuery(client, query, variables, context) {
231
- try {
232
- if (!context) {
233
- return await client.request(query, variables);
234
- }
235
- const mergedContext = {
236
- ...this.defaultContext,
237
- ...context
238
- };
239
- return await client.request({
240
- document: query,
241
- variables,
242
- requestHeaders: this.getHeaders(mergedContext)
243
- });
244
- } catch (error) {
245
- throw this.handleError(error);
246
- }
247
- }
248
- /**
249
- * Execute with retry logic
250
- */
251
- async executeWithRetry(operation, api) {
252
- const maxAttempts = this.config.retry?.maxAttempts || 3;
253
- const initialDelay = this.config.retry?.initialDelay || 1e3;
254
- const maxDelay = this.config.retry?.maxDelay || 1e4;
255
- const backoffMultiplier = this.config.retry?.backoffMultiplier || 2;
256
- let lastError;
257
- let delay = initialDelay;
258
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
259
- try {
260
- return await operation();
261
- } catch (error) {
262
- lastError = error;
263
- if (error instanceof APIError && !this.shouldRetry(error)) {
264
- throw error;
265
- }
266
- if (attempt === maxAttempts) {
267
- break;
268
- }
269
- await this.sleep(Math.min(delay, maxDelay));
270
- delay *= backoffMultiplier;
271
- }
272
- }
273
- throw new APIError(`GraphQL request failed after ${maxAttempts} attempts`, {
274
- api,
275
- lastError: lastError?.message
276
- });
277
- }
278
- /**
279
- * Determine if error should be retried
280
- */
281
- shouldRetry(error) {
282
- if (error instanceof NetworkError || error instanceof TimeoutError) {
283
- return true;
284
- }
285
- if (error.code === "SERVER_ERROR") {
286
- return true;
287
- }
288
- return false;
289
- }
290
- /**
291
- * Handle GraphQL errors
292
- */
293
- handleError(error) {
294
- if (error instanceof Error) {
295
- if (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED")) {
296
- return new NetworkError("Network error while connecting to API", {
297
- originalError: error.message
298
- });
299
- }
300
- if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) {
301
- return new TimeoutError("Request timed out", {
302
- originalError: error.message
303
- });
304
- }
305
- if ("response" in error && error.response) {
306
- const response = error.response;
307
- if (response.errors && response.errors.length > 0) {
308
- const firstError = response.errors[0];
309
- if (firstError) {
310
- return new APIError(firstError.message, {
311
- graphqlErrors: response.errors,
312
- extensions: firstError.extensions
313
- });
314
- }
315
- }
316
- }
317
- return new APIError(error.message, {
318
- originalError: error.message
319
- });
320
- }
321
- return new APIError("Unknown error occurred", {
322
- error: String(error)
323
- });
324
- }
325
- /**
326
- * Sleep utility for retry delays
327
- */
328
- sleep(ms) {
329
- return new Promise((resolve) => setTimeout(resolve, ms));
330
- }
331
- /**
332
- * Get current context
333
- */
334
- getContext() {
335
- return {
336
- ...this.defaultContext
337
- };
338
- }
54
+ workspacesClient;
55
+ /**
56
+ * Cross-layer (tenant) calls go through the unified GatewayClient, which
57
+ * targets the peer layer's PUBLIC gateway and mints a short-lived `service`
58
+ * actor JWT (via signServiceJwt) so the gateway admits the M2M call and the
59
+ * subgraph sees a trusted service context. This is the same mechanism used by
60
+ * `GatewayClient.crossLayerQuery` everywhere else — kept consistent here so
61
+ * tenant SDK calls (notifications, tenant lookups) authenticate identically.
62
+ */
63
+ tenantGateway;
64
+ config;
65
+ defaultContext;
66
+ constructor(config, defaultContext = {}) {
67
+ this.config = config;
68
+ this.defaultContext = defaultContext;
69
+ this.workspacesClient = new GraphQLClient(config.workspacesApiUrl, { headers: this.getHeaders(defaultContext) });
70
+ if (config.tenantApiUrl) this.tenantGateway = new GatewayClient({
71
+ layer: config.serviceLayer ?? (isServiceLayer(process.env["SERVICE_LAYER"]) ? process.env["SERVICE_LAYER"] : "wspace"),
72
+ serviceName: config.serviceName ?? process.env["SERVICE_NAME"] ?? "burdenoff-be-sdk",
73
+ crossLayerGatewayUrl: config.tenantApiUrl,
74
+ timeout: config.timeout,
75
+ retry: config.retry
76
+ });
77
+ }
78
+ /**
79
+ * Get headers for GraphQL request
80
+ * Includes actor context headers for RBAC authorization
81
+ */
82
+ getHeaders(context) {
83
+ const headers = { "Content-Type": "application/json" };
84
+ if (context.token) headers["Authorization"] = `Bearer ${context.token}`;
85
+ if (context.actorId) headers["x-actor-id"] = context.actorId;
86
+ if (context.actorType) headers["x-actor-type"] = context.actorType;
87
+ if (context.workspaceId) headers["x-workspace-id"] = context.workspaceId;
88
+ if (context.productId) headers["x-product-id"] = context.productId;
89
+ return headers;
90
+ }
91
+ /**
92
+ * Update context for future requests
93
+ */
94
+ updateContext(context) {
95
+ this.defaultContext = {
96
+ ...this.defaultContext,
97
+ ...context
98
+ };
99
+ this.workspacesClient.setHeaders(this.getHeaders(this.defaultContext));
100
+ }
101
+ /**
102
+ * Execute GraphQL query/mutation against workspaces API
103
+ */
104
+ async query(query, variables, context) {
105
+ return this.executeWithRetry(() => this.executeQuery(this.workspacesClient, query, variables, context), "workspaces");
106
+ }
107
+ /**
108
+ * Execute GraphQL query/mutation against the tenant (cross-layer) API.
109
+ *
110
+ * Routed through GatewayClient.crossLayerQuery: targets the peer layer's
111
+ * PUBLIC gateway and mints a short-lived `service` actor JWT. Only routing
112
+ * context (workspace / product) is forwarded — the end-user identity is not,
113
+ * because cross-layer tenant operations are service-to-service M2M. Retry and
114
+ * circuit-breaking are handled inside GatewayClient.
115
+ */
116
+ async tenantQuery(query, variables, context) {
117
+ if (!this.tenantGateway) throw new APIError("Tenant API URL not configured", { operation: "tenantQuery" });
118
+ const mergedContext = {
119
+ ...this.defaultContext,
120
+ ...context
121
+ };
122
+ const headers = {};
123
+ if (mergedContext.workspaceId) headers["x-workspace-id"] = mergedContext.workspaceId;
124
+ if (mergedContext.productId) headers["x-product-id"] = mergedContext.productId;
125
+ if (mergedContext.organizationId) headers["x-org-id"] = mergedContext.organizationId;
126
+ try {
127
+ const response = await this.tenantGateway.crossLayerQuery({
128
+ query,
129
+ variables,
130
+ headers
131
+ });
132
+ if (response.data == null) throw new APIError("Tenant query returned no data", { api: "tenant" });
133
+ return response.data;
134
+ } catch (error) {
135
+ throw this.mapTenantError(error);
136
+ }
137
+ }
138
+ /**
139
+ * Map a GatewayClient failure back to the SDK's APIError contract so existing
140
+ * tenant callers (which inspect `error.message` / extensions, e.g. "Forbidden")
141
+ * keep working unchanged.
142
+ */
143
+ mapTenantError(error) {
144
+ if (error instanceof APIError) return error;
145
+ if (error instanceof GatewayError) {
146
+ const first = error.graphqlErrors?.[0];
147
+ if (first) return new APIError(first.message, {
148
+ graphqlErrors: error.graphqlErrors,
149
+ extensions: first.extensions
150
+ });
151
+ if (error.type === "NETWORK_ERROR") return new NetworkError(error.message, { gatewayErrorType: error.type });
152
+ if (error.type === "TIMEOUT_ERROR") return new TimeoutError(error.message, { gatewayErrorType: error.type });
153
+ return new APIError(error.message, { gatewayErrorType: error.type });
154
+ }
155
+ return this.handleError(error);
156
+ }
157
+ /**
158
+ * Execute GraphQL request
159
+ */
160
+ async executeQuery(client, query, variables, context) {
161
+ try {
162
+ if (!context) return await client.request(query, variables);
163
+ const mergedContext = {
164
+ ...this.defaultContext,
165
+ ...context
166
+ };
167
+ return await client.request({
168
+ document: query,
169
+ variables,
170
+ requestHeaders: this.getHeaders(mergedContext)
171
+ });
172
+ } catch (error) {
173
+ throw this.handleError(error);
174
+ }
175
+ }
176
+ /**
177
+ * Execute with retry logic
178
+ */
179
+ async executeWithRetry(operation, api) {
180
+ const maxAttempts = this.config.retry?.maxAttempts || 3;
181
+ const initialDelay = this.config.retry?.initialDelay || 1e3;
182
+ const maxDelay = this.config.retry?.maxDelay || 1e4;
183
+ const backoffMultiplier = this.config.retry?.backoffMultiplier || 2;
184
+ let lastError;
185
+ let delay = initialDelay;
186
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
187
+ return await operation();
188
+ } catch (error) {
189
+ lastError = error;
190
+ if (error instanceof APIError && !this.shouldRetry(error)) throw error;
191
+ if (attempt === maxAttempts) break;
192
+ await this.sleep(Math.min(delay, maxDelay));
193
+ delay *= backoffMultiplier;
194
+ }
195
+ throw new APIError(`GraphQL request failed after ${maxAttempts} attempts`, {
196
+ api,
197
+ lastError: lastError?.message
198
+ });
199
+ }
200
+ /**
201
+ * Determine if error should be retried
202
+ */
203
+ shouldRetry(error) {
204
+ if (error instanceof NetworkError || error instanceof TimeoutError) return true;
205
+ if (error.code === "SERVER_ERROR") return true;
206
+ return false;
207
+ }
208
+ /**
209
+ * Handle GraphQL errors
210
+ */
211
+ handleError(error) {
212
+ if (error instanceof Error) {
213
+ if (error.message.includes("fetch failed") || error.message.includes("ECONNREFUSED")) return new NetworkError("Network error while connecting to API", { originalError: error.message });
214
+ if (error.message.includes("timeout") || error.message.includes("ETIMEDOUT")) return new TimeoutError("Request timed out", { originalError: error.message });
215
+ if ("response" in error && error.response) {
216
+ const response = error.response;
217
+ if (response.errors && response.errors.length > 0) {
218
+ const firstError = response.errors[0];
219
+ if (firstError) return new APIError(firstError.message, {
220
+ graphqlErrors: response.errors,
221
+ extensions: firstError.extensions
222
+ });
223
+ }
224
+ }
225
+ return new APIError(error.message, { originalError: error.message });
226
+ }
227
+ return new APIError("Unknown error occurred", { error: String(error) });
228
+ }
229
+ /**
230
+ * Sleep utility for retry delays
231
+ */
232
+ sleep(ms) {
233
+ return new Promise((resolve) => setTimeout(resolve, ms));
234
+ }
235
+ /**
236
+ * Get current context
237
+ */
238
+ getContext() {
239
+ return { ...this.defaultContext };
240
+ }
339
241
  };
340
242
 
341
243
  // src/search/index.ts
244
+ /**
245
+ * Search Module
246
+ */
342
247
  var SearchModule = class {
343
- static {
344
- __name(this, "SearchModule");
345
- }
346
- client;
347
- context;
348
- constructor(client, context) {
349
- this.client = client;
350
- this.context = context;
351
- }
352
- /**
353
- * Search across all resources
354
- */
355
- async search(options) {
356
- if (!options.query || options.query.trim().length === 0) {
357
- throw new ValidationError("Search query is required");
358
- }
359
- logger.debug("[Search] Searching", {
360
- query: options.query,
361
- resourceTypes: options.resourceTypes
362
- });
363
- const query = `
248
+ client;
249
+ context;
250
+ constructor(client, context) {
251
+ this.client = client;
252
+ this.context = context;
253
+ }
254
+ /**
255
+ * Search across all resources
256
+ */
257
+ async search(options) {
258
+ if (!options.query || options.query.trim().length === 0) throw new ValidationError("Search query is required");
259
+ logger.debug("[Search] Searching", {
260
+ query: options.query,
261
+ resourceTypes: options.resourceTypes
262
+ });
263
+ const query = `
364
264
  query Search($input: SearchInput!) {
365
265
  search(input: $input) {
366
266
  results {
@@ -383,48 +283,40 @@ var SearchModule = class {
383
283
  }
384
284
  }
385
285
  `;
386
- const variables = {
387
- input: {
388
- query: options.query,
389
- resourceTypes: options.resourceTypes,
390
- workspaceId: options.workspaceId || this.context.workspaceId,
391
- organizationId: options.organizationId,
392
- projectId: options.projectId || this.context.projectId,
393
- fields: options.fields,
394
- fuzziness: options.fuzziness || 0.8,
395
- boosts: options.boosts,
396
- filters: options.filters,
397
- sort: options.sort,
398
- limit: options.limit || 20,
399
- offset: options.offset || 0,
400
- highlight: options.highlight !== false
401
- }
402
- };
403
- const response = await this.client.query(query, variables, this.context);
404
- logger.info("[Search] Search completed", {
405
- total: response.search.total,
406
- took: response.search.took
407
- });
408
- return response.search;
409
- }
410
- /**
411
- * Index document for search
412
- */
413
- async indexDocument(options) {
414
- if (!options.id) {
415
- throw new ValidationError("Document ID is required");
416
- }
417
- if (!options.type) {
418
- throw new ValidationError("Document type is required");
419
- }
420
- if (!options.title) {
421
- throw new ValidationError("Document title is required");
422
- }
423
- logger.debug("[Search] Indexing document", {
424
- id: options.id,
425
- type: options.type
426
- });
427
- const mutation = `
286
+ const variables = { input: {
287
+ query: options.query,
288
+ resourceTypes: options.resourceTypes,
289
+ workspaceId: options.workspaceId || this.context.workspaceId,
290
+ organizationId: options.organizationId,
291
+ projectId: options.projectId || this.context.projectId,
292
+ fields: options.fields,
293
+ fuzziness: options.fuzziness || .8,
294
+ boosts: options.boosts,
295
+ filters: options.filters,
296
+ sort: options.sort,
297
+ limit: options.limit || 20,
298
+ offset: options.offset || 0,
299
+ highlight: options.highlight !== false
300
+ } };
301
+ const response = await this.client.query(query, variables, this.context);
302
+ logger.info("[Search] Search completed", {
303
+ total: response.search.total,
304
+ took: response.search.took
305
+ });
306
+ return response.search;
307
+ }
308
+ /**
309
+ * Index document for search
310
+ */
311
+ async indexDocument(options) {
312
+ if (!options.id) throw new ValidationError("Document ID is required");
313
+ if (!options.type) throw new ValidationError("Document type is required");
314
+ if (!options.title) throw new ValidationError("Document title is required");
315
+ logger.debug("[Search] Indexing document", {
316
+ id: options.id,
317
+ type: options.type
318
+ });
319
+ const mutation = `
428
320
  mutation IndexDocument($input: IndexDocumentInput!) {
429
321
  indexDocument(input: $input) {
430
322
  id
@@ -432,85 +324,73 @@ var SearchModule = class {
432
324
  }
433
325
  }
434
326
  `;
435
- const variables = {
436
- input: {
437
- id: options.id,
438
- type: options.type,
439
- title: options.title,
440
- description: options.description,
441
- content: options.content,
442
- data: options.data,
443
- workspaceId: options.workspaceId || this.context.workspaceId,
444
- organizationId: options.organizationId,
445
- projectId: options.projectId || this.context.projectId,
446
- tags: options.tags,
447
- metadata: options.metadata
448
- }
449
- };
450
- const response = await this.client.query(mutation, variables, this.context);
451
- logger.info("[Search] Document indexed", {
452
- id: response.indexDocument.id
453
- });
454
- return response.indexDocument;
455
- }
456
- /**
457
- * Remove document from search index
458
- */
459
- async removeDocument(id, type) {
460
- logger.debug("[Search] Removing document", {
461
- id,
462
- type
463
- });
464
- const mutation = `
327
+ const variables = { input: {
328
+ id: options.id,
329
+ type: options.type,
330
+ title: options.title,
331
+ description: options.description,
332
+ content: options.content,
333
+ data: options.data,
334
+ workspaceId: options.workspaceId || this.context.workspaceId,
335
+ organizationId: options.organizationId,
336
+ projectId: options.projectId || this.context.projectId,
337
+ tags: options.tags,
338
+ metadata: options.metadata
339
+ } };
340
+ const response = await this.client.query(mutation, variables, this.context);
341
+ logger.info("[Search] Document indexed", { id: response.indexDocument.id });
342
+ return response.indexDocument;
343
+ }
344
+ /**
345
+ * Remove document from search index
346
+ */
347
+ async removeDocument(id, type) {
348
+ logger.debug("[Search] Removing document", {
349
+ id,
350
+ type
351
+ });
352
+ await this.client.query(`
465
353
  mutation RemoveDocument($id: ID!, $type: String!) {
466
354
  removeDocument(id: $id, type: $type) {
467
355
  success
468
356
  }
469
357
  }
470
- `;
471
- await this.client.query(mutation, {
472
- id,
473
- type
474
- }, this.context);
475
- logger.info("[Search] Document removed", {
476
- id
477
- });
478
- return true;
479
- }
480
- /**
481
- * Update document in search index
482
- */
483
- async updateDocument(id, type, updates) {
484
- logger.debug("[Search] Updating document", {
485
- id,
486
- type
487
- });
488
- const mutation = `
358
+ `, {
359
+ id,
360
+ type
361
+ }, this.context);
362
+ logger.info("[Search] Document removed", { id });
363
+ return true;
364
+ }
365
+ /**
366
+ * Update document in search index
367
+ */
368
+ async updateDocument(id, type, updates) {
369
+ logger.debug("[Search] Updating document", {
370
+ id,
371
+ type
372
+ });
373
+ const response = await this.client.query(`
489
374
  mutation UpdateDocument($id: ID!, $type: String!, $updates: JSON!) {
490
375
  updateDocument(id: $id, type: $type, updates: $updates) {
491
376
  id
492
377
  updated
493
378
  }
494
379
  }
495
- `;
496
- const response = await this.client.query(mutation, {
497
- id,
498
- type,
499
- updates
500
- }, this.context);
501
- logger.info("[Search] Document updated", {
502
- id
503
- });
504
- return response.updateDocument;
505
- }
506
- /**
507
- * Bulk index documents
508
- */
509
- async indexDocumentsBulk(documents) {
510
- logger.debug("[Search] Bulk indexing documents", {
511
- count: documents.length
512
- });
513
- const mutation = `
380
+ `, {
381
+ id,
382
+ type,
383
+ updates
384
+ }, this.context);
385
+ logger.info("[Search] Document updated", { id });
386
+ return response.updateDocument;
387
+ }
388
+ /**
389
+ * Bulk index documents
390
+ */
391
+ async indexDocumentsBulk(documents) {
392
+ logger.debug("[Search] Bulk indexing documents", { count: documents.length });
393
+ const response = await this.client.query(`
514
394
  mutation IndexDocumentsBulk($documents: [IndexDocumentInput!]!) {
515
395
  indexDocumentsBulk(documents: $documents) {
516
396
  indexed
@@ -518,27 +398,20 @@ var SearchModule = class {
518
398
  errors
519
399
  }
520
400
  }
521
- `;
522
- const response = await this.client.query(mutation, {
523
- documents
524
- }, this.context);
525
- logger.info("[Search] Bulk indexing completed", {
526
- indexed: response.indexDocumentsBulk.indexed,
527
- failed: response.indexDocumentsBulk.failed
528
- });
529
- return response.indexDocumentsBulk;
530
- }
531
- /**
532
- * Get search suggestions (autocomplete)
533
- */
534
- async suggest(prefix, options) {
535
- if (!prefix || prefix.trim().length === 0) {
536
- throw new ValidationError("Prefix is required for suggestions");
537
- }
538
- logger.debug("[Search] Getting suggestions", {
539
- prefix
540
- });
541
- const query = `
401
+ `, { documents }, this.context);
402
+ logger.info("[Search] Bulk indexing completed", {
403
+ indexed: response.indexDocumentsBulk.indexed,
404
+ failed: response.indexDocumentsBulk.failed
405
+ });
406
+ return response.indexDocumentsBulk;
407
+ }
408
+ /**
409
+ * Get search suggestions (autocomplete)
410
+ */
411
+ async suggest(prefix, options) {
412
+ if (!prefix || prefix.trim().length === 0) throw new ValidationError("Prefix is required for suggestions");
413
+ logger.debug("[Search] Getting suggestions", { prefix });
414
+ return (await this.client.query(`
542
415
  query GetSuggestions($prefix: String!, $resourceTypes: [String!], $limit: Int) {
543
416
  getSuggestions(prefix: $prefix, resourceTypes: $resourceTypes, limit: $limit) {
544
417
  text
@@ -546,22 +419,18 @@ var SearchModule = class {
546
419
  type
547
420
  }
548
421
  }
549
- `;
550
- const response = await this.client.query(query, {
551
- prefix,
552
- resourceTypes: options?.resourceTypes,
553
- limit: options?.limit || 10
554
- }, this.context);
555
- return response.getSuggestions;
556
- }
557
- /**
558
- * Get related documents
559
- */
560
- async getRelated(documentId, options) {
561
- logger.debug("[Search] Getting related documents", {
562
- documentId
563
- });
564
- const query = `
422
+ `, {
423
+ prefix,
424
+ resourceTypes: options?.resourceTypes,
425
+ limit: options?.limit || 10
426
+ }, this.context)).getSuggestions;
427
+ }
428
+ /**
429
+ * Get related documents
430
+ */
431
+ async getRelated(documentId, options) {
432
+ logger.debug("[Search] Getting related documents", { documentId });
433
+ return (await this.client.query(`
565
434
  query GetRelatedDocuments($documentId: ID!, $limit: Int, $minScore: Float) {
566
435
  getRelatedDocuments(documentId: $documentId, limit: $limit, minScore: $minScore) {
567
436
  id
@@ -574,105 +443,87 @@ var SearchModule = class {
574
443
  updatedAt
575
444
  }
576
445
  }
577
- `;
578
- const response = await this.client.query(query, {
579
- documentId,
580
- limit: options?.limit || 10,
581
- minScore: options?.minScore || 0.5
582
- }, this.context);
583
- return response.getRelatedDocuments;
584
- }
585
- /**
586
- * Get search aggregations
587
- */
588
- async aggregate(query, aggregations) {
589
- logger.debug("[Search] Getting aggregations", {
590
- query
591
- });
592
- const gqlQuery = `
446
+ `, {
447
+ documentId,
448
+ limit: options?.limit || 10,
449
+ minScore: options?.minScore || .5
450
+ }, this.context)).getRelatedDocuments;
451
+ }
452
+ /**
453
+ * Get search aggregations
454
+ */
455
+ async aggregate(query, aggregations) {
456
+ logger.debug("[Search] Getting aggregations", { query });
457
+ return (await this.client.query(`
593
458
  query GetAggregations($query: String!, $aggregations: [AggregationInput!]!) {
594
459
  getAggregations(query: $query, aggregations: $aggregations) {
595
460
  aggregations
596
461
  }
597
462
  }
598
- `;
599
- const response = await this.client.query(gqlQuery, {
600
- query,
601
- aggregations
602
- }, this.context);
603
- return response.getAggregations.aggregations;
604
- }
605
- /**
606
- * Clear search index for workspace
607
- */
608
- async clearIndex(workspaceId) {
609
- logger.debug("[Search] Clearing index", {
610
- workspaceId
611
- });
612
- const mutation = `
463
+ `, {
464
+ query,
465
+ aggregations
466
+ }, this.context)).getAggregations.aggregations;
467
+ }
468
+ /**
469
+ * Clear search index for workspace
470
+ */
471
+ async clearIndex(workspaceId) {
472
+ logger.debug("[Search] Clearing index", { workspaceId });
473
+ const response = await this.client.query(`
613
474
  mutation ClearSearchIndex($workspaceId: ID) {
614
475
  clearSearchIndex(workspaceId: $workspaceId) {
615
476
  deletedCount
616
477
  }
617
478
  }
618
- `;
619
- const response = await this.client.query(mutation, {
620
- workspaceId: workspaceId || this.context.workspaceId
621
- }, this.context);
622
- logger.info("[Search] Index cleared", {
623
- deletedCount: response.clearSearchIndex.deletedCount
624
- });
625
- return response.clearSearchIndex;
626
- }
627
- /**
628
- * Reindex all documents
629
- */
630
- async reindex(options) {
631
- logger.debug("[Search] Reindexing", options);
632
- const mutation = `
479
+ `, { workspaceId: workspaceId || this.context.workspaceId }, this.context);
480
+ logger.info("[Search] Index cleared", { deletedCount: response.clearSearchIndex.deletedCount });
481
+ return response.clearSearchIndex;
482
+ }
483
+ /**
484
+ * Reindex all documents
485
+ */
486
+ async reindex(options) {
487
+ logger.debug("[Search] Reindexing", options);
488
+ const response = await this.client.query(`
633
489
  mutation ReindexDocuments($workspaceId: ID, $resourceTypes: [String!]) {
634
490
  reindexDocuments(workspaceId: $workspaceId, resourceTypes: $resourceTypes) {
635
491
  indexed
636
492
  failed
637
493
  }
638
494
  }
639
- `;
640
- const response = await this.client.query(mutation, {
641
- workspaceId: options?.workspaceId || this.context.workspaceId,
642
- resourceTypes: options?.resourceTypes
643
- }, this.context);
644
- logger.info("[Search] Reindexing completed", response.reindexDocuments);
645
- return response.reindexDocuments;
646
- }
495
+ `, {
496
+ workspaceId: options?.workspaceId || this.context.workspaceId,
497
+ resourceTypes: options?.resourceTypes
498
+ }, this.context);
499
+ logger.info("[Search] Reindexing completed", response.reindexDocuments);
500
+ return response.reindexDocuments;
501
+ }
647
502
  };
648
503
 
649
504
  // src/translation/index.ts
505
+ /**
506
+ * Translation Module
507
+ */
650
508
  var TranslationModule = class {
651
- static {
652
- __name(this, "TranslationModule");
653
- }
654
- client;
655
- context;
656
- constructor(client, context) {
657
- this.client = client;
658
- this.context = context;
659
- }
660
- /**
661
- * Translate text
662
- */
663
- async translate(options) {
664
- if (!options.text || options.text.trim().length === 0) {
665
- throw new ValidationError("Text to translate is required");
666
- }
667
- if (!options.targetLanguage) {
668
- throw new ValidationError("Target language is required");
669
- }
670
- logger.debug("[Translation] Translating text", {
671
- sourceLanguage: options.sourceLanguage || "auto",
672
- targetLanguage: options.targetLanguage,
673
- textLength: options.text.length
674
- });
675
- const query = `
509
+ client;
510
+ context;
511
+ constructor(client, context) {
512
+ this.client = client;
513
+ this.context = context;
514
+ }
515
+ /**
516
+ * Translate text
517
+ */
518
+ async translate(options) {
519
+ if (!options.text || options.text.trim().length === 0) throw new ValidationError("Text to translate is required");
520
+ if (!options.targetLanguage) throw new ValidationError("Target language is required");
521
+ logger.debug("[Translation] Translating text", {
522
+ sourceLanguage: options.sourceLanguage || "auto",
523
+ targetLanguage: options.targetLanguage,
524
+ textLength: options.text.length
525
+ });
526
+ const query = `
676
527
  query Translate($input: TranslateInput!) {
677
528
  translate(input: $input) {
678
529
  original
@@ -683,43 +534,35 @@ var TranslationModule = class {
683
534
  }
684
535
  }
685
536
  `;
686
- const variables = {
687
- input: {
688
- text: options.text,
689
- sourceLanguage: options.sourceLanguage,
690
- targetLanguage: options.targetLanguage,
691
- context: options.context
692
- }
693
- };
694
- const response = await this.client.query(query, variables, this.context);
695
- let translated = response.translate.translated;
696
- if (options.variables) {
697
- translated = this.interpolate(translated, options.variables);
698
- }
699
- logger.info("[Translation] Text translated", {
700
- sourceLanguage: response.translate.sourceLanguage,
701
- targetLanguage: response.translate.targetLanguage
702
- });
703
- return {
704
- ...response.translate,
705
- translated
706
- };
707
- }
708
- /**
709
- * Get translations for keys
710
- */
711
- async getTranslations(options) {
712
- if (!options.keys || options.keys.length === 0) {
713
- throw new ValidationError("Translation keys are required");
714
- }
715
- if (!options.language) {
716
- throw new ValidationError("Language is required");
717
- }
718
- logger.debug("[Translation] Getting translations", {
719
- language: options.language,
720
- count: options.keys.length
721
- });
722
- const query = `
537
+ const variables = { input: {
538
+ text: options.text,
539
+ sourceLanguage: options.sourceLanguage,
540
+ targetLanguage: options.targetLanguage,
541
+ context: options.context
542
+ } };
543
+ const response = await this.client.query(query, variables, this.context);
544
+ let translated = response.translate.translated;
545
+ if (options.variables) translated = this.interpolate(translated, options.variables);
546
+ logger.info("[Translation] Text translated", {
547
+ sourceLanguage: response.translate.sourceLanguage,
548
+ targetLanguage: response.translate.targetLanguage
549
+ });
550
+ return {
551
+ ...response.translate,
552
+ translated
553
+ };
554
+ }
555
+ /**
556
+ * Get translations for keys
557
+ */
558
+ async getTranslations(options) {
559
+ if (!options.keys || options.keys.length === 0) throw new ValidationError("Translation keys are required");
560
+ if (!options.language) throw new ValidationError("Language is required");
561
+ logger.debug("[Translation] Getting translations", {
562
+ language: options.language,
563
+ count: options.keys.length
564
+ });
565
+ return (await this.client.query(`
723
566
  query GetTranslations(
724
567
  $keys: [String!]!
725
568
  $language: String!
@@ -735,49 +578,36 @@ var TranslationModule = class {
735
578
  translations
736
579
  }
737
580
  }
738
- `;
739
- const response = await this.client.query(query, {
740
- keys: options.keys,
741
- language: options.language,
742
- namespace: options.namespace,
743
- fallbackLanguage: options.fallbackLanguage || "en"
744
- }, this.context);
745
- return response.getTranslations.translations;
746
- }
747
- /**
748
- * Get single translation
749
- */
750
- async get(key, language, variables) {
751
- const translations = await this.getTranslations({
752
- keys: [
753
- key
754
- ],
755
- language
756
- });
757
- let translation = translations[key] || key;
758
- if (variables) {
759
- translation = this.interpolate(translation, variables);
760
- }
761
- return translation;
762
- }
763
- /**
764
- * Set translation
765
- */
766
- async setTranslation(options) {
767
- if (!options.key) {
768
- throw new ValidationError("Translation key is required");
769
- }
770
- if (!options.value) {
771
- throw new ValidationError("Translation value is required");
772
- }
773
- if (!options.language) {
774
- throw new ValidationError("Language is required");
775
- }
776
- logger.debug("[Translation] Setting translation", {
777
- key: options.key,
778
- language: options.language
779
- });
780
- const mutation = `
581
+ `, {
582
+ keys: options.keys,
583
+ language: options.language,
584
+ namespace: options.namespace,
585
+ fallbackLanguage: options.fallbackLanguage || "en"
586
+ }, this.context)).getTranslations.translations;
587
+ }
588
+ /**
589
+ * Get single translation
590
+ */
591
+ async get(key, language, variables) {
592
+ let translation = (await this.getTranslations({
593
+ keys: [key],
594
+ language
595
+ }))[key] || key;
596
+ if (variables) translation = this.interpolate(translation, variables);
597
+ return translation;
598
+ }
599
+ /**
600
+ * Set translation
601
+ */
602
+ async setTranslation(options) {
603
+ if (!options.key) throw new ValidationError("Translation key is required");
604
+ if (!options.value) throw new ValidationError("Translation value is required");
605
+ if (!options.language) throw new ValidationError("Language is required");
606
+ logger.debug("[Translation] Setting translation", {
607
+ key: options.key,
608
+ language: options.language
609
+ });
610
+ const mutation = `
781
611
  mutation SetTranslation($input: SetTranslationInput!) {
782
612
  setTranslation(input: $input) {
783
613
  key
@@ -789,57 +619,52 @@ var TranslationModule = class {
789
619
  }
790
620
  }
791
621
  `;
792
- const variables = {
793
- input: {
794
- key: options.key,
795
- value: options.value,
796
- language: options.language,
797
- namespace: options.namespace,
798
- description: options.description,
799
- variables: options.variables
800
- }
801
- };
802
- const response = await this.client.query(mutation, variables, this.context);
803
- logger.info("[Translation] Translation set", {
804
- key: options.key,
805
- language: options.language
806
- });
807
- return response.setTranslation;
808
- }
809
- /**
810
- * Delete translation
811
- */
812
- async deleteTranslation(key, language, namespace) {
813
- logger.debug("[Translation] Deleting translation", {
814
- key,
815
- language
816
- });
817
- const mutation = `
622
+ const variables = { input: {
623
+ key: options.key,
624
+ value: options.value,
625
+ language: options.language,
626
+ namespace: options.namespace,
627
+ description: options.description,
628
+ variables: options.variables
629
+ } };
630
+ const response = await this.client.query(mutation, variables, this.context);
631
+ logger.info("[Translation] Translation set", {
632
+ key: options.key,
633
+ language: options.language
634
+ });
635
+ return response.setTranslation;
636
+ }
637
+ /**
638
+ * Delete translation
639
+ */
640
+ async deleteTranslation(key, language, namespace) {
641
+ logger.debug("[Translation] Deleting translation", {
642
+ key,
643
+ language
644
+ });
645
+ await this.client.query(`
818
646
  mutation DeleteTranslation($key: String!, $language: String!, $namespace: String) {
819
647
  deleteTranslation(key: $key, language: $language, namespace: $namespace) {
820
648
  success
821
649
  }
822
650
  }
823
- `;
824
- await this.client.query(mutation, {
825
- key,
826
- language,
827
- namespace
828
- }, this.context);
829
- logger.info("[Translation] Translation deleted", {
830
- key,
831
- language
832
- });
833
- return true;
834
- }
835
- /**
836
- * Batch set translations
837
- */
838
- async setTranslationsBatch(translations) {
839
- logger.debug("[Translation] Batch setting translations", {
840
- count: translations.length
841
- });
842
- const mutation = `
651
+ `, {
652
+ key,
653
+ language,
654
+ namespace
655
+ }, this.context);
656
+ logger.info("[Translation] Translation deleted", {
657
+ key,
658
+ language
659
+ });
660
+ return true;
661
+ }
662
+ /**
663
+ * Batch set translations
664
+ */
665
+ async setTranslationsBatch(translations) {
666
+ logger.debug("[Translation] Batch setting translations", { count: translations.length });
667
+ const response = await this.client.query(`
843
668
  mutation SetTranslationsBatch($translations: [SetTranslationInput!]!) {
844
669
  setTranslationsBatch(translations: $translations) {
845
670
  key
@@ -850,24 +675,19 @@ var TranslationModule = class {
850
675
  variables
851
676
  }
852
677
  }
853
- `;
854
- const response = await this.client.query(mutation, {
855
- translations
856
- }, this.context);
857
- logger.info("[Translation] Batch translations set", {
858
- count: response.setTranslationsBatch.length
859
- });
860
- return response.setTranslationsBatch;
861
- }
862
- /**
863
- * Get all translations for language
864
- */
865
- async getAllTranslations(language, namespace) {
866
- logger.debug("[Translation] Getting all translations", {
867
- language,
868
- namespace
869
- });
870
- const query = `
678
+ `, { translations }, this.context);
679
+ logger.info("[Translation] Batch translations set", { count: response.setTranslationsBatch.length });
680
+ return response.setTranslationsBatch;
681
+ }
682
+ /**
683
+ * Get all translations for language
684
+ */
685
+ async getAllTranslations(language, namespace) {
686
+ logger.debug("[Translation] Getting all translations", {
687
+ language,
688
+ namespace
689
+ });
690
+ return (await this.client.query(`
871
691
  query GetAllTranslations($language: String!, $namespace: String) {
872
692
  getAllTranslations(language: $language, namespace: $namespace) {
873
693
  key
@@ -878,40 +698,32 @@ var TranslationModule = class {
878
698
  variables
879
699
  }
880
700
  }
881
- `;
882
- const response = await this.client.query(query, {
883
- language,
884
- namespace
885
- }, this.context);
886
- return response.getAllTranslations;
887
- }
888
- /**
889
- * Detect language
890
- */
891
- async detectLanguage(text) {
892
- if (!text || text.trim().length === 0) {
893
- throw new ValidationError("Text is required for language detection");
894
- }
895
- logger.debug("[Translation] Detecting language");
896
- const query = `
701
+ `, {
702
+ language,
703
+ namespace
704
+ }, this.context)).getAllTranslations;
705
+ }
706
+ /**
707
+ * Detect language
708
+ */
709
+ async detectLanguage(text) {
710
+ if (!text || text.trim().length === 0) throw new ValidationError("Text is required for language detection");
711
+ logger.debug("[Translation] Detecting language");
712
+ return (await this.client.query(`
897
713
  query DetectLanguage($text: String!) {
898
714
  detectLanguage(text: $text) {
899
715
  language
900
716
  confidence
901
717
  }
902
718
  }
903
- `;
904
- const response = await this.client.query(query, {
905
- text
906
- }, this.context);
907
- return response.detectLanguage;
908
- }
909
- /**
910
- * Get supported languages
911
- */
912
- async getSupportedLanguages() {
913
- logger.debug("[Translation] Getting supported languages");
914
- const query = `
719
+ `, { text }, this.context)).detectLanguage;
720
+ }
721
+ /**
722
+ * Get supported languages
723
+ */
724
+ async getSupportedLanguages() {
725
+ logger.debug("[Translation] Getting supported languages");
726
+ return (await this.client.query(`
915
727
  query GetSupportedLanguages {
916
728
  getSupportedLanguages {
917
729
  code
@@ -919,71 +731,67 @@ var TranslationModule = class {
919
731
  nativeName
920
732
  }
921
733
  }
922
- `;
923
- const response = await this.client.query(query, {}, this.context);
924
- return response.getSupportedLanguages;
925
- }
926
- /**
927
- * Import translations from file
928
- */
929
- async importTranslations(language, translations, namespace) {
930
- logger.debug("[Translation] Importing translations", {
931
- language,
932
- count: Object.keys(translations).length
933
- });
934
- const mutation = `
734
+ `, {}, this.context)).getSupportedLanguages;
735
+ }
736
+ /**
737
+ * Import translations from file
738
+ */
739
+ async importTranslations(language, translations, namespace) {
740
+ logger.debug("[Translation] Importing translations", {
741
+ language,
742
+ count: Object.keys(translations).length
743
+ });
744
+ const response = await this.client.query(`
935
745
  mutation ImportTranslations($language: String!, $translations: JSON!, $namespace: String) {
936
746
  importTranslations(language: $language, translations: $translations, namespace: $namespace) {
937
747
  imported
938
748
  failed
939
749
  }
940
750
  }
941
- `;
942
- const response = await this.client.query(mutation, {
943
- language,
944
- translations,
945
- namespace
946
- }, this.context);
947
- logger.info("[Translation] Translations imported", response.importTranslations);
948
- return response.importTranslations;
949
- }
950
- /**
951
- * Export translations to JSON
952
- */
953
- async exportTranslations(language, namespace) {
954
- logger.debug("[Translation] Exporting translations", {
955
- language,
956
- namespace
957
- });
958
- const query = `
751
+ `, {
752
+ language,
753
+ translations,
754
+ namespace
755
+ }, this.context);
756
+ logger.info("[Translation] Translations imported", response.importTranslations);
757
+ return response.importTranslations;
758
+ }
759
+ /**
760
+ * Export translations to JSON
761
+ */
762
+ async exportTranslations(language, namespace) {
763
+ logger.debug("[Translation] Exporting translations", {
764
+ language,
765
+ namespace
766
+ });
767
+ const response = await this.client.query(`
959
768
  query ExportTranslations($language: String!, $namespace: String) {
960
769
  exportTranslations(language: $language, namespace: $namespace) {
961
770
  translations
962
771
  }
963
772
  }
964
- `;
965
- const response = await this.client.query(query, {
966
- language,
967
- namespace
968
- }, this.context);
969
- logger.info("[Translation] Translations exported", {
970
- language,
971
- count: Object.keys(response.exportTranslations.translations).length
972
- });
973
- return response.exportTranslations.translations;
974
- }
975
- /**
976
- * Export product translations from global i18n service (federated schema).
977
- *
978
- * This uses the modern i18n GraphQL contract:
979
- * - i18nProductByName
980
- * - exportTranslations(productId, languageCode, format)
981
- */
982
- async exportProductTranslations(options) {
983
- const productId = await this.resolveProductId(options.productId, options.productName);
984
- const languageCode = options.languageCode ?? "en";
985
- const format = options.format ?? "JSON";
986
- const query = `
773
+ `, {
774
+ language,
775
+ namespace
776
+ }, this.context);
777
+ logger.info("[Translation] Translations exported", {
778
+ language,
779
+ count: Object.keys(response.exportTranslations.translations).length
780
+ });
781
+ return response.exportTranslations.translations;
782
+ }
783
+ /**
784
+ * Export product translations from global i18n service (federated schema).
785
+ *
786
+ * This uses the modern i18n GraphQL contract:
787
+ * - i18nProductByName
788
+ * - exportTranslations(productId, languageCode, format)
789
+ */
790
+ async exportProductTranslations(options) {
791
+ const productId = await this.resolveProductId(options.productId, options.productName);
792
+ const languageCode = options.languageCode ?? "en";
793
+ const format = options.format ?? "JSON";
794
+ const response = await this.client.query(`
987
795
  query ExportProductTranslations(
988
796
  $productId: String!
989
797
  $languageCode: String!
@@ -994,212 +802,172 @@ var TranslationModule = class {
994
802
  url
995
803
  }
996
804
  }
997
- `;
998
- const response = await this.client.query(query, {
999
- productId,
1000
- languageCode,
1001
- format
1002
- }, this.context);
1003
- const result = {
1004
- format: response.exportTranslations.format,
1005
- url: response.exportTranslations.url
1006
- };
1007
- if ((options.decodeJson ?? true) && format === "JSON") {
1008
- result.translations = this.decodeDataUrlJson(response.exportTranslations.url);
1009
- }
1010
- return result;
1011
- }
1012
- /**
1013
- * Upsert product translations in global i18n service.
1014
- *
1015
- * Behavior:
1016
- * - Ensures translation keys exist (create if missing)
1017
- * - Optionally updates translation key defaultValue
1018
- * - Creates/updates language translation entries
1019
- * - Optionally publishes translations
1020
- */
1021
- async upsertProductTranslations(options) {
1022
- if (!options.languageCode) {
1023
- throw new ValidationError("languageCode is required");
1024
- }
1025
- const flatTranslations = this.flattenTranslationTree(options.translations);
1026
- if (Object.keys(flatTranslations).length === 0) {
1027
- throw new ValidationError("translations cannot be empty");
1028
- }
1029
- const flatDefaults = options.defaultValues ? this.flattenTranslationTree(options.defaultValues) : flatTranslations;
1030
- const productId = await this.resolveProductId(options.productId, options.productName);
1031
- const publish = options.publish ?? true;
1032
- const updateExisting = options.updateExisting ?? true;
1033
- const result = {
1034
- productId,
1035
- languageCode: options.languageCode,
1036
- keysProcessed: 0,
1037
- createdKeys: 0,
1038
- updatedKeyDefaults: 0,
1039
- createdTranslations: 0,
1040
- updatedTranslations: 0
1041
- };
1042
- const entries = Object.entries(flatTranslations);
1043
- const existingKeysMap = /* @__PURE__ */ new Map();
1044
- for (const [key] of entries) {
1045
- const keyRow = await this.findTranslationKeyByKey(productId, key);
1046
- if (keyRow) {
1047
- existingKeysMap.set(key, keyRow);
1048
- }
1049
- }
1050
- for (const [key, value] of entries) {
1051
- const defaultValue = flatDefaults[key] ?? value;
1052
- let keyId = "";
1053
- const keyRow = existingKeysMap.get(key);
1054
- if (!keyRow) {
1055
- const createdKey = await this.createTranslationKey(productId, key, defaultValue);
1056
- keyId = createdKey.id;
1057
- result.createdKeys += 1;
1058
- } else {
1059
- keyId = keyRow.id;
1060
- if (defaultValue && keyRow.defaultValue !== defaultValue) {
1061
- await this.updateTranslationKeyDefaultValue(keyId, defaultValue);
1062
- result.updatedKeyDefaults += 1;
1063
- }
1064
- }
1065
- const translationRow = await this.findGlobalTranslation(keyId, options.languageCode);
1066
- if (!translationRow) {
1067
- const createdTranslation = await this.createLanguageTranslation(keyId, options.languageCode, value);
1068
- result.createdTranslations += 1;
1069
- if (publish && createdTranslation.status !== "PUBLISHED") {
1070
- await this.updateLanguageTranslation(createdTranslation.id, value, "PUBLISHED");
1071
- }
1072
- } else {
1073
- const shouldUpdateValue = updateExisting && translationRow.value !== value;
1074
- const shouldPublish = publish && translationRow.status !== "PUBLISHED";
1075
- if (shouldUpdateValue || shouldPublish) {
1076
- await this.updateLanguageTranslation(translationRow.id, shouldUpdateValue ? value : translationRow.value, publish ? "PUBLISHED" : translationRow.status);
1077
- if (shouldUpdateValue) {
1078
- result.updatedTranslations += 1;
1079
- }
1080
- }
1081
- }
1082
- result.keysProcessed += 1;
1083
- }
1084
- logger.info("[Translation] Product translations upsert completed", {
1085
- productId,
1086
- languageCode: options.languageCode,
1087
- keysProcessed: result.keysProcessed,
1088
- createdKeys: result.createdKeys,
1089
- createdTranslations: result.createdTranslations,
1090
- updatedTranslations: result.updatedTranslations
1091
- });
1092
- return result;
1093
- }
1094
- flattenTranslationTree(input, prefix = "") {
1095
- const out = {};
1096
- for (const [key, rawValue] of Object.entries(input)) {
1097
- const nextKey = prefix ? `${prefix}.${key}` : key;
1098
- if (typeof rawValue === "string") {
1099
- out[nextKey] = rawValue;
1100
- continue;
1101
- }
1102
- if (rawValue && typeof rawValue === "object") {
1103
- Object.assign(out, this.flattenTranslationTree(rawValue, nextKey));
1104
- }
1105
- }
1106
- return out;
1107
- }
1108
- decodeDataUrlJson(url) {
1109
- if (!url.startsWith("data:")) {
1110
- throw new ValidationError("Expected exportTranslations URL to be a data URL");
1111
- }
1112
- const commaIdx = url.indexOf(",");
1113
- if (commaIdx === -1) {
1114
- throw new ValidationError("Invalid data URL: missing comma separator");
1115
- }
1116
- const header = url.slice(0, commaIdx);
1117
- const payload = url.slice(commaIdx + 1);
1118
- if (!payload) {
1119
- throw new ValidationError("Invalid data URL payload");
1120
- }
1121
- try {
1122
- const decoded = header.includes("base64") ? Buffer.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
1123
- return JSON.parse(decoded);
1124
- } catch (error) {
1125
- logger.error("[Translation] Failed to decode data URL JSON", {
1126
- error,
1127
- isBase64: header.includes("base64")
1128
- });
1129
- throw new ValidationError("Failed to decode JSON translation payload");
1130
- }
1131
- }
1132
- async resolveProductId(productId, productName) {
1133
- if (productId) {
1134
- return productId;
1135
- }
1136
- if (!productName) {
1137
- throw new ValidationError("Either productId or productName is required");
1138
- }
1139
- const query = `
805
+ `, {
806
+ productId,
807
+ languageCode,
808
+ format
809
+ }, this.context);
810
+ const result = {
811
+ format: response.exportTranslations.format,
812
+ url: response.exportTranslations.url
813
+ };
814
+ if ((options.decodeJson ?? true) && format === "JSON") result.translations = this.decodeDataUrlJson(response.exportTranslations.url);
815
+ return result;
816
+ }
817
+ /**
818
+ * Upsert product translations in global i18n service.
819
+ *
820
+ * Behavior:
821
+ * - Ensures translation keys exist (create if missing)
822
+ * - Optionally updates translation key defaultValue
823
+ * - Creates/updates language translation entries
824
+ * - Optionally publishes translations
825
+ */
826
+ async upsertProductTranslations(options) {
827
+ if (!options.languageCode) throw new ValidationError("languageCode is required");
828
+ const flatTranslations = this.flattenTranslationTree(options.translations);
829
+ if (Object.keys(flatTranslations).length === 0) throw new ValidationError("translations cannot be empty");
830
+ const flatDefaults = options.defaultValues ? this.flattenTranslationTree(options.defaultValues) : flatTranslations;
831
+ const productId = await this.resolveProductId(options.productId, options.productName);
832
+ const publish = options.publish ?? true;
833
+ const updateExisting = options.updateExisting ?? true;
834
+ const result = {
835
+ productId,
836
+ languageCode: options.languageCode,
837
+ keysProcessed: 0,
838
+ createdKeys: 0,
839
+ updatedKeyDefaults: 0,
840
+ createdTranslations: 0,
841
+ updatedTranslations: 0
842
+ };
843
+ const entries = Object.entries(flatTranslations);
844
+ const existingKeysMap = /* @__PURE__ */ new Map();
845
+ for (const [key] of entries) {
846
+ const keyRow = await this.findTranslationKeyByKey(productId, key);
847
+ if (keyRow) existingKeysMap.set(key, keyRow);
848
+ }
849
+ for (const [key, value] of entries) {
850
+ const defaultValue = flatDefaults[key] ?? value;
851
+ let keyId = "";
852
+ const keyRow = existingKeysMap.get(key);
853
+ if (!keyRow) {
854
+ keyId = (await this.createTranslationKey(productId, key, defaultValue)).id;
855
+ result.createdKeys += 1;
856
+ } else {
857
+ keyId = keyRow.id;
858
+ if (defaultValue && keyRow.defaultValue !== defaultValue) {
859
+ await this.updateTranslationKeyDefaultValue(keyId, defaultValue);
860
+ result.updatedKeyDefaults += 1;
861
+ }
862
+ }
863
+ const translationRow = await this.findGlobalTranslation(keyId, options.languageCode);
864
+ if (!translationRow) {
865
+ const createdTranslation = await this.createLanguageTranslation(keyId, options.languageCode, value);
866
+ result.createdTranslations += 1;
867
+ if (publish && createdTranslation.status !== "PUBLISHED") await this.updateLanguageTranslation(createdTranslation.id, value, "PUBLISHED");
868
+ } else {
869
+ const shouldUpdateValue = updateExisting && translationRow.value !== value;
870
+ const shouldPublish = publish && translationRow.status !== "PUBLISHED";
871
+ if (shouldUpdateValue || shouldPublish) {
872
+ await this.updateLanguageTranslation(translationRow.id, shouldUpdateValue ? value : translationRow.value, publish ? "PUBLISHED" : translationRow.status);
873
+ if (shouldUpdateValue) result.updatedTranslations += 1;
874
+ }
875
+ }
876
+ result.keysProcessed += 1;
877
+ }
878
+ logger.info("[Translation] Product translations upsert completed", {
879
+ productId,
880
+ languageCode: options.languageCode,
881
+ keysProcessed: result.keysProcessed,
882
+ createdKeys: result.createdKeys,
883
+ createdTranslations: result.createdTranslations,
884
+ updatedTranslations: result.updatedTranslations
885
+ });
886
+ return result;
887
+ }
888
+ flattenTranslationTree(input, prefix = "") {
889
+ const out = {};
890
+ for (const [key, rawValue] of Object.entries(input)) {
891
+ const nextKey = prefix ? `${prefix}.${key}` : key;
892
+ if (typeof rawValue === "string") {
893
+ out[nextKey] = rawValue;
894
+ continue;
895
+ }
896
+ if (rawValue && typeof rawValue === "object") Object.assign(out, this.flattenTranslationTree(rawValue, nextKey));
897
+ }
898
+ return out;
899
+ }
900
+ decodeDataUrlJson(url) {
901
+ if (!url.startsWith("data:")) throw new ValidationError("Expected exportTranslations URL to be a data URL");
902
+ const commaIdx = url.indexOf(",");
903
+ if (commaIdx === -1) throw new ValidationError("Invalid data URL: missing comma separator");
904
+ const header = url.slice(0, commaIdx);
905
+ const payload = url.slice(commaIdx + 1);
906
+ if (!payload) throw new ValidationError("Invalid data URL payload");
907
+ try {
908
+ const decoded = header.includes("base64") ? Buffer.from(payload, "base64").toString("utf8") : decodeURIComponent(payload);
909
+ return JSON.parse(decoded);
910
+ } catch (error) {
911
+ logger.error("[Translation] Failed to decode data URL JSON", {
912
+ error,
913
+ isBase64: header.includes("base64")
914
+ });
915
+ throw new ValidationError("Failed to decode JSON translation payload");
916
+ }
917
+ }
918
+ async resolveProductId(productId, productName) {
919
+ if (productId) return productId;
920
+ if (!productName) throw new ValidationError("Either productId or productName is required");
921
+ const response = await this.client.query(`
1140
922
  query GetI18nProductByName($name: String!) {
1141
923
  i18nProductByName(name: $name) {
1142
924
  id
1143
925
  }
1144
926
  }
1145
- `;
1146
- const response = await this.client.query(query, {
1147
- name: productName
1148
- }, this.context);
1149
- if (!response.i18nProductByName?.id) {
1150
- throw new ValidationError(`i18n product not found: ${productName}`);
1151
- }
1152
- return response.i18nProductByName.id;
1153
- }
1154
- async findTranslationKeyByKey(productId, key) {
1155
- const query = `
927
+ `, { name: productName }, this.context);
928
+ if (!response.i18nProductByName?.id) throw new ValidationError(`i18n product not found: ${productName}`);
929
+ return response.i18nProductByName.id;
930
+ }
931
+ async findTranslationKeyByKey(productId, key) {
932
+ return (await this.client.query(`
1156
933
  query FindTranslationKey($productId: String!, $key: String!) {
1157
934
  translationKeyByKey(productId: $productId, key: $key) {
1158
935
  id
1159
936
  defaultValue
1160
937
  }
1161
938
  }
1162
- `;
1163
- const response = await this.client.query(query, {
1164
- productId,
1165
- key
1166
- }, this.context);
1167
- return response.translationKeyByKey;
1168
- }
1169
- async createTranslationKey(productId, key, defaultValue) {
1170
- const mutation = `
939
+ `, {
940
+ productId,
941
+ key
942
+ }, this.context)).translationKeyByKey;
943
+ }
944
+ async createTranslationKey(productId, key, defaultValue) {
945
+ return (await this.client.query(`
1171
946
  mutation CreateTranslationKey($input: CreateTranslationKeyInput!) {
1172
947
  createTranslationKey(input: $input) {
1173
948
  id
1174
949
  }
1175
950
  }
1176
- `;
1177
- const response = await this.client.query(mutation, {
1178
- input: {
1179
- productId,
1180
- key,
1181
- defaultValue
1182
- }
1183
- }, this.context);
1184
- return response.createTranslationKey;
1185
- }
1186
- async updateTranslationKeyDefaultValue(id, defaultValue) {
1187
- const mutation = `
951
+ `, { input: {
952
+ productId,
953
+ key,
954
+ defaultValue
955
+ } }, this.context)).createTranslationKey;
956
+ }
957
+ async updateTranslationKeyDefaultValue(id, defaultValue) {
958
+ await this.client.query(`
1188
959
  mutation UpdateTranslationKeyDefault($id: ID!, $input: UpdateTranslationKeyInput!) {
1189
960
  updateTranslationKey(id: $id, input: $input) {
1190
961
  id
1191
962
  }
1192
963
  }
1193
- `;
1194
- await this.client.query(mutation, {
1195
- id,
1196
- input: {
1197
- defaultValue
1198
- }
1199
- }, this.context);
1200
- }
1201
- async findGlobalTranslation(keyId, languageCode) {
1202
- const query = `
964
+ `, {
965
+ id,
966
+ input: { defaultValue }
967
+ }, this.context);
968
+ }
969
+ async findGlobalTranslation(keyId, languageCode) {
970
+ const globalTranslation = (await this.client.query(`
1203
971
  query FindTranslation($filter: TranslationFilterInput) {
1204
972
  translations(filter: $filter, limit: 50, offset: 0) {
1205
973
  items {
@@ -1210,145 +978,122 @@ var TranslationModule = class {
1210
978
  }
1211
979
  }
1212
980
  }
1213
- `;
1214
- const response = await this.client.query(query, {
1215
- filter: {
1216
- keyId,
1217
- languageCode
1218
- }
1219
- }, this.context);
1220
- const globalTranslation = response.translations.items.find((item) => item.tenantId === null);
1221
- if (!globalTranslation) {
1222
- return null;
1223
- }
1224
- return {
1225
- id: globalTranslation.id,
1226
- value: globalTranslation.value,
1227
- status: globalTranslation.status
1228
- };
1229
- }
1230
- async createLanguageTranslation(keyId, languageCode, value) {
1231
- const mutation = `
981
+ `, { filter: {
982
+ keyId,
983
+ languageCode
984
+ } }, this.context)).translations.items.find((item) => item.tenantId === null);
985
+ if (!globalTranslation) return null;
986
+ return {
987
+ id: globalTranslation.id,
988
+ value: globalTranslation.value,
989
+ status: globalTranslation.status
990
+ };
991
+ }
992
+ async createLanguageTranslation(keyId, languageCode, value) {
993
+ return (await this.client.query(`
1232
994
  mutation CreateTranslation($input: CreateTranslationInput!) {
1233
995
  createTranslation(input: $input) {
1234
996
  id
1235
997
  status
1236
998
  }
1237
999
  }
1238
- `;
1239
- const response = await this.client.query(mutation, {
1240
- input: {
1241
- keyId,
1242
- languageCode,
1243
- value
1244
- }
1245
- }, this.context);
1246
- return response.createTranslation;
1247
- }
1248
- async updateLanguageTranslation(id, value, status) {
1249
- const mutation = `
1000
+ `, { input: {
1001
+ keyId,
1002
+ languageCode,
1003
+ value
1004
+ } }, this.context)).createTranslation;
1005
+ }
1006
+ async updateLanguageTranslation(id, value, status) {
1007
+ await this.client.query(`
1250
1008
  mutation UpdateTranslation($id: ID!, $input: UpdateTranslationInput!) {
1251
1009
  updateTranslation(id: $id, input: $input) {
1252
1010
  id
1253
1011
  status
1254
1012
  }
1255
1013
  }
1256
- `;
1257
- await this.client.query(mutation, {
1258
- id,
1259
- input: {
1260
- value,
1261
- status
1262
- }
1263
- }, this.context);
1264
- }
1265
- /**
1266
- * Escape regex special characters in a string
1267
- */
1268
- escapeRegex(str) {
1269
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1270
- }
1271
- /**
1272
- * Interpolate variables in translation string
1273
- */
1274
- interpolate(text, variables) {
1275
- let result = text;
1276
- for (const [key, value] of Object.entries(variables)) {
1277
- const escapedKey = this.escapeRegex(key);
1278
- const regex = new RegExp(`{{\\s*${escapedKey}\\s*}}`, "g");
1279
- result = result.replace(regex, String(value));
1280
- }
1281
- return result;
1282
- }
1283
- /**
1284
- * Format translation with pluralization
1285
- */
1286
- formatPlural(_language, count, translations) {
1287
- if (count === 0 && translations.zero) {
1288
- return translations.zero;
1289
- }
1290
- if (count === 1) {
1291
- return translations.one;
1292
- }
1293
- return translations.other;
1294
- }
1295
- /**
1296
- * Format date/time for locale
1297
- */
1298
- formatDateTime(date, language, options) {
1299
- const dateObj = typeof date === "string" ? new Date(date) : date;
1300
- return new Intl.DateTimeFormat(language, options).format(dateObj);
1301
- }
1302
- /**
1303
- * Format number for locale
1304
- */
1305
- formatNumber(number, language, options) {
1306
- return new Intl.NumberFormat(language, options).format(number);
1307
- }
1308
- /**
1309
- * Format currency for locale
1310
- */
1311
- formatCurrency(amount, currency, language) {
1312
- return new Intl.NumberFormat(language, {
1313
- style: "currency",
1314
- currency
1315
- }).format(amount);
1316
- }
1014
+ `, {
1015
+ id,
1016
+ input: {
1017
+ value,
1018
+ status
1019
+ }
1020
+ }, this.context);
1021
+ }
1022
+ /**
1023
+ * Escape regex special characters in a string
1024
+ */
1025
+ escapeRegex(str) {
1026
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1027
+ }
1028
+ /**
1029
+ * Interpolate variables in translation string
1030
+ */
1031
+ interpolate(text, variables) {
1032
+ let result = text;
1033
+ for (const [key, value] of Object.entries(variables)) {
1034
+ const escapedKey = this.escapeRegex(key);
1035
+ const regex = new RegExp(`{{\\s*${escapedKey}\\s*}}`, "g");
1036
+ result = result.replace(regex, String(value));
1037
+ }
1038
+ return result;
1039
+ }
1040
+ /**
1041
+ * Format translation with pluralization
1042
+ */
1043
+ formatPlural(_language, count, translations) {
1044
+ if (count === 0 && translations.zero) return translations.zero;
1045
+ if (count === 1) return translations.one;
1046
+ return translations.other;
1047
+ }
1048
+ /**
1049
+ * Format date/time for locale
1050
+ */
1051
+ formatDateTime(date, language, options) {
1052
+ const dateObj = typeof date === "string" ? new Date(date) : date;
1053
+ return new Intl.DateTimeFormat(language, options).format(dateObj);
1054
+ }
1055
+ /**
1056
+ * Format number for locale
1057
+ */
1058
+ formatNumber(number, language, options) {
1059
+ return new Intl.NumberFormat(language, options).format(number);
1060
+ }
1061
+ /**
1062
+ * Format currency for locale
1063
+ */
1064
+ formatCurrency(amount, currency, language) {
1065
+ return new Intl.NumberFormat(language, {
1066
+ style: "currency",
1067
+ currency
1068
+ }).format(amount);
1069
+ }
1317
1070
  };
1318
1071
 
1319
1072
  // src/payments/index.ts
1073
+ /**
1074
+ * Payments Module
1075
+ */
1320
1076
  var PaymentsModule = class {
1321
- static {
1322
- __name(this, "PaymentsModule");
1323
- }
1324
- client;
1325
- context;
1326
- constructor(client, context) {
1327
- this.client = client;
1328
- this.context = context;
1329
- }
1330
- /**
1331
- * Create payment
1332
- */
1333
- async createPayment(options) {
1334
- if (typeof options.amount !== "number" || options.amount <= 0) {
1335
- throw new ValidationError("Amount must be a positive number");
1336
- }
1337
- if (!options.currency) {
1338
- throw new ValidationError("Currency is required");
1339
- }
1340
- if (!options.paymentMethod) {
1341
- throw new ValidationError("Payment method is required");
1342
- }
1343
- if (!options.customerId) {
1344
- throw new ValidationError("Customer ID is required");
1345
- }
1346
- logger.debug("[Payments] Creating payment", {
1347
- amount: options.amount,
1348
- currency: options.currency,
1349
- customerId: options.customerId
1350
- });
1351
- const mutation = `
1077
+ client;
1078
+ context;
1079
+ constructor(client, context) {
1080
+ this.client = client;
1081
+ this.context = context;
1082
+ }
1083
+ /**
1084
+ * Create payment
1085
+ */
1086
+ async createPayment(options) {
1087
+ if (typeof options.amount !== "number" || options.amount <= 0) throw new ValidationError("Amount must be a positive number");
1088
+ if (!options.currency) throw new ValidationError("Currency is required");
1089
+ if (!options.paymentMethod) throw new ValidationError("Payment method is required");
1090
+ if (!options.customerId) throw new ValidationError("Customer ID is required");
1091
+ logger.debug("[Payments] Creating payment", {
1092
+ amount: options.amount,
1093
+ currency: options.currency,
1094
+ customerId: options.customerId
1095
+ });
1096
+ const mutation = `
1352
1097
  mutation CreatePayment($input: CreatePaymentInput!) {
1353
1098
  createPayment(input: $input) {
1354
1099
  id
@@ -1368,32 +1113,26 @@ var PaymentsModule = class {
1368
1113
  }
1369
1114
  }
1370
1115
  `;
1371
- const variables = {
1372
- input: {
1373
- amount: options.amount,
1374
- currency: options.currency,
1375
- paymentMethod: options.paymentMethod,
1376
- customerId: options.customerId,
1377
- description: options.description,
1378
- metadata: options.metadata,
1379
- workspaceId: options.workspaceId || this.context.workspaceId,
1380
- organizationId: options.organizationId
1381
- }
1382
- };
1383
- const response = await this.client.query(mutation, variables, this.context);
1384
- logger.info("[Payments] Payment created", {
1385
- paymentId: response.createPayment.id
1386
- });
1387
- return response.createPayment;
1388
- }
1389
- /**
1390
- * Get payment by ID
1391
- */
1392
- async getPayment(paymentId) {
1393
- logger.debug("[Payments] Getting payment", {
1394
- paymentId
1395
- });
1396
- const query = `
1116
+ const variables = { input: {
1117
+ amount: options.amount,
1118
+ currency: options.currency,
1119
+ paymentMethod: options.paymentMethod,
1120
+ customerId: options.customerId,
1121
+ description: options.description,
1122
+ metadata: options.metadata,
1123
+ workspaceId: options.workspaceId || this.context.workspaceId,
1124
+ organizationId: options.organizationId
1125
+ } };
1126
+ const response = await this.client.query(mutation, variables, this.context);
1127
+ logger.info("[Payments] Payment created", { paymentId: response.createPayment.id });
1128
+ return response.createPayment;
1129
+ }
1130
+ /**
1131
+ * Get payment by ID
1132
+ */
1133
+ async getPayment(paymentId) {
1134
+ logger.debug("[Payments] Getting payment", { paymentId });
1135
+ return (await this.client.query(`
1397
1136
  query GetPayment($paymentId: ID!) {
1398
1137
  getPayment(paymentId: $paymentId) {
1399
1138
  id
@@ -1412,18 +1151,14 @@ var PaymentsModule = class {
1412
1151
  updatedAt
1413
1152
  }
1414
1153
  }
1415
- `;
1416
- const response = await this.client.query(query, {
1417
- paymentId
1418
- }, this.context);
1419
- return response.getPayment;
1420
- }
1421
- /**
1422
- * Get payments with filters
1423
- */
1424
- async getPayments(options) {
1425
- logger.debug("[Payments] Getting payments", options);
1426
- const query = `
1154
+ `, { paymentId }, this.context)).getPayment;
1155
+ }
1156
+ /**
1157
+ * Get payments with filters
1158
+ */
1159
+ async getPayments(options) {
1160
+ logger.debug("[Payments] Getting payments", options);
1161
+ const query = `
1427
1162
  query GetPayments(
1428
1163
  $customerId: ID
1429
1164
  $status: PaymentStatus
@@ -1460,28 +1195,27 @@ var PaymentsModule = class {
1460
1195
  }
1461
1196
  }
1462
1197
  `;
1463
- const variables = {
1464
- customerId: options.customerId,
1465
- status: options.status,
1466
- workspaceId: options.workspaceId || this.context.workspaceId,
1467
- organizationId: options.organizationId,
1468
- startDate: options.startDate,
1469
- endDate: options.endDate,
1470
- limit: options.limit || 50,
1471
- offset: options.offset || 0
1472
- };
1473
- const response = await this.client.query(query, variables, this.context);
1474
- return response.getPayments;
1475
- }
1476
- /**
1477
- * Refund payment
1478
- */
1479
- async refundPayment(paymentId, amount, reason) {
1480
- logger.debug("[Payments] Refunding payment", {
1481
- paymentId,
1482
- amount
1483
- });
1484
- const mutation = `
1198
+ const variables = {
1199
+ customerId: options.customerId,
1200
+ status: options.status,
1201
+ workspaceId: options.workspaceId || this.context.workspaceId,
1202
+ organizationId: options.organizationId,
1203
+ startDate: options.startDate,
1204
+ endDate: options.endDate,
1205
+ limit: options.limit || 50,
1206
+ offset: options.offset || 0
1207
+ };
1208
+ return (await this.client.query(query, variables, this.context)).getPayments;
1209
+ }
1210
+ /**
1211
+ * Refund payment
1212
+ */
1213
+ async refundPayment(paymentId, amount, reason) {
1214
+ logger.debug("[Payments] Refunding payment", {
1215
+ paymentId,
1216
+ amount
1217
+ });
1218
+ const response = await this.client.query(`
1485
1219
  mutation RefundPayment($paymentId: ID!, $amount: Int, $reason: String) {
1486
1220
  refundPayment(paymentId: $paymentId, amount: $amount, reason: $reason) {
1487
1221
  id
@@ -1494,60 +1228,48 @@ var PaymentsModule = class {
1494
1228
  updatedAt
1495
1229
  }
1496
1230
  }
1497
- `;
1498
- const response = await this.client.query(mutation, {
1499
- paymentId,
1500
- amount,
1501
- reason
1502
- }, this.context);
1503
- logger.info("[Payments] Payment refunded", {
1504
- paymentId
1505
- });
1506
- return response.refundPayment;
1507
- }
1508
- /**
1509
- * Verify payment
1510
- */
1511
- async verifyPayment(paymentId, verificationData) {
1512
- logger.debug("[Payments] Verifying payment", {
1513
- paymentId
1514
- });
1515
- const mutation = `
1231
+ `, {
1232
+ paymentId,
1233
+ amount,
1234
+ reason
1235
+ }, this.context);
1236
+ logger.info("[Payments] Payment refunded", { paymentId });
1237
+ return response.refundPayment;
1238
+ }
1239
+ /**
1240
+ * Verify payment
1241
+ */
1242
+ async verifyPayment(paymentId, verificationData) {
1243
+ logger.debug("[Payments] Verifying payment", { paymentId });
1244
+ const response = await this.client.query(`
1516
1245
  mutation VerifyPayment($paymentId: ID!, $verificationData: JSON!) {
1517
1246
  verifyPayment(paymentId: $paymentId, verificationData: $verificationData) {
1518
1247
  verified
1519
1248
  status
1520
1249
  }
1521
1250
  }
1522
- `;
1523
- const response = await this.client.query(mutation, {
1524
- paymentId,
1525
- verificationData
1526
- }, this.context);
1527
- logger.info("[Payments] Payment verified", {
1528
- paymentId,
1529
- verified: response.verifyPayment.verified
1530
- });
1531
- return response.verifyPayment;
1532
- }
1533
- /**
1534
- * Create subscription
1535
- */
1536
- async createSubscription(options) {
1537
- if (!options.customerId) {
1538
- throw new ValidationError("Customer ID is required");
1539
- }
1540
- if (!options.planId) {
1541
- throw new ValidationError("Plan ID is required");
1542
- }
1543
- if (!options.paymentMethod) {
1544
- throw new ValidationError("Payment method is required");
1545
- }
1546
- logger.debug("[Payments] Creating subscription", {
1547
- customerId: options.customerId,
1548
- planId: options.planId
1549
- });
1550
- const mutation = `
1251
+ `, {
1252
+ paymentId,
1253
+ verificationData
1254
+ }, this.context);
1255
+ logger.info("[Payments] Payment verified", {
1256
+ paymentId,
1257
+ verified: response.verifyPayment.verified
1258
+ });
1259
+ return response.verifyPayment;
1260
+ }
1261
+ /**
1262
+ * Create subscription
1263
+ */
1264
+ async createSubscription(options) {
1265
+ if (!options.customerId) throw new ValidationError("Customer ID is required");
1266
+ if (!options.planId) throw new ValidationError("Plan ID is required");
1267
+ if (!options.paymentMethod) throw new ValidationError("Payment method is required");
1268
+ logger.debug("[Payments] Creating subscription", {
1269
+ customerId: options.customerId,
1270
+ planId: options.planId
1271
+ });
1272
+ const mutation = `
1551
1273
  mutation CreateSubscription($input: CreateSubscriptionInput!) {
1552
1274
  createSubscription(input: $input) {
1553
1275
  id
@@ -1567,31 +1289,25 @@ var PaymentsModule = class {
1567
1289
  }
1568
1290
  }
1569
1291
  `;
1570
- const variables = {
1571
- input: {
1572
- customerId: options.customerId,
1573
- planId: options.planId,
1574
- paymentMethod: options.paymentMethod,
1575
- trialDays: options.trialDays,
1576
- metadata: options.metadata,
1577
- workspaceId: options.workspaceId || this.context.workspaceId,
1578
- organizationId: options.organizationId
1579
- }
1580
- };
1581
- const response = await this.client.query(mutation, variables, this.context);
1582
- logger.info("[Payments] Subscription created", {
1583
- subscriptionId: response.createSubscription.id
1584
- });
1585
- return response.createSubscription;
1586
- }
1587
- /**
1588
- * Get subscription
1589
- */
1590
- async getSubscription(subscriptionId) {
1591
- logger.debug("[Payments] Getting subscription", {
1592
- subscriptionId
1593
- });
1594
- const query = `
1292
+ const variables = { input: {
1293
+ customerId: options.customerId,
1294
+ planId: options.planId,
1295
+ paymentMethod: options.paymentMethod,
1296
+ trialDays: options.trialDays,
1297
+ metadata: options.metadata,
1298
+ workspaceId: options.workspaceId || this.context.workspaceId,
1299
+ organizationId: options.organizationId
1300
+ } };
1301
+ const response = await this.client.query(mutation, variables, this.context);
1302
+ logger.info("[Payments] Subscription created", { subscriptionId: response.createSubscription.id });
1303
+ return response.createSubscription;
1304
+ }
1305
+ /**
1306
+ * Get subscription
1307
+ */
1308
+ async getSubscription(subscriptionId) {
1309
+ logger.debug("[Payments] Getting subscription", { subscriptionId });
1310
+ return (await this.client.query(`
1595
1311
  query GetSubscription($subscriptionId: ID!) {
1596
1312
  getSubscription(subscriptionId: $subscriptionId) {
1597
1313
  id
@@ -1610,21 +1326,17 @@ var PaymentsModule = class {
1610
1326
  updatedAt
1611
1327
  }
1612
1328
  }
1613
- `;
1614
- const response = await this.client.query(query, {
1615
- subscriptionId
1616
- }, this.context);
1617
- return response.getSubscription;
1618
- }
1619
- /**
1620
- * Cancel subscription
1621
- */
1622
- async cancelSubscription(subscriptionId, cancelAtPeriodEnd = false) {
1623
- logger.debug("[Payments] Cancelling subscription", {
1624
- subscriptionId,
1625
- cancelAtPeriodEnd
1626
- });
1627
- const mutation = `
1329
+ `, { subscriptionId }, this.context)).getSubscription;
1330
+ }
1331
+ /**
1332
+ * Cancel subscription
1333
+ */
1334
+ async cancelSubscription(subscriptionId, cancelAtPeriodEnd = false) {
1335
+ logger.debug("[Payments] Cancelling subscription", {
1336
+ subscriptionId,
1337
+ cancelAtPeriodEnd
1338
+ });
1339
+ const response = await this.client.query(`
1628
1340
  mutation CancelSubscription($subscriptionId: ID!, $cancelAtPeriodEnd: Boolean!) {
1629
1341
  cancelSubscription(subscriptionId: $subscriptionId, cancelAtPeriodEnd: $cancelAtPeriodEnd) {
1630
1342
  id
@@ -1634,24 +1346,19 @@ var PaymentsModule = class {
1634
1346
  updatedAt
1635
1347
  }
1636
1348
  }
1637
- `;
1638
- const response = await this.client.query(mutation, {
1639
- subscriptionId,
1640
- cancelAtPeriodEnd
1641
- }, this.context);
1642
- logger.info("[Payments] Subscription cancelled", {
1643
- subscriptionId
1644
- });
1645
- return response.cancelSubscription;
1646
- }
1647
- /**
1648
- * Get customer subscriptions
1649
- */
1650
- async getCustomerSubscriptions(customerId) {
1651
- logger.debug("[Payments] Getting customer subscriptions", {
1652
- customerId
1653
- });
1654
- const query = `
1349
+ `, {
1350
+ subscriptionId,
1351
+ cancelAtPeriodEnd
1352
+ }, this.context);
1353
+ logger.info("[Payments] Subscription cancelled", { subscriptionId });
1354
+ return response.cancelSubscription;
1355
+ }
1356
+ /**
1357
+ * Get customer subscriptions
1358
+ */
1359
+ async getCustomerSubscriptions(customerId) {
1360
+ logger.debug("[Payments] Getting customer subscriptions", { customerId });
1361
+ return (await this.client.query(`
1655
1362
  query GetCustomerSubscriptions($customerId: ID!) {
1656
1363
  getCustomerSubscriptions(customerId: $customerId) {
1657
1364
  id
@@ -1665,20 +1372,14 @@ var PaymentsModule = class {
1665
1372
  createdAt
1666
1373
  }
1667
1374
  }
1668
- `;
1669
- const response = await this.client.query(query, {
1670
- customerId
1671
- }, this.context);
1672
- return response.getCustomerSubscriptions;
1673
- }
1674
- /**
1675
- * Get plans
1676
- */
1677
- async getPlans(activeOnly = true) {
1678
- logger.debug("[Payments] Getting plans", {
1679
- activeOnly
1680
- });
1681
- const query = `
1375
+ `, { customerId }, this.context)).getCustomerSubscriptions;
1376
+ }
1377
+ /**
1378
+ * Get plans
1379
+ */
1380
+ async getPlans(activeOnly = true) {
1381
+ logger.debug("[Payments] Getting plans", { activeOnly });
1382
+ return (await this.client.query(`
1682
1383
  query GetPlans($activeOnly: Boolean!) {
1683
1384
  getPlans(activeOnly: $activeOnly) {
1684
1385
  id
@@ -1694,42 +1395,33 @@ var PaymentsModule = class {
1694
1395
  createdAt
1695
1396
  }
1696
1397
  }
1697
- `;
1698
- const response = await this.client.query(query, {
1699
- activeOnly
1700
- }, this.context);
1701
- return response.getPlans;
1702
- }
1703
- /**
1704
- * Create payment intent
1705
- */
1706
- async createPaymentIntent(options) {
1707
- logger.debug("[Payments] Creating payment intent", {
1708
- amount: options.amount,
1709
- currency: options.currency
1710
- });
1711
- const mutation = `
1398
+ `, { activeOnly }, this.context)).getPlans;
1399
+ }
1400
+ /**
1401
+ * Create payment intent
1402
+ */
1403
+ async createPaymentIntent(options) {
1404
+ logger.debug("[Payments] Creating payment intent", {
1405
+ amount: options.amount,
1406
+ currency: options.currency
1407
+ });
1408
+ const response = await this.client.query(`
1712
1409
  mutation CreatePaymentIntent($input: CreatePaymentIntentInput!) {
1713
1410
  createPaymentIntent(input: $input) {
1714
1411
  clientSecret
1715
1412
  paymentIntentId
1716
1413
  }
1717
1414
  }
1718
- `;
1719
- const response = await this.client.query(mutation, {
1720
- input: options
1721
- }, this.context);
1722
- logger.info("[Payments] Payment intent created", {
1723
- paymentIntentId: response.createPaymentIntent.paymentIntentId
1724
- });
1725
- return response.createPaymentIntent;
1726
- }
1727
- /**
1728
- * Get payment statistics
1729
- */
1730
- async getPaymentStats(options) {
1731
- logger.debug("[Payments] Getting payment statistics", options);
1732
- const query = `
1415
+ `, { input: options }, this.context);
1416
+ logger.info("[Payments] Payment intent created", { paymentIntentId: response.createPaymentIntent.paymentIntentId });
1417
+ return response.createPaymentIntent;
1418
+ }
1419
+ /**
1420
+ * Get payment statistics
1421
+ */
1422
+ async getPaymentStats(options) {
1423
+ logger.debug("[Payments] Getting payment statistics", options);
1424
+ return (await this.client.query(`
1733
1425
  query GetPaymentStats($startDate: DateTime, $endDate: DateTime, $workspaceId: ID) {
1734
1426
  getPaymentStats(startDate: $startDate, endDate: $endDate, workspaceId: $workspaceId) {
1735
1427
  totalRevenue
@@ -1740,873 +1432,830 @@ var PaymentsModule = class {
1740
1432
  averagePaymentAmount
1741
1433
  }
1742
1434
  }
1743
- `;
1744
- const response = await this.client.query(query, {
1745
- startDate: options?.startDate,
1746
- endDate: options?.endDate,
1747
- workspaceId: options?.workspaceId || this.context.workspaceId
1748
- }, this.context);
1749
- return response.getPaymentStats;
1750
- }
1435
+ `, {
1436
+ startDate: options?.startDate,
1437
+ endDate: options?.endDate,
1438
+ workspaceId: options?.workspaceId || this.context.workspaceId
1439
+ }, this.context)).getPaymentStats;
1440
+ }
1751
1441
  };
1752
1442
 
1753
1443
  // src/bootstrap/index.ts
1444
+ /**
1445
+ * Bootstrap Module
1446
+ * Helpers for bootstrapping server, loading modules, and setting up schemas
1447
+ */
1448
+ /**
1449
+ * Bootstrap Module
1450
+ */
1754
1451
  var BootstrapModule = class {
1755
- static {
1756
- __name(this, "BootstrapModule");
1757
- }
1758
- config;
1759
- startTime;
1760
- healthCheckInterval;
1761
- constructor(config) {
1762
- this.config = config;
1763
- this.startTime = /* @__PURE__ */ new Date();
1764
- }
1765
- /**
1766
- * Bootstrap the application
1767
- */
1768
- async bootstrap() {
1769
- logger.info("[Bootstrap] Starting application bootstrap", {
1770
- serviceName: this.config.serviceName,
1771
- environment: this.config.environment || "development"
1772
- });
1773
- try {
1774
- await this.validateConfiguration();
1775
- const databaseConnected = await this.connectDatabase();
1776
- const loadedModules = await this.loadModules();
1777
- if (this.config.healthCheck) {
1778
- await this.setupHealthChecks();
1779
- }
1780
- this.setupSignalHandlers();
1781
- const result = {
1782
- success: true,
1783
- serviceName: this.config.serviceName || "burdenoff-service",
1784
- serviceVersion: this.config.serviceVersion || "1.0.0",
1785
- environment: this.config.environment || "development",
1786
- startedAt: this.startTime.toISOString(),
1787
- modules: loadedModules,
1788
- databaseConnected,
1789
- healthCheckEnabled: this.config.healthCheck || false
1790
- };
1791
- logger.info("[Bootstrap] Application bootstrapped successfully", result);
1792
- return result;
1793
- } catch (error) {
1794
- logger.error("[Bootstrap] Failed to bootstrap application", {
1795
- error
1796
- });
1797
- throw error;
1798
- }
1799
- }
1800
- /**
1801
- * Validate configuration
1802
- */
1803
- async validateConfiguration() {
1804
- logger.debug("[Bootstrap] Validating configuration");
1805
- if (!this.config.workspacesApiUrl) {
1806
- throw new Error("Workspaces API URL is required");
1807
- }
1808
- if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) {
1809
- throw new Error("Invalid database URL");
1810
- }
1811
- logger.debug("[Bootstrap] Configuration validated");
1812
- }
1813
- /**
1814
- * Connect to database
1815
- */
1816
- async connectDatabase() {
1817
- if (!this.config.database) {
1818
- logger.debug("[Bootstrap] No database configuration provided, skipping");
1819
- return false;
1820
- }
1821
- logger.info("[Bootstrap] Connecting to database");
1822
- try {
1823
- const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);
1824
- logger.info("[Bootstrap] Database connection configured", {
1825
- url: sanitizedUrl
1826
- });
1827
- return true;
1828
- } catch (error) {
1829
- logger.error("[Bootstrap] Failed to connect to database", {
1830
- error
1831
- });
1832
- return false;
1833
- }
1834
- }
1835
- /**
1836
- * Load modules
1837
- */
1838
- async loadModules() {
1839
- const modules = this.config.modules || [];
1840
- if (modules.length === 0) {
1841
- logger.debug("[Bootstrap] No modules to load");
1842
- return [];
1843
- }
1844
- logger.info("[Bootstrap] Loading modules", {
1845
- modules
1846
- });
1847
- const loadedModules = [];
1848
- for (const moduleName of modules) {
1849
- try {
1850
- logger.debug(`[Bootstrap] Loading module: ${moduleName}`);
1851
- loadedModules.push(moduleName);
1852
- } catch (error) {
1853
- logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, {
1854
- error
1855
- });
1856
- }
1857
- }
1858
- logger.info("[Bootstrap] Modules loaded", {
1859
- loaded: loadedModules
1860
- });
1861
- return loadedModules;
1862
- }
1863
- /**
1864
- * Setup health checks
1865
- */
1866
- async setupHealthChecks() {
1867
- logger.info("[Bootstrap] Setting up health checks");
1868
- const interval = this.config.healthCheckInterval || 3e4;
1869
- this.healthCheckInterval = setInterval(() => {
1870
- void (async () => {
1871
- const health = await this.performHealthCheck();
1872
- if (!health.healthy) {
1873
- logger.warn("[Bootstrap] Health check failed", health);
1874
- } else {
1875
- logger.debug("[Bootstrap] Health check passed", health);
1876
- }
1877
- })();
1878
- }, interval);
1879
- logger.info("[Bootstrap] Health checks configured", {
1880
- interval
1881
- });
1882
- }
1883
- /**
1884
- * Perform health check
1885
- */
1886
- async performHealthCheck() {
1887
- const checks = {};
1888
- const memUsage = process.memoryUsage();
1889
- checks.memory = {
1890
- used: memUsage.heapUsed,
1891
- total: memUsage.heapTotal,
1892
- percentage: memUsage.heapUsed / memUsage.heapTotal * 100
1893
- };
1894
- checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1e3);
1895
- const healthy = checks.memory.percentage < 90 && // Less than 90% memory usage
1896
- checks.uptime > 0;
1897
- return {
1898
- healthy,
1899
- checks,
1900
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
1901
- };
1902
- }
1903
- /**
1904
- * Setup signal handlers for graceful shutdown
1905
- */
1906
- setupSignalHandlers() {
1907
- logger.debug("[Bootstrap] Setting up signal handlers");
1908
- const gracefulShutdown = /* @__PURE__ */ __name(async (signal) => {
1909
- logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);
1910
- if (this.healthCheckInterval) {
1911
- clearInterval(this.healthCheckInterval);
1912
- }
1913
- await this.cleanup();
1914
- process.exit(0);
1915
- }, "gracefulShutdown");
1916
- process.on("SIGTERM", () => {
1917
- void gracefulShutdown("SIGTERM");
1918
- });
1919
- process.on("SIGINT", () => {
1920
- void gracefulShutdown("SIGINT");
1921
- });
1922
- process.on("unhandledRejection", (reason, promise) => {
1923
- logger.error("[Bootstrap] Unhandled rejection", {
1924
- reason,
1925
- promise
1926
- });
1927
- });
1928
- process.on("uncaughtException", (error) => {
1929
- logger.error("[Bootstrap] Uncaught exception", {
1930
- error
1931
- });
1932
- process.exit(1);
1933
- });
1934
- }
1935
- /**
1936
- * Cleanup on shutdown
1937
- */
1938
- async cleanup() {
1939
- logger.info("[Bootstrap] Performing cleanup");
1940
- await disposeAll();
1941
- ContextManager.clearContext();
1942
- logger.info("[Bootstrap] Cleanup completed");
1943
- }
1944
- /**
1945
- * Get application info
1946
- */
1947
- getInfo() {
1948
- return {
1949
- serviceName: this.config.serviceName || "burdenoff-service",
1950
- serviceVersion: this.config.serviceVersion || "1.0.0",
1951
- environment: this.config.environment || "development",
1952
- uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
1953
- startedAt: this.startTime.toISOString()
1954
- };
1955
- }
1956
- /**
1957
- * Setup default context
1958
- */
1959
- setupDefaultContext(context) {
1960
- logger.debug("[Bootstrap] Setting up default context", context);
1961
- ContextManager.setContext(context);
1962
- }
1963
- /**
1964
- * Create context middleware (for Elysia/HTTP frameworks)
1965
- */
1966
- createContextMiddleware() {
1967
- return async (req, _res, next) => {
1968
- const context = this.extractContextFromRequest(req);
1969
- ContextManager.setContext(context);
1970
- next();
1971
- };
1972
- }
1973
- /**
1974
- * Extract context from request
1975
- */
1976
- extractContextFromRequest(req) {
1977
- const context = {};
1978
- if (req.user) {
1979
- context.actorId = req.user.user_id;
1980
- context.workspaceId = req.user.workspace_id;
1981
- context.tenantId = req.user.tenant_endpoint;
1982
- }
1983
- const getHeader = /* @__PURE__ */ __name((key) => {
1984
- const value = req.headers[key.toLowerCase()];
1985
- return Array.isArray(value) ? value[0] : value;
1986
- }, "getHeader");
1987
- const authHeader = getHeader("authorization");
1988
- if (authHeader) {
1989
- context.token = authHeader.replace("Bearer ", "");
1990
- }
1991
- const workspaceId = getHeader("x-workspace-id");
1992
- if (workspaceId && !context.workspaceId) {
1993
- context.workspaceId = workspaceId;
1994
- }
1995
- const productId = getHeader("x-product-id");
1996
- if (productId) {
1997
- context.productId = productId;
1998
- }
1999
- const projectId = getHeader("x-project-id");
2000
- if (projectId) {
2001
- context.projectId = projectId;
2002
- }
2003
- const appId = getHeader("x-app-id");
2004
- if (appId) {
2005
- context.appId = appId;
2006
- }
2007
- const cfAccessClientId = getHeader("cf-access-client-id");
2008
- if (cfAccessClientId) {
2009
- context.cfAccessClientId = cfAccessClientId;
2010
- }
2011
- const cfAccessClientSecret = getHeader("cf-access-client-secret");
2012
- if (cfAccessClientSecret) {
2013
- context.cfAccessClientSecret = cfAccessClientSecret;
2014
- }
2015
- const cfAuthorization = getHeader("x-cf-authorization");
2016
- if (cfAuthorization) {
2017
- context.cfAuthorization = cfAuthorization;
2018
- }
2019
- return context;
2020
- }
2021
- /**
2022
- * Load GraphQL schema
2023
- */
2024
- async loadSchema(schemaPath) {
2025
- logger.info("[Bootstrap] Loading GraphQL schema", {
2026
- schemaPath
2027
- });
2028
- try {
2029
- logger.info("[Bootstrap] Schema loaded successfully");
2030
- return true;
2031
- } catch (error) {
2032
- logger.error("[Bootstrap] Failed to load schema", {
2033
- error
2034
- });
2035
- return false;
2036
- }
2037
- }
2038
- /**
2039
- * Register shutdown hook
2040
- */
2041
- onShutdown(callback) {
2042
- const originalHandler = process.listeners("SIGTERM")[0];
2043
- process.removeAllListeners("SIGTERM");
2044
- process.on("SIGTERM", () => {
2045
- void (async () => {
2046
- await callback();
2047
- if (typeof originalHandler === "function") {
2048
- originalHandler();
2049
- }
2050
- })();
2051
- });
2052
- }
2053
- /**
2054
- * Check if application is ready
2055
- */
2056
- async isReady() {
2057
- const health = await this.performHealthCheck();
2058
- return health.healthy;
2059
- }
2060
- /**
2061
- * Get metrics
2062
- */
2063
- getMetrics() {
2064
- return {
2065
- memory: process.memoryUsage(),
2066
- uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
2067
- cpu: process.cpuUsage()
2068
- };
2069
- }
1452
+ config;
1453
+ startTime;
1454
+ healthCheckInterval;
1455
+ constructor(config) {
1456
+ this.config = config;
1457
+ this.startTime = /* @__PURE__ */ new Date();
1458
+ }
1459
+ /**
1460
+ * Bootstrap the application
1461
+ */
1462
+ async bootstrap() {
1463
+ logger.info("[Bootstrap] Starting application bootstrap", {
1464
+ serviceName: this.config.serviceName,
1465
+ environment: this.config.environment || "development"
1466
+ });
1467
+ try {
1468
+ await this.validateConfiguration();
1469
+ const databaseConnected = await this.connectDatabase();
1470
+ const loadedModules = await this.loadModules();
1471
+ if (this.config.healthCheck) await this.setupHealthChecks();
1472
+ this.setupSignalHandlers();
1473
+ const result = {
1474
+ success: true,
1475
+ serviceName: this.config.serviceName || "burdenoff-service",
1476
+ serviceVersion: this.config.serviceVersion || "1.0.0",
1477
+ environment: this.config.environment || "development",
1478
+ startedAt: this.startTime.toISOString(),
1479
+ modules: loadedModules,
1480
+ databaseConnected,
1481
+ healthCheckEnabled: this.config.healthCheck || false
1482
+ };
1483
+ logger.info("[Bootstrap] Application bootstrapped successfully", result);
1484
+ return result;
1485
+ } catch (error) {
1486
+ logger.error("[Bootstrap] Failed to bootstrap application", { error });
1487
+ throw error;
1488
+ }
1489
+ }
1490
+ /**
1491
+ * Validate configuration
1492
+ */
1493
+ async validateConfiguration() {
1494
+ logger.debug("[Bootstrap] Validating configuration");
1495
+ if (!this.config.workspacesApiUrl) throw new Error("Workspaces API URL is required");
1496
+ if (this.config.database?.url && !DatabaseModule.validateDatabaseUrl(this.config.database.url)) throw new Error("Invalid database URL");
1497
+ logger.debug("[Bootstrap] Configuration validated");
1498
+ }
1499
+ /**
1500
+ * Connect to database
1501
+ */
1502
+ async connectDatabase() {
1503
+ if (!this.config.database) {
1504
+ logger.debug("[Bootstrap] No database configuration provided, skipping");
1505
+ return false;
1506
+ }
1507
+ logger.info("[Bootstrap] Connecting to database");
1508
+ try {
1509
+ const sanitizedUrl = DatabaseModule.sanitizeDatabaseUrl(this.config.database.url);
1510
+ logger.info("[Bootstrap] Database connection configured", { url: sanitizedUrl });
1511
+ return true;
1512
+ } catch (error) {
1513
+ logger.error("[Bootstrap] Failed to connect to database", { error });
1514
+ return false;
1515
+ }
1516
+ }
1517
+ /**
1518
+ * Load modules
1519
+ */
1520
+ async loadModules() {
1521
+ const modules = this.config.modules || [];
1522
+ if (modules.length === 0) {
1523
+ logger.debug("[Bootstrap] No modules to load");
1524
+ return [];
1525
+ }
1526
+ logger.info("[Bootstrap] Loading modules", { modules });
1527
+ const loadedModules = [];
1528
+ for (const moduleName of modules) try {
1529
+ logger.debug(`[Bootstrap] Loading module: ${moduleName}`);
1530
+ loadedModules.push(moduleName);
1531
+ } catch (error) {
1532
+ logger.error(`[Bootstrap] Failed to load module: ${moduleName}`, { error });
1533
+ }
1534
+ logger.info("[Bootstrap] Modules loaded", { loaded: loadedModules });
1535
+ return loadedModules;
1536
+ }
1537
+ /**
1538
+ * Setup health checks
1539
+ */
1540
+ async setupHealthChecks() {
1541
+ logger.info("[Bootstrap] Setting up health checks");
1542
+ const interval = this.config.healthCheckInterval || 3e4;
1543
+ this.healthCheckInterval = setInterval(() => {
1544
+ (async () => {
1545
+ const health = await this.performHealthCheck();
1546
+ if (!health.healthy) logger.warn("[Bootstrap] Health check failed", health);
1547
+ else logger.debug("[Bootstrap] Health check passed", health);
1548
+ })();
1549
+ }, interval);
1550
+ logger.info("[Bootstrap] Health checks configured", { interval });
1551
+ }
1552
+ /**
1553
+ * Perform health check
1554
+ */
1555
+ async performHealthCheck() {
1556
+ const checks = {};
1557
+ const memUsage = process.memoryUsage();
1558
+ checks.memory = {
1559
+ used: memUsage.heapUsed,
1560
+ total: memUsage.heapTotal,
1561
+ percentage: memUsage.heapUsed / memUsage.heapTotal * 100
1562
+ };
1563
+ checks.uptime = Math.floor((Date.now() - this.startTime.getTime()) / 1e3);
1564
+ return {
1565
+ healthy: checks.memory.percentage < 90 && checks.uptime > 0,
1566
+ checks,
1567
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
1568
+ };
1569
+ }
1570
+ /**
1571
+ * Setup signal handlers for graceful shutdown
1572
+ */
1573
+ setupSignalHandlers() {
1574
+ logger.debug("[Bootstrap] Setting up signal handlers");
1575
+ const gracefulShutdown = async (signal) => {
1576
+ logger.info(`[Bootstrap] Received ${signal}, shutting down gracefully`);
1577
+ if (this.healthCheckInterval) clearInterval(this.healthCheckInterval);
1578
+ await this.cleanup();
1579
+ process.exit(0);
1580
+ };
1581
+ process.on("SIGTERM", () => {
1582
+ gracefulShutdown("SIGTERM");
1583
+ });
1584
+ process.on("SIGINT", () => {
1585
+ gracefulShutdown("SIGINT");
1586
+ });
1587
+ process.on("unhandledRejection", (reason, promise) => {
1588
+ logger.error("[Bootstrap] Unhandled rejection", {
1589
+ reason,
1590
+ promise
1591
+ });
1592
+ });
1593
+ process.on("uncaughtException", (error) => {
1594
+ logger.error("[Bootstrap] Uncaught exception", { error });
1595
+ process.exit(1);
1596
+ });
1597
+ }
1598
+ /**
1599
+ * Cleanup on shutdown
1600
+ */
1601
+ async cleanup() {
1602
+ logger.info("[Bootstrap] Performing cleanup");
1603
+ await disposeAll();
1604
+ ContextManager.clearContext();
1605
+ logger.info("[Bootstrap] Cleanup completed");
1606
+ }
1607
+ /**
1608
+ * Get application info
1609
+ */
1610
+ getInfo() {
1611
+ return {
1612
+ serviceName: this.config.serviceName || "burdenoff-service",
1613
+ serviceVersion: this.config.serviceVersion || "1.0.0",
1614
+ environment: this.config.environment || "development",
1615
+ uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
1616
+ startedAt: this.startTime.toISOString()
1617
+ };
1618
+ }
1619
+ /**
1620
+ * Setup default context
1621
+ */
1622
+ setupDefaultContext(context) {
1623
+ logger.debug("[Bootstrap] Setting up default context", context);
1624
+ ContextManager.setContext(context);
1625
+ }
1626
+ /**
1627
+ * Create context middleware (for Elysia/HTTP frameworks)
1628
+ */
1629
+ createContextMiddleware() {
1630
+ return async (req, _res, next) => {
1631
+ const context = this.extractContextFromRequest(req);
1632
+ ContextManager.setContext(context);
1633
+ next();
1634
+ };
1635
+ }
1636
+ /**
1637
+ * Extract context from request
1638
+ */
1639
+ extractContextFromRequest(req) {
1640
+ const context = {};
1641
+ if (req.user) {
1642
+ context.actorId = req.user.user_id;
1643
+ context.workspaceId = req.user.workspace_id;
1644
+ context.tenantId = req.user.tenant_endpoint;
1645
+ }
1646
+ const getHeader = (key) => {
1647
+ const value = req.headers[key.toLowerCase()];
1648
+ return Array.isArray(value) ? value[0] : value;
1649
+ };
1650
+ const authHeader = getHeader("authorization");
1651
+ if (authHeader) context.token = authHeader.replace("Bearer ", "");
1652
+ const workspaceId = getHeader("x-workspace-id");
1653
+ if (workspaceId && !context.workspaceId) context.workspaceId = workspaceId;
1654
+ const productId = getHeader("x-product-id");
1655
+ if (productId) context.productId = productId;
1656
+ const projectId = getHeader("x-project-id");
1657
+ if (projectId) context.projectId = projectId;
1658
+ const appId = getHeader("x-app-id");
1659
+ if (appId) context.appId = appId;
1660
+ const cfAccessClientId = getHeader("cf-access-client-id");
1661
+ if (cfAccessClientId) context.cfAccessClientId = cfAccessClientId;
1662
+ const cfAccessClientSecret = getHeader("cf-access-client-secret");
1663
+ if (cfAccessClientSecret) context.cfAccessClientSecret = cfAccessClientSecret;
1664
+ const cfAuthorization = getHeader("x-cf-authorization");
1665
+ if (cfAuthorization) context.cfAuthorization = cfAuthorization;
1666
+ return context;
1667
+ }
1668
+ /**
1669
+ * Load GraphQL schema
1670
+ */
1671
+ async loadSchema(schemaPath) {
1672
+ logger.info("[Bootstrap] Loading GraphQL schema", { schemaPath });
1673
+ try {
1674
+ logger.info("[Bootstrap] Schema loaded successfully");
1675
+ return true;
1676
+ } catch (error) {
1677
+ logger.error("[Bootstrap] Failed to load schema", { error });
1678
+ return false;
1679
+ }
1680
+ }
1681
+ /**
1682
+ * Register shutdown hook
1683
+ */
1684
+ onShutdown(callback) {
1685
+ const originalHandler = process.listeners("SIGTERM")[0];
1686
+ process.removeAllListeners("SIGTERM");
1687
+ process.on("SIGTERM", () => {
1688
+ (async () => {
1689
+ await callback();
1690
+ if (typeof originalHandler === "function") originalHandler();
1691
+ })();
1692
+ });
1693
+ }
1694
+ /**
1695
+ * Check if application is ready
1696
+ */
1697
+ async isReady() {
1698
+ return (await this.performHealthCheck()).healthy;
1699
+ }
1700
+ /**
1701
+ * Get metrics
1702
+ */
1703
+ getMetrics() {
1704
+ return {
1705
+ memory: process.memoryUsage(),
1706
+ uptime: Math.floor((Date.now() - this.startTime.getTime()) / 1e3),
1707
+ cpu: process.cpuUsage()
1708
+ };
1709
+ }
2070
1710
  };
1711
+ /**
1712
+ * Create bootstrap instance
1713
+ */
2071
1714
  function createBootstrap(config) {
2072
- return new BootstrapModule(config);
1715
+ return new BootstrapModule(config);
2073
1716
  }
2074
- __name(createBootstrap, "createBootstrap");
2075
1717
 
2076
1718
  // src/client/tenant-backend.ts
1719
+ /**
1720
+ * Tenant Backend Client
1721
+ * Centralized client for accessing tenant-backend services (notifications, auth, etc.)
1722
+ *
1723
+ * This is a reusable utility that can be used by any backend to communicate with tenant-backend.
1724
+ */
1725
+ /**
1726
+ * Tenant Backend Client
1727
+ * Provides access to centralized tenant-backend services using be-sdk
1728
+ *
1729
+ * @example
1730
+ * ```typescript
1731
+ * import { TenantBackendClient } from '@burdenoff/be-sdk';
1732
+ *
1733
+ * const client = new TenantBackendClient({
1734
+ * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,
1735
+ * workspacesBackendUrl: process.env.WORKSPACES_BACKEND_URL,
1736
+ * apiKey: process.env.TENANT_BACKEND_API_KEY,
1737
+ * });
1738
+ *
1739
+ * // Send notification
1740
+ * await client.notifications.sendWithTemplate({
1741
+ * templateSlug: 'user-welcome',
1742
+ * recipients: ['user@example.com'],
1743
+ * variables: { userName: 'John' },
1744
+ * });
1745
+ *
1746
+ * // Execute raw query
1747
+ * const result = await client.query(`
1748
+ * query GetUser($id: ID!) {
1749
+ * user(id: $id) { id name email }
1750
+ * }
1751
+ * `, { id: 'user-123' });
1752
+ * ```
1753
+ */
2077
1754
  var TenantBackendClient = class {
2078
- static {
2079
- __name(this, "TenantBackendClient");
2080
- }
2081
- graphqlClient;
2082
- config;
2083
- /** Notifications module for sending notifications via tenant backend */
2084
- notifications;
2085
- constructor(config) {
2086
- this.config = config;
2087
- const sdkConfig = {
2088
- workspacesApiUrl: config.workspacesBackendUrl || "http://localhost:4000/graphql",
2089
- tenantApiUrl: config.tenantBackendUrl
2090
- };
2091
- this.graphqlClient = new BurdenoffGraphQLClient(sdkConfig, {});
2092
- this.notifications = new TenantNotificationsModule(this.graphqlClient, {});
2093
- logger.info("[TenantBackend] Client initialized using be-sdk", {
2094
- tenantUrl: config.tenantBackendUrl,
2095
- workspacesUrl: config.workspacesBackendUrl,
2096
- hasApiKey: !!config.apiKey
2097
- });
2098
- }
2099
- /**
2100
- * Update authentication token
2101
- *
2102
- * @param token - JWT token for authentication
2103
- */
2104
- setAuthToken(token) {
2105
- this.graphqlClient.updateContext({
2106
- token
2107
- });
2108
- logger.debug("[TenantBackend] Authentication token updated");
2109
- }
2110
- /**
2111
- * Execute raw GraphQL query against tenant backend
2112
- *
2113
- * @param query - GraphQL query string
2114
- * @param variables - Query variables
2115
- * @returns Query result
2116
- *
2117
- * @example
2118
- * ```typescript
2119
- * const result = await client.query(`
2120
- * query GetTemplate($slug: String!) {
2121
- * notificationTemplate(slug: $slug) {
2122
- * id
2123
- * slug
2124
- * subject
2125
- * }
2126
- * }
2127
- * `, { slug: 'user-welcome' });
2128
- * ```
2129
- */
2130
- async query(query, variables) {
2131
- return this.graphqlClient.tenantQuery(query, variables);
2132
- }
2133
- /**
2134
- * Health check
2135
- *
2136
- * @returns True if tenant backend is reachable, false otherwise
2137
- */
2138
- async healthCheck() {
2139
- try {
2140
- const query = `
1755
+ graphqlClient;
1756
+ config;
1757
+ /** Notifications module for sending notifications via tenant backend */
1758
+ notifications;
1759
+ constructor(config) {
1760
+ this.config = config;
1761
+ const sdkConfig = {
1762
+ workspacesApiUrl: config.workspacesBackendUrl || "http://localhost:4000/graphql",
1763
+ tenantApiUrl: config.tenantBackendUrl
1764
+ };
1765
+ this.graphqlClient = new BurdenoffGraphQLClient(sdkConfig, {});
1766
+ this.notifications = new TenantNotificationsModule(this.graphqlClient, {});
1767
+ logger.info("[TenantBackend] Client initialized using be-sdk", {
1768
+ tenantUrl: config.tenantBackendUrl,
1769
+ workspacesUrl: config.workspacesBackendUrl,
1770
+ hasApiKey: !!config.apiKey
1771
+ });
1772
+ }
1773
+ /**
1774
+ * Update authentication token
1775
+ *
1776
+ * @param token - JWT token for authentication
1777
+ */
1778
+ setAuthToken(token) {
1779
+ this.graphqlClient.updateContext({ token });
1780
+ logger.debug("[TenantBackend] Authentication token updated");
1781
+ }
1782
+ /**
1783
+ * Execute raw GraphQL query against tenant backend
1784
+ *
1785
+ * @param query - GraphQL query string
1786
+ * @param variables - Query variables
1787
+ * @returns Query result
1788
+ *
1789
+ * @example
1790
+ * ```typescript
1791
+ * const result = await client.query(`
1792
+ * query GetTemplate($slug: String!) {
1793
+ * notificationTemplate(slug: $slug) {
1794
+ * id
1795
+ * slug
1796
+ * subject
1797
+ * }
1798
+ * }
1799
+ * `, { slug: 'user-welcome' });
1800
+ * ```
1801
+ */
1802
+ async query(query, variables) {
1803
+ return this.graphqlClient.tenantQuery(query, variables);
1804
+ }
1805
+ /**
1806
+ * Health check
1807
+ *
1808
+ * @returns True if tenant backend is reachable, false otherwise
1809
+ */
1810
+ async healthCheck() {
1811
+ try {
1812
+ await this.graphqlClient.tenantQuery(`
2141
1813
  query HealthCheck {
2142
1814
  __typename
2143
1815
  }
2144
- `;
2145
- await this.graphqlClient.tenantQuery(query);
2146
- return true;
2147
- } catch (error) {
2148
- logger.error("[TenantBackend] Health check failed", {
2149
- error: error instanceof Error ? error.message : "Unknown error"
2150
- });
2151
- return false;
2152
- }
2153
- }
2154
- /**
2155
- * Get GraphQL client for advanced usage
2156
- *
2157
- * @returns Underlying BurdenoffGraphQLClient
2158
- */
2159
- getClient() {
2160
- return this.graphqlClient;
2161
- }
2162
- /**
2163
- * Get client configuration
2164
- *
2165
- * @returns Client configuration
2166
- */
2167
- getConfig() {
2168
- return {
2169
- ...this.config
2170
- };
2171
- }
1816
+ `);
1817
+ return true;
1818
+ } catch (error) {
1819
+ logger.error("[TenantBackend] Health check failed", { error: error instanceof Error ? error.message : "Unknown error" });
1820
+ return false;
1821
+ }
1822
+ }
1823
+ /**
1824
+ * Get GraphQL client for advanced usage
1825
+ *
1826
+ * @returns Underlying BurdenoffGraphQLClient
1827
+ */
1828
+ getClient() {
1829
+ return this.graphqlClient;
1830
+ }
1831
+ /**
1832
+ * Get client configuration
1833
+ *
1834
+ * @returns Client configuration
1835
+ */
1836
+ getConfig() {
1837
+ return { ...this.config };
1838
+ }
2172
1839
  };
1840
+ /**
1841
+ * Create a TenantBackendClient instance
1842
+ *
1843
+ * @param config - Client configuration
1844
+ * @returns TenantBackendClient instance
1845
+ *
1846
+ * @example
1847
+ * ```typescript
1848
+ * import { createTenantBackendClient } from '@burdenoff/be-sdk';
1849
+ *
1850
+ * const client = createTenantBackendClient({
1851
+ * tenantBackendUrl: process.env.GLOBAL_INT_GATEWAY_URL!,
1852
+ * });
1853
+ * ```
1854
+ */
2173
1855
  function createTenantBackendClient(config) {
2174
- return new TenantBackendClient(config);
1856
+ return new TenantBackendClient(config);
2175
1857
  }
2176
- __name(createTenantBackendClient, "createTenantBackendClient");
2177
1858
 
2178
1859
  // src/index.ts
1860
+ /**
1861
+ * Burdenoff Backend SDK
1862
+ * Comprehensive SDK for all Burdenoff products
1863
+ *
1864
+ * @packageDocumentation
1865
+ */
1866
+ /**
1867
+ * Main Burdenoff SDK class
1868
+ *
1869
+ * @example
1870
+ * ```typescript
1871
+ * import { BurdenoffSDK } from '@burdenoff/be-sdk';
1872
+ *
1873
+ * const sdk = new BurdenoffSDK({
1874
+ * workspacesApiUrl: 'https://api.burdenoff.com/graphql',
1875
+ * timeout: 30000,
1876
+ * });
1877
+ *
1878
+ * // Use the unified tracker (most common use case)
1879
+ * const result = await sdk.tracker.track({
1880
+ * userId: 'user123',
1881
+ * action: 'create_project',
1882
+ * resourceType: 'project',
1883
+ * workspaceId: 'ws123',
1884
+ * usage: {
1885
+ * quotaName: 'myproduct.projects.count',
1886
+ * productId: 'myproduct',
1887
+ * amount: 1,
1888
+ * },
1889
+ * });
1890
+ * ```
1891
+ */
2179
1892
  var BurdenoffSDK = class {
2180
- static {
2181
- __name(this, "BurdenoffSDK");
2182
- }
2183
- client;
2184
- defaultContext;
2185
- // Event queue publisher state (Redis Streams)
2186
- eventPublisher = null;
2187
- eventPublisherInitPromise = null;
2188
- eventQueueConfig = null;
2189
- // Initialization state
2190
- initializationPromise = null;
2191
- isShuttingDown = false;
2192
- /** Authentication module */
2193
- auth;
2194
- /** Notifications module (workspaces-backend) */
2195
- notifications;
2196
- /** Tenant Notifications module (tenant-backend - RECOMMENDED) */
2197
- tenantNotifications;
2198
- /** RBAC module */
2199
- rbac;
2200
- /** Activity tracking module */
2201
- activity;
2202
- /** Usage & Quota module */
2203
- usage;
2204
- /** Unified Tracker module (MOST IMPORTANT - use this for most operations) */
2205
- tracker;
2206
- /** Database helpers module */
2207
- database;
2208
- /** Events/Queue module */
2209
- events;
2210
- /** Graph integration module */
2211
- graph;
2212
- /** Search module */
2213
- search;
2214
- /** Translation module */
2215
- translation;
2216
- /** Payments module */
2217
- payments;
2218
- /** Temporal workflow orchestration module (lazy-loaded) */
2219
- _temporal = null;
2220
- _temporalPromise = null;
2221
- _temporalConfig = null;
2222
- /**
2223
- * Get Temporal workflow orchestration module (lazy-loaded)
2224
- * Only loads @temporalio/client when this method is called
2225
- *
2226
- * @returns Promise resolving to TemporalModule
2227
- * @example
2228
- * ```typescript
2229
- * const temporal = await sdk.getTemporalModule();
2230
- * await temporal.startWorkflow('myWorkflow', { ... });
2231
- * ```
2232
- */
2233
- async getTemporalModule() {
2234
- if (this._temporal) {
2235
- return this._temporal;
2236
- }
2237
- if (!this._temporalPromise) {
2238
- this._temporalPromise = this.loadTemporalModule();
2239
- }
2240
- return this._temporalPromise;
2241
- }
2242
- /**
2243
- * Load temporal module dynamically
2244
- * @private
2245
- */
2246
- async loadTemporalModule() {
2247
- const { TemporalModule: TM } = await import('./temporal/index.js');
2248
- this._temporal = this._temporalConfig?.moduleType ? new TM({
2249
- moduleType: this._temporalConfig.moduleType,
2250
- address: this._temporalConfig.address,
2251
- namespace: this._temporalConfig.namespace,
2252
- taskQueue: this._temporalConfig.taskQueue
2253
- }) : TM.fromEnv();
2254
- return this._temporal;
2255
- }
2256
- /** Logger instance */
2257
- logger;
2258
- /** Context manager */
2259
- context;
2260
- /**
2261
- * Create SDK instance
2262
- */
2263
- constructor(config, defaultContext = {}) {
2264
- this.client = new BurdenoffGraphQLClient(config, defaultContext);
2265
- this.defaultContext = defaultContext;
2266
- this.logger = logger;
2267
- if (config.logger) {
2268
- this.logger.setLevel(config.logger.level);
2269
- this.logger.setConsoleEnabled(config.logger.console);
2270
- if (config.logger.transport) {
2271
- this.logger.addTransport(config.logger.transport);
2272
- }
2273
- }
2274
- this.context = ContextManager;
2275
- if (Object.keys(defaultContext).length > 0) {
2276
- ContextManager.setContext(defaultContext);
2277
- }
2278
- this.auth = new AuthModule(this.client, defaultContext);
2279
- this.notifications = new NotificationsModule(this.client, defaultContext);
2280
- this.tenantNotifications = new TenantNotificationsModule(this.client, defaultContext);
2281
- this.rbac = new RBACModule(this.client, defaultContext);
2282
- this.activity = new ActivityModule(this.client, defaultContext);
2283
- this.usage = new UsageModule(this.client, defaultContext);
2284
- this.tracker = new TrackerModule(this.client, defaultContext);
2285
- this.database = DatabaseModule;
2286
- this.events = new EventsModule(this.client, defaultContext);
2287
- this.graph = new GraphModule(this.client, defaultContext);
2288
- this.search = new SearchModule(this.client, defaultContext);
2289
- this.translation = new TranslationModule(this.client, defaultContext);
2290
- this.payments = new PaymentsModule(this.client, defaultContext);
2291
- if (config.temporalModuleType) {
2292
- this._temporalConfig = {
2293
- moduleType: config.temporalModuleType,
2294
- address: config.temporalAddress,
2295
- namespace: config.temporalNamespace,
2296
- taskQueue: config.temporalTaskQueue
2297
- };
2298
- }
2299
- if (config.eventQueue || resolveEventStreamsUrl()) {
2300
- this.eventQueueConfig = {
2301
- autoConnect: true,
2302
- maxReconnectAttempts: -1,
2303
- reconnectTimeWait: 2e3,
2304
- ...config.eventQueue
2305
- };
2306
- }
2307
- logger.info("[SDK] Burdenoff SDK initialized", {
2308
- workspacesApiUrl: config.workspacesApiUrl,
2309
- tenantApiUrl: config.tenantApiUrl,
2310
- hasDefaultContext: Object.keys(defaultContext).length > 0,
2311
- hasEventQueueConfig: !!this.eventQueueConfig,
2312
- hasTemporalConfig: !!config.temporalModuleType
2313
- });
2314
- this.scheduleBackgroundInit();
2315
- }
2316
- /**
2317
- * Schedule background initialization outside constructor
2318
- * Uses queueMicrotask to defer async work while maintaining initialization order
2319
- * @private
2320
- */
2321
- scheduleBackgroundInit() {
2322
- queueMicrotask(() => {
2323
- this.initializationPromise = this.initializeAsync();
2324
- });
2325
- }
2326
- /**
2327
- * Update SDK context
2328
- */
2329
- setContext(context) {
2330
- this.defaultContext = {
2331
- ...this.defaultContext,
2332
- ...context
2333
- };
2334
- this.client.updateContext(context);
2335
- ContextManager.setContext(this.defaultContext);
2336
- }
2337
- /**
2338
- * Get current context
2339
- */
2340
- getContext() {
2341
- return ContextManager.getContext();
2342
- }
2343
- /**
2344
- * Run function with specific context
2345
- */
2346
- async withContext(context, fn) {
2347
- return ContextManager.withContext(context, fn);
2348
- }
2349
- /**
2350
- * Background initialization for event queue and other async resources
2351
- * @private
2352
- */
2353
- async initializeAsync() {
2354
- const promises = [];
2355
- if (this.eventQueueConfig?.autoConnect) {
2356
- promises.push(this.initializeEventQueue().catch((error) => {
2357
- logger.warn("[SDK] Failed to auto-connect to Redis Streams", {
2358
- error
2359
- });
2360
- }));
2361
- }
2362
- await Promise.allSettled(promises);
2363
- }
2364
- /**
2365
- * Initialize the Redis Streams event publisher
2366
- * @private
2367
- */
2368
- async initializeEventQueue() {
2369
- if (!this.eventQueueConfig || this.eventPublisher) return;
2370
- const url = this.eventQueueConfig.url || resolveEventStreamsUrl();
2371
- if (!url) {
2372
- logger.warn("[SDK] No REDIS_STREAMS_URL / REDIS_URL available \u2014 event publisher disabled");
2373
- return;
2374
- }
2375
- const publisherConfig = {
2376
- type: QueueType.REDIS_STREAMS,
2377
- url,
2378
- password: this.eventQueueConfig.password,
2379
- name: this.eventQueueConfig.name || "burdenoff-sdk-publisher",
2380
- maxReconnectAttempts: this.eventQueueConfig.maxReconnectAttempts ?? -1,
2381
- reconnectTimeWait: this.eventQueueConfig.reconnectTimeWait ?? 2e3
2382
- };
2383
- this.eventPublisher = EventQueueFactory.createPublisher(publisherConfig);
2384
- await this.eventPublisher.connect();
2385
- logger.info("[SDK] Redis Streams event publisher initialized", {
2386
- url,
2387
- name: this.eventQueueConfig.name
2388
- });
2389
- }
2390
- /**
2391
- * Get the event publisher instance (lazy initialization).
2392
- *
2393
- * @example
2394
- * ```typescript
2395
- * const publisher = await sdk.getEventPublisher();
2396
- * await publisher.publish({
2397
- * subject: 'events.user.created',
2398
- * data: { userId: 'user-123' }
2399
- * });
2400
- * ```
2401
- */
2402
- async getEventPublisher() {
2403
- if (this.eventPublisher) return this.eventPublisher;
2404
- if (!this.eventQueueConfig) {
2405
- throw new Error("[SDK] Event queue not configured - set REDIS_STREAMS_URL / REDIS_URL or provide config.eventQueue");
2406
- }
2407
- if (!this.eventPublisherInitPromise) {
2408
- this.eventPublisherInitPromise = this.initializeEventQueue();
2409
- }
2410
- await this.eventPublisherInitPromise;
2411
- if (!this.eventPublisher) {
2412
- throw new Error("[SDK] Event publisher initialization failed");
2413
- }
2414
- return this.eventPublisher;
2415
- }
2416
- /**
2417
- * Wait for SDK initialization to complete
2418
- *
2419
- * @example
2420
- * ```typescript
2421
- * await sdk.waitForReady();
2422
- * ```
2423
- */
2424
- async waitForReady() {
2425
- if (this.initializationPromise) {
2426
- await this.initializationPromise;
2427
- }
2428
- }
2429
- /**
2430
- * Check event queue (Redis Streams) health status
2431
- *
2432
- * @example
2433
- * ```typescript
2434
- * const health = await sdk.isEventQueueHealthy();
2435
- * if (health.status === 'healthy') {
2436
- * console.log('Event queue is connected');
2437
- * }
2438
- * ```
2439
- */
2440
- async isEventQueueHealthy() {
2441
- if (!this.eventQueueConfig) {
2442
- return {
2443
- status: "not_configured",
2444
- connected: false
2445
- };
2446
- }
2447
- if (!this.eventPublisher) {
2448
- return {
2449
- status: "unhealthy",
2450
- connected: false,
2451
- url: this.eventQueueConfig.url,
2452
- details: {
2453
- reason: "Not initialized"
2454
- }
2455
- };
2456
- }
2457
- try {
2458
- const healthCheck = await this.eventPublisher.healthCheck();
2459
- return {
2460
- status: healthCheck.status,
2461
- connected: this.eventPublisher.isConnected(),
2462
- url: this.eventQueueConfig.url,
2463
- details: healthCheck.details
2464
- };
2465
- } catch (error) {
2466
- return {
2467
- status: "unhealthy",
2468
- connected: false,
2469
- url: this.eventQueueConfig.url,
2470
- details: {
2471
- error: error instanceof Error ? error.message : String(error)
2472
- }
2473
- };
2474
- }
2475
- }
2476
- /**
2477
- * Check Temporal health status
2478
- *
2479
- * @example
2480
- * ```typescript
2481
- * const health = await sdk.isTemporalHealthy();
2482
- * if (health.status === 'healthy') {
2483
- * console.log('Temporal is connected');
2484
- * }
2485
- * ```
2486
- */
2487
- async isTemporalHealthy() {
2488
- if (!this._temporal) {
2489
- return {
2490
- status: "not_configured",
2491
- connected: false
2492
- };
2493
- }
2494
- const config = this._temporal.getConfig();
2495
- if (!config.address) {
2496
- return {
2497
- status: "not_configured",
2498
- connected: false
2499
- };
2500
- }
2501
- try {
2502
- const client = this._temporal.getClient();
2503
- const connected = client.isClientConnected();
2504
- return {
2505
- status: connected ? "healthy" : "unhealthy",
2506
- connected,
2507
- address: config.address,
2508
- namespace: config.namespace,
2509
- details: {
2510
- taskQueue: config.taskQueue
2511
- }
2512
- };
2513
- } catch (error) {
2514
- return {
2515
- status: "unhealthy",
2516
- connected: false,
2517
- address: config.address,
2518
- namespace: config.namespace,
2519
- details: {
2520
- error: error instanceof Error ? error.message : String(error)
2521
- }
2522
- };
2523
- }
2524
- }
2525
- /**
2526
- * Get overall SDK health status
2527
- *
2528
- * @example
2529
- * ```typescript
2530
- * const health = await sdk.getHealthStatus();
2531
- * console.log('Event Queue:', health.eventQueue.status);
2532
- * console.log('Temporal:', health.temporal.status);
2533
- * ```
2534
- */
2535
- async getHealthStatus() {
2536
- const [eventQueue, temporal] = await Promise.all([
2537
- this.isEventQueueHealthy(),
2538
- this.isTemporalHealthy()
2539
- ]);
2540
- return {
2541
- eventQueue,
2542
- temporal
2543
- };
2544
- }
2545
- /**
2546
- * Graceful shutdown - disconnect all resources
2547
- *
2548
- * @example
2549
- * ```typescript
2550
- * // On application shutdown
2551
- * await sdk.shutdown({ timeout: 5000, force: true });
2552
- * ```
2553
- */
2554
- async shutdown(options = {}) {
2555
- if (this.isShuttingDown) {
2556
- logger.warn("[SDK] Shutdown already in progress");
2557
- return;
2558
- }
2559
- this.isShuttingDown = true;
2560
- const timeout = options.timeout ?? 5e3;
2561
- const force = options.force ?? true;
2562
- logger.info("[SDK] Starting graceful shutdown", {
2563
- timeout,
2564
- force
2565
- });
2566
- const shutdownPromises = [];
2567
- if (this.eventPublisher) {
2568
- shutdownPromises.push(this.eventPublisher.disconnect().catch((error) => {
2569
- logger.error("[SDK] Error disconnecting event publisher", {
2570
- error
2571
- });
2572
- }));
2573
- }
2574
- if (this._temporal) {
2575
- shutdownPromises.push(this._temporal.disconnect().catch((error) => {
2576
- logger.error("[SDK] Error disconnecting Temporal", {
2577
- error
2578
- });
2579
- }));
2580
- }
2581
- shutdownPromises.push(disposeAll(timeout));
2582
- try {
2583
- await Promise.race([
2584
- Promise.allSettled(shutdownPromises),
2585
- new Promise((_, reject) => setTimeout(() => reject(new Error("[SDK] Shutdown timeout exceeded")), timeout))
2586
- ]);
2587
- logger.info("[SDK] Shutdown completed successfully");
2588
- } catch (error) {
2589
- if (!force) {
2590
- throw error;
2591
- }
2592
- logger.warn("[SDK] Shutdown timeout exceeded, forcing shutdown", {
2593
- error
2594
- });
2595
- }
2596
- }
2597
- /**
2598
- * Create bootstrap instance
2599
- */
2600
- static createBootstrap(config) {
2601
- return createBootstrap(config);
2602
- }
1893
+ client;
1894
+ defaultContext;
1895
+ eventPublisher = null;
1896
+ eventPublisherInitPromise = null;
1897
+ eventQueueConfig = null;
1898
+ initializationPromise = null;
1899
+ isShuttingDown = false;
1900
+ /** Authentication module */
1901
+ auth;
1902
+ /** Notifications module (workspaces-backend) */
1903
+ notifications;
1904
+ /** Tenant Notifications module (tenant-backend - RECOMMENDED) */
1905
+ tenantNotifications;
1906
+ /** RBAC module */
1907
+ rbac;
1908
+ /** Activity tracking module */
1909
+ activity;
1910
+ /** Usage & Quota module */
1911
+ usage;
1912
+ /** Unified Tracker module (MOST IMPORTANT - use this for most operations) */
1913
+ tracker;
1914
+ /** Database helpers module */
1915
+ database;
1916
+ /** Events/Queue module */
1917
+ events;
1918
+ /** Graph integration module */
1919
+ graph;
1920
+ /** Search module */
1921
+ search;
1922
+ /** Translation module */
1923
+ translation;
1924
+ /** Payments module */
1925
+ payments;
1926
+ /** Temporal workflow orchestration module (lazy-loaded) */
1927
+ _temporal = null;
1928
+ _temporalPromise = null;
1929
+ _temporalConfig = null;
1930
+ /**
1931
+ * Get Temporal workflow orchestration module (lazy-loaded)
1932
+ * Only loads @temporalio/client when this method is called
1933
+ *
1934
+ * @returns Promise resolving to TemporalModule
1935
+ * @example
1936
+ * ```typescript
1937
+ * const temporal = await sdk.getTemporalModule();
1938
+ * await temporal.startWorkflow('myWorkflow', { ... });
1939
+ * ```
1940
+ */
1941
+ async getTemporalModule() {
1942
+ if (this._temporal) return this._temporal;
1943
+ if (!this._temporalPromise) this._temporalPromise = this.loadTemporalModule();
1944
+ return this._temporalPromise;
1945
+ }
1946
+ /**
1947
+ * Load temporal module dynamically
1948
+ * @private
1949
+ */
1950
+ async loadTemporalModule() {
1951
+ const { TemporalModule: TM } = await import("./temporal/index.js");
1952
+ this._temporal = this._temporalConfig?.moduleType ? new TM({
1953
+ moduleType: this._temporalConfig.moduleType,
1954
+ address: this._temporalConfig.address,
1955
+ namespace: this._temporalConfig.namespace,
1956
+ taskQueue: this._temporalConfig.taskQueue
1957
+ }) : TM.fromEnv();
1958
+ return this._temporal;
1959
+ }
1960
+ /** Logger instance */
1961
+ logger;
1962
+ /** Context manager */
1963
+ context;
1964
+ /**
1965
+ * Create SDK instance
1966
+ */
1967
+ constructor(config, defaultContext = {}) {
1968
+ this.client = new BurdenoffGraphQLClient(config, defaultContext);
1969
+ this.defaultContext = defaultContext;
1970
+ this.logger = logger;
1971
+ if (config.logger) {
1972
+ this.logger.setLevel(config.logger.level);
1973
+ this.logger.setConsoleEnabled(config.logger.console);
1974
+ if (config.logger.transport) this.logger.addTransport(config.logger.transport);
1975
+ }
1976
+ this.context = ContextManager;
1977
+ if (Object.keys(defaultContext).length > 0) ContextManager.setContext(defaultContext);
1978
+ this.auth = new AuthModule(this.client, defaultContext);
1979
+ this.notifications = new NotificationsModule(this.client, defaultContext);
1980
+ this.tenantNotifications = new TenantNotificationsModule(this.client, defaultContext);
1981
+ this.rbac = new RBACModule(this.client, defaultContext);
1982
+ this.activity = new ActivityModule(this.client, defaultContext);
1983
+ this.usage = new UsageModule(this.client, defaultContext);
1984
+ this.tracker = new TrackerModule(this.client, defaultContext);
1985
+ this.database = DatabaseModule;
1986
+ this.events = new EventsModule(this.client, defaultContext);
1987
+ this.graph = new GraphModule(this.client, defaultContext);
1988
+ this.search = new SearchModule(this.client, defaultContext);
1989
+ this.translation = new TranslationModule(this.client, defaultContext);
1990
+ this.payments = new PaymentsModule(this.client, defaultContext);
1991
+ if (config.temporalModuleType) this._temporalConfig = {
1992
+ moduleType: config.temporalModuleType,
1993
+ address: config.temporalAddress,
1994
+ namespace: config.temporalNamespace,
1995
+ taskQueue: config.temporalTaskQueue
1996
+ };
1997
+ if (config.eventQueue || resolveEventStreamsUrl()) this.eventQueueConfig = {
1998
+ autoConnect: true,
1999
+ maxReconnectAttempts: -1,
2000
+ reconnectTimeWait: 2e3,
2001
+ ...config.eventQueue
2002
+ };
2003
+ logger.info("[SDK] Burdenoff SDK initialized", {
2004
+ workspacesApiUrl: config.workspacesApiUrl,
2005
+ tenantApiUrl: config.tenantApiUrl,
2006
+ hasDefaultContext: Object.keys(defaultContext).length > 0,
2007
+ hasEventQueueConfig: !!this.eventQueueConfig,
2008
+ hasTemporalConfig: !!config.temporalModuleType
2009
+ });
2010
+ this.scheduleBackgroundInit();
2011
+ }
2012
+ /**
2013
+ * Schedule background initialization outside constructor
2014
+ * Uses queueMicrotask to defer async work while maintaining initialization order
2015
+ * @private
2016
+ */
2017
+ scheduleBackgroundInit() {
2018
+ queueMicrotask(() => {
2019
+ this.initializationPromise = this.initializeAsync();
2020
+ });
2021
+ }
2022
+ /**
2023
+ * Update SDK context
2024
+ */
2025
+ setContext(context) {
2026
+ this.defaultContext = {
2027
+ ...this.defaultContext,
2028
+ ...context
2029
+ };
2030
+ this.client.updateContext(context);
2031
+ ContextManager.setContext(this.defaultContext);
2032
+ }
2033
+ /**
2034
+ * Get current context
2035
+ */
2036
+ getContext() {
2037
+ return ContextManager.getContext();
2038
+ }
2039
+ /**
2040
+ * Run function with specific context
2041
+ */
2042
+ async withContext(context, fn) {
2043
+ return ContextManager.withContext(context, fn);
2044
+ }
2045
+ /**
2046
+ * Background initialization for event queue and other async resources
2047
+ * @private
2048
+ */
2049
+ async initializeAsync() {
2050
+ const promises = [];
2051
+ if (this.eventQueueConfig?.autoConnect) promises.push(this.initializeEventQueue().catch((error) => {
2052
+ logger.warn("[SDK] Failed to auto-connect to Redis Streams", { error });
2053
+ }));
2054
+ await Promise.allSettled(promises);
2055
+ }
2056
+ /**
2057
+ * Initialize the Redis Streams event publisher
2058
+ * @private
2059
+ */
2060
+ async initializeEventQueue() {
2061
+ if (!this.eventQueueConfig || this.eventPublisher) return;
2062
+ const url = this.eventQueueConfig.url || resolveEventStreamsUrl();
2063
+ if (!url) {
2064
+ logger.warn("[SDK] No REDIS_STREAMS_URL / REDIS_URL available — event publisher disabled");
2065
+ return;
2066
+ }
2067
+ const publisherConfig = {
2068
+ type: "redis-streams",
2069
+ url,
2070
+ password: this.eventQueueConfig.password,
2071
+ name: this.eventQueueConfig.name || "burdenoff-sdk-publisher",
2072
+ maxReconnectAttempts: this.eventQueueConfig.maxReconnectAttempts ?? -1,
2073
+ reconnectTimeWait: this.eventQueueConfig.reconnectTimeWait ?? 2e3
2074
+ };
2075
+ this.eventPublisher = EventQueueFactory.createPublisher(publisherConfig);
2076
+ await this.eventPublisher.connect();
2077
+ logger.info("[SDK] Redis Streams event publisher initialized", {
2078
+ url,
2079
+ name: this.eventQueueConfig.name
2080
+ });
2081
+ }
2082
+ /**
2083
+ * Get the event publisher instance (lazy initialization).
2084
+ *
2085
+ * @example
2086
+ * ```typescript
2087
+ * const publisher = await sdk.getEventPublisher();
2088
+ * await publisher.publish({
2089
+ * subject: 'events.user.created',
2090
+ * data: { userId: 'user-123' }
2091
+ * });
2092
+ * ```
2093
+ */
2094
+ async getEventPublisher() {
2095
+ if (this.eventPublisher) return this.eventPublisher;
2096
+ if (!this.eventQueueConfig) throw new Error("[SDK] Event queue not configured - set REDIS_STREAMS_URL / REDIS_URL or provide config.eventQueue");
2097
+ if (!this.eventPublisherInitPromise) this.eventPublisherInitPromise = this.initializeEventQueue();
2098
+ await this.eventPublisherInitPromise;
2099
+ if (!this.eventPublisher) throw new Error("[SDK] Event publisher initialization failed");
2100
+ return this.eventPublisher;
2101
+ }
2102
+ /**
2103
+ * Wait for SDK initialization to complete
2104
+ *
2105
+ * @example
2106
+ * ```typescript
2107
+ * await sdk.waitForReady();
2108
+ * ```
2109
+ */
2110
+ async waitForReady() {
2111
+ if (this.initializationPromise) await this.initializationPromise;
2112
+ }
2113
+ /**
2114
+ * Check event queue (Redis Streams) health status
2115
+ *
2116
+ * @example
2117
+ * ```typescript
2118
+ * const health = await sdk.isEventQueueHealthy();
2119
+ * if (health.status === 'healthy') {
2120
+ * console.log('Event queue is connected');
2121
+ * }
2122
+ * ```
2123
+ */
2124
+ async isEventQueueHealthy() {
2125
+ if (!this.eventQueueConfig) return {
2126
+ status: "not_configured",
2127
+ connected: false
2128
+ };
2129
+ if (!this.eventPublisher) return {
2130
+ status: "unhealthy",
2131
+ connected: false,
2132
+ url: this.eventQueueConfig.url,
2133
+ details: { reason: "Not initialized" }
2134
+ };
2135
+ try {
2136
+ const healthCheck = await this.eventPublisher.healthCheck();
2137
+ return {
2138
+ status: healthCheck.status,
2139
+ connected: this.eventPublisher.isConnected(),
2140
+ url: this.eventQueueConfig.url,
2141
+ details: healthCheck.details
2142
+ };
2143
+ } catch (error) {
2144
+ return {
2145
+ status: "unhealthy",
2146
+ connected: false,
2147
+ url: this.eventQueueConfig.url,
2148
+ details: { error: error instanceof Error ? error.message : String(error) }
2149
+ };
2150
+ }
2151
+ }
2152
+ /**
2153
+ * Check Temporal health status
2154
+ *
2155
+ * @example
2156
+ * ```typescript
2157
+ * const health = await sdk.isTemporalHealthy();
2158
+ * if (health.status === 'healthy') {
2159
+ * console.log('Temporal is connected');
2160
+ * }
2161
+ * ```
2162
+ */
2163
+ async isTemporalHealthy() {
2164
+ if (!this._temporal) return {
2165
+ status: "not_configured",
2166
+ connected: false
2167
+ };
2168
+ const config = this._temporal.getConfig();
2169
+ if (!config.address) return {
2170
+ status: "not_configured",
2171
+ connected: false
2172
+ };
2173
+ try {
2174
+ const connected = this._temporal.getClient().isClientConnected();
2175
+ return {
2176
+ status: connected ? "healthy" : "unhealthy",
2177
+ connected,
2178
+ address: config.address,
2179
+ namespace: config.namespace,
2180
+ details: { taskQueue: config.taskQueue }
2181
+ };
2182
+ } catch (error) {
2183
+ return {
2184
+ status: "unhealthy",
2185
+ connected: false,
2186
+ address: config.address,
2187
+ namespace: config.namespace,
2188
+ details: { error: error instanceof Error ? error.message : String(error) }
2189
+ };
2190
+ }
2191
+ }
2192
+ /**
2193
+ * Get overall SDK health status
2194
+ *
2195
+ * @example
2196
+ * ```typescript
2197
+ * const health = await sdk.getHealthStatus();
2198
+ * console.log('Event Queue:', health.eventQueue.status);
2199
+ * console.log('Temporal:', health.temporal.status);
2200
+ * ```
2201
+ */
2202
+ async getHealthStatus() {
2203
+ const [eventQueue, temporal] = await Promise.all([this.isEventQueueHealthy(), this.isTemporalHealthy()]);
2204
+ return {
2205
+ eventQueue,
2206
+ temporal
2207
+ };
2208
+ }
2209
+ /**
2210
+ * Graceful shutdown - disconnect all resources
2211
+ *
2212
+ * @example
2213
+ * ```typescript
2214
+ * // On application shutdown
2215
+ * await sdk.shutdown({ timeout: 5000, force: true });
2216
+ * ```
2217
+ */
2218
+ async shutdown(options = {}) {
2219
+ if (this.isShuttingDown) {
2220
+ logger.warn("[SDK] Shutdown already in progress");
2221
+ return;
2222
+ }
2223
+ this.isShuttingDown = true;
2224
+ const timeout = options.timeout ?? 5e3;
2225
+ const force = options.force ?? true;
2226
+ logger.info("[SDK] Starting graceful shutdown", {
2227
+ timeout,
2228
+ force
2229
+ });
2230
+ const shutdownPromises = [];
2231
+ if (this.eventPublisher) shutdownPromises.push(this.eventPublisher.disconnect().catch((error) => {
2232
+ logger.error("[SDK] Error disconnecting event publisher", { error });
2233
+ }));
2234
+ if (this._temporal) shutdownPromises.push(this._temporal.disconnect().catch((error) => {
2235
+ logger.error("[SDK] Error disconnecting Temporal", { error });
2236
+ }));
2237
+ shutdownPromises.push(disposeAll(timeout));
2238
+ try {
2239
+ await Promise.race([Promise.allSettled(shutdownPromises), new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("[SDK] Shutdown timeout exceeded")), timeout))]);
2240
+ logger.info("[SDK] Shutdown completed successfully");
2241
+ } catch (error) {
2242
+ if (!force) throw error;
2243
+ logger.warn("[SDK] Shutdown timeout exceeded, forcing shutdown", { error });
2244
+ }
2245
+ }
2246
+ /**
2247
+ * Create bootstrap instance
2248
+ */
2249
+ static createBootstrap(config) {
2250
+ return createBootstrap(config);
2251
+ }
2603
2252
  };
2604
- var index_default = BurdenoffSDK;
2253
+ /**
2254
+ * Create SDK instance (convenience function)
2255
+ */
2605
2256
  function createSDK(config, context) {
2606
- return new BurdenoffSDK(config, context);
2257
+ return new BurdenoffSDK(config, context);
2607
2258
  }
2608
- __name(createSDK, "createSDK");
2609
2259
 
2610
- export { BootstrapModule, BurdenoffGraphQLClient, BurdenoffSDK, PaymentsModule, SearchModule, TenantBackendClient, TranslationModule, createBootstrap, createSDK, createTenantBackendClient, index_default as default };
2611
- //# sourceMappingURL=index.js.map
2260
+ export { ActivityModule, ActivityOperationUnsupportedError, ai_credits_exports as AiCredits, AuthModule, BillingUsageClient, BootstrapModule, BurdenoffGraphQLClient, BurdenoffSDK, BurdenoffSDK as default, cache_exports as Cache, captcha_exports as Captcha, ContextManager, crypto_exports as Crypto, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS, dataloader_exports as DataLoader, DatabaseModule, event_queue_exports as EventQueue, EventsModule, export_exports as Export, feature_flags_exports as FeatureFlags, files_exports as Files, gateway_exports as Gateway, graph_exports as Graph, GraphModule, graphql_exports as GraphQL, i18n_exports as I18n, init_exports as Init, instrumentation_exports as Instrumentation, layer_exports as Layer, lifecycle_exports as Lifecycle, logger_exports as Logger, middleware_exports as Middleware, NAME_MAX_LENGTH, NAME_MIN_LENGTH, tenant_notifications_exports as Notifications, NotificationsModule, observability_exports as Observability, PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, PaymentsModule, platform_exports as Platform, prisma_exports as Prisma, product_alias_exports as ProductAlias, RBACModule, RENAME_CONCERNS, RESOURCE_CAP_DEFAULTS, RbacCoverageError, ResourceCapExceededError, ResourceCapsModule, SearchModule, sharing_exports as Sharing, tags_exports as Tags, TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager, TenantBackendClient, TrackerModule, TranslationModule, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, UsageModule, utils_exports as Utils, validation_exports as Validation, analyzeRbacCoverage, assertRbacCoverage, billingIdVariants, configureResourceCaps, createBootstrap, createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv, createSDK, createTenantBackendClient, createTranslator, disposeAll, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, getLanguage, getLocale, getRegisteredDisposableCount, getResourceCaps, hasI18n, isCaptchaEnabled, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, lengthInCodePoints, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, registerDisposable, t, templateKeyVariants, toCurrentName, toLegacyName, unregisterDisposable, validateName, validateUserFields, validateUsername, verifyCaptcha, verifyCaptchaIfEnabled };
2612
2261
  //# sourceMappingURL=index.js.map