@ductape/sdk 0.1.6 → 0.1.8

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 (973) hide show
  1. package/package.json +5 -9
  2. package/dist/agents/agent-context.d.ts +0 -100
  3. package/dist/agents/agent-context.js +0 -604
  4. package/dist/agents/agent-context.js.map +0 -1
  5. package/dist/agents/agent-executor.d.ts +0 -180
  6. package/dist/agents/agent-executor.js +0 -715
  7. package/dist/agents/agent-executor.js.map +0 -1
  8. package/dist/agents/agents.service.d.ts +0 -310
  9. package/dist/agents/agents.service.js +0 -1255
  10. package/dist/agents/agents.service.js.map +0 -1
  11. package/dist/agents/index.d.ts +0 -55
  12. package/dist/agents/index.js +0 -110
  13. package/dist/agents/index.js.map +0 -1
  14. package/dist/agents/memory-manager.d.ts +0 -182
  15. package/dist/agents/memory-manager.js +0 -383
  16. package/dist/agents/memory-manager.js.map +0 -1
  17. package/dist/agents/tool-registry.d.ts +0 -141
  18. package/dist/agents/tool-registry.js +0 -355
  19. package/dist/agents/tool-registry.js.map +0 -1
  20. package/dist/agents/types/agents.types.d.ts +0 -1240
  21. package/dist/agents/types/agents.types.js +0 -12
  22. package/dist/agents/types/agents.types.js.map +0 -1
  23. package/dist/agents/types/index.d.ts +0 -6
  24. package/dist/agents/types/index.js +0 -23
  25. package/dist/agents/types/index.js.map +0 -1
  26. package/dist/agents/vector-store-adapter.d.ts +0 -108
  27. package/dist/agents/vector-store-adapter.js +0 -213
  28. package/dist/agents/vector-store-adapter.js.map +0 -1
  29. package/dist/api/services/appApi.service.d.ts +0 -78
  30. package/dist/api/services/appApi.service.js +0 -303
  31. package/dist/api/services/appApi.service.js.map +0 -1
  32. package/dist/api/services/logsApi.service.d.ts +0 -62
  33. package/dist/api/services/logsApi.service.js +0 -67
  34. package/dist/api/services/logsApi.service.js.map +0 -1
  35. package/dist/api/services/pricingApi.service.d.ts +0 -10
  36. package/dist/api/services/pricingApi.service.js +0 -34
  37. package/dist/api/services/pricingApi.service.js.map +0 -1
  38. package/dist/api/services/processorApi.service.d.ts +0 -927
  39. package/dist/api/services/processorApi.service.js +0 -787
  40. package/dist/api/services/processorApi.service.js.map +0 -1
  41. package/dist/api/services/productsApi.service.d.ts +0 -150
  42. package/dist/api/services/productsApi.service.js +0 -279
  43. package/dist/api/services/productsApi.service.js.map +0 -1
  44. package/dist/api/services/resilienceApi.service.d.ts +0 -106
  45. package/dist/api/services/resilienceApi.service.js +0 -224
  46. package/dist/api/services/resilienceApi.service.js.map +0 -1
  47. package/dist/api/services/secretsApi.service.d.ts +0 -51
  48. package/dist/api/services/secretsApi.service.js +0 -126
  49. package/dist/api/services/secretsApi.service.js.map +0 -1
  50. package/dist/api/services/userApi.service.d.ts +0 -10
  51. package/dist/api/services/userApi.service.js +0 -20
  52. package/dist/api/services/userApi.service.js.map +0 -1
  53. package/dist/api/services/webhooksApi.service.d.ts +0 -14
  54. package/dist/api/services/webhooksApi.service.js +0 -65
  55. package/dist/api/services/webhooksApi.service.js.map +0 -1
  56. package/dist/api/services/workflowApi.service.d.ts +0 -199
  57. package/dist/api/services/workflowApi.service.js +0 -201
  58. package/dist/api/services/workflowApi.service.js.map +0 -1
  59. package/dist/api/services/workspaceApi.service.d.ts +0 -20
  60. package/dist/api/services/workspaceApi.service.js +0 -54
  61. package/dist/api/services/workspaceApi.service.js.map +0 -1
  62. package/dist/api/urls.d.ts +0 -136
  63. package/dist/api/urls.js +0 -185
  64. package/dist/api/urls.js.map +0 -1
  65. package/dist/api/utils/auth.utils.d.ts +0 -10
  66. package/dist/api/utils/auth.utils.js +0 -24
  67. package/dist/api/utils/auth.utils.js.map +0 -1
  68. package/dist/api/utils/cache.utils.d.ts +0 -3
  69. package/dist/api/utils/cache.utils.js +0 -18
  70. package/dist/api/utils/cache.utils.js.map +0 -1
  71. package/dist/api/utils/strings.utils.d.ts +0 -7
  72. package/dist/api/utils/strings.utils.js +0 -64
  73. package/dist/api/utils/strings.utils.js.map +0 -1
  74. package/dist/apps/services/app.service.d.ts +0 -126
  75. package/dist/apps/services/app.service.js +0 -1436
  76. package/dist/apps/services/app.service.js.map +0 -1
  77. package/dist/apps/utils/auth-context-manager.d.ts +0 -137
  78. package/dist/apps/utils/auth-context-manager.js +0 -248
  79. package/dist/apps/utils/auth-context-manager.js.map +0 -1
  80. package/dist/apps/utils/credential-manager.d.ts +0 -128
  81. package/dist/apps/utils/credential-manager.js +0 -199
  82. package/dist/apps/utils/credential-manager.js.map +0 -1
  83. package/dist/apps/utils/index.d.ts +0 -10
  84. package/dist/apps/utils/index.js +0 -54
  85. package/dist/apps/utils/index.js.map +0 -1
  86. package/dist/apps/utils/input-helpers.d.ts +0 -67
  87. package/dist/apps/utils/input-helpers.js +0 -185
  88. package/dist/apps/utils/input-helpers.js.map +0 -1
  89. package/dist/apps/utils/input-resolver.d.ts +0 -165
  90. package/dist/apps/utils/input-resolver.js +0 -477
  91. package/dist/apps/utils/input-resolver.js.map +0 -1
  92. package/dist/apps/utils/oauth-manager.d.ts +0 -196
  93. package/dist/apps/utils/oauth-manager.js +0 -429
  94. package/dist/apps/utils/oauth-manager.js.map +0 -1
  95. package/dist/apps/utils/objects.utils.d.ts +0 -4
  96. package/dist/apps/utils/objects.utils.js +0 -59
  97. package/dist/apps/utils/objects.utils.js.map +0 -1
  98. package/dist/apps/utils/string.utils.d.ts +0 -9
  99. package/dist/apps/utils/string.utils.js +0 -89
  100. package/dist/apps/utils/string.utils.js.map +0 -1
  101. package/dist/apps/validators/index.d.ts +0 -17
  102. package/dist/apps/validators/index.js +0 -39
  103. package/dist/apps/validators/index.js.map +0 -1
  104. package/dist/apps/validators/joi-validators/create.app.validator.d.ts +0 -3
  105. package/dist/apps/validators/joi-validators/create.app.validator.js +0 -43
  106. package/dist/apps/validators/joi-validators/create.app.validator.js.map +0 -1
  107. package/dist/apps/validators/joi-validators/create.appAction.validator.d.ts +0 -3
  108. package/dist/apps/validators/joi-validators/create.appAction.validator.js +0 -72
  109. package/dist/apps/validators/joi-validators/create.appAction.validator.js.map +0 -1
  110. package/dist/apps/validators/joi-validators/create.appActionResponse.validator.d.ts +0 -7
  111. package/dist/apps/validators/joi-validators/create.appActionResponse.validator.js +0 -81
  112. package/dist/apps/validators/joi-validators/create.appActionResponse.validator.js.map +0 -1
  113. package/dist/apps/validators/joi-validators/create.appAuth.validator.d.ts +0 -3
  114. package/dist/apps/validators/joi-validators/create.appAuth.validator.js +0 -64
  115. package/dist/apps/validators/joi-validators/create.appAuth.validator.js.map +0 -1
  116. package/dist/apps/validators/joi-validators/create.appBody.validators.d.ts +0 -4
  117. package/dist/apps/validators/joi-validators/create.appBody.validators.js +0 -44
  118. package/dist/apps/validators/joi-validators/create.appBody.validators.js.map +0 -1
  119. package/dist/apps/validators/joi-validators/create.appConstants.validator.d.ts +0 -4
  120. package/dist/apps/validators/joi-validators/create.appConstants.validator.js +0 -45
  121. package/dist/apps/validators/joi-validators/create.appConstants.validator.js.map +0 -1
  122. package/dist/apps/validators/joi-validators/create.appEnv.validator.d.ts +0 -4
  123. package/dist/apps/validators/joi-validators/create.appEnv.validator.js +0 -50
  124. package/dist/apps/validators/joi-validators/create.appEnv.validator.js.map +0 -1
  125. package/dist/apps/validators/joi-validators/create.appVariable.validator.d.ts +0 -4
  126. package/dist/apps/validators/joi-validators/create.appVariable.validator.js +0 -47
  127. package/dist/apps/validators/joi-validators/create.appVariable.validator.js.map +0 -1
  128. package/dist/apps/validators/joi-validators/create.appWebhook.validator.d.ts +0 -4
  129. package/dist/apps/validators/joi-validators/create.appWebhook.validator.js +0 -60
  130. package/dist/apps/validators/joi-validators/create.appWebhook.validator.js.map +0 -1
  131. package/dist/apps/validators/joi-validators/create.appWebhookEvent.validator.d.ts +0 -3
  132. package/dist/apps/validators/joi-validators/create.appWebhookEvent.validator.js +0 -48
  133. package/dist/apps/validators/joi-validators/create.appWebhookEvent.validator.js.map +0 -1
  134. package/dist/apps/validators/joi-validators/sample.validator.d.ts +0 -6
  135. package/dist/apps/validators/joi-validators/sample.validator.js +0 -65
  136. package/dist/apps/validators/joi-validators/sample.validator.js.map +0 -1
  137. package/dist/apps/validators/joi-validators/update.app.validator.d.ts +0 -4
  138. package/dist/apps/validators/joi-validators/update.app.validator.js +0 -66
  139. package/dist/apps/validators/joi-validators/update.app.validator.js.map +0 -1
  140. package/dist/apps/validators/joi-validators/update.appAction.validator.d.ts +0 -4
  141. package/dist/apps/validators/joi-validators/update.appAction.validator.js +0 -76
  142. package/dist/apps/validators/joi-validators/update.appAction.validator.js.map +0 -1
  143. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.d.ts +0 -3
  144. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.js +0 -57
  145. package/dist/apps/validators/joi-validators/update.appActionResponse.validator.js.map +0 -1
  146. package/dist/apps/validators/joi-validators/update.appAuth.validator.d.ts +0 -4
  147. package/dist/apps/validators/joi-validators/update.appAuth.validator.js +0 -52
  148. package/dist/apps/validators/joi-validators/update.appAuth.validator.js.map +0 -1
  149. package/dist/apps/validators/joi-validators/update.appConstants.validator.d.ts +0 -4
  150. package/dist/apps/validators/joi-validators/update.appConstants.validator.js +0 -45
  151. package/dist/apps/validators/joi-validators/update.appConstants.validator.js.map +0 -1
  152. package/dist/apps/validators/joi-validators/update.appEnv.validator.d.ts +0 -4
  153. package/dist/apps/validators/joi-validators/update.appEnv.validator.js +0 -50
  154. package/dist/apps/validators/joi-validators/update.appEnv.validator.js.map +0 -1
  155. package/dist/apps/validators/joi-validators/update.appVariables.validator.d.ts +0 -4
  156. package/dist/apps/validators/joi-validators/update.appVariables.validator.js +0 -47
  157. package/dist/apps/validators/joi-validators/update.appVariables.validator.js.map +0 -1
  158. package/dist/apps/validators/joi-validators/update.appWebhook.validator.d.ts +0 -4
  159. package/dist/apps/validators/joi-validators/update.appWebhook.validator.js +0 -59
  160. package/dist/apps/validators/joi-validators/update.appWebhook.validator.js.map +0 -1
  161. package/dist/apps/validators/joi-validators/update.appWebhookEvent.validator.d.ts +0 -3
  162. package/dist/apps/validators/joi-validators/update.appWebhookEvent.validator.js +0 -48
  163. package/dist/apps/validators/joi-validators/update.appWebhookEvent.validator.js.map +0 -1
  164. package/dist/apps/validators/joi-validators/update.validation.entityData.validator.d.ts +0 -3
  165. package/dist/apps/validators/joi-validators/update.validation.entityData.validator.js +0 -60
  166. package/dist/apps/validators/joi-validators/update.validation.entityData.validator.js.map +0 -1
  167. package/dist/bin.d.ts +0 -26
  168. package/dist/bin.js +0 -28
  169. package/dist/bin.js.map +0 -1
  170. package/dist/brokers/brokers.service.d.ts +0 -438
  171. package/dist/brokers/brokers.service.js +0 -1294
  172. package/dist/brokers/brokers.service.js.map +0 -1
  173. package/dist/brokers/index.d.ts +0 -46
  174. package/dist/brokers/index.js +0 -83
  175. package/dist/brokers/index.js.map +0 -1
  176. package/dist/brokers/types/index.d.ts +0 -569
  177. package/dist/brokers/types/index.js +0 -8
  178. package/dist/brokers/types/index.js.map +0 -1
  179. package/dist/brokers/utils/broker.util.d.ts +0 -33
  180. package/dist/brokers/utils/broker.util.js +0 -125
  181. package/dist/brokers/utils/broker.util.js.map +0 -1
  182. package/dist/brokers/utils/providers/aws-sqs.service.d.ts +0 -16
  183. package/dist/brokers/utils/providers/aws-sqs.service.js +0 -71
  184. package/dist/brokers/utils/providers/aws-sqs.service.js.map +0 -1
  185. package/dist/brokers/utils/providers/google-pubsub.service.d.ts +0 -16
  186. package/dist/brokers/utils/providers/google-pubsub.service.js +0 -43
  187. package/dist/brokers/utils/providers/google-pubsub.service.js.map +0 -1
  188. package/dist/brokers/utils/providers/index.d.ts +0 -6
  189. package/dist/brokers/utils/providers/index.js +0 -16
  190. package/dist/brokers/utils/providers/index.js.map +0 -1
  191. package/dist/brokers/utils/providers/kafka.service.d.ts +0 -23
  192. package/dist/brokers/utils/providers/kafka.service.js +0 -131
  193. package/dist/brokers/utils/providers/kafka.service.js.map +0 -1
  194. package/dist/brokers/utils/providers/nats.service.d.ts +0 -18
  195. package/dist/brokers/utils/providers/nats.service.js +0 -63
  196. package/dist/brokers/utils/providers/nats.service.js.map +0 -1
  197. package/dist/brokers/utils/providers/rabbitmq.service.d.ts +0 -25
  198. package/dist/brokers/utils/providers/rabbitmq.service.js +0 -138
  199. package/dist/brokers/utils/providers/rabbitmq.service.js.map +0 -1
  200. package/dist/brokers/utils/providers/redis.service.d.ts +0 -18
  201. package/dist/brokers/utils/providers/redis.service.js +0 -93
  202. package/dist/brokers/utils/providers/redis.service.js.map +0 -1
  203. package/dist/cache/cache.manager.d.ts +0 -308
  204. package/dist/cache/cache.manager.js +0 -900
  205. package/dist/cache/cache.manager.js.map +0 -1
  206. package/dist/cache/cache.service.d.ts +0 -192
  207. package/dist/cache/cache.service.js +0 -596
  208. package/dist/cache/cache.service.js.map +0 -1
  209. package/dist/cache/index.d.ts +0 -52
  210. package/dist/cache/index.js +0 -81
  211. package/dist/cache/index.js.map +0 -1
  212. package/dist/cache/types/index.d.ts +0 -112
  213. package/dist/cache/types/index.js +0 -6
  214. package/dist/cache/types/index.js.map +0 -1
  215. package/dist/clients/apps.client.d.ts +0 -4
  216. package/dist/clients/apps.client.js +0 -31
  217. package/dist/clients/apps.client.js.map +0 -1
  218. package/dist/clients/email.client.d.ts +0 -4
  219. package/dist/clients/email.client.js +0 -29
  220. package/dist/clients/email.client.js.map +0 -1
  221. package/dist/clients/expo.client.d.ts +0 -3
  222. package/dist/clients/expo.client.js +0 -28
  223. package/dist/clients/expo.client.js.map +0 -1
  224. package/dist/clients/function.client.d.ts +0 -3
  225. package/dist/clients/function.client.js +0 -27
  226. package/dist/clients/function.client.js.map +0 -1
  227. package/dist/clients/http.client.d.ts +0 -3
  228. package/dist/clients/http.client.js +0 -27
  229. package/dist/clients/http.client.js.map +0 -1
  230. package/dist/clients/logs.client.d.ts +0 -4
  231. package/dist/clients/logs.client.js +0 -34
  232. package/dist/clients/logs.client.js.map +0 -1
  233. package/dist/clients/pricing.client.d.ts +0 -4
  234. package/dist/clients/pricing.client.js +0 -34
  235. package/dist/clients/pricing.client.js.map +0 -1
  236. package/dist/clients/products.client.d.ts +0 -3
  237. package/dist/clients/products.client.js +0 -32
  238. package/dist/clients/products.client.js.map +0 -1
  239. package/dist/clients/users.client.d.ts +0 -4
  240. package/dist/clients/users.client.js +0 -34
  241. package/dist/clients/users.client.js.map +0 -1
  242. package/dist/clients/webhooks.client.d.ts +0 -4
  243. package/dist/clients/webhooks.client.js +0 -34
  244. package/dist/clients/webhooks.client.js.map +0 -1
  245. package/dist/clients/workspace.client.d.ts +0 -7
  246. package/dist/clients/workspace.client.js +0 -39
  247. package/dist/clients/workspace.client.js.map +0 -1
  248. package/dist/database/actions/action-manager.d.ts +0 -170
  249. package/dist/database/actions/action-manager.js +0 -465
  250. package/dist/database/actions/action-manager.js.map +0 -1
  251. package/dist/database/actions/index.d.ts +0 -6
  252. package/dist/database/actions/index.js +0 -13
  253. package/dist/database/actions/index.js.map +0 -1
  254. package/dist/database/adapters/adapter.factory.d.ts +0 -62
  255. package/dist/database/adapters/adapter.factory.js +0 -97
  256. package/dist/database/adapters/adapter.factory.js.map +0 -1
  257. package/dist/database/adapters/base.adapter.d.ts +0 -423
  258. package/dist/database/adapters/base.adapter.js +0 -260
  259. package/dist/database/adapters/base.adapter.js.map +0 -1
  260. package/dist/database/adapters/cassandra.adapter.d.ts +0 -92
  261. package/dist/database/adapters/cassandra.adapter.js +0 -1091
  262. package/dist/database/adapters/cassandra.adapter.js.map +0 -1
  263. package/dist/database/adapters/dynamodb.adapter.d.ts +0 -110
  264. package/dist/database/adapters/dynamodb.adapter.js +0 -1564
  265. package/dist/database/adapters/dynamodb.adapter.js.map +0 -1
  266. package/dist/database/adapters/index.d.ts +0 -11
  267. package/dist/database/adapters/index.js +0 -27
  268. package/dist/database/adapters/index.js.map +0 -1
  269. package/dist/database/adapters/mariadb.adapter.d.ts +0 -100
  270. package/dist/database/adapters/mariadb.adapter.js +0 -247
  271. package/dist/database/adapters/mariadb.adapter.js.map +0 -1
  272. package/dist/database/adapters/mongodb.adapter.d.ts +0 -121
  273. package/dist/database/adapters/mongodb.adapter.js +0 -1284
  274. package/dist/database/adapters/mongodb.adapter.js.map +0 -1
  275. package/dist/database/adapters/mysql.adapter.d.ts +0 -86
  276. package/dist/database/adapters/mysql.adapter.js +0 -1371
  277. package/dist/database/adapters/mysql.adapter.js.map +0 -1
  278. package/dist/database/adapters/postgresql.adapter.d.ts +0 -90
  279. package/dist/database/adapters/postgresql.adapter.js +0 -1487
  280. package/dist/database/adapters/postgresql.adapter.js.map +0 -1
  281. package/dist/database/databases.service.d.ts +0 -1496
  282. package/dist/database/databases.service.js +0 -3294
  283. package/dist/database/databases.service.js.map +0 -1
  284. package/dist/database/index.d.ts +0 -46
  285. package/dist/database/index.js +0 -109
  286. package/dist/database/index.js.map +0 -1
  287. package/dist/database/migrations/index.d.ts +0 -6
  288. package/dist/database/migrations/index.js +0 -12
  289. package/dist/database/migrations/index.js.map +0 -1
  290. package/dist/database/migrations/migration-engine.d.ts +0 -136
  291. package/dist/database/migrations/migration-engine.js +0 -1421
  292. package/dist/database/migrations/migration-engine.js.map +0 -1
  293. package/dist/database/operators/aggregation-builder.d.ts +0 -67
  294. package/dist/database/operators/aggregation-builder.js +0 -841
  295. package/dist/database/operators/aggregation-builder.js.map +0 -1
  296. package/dist/database/operators/index.d.ts +0 -7
  297. package/dist/database/operators/index.js +0 -15
  298. package/dist/database/operators/index.js.map +0 -1
  299. package/dist/database/operators/query-builder.d.ts +0 -69
  300. package/dist/database/operators/query-builder.js +0 -447
  301. package/dist/database/operators/query-builder.js.map +0 -1
  302. package/dist/database/presave/decrypt.d.ts +0 -25
  303. package/dist/database/presave/decrypt.js +0 -146
  304. package/dist/database/presave/decrypt.js.map +0 -1
  305. package/dist/database/presave/index.d.ts +0 -9
  306. package/dist/database/presave/index.js +0 -18
  307. package/dist/database/presave/index.js.map +0 -1
  308. package/dist/database/presave/presave-processor.d.ts +0 -148
  309. package/dist/database/presave/presave-processor.js +0 -702
  310. package/dist/database/presave/presave-processor.js.map +0 -1
  311. package/dist/database/schema/index.d.ts +0 -7
  312. package/dist/database/schema/index.js +0 -13
  313. package/dist/database/schema/index.js.map +0 -1
  314. package/dist/database/schema/schema-manager.d.ts +0 -258
  315. package/dist/database/schema/schema-manager.js +0 -638
  316. package/dist/database/schema/schema-manager.js.map +0 -1
  317. package/dist/database/transactions/index.d.ts +0 -6
  318. package/dist/database/transactions/index.js +0 -13
  319. package/dist/database/transactions/index.js.map +0 -1
  320. package/dist/database/transactions/transaction-manager.d.ts +0 -113
  321. package/dist/database/transactions/transaction-manager.js +0 -344
  322. package/dist/database/transactions/transaction-manager.js.map +0 -1
  323. package/dist/database/triggers/index.d.ts +0 -7
  324. package/dist/database/triggers/index.js +0 -14
  325. package/dist/database/triggers/index.js.map +0 -1
  326. package/dist/database/triggers/trigger-processor.d.ts +0 -239
  327. package/dist/database/triggers/trigger-processor.js +0 -1034
  328. package/dist/database/triggers/trigger-processor.js.map +0 -1
  329. package/dist/database/types/action.interface.d.ts +0 -148
  330. package/dist/database/types/action.interface.js +0 -6
  331. package/dist/database/types/action.interface.js.map +0 -1
  332. package/dist/database/types/aggregation.interface.d.ts +0 -185
  333. package/dist/database/types/aggregation.interface.js +0 -6
  334. package/dist/database/types/aggregation.interface.js.map +0 -1
  335. package/dist/database/types/connection.interface.d.ts +0 -137
  336. package/dist/database/types/connection.interface.js +0 -6
  337. package/dist/database/types/connection.interface.js.map +0 -1
  338. package/dist/database/types/dashboard.interface.d.ts +0 -74
  339. package/dist/database/types/dashboard.interface.js +0 -7
  340. package/dist/database/types/dashboard.interface.js.map +0 -1
  341. package/dist/database/types/enums.d.ts +0 -195
  342. package/dist/database/types/enums.js +0 -244
  343. package/dist/database/types/enums.js.map +0 -1
  344. package/dist/database/types/index.d.ts +0 -15
  345. package/dist/database/types/index.js +0 -31
  346. package/dist/database/types/index.js.map +0 -1
  347. package/dist/database/types/migration.interface.d.ts +0 -686
  348. package/dist/database/types/migration.interface.js +0 -9
  349. package/dist/database/types/migration.interface.js.map +0 -1
  350. package/dist/database/types/presave.interface.d.ts +0 -292
  351. package/dist/database/types/presave.interface.js +0 -60
  352. package/dist/database/types/presave.interface.js.map +0 -1
  353. package/dist/database/types/query.interface.d.ts +0 -205
  354. package/dist/database/types/query.interface.js +0 -6
  355. package/dist/database/types/query.interface.js.map +0 -1
  356. package/dist/database/types/schema.interface.d.ts +0 -412
  357. package/dist/database/types/schema.interface.js +0 -6
  358. package/dist/database/types/schema.interface.js.map +0 -1
  359. package/dist/database/types/transaction.interface.d.ts +0 -84
  360. package/dist/database/types/transaction.interface.js +0 -6
  361. package/dist/database/types/transaction.interface.js.map +0 -1
  362. package/dist/database/types/trigger.interface.d.ts +0 -612
  363. package/dist/database/types/trigger.interface.js +0 -121
  364. package/dist/database/types/trigger.interface.js.map +0 -1
  365. package/dist/database/types/write.interface.d.ts +0 -216
  366. package/dist/database/types/write.interface.js +0 -6
  367. package/dist/database/types/write.interface.js.map +0 -1
  368. package/dist/database/utils/database-error.d.ts +0 -96
  369. package/dist/database/utils/database-error.js +0 -221
  370. package/dist/database/utils/database-error.js.map +0 -1
  371. package/dist/database/utils/index.d.ts +0 -6
  372. package/dist/database/utils/index.js +0 -11
  373. package/dist/database/utils/index.js.map +0 -1
  374. package/dist/graph/adapters/adapter.factory.d.ts +0 -47
  375. package/dist/graph/adapters/adapter.factory.js +0 -77
  376. package/dist/graph/adapters/adapter.factory.js.map +0 -1
  377. package/dist/graph/adapters/arangodb.adapter.d.ts +0 -86
  378. package/dist/graph/adapters/arangodb.adapter.js +0 -1588
  379. package/dist/graph/adapters/arangodb.adapter.js.map +0 -1
  380. package/dist/graph/adapters/base.adapter.d.ts +0 -264
  381. package/dist/graph/adapters/base.adapter.js +0 -156
  382. package/dist/graph/adapters/base.adapter.js.map +0 -1
  383. package/dist/graph/adapters/index.d.ts +0 -11
  384. package/dist/graph/adapters/index.js +0 -21
  385. package/dist/graph/adapters/index.js.map +0 -1
  386. package/dist/graph/adapters/memgraph.adapter.d.ts +0 -110
  387. package/dist/graph/adapters/memgraph.adapter.js +0 -1452
  388. package/dist/graph/adapters/memgraph.adapter.js.map +0 -1
  389. package/dist/graph/adapters/neo4j.adapter.d.ts +0 -81
  390. package/dist/graph/adapters/neo4j.adapter.js +0 -1317
  391. package/dist/graph/adapters/neo4j.adapter.js.map +0 -1
  392. package/dist/graph/adapters/neptune.adapter.d.ts +0 -82
  393. package/dist/graph/adapters/neptune.adapter.js +0 -1369
  394. package/dist/graph/adapters/neptune.adapter.js.map +0 -1
  395. package/dist/graph/graphs.service.d.ts +0 -617
  396. package/dist/graph/graphs.service.js +0 -2594
  397. package/dist/graph/graphs.service.js.map +0 -1
  398. package/dist/graph/index.d.ts +0 -57
  399. package/dist/graph/index.js +0 -77
  400. package/dist/graph/index.js.map +0 -1
  401. package/dist/graph/transactions/index.d.ts +0 -4
  402. package/dist/graph/transactions/index.js +0 -9
  403. package/dist/graph/transactions/index.js.map +0 -1
  404. package/dist/graph/transactions/transaction-manager.d.ts +0 -61
  405. package/dist/graph/transactions/transaction-manager.js +0 -126
  406. package/dist/graph/transactions/transaction-manager.js.map +0 -1
  407. package/dist/graph/types/connection.interface.d.ts +0 -149
  408. package/dist/graph/types/connection.interface.js +0 -9
  409. package/dist/graph/types/connection.interface.js.map +0 -1
  410. package/dist/graph/types/enums.d.ts +0 -101
  411. package/dist/graph/types/enums.js +0 -114
  412. package/dist/graph/types/enums.js.map +0 -1
  413. package/dist/graph/types/index.d.ts +0 -13
  414. package/dist/graph/types/index.js +0 -20
  415. package/dist/graph/types/index.js.map +0 -1
  416. package/dist/graph/types/node.interface.d.ts +0 -248
  417. package/dist/graph/types/node.interface.js +0 -9
  418. package/dist/graph/types/node.interface.js.map +0 -1
  419. package/dist/graph/types/query.interface.d.ts +0 -175
  420. package/dist/graph/types/query.interface.js +0 -9
  421. package/dist/graph/types/query.interface.js.map +0 -1
  422. package/dist/graph/types/relationship.interface.d.ts +0 -207
  423. package/dist/graph/types/relationship.interface.js +0 -9
  424. package/dist/graph/types/relationship.interface.js.map +0 -1
  425. package/dist/graph/types/schema.interface.d.ts +0 -295
  426. package/dist/graph/types/schema.interface.js +0 -9
  427. package/dist/graph/types/schema.interface.js.map +0 -1
  428. package/dist/graph/types/transaction.interface.d.ts +0 -55
  429. package/dist/graph/types/transaction.interface.js +0 -9
  430. package/dist/graph/types/transaction.interface.js.map +0 -1
  431. package/dist/graph/types/traversal.interface.d.ts +0 -181
  432. package/dist/graph/types/traversal.interface.js +0 -9
  433. package/dist/graph/types/traversal.interface.js.map +0 -1
  434. package/dist/graph/utils/graph-error.d.ts +0 -71
  435. package/dist/graph/utils/graph-error.js +0 -142
  436. package/dist/graph/utils/graph-error.js.map +0 -1
  437. package/dist/graph/utils/index.d.ts +0 -4
  438. package/dist/graph/utils/index.js +0 -9
  439. package/dist/graph/utils/index.js.map +0 -1
  440. package/dist/imports/imports.repo.d.ts +0 -0
  441. package/dist/imports/imports.repo.js +0 -1
  442. package/dist/imports/imports.repo.js.map +0 -1
  443. package/dist/imports/imports.service.d.ts +0 -23
  444. package/dist/imports/imports.service.js +0 -71
  445. package/dist/imports/imports.service.js.map +0 -1
  446. package/dist/imports/imports.types.d.ts +0 -350
  447. package/dist/imports/imports.types.js +0 -33
  448. package/dist/imports/imports.types.js.map +0 -1
  449. package/dist/imports/openAPI3.0.types.d.ts +0 -52
  450. package/dist/imports/openAPI3.0.types.js +0 -3
  451. package/dist/imports/openAPI3.0.types.js.map +0 -1
  452. package/dist/imports/repos/openApi.repo.d.ts +0 -6
  453. package/dist/imports/repos/openApi.repo.js +0 -422
  454. package/dist/imports/repos/openApi.repo.js.map +0 -1
  455. package/dist/imports/repos/postmanV21.repo.d.ts +0 -14
  456. package/dist/imports/repos/postmanV21.repo.js +0 -257
  457. package/dist/imports/repos/postmanV21.repo.js.map +0 -1
  458. package/dist/imports/utils/imports.utils.d.ts +0 -80
  459. package/dist/imports/utils/imports.utils.js +0 -114
  460. package/dist/imports/utils/imports.utils.js.map +0 -1
  461. package/dist/imports/validators/index.d.ts +0 -0
  462. package/dist/imports/validators/index.js +0 -1
  463. package/dist/imports/validators/index.js.map +0 -1
  464. package/dist/imports/validators/joi-validators/postmanV21.validator.d.ts +0 -5
  465. package/dist/imports/validators/joi-validators/postmanV21.validator.js +0 -96
  466. package/dist/imports/validators/joi-validators/postmanV21.validator.js.map +0 -1
  467. package/dist/index.d.ts +0 -4021
  468. package/dist/index.js +0 -5895
  469. package/dist/index.js.map +0 -1
  470. package/dist/init.interface.d.ts +0 -407
  471. package/dist/init.interface.js +0 -3
  472. package/dist/init.interface.js.map +0 -1
  473. package/dist/inputs/inputs.repo.d.ts +0 -7
  474. package/dist/inputs/inputs.repo.js +0 -16
  475. package/dist/inputs/inputs.repo.js.map +0 -1
  476. package/dist/inputs/inputs.service.d.ts +0 -61
  477. package/dist/inputs/inputs.service.js +0 -468
  478. package/dist/inputs/inputs.service.js.map +0 -1
  479. package/dist/inputs/utils/inputs.utils.create.d.ts +0 -11
  480. package/dist/inputs/utils/inputs.utils.create.js +0 -273
  481. package/dist/inputs/utils/inputs.utils.create.js.map +0 -1
  482. package/dist/inputs/validators/inputs.validator.parse.d.ts +0 -4
  483. package/dist/inputs/validators/inputs.validator.parse.js +0 -53
  484. package/dist/inputs/validators/inputs.validator.parse.js.map +0 -1
  485. package/dist/jobs/index.d.ts +0 -38
  486. package/dist/jobs/index.js +0 -50
  487. package/dist/jobs/index.js.map +0 -1
  488. package/dist/jobs/jobs.service.d.ts +0 -154
  489. package/dist/jobs/jobs.service.js +0 -491
  490. package/dist/jobs/jobs.service.js.map +0 -1
  491. package/dist/jobs/jobs.state.d.ts +0 -113
  492. package/dist/jobs/jobs.state.js +0 -447
  493. package/dist/jobs/jobs.state.js.map +0 -1
  494. package/dist/jobs/types.d.ts +0 -449
  495. package/dist/jobs/types.js +0 -74
  496. package/dist/jobs/types.js.map +0 -1
  497. package/dist/logs/logs.repo.d.ts +0 -6
  498. package/dist/logs/logs.repo.js +0 -12
  499. package/dist/logs/logs.repo.js.map +0 -1
  500. package/dist/logs/logs.service.d.ts +0 -30
  501. package/dist/logs/logs.service.js +0 -89
  502. package/dist/logs/logs.service.js.map +0 -1
  503. package/dist/logs/logs.types.d.ts +0 -85
  504. package/dist/logs/logs.types.js +0 -52
  505. package/dist/logs/logs.types.js.map +0 -1
  506. package/dist/logs/utils/logs.utils.create.d.ts +0 -0
  507. package/dist/logs/utils/logs.utils.create.js +0 -1
  508. package/dist/logs/utils/logs.utils.create.js.map +0 -1
  509. package/dist/logs/utils/logs.utils.errors.d.ts +0 -2
  510. package/dist/logs/utils/logs.utils.errors.js +0 -8
  511. package/dist/logs/utils/logs.utils.errors.js.map +0 -1
  512. package/dist/models/index.d.ts +0 -6
  513. package/dist/models/index.js +0 -11
  514. package/dist/models/index.js.map +0 -1
  515. package/dist/models/models.service.d.ts +0 -137
  516. package/dist/models/models.service.js +0 -195
  517. package/dist/models/models.service.js.map +0 -1
  518. package/dist/notifications/index.d.ts +0 -13
  519. package/dist/notifications/index.js +0 -26
  520. package/dist/notifications/index.js.map +0 -1
  521. package/dist/notifications/notifications.service.d.ts +0 -268
  522. package/dist/notifications/notifications.service.js +0 -907
  523. package/dist/notifications/notifications.service.js.map +0 -1
  524. package/dist/notifications/types/index.d.ts +0 -4
  525. package/dist/notifications/types/index.js +0 -21
  526. package/dist/notifications/types/index.js.map +0 -1
  527. package/dist/notifications/types/notifications.types.d.ts +0 -454
  528. package/dist/notifications/types/notifications.types.js +0 -51
  529. package/dist/notifications/types/notifications.types.js.map +0 -1
  530. package/dist/parsers/index.d.ts +0 -3
  531. package/dist/parsers/index.js +0 -27
  532. package/dist/parsers/index.js.map +0 -1
  533. package/dist/parsers/pipelines/postman.pipelines.d.ts +0 -15
  534. package/dist/parsers/pipelines/postman.pipelines.js +0 -103
  535. package/dist/parsers/pipelines/postman.pipelines.js.map +0 -1
  536. package/dist/parsers/types/postman.types.d.ts +0 -200
  537. package/dist/parsers/types/postman.types.js +0 -3
  538. package/dist/parsers/types/postman.types.js.map +0 -1
  539. package/dist/parsers/utils/postman.utils.d.ts +0 -12
  540. package/dist/parsers/utils/postman.utils.js +0 -116
  541. package/dist/parsers/utils/postman.utils.js.map +0 -1
  542. package/dist/parsers/validators/postman-auth.validators.d.ts +0 -10
  543. package/dist/parsers/validators/postman-auth.validators.js +0 -127
  544. package/dist/parsers/validators/postman-auth.validators.js.map +0 -1
  545. package/dist/parsers/validators/postman-request.validators.d.ts +0 -13
  546. package/dist/parsers/validators/postman-request.validators.js +0 -139
  547. package/dist/parsers/validators/postman-request.validators.js.map +0 -1
  548. package/dist/parsers/validators/postman-response.validators.d.ts +0 -13
  549. package/dist/parsers/validators/postman-response.validators.js +0 -150
  550. package/dist/parsers/validators/postman-response.validators.js.map +0 -1
  551. package/dist/parsers/validators/postman-variable.validators.d.ts +0 -14
  552. package/dist/parsers/validators/postman-variable.validators.js +0 -163
  553. package/dist/parsers/validators/postman-variable.validators.js.map +0 -1
  554. package/dist/pricing/pricing.repo.d.ts +0 -0
  555. package/dist/pricing/pricing.repo.js +0 -1
  556. package/dist/pricing/pricing.repo.js.map +0 -1
  557. package/dist/pricing/pricing.service.d.ts +0 -24
  558. package/dist/pricing/pricing.service.js +0 -51
  559. package/dist/pricing/pricing.service.js.map +0 -1
  560. package/dist/pricing/pricing.types.d.ts +0 -76
  561. package/dist/pricing/pricing.types.js +0 -21
  562. package/dist/pricing/pricing.types.js.map +0 -1
  563. package/dist/pricing/utils/string.utils.d.ts +0 -1
  564. package/dist/pricing/utils/string.utils.js +0 -9
  565. package/dist/pricing/utils/string.utils.js.map +0 -1
  566. package/dist/processor/repos/mongo.repo.d.ts +0 -39
  567. package/dist/processor/repos/mongo.repo.js +0 -260
  568. package/dist/processor/repos/mongo.repo.js.map +0 -1
  569. package/dist/processor/repos/postgres.repo.d.ts +0 -31
  570. package/dist/processor/repos/postgres.repo.js +0 -185
  571. package/dist/processor/repos/postgres.repo.js.map +0 -1
  572. package/dist/processor/repos/sms.repo.d.ts +0 -39
  573. package/dist/processor/repos/sms.repo.js +0 -124
  574. package/dist/processor/repos/sms.repo.js.map +0 -1
  575. package/dist/processor/services/processor.service.d.ts +0 -465
  576. package/dist/processor/services/processor.service.js +0 -5343
  577. package/dist/processor/services/processor.service.js.map +0 -1
  578. package/dist/processor/services/request.service.d.ts +0 -36
  579. package/dist/processor/services/request.service.js +0 -304
  580. package/dist/processor/services/request.service.js.map +0 -1
  581. package/dist/processor/types/request.types.d.ts +0 -14
  582. package/dist/processor/types/request.types.js +0 -3
  583. package/dist/processor/types/request.types.js.map +0 -1
  584. package/dist/processor/utils/processor.utils.d.ts +0 -104
  585. package/dist/processor/utils/processor.utils.js +0 -1066
  586. package/dist/processor/utils/processor.utils.js.map +0 -1
  587. package/dist/processor/utils/request.utils.d.ts +0 -20
  588. package/dist/processor/utils/request.utils.js +0 -113
  589. package/dist/processor/utils/request.utils.js.map +0 -1
  590. package/dist/processor/utils/storage.util.d.ts +0 -8
  591. package/dist/processor/utils/storage.util.js +0 -106
  592. package/dist/processor/utils/storage.util.js.map +0 -1
  593. package/dist/products/services/products.service.d.ts +0 -577
  594. package/dist/products/services/products.service.js +0 -5845
  595. package/dist/products/services/products.service.js.map +0 -1
  596. package/dist/products/utils/crypt.utils.d.ts +0 -1
  597. package/dist/products/utils/crypt.utils.js +0 -17
  598. package/dist/products/utils/crypt.utils.js.map +0 -1
  599. package/dist/products/utils/functions.utils.d.ts +0 -13
  600. package/dist/products/utils/functions.utils.js +0 -294
  601. package/dist/products/utils/functions.utils.js.map +0 -1
  602. package/dist/products/utils/objects.utils.d.ts +0 -13
  603. package/dist/products/utils/objects.utils.js +0 -89
  604. package/dist/products/utils/objects.utils.js.map +0 -1
  605. package/dist/products/utils/string.utils.d.ts +0 -12
  606. package/dist/products/utils/string.utils.js +0 -168
  607. package/dist/products/utils/string.utils.js.map +0 -1
  608. package/dist/products/validators/index.d.ts +0 -33
  609. package/dist/products/validators/index.js +0 -75
  610. package/dist/products/validators/index.js.map +0 -1
  611. package/dist/products/validators/joi-validators/create.html.validator.d.ts +0 -2
  612. package/dist/products/validators/joi-validators/create.html.validator.js +0 -55
  613. package/dist/products/validators/joi-validators/create.html.validator.js.map +0 -1
  614. package/dist/products/validators/joi-validators/create.productAgent.validator.d.ts +0 -3
  615. package/dist/products/validators/joi-validators/create.productAgent.validator.js +0 -266
  616. package/dist/products/validators/joi-validators/create.productAgent.validator.js.map +0 -1
  617. package/dist/products/validators/joi-validators/create.productApp.validator.d.ts +0 -4
  618. package/dist/products/validators/joi-validators/create.productApp.validator.js +0 -61
  619. package/dist/products/validators/joi-validators/create.productApp.validator.js.map +0 -1
  620. package/dist/products/validators/joi-validators/create.productCache.validator.d.ts +0 -3
  621. package/dist/products/validators/joi-validators/create.productCache.validator.js +0 -46
  622. package/dist/products/validators/joi-validators/create.productCache.validator.js.map +0 -1
  623. package/dist/products/validators/joi-validators/create.productDatabase.validator.d.ts +0 -3
  624. package/dist/products/validators/joi-validators/create.productDatabase.validator.js +0 -77
  625. package/dist/products/validators/joi-validators/create.productDatabase.validator.js.map +0 -1
  626. package/dist/products/validators/joi-validators/create.productDatabaseAction.validator.d.ts +0 -7
  627. package/dist/products/validators/joi-validators/create.productDatabaseAction.validator.js +0 -194
  628. package/dist/products/validators/joi-validators/create.productDatabaseAction.validator.js.map +0 -1
  629. package/dist/products/validators/joi-validators/create.productDatabaseMigration.validator.d.ts +0 -4
  630. package/dist/products/validators/joi-validators/create.productDatabaseMigration.validator.js +0 -63
  631. package/dist/products/validators/joi-validators/create.productDatabaseMigration.validator.js.map +0 -1
  632. package/dist/products/validators/joi-validators/create.productEnv.validator.d.ts +0 -3
  633. package/dist/products/validators/joi-validators/create.productEnv.validator.js +0 -45
  634. package/dist/products/validators/joi-validators/create.productEnv.validator.js.map +0 -1
  635. package/dist/products/validators/joi-validators/create.productFallback.validator.d.ts +0 -3
  636. package/dist/products/validators/joi-validators/create.productFallback.validator.js +0 -64
  637. package/dist/products/validators/joi-validators/create.productFallback.validator.js.map +0 -1
  638. package/dist/products/validators/joi-validators/create.productFeature.validator.d.ts +0 -14
  639. package/dist/products/validators/joi-validators/create.productFeature.validator.js +0 -140
  640. package/dist/products/validators/joi-validators/create.productFeature.validator.js.map +0 -1
  641. package/dist/products/validators/joi-validators/create.productFunction.validator.d.ts +0 -3
  642. package/dist/products/validators/joi-validators/create.productFunction.validator.js +0 -57
  643. package/dist/products/validators/joi-validators/create.productFunction.validator.js.map +0 -1
  644. package/dist/products/validators/joi-validators/create.productGraph.validator.d.ts +0 -3
  645. package/dist/products/validators/joi-validators/create.productGraph.validator.js +0 -89
  646. package/dist/products/validators/joi-validators/create.productGraph.validator.js.map +0 -1
  647. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.d.ts +0 -4
  648. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.js +0 -58
  649. package/dist/products/validators/joi-validators/create.productHealthcheck.validator.js.map +0 -1
  650. package/dist/products/validators/joi-validators/create.productJob.validator.d.ts +0 -12
  651. package/dist/products/validators/joi-validators/create.productJob.validator.js +0 -60
  652. package/dist/products/validators/joi-validators/create.productJob.validator.js.map +0 -1
  653. package/dist/products/validators/joi-validators/create.productMessageBrokerTopic.validator.d.ts +0 -3
  654. package/dist/products/validators/joi-validators/create.productMessageBrokerTopic.validator.js +0 -52
  655. package/dist/products/validators/joi-validators/create.productMessageBrokerTopic.validator.js.map +0 -1
  656. package/dist/products/validators/joi-validators/create.productMessageBrokers.validator.d.ts +0 -3
  657. package/dist/products/validators/joi-validators/create.productMessageBrokers.validator.js +0 -193
  658. package/dist/products/validators/joi-validators/create.productMessageBrokers.validator.js.map +0 -1
  659. package/dist/products/validators/joi-validators/create.productModel.validator.d.ts +0 -3
  660. package/dist/products/validators/joi-validators/create.productModel.validator.js +0 -132
  661. package/dist/products/validators/joi-validators/create.productModel.validator.js.map +0 -1
  662. package/dist/products/validators/joi-validators/create.productNotification.validator.d.ts +0 -4
  663. package/dist/products/validators/joi-validators/create.productNotification.validator.js +0 -241
  664. package/dist/products/validators/joi-validators/create.productNotification.validator.js.map +0 -1
  665. package/dist/products/validators/joi-validators/create.productNotificationMessage.validator.d.ts +0 -3
  666. package/dist/products/validators/joi-validators/create.productNotificationMessage.validator.js +0 -57
  667. package/dist/products/validators/joi-validators/create.productNotificationMessage.validator.js.map +0 -1
  668. package/dist/products/validators/joi-validators/create.productNotifications.validator.d.ts +0 -0
  669. package/dist/products/validators/joi-validators/create.productNotifications.validator.js +0 -1
  670. package/dist/products/validators/joi-validators/create.productNotifications.validator.js.map +0 -1
  671. package/dist/products/validators/joi-validators/create.productQuota.validator.d.ts +0 -3
  672. package/dist/products/validators/joi-validators/create.productQuota.validator.js +0 -67
  673. package/dist/products/validators/joi-validators/create.productQuota.validator.js.map +0 -1
  674. package/dist/products/validators/joi-validators/create.productStorage.validator.d.ts +0 -3
  675. package/dist/products/validators/joi-validators/create.productStorage.validator.js +0 -158
  676. package/dist/products/validators/joi-validators/create.productStorage.validator.js.map +0 -1
  677. package/dist/products/validators/joi-validators/create.productVector.validator.d.ts +0 -3
  678. package/dist/products/validators/joi-validators/create.productVector.validator.js +0 -136
  679. package/dist/products/validators/joi-validators/create.productVector.validator.js.map +0 -1
  680. package/dist/products/validators/joi-validators/create.products.validator.d.ts +0 -3
  681. package/dist/products/validators/joi-validators/create.products.validator.js +0 -43
  682. package/dist/products/validators/joi-validators/create.products.validator.js.map +0 -1
  683. package/dist/products/validators/joi-validators/create.requestAction.validator.d.ts +0 -2
  684. package/dist/products/validators/joi-validators/create.requestAction.validator.js +0 -45
  685. package/dist/products/validators/joi-validators/create.requestAction.validator.js.map +0 -1
  686. package/dist/products/validators/joi-validators/create.userAuth.validator.d.ts +0 -3
  687. package/dist/products/validators/joi-validators/create.userAuth.validator.js +0 -48
  688. package/dist/products/validators/joi-validators/create.userAuth.validator.js.map +0 -1
  689. package/dist/products/validators/joi-validators/register.productWebhooks.validator.d.ts +0 -3
  690. package/dist/products/validators/joi-validators/register.productWebhooks.validator.js +0 -48
  691. package/dist/products/validators/joi-validators/register.productWebhooks.validator.js.map +0 -1
  692. package/dist/products/validators/joi-validators/update.dataValue.validator.d.ts +0 -3
  693. package/dist/products/validators/joi-validators/update.dataValue.validator.js +0 -103
  694. package/dist/products/validators/joi-validators/update.dataValue.validator.js.map +0 -1
  695. package/dist/products/validators/joi-validators/update.productApp.validator.d.ts +0 -3
  696. package/dist/products/validators/joi-validators/update.productApp.validator.js +0 -42
  697. package/dist/products/validators/joi-validators/update.productApp.validator.js.map +0 -1
  698. package/dist/products/validators/joi-validators/update.productCache.validator.d.ts +0 -3
  699. package/dist/products/validators/joi-validators/update.productCache.validator.js +0 -45
  700. package/dist/products/validators/joi-validators/update.productCache.validator.js.map +0 -1
  701. package/dist/products/validators/joi-validators/update.productDatabase.validator.d.ts +0 -3
  702. package/dist/products/validators/joi-validators/update.productDatabase.validator.js +0 -76
  703. package/dist/products/validators/joi-validators/update.productDatabase.validator.js.map +0 -1
  704. package/dist/products/validators/joi-validators/update.productDatabaseAction.validator.d.ts +0 -3
  705. package/dist/products/validators/joi-validators/update.productDatabaseAction.validator.js +0 -79
  706. package/dist/products/validators/joi-validators/update.productDatabaseAction.validator.js.map +0 -1
  707. package/dist/products/validators/joi-validators/update.productDatabaseMigration.validator.d.ts +0 -4
  708. package/dist/products/validators/joi-validators/update.productDatabaseMigration.validator.js +0 -64
  709. package/dist/products/validators/joi-validators/update.productDatabaseMigration.validator.js.map +0 -1
  710. package/dist/products/validators/joi-validators/update.productEnv.validator.d.ts +0 -3
  711. package/dist/products/validators/joi-validators/update.productEnv.validator.js +0 -46
  712. package/dist/products/validators/joi-validators/update.productEnv.validator.js.map +0 -1
  713. package/dist/products/validators/joi-validators/update.productFallback.validator.d.ts +0 -3
  714. package/dist/products/validators/joi-validators/update.productFallback.validator.js +0 -60
  715. package/dist/products/validators/joi-validators/update.productFallback.validator.js.map +0 -1
  716. package/dist/products/validators/joi-validators/update.productFeature.validator.d.ts +0 -3
  717. package/dist/products/validators/joi-validators/update.productFeature.validator.js +0 -53
  718. package/dist/products/validators/joi-validators/update.productFeature.validator.js.map +0 -1
  719. package/dist/products/validators/joi-validators/update.productFunction.validator.d.ts +0 -3
  720. package/dist/products/validators/joi-validators/update.productFunction.validator.js +0 -41
  721. package/dist/products/validators/joi-validators/update.productFunction.validator.js.map +0 -1
  722. package/dist/products/validators/joi-validators/update.productGraph.validator.d.ts +0 -3
  723. package/dist/products/validators/joi-validators/update.productGraph.validator.js +0 -88
  724. package/dist/products/validators/joi-validators/update.productGraph.validator.js.map +0 -1
  725. package/dist/products/validators/joi-validators/update.productJob.validator.d.ts +0 -3
  726. package/dist/products/validators/joi-validators/update.productJob.validator.js +0 -50
  727. package/dist/products/validators/joi-validators/update.productJob.validator.js.map +0 -1
  728. package/dist/products/validators/joi-validators/update.productMessageBrokerTopic.validator.d.ts +0 -3
  729. package/dist/products/validators/joi-validators/update.productMessageBrokerTopic.validator.js +0 -52
  730. package/dist/products/validators/joi-validators/update.productMessageBrokerTopic.validator.js.map +0 -1
  731. package/dist/products/validators/joi-validators/update.productNotification.validator.d.ts +0 -3
  732. package/dist/products/validators/joi-validators/update.productNotification.validator.js +0 -47
  733. package/dist/products/validators/joi-validators/update.productNotification.validator.js.map +0 -1
  734. package/dist/products/validators/joi-validators/update.productNotificationMessage.validator.d.ts +0 -3
  735. package/dist/products/validators/joi-validators/update.productNotificationMessage.validator.js +0 -58
  736. package/dist/products/validators/joi-validators/update.productNotificationMessage.validator.js.map +0 -1
  737. package/dist/products/validators/joi-validators/update.productQuota.validator.d.ts +0 -3
  738. package/dist/products/validators/joi-validators/update.productQuota.validator.js +0 -64
  739. package/dist/products/validators/joi-validators/update.productQuota.validator.js.map +0 -1
  740. package/dist/products/validators/joi-validators/update.userAuth.validator.d.ts +0 -3
  741. package/dist/products/validators/joi-validators/update.userAuth.validator.js +0 -48
  742. package/dist/products/validators/joi-validators/update.userAuth.validator.js.map +0 -1
  743. package/dist/resilience/fallback.service.d.ts +0 -141
  744. package/dist/resilience/fallback.service.js +0 -766
  745. package/dist/resilience/fallback.service.js.map +0 -1
  746. package/dist/resilience/healthcheck.service.d.ts +0 -163
  747. package/dist/resilience/healthcheck.service.js +0 -1012
  748. package/dist/resilience/healthcheck.service.js.map +0 -1
  749. package/dist/resilience/index.d.ts +0 -104
  750. package/dist/resilience/index.js +0 -140
  751. package/dist/resilience/index.js.map +0 -1
  752. package/dist/resilience/quota.service.d.ts +0 -83
  753. package/dist/resilience/quota.service.js +0 -518
  754. package/dist/resilience/quota.service.js.map +0 -1
  755. package/dist/resilience/resilience.service.d.ts +0 -98
  756. package/dist/resilience/resilience.service.js +0 -560
  757. package/dist/resilience/resilience.service.js.map +0 -1
  758. package/dist/resilience/types/index.d.ts +0 -513
  759. package/dist/resilience/types/index.js +0 -29
  760. package/dist/resilience/types/index.js.map +0 -1
  761. package/dist/secrets/index.d.ts +0 -10
  762. package/dist/secrets/index.js +0 -33
  763. package/dist/secrets/index.js.map +0 -1
  764. package/dist/secrets/secrets.resolver.d.ts +0 -52
  765. package/dist/secrets/secrets.resolver.js +0 -236
  766. package/dist/secrets/secrets.resolver.js.map +0 -1
  767. package/dist/secrets/secrets.service.d.ts +0 -93
  768. package/dist/secrets/secrets.service.js +0 -246
  769. package/dist/secrets/secrets.service.js.map +0 -1
  770. package/dist/secrets/secrets.types.d.ts +0 -188
  771. package/dist/secrets/secrets.types.js +0 -87
  772. package/dist/secrets/secrets.types.js.map +0 -1
  773. package/dist/sessions/index.d.ts +0 -50
  774. package/dist/sessions/index.js +0 -96
  775. package/dist/sessions/index.js.map +0 -1
  776. package/dist/sessions/sessions.helper.d.ts +0 -88
  777. package/dist/sessions/sessions.helper.js +0 -190
  778. package/dist/sessions/sessions.helper.js.map +0 -1
  779. package/dist/sessions/sessions.resolver.d.ts +0 -188
  780. package/dist/sessions/sessions.resolver.js +0 -603
  781. package/dist/sessions/sessions.resolver.js.map +0 -1
  782. package/dist/sessions/sessions.service.d.ts +0 -194
  783. package/dist/sessions/sessions.service.js +0 -988
  784. package/dist/sessions/sessions.service.js.map +0 -1
  785. package/dist/sessions/types/index.d.ts +0 -344
  786. package/dist/sessions/types/index.js +0 -6
  787. package/dist/sessions/types/index.js.map +0 -1
  788. package/dist/storage/index.d.ts +0 -66
  789. package/dist/storage/index.js +0 -99
  790. package/dist/storage/index.js.map +0 -1
  791. package/dist/storage/storage.service.d.ts +0 -177
  792. package/dist/storage/storage.service.js +0 -905
  793. package/dist/storage/storage.service.js.map +0 -1
  794. package/dist/storage/types/index.d.ts +0 -270
  795. package/dist/storage/types/index.js +0 -6
  796. package/dist/storage/types/index.js.map +0 -1
  797. package/dist/storage/utils/storage.util.d.ts +0 -62
  798. package/dist/storage/utils/storage.util.js +0 -593
  799. package/dist/storage/utils/storage.util.js.map +0 -1
  800. package/dist/types/actions.types.d.ts +0 -0
  801. package/dist/types/actions.types.js +0 -1
  802. package/dist/types/actions.types.js.map +0 -1
  803. package/dist/types/appBuilder.types.d.ts +0 -316
  804. package/dist/types/appBuilder.types.js +0 -3
  805. package/dist/types/appBuilder.types.js.map +0 -1
  806. package/dist/types/database.types.d.ts +0 -9
  807. package/dist/types/database.types.js +0 -3
  808. package/dist/types/database.types.js.map +0 -1
  809. package/dist/types/enums.d.ts +0 -231
  810. package/dist/types/enums.js +0 -261
  811. package/dist/types/enums.js.map +0 -1
  812. package/dist/types/index.d.ts +0 -12
  813. package/dist/types/index.js +0 -29
  814. package/dist/types/index.js.map +0 -1
  815. package/dist/types/index.types.d.ts +0 -30
  816. package/dist/types/index.types.js +0 -9
  817. package/dist/types/index.types.js.map +0 -1
  818. package/dist/types/inputs.types.d.ts +0 -114
  819. package/dist/types/inputs.types.js +0 -44
  820. package/dist/types/inputs.types.js.map +0 -1
  821. package/dist/types/logs.types.d.ts +0 -19
  822. package/dist/types/logs.types.js +0 -8
  823. package/dist/types/logs.types.js.map +0 -1
  824. package/dist/types/pricing.types.d.ts +0 -4
  825. package/dist/types/pricing.types.js +0 -3
  826. package/dist/types/pricing.types.js.map +0 -1
  827. package/dist/types/processor.types.d.ts +0 -602
  828. package/dist/types/processor.types.js +0 -19
  829. package/dist/types/processor.types.js.map +0 -1
  830. package/dist/types/productsBuilder.types.d.ts +0 -1566
  831. package/dist/types/productsBuilder.types.js +0 -303
  832. package/dist/types/productsBuilder.types.js.map +0 -1
  833. package/dist/types/request-tracker.interface.d.ts +0 -0
  834. package/dist/types/request-tracker.interface.js +0 -1
  835. package/dist/types/request-tracker.interface.js.map +0 -1
  836. package/dist/types/requests.types.d.ts +0 -8
  837. package/dist/types/requests.types.js +0 -3
  838. package/dist/types/requests.types.js.map +0 -1
  839. package/dist/types/workspaces.types.d.ts +0 -28
  840. package/dist/types/workspaces.types.js +0 -4
  841. package/dist/types/workspaces.types.js.map +0 -1
  842. package/dist/utils/constants.d.ts +0 -1
  843. package/dist/utils/constants.js +0 -5
  844. package/dist/utils/constants.js.map +0 -1
  845. package/dist/utils/index.d.ts +0 -2
  846. package/dist/utils/index.js +0 -109
  847. package/dist/utils/index.js.map +0 -1
  848. package/dist/vector/actions/action-manager.d.ts +0 -140
  849. package/dist/vector/actions/action-manager.js +0 -356
  850. package/dist/vector/actions/action-manager.js.map +0 -1
  851. package/dist/vector/adapters/base.adapter.d.ts +0 -169
  852. package/dist/vector/adapters/base.adapter.js +0 -218
  853. package/dist/vector/adapters/base.adapter.js.map +0 -1
  854. package/dist/vector/adapters/index.d.ts +0 -10
  855. package/dist/vector/adapters/index.js +0 -19
  856. package/dist/vector/adapters/index.js.map +0 -1
  857. package/dist/vector/adapters/memory.adapter.d.ts +0 -85
  858. package/dist/vector/adapters/memory.adapter.js +0 -505
  859. package/dist/vector/adapters/memory.adapter.js.map +0 -1
  860. package/dist/vector/adapters/pinecone.adapter.d.ts +0 -52
  861. package/dist/vector/adapters/pinecone.adapter.js +0 -433
  862. package/dist/vector/adapters/pinecone.adapter.js.map +0 -1
  863. package/dist/vector/adapters/qdrant.adapter.d.ts +0 -56
  864. package/dist/vector/adapters/qdrant.adapter.js +0 -442
  865. package/dist/vector/adapters/qdrant.adapter.js.map +0 -1
  866. package/dist/vector/adapters/weaviate.adapter.d.ts +0 -68
  867. package/dist/vector/adapters/weaviate.adapter.js +0 -661
  868. package/dist/vector/adapters/weaviate.adapter.js.map +0 -1
  869. package/dist/vector/index.d.ts +0 -36
  870. package/dist/vector/index.js +0 -70
  871. package/dist/vector/index.js.map +0 -1
  872. package/dist/vector/types/action.interface.d.ts +0 -195
  873. package/dist/vector/types/action.interface.js +0 -100
  874. package/dist/vector/types/action.interface.js.map +0 -1
  875. package/dist/vector/types/connection.interface.d.ts +0 -151
  876. package/dist/vector/types/connection.interface.js +0 -8
  877. package/dist/vector/types/connection.interface.js.map +0 -1
  878. package/dist/vector/types/embedding.interface.d.ts +0 -144
  879. package/dist/vector/types/embedding.interface.js +0 -8
  880. package/dist/vector/types/embedding.interface.js.map +0 -1
  881. package/dist/vector/types/enums.d.ts +0 -104
  882. package/dist/vector/types/enums.js +0 -113
  883. package/dist/vector/types/enums.js.map +0 -1
  884. package/dist/vector/types/index.d.ts +0 -11
  885. package/dist/vector/types/index.js +0 -23
  886. package/dist/vector/types/index.js.map +0 -1
  887. package/dist/vector/types/vector.interface.d.ts +0 -315
  888. package/dist/vector/types/vector.interface.js +0 -8
  889. package/dist/vector/types/vector.interface.js.map +0 -1
  890. package/dist/vector/utils/index.d.ts +0 -6
  891. package/dist/vector/utils/index.js +0 -11
  892. package/dist/vector/utils/index.js.map +0 -1
  893. package/dist/vector/utils/vector-error.d.ts +0 -69
  894. package/dist/vector/utils/vector-error.js +0 -116
  895. package/dist/vector/utils/vector-error.js.map +0 -1
  896. package/dist/vector/vector-database.service.d.ts +0 -484
  897. package/dist/vector/vector-database.service.js +0 -1002
  898. package/dist/vector/vector-database.service.js.map +0 -1
  899. package/dist/vector/vector.service.d.ts +0 -283
  900. package/dist/vector/vector.service.js +0 -544
  901. package/dist/vector/vector.service.js.map +0 -1
  902. package/dist/warehouse/executor/index.d.ts +0 -5
  903. package/dist/warehouse/executor/index.js +0 -12
  904. package/dist/warehouse/executor/index.js.map +0 -1
  905. package/dist/warehouse/executor/joins/index.d.ts +0 -5
  906. package/dist/warehouse/executor/joins/index.js +0 -11
  907. package/dist/warehouse/executor/joins/index.js.map +0 -1
  908. package/dist/warehouse/executor/joins/join-executor.d.ts +0 -101
  909. package/dist/warehouse/executor/joins/join-executor.js +0 -493
  910. package/dist/warehouse/executor/joins/join-executor.js.map +0 -1
  911. package/dist/warehouse/executor/joins/semantic-join.d.ts +0 -64
  912. package/dist/warehouse/executor/joins/semantic-join.js +0 -241
  913. package/dist/warehouse/executor/joins/semantic-join.js.map +0 -1
  914. package/dist/warehouse/executor/single-source-executor.d.ts +0 -155
  915. package/dist/warehouse/executor/single-source-executor.js +0 -573
  916. package/dist/warehouse/executor/single-source-executor.js.map +0 -1
  917. package/dist/warehouse/index.d.ts +0 -79
  918. package/dist/warehouse/index.js +0 -111
  919. package/dist/warehouse/index.js.map +0 -1
  920. package/dist/warehouse/parser/index.d.ts +0 -4
  921. package/dist/warehouse/parser/index.js +0 -10
  922. package/dist/warehouse/parser/index.js.map +0 -1
  923. package/dist/warehouse/parser/query-parser.d.ts +0 -181
  924. package/dist/warehouse/parser/query-parser.js +0 -415
  925. package/dist/warehouse/parser/query-parser.js.map +0 -1
  926. package/dist/warehouse/registry/data-source-registry.d.ts +0 -207
  927. package/dist/warehouse/registry/data-source-registry.js +0 -396
  928. package/dist/warehouse/registry/data-source-registry.js.map +0 -1
  929. package/dist/warehouse/registry/index.d.ts +0 -4
  930. package/dist/warehouse/registry/index.js +0 -9
  931. package/dist/warehouse/registry/index.js.map +0 -1
  932. package/dist/warehouse/transactions/index.d.ts +0 -4
  933. package/dist/warehouse/transactions/index.js +0 -9
  934. package/dist/warehouse/transactions/index.js.map +0 -1
  935. package/dist/warehouse/transactions/saga-orchestrator.d.ts +0 -92
  936. package/dist/warehouse/transactions/saga-orchestrator.js +0 -383
  937. package/dist/warehouse/transactions/saga-orchestrator.js.map +0 -1
  938. package/dist/warehouse/types/index.d.ts +0 -9
  939. package/dist/warehouse/types/index.js +0 -33
  940. package/dist/warehouse/types/index.js.map +0 -1
  941. package/dist/warehouse/types/join.interface.d.ts +0 -225
  942. package/dist/warehouse/types/join.interface.js +0 -87
  943. package/dist/warehouse/types/join.interface.js.map +0 -1
  944. package/dist/warehouse/types/query.interface.d.ts +0 -232
  945. package/dist/warehouse/types/query.interface.js +0 -9
  946. package/dist/warehouse/types/query.interface.js.map +0 -1
  947. package/dist/warehouse/types/transaction.interface.d.ts +0 -236
  948. package/dist/warehouse/types/transaction.interface.js +0 -74
  949. package/dist/warehouse/types/transaction.interface.js.map +0 -1
  950. package/dist/warehouse/types/where.interface.d.ts +0 -208
  951. package/dist/warehouse/types/where.interface.js +0 -89
  952. package/dist/warehouse/types/where.interface.js.map +0 -1
  953. package/dist/warehouse/warehouse.service.d.ts +0 -200
  954. package/dist/warehouse/warehouse.service.js +0 -470
  955. package/dist/warehouse/warehouse.service.js.map +0 -1
  956. package/dist/workflows/index.d.ts +0 -30
  957. package/dist/workflows/index.js +0 -64
  958. package/dist/workflows/index.js.map +0 -1
  959. package/dist/workflows/types/index.d.ts +0 -6
  960. package/dist/workflows/types/index.js +0 -23
  961. package/dist/workflows/types/index.js.map +0 -1
  962. package/dist/workflows/types/workflows.types.d.ts +0 -1095
  963. package/dist/workflows/types/workflows.types.js +0 -13
  964. package/dist/workflows/types/workflows.types.js.map +0 -1
  965. package/dist/workflows/workflow-builder.d.ts +0 -70
  966. package/dist/workflows/workflow-builder.js +0 -353
  967. package/dist/workflows/workflow-builder.js.map +0 -1
  968. package/dist/workflows/workflow-executor.d.ts +0 -289
  969. package/dist/workflows/workflow-executor.js +0 -2467
  970. package/dist/workflows/workflow-executor.js.map +0 -1
  971. package/dist/workflows/workflows.service.d.ts +0 -412
  972. package/dist/workflows/workflows.service.js +0 -2233
  973. package/dist/workflows/workflows.service.js.map +0 -1
@@ -1,3294 +0,0 @@
1
- "use strict";
2
- /**
3
- * DatabaseService - Main ORM Service Class
4
- *
5
- * This is the primary entry point for all database operations in the Ductape SDK.
6
- * It provides a unified interface for querying, writing, transactions, schema management,
7
- * migrations, and database actions across multiple database types.
8
- *
9
- * Supported databases: PostgreSQL, MySQL, MongoDB, DynamoDB, MariaDB, Cassandra
10
- */
11
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- var desc = Object.getOwnPropertyDescriptor(m, k);
14
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
15
- desc = { enumerable: true, get: function() { return m[k]; } };
16
- }
17
- Object.defineProperty(o, k2, desc);
18
- }) : (function(o, m, k, k2) {
19
- if (k2 === undefined) k2 = k;
20
- o[k2] = m[k];
21
- }));
22
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
23
- Object.defineProperty(o, "default", { enumerable: true, value: v });
24
- }) : function(o, v) {
25
- o["default"] = v;
26
- });
27
- var __importStar = (this && this.__importStar) || (function () {
28
- var ownKeys = function(o) {
29
- ownKeys = Object.getOwnPropertyNames || function (o) {
30
- var ar = [];
31
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
32
- return ar;
33
- };
34
- return ownKeys(o);
35
- };
36
- return function (mod) {
37
- if (mod && mod.__esModule) return mod;
38
- var result = {};
39
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
40
- __setModuleDefault(result, mod);
41
- return result;
42
- };
43
- })();
44
- var __importDefault = (this && this.__importDefault) || function (mod) {
45
- return (mod && mod.__esModule) ? mod : { "default": mod };
46
- };
47
- Object.defineProperty(exports, "__esModule", { value: true });
48
- exports.databaseService = exports.DatabaseConnection = exports.DatabaseService = void 0;
49
- const enums_1 = require("./types/enums");
50
- const presave_processor_1 = require("./presave/presave-processor");
51
- const adapter_factory_1 = require("./adapters/adapter.factory");
52
- const query_builder_1 = require("./operators/query-builder");
53
- const aggregation_builder_1 = require("./operators/aggregation-builder");
54
- const transaction_manager_1 = require("./transactions/transaction-manager");
55
- const schema_manager_1 = require("./schema/schema-manager");
56
- const migration_engine_1 = require("./migrations/migration-engine");
57
- const action_manager_1 = require("./actions/action-manager");
58
- const trigger_processor_1 = require("./triggers/trigger-processor");
59
- const trigger_interface_1 = require("./types/trigger.interface");
60
- const database_error_1 = require("./utils/database-error");
61
- const products_service_1 = __importDefault(require("../products/services/products.service"));
62
- const types_1 = require("../types");
63
- const cache_manager_1 = require("../cache/cache.manager");
64
- const processor_service_1 = __importDefault(require("../processor/services/processor.service"));
65
- const crypto_1 = require("crypto");
66
- const logs_service_1 = __importDefault(require("../logs/logs.service"));
67
- const logs_types_1 = require("../logs/logs.types");
68
- const processor_utils_1 = require("../processor/utils/processor.utils");
69
- const secrets_1 = require("../secrets");
70
- /** Module-level: last time we logged connect initiated/success/failed per key, to avoid duplicate logs across multiple DatabaseService instances */
71
- const lastConnectLogAt = new Map();
72
- const CONNECT_LOG_DEBOUNCE_MS = 15000;
73
- function getConnectLogKey(product, database, env) {
74
- return `${product !== null && product !== void 0 ? product : ''}:${database}:${env}`;
75
- }
76
- const sharedConnectionRegistry = new Map();
77
- const sharedConnectInFlight = new Map();
78
- function getSharedConnectionKey(workspaceId, product, database, env) {
79
- return `${workspaceId}:${product}:${database}:${env}`;
80
- }
81
- /**
82
- * Main Database Service class
83
- * Provides unified ORM interface for all supported databases
84
- */
85
- class DatabaseService {
86
- /**
87
- * Create a new DatabaseService instance
88
- * @param config - Optional configuration for authentication and workspace context
89
- */
90
- constructor(config) {
91
- this.adapters = new Map();
92
- this.connectionContexts = new Map();
93
- this.currentContext = null;
94
- this.schemaManagers = new Map();
95
- this.migrationEngines = new Map();
96
- /** Service configuration */
97
- this.config = null;
98
- /** ProductBuilder instances cache (keyed by product tag) */
99
- this.productBuilders = new Map();
100
- /** LogService instance for logging operations */
101
- this.logService = null;
102
- /** Current product ID for logging */
103
- this.productId = '';
104
- /** CacheManager for two-tier caching (Redis + remote) */
105
- this.cacheManager = null;
106
- /** Private keys cache for products (keyed by product tag) */
107
- this.privateKeys = new Map();
108
- /** Local cache for cache configurations to avoid repeated API calls (5 minute TTL) */
109
- this.cacheConfigCache = new Map();
110
- /** In-flight connect() promises per contextKey to deduplicate concurrent connects and avoid duplicate logs */
111
- this.connectPromises = new Map();
112
- this.config = config || null;
113
- this.adapterFactory = new adapter_factory_1.AdapterFactory();
114
- this.transactionManager = new transaction_manager_1.TransactionManager();
115
- this.actionManager = new action_manager_1.ActionManager(this);
116
- this._privateKey = (config === null || config === void 0 ? void 0 : config.private_key) || '';
117
- // Initialize CacheManager (Redis is optional - Tier 1 internal cache and Tier 3 remote cache always work)
118
- if ((config === null || config === void 0 ? void 0 : config.workspace_id) && (config === null || config === void 0 ? void 0 : config.public_key) && (config === null || config === void 0 ? void 0 : config.user_id) && (config === null || config === void 0 ? void 0 : config.token)) {
119
- this.cacheManager = new cache_manager_1.CacheManager({
120
- workspace_id: config.workspace_id,
121
- public_key: config.public_key,
122
- user_id: config.user_id,
123
- token: config.token,
124
- env_type: config.env_type,
125
- redis_client: config.redis_client, // Optional - Tier 2 cache
126
- });
127
- }
128
- }
129
- /**
130
- * Get or create a SchemaManager for the given adapter key or current context
131
- */
132
- getSchemaManager(adapterKey) {
133
- // If no key provided, use current context
134
- if (!adapterKey) {
135
- if (!this.currentContext) {
136
- throw new database_error_1.DatabaseError('No active database connection. Please connect first.', enums_1.DatabaseErrorType.CONNECTION_ERROR);
137
- }
138
- adapterKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
139
- }
140
- let manager = this.schemaManagers.get(adapterKey);
141
- if (!manager) {
142
- const adapter = this.adapters.get(adapterKey);
143
- if (!adapter) {
144
- throw new database_error_1.DatabaseError(`No adapter found for key: ${adapterKey}`, enums_1.DatabaseErrorType.NOT_FOUND);
145
- }
146
- manager = new schema_manager_1.SchemaManager(adapter);
147
- this.schemaManagers.set(adapterKey, manager);
148
- }
149
- return manager;
150
- }
151
- /**
152
- * Get or create a MigrationEngine for the given adapter key or current context
153
- */
154
- getMigrationEngine(adapterKey) {
155
- // If no key provided, use current context
156
- if (!adapterKey) {
157
- if (!this.currentContext) {
158
- throw new database_error_1.DatabaseError('No active database connection. Please connect first.', enums_1.DatabaseErrorType.CONNECTION_ERROR);
159
- }
160
- adapterKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
161
- }
162
- let engine = this.migrationEngines.get(adapterKey);
163
- if (!engine) {
164
- const adapter = this.adapters.get(adapterKey);
165
- if (!adapter) {
166
- throw new database_error_1.DatabaseError(`No adapter found for key: ${adapterKey}`, enums_1.DatabaseErrorType.NOT_FOUND);
167
- }
168
- engine = new migration_engine_1.MigrationEngine(adapter);
169
- this.migrationEngines.set(adapterKey, engine);
170
- }
171
- return engine;
172
- }
173
- // ==================== PRODUCT BUILDER MANAGEMENT ====================
174
- /**
175
- * Create a new ProductBuilder instance
176
- */
177
- createNewProductBuilder() {
178
- if (!this.config) {
179
- throw new database_error_1.DatabaseError('DatabaseService not configured. Please provide config when initializing.', enums_1.DatabaseErrorType.CONFIGURATION_ERROR);
180
- }
181
- return new products_service_1.default({
182
- workspace_id: this.config.workspace_id,
183
- public_key: this.config.public_key,
184
- user_id: this.config.user_id,
185
- token: this.config.token,
186
- env_type: this.config.env_type,
187
- access_key: this.config.access_key,
188
- });
189
- }
190
- /**
191
- * Get or create a ProductBuilder instance for the given product tag
192
- */
193
- async getProductBuilder(productTag) {
194
- let builder = this.productBuilders.get(productTag);
195
- if (!builder) {
196
- builder = this.createNewProductBuilder();
197
- await builder.initializeProductByTag(productTag);
198
- this.productBuilders.set(productTag, builder);
199
- // Update productId for logging
200
- this.productId = builder.fetchProductId() || '';
201
- // Cache private key for caching operations
202
- const privateKey = builder.fetchPrivateKey();
203
- if (privateKey) {
204
- this.privateKeys.set(productTag, privateKey);
205
- }
206
- }
207
- return builder;
208
- }
209
- /**
210
- * Initialize logging service
211
- */
212
- initializeLogService() {
213
- var _a;
214
- if (!this.logService && this.config) {
215
- this.logService = new logs_service_1.default({
216
- product_id: this.productId,
217
- workspace_id: this.config.workspace_id,
218
- public_key: this.config.public_key,
219
- user_id: this.config.user_id,
220
- token: this.config.token,
221
- env_type: this.config.env_type,
222
- workspace_private_key: (_a = this._privateKey) !== null && _a !== void 0 ? _a : undefined,
223
- });
224
- }
225
- }
226
- /**
227
- * Create a new ProcessorService instance for job scheduling
228
- */
229
- createNewProcessor() {
230
- if (!this.config) {
231
- throw new database_error_1.DatabaseError('DatabaseService not configured. Please provide config when initializing.', enums_1.DatabaseErrorType.CONFIGURATION_ERROR);
232
- }
233
- return new processor_service_1.default({
234
- workspace_id: this.config.workspace_id,
235
- public_key: this.config.public_key,
236
- user_id: this.config.user_id,
237
- token: this.config.token,
238
- env_type: this.config.env_type,
239
- private_key: this._privateKey,
240
- });
241
- }
242
- // ==================== DATABASE CRUD OPERATIONS ====================
243
- /**
244
- * Register a new database configuration for a product
245
- * @param productTag - The product tag
246
- * @param data - The database configuration data
247
- */
248
- async registerDatabase(productTag, data) {
249
- const builder = await this.getProductBuilder(productTag);
250
- return builder.createDatabase(data);
251
- }
252
- /**
253
- * Fetch all databases for a product
254
- * @param productTag - The product tag
255
- * @returns Array of database configurations
256
- */
257
- async fetchAllDatabases(productTag) {
258
- const builder = await this.getProductBuilder(productTag);
259
- return builder.fetchDatabases();
260
- }
261
- /**
262
- * Fetch a specific database by tag
263
- * @param productTag - The product tag
264
- * @param databaseTag - The database tag
265
- * @returns The database configuration or null if not found
266
- */
267
- async fetchDatabase(productTag, databaseTag) {
268
- const builder = await this.getProductBuilder(productTag);
269
- return builder.fetchDatabase(databaseTag);
270
- }
271
- /**
272
- * Update a database configuration
273
- * @param productTag - The product tag
274
- * @param databaseTag - The database tag
275
- * @param data - The data to update
276
- */
277
- async updateDatabase(productTag, databaseTag, data) {
278
- const builder = await this.getProductBuilder(productTag);
279
- // Process connection URLs in envs if provided
280
- if (data.envs && data.envs.length > 0) {
281
- const secretsService = (0, secrets_1.getSecretsService)();
282
- const processedEnvs = [];
283
- for (const env of data.envs) {
284
- let connectionUrl = env.connection_url;
285
- const secretCheck = (0, secrets_1.isSecretReference)(connectionUrl);
286
- // If not already a secret reference and we have a secrets service, store it as a secret
287
- if (!secretCheck.isSecret && secretsService) {
288
- const secretKey = this.generateDbSecretKey(productTag, databaseTag, env.slug);
289
- try {
290
- const exists = await secretsService.exists(secretKey);
291
- if (exists) {
292
- await secretsService.update(secretKey, { value: connectionUrl });
293
- console.log(`[Secrets] Updated existing secret '${secretKey}' for database '${databaseTag}' in environment '${env.slug}'`);
294
- }
295
- else {
296
- await secretsService.create({
297
- key: secretKey,
298
- value: connectionUrl,
299
- description: `Database connection URL for ${databaseTag} in ${env.slug}`,
300
- scope: [productTag, databaseTag],
301
- envs: [env.slug],
302
- });
303
- console.log(`[Secrets] Created new secret '${secretKey}' for database '${databaseTag}' in environment '${env.slug}'`);
304
- }
305
- // Update the connection URL to use the secret reference
306
- connectionUrl = `$Secret{${secretKey}}`;
307
- console.log(`[Secrets] Connection URL converted to secret reference: $Secret{${secretKey}}`);
308
- }
309
- catch (error) {
310
- console.warn(`[Secrets] Failed to store database connection URL as secret: ${error}`);
311
- // Continue with the original connection URL
312
- }
313
- }
314
- processedEnvs.push(Object.assign(Object.assign({}, env), { connection_url: connectionUrl }));
315
- }
316
- data = Object.assign(Object.assign({}, data), { envs: processedEnvs });
317
- }
318
- return builder.updateDatabase(databaseTag, data);
319
- }
320
- // ==================== DATABASE TRIGGER OPERATIONS ====================
321
- /**
322
- * Create a database trigger
323
- * @param productTag - The product tag
324
- * @param data - The trigger configuration
325
- */
326
- async createTrigger(productTag, data) {
327
- const builder = await this.getProductBuilder(productTag);
328
- return builder.createDatabaseTrigger(data);
329
- }
330
- /**
331
- * Update a database trigger
332
- * @param productTag - The product tag
333
- * @param data - The trigger configuration
334
- */
335
- async updateTrigger(productTag, data) {
336
- const builder = await this.getProductBuilder(productTag);
337
- return builder.updateDatabaseTrigger(data);
338
- }
339
- /**
340
- * Fetch a database trigger
341
- * @param productTag - The product tag
342
- * @param tag - The trigger tag (format: database_tag:trigger_tag)
343
- */
344
- async fetchTrigger(productTag, tag) {
345
- const builder = await this.getProductBuilder(productTag);
346
- return builder.fetchDatabaseTrigger(tag);
347
- }
348
- /**
349
- * Fetch all triggers for a database
350
- * @param productTag - The product tag
351
- * @param databaseTag - The database tag
352
- */
353
- async fetchTriggers(productTag, databaseTag) {
354
- const builder = await this.getProductBuilder(productTag);
355
- return builder.fetchDatabaseTriggers(databaseTag);
356
- }
357
- /**
358
- * Delete a database trigger
359
- * @param productTag - The product tag
360
- * @param tag - The trigger tag (format: database_tag:trigger_tag)
361
- */
362
- async deleteTrigger(productTag, tag) {
363
- const builder = await this.getProductBuilder(productTag);
364
- return builder.deleteDatabaseTrigger(tag);
365
- }
366
- /**
367
- * Get the current service configuration
368
- */
369
- getConfig() {
370
- return this.config;
371
- }
372
- /**
373
- * Validate cache tag exists in product and return cache configuration
374
- * Uses local in-memory cache to avoid repeated API calls (5 minute TTL)
375
- */
376
- async validateCache(productTag, cacheTag) {
377
- const cacheKey = `${productTag}:${cacheTag}`;
378
- const cached = this.cacheConfigCache.get(cacheKey);
379
- const now = Date.now();
380
- const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
381
- // Return cached config if still valid
382
- if (cached && (now - cached.fetchedAt) < CACHE_TTL) {
383
- return { expiry: cached.expiry };
384
- }
385
- // Fetch from API and cache the result
386
- const builder = await this.getProductBuilder(productTag);
387
- const cache = await builder.fetchCache(cacheTag);
388
- if (!cache) {
389
- throw new database_error_1.DatabaseError(`Cache configuration '${cacheTag}' does not exist`, enums_1.DatabaseErrorType.NOT_FOUND);
390
- }
391
- this.cacheConfigCache.set(cacheKey, { expiry: cache.expiry, fetchedAt: now });
392
- return { expiry: cache.expiry };
393
- }
394
- /**
395
- * Update the service configuration (used after auth is complete)
396
- */
397
- updateConfig(config) {
398
- if (this.config) {
399
- this.config = Object.assign(Object.assign({}, this.config), config);
400
- }
401
- else {
402
- this.config = config;
403
- }
404
- }
405
- /**
406
- * Get workspace ID from config
407
- */
408
- getWorkspaceId() {
409
- var _a;
410
- return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || null;
411
- }
412
- /**
413
- * Get user ID from config
414
- */
415
- getUserId() {
416
- var _a;
417
- return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.user_id) || null;
418
- }
419
- /**
420
- * Get authentication token from config
421
- */
422
- getToken() {
423
- var _a;
424
- return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.token) || null;
425
- }
426
- /**
427
- * Get environment type from config
428
- */
429
- getEnvType() {
430
- var _a;
431
- return ((_a = this.config) === null || _a === void 0 ? void 0 : _a.env_type) || null;
432
- }
433
- // ==================== CONNECTION MANAGEMENT ====================
434
- /**
435
- * Create/register a new database configuration
436
- *
437
- * @example
438
- * // Persist to product
439
- * await ductape.database.create({
440
- * product: 'my-product',
441
- * name: 'User Database',
442
- * tag: 'users-db',
443
- * type: 'postgresql',
444
- * description: 'Stores user accounts and profiles',
445
- * envs: [
446
- * { slug: 'dev', connection_url: 'postgresql://localhost:5432/myapp_dev' },
447
- * { slug: 'prd', connection_url: 'postgresql://prod-host:5432/myapp_prod' },
448
- * ],
449
- * });
450
- *
451
- * // Local only (not persisted)
452
- * await ductape.database.create({
453
- * name: 'Temp Database',
454
- * tag: 'temp-db',
455
- * type: 'postgresql',
456
- * envs: [{ slug: 'dev', connection_url: 'postgresql://localhost:5432/temp' }],
457
- * });
458
- */
459
- async create(config) {
460
- var _a;
461
- // Validate required fields
462
- if (!config.name || !config.tag || !config.type || !((_a = config.envs) === null || _a === void 0 ? void 0 : _a.length)) {
463
- throw new database_error_1.DatabaseError('Missing required fields: name, tag, type, and envs are required', enums_1.DatabaseErrorType.VALIDATION_ERROR);
464
- }
465
- const exists = await this.fetchDatabase(config.product, config.tag);
466
- if (exists) {
467
- return;
468
- }
469
- // Validate database type
470
- if (!Object.values(enums_1.DatabaseType).includes(config.type)) {
471
- throw new database_error_1.DatabaseError(`Unsupported database type: ${config.type}. Supported types: ${Object.values(enums_1.DatabaseType).join(', ')}`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
472
- }
473
- // Process connection URLs - store as secrets if not already secret references
474
- const secretsService = (0, secrets_1.getSecretsService)();
475
- const processedEnvs = [];
476
- for (const env of config.envs) {
477
- let connectionUrl = env.connection_url;
478
- const secretCheck = (0, secrets_1.isSecretReference)(connectionUrl);
479
- // If not already a secret reference and we have a secrets service, store it as a secret
480
- if (!secretCheck.isSecret && secretsService && config.product) {
481
- const secretKey = this.generateDbSecretKey(config.product, config.tag, env.slug);
482
- try {
483
- const exists = await secretsService.exists(secretKey);
484
- if (exists) {
485
- await secretsService.update(secretKey, { value: connectionUrl });
486
- }
487
- else {
488
- await secretsService.create({
489
- key: secretKey,
490
- value: connectionUrl,
491
- description: `Database connection URL for ${config.tag} in ${env.slug}`,
492
- scope: [config.product, config.tag],
493
- envs: [env.slug],
494
- });
495
- }
496
- // Update the connection URL to use the secret reference
497
- connectionUrl = `$Secret{${secretKey}}`;
498
- }
499
- catch (error) {
500
- // Continue with the original connection URL on failure
501
- }
502
- }
503
- processedEnvs.push(Object.assign(Object.assign({}, env), { connection_url: connectionUrl }));
504
- }
505
- // Persist to ProductBuilder if product is specified
506
- if (config.product) {
507
- const productBuilder = await this.getProductBuilder(config.product);
508
- await productBuilder.createDatabase({
509
- name: config.name,
510
- tag: config.tag,
511
- type: config.type, // DatabaseType maps to DatabaseTypes enum
512
- description: config.description,
513
- envs: processedEnvs.map(env => ({
514
- slug: env.slug,
515
- connection_url: env.connection_url,
516
- description: env.description,
517
- })),
518
- });
519
- }
520
- // Create local adapters and connection contexts
521
- this.createAdapter({
522
- tag: config.tag,
523
- name: config.name,
524
- type: config.type,
525
- description: config.description,
526
- envs: processedEnvs,
527
- });
528
- }
529
- /**
530
- * Create local adapter and connection context for a database configuration.
531
- * This is a lightweight operation that only sets up local state without API calls.
532
- * Use this when the database config is already fetched/decrypted from the API.
533
- *
534
- * @param config - The database configuration (already decrypted if from API)
535
- */
536
- createAdapter(config) {
537
- var _a;
538
- // Validate required fields
539
- if (!config.tag || !config.type || !((_a = config.envs) === null || _a === void 0 ? void 0 : _a.length)) {
540
- throw new database_error_1.DatabaseError('Database configuration requires tag, type, and at least one environment', enums_1.DatabaseErrorType.VALIDATION_ERROR);
541
- }
542
- const databaseType = typeof config.type === 'string'
543
- ? this.convertDatabaseType(config.type)
544
- : config.type;
545
- // Validate database type
546
- if (!Object.values(enums_1.DatabaseType).includes(databaseType)) {
547
- throw new database_error_1.DatabaseError(`Unsupported database type: ${config.type}. Supported types: ${Object.values(enums_1.DatabaseType).join(', ')}`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
548
- }
549
- // Create adapters and contexts for each environment
550
- for (const envConfig of config.envs) {
551
- const contextKey = this.buildContextKey(config.tag, envConfig.slug);
552
- // Skip if already exists
553
- if (this.adapters.has(contextKey) && this.connectionContexts.has(contextKey)) {
554
- continue;
555
- }
556
- const adapter = this.adapterFactory.create(databaseType);
557
- this.adapters.set(contextKey, adapter);
558
- this.connectionContexts.set(contextKey, {
559
- database: config.tag,
560
- env: envConfig.slug,
561
- type: databaseType,
562
- connectionUrl: envConfig.connection_url,
563
- connected: false,
564
- name: config.name,
565
- description: config.description,
566
- });
567
- }
568
- }
569
- /**
570
- * Generate a secret key for database connection URLs
571
- * Format: DB_{PRODUCT}_{ASSET_TAG}_{ENV}_{KEY}
572
- *
573
- * Where:
574
- * - PRODUCT = productTag.split('.')[1] (second part after workspace)
575
- * - ASSET_TAG = if dbTag starts with same workspace prefix, use second part; otherwise sanitize full tag
576
- * - All parts are automatically capitalized
577
- */
578
- generateDbSecretKey(product, dbTag, env) {
579
- const sanitize = (str) => str.toUpperCase().replace(/[^A-Z0-9]/g, '_');
580
- // Support both ':' and '.' delimiters for product tags (e.g., 'ductape:rematch' or 'ductape.rematch')
581
- const productParts = product.includes(':') ? product.split(':') : product.split('.');
582
- const productKey = productParts[1] || productParts[0]; // Use product name (index 1), fallback to index 0
583
- const workspace = productParts[0];
584
- // Support both ':' and '.' delimiters for database tags
585
- const dbParts = dbTag.includes(':') ? dbTag.split(':') : dbTag.split('.');
586
- let assetTag;
587
- if (dbParts.length > 1 && dbParts[0] === workspace) {
588
- // Same workspace prefix, use second part
589
- assetTag = dbParts[1];
590
- }
591
- else {
592
- // Different or no prefix, use full tag
593
- assetTag = dbTag;
594
- }
595
- return `DB_${sanitize(productKey)}_${sanitize(assetTag)}_${sanitize(env)}_URL`;
596
- }
597
- /**
598
- * Connect to a database
599
- *
600
- * @example
601
- * const result = await ductape.database.connect({
602
- * env: 'dev',
603
- * product: 'my-app',
604
- * database: 'users-db',
605
- * });
606
- * console.log('Connected:', result.connected);
607
- * console.log('Database Version:', result.version);
608
- * console.log('Latency:', result.latency, 'ms');
609
- *
610
- * // With the returned connection object, you can use scoped operations:
611
- * const db = await ductape.databases.connect({ env: 'dev', product: 'my-app', database: 'users-db' });
612
- * await db.triggers.create({ tag: 'my-trigger', ... });
613
- */
614
- async connect(config) {
615
- var _a, _b, _c;
616
- const process_id = (0, processor_utils_1.generateObjectId)();
617
- const start = Date.now();
618
- const contextKey = this.buildContextKey(config.database, config.env);
619
- const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
620
- const product = (_c = config.product) !== null && _c !== void 0 ? _c : '';
621
- // Use shared registry only when we have an authenticated scope (workspace + product).
622
- // Connections are never shared across workspaces or products.
623
- const useShared = workspaceId !== '' && product !== '';
624
- if (useShared) {
625
- const sharedKey = getSharedConnectionKey(workspaceId, product, config.database, config.env);
626
- const existing = sharedConnectionRegistry.get(sharedKey);
627
- if (existing === null || existing === void 0 ? void 0 : existing.context.connected) {
628
- this.adapters.set(contextKey, existing.adapter);
629
- this.connectionContexts.set(contextKey, existing.context);
630
- return new DatabaseConnection(this, config.database, config.env, config.product || '');
631
- }
632
- const inFlight = sharedConnectInFlight.get(sharedKey);
633
- if (inFlight) {
634
- const entry = await inFlight;
635
- this.adapters.set(contextKey, entry.adapter);
636
- this.connectionContexts.set(contextKey, entry.context);
637
- return new DatabaseConnection(this, config.database, config.env, config.product || '');
638
- }
639
- const createPromise = this.connectAndRegisterShared(sharedKey, config, contextKey, process_id, start);
640
- sharedConnectInFlight.set(sharedKey, createPromise);
641
- try {
642
- const entry = await createPromise;
643
- this.adapters.set(contextKey, entry.adapter);
644
- this.connectionContexts.set(contextKey, entry.context);
645
- return new DatabaseConnection(this, config.database, config.env, config.product || '');
646
- }
647
- finally {
648
- sharedConnectInFlight.delete(sharedKey);
649
- }
650
- }
651
- // Per-instance path when shared registry is not used (no workspace/product scope)
652
- let adapter = this.adapters.get(contextKey);
653
- let context = this.connectionContexts.get(contextKey);
654
- if (!adapter || !context) {
655
- if (!config.product) {
656
- throw new database_error_1.DatabaseError(`Database '${config.database}' not found locally. Please provide 'product' to fetch from remote.`, enums_1.DatabaseErrorType.NOT_FOUND);
657
- }
658
- await this.getProductBuilder(config.product);
659
- const dbConfig = await this.fetchDatabase(config.product, config.database);
660
- if (!dbConfig) {
661
- throw new database_error_1.DatabaseError(`Database '${config.database}' not found for product '${config.product}'.`, enums_1.DatabaseErrorType.NOT_FOUND);
662
- }
663
- this.createAdapter({
664
- tag: config.database,
665
- name: dbConfig.name,
666
- type: dbConfig.type,
667
- description: dbConfig.description,
668
- envs: dbConfig.envs.map(e => ({
669
- slug: e.slug,
670
- connection_url: e.connection_url,
671
- description: e.description,
672
- })),
673
- });
674
- adapter = this.adapters.get(contextKey);
675
- context = this.connectionContexts.get(contextKey);
676
- }
677
- if (!adapter || !context) {
678
- throw new database_error_1.DatabaseError(`Failed to initialize adapter for ${contextKey}`, enums_1.DatabaseErrorType.CONNECTION_ERROR);
679
- }
680
- if (context.connected) {
681
- return new DatabaseConnection(this, config.database, config.env, config.product || '');
682
- }
683
- const inFlight = this.connectPromises.get(contextKey);
684
- if (inFlight) {
685
- return inFlight;
686
- }
687
- const connectPromise = this.runConnect(config, contextKey, adapter, context, process_id, start);
688
- this.connectPromises.set(contextKey, connectPromise);
689
- try {
690
- return await connectPromise;
691
- }
692
- finally {
693
- this.connectPromises.delete(contextKey);
694
- }
695
- }
696
- /**
697
- * Disconnect any existing connection to this resource from the SDK (shared registry and this instance) before creating a fresh one.
698
- */
699
- async disconnectExistingForResource(sharedKey, contextKey, workspaceId, product, database, env) {
700
- const existingInRegistry = sharedConnectionRegistry.get(sharedKey);
701
- if (existingInRegistry) {
702
- try {
703
- await existingInRegistry.adapter.disconnect();
704
- existingInRegistry.context.connected = false;
705
- }
706
- catch (_a) {
707
- // Non-fatal
708
- }
709
- sharedConnectionRegistry.delete(sharedKey);
710
- }
711
- const context = this.connectionContexts.get(contextKey);
712
- if (context === null || context === void 0 ? void 0 : context.connected) {
713
- const adapter = this.adapters.get(contextKey);
714
- if (adapter) {
715
- try {
716
- await adapter.disconnect();
717
- }
718
- catch (_b) {
719
- // Non-fatal
720
- }
721
- context.connected = false;
722
- if (workspaceId && product) {
723
- sharedConnectionRegistry.delete(getSharedConnectionKey(workspaceId, product, database, env));
724
- }
725
- }
726
- }
727
- }
728
- /**
729
- * Get or create adapter/context, connect, and register in shared registry.
730
- * Only used when connect() is scoped with workspace_id and product (no cross-tenant sharing).
731
- */
732
- async connectAndRegisterShared(sharedKey, config, contextKey, process_id, start) {
733
- var _a, _b, _c;
734
- const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
735
- const product = (_c = config.product) !== null && _c !== void 0 ? _c : '';
736
- await this.disconnectExistingForResource(sharedKey, contextKey, workspaceId, product, config.database, config.env);
737
- let adapter = this.adapters.get(contextKey);
738
- let context = this.connectionContexts.get(contextKey);
739
- if (!adapter || !context) {
740
- if (!config.product) {
741
- throw new database_error_1.DatabaseError(`Database '${config.database}' not found locally. Please provide 'product' to fetch from remote.`, enums_1.DatabaseErrorType.NOT_FOUND);
742
- }
743
- await this.getProductBuilder(config.product);
744
- const dbConfig = await this.fetchDatabase(config.product, config.database);
745
- if (!dbConfig) {
746
- throw new database_error_1.DatabaseError(`Database '${config.database}' not found for product '${config.product}'.`, enums_1.DatabaseErrorType.NOT_FOUND);
747
- }
748
- this.createAdapter({
749
- tag: config.database,
750
- name: dbConfig.name,
751
- type: dbConfig.type,
752
- description: dbConfig.description,
753
- envs: dbConfig.envs.map(e => ({
754
- slug: e.slug,
755
- connection_url: e.connection_url,
756
- description: e.description,
757
- })),
758
- });
759
- adapter = this.adapters.get(contextKey);
760
- context = this.connectionContexts.get(contextKey);
761
- }
762
- await this.runConnect(config, contextKey, adapter, context, process_id, start);
763
- const entry = { adapter, context };
764
- const raceExisting = sharedConnectionRegistry.get(sharedKey);
765
- if (raceExisting) {
766
- try {
767
- await raceExisting.adapter.disconnect();
768
- raceExisting.context.connected = false;
769
- }
770
- catch (_d) {
771
- // Non-fatal
772
- }
773
- sharedConnectionRegistry.delete(sharedKey);
774
- }
775
- sharedConnectionRegistry.set(sharedKey, entry);
776
- return entry;
777
- }
778
- /**
779
- * Performs the actual connect (resolve URL, adapter.connect(), log). Called once per contextKey when not already connected.
780
- */
781
- async runConnect(config, contextKey, adapter, context, process_id, start) {
782
- var _a, _b, _c, _d, _e, _f, _g;
783
- this.initializeLogService();
784
- const envValue = config.env || '';
785
- const baseLogs = {
786
- product_tag: config.product || '',
787
- workspace_id: ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || '',
788
- env: envValue,
789
- app_env: envValue,
790
- process_id,
791
- type: logs_types_1.LogEventTypes.DATABASE,
792
- parent_tag: config.database,
793
- child_tag: 'connect',
794
- data: { database: config.database, env: envValue, operation: 'connect' },
795
- };
796
- const logKey = getConnectLogKey(config.product, config.database, config.env);
797
- const now = Date.now();
798
- const last = (_b = lastConnectLogAt.get(logKey)) !== null && _b !== void 0 ? _b : {};
799
- if (this.logService && (!last.initiated || now - last.initiated >= CONNECT_LOG_DEBOUNCE_MS)) {
800
- lastConnectLogAt.set(logKey, Object.assign(Object.assign({}, last), { initiated: now }));
801
- this.logService.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database connect - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
802
- }
803
- try {
804
- // Resolve secret reference in connection URL if needed
805
- let connectionUrl = context.connectionUrl;
806
- const secretCheck = (0, secrets_1.isSecretReference)(connectionUrl);
807
- if (secretCheck.isSecret) {
808
- const secretsService = (0, secrets_1.getSecretsService)();
809
- if (secretsService) {
810
- const resolved = await secretsService.resolve(connectionUrl, { env: config.env });
811
- connectionUrl = resolved.value;
812
- }
813
- else {
814
- throw new database_error_1.DatabaseError(`Connection URL contains secret reference but secrets service is not initialized.`, enums_1.DatabaseErrorType.CONNECTION_ERROR);
815
- }
816
- }
817
- await adapter.connect({
818
- connectionUrl,
819
- });
820
- context.connected = true;
821
- context.product = config.product;
822
- this.currentContext = context;
823
- const end = Date.now();
824
- const lastSuccess = (_c = lastConnectLogAt.get(logKey)) !== null && _c !== void 0 ? _c : {};
825
- if (this.logService && (!lastSuccess.success || end - lastSuccess.success >= CONNECT_LOG_DEBOUNCE_MS)) {
826
- lastConnectLogAt.set(logKey, Object.assign(Object.assign({}, lastSuccess), { success: end }));
827
- this.logService.add(Object.assign(Object.assign({}, baseLogs), { start,
828
- end, message: 'Database connect - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
829
- this.logService.publish();
830
- }
831
- return new DatabaseConnection(this, config.database, config.env, config.product || '');
832
- }
833
- catch (error) {
834
- const end = Date.now();
835
- const lastFail = (_d = lastConnectLogAt.get(logKey)) !== null && _d !== void 0 ? _d : {};
836
- if (this.logService && (!lastFail.failed || end - lastFail.failed >= CONNECT_LOG_DEBOUNCE_MS)) {
837
- lastConnectLogAt.set(logKey, Object.assign(Object.assign({}, lastFail), { failed: end }));
838
- this.logService.add(Object.assign(Object.assign({}, baseLogs), { start,
839
- end, message: 'Database connect - failed', failed_execution: true, data: { database: config.database, env: config.env, error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
840
- await this.logService.publish();
841
- }
842
- const err = error;
843
- const baseMsg = (_e = err === null || err === void 0 ? void 0 : err.message) !== null && _e !== void 0 ? _e : String(error);
844
- let detail = baseMsg;
845
- if (err === null || err === void 0 ? void 0 : err.response) {
846
- const status = (_f = err.response) === null || _f === void 0 ? void 0 : _f.status;
847
- const body = (_g = err.response) === null || _g === void 0 ? void 0 : _g.data;
848
- const bodyStr = typeof body === 'object' ? JSON.stringify(body) : body;
849
- detail = bodyStr ? `${baseMsg} (HTTP ${status}): ${bodyStr}` : `${baseMsg} (HTTP ${status})`;
850
- }
851
- throw new database_error_1.DatabaseError(`Failed to connect to database: ${detail}`, enums_1.DatabaseErrorType.CONNECTION_ERROR, error);
852
- }
853
- }
854
- /**
855
- * Test database connection without establishing persistent connection
856
- *
857
- * @example
858
- * const result = await ductape.database.testConnection({
859
- * env: 'dev',
860
- * product: 'my-app',
861
- * database: 'users-db',
862
- * });
863
- * if (result.connected) {
864
- * console.log('Connection successful!');
865
- * } else {
866
- * console.error('Connection failed:', result.error);
867
- * }
868
- */
869
- async testConnection(config) {
870
- const contextKey = this.buildContextKey(config.database, config.env);
871
- let adapter = this.adapters.get(contextKey);
872
- let context = this.connectionContexts.get(contextKey);
873
- if (!adapter || !context) {
874
- return {
875
- connected: false,
876
- error: `Database '${config.database}' not found for environment '${config.env}'`,
877
- };
878
- }
879
- const startTime = Date.now();
880
- try {
881
- const result = await adapter.testConnection({
882
- connectionUrl: context.connectionUrl,
883
- });
884
- return {
885
- connected: result.connected,
886
- version: result.version,
887
- latency: Date.now() - startTime,
888
- };
889
- }
890
- catch (error) {
891
- return {
892
- connected: false,
893
- error: error.message,
894
- latency: Date.now() - startTime,
895
- };
896
- }
897
- }
898
- /**
899
- * Disconnect from the current database
900
- */
901
- async disconnect() {
902
- var _a, _b, _c;
903
- if (this.currentContext) {
904
- const contextKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
905
- const adapter = this.adapters.get(contextKey);
906
- if (adapter) {
907
- await adapter.disconnect();
908
- this.currentContext.connected = false;
909
- const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
910
- const product = (_c = this.currentContext.product) !== null && _c !== void 0 ? _c : '';
911
- if (workspaceId && product) {
912
- sharedConnectionRegistry.delete(getSharedConnectionKey(workspaceId, product, this.currentContext.database, this.currentContext.env));
913
- }
914
- }
915
- this.currentContext = null;
916
- }
917
- }
918
- /**
919
- * Close all database connections
920
- *
921
- * @example
922
- * await ductape.database.closeAll();
923
- */
924
- async closeAll() {
925
- var _a, _b, _c;
926
- const disconnectPromises = [];
927
- const workspaceId = (_b = (_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) !== null && _b !== void 0 ? _b : '';
928
- for (const [key, adapter] of this.adapters) {
929
- disconnectPromises.push(adapter.disconnect());
930
- const context = this.connectionContexts.get(key);
931
- if (context) {
932
- context.connected = false;
933
- const product = (_c = context.product) !== null && _c !== void 0 ? _c : '';
934
- if (workspaceId && product) {
935
- sharedConnectionRegistry.delete(getSharedConnectionKey(workspaceId, product, context.database, context.env));
936
- }
937
- }
938
- }
939
- await Promise.all(disconnectPromises);
940
- this.currentContext = null;
941
- }
942
- /**
943
- * Fetch all registered databases
944
- *
945
- * @example
946
- * const databases = await ductape.database.fetchAll();
947
- * databases.forEach((db) => {
948
- * console.log(`${db.name} (${db.tag}): ${db.type}`);
949
- * });
950
- */
951
- async fetchAll(product) {
952
- const databases = new Map();
953
- for (const [key, context] of this.connectionContexts) {
954
- if (!databases.has(context.database)) {
955
- databases.set(context.database, {
956
- product,
957
- name: context.name || context.database,
958
- tag: context.database,
959
- type: context.type,
960
- description: context.description,
961
- envs: [],
962
- });
963
- }
964
- databases.get(context.database).envs.push({
965
- slug: context.env,
966
- connection_url: context.connectionUrl,
967
- });
968
- }
969
- return Array.from(databases.values());
970
- }
971
- /**
972
- * Fetch a specific database configuration
973
- *
974
- * @example
975
- * const usersDb = await ductape.database.fetch('users-db');
976
- * console.log('Database:', usersDb.name);
977
- * console.log('Type:', usersDb.type);
978
- * console.log('Environments:', usersDb.envs);
979
- */
980
- async fetch(product, database) {
981
- const databases = await this.fetchAll(product);
982
- return databases.find((db) => db.tag === database) || null;
983
- }
984
- /**
985
- * Update a local database configuration
986
- *
987
- * @example
988
- * await ductape.database.updateLocalConfig('users-db', {
989
- * name: 'User Database v2',
990
- * description: 'Updated user storage',
991
- * envs: [
992
- * { slug: 'dev', connection_url: 'postgresql://new-dev-host:5432/myapp' },
993
- * ],
994
- * });
995
- */
996
- async updateLocalConfig(tag, updates) {
997
- for (const [key, context] of this.connectionContexts) {
998
- if (context.database === tag) {
999
- if (updates.name) {
1000
- context.name = updates.name;
1001
- }
1002
- if (updates.description) {
1003
- context.description = updates.description;
1004
- }
1005
- if (updates.envs) {
1006
- const envUpdate = updates.envs.find((e) => e.slug === context.env);
1007
- if (envUpdate) {
1008
- context.connectionUrl = envUpdate.connection_url;
1009
- }
1010
- }
1011
- }
1012
- }
1013
- }
1014
- // ==================== QUERY OPERATIONS ====================
1015
- /**
1016
- * Query records from a table
1017
- *
1018
- * @example
1019
- * // With established connection
1020
- * const result = await ductape.database.query({
1021
- * table: 'users',
1022
- * where: { status: 'active' },
1023
- * orderBy: { column: 'created_at', order: 'DESC' },
1024
- * limit: 10,
1025
- * });
1026
- *
1027
- * // With explicit connection params
1028
- * const result = await ductape.database.query({
1029
- * env: 'prd',
1030
- * product: 'my-app',
1031
- * database: 'main-db',
1032
- * table: 'users',
1033
- * });
1034
- */
1035
- async query(options) {
1036
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
1037
- const process_id = (0, processor_utils_1.generateObjectId)();
1038
- const start = Date.now();
1039
- this.initializeLogService();
1040
- // Session log fields (will be populated if session is provided)
1041
- let sessionLogFields = {};
1042
- let resolvedOptions = options;
1043
- // Process session if provided
1044
- if (options.session && options.product) {
1045
- const builder = await this.getProductBuilder(options.product);
1046
- const privateKey = builder.fetchPrivateKey();
1047
- if (privateKey) {
1048
- const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1049
- const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1050
- fetchSessionSelector: async (sessionTag) => {
1051
- const sessionConfig = await builder.fetchSession(sessionTag);
1052
- return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1053
- },
1054
- });
1055
- if (sessionResult.error) {
1056
- throw new Error(`Session validation failed: ${sessionResult.error}`);
1057
- }
1058
- resolvedOptions = sessionResult.input;
1059
- sessionLogFields = sessionResult.logFields;
1060
- }
1061
- }
1062
- const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1063
- const baseLogs = Object.assign({ product_tag: options.product || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.product) || '', workspace_id: ((_c = this.config) === null || _c === void 0 ? void 0 : _c.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: options.database || ((_d = this.currentContext) === null || _d === void 0 ? void 0 : _d.database) || '', child_tag: 'query', data: {
1064
- table: options.table,
1065
- operation: 'query',
1066
- database: options.database || ((_e = this.currentContext) === null || _e === void 0 ? void 0 : _e.database) || '',
1067
- env: envValue,
1068
- where: options.where,
1069
- select: options.select,
1070
- orderBy: options.orderBy,
1071
- limit: options.limit,
1072
- offset: options.offset,
1073
- include: options.include,
1074
- } }, sessionLogFields);
1075
- (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database query - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1076
- // Check cache if cache tag is provided
1077
- // Use product from options or from current context (set during connect)
1078
- const productTag = options.product || ((_g = this.currentContext) === null || _g === void 0 ? void 0 : _g.product);
1079
- const privateKey = productTag ? this.privateKeys.get(productTag) : undefined;
1080
- let queryCacheKey;
1081
- try {
1082
- if (options.cache && this.cacheManager && privateKey) {
1083
- const cacheOptions = {
1084
- cache_tag: options.cache,
1085
- product_tag: productTag || '',
1086
- component_tag: options.database || ((_h = this.currentContext) === null || _h === void 0 ? void 0 : _h.database) || '',
1087
- component_type: 'database',
1088
- input: { table: options.table, where: options.where, select: options.select, orderBy: options.orderBy, limit: options.limit, offset: options.offset },
1089
- privateKey,
1090
- };
1091
- const cached = await this.cacheManager.fetch(cacheOptions);
1092
- queryCacheKey = cached.key;
1093
- if (cached.hit && cached.data) {
1094
- const end = Date.now();
1095
- (_j = this.logService) === null || _j === void 0 ? void 0 : _j.add(Object.assign(Object.assign({}, baseLogs), { start,
1096
- end, message: `Database query - cache hit (${cached.source})`, successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: cached.key, cache_status: true }));
1097
- (_k = this.logService) === null || _k === void 0 ? void 0 : _k.publish();
1098
- return cached.data;
1099
- }
1100
- }
1101
- await this.ensureAdapterFor(resolvedOptions);
1102
- const adapter = this.getAdapter(resolvedOptions);
1103
- const queryBuilder = new query_builder_1.QueryBuilder(adapter.getDatabaseType());
1104
- const builtQuery = queryBuilder.buildQuery(resolvedOptions);
1105
- const result = await adapter.query(builtQuery);
1106
- // Store in cache if cache tag is provided
1107
- if (options.cache && this.cacheManager && privateKey && productTag) {
1108
- const cacheConfig = await this.validateCache(productTag, options.cache);
1109
- const cacheOptions = {
1110
- cache_tag: options.cache,
1111
- product_tag: productTag,
1112
- component_tag: options.database || ((_l = this.currentContext) === null || _l === void 0 ? void 0 : _l.database) || '',
1113
- component_type: 'database',
1114
- input: { table: options.table, where: options.where, select: options.select, orderBy: options.orderBy, limit: options.limit, offset: options.offset },
1115
- privateKey,
1116
- expiry: cacheConfig.expiry,
1117
- };
1118
- this.cacheManager.store(cacheOptions, result); // Fire-and-forget
1119
- }
1120
- const end = Date.now();
1121
- (_m = this.logService) === null || _m === void 0 ? void 0 : _m.add(Object.assign(Object.assign({}, baseLogs), { start,
1122
- end, message: options.cache ? 'Database query - cache miss' : 'Database query - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: queryCacheKey }));
1123
- (_o = this.logService) === null || _o === void 0 ? void 0 : _o.publish();
1124
- return result;
1125
- }
1126
- catch (error) {
1127
- const end = Date.now();
1128
- (_p = this.logService) === null || _p === void 0 ? void 0 : _p.add(Object.assign(Object.assign({}, baseLogs), { start,
1129
- end, message: 'Database query - failed', failed_execution: true, data: { table: options.table, operation: 'query', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL, cache_tag: options.cache, cache_key: queryCacheKey }));
1130
- await ((_q = this.logService) === null || _q === void 0 ? void 0 : _q.publish());
1131
- throw error;
1132
- }
1133
- }
1134
- /**
1135
- * Execute a raw query
1136
- *
1137
- * @example
1138
- * // PostgreSQL
1139
- * const result = await ductape.database.raw({
1140
- * query: 'SELECT * FROM users WHERE created_at > $1 AND status = $2',
1141
- * params: [new Date('2024-01-01'), 'active'],
1142
- * });
1143
- *
1144
- * // MySQL
1145
- * const result = await ductape.database.raw({
1146
- * query: 'SELECT * FROM users WHERE created_at > ? AND status = ?',
1147
- * params: [new Date('2024-01-01'), 'active'],
1148
- * });
1149
- *
1150
- * // MongoDB
1151
- * const result = await ductape.database.raw({
1152
- * query: { status: 'active', created_at: { $gte: new Date('2024-01-01') } },
1153
- * collection: 'users',
1154
- * });
1155
- */
1156
- async raw(options) {
1157
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
1158
- const process_id = (0, processor_utils_1.generateObjectId)();
1159
- const start = Date.now();
1160
- this.initializeLogService();
1161
- const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1162
- const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1163
- const baseLogs = {
1164
- product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '',
1165
- workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '',
1166
- env: envValue,
1167
- app_env: envValue,
1168
- process_id,
1169
- type: logs_types_1.LogEventTypes.DATABASE,
1170
- parent_tag: databaseValue,
1171
- child_tag: 'raw',
1172
- data: {
1173
- operation: 'raw',
1174
- database: databaseValue,
1175
- env: envValue,
1176
- collection: options.collection,
1177
- query: options.query,
1178
- params: options.params,
1179
- },
1180
- };
1181
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database raw query - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1182
- // Check cache if cache tag is provided
1183
- const privateKey = options.product ? this.privateKeys.get(options.product) : undefined;
1184
- let rawQueryCacheKey;
1185
- try {
1186
- if (options.cache && this.cacheManager && privateKey) {
1187
- const cacheOptions = {
1188
- cache_tag: options.cache,
1189
- product_tag: options.product || '',
1190
- component_tag: options.database || '',
1191
- component_type: 'database',
1192
- input: { query: options.query, params: options.params, collection: options.collection },
1193
- privateKey,
1194
- };
1195
- const cached = await this.cacheManager.fetch(cacheOptions);
1196
- rawQueryCacheKey = cached.key;
1197
- if (cached.hit && cached.data) {
1198
- const end = Date.now();
1199
- (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1200
- end, message: `Database raw query - cache hit (${cached.source})`, successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: cached.key, cache_status: true }));
1201
- (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1202
- return cached.data;
1203
- }
1204
- }
1205
- await this.ensureAdapterFor(options);
1206
- const adapter = this.getAdapter(options);
1207
- const result = await adapter.raw(options);
1208
- // Store in cache if cache tag is provided
1209
- if (options.cache && this.cacheManager && privateKey && options.product) {
1210
- const cacheConfig = await this.validateCache(options.product, options.cache);
1211
- const cacheOptions = {
1212
- cache_tag: options.cache,
1213
- product_tag: options.product,
1214
- component_tag: options.database || '',
1215
- component_type: 'database',
1216
- input: { query: options.query, params: options.params, collection: options.collection },
1217
- privateKey,
1218
- expiry: cacheConfig.expiry,
1219
- };
1220
- this.cacheManager.store(cacheOptions, result); // Fire-and-forget
1221
- }
1222
- const end = Date.now();
1223
- (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1224
- end, message: options.cache ? 'Database raw query - cache miss' : 'Database raw query - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS, cache_tag: options.cache, cache_key: rawQueryCacheKey }));
1225
- (_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish();
1226
- return result;
1227
- }
1228
- catch (error) {
1229
- const end = Date.now();
1230
- (_k = this.logService) === null || _k === void 0 ? void 0 : _k.add(Object.assign(Object.assign({}, baseLogs), { start,
1231
- end, message: 'Database raw query - failed', failed_execution: true, data: { operation: 'raw', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL, cache_tag: options.cache, cache_key: rawQueryCacheKey }));
1232
- await ((_l = this.logService) === null || _l === void 0 ? void 0 : _l.publish());
1233
- throw error;
1234
- }
1235
- }
1236
- // ==================== WRITE OPERATIONS ====================
1237
- /**
1238
- * Insert one or more records
1239
- *
1240
- * @example
1241
- * // Single record
1242
- * const result = await ductape.database.insert({
1243
- * table: 'users',
1244
- * data: {
1245
- * name: 'Jane Doe',
1246
- * email: 'jane@example.com',
1247
- * status: 'active',
1248
- * },
1249
- * returning: true,
1250
- * });
1251
- *
1252
- * // Multiple records
1253
- * const result = await ductape.database.insert({
1254
- * table: 'users',
1255
- * data: [
1256
- * { name: 'User 1', email: 'user1@example.com' },
1257
- * { name: 'User 2', email: 'user2@example.com' },
1258
- * ],
1259
- * });
1260
- *
1261
- * // With conflict handling (upsert)
1262
- * const result = await ductape.database.insert({
1263
- * table: 'users',
1264
- * data: { email: 'john@example.com', name: 'John' },
1265
- * onConflict: {
1266
- * columns: ['email'],
1267
- * action: 'update',
1268
- * update: ['name'],
1269
- * },
1270
- * });
1271
- */
1272
- async insert(options) {
1273
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1274
- const process_id = (0, processor_utils_1.generateObjectId)();
1275
- const start = Date.now();
1276
- this.initializeLogService();
1277
- // Session log fields (will be populated if session is provided)
1278
- let sessionLogFields = {};
1279
- let resolvedOptions = options;
1280
- // Process session if provided
1281
- if (options.session && options.product) {
1282
- const builder = await this.getProductBuilder(options.product);
1283
- const privateKey = builder.fetchPrivateKey();
1284
- if (privateKey) {
1285
- const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1286
- const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1287
- fetchSessionSelector: async (sessionTag) => {
1288
- const sessionConfig = await builder.fetchSession(sessionTag);
1289
- return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1290
- },
1291
- });
1292
- if (sessionResult.error) {
1293
- throw new Error(`Session validation failed: ${sessionResult.error}`);
1294
- }
1295
- resolvedOptions = sessionResult.input;
1296
- sessionLogFields = sessionResult.logFields;
1297
- }
1298
- }
1299
- const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1300
- const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1301
- const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'insert', data: {
1302
- table: options.table,
1303
- operation: 'insert',
1304
- database: databaseValue,
1305
- env: envValue,
1306
- data: options.data,
1307
- returning: options.returning,
1308
- onConflict: options.onConflict,
1309
- } }, sessionLogFields);
1310
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database insert - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1311
- try {
1312
- // Apply pre-save operations if specified
1313
- let processedData = resolvedOptions.data;
1314
- if (resolvedOptions.preSave && resolvedOptions.preSave.length > 0) {
1315
- const processor = new presave_processor_1.PreSaveProcessor(resolvedOptions.preSaveConfig);
1316
- const preSaveResult = await processor.process(resolvedOptions.data, resolvedOptions.preSave);
1317
- processedData = preSaveResult.data;
1318
- }
1319
- await this.ensureAdapterFor(resolvedOptions);
1320
- const adapter = this.getAdapter(resolvedOptions);
1321
- const result = await adapter.insert(Object.assign(Object.assign({}, resolvedOptions), { data: processedData }));
1322
- const end = Date.now();
1323
- (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1324
- end, message: 'Database insert - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1325
- (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1326
- return result;
1327
- }
1328
- catch (error) {
1329
- const end = Date.now();
1330
- (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1331
- end, message: 'Database insert - failed', failed_execution: true, data: { table: options.table, operation: 'insert', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1332
- await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1333
- throw error;
1334
- }
1335
- }
1336
- /**
1337
- * Update records matching conditions
1338
- *
1339
- * @example
1340
- * // Simple update
1341
- * const result = await ductape.database.update({
1342
- * table: 'users',
1343
- * data: { status: 'inactive' },
1344
- * where: { last_login: { $LT: new Date('2023-01-01') } },
1345
- * });
1346
- *
1347
- * // With increment/decrement
1348
- * await ductape.database.update({
1349
- * table: 'products',
1350
- * data: { stock: { $inc: 10 } },
1351
- * where: { id: productId },
1352
- * });
1353
- */
1354
- async update(options) {
1355
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1356
- const process_id = (0, processor_utils_1.generateObjectId)();
1357
- const start = Date.now();
1358
- this.initializeLogService();
1359
- // Session log fields (will be populated if session is provided)
1360
- let sessionLogFields = {};
1361
- let resolvedOptions = options;
1362
- // Process session if provided
1363
- if (options.session && options.product) {
1364
- const builder = await this.getProductBuilder(options.product);
1365
- const privateKey = builder.fetchPrivateKey();
1366
- if (privateKey) {
1367
- const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1368
- const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1369
- fetchSessionSelector: async (sessionTag) => {
1370
- const sessionConfig = await builder.fetchSession(sessionTag);
1371
- return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1372
- },
1373
- });
1374
- if (sessionResult.error) {
1375
- throw new Error(`Session validation failed: ${sessionResult.error}`);
1376
- }
1377
- resolvedOptions = sessionResult.input;
1378
- sessionLogFields = sessionResult.logFields;
1379
- }
1380
- }
1381
- const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1382
- const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1383
- const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'update', data: {
1384
- table: options.table,
1385
- operation: 'update',
1386
- database: databaseValue,
1387
- env: envValue,
1388
- where: options.where,
1389
- data: options.data,
1390
- returning: options.returning,
1391
- } }, sessionLogFields);
1392
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database update - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1393
- try {
1394
- // Apply pre-save operations if specified
1395
- let processedData = resolvedOptions.data;
1396
- if (resolvedOptions.preSave && resolvedOptions.preSave.length > 0) {
1397
- const processor = new presave_processor_1.PreSaveProcessor(resolvedOptions.preSaveConfig);
1398
- const preSaveResult = await processor.process(resolvedOptions.data, resolvedOptions.preSave);
1399
- processedData = preSaveResult.data;
1400
- }
1401
- await this.ensureAdapterFor(resolvedOptions);
1402
- const adapter = this.getAdapter(resolvedOptions);
1403
- const result = await adapter.update(Object.assign(Object.assign({}, resolvedOptions), { data: processedData }));
1404
- const end = Date.now();
1405
- (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1406
- end, message: 'Database update - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1407
- (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1408
- return result;
1409
- }
1410
- catch (error) {
1411
- const end = Date.now();
1412
- (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1413
- end, message: 'Database update - failed', failed_execution: true, data: { table: options.table, operation: 'update', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1414
- await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1415
- throw error;
1416
- }
1417
- }
1418
- /**
1419
- * Delete records matching conditions
1420
- *
1421
- * @example
1422
- * const result = await ductape.database.delete({
1423
- * table: 'users',
1424
- * where: { status: 'deleted' },
1425
- * });
1426
- * console.log('Deleted count:', result.count);
1427
- */
1428
- async delete(options) {
1429
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1430
- const process_id = (0, processor_utils_1.generateObjectId)();
1431
- const start = Date.now();
1432
- this.initializeLogService();
1433
- // Session log fields (will be populated if session is provided)
1434
- let sessionLogFields = {};
1435
- let resolvedOptions = options;
1436
- // Process session if provided
1437
- if (options.session && options.product) {
1438
- const builder = await this.getProductBuilder(options.product);
1439
- const privateKey = builder.fetchPrivateKey();
1440
- if (privateKey) {
1441
- const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1442
- const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1443
- fetchSessionSelector: async (sessionTag) => {
1444
- const sessionConfig = await builder.fetchSession(sessionTag);
1445
- return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1446
- },
1447
- });
1448
- if (sessionResult.error) {
1449
- throw new Error(`Session validation failed: ${sessionResult.error}`);
1450
- }
1451
- resolvedOptions = sessionResult.input;
1452
- sessionLogFields = sessionResult.logFields;
1453
- }
1454
- }
1455
- const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1456
- const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1457
- const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'delete', data: {
1458
- table: options.table,
1459
- operation: 'delete',
1460
- database: databaseValue,
1461
- env: envValue,
1462
- where: options.where,
1463
- } }, sessionLogFields);
1464
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database delete - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1465
- try {
1466
- await this.ensureAdapterFor(resolvedOptions);
1467
- const adapter = this.getAdapter(resolvedOptions);
1468
- const result = await adapter.delete(resolvedOptions);
1469
- const end = Date.now();
1470
- (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1471
- end, message: 'Database delete - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1472
- (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1473
- return result;
1474
- }
1475
- catch (error) {
1476
- const end = Date.now();
1477
- (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1478
- end, message: 'Database delete - failed', failed_execution: true, data: { table: options.table, operation: 'delete', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1479
- await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1480
- throw error;
1481
- }
1482
- }
1483
- /**
1484
- * Insert or update a record based on conflict keys
1485
- *
1486
- * @example
1487
- * const result = await ductape.database.upsert({
1488
- * table: 'user_preferences',
1489
- * data: {
1490
- * user_id: 123,
1491
- * theme: 'dark',
1492
- * language: 'en',
1493
- * },
1494
- * conflictKeys: ['user_id'],
1495
- * });
1496
- * console.log('Operation:', result.operation); // 'inserted' or 'updated'
1497
- */
1498
- async upsert(options) {
1499
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
1500
- const process_id = (0, processor_utils_1.generateObjectId)();
1501
- const start = Date.now();
1502
- this.initializeLogService();
1503
- // Session log fields (will be populated if session is provided)
1504
- let sessionLogFields = {};
1505
- let resolvedOptions = options;
1506
- // Process session if provided
1507
- if (options.session && options.product) {
1508
- const builder = await this.getProductBuilder(options.product);
1509
- const privateKey = builder.fetchPrivateKey();
1510
- if (privateKey) {
1511
- const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
1512
- const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
1513
- fetchSessionSelector: async (sessionTag) => {
1514
- const sessionConfig = await builder.fetchSession(sessionTag);
1515
- return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
1516
- },
1517
- });
1518
- if (sessionResult.error) {
1519
- throw new Error(`Session validation failed: ${sessionResult.error}`);
1520
- }
1521
- resolvedOptions = sessionResult.input;
1522
- sessionLogFields = sessionResult.logFields;
1523
- }
1524
- }
1525
- const envValue = options.env || ((_a = this.currentContext) === null || _a === void 0 ? void 0 : _a.env) || '';
1526
- const databaseValue = options.database || ((_b = this.currentContext) === null || _b === void 0 ? void 0 : _b.database) || '';
1527
- const baseLogs = Object.assign({ product_tag: options.product || ((_c = this.currentContext) === null || _c === void 0 ? void 0 : _c.product) || '', workspace_id: ((_d = this.config) === null || _d === void 0 ? void 0 : _d.workspace_id) || '', env: envValue, app_env: envValue, process_id, type: logs_types_1.LogEventTypes.DATABASE, parent_tag: databaseValue, child_tag: 'upsert', data: {
1528
- table: options.table,
1529
- operation: 'upsert',
1530
- database: databaseValue,
1531
- env: envValue,
1532
- data: options.data,
1533
- conflictKeys: options.conflictKeys,
1534
- updateColumns: options.updateColumns,
1535
- returning: options.returning,
1536
- } }, sessionLogFields);
1537
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database upsert - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
1538
- try {
1539
- await this.ensureAdapterFor(resolvedOptions);
1540
- const adapter = this.getAdapter(resolvedOptions);
1541
- const result = await adapter.upsert(resolvedOptions);
1542
- const end = Date.now();
1543
- (_f = this.logService) === null || _f === void 0 ? void 0 : _f.add(Object.assign(Object.assign({}, baseLogs), { start,
1544
- end, message: 'Database upsert - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
1545
- (_g = this.logService) === null || _g === void 0 ? void 0 : _g.publish();
1546
- return result;
1547
- }
1548
- catch (error) {
1549
- const end = Date.now();
1550
- (_h = this.logService) === null || _h === void 0 ? void 0 : _h.add(Object.assign(Object.assign({}, baseLogs), { start,
1551
- end, message: 'Database upsert - failed', failed_execution: true, data: { table: options.table, operation: 'upsert', error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
1552
- await ((_j = this.logService) === null || _j === void 0 ? void 0 : _j.publish());
1553
- throw error;
1554
- }
1555
- }
1556
- // ==================== AGGREGATION OPERATIONS ====================
1557
- /**
1558
- * Count records
1559
- *
1560
- * @example
1561
- * const count = await ductape.database.count({
1562
- * table: 'users',
1563
- * where: { status: 'active' },
1564
- * });
1565
- */
1566
- async count(options) {
1567
- await this.ensureAdapterFor(options);
1568
- const adapter = this.getAdapter(options);
1569
- return adapter.count(options);
1570
- }
1571
- /**
1572
- * Sum values of a column
1573
- *
1574
- * @example
1575
- * const totalRevenue = await ductape.database.sum({
1576
- * table: 'orders',
1577
- * column: 'total',
1578
- * where: { status: 'completed' },
1579
- * });
1580
- */
1581
- async sum(options) {
1582
- await this.ensureAdapterFor(options);
1583
- const adapter = this.getAdapter(options);
1584
- return adapter.sum(options);
1585
- }
1586
- /**
1587
- * Calculate average of a column
1588
- *
1589
- * @example
1590
- * const avgOrderValue = await ductape.database.avg({
1591
- * table: 'orders',
1592
- * column: 'total',
1593
- * });
1594
- */
1595
- async avg(options) {
1596
- await this.ensureAdapterFor(options);
1597
- const adapter = this.getAdapter(options);
1598
- return adapter.avg(options);
1599
- }
1600
- /**
1601
- * Get minimum value of a column
1602
- *
1603
- * @example
1604
- * const minPrice = await ductape.database.min({
1605
- * table: 'products',
1606
- * column: 'price',
1607
- * });
1608
- */
1609
- async min(options) {
1610
- await this.ensureAdapterFor(options);
1611
- const adapter = this.getAdapter(options);
1612
- return adapter.min(options);
1613
- }
1614
- /**
1615
- * Get maximum value of a column
1616
- *
1617
- * @example
1618
- * const maxPrice = await ductape.database.max({
1619
- * table: 'products',
1620
- * column: 'price',
1621
- * });
1622
- */
1623
- async max(options) {
1624
- await this.ensureAdapterFor(options);
1625
- const adapter = this.getAdapter(options);
1626
- return adapter.max(options);
1627
- }
1628
- /**
1629
- * Perform multiple aggregations in one query
1630
- *
1631
- * @example
1632
- * const stats = await ductape.database.aggregate({
1633
- * table: 'orders',
1634
- * operations: {
1635
- * total_revenue: { $SUM: 'total' },
1636
- * order_count: { $COUNT: '*' },
1637
- * avg_order_value: { $AVG: 'total' },
1638
- * },
1639
- * where: { status: 'completed' },
1640
- * });
1641
- */
1642
- async aggregate(options) {
1643
- await this.ensureAdapterFor(options);
1644
- const adapter = this.getAdapter(options);
1645
- const aggregationBuilder = new aggregation_builder_1.AggregationBuilder(adapter.getDatabaseType());
1646
- const builtAggregation = aggregationBuilder.buildAggregation(options);
1647
- return adapter.aggregate(builtAggregation);
1648
- }
1649
- /**
1650
- * Group records and perform aggregations
1651
- *
1652
- * @example
1653
- * const salesByCategory = await ductape.database.groupBy({
1654
- * table: 'products',
1655
- * groupBy: ['category'],
1656
- * operations: {
1657
- * total_sales: { $SUM: 'sales_count' },
1658
- * avg_price: { $AVG: 'price' },
1659
- * },
1660
- * having: {
1661
- * total_sales: { $GT: 100 },
1662
- * },
1663
- * });
1664
- */
1665
- async groupBy(options) {
1666
- await this.ensureAdapterFor(options);
1667
- const adapter = this.getAdapter(options);
1668
- const aggregationBuilder = new aggregation_builder_1.AggregationBuilder(adapter.getDatabaseType());
1669
- const builtGroupBy = aggregationBuilder.buildGroupBy(options);
1670
- return adapter.groupBy(builtGroupBy);
1671
- }
1672
- // ==================== TRANSACTION OPERATIONS ====================
1673
- /**
1674
- * Execute operations within a transaction (callback API - recommended)
1675
- *
1676
- * @example
1677
- * const order = await ductape.database.transaction({
1678
- * env: 'prd',
1679
- * product: 'my-app',
1680
- * database: 'main-db',
1681
- * }, async (transaction) => {
1682
- * const order = await ductape.database.insert({
1683
- * table: 'orders',
1684
- * data: { customer_id: 123, total: 99.99 },
1685
- * transaction,
1686
- * });
1687
- *
1688
- * await ductape.database.insert({
1689
- * table: 'order_items',
1690
- * data: items.map(item => ({ order_id: order.insertedIds[0], ...item })),
1691
- * transaction,
1692
- * });
1693
- *
1694
- * return order;
1695
- * });
1696
- */
1697
- async transaction(options, callback) {
1698
- await this.ensureAdapterFor(options);
1699
- const adapter = this.getAdapter(options);
1700
- return this.transactionManager.executeTransaction(adapter, options, callback);
1701
- }
1702
- /**
1703
- * Begin a transaction manually
1704
- *
1705
- * @example
1706
- * const transaction = await ductape.database.beginTransaction({
1707
- * env: 'prd',
1708
- * product: 'my-app',
1709
- * database: 'main-db',
1710
- * isolationLevel: 'REPEATABLE_READ',
1711
- * });
1712
- *
1713
- * try {
1714
- * await ductape.database.insert({ table: 'accounts', data: {...}, transaction });
1715
- * await transaction.commit();
1716
- * } catch (error) {
1717
- * await transaction.rollback();
1718
- * throw error;
1719
- * }
1720
- */
1721
- async beginTransaction(options) {
1722
- await this.ensureAdapterFor(options);
1723
- const adapter = this.getAdapter(options);
1724
- return this.transactionManager.beginTransaction(adapter, options);
1725
- }
1726
- // ==================== SCHEMA OPERATIONS ====================
1727
- /**
1728
- * Create a new table
1729
- *
1730
- * @example
1731
- * import { SchemaHelpers } from '@ductape/sdk';
1732
- *
1733
- * await ductape.database.createTable(
1734
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1735
- * {
1736
- * name: 'products',
1737
- * columns: [
1738
- * SchemaHelpers.id(),
1739
- * SchemaHelpers.string('name', 255, false),
1740
- * SchemaHelpers.decimal('price', 10, 2),
1741
- * ...SchemaHelpers.timestamps(),
1742
- * ],
1743
- * },
1744
- * { ifNotExists: true }
1745
- * );
1746
- */
1747
- async createTable(connectionConfigOrDefinition, tableDefinitionOrOptions, options) {
1748
- // Check if first arg is a table definition (no connectionConfig provided)
1749
- if ('columns' in connectionConfigOrDefinition || 'name' in connectionConfigOrDefinition && !('env' in connectionConfigOrDefinition)) {
1750
- // Using current context - connectionConfigOrDefinition is actually tableDefinition
1751
- const adapter = this.getAdapter();
1752
- return adapter.createTable(connectionConfigOrDefinition, tableDefinitionOrOptions);
1753
- }
1754
- // Using explicit connection config
1755
- const connConfig = connectionConfigOrDefinition;
1756
- await this.ensureAdapterFor(connConfig);
1757
- const adapter = this.getAdapter(connConfig);
1758
- return adapter.createTable(tableDefinitionOrOptions, options);
1759
- }
1760
- /**
1761
- * Alter an existing table
1762
- *
1763
- * @example
1764
- * import { ColumnAlterationType, ColumnType } from '@ductape/sdk';
1765
- *
1766
- * // Add column
1767
- * await ductape.database.alterTable(
1768
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1769
- * 'products',
1770
- * [{ type: ColumnAlterationType.ADD, column: { name: 'sku', type: ColumnType.STRING, length: 50 } }]
1771
- * );
1772
- *
1773
- * // Drop column
1774
- * await ductape.database.alterTable(
1775
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1776
- * 'products',
1777
- * [{ type: ColumnAlterationType.DROP, columnName: 'old_field' }]
1778
- * );
1779
- *
1780
- * // Rename column
1781
- * await ductape.database.alterTable(
1782
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1783
- * 'products',
1784
- * [{ type: ColumnAlterationType.RENAME, oldName: 'old_name', newName: 'new_name' }]
1785
- * );
1786
- */
1787
- async alterTable(connectionConfigOrTableName, tableNameOrAlterations, alterations) {
1788
- // Check if first arg is a string (tableName - no connectionConfig provided)
1789
- if (typeof connectionConfigOrTableName === 'string') {
1790
- const adapter = this.getAdapter();
1791
- return adapter.alterTable(connectionConfigOrTableName, tableNameOrAlterations);
1792
- }
1793
- // Using explicit connection config
1794
- const connConfig = connectionConfigOrTableName;
1795
- await this.ensureAdapterFor(connConfig);
1796
- const adapter = this.getAdapter(connConfig);
1797
- return adapter.alterTable(tableNameOrAlterations, alterations);
1798
- }
1799
- /**
1800
- * Drop a table
1801
- *
1802
- * @example
1803
- * await ductape.database.dropTable(
1804
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1805
- * 'old_table'
1806
- * );
1807
- */
1808
- async dropTable(connectionConfigOrTableName, tableName) {
1809
- // Check if first arg is a string (tableName - no connectionConfig provided)
1810
- if (typeof connectionConfigOrTableName === 'string') {
1811
- const adapter = this.getAdapter();
1812
- return adapter.dropTable(connectionConfigOrTableName, true);
1813
- }
1814
- // Using explicit connection config
1815
- const connConfig = connectionConfigOrTableName;
1816
- await this.ensureAdapterFor(connConfig);
1817
- const adapter = this.getAdapter(connConfig);
1818
- return adapter.dropTable(tableName, true);
1819
- }
1820
- /**
1821
- * List all tables in the database
1822
- *
1823
- * @example
1824
- * const tables = await ductape.database.listTables({
1825
- * env: 'dev',
1826
- * product: 'my-app',
1827
- * database: 'main-db',
1828
- * });
1829
- */
1830
- async listTables(connectionConfig) {
1831
- if (connectionConfig)
1832
- await this.ensureAdapterFor(connectionConfig);
1833
- const adapter = this.getAdapter(connectionConfig);
1834
- return adapter.listTables();
1835
- }
1836
- /**
1837
- * List all tables with basic information including estimated row counts
1838
- *
1839
- * @example
1840
- * const tables = await ductape.database.listTablesWithInfo({
1841
- * env: 'dev',
1842
- * product: 'my-app',
1843
- * database: 'main-db',
1844
- * });
1845
- * // Returns: [{ name: 'users', estimatedRowCount: 1247, schema: 'public' }, ...]
1846
- */
1847
- async listTablesWithInfo(connectionConfig) {
1848
- if (connectionConfig)
1849
- await this.ensureAdapterFor(connectionConfig);
1850
- const adapter = this.getAdapter(connectionConfig);
1851
- return adapter.listTablesWithInfo();
1852
- }
1853
- /**
1854
- * Check if a table exists
1855
- *
1856
- * @example
1857
- * const exists = await ductape.database.tableExists(
1858
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1859
- * 'users'
1860
- * );
1861
- */
1862
- async tableExists(connectionConfigOrTableName, tableName) {
1863
- // Check if first arg is a string (tableName - no connectionConfig provided)
1864
- if (typeof connectionConfigOrTableName === 'string') {
1865
- const adapter = this.getAdapter();
1866
- return adapter.tableExists(connectionConfigOrTableName);
1867
- }
1868
- // Using explicit connection config
1869
- const connConfig = connectionConfigOrTableName;
1870
- await this.ensureAdapterFor(connConfig);
1871
- const adapter = this.getAdapter(connConfig);
1872
- return adapter.tableExists(tableName);
1873
- }
1874
- /**
1875
- * Get the schema of a table
1876
- *
1877
- * @example
1878
- * const schema = await ductape.database.getTableSchema(
1879
- * { env: 'dev', product: 'my-app', database: 'main-db' },
1880
- * 'users'
1881
- * );
1882
- * console.log('Table:', schema.name);
1883
- * console.log('Columns:', schema.columns);
1884
- * console.log('Indexes:', schema.indexes);
1885
- */
1886
- async getTableSchema(connectionConfigOrTableName, tableName) {
1887
- // Check if first arg is a string (tableName - no connectionConfig provided)
1888
- if (typeof connectionConfigOrTableName === 'string') {
1889
- const adapter = this.getAdapter();
1890
- return adapter.getTableSchema(connectionConfigOrTableName);
1891
- }
1892
- // Using explicit connection config
1893
- const connConfig = connectionConfigOrTableName;
1894
- await this.ensureAdapterFor(connConfig);
1895
- const adapter = this.getAdapter(connConfig);
1896
- return adapter.getTableSchema(tableName);
1897
- }
1898
- /**
1899
- * Create an index
1900
- *
1901
- * @example
1902
- * await ductape.database.createIndex({
1903
- * env: 'dev',
1904
- * product: 'my-app',
1905
- * database: 'main-db',
1906
- * table: 'users',
1907
- * index: {
1908
- * name: 'idx_users_email',
1909
- * table: 'users',
1910
- * columns: [{ name: 'email' }],
1911
- * unique: true,
1912
- * },
1913
- * ifNotExists: true,
1914
- * concurrent: true, // PostgreSQL: create without locking
1915
- * });
1916
- */
1917
- async createIndex(options) {
1918
- await this.ensureAdapterFor(options);
1919
- const adapter = this.getAdapter(options);
1920
- return adapter.createIndex(options.index, options.ifNotExists, options.concurrent);
1921
- }
1922
- /**
1923
- * Drop an index
1924
- *
1925
- * @example
1926
- * await ductape.database.dropIndex({
1927
- * env: 'dev',
1928
- * product: 'my-app',
1929
- * database: 'main-db',
1930
- * table: 'users',
1931
- * indexName: 'idx_users_old',
1932
- * ifExists: true,
1933
- * concurrent: true,
1934
- * });
1935
- */
1936
- async dropIndex(options) {
1937
- await this.ensureAdapterFor(options);
1938
- const adapter = this.getAdapter(options);
1939
- return adapter.dropIndex(options.table, options.indexName, options.ifExists, options.concurrent, options.cascade);
1940
- }
1941
- /**
1942
- * List all indexes on a table
1943
- *
1944
- * @example
1945
- * const indexes = await ductape.database.listIndexes({
1946
- * env: 'dev',
1947
- * product: 'my-app',
1948
- * database: 'main-db',
1949
- * table: 'users',
1950
- * includeSystem: false,
1951
- * });
1952
- */
1953
- async listIndexes(options) {
1954
- await this.ensureAdapterFor(options);
1955
- const adapter = this.getAdapter(options);
1956
- return adapter.listIndexes(options.table, options.includeSystem);
1957
- }
1958
- /**
1959
- * Get index statistics
1960
- *
1961
- * @example
1962
- * // All indexes on a table
1963
- * const stats = await ductape.database.getIndexStatistics(
1964
- * { env: 'prd', product: 'my-app', database: 'main-db' },
1965
- * 'users'
1966
- * );
1967
- *
1968
- * // Specific index
1969
- * const emailStats = await ductape.database.getIndexStatistics(
1970
- * { env: 'prd', product: 'my-app', database: 'main-db' },
1971
- * 'users',
1972
- * 'idx_users_email'
1973
- * );
1974
- */
1975
- async getIndexStatistics(connectionConfig, tableName, indexName) {
1976
- await this.ensureAdapterFor(connectionConfig);
1977
- const adapter = this.getAdapter(connectionConfig);
1978
- return adapter.getIndexStatistics(tableName, indexName);
1979
- }
1980
- // ==================== MIGRATION OPERATIONS ====================
1981
- /**
1982
- * Run a migration
1983
- *
1984
- * @example
1985
- * const result = await ductape.database.runMigration([migration]);
1986
- * console.log('Migrated:', result.size);
1987
- */
1988
- async runMigration(migrations, options) {
1989
- const engine = this.getMigrationEngine();
1990
- return engine.migrate(migrations, options);
1991
- }
1992
- /**
1993
- * Rollback migrations
1994
- *
1995
- * @example
1996
- * const result = await ductape.database.rollbackMigration([migration], 1);
1997
- * console.log('Rolled back:', result.size);
1998
- */
1999
- async rollbackMigration(migrations, count = 1) {
2000
- const engine = this.getMigrationEngine();
2001
- return engine.rollback(migrations, count);
2002
- }
2003
- /**
2004
- * Get migration history (applied migrations)
2005
- *
2006
- * @example
2007
- * const history = await ductape.database.getMigrationHistory();
2008
- * history.forEach((entry) => {
2009
- * console.log('Tag:', entry.tag);
2010
- * console.log('Applied at:', entry.appliedAt);
2011
- * });
2012
- */
2013
- async getMigrationHistory() {
2014
- const engine = this.getMigrationEngine();
2015
- return engine.getAppliedMigrations();
2016
- }
2017
- /**
2018
- * Get status of all migrations
2019
- *
2020
- * @example
2021
- * const status = await ductape.database.getMigrationStatus(allMigrations);
2022
- * console.log('Pending:', status.pending);
2023
- */
2024
- async getMigrationStatus(migrations) {
2025
- const engine = this.getMigrationEngine();
2026
- return engine.getStatus(migrations);
2027
- }
2028
- // ==================== MIGRATION CRUD OPERATIONS ====================
2029
- /**
2030
- * Migration management sub-object
2031
- * Provides CRUD operations for database migrations via ProductBuilder
2032
- */
2033
- get migration() {
2034
- return {
2035
- /**
2036
- * Create a new database migration
2037
- *
2038
- * @example
2039
- * await ductape.database.migration.create({
2040
- * product: 'my-product',
2041
- * database: 'main-db',
2042
- * data: {
2043
- * name: 'Add users table',
2044
- * tag: 'main-db:add-users-table',
2045
- * value: {
2046
- * up: ['CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255))'],
2047
- * down: ['DROP TABLE users'],
2048
- * },
2049
- * },
2050
- * });
2051
- */
2052
- create: async (options) => {
2053
- const builder = await this.getProductBuilder(options.product);
2054
- // Format tag as database:migration if not already formatted
2055
- const tag = options.data.tag.includes(':')
2056
- ? options.data.tag
2057
- : `${options.database}:${options.data.tag}`;
2058
- await builder.createDatabaseMigration({
2059
- name: options.data.name,
2060
- tag,
2061
- description: options.data.description,
2062
- value: options.data.value,
2063
- });
2064
- },
2065
- /**
2066
- * Update an existing database migration
2067
- *
2068
- * @example
2069
- * await ductape.database.migration.update({
2070
- * product: 'my-product',
2071
- * tag: 'main-db:add-users-table',
2072
- * data: {
2073
- * description: 'Updated description',
2074
- * },
2075
- * });
2076
- */
2077
- update: async (options) => {
2078
- const builder = await this.getProductBuilder(options.product);
2079
- await builder.updateDatabaseMigration(Object.assign({ tag: options.tag }, options.data));
2080
- },
2081
- /**
2082
- * Fetch a specific database migration
2083
- *
2084
- * @example
2085
- * const migration = await ductape.database.migration.fetch({
2086
- * product: 'my-product',
2087
- * tag: 'main-db:add-users-table',
2088
- * });
2089
- */
2090
- fetch: async (options) => {
2091
- const builder = await this.getProductBuilder(options.product);
2092
- return builder.fetchDatabaseMigration(options.tag);
2093
- },
2094
- /**
2095
- * Fetch all database migrations for a database
2096
- *
2097
- * @example
2098
- * const migrations = await ductape.database.migration.fetchAll({
2099
- * product: 'my-product',
2100
- * database: 'main-db',
2101
- * });
2102
- */
2103
- fetchAll: async (options) => {
2104
- const builder = await this.getProductBuilder(options.product);
2105
- return builder.fetchDatabaseMigrations(options.database);
2106
- },
2107
- /**
2108
- * Delete a database migration
2109
- *
2110
- * @example
2111
- * await ductape.database.migration.delete({
2112
- * product: 'my-product',
2113
- * tag: 'main-db:add-users-table',
2114
- * });
2115
- */
2116
- delete: async (options) => {
2117
- const builder = await this.getProductBuilder(options.product);
2118
- return builder.deleteDatabaseMigration(options.tag);
2119
- },
2120
- /**
2121
- * Run a database migration (up)
2122
- * @deprecated Migration execution has been deprecated
2123
- */
2124
- run: async (_options) => {
2125
- throw new Error('Migration execution has been deprecated');
2126
- },
2127
- /**
2128
- * Rollback a database migration (down)
2129
- * @deprecated Migration execution has been deprecated
2130
- */
2131
- rollback: async (_options) => {
2132
- throw new Error('Migration execution has been deprecated');
2133
- },
2134
- };
2135
- }
2136
- // ==================== ACTION OPERATIONS ====================
2137
- /**
2138
- * Action management sub-object
2139
- */
2140
- get action() {
2141
- return {
2142
- /**
2143
- * Create a new database action
2144
- *
2145
- * @example
2146
- * await ductape.database.action.create({
2147
- * name: 'Get Users Paginated',
2148
- * tag: 'postgresdb:get-users-paginated',
2149
- * tableName: 'users',
2150
- * operation: DatabaseActionTypes.QUERY,
2151
- * template: {
2152
- * where: { is_active: true },
2153
- * limit: '{{limit}}',
2154
- * offset: '{{offset}}',
2155
- * },
2156
- * });
2157
- */
2158
- create: async (options) => {
2159
- return this.actionManager.create(options);
2160
- },
2161
- /**
2162
- * Update an existing action
2163
- *
2164
- * @example
2165
- * await ductape.database.action.update({
2166
- * tag: 'postgresdb:get-users',
2167
- * template: { where: { status: '{{status}}' } },
2168
- * });
2169
- */
2170
- update: async (options) => {
2171
- return this.actionManager.update(options);
2172
- },
2173
- /**
2174
- * Fetch a specific action
2175
- *
2176
- * @example
2177
- * const action = await ductape.database.action.fetch('postgresdb:get-users');
2178
- */
2179
- fetch: async (tag) => {
2180
- return this.actionManager.fetch(tag);
2181
- },
2182
- /**
2183
- * Fetch all actions for a database
2184
- *
2185
- * @example
2186
- * const actions = await ductape.database.action.fetchAll('postgresdb');
2187
- */
2188
- fetchAll: async (databaseTag) => {
2189
- return this.actionManager.fetchAll(databaseTag);
2190
- },
2191
- /**
2192
- * Delete a database action
2193
- *
2194
- * @example
2195
- * await ductape.database.action.delete('postgresdb:get-users');
2196
- */
2197
- delete: async (tag) => {
2198
- return this.actionManager.delete(tag);
2199
- },
2200
- /**
2201
- * Dispatches a database action to run as a scheduled job.
2202
- * @param {IDBActionDispatchInput} data - The database action dispatch input.
2203
- * @returns {Promise<IDispatchResult>} The dispatch result with job ID and status.
2204
- * @example
2205
- * // Schedule a database action to run in 1 hour
2206
- * await ductape.databases.action.dispatch({
2207
- * product: 'my-product',
2208
- * env: 'production',
2209
- * database: 'users-db',
2210
- * event: 'cleanup-inactive',
2211
- * input: { query: { inactive: true } },
2212
- * schedule: { start_at: Date.now() + 3600000 }
2213
- * });
2214
- *
2215
- * // Run on a cron schedule
2216
- * await ductape.databases.action.dispatch({
2217
- * product: 'my-product',
2218
- * env: 'production',
2219
- * database: 'analytics-db',
2220
- * event: 'aggregate-daily',
2221
- * input: { query: {} },
2222
- * schedule: { cron: '0 0 * * *' } // Daily at midnight
2223
- * });
2224
- */
2225
- dispatch: async (data) => {
2226
- const processorService = this.createNewProcessor();
2227
- const productBuilder = await this.getProductBuilder(data.product);
2228
- const schedule = data.schedule || {};
2229
- const startAt = typeof schedule.start_at === 'string'
2230
- ? new Date(schedule.start_at).getTime()
2231
- : schedule.start_at || Date.now();
2232
- // Generate job tag based on type, database, and event
2233
- const jobTag = `database:${data.database}:${data.event}`;
2234
- // Check if job exists, if not create it
2235
- const existingJob = await productBuilder.fetchJob(jobTag);
2236
- if (!existingJob) {
2237
- await productBuilder.createJob({
2238
- tag: jobTag,
2239
- name: `Database: ${data.database}/${data.event}`,
2240
- description: `Auto-created job for database action ${data.event} on database ${data.database}`,
2241
- type: types_1.JobEventTypes.DATABASE_ACTION,
2242
- app: data.database,
2243
- event: data.event,
2244
- executions: 0,
2245
- intervals: schedule.every || 0,
2246
- start_at: startAt,
2247
- });
2248
- }
2249
- const jobInput = {
2250
- product: data.product,
2251
- env: data.env,
2252
- event: jobTag,
2253
- input: data.input,
2254
- retries: data.retries || 0,
2255
- start_at: startAt,
2256
- session: data.session,
2257
- cache: data.cache,
2258
- repeat: schedule.cron || schedule.every ? {
2259
- cron: schedule.cron,
2260
- every: schedule.every,
2261
- limit: schedule.limit,
2262
- endDate: schedule.endDate,
2263
- tz: schedule.tz,
2264
- } : undefined,
2265
- };
2266
- await processorService.processJob(jobInput);
2267
- const isRecurring = !!(schedule.cron || schedule.every);
2268
- let nextRunAt;
2269
- if (isRecurring && schedule.every) {
2270
- nextRunAt = startAt + schedule.every;
2271
- }
2272
- return {
2273
- job_id: (0, crypto_1.randomUUID)(),
2274
- status: startAt > Date.now() ? 'scheduled' : 'queued',
2275
- scheduled_at: startAt,
2276
- recurring: isRecurring,
2277
- next_run_at: nextRunAt,
2278
- };
2279
- },
2280
- };
2281
- }
2282
- /**
2283
- * Execute a database action
2284
- *
2285
- * @example
2286
- * const users = await ductape.database.execute({
2287
- * product: 'my-product',
2288
- * env: 'prd',
2289
- * database: 'postgresdb',
2290
- * action: 'get-users-paginated',
2291
- * input: {
2292
- * limit: 25,
2293
- * offset: 0,
2294
- * },
2295
- * });
2296
- */
2297
- async execute(options) {
2298
- var _a, _b, _c, _d, _e, _f;
2299
- const process_id = (0, processor_utils_1.generateObjectId)();
2300
- const start = Date.now();
2301
- // Session log fields (will be populated if session is provided)
2302
- let sessionLogFields = {};
2303
- let resolvedOptions = options;
2304
- // Initialize product builder and logging
2305
- if (options.product) {
2306
- const builder = await this.getProductBuilder(options.product);
2307
- // Process session if provided
2308
- if (options.session) {
2309
- const privateKey = builder.fetchPrivateKey();
2310
- if (privateKey) {
2311
- const { processSessionForExecution } = await Promise.resolve().then(() => __importStar(require('../sessions')));
2312
- const sessionResult = await processSessionForExecution(options.session, privateKey, options, options.env, {
2313
- fetchSessionSelector: async (sessionTag) => {
2314
- const sessionConfig = await builder.fetchSession(sessionTag);
2315
- return sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.selector;
2316
- },
2317
- });
2318
- if (sessionResult.error) {
2319
- throw new Error(`Session validation failed: ${sessionResult.error}`);
2320
- }
2321
- resolvedOptions = sessionResult.input;
2322
- sessionLogFields = sessionResult.logFields;
2323
- }
2324
- }
2325
- }
2326
- this.initializeLogService();
2327
- const baseLogs = Object.assign({ product_tag: options.product || '', workspace_id: ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || '', env: options.env, process_id, type: logs_types_1.LogEventTypes.DB_ACTION, parent_tag: options.database, child_tag: options.action, data: { database: options.database, action: options.action } }, sessionLogFields);
2328
- (_b = this.logService) === null || _b === void 0 ? void 0 : _b.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database action execute - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
2329
- try {
2330
- const result = await this.actionManager.execute(resolvedOptions);
2331
- const end = Date.now();
2332
- (_c = this.logService) === null || _c === void 0 ? void 0 : _c.add(Object.assign(Object.assign({}, baseLogs), { start,
2333
- end, message: 'Database action execute - success', successful_execution: true, status: logs_types_1.LogEventStatus.SUCCESS }));
2334
- (_d = this.logService) === null || _d === void 0 ? void 0 : _d.publish();
2335
- return result;
2336
- }
2337
- catch (error) {
2338
- const end = Date.now();
2339
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start,
2340
- end, message: 'Database action execute - failed', failed_execution: true, data: { database: options.database, action: options.action, error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
2341
- await ((_f = this.logService) === null || _f === void 0 ? void 0 : _f.publish());
2342
- throw error;
2343
- }
2344
- }
2345
- /**
2346
- * Dispatches a database operation to run as a scheduled job.
2347
- * Use this for direct database operations (query, insert, update, delete, etc.).
2348
- * @param {IDBOperationDispatchInput} data - The database operation dispatch input.
2349
- * @returns {Promise<IDispatchResult>} The dispatch result with job ID and status.
2350
- * @example
2351
- * // Schedule a database operation to run in 1 hour
2352
- * await ductape.databases.dispatch({
2353
- * product: 'my-product',
2354
- * env: 'production',
2355
- * database: 'users-db',
2356
- * operation: 'deleteMany',
2357
- * input: { filter: { inactive: true, lastLogin: { $lt: '2024-01-01' } } },
2358
- * schedule: { start_at: Date.now() + 3600000 }
2359
- * });
2360
- *
2361
- * // Run daily database cleanup
2362
- * await ductape.databases.dispatch({
2363
- * product: 'my-product',
2364
- * env: 'production',
2365
- * database: 'logs-db',
2366
- * operation: 'deleteMany',
2367
- * input: { filter: { createdAt: { $lt: '$DateAdd($Now(), -30, "days")' } } },
2368
- * schedule: { cron: '0 3 * * *' } // Daily at 3 AM
2369
- * });
2370
- */
2371
- async dispatch(data) {
2372
- var _a, _b, _c, _d, _e, _f;
2373
- const process_id = (0, processor_utils_1.generateObjectId)();
2374
- const start = Date.now();
2375
- const processorService = this.createNewProcessor();
2376
- const productBuilder = await this.getProductBuilder(data.product);
2377
- const schedule = data.schedule || {};
2378
- const startAt = typeof schedule.start_at === 'string'
2379
- ? new Date(schedule.start_at).getTime()
2380
- : schedule.start_at || Date.now();
2381
- // Generate job tag based on type, database, and operation
2382
- const jobTag = `database-operation:${data.database}:${data.operation}`;
2383
- // Initialize logging
2384
- this.initializeLogService();
2385
- const baseLogs = {
2386
- product_tag: data.product,
2387
- workspace_id: ((_a = this.config) === null || _a === void 0 ? void 0 : _a.workspace_id) || '',
2388
- env: data.env,
2389
- process_id,
2390
- type: logs_types_1.LogEventTypes.DATABASE,
2391
- parent_tag: data.database,
2392
- child_tag: data.operation,
2393
- data: { database: data.database, operation: data.operation },
2394
- };
2395
- (_b = this.logService) === null || _b === void 0 ? void 0 : _b.add(Object.assign(Object.assign({}, baseLogs), { start, message: 'Database dispatch - initiated', status: logs_types_1.LogEventStatus.PROCESSING }));
2396
- try {
2397
- // Check if job exists, if not create it
2398
- const existingJob = await productBuilder.fetchJob(jobTag);
2399
- if (!existingJob) {
2400
- await productBuilder.createJob({
2401
- tag: jobTag,
2402
- name: `Database Operation: ${data.database}/${data.operation}`,
2403
- description: `Auto-created job for database operation ${data.operation} on database ${data.database}`,
2404
- type: types_1.JobEventTypes.DATABASE_OPERATION,
2405
- app: data.database,
2406
- event: data.operation,
2407
- executions: 0,
2408
- intervals: schedule.every || 0,
2409
- start_at: startAt,
2410
- });
2411
- }
2412
- const jobInput = {
2413
- product: data.product,
2414
- env: data.env,
2415
- event: jobTag,
2416
- input: data.input,
2417
- retries: data.retries || 0,
2418
- start_at: startAt,
2419
- session: data.session,
2420
- cache: data.cache,
2421
- repeat: schedule.cron || schedule.every ? {
2422
- cron: schedule.cron,
2423
- every: schedule.every,
2424
- limit: schedule.limit,
2425
- endDate: schedule.endDate,
2426
- tz: schedule.tz,
2427
- } : undefined,
2428
- };
2429
- await processorService.processJob(jobInput);
2430
- const isRecurring = !!(schedule.cron || schedule.every);
2431
- let nextRunAt;
2432
- if (isRecurring && schedule.every) {
2433
- nextRunAt = startAt + schedule.every;
2434
- }
2435
- const job_id = (0, crypto_1.randomUUID)();
2436
- const end = Date.now();
2437
- (_c = this.logService) === null || _c === void 0 ? void 0 : _c.add(Object.assign(Object.assign({}, baseLogs), { start,
2438
- end, message: 'Database dispatch - success', successful_execution: true, data: { database: data.database, operation: data.operation, job_id }, status: logs_types_1.LogEventStatus.SUCCESS }));
2439
- (_d = this.logService) === null || _d === void 0 ? void 0 : _d.publish();
2440
- return {
2441
- job_id,
2442
- status: startAt > Date.now() ? 'scheduled' : 'queued',
2443
- scheduled_at: startAt,
2444
- recurring: isRecurring,
2445
- next_run_at: nextRunAt,
2446
- };
2447
- }
2448
- catch (error) {
2449
- const end = Date.now();
2450
- (_e = this.logService) === null || _e === void 0 ? void 0 : _e.add(Object.assign(Object.assign({}, baseLogs), { start,
2451
- end, message: 'Database dispatch - failed', failed_execution: true, data: { database: data.database, operation: data.operation, error: String(error) }, status: logs_types_1.LogEventStatus.FAIL }));
2452
- await ((_f = this.logService) === null || _f === void 0 ? void 0 : _f.publish());
2453
- throw error;
2454
- }
2455
- }
2456
- // ==================== HELPER METHODS ====================
2457
- /**
2458
- * Get the appropriate adapter for the operation
2459
- */
2460
- getAdapter(options) {
2461
- // If options specify env and database, use those
2462
- if ((options === null || options === void 0 ? void 0 : options.env) && (options === null || options === void 0 ? void 0 : options.database)) {
2463
- const contextKey = this.buildContextKey(options.database, options.env);
2464
- const adapter = this.adapters.get(contextKey);
2465
- if (!adapter) {
2466
- throw new database_error_1.DatabaseError(`No adapter found for database '${options.database}' in environment '${options.env}'`, enums_1.DatabaseErrorType.NOT_FOUND);
2467
- }
2468
- return adapter;
2469
- }
2470
- // Otherwise use current context
2471
- if (!this.currentContext) {
2472
- throw new database_error_1.DatabaseError('No database connection established. Call connect() first or provide env and database options.', enums_1.DatabaseErrorType.CONNECTION_ERROR);
2473
- }
2474
- const contextKey = this.buildContextKey(this.currentContext.database, this.currentContext.env);
2475
- const adapter = this.adapters.get(contextKey);
2476
- if (!adapter) {
2477
- throw new database_error_1.DatabaseError('No adapter found for current connection context', enums_1.DatabaseErrorType.CONNECTION_ERROR);
2478
- }
2479
- return adapter;
2480
- }
2481
- /**
2482
- * Ensure an adapter exists for the given database/env/product (connect on demand).
2483
- * Use before getAdapter() when options include database+env+product (e.g. from proxy).
2484
- */
2485
- async ensureAdapterFor(options) {
2486
- if (!(options === null || options === void 0 ? void 0 : options.database) || !(options === null || options === void 0 ? void 0 : options.env) || !(options === null || options === void 0 ? void 0 : options.product))
2487
- return;
2488
- const contextKey = this.buildContextKey(options.database, options.env);
2489
- const existing = this.adapters.get(contextKey);
2490
- if (existing && typeof existing.isConnected === 'function' && existing.isConnected())
2491
- return;
2492
- await this.connect({ database: options.database, env: options.env, product: options.product });
2493
- }
2494
- /**
2495
- * Get the current connection context
2496
- */
2497
- getCurrentContext() {
2498
- return this.currentContext;
2499
- }
2500
- /**
2501
- * Get a connection-scoped interface for a specific database/environment.
2502
- * This ensures schema operations are isolated to a specific connection.
2503
- *
2504
- * @example
2505
- * const usersDb = db.connection('users-db', 'dev');
2506
- * await usersDb.schema.create('users', { ... });
2507
- *
2508
- * const ordersDb = db.connection('orders-db', 'dev');
2509
- * await ordersDb.schema.create('orders', { ... }); // Different connection
2510
- */
2511
- connection(database, env, product = '') {
2512
- return new DatabaseConnection(this, database, env, product);
2513
- }
2514
- /**
2515
- * Build a context key from database and environment
2516
- */
2517
- buildContextKey(database, env) {
2518
- return `${database}:${env}`;
2519
- }
2520
- /**
2521
- * Convert DatabaseTypes (from product API) to DatabaseType (ORM internal)
2522
- */
2523
- convertDatabaseType(type) {
2524
- // Map from DatabaseTypes enum values to DatabaseType enum
2525
- const typeMap = {
2526
- 'postgresql': enums_1.DatabaseType.POSTGRESQL,
2527
- 'mongodb': enums_1.DatabaseType.MONGODB,
2528
- 'mysql': enums_1.DatabaseType.MYSQL,
2529
- 'dynamodb': enums_1.DatabaseType.DYNAMODB,
2530
- 'mariadb': enums_1.DatabaseType.MARIADB,
2531
- 'cassandra': enums_1.DatabaseType.CASSANDRA,
2532
- };
2533
- const normalizedType = String(type).toLowerCase();
2534
- const mappedType = typeMap[normalizedType];
2535
- if (!mappedType) {
2536
- throw new database_error_1.DatabaseError(`Unsupported database type: ${type}. Supported types: ${Object.keys(typeMap).join(', ')}`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
2537
- }
2538
- return mappedType;
2539
- }
2540
- // ==================== SIMPLIFIED SCHEMA API ====================
2541
- /**
2542
- * Simplified schema operations API (Mongoose-style)
2543
- *
2544
- * @example
2545
- * await db.connect({ env: 'dev', product: 'my-app', database: 'users-db' });
2546
- *
2547
- * // Create a table with Mongoose-style schema
2548
- * await db.schema.create('users', {
2549
- * id: { type: 'uuid', primaryKey: true },
2550
- * email: { type: 'string', length: 255, required: true, unique: true },
2551
- * name: { type: 'string', length: 100 },
2552
- * age: 'integer', // Shorthand
2553
- * status: { type: 'enum', enum: ['active', 'inactive'], default: 'active' },
2554
- * }, { timestamps: true });
2555
- */
2556
- get schema() {
2557
- return {
2558
- /**
2559
- * Create a collection/table with Mongoose-style schema definition
2560
- */
2561
- create: (name, definition, options) => this.schemaCreate(name, definition, options),
2562
- /**
2563
- * Drop a collection/table
2564
- */
2565
- drop: (name, options) => this.schemaDrop(name, options),
2566
- /**
2567
- * Add a field to a collection
2568
- */
2569
- addField: (collection, fieldName, definition) => this.schemaAddField(collection, fieldName, definition),
2570
- /**
2571
- * Drop a field from a collection
2572
- */
2573
- dropField: (collection, fieldName) => this.schemaDropField(collection, fieldName),
2574
- /**
2575
- * Rename a field in a collection
2576
- */
2577
- renameField: (collection, oldName, newName) => this.schemaRenameField(collection, oldName, newName),
2578
- /**
2579
- * Modify a field's definition
2580
- */
2581
- modifyField: (collection, fieldName, changes) => this.schemaModifyField(collection, fieldName, changes),
2582
- /**
2583
- * Create an index on a collection
2584
- */
2585
- createIndex: (collection, fields, options) => this.schemaCreateIndex(collection, fields, options),
2586
- /**
2587
- * Drop an index from a collection
2588
- */
2589
- dropIndex: (collection, indexName) => this.schemaDropIndex(collection, indexName),
2590
- /**
2591
- * Add a constraint (SQL databases only)
2592
- */
2593
- addConstraint: (collection, constraint) => this.schemaAddConstraint(collection, constraint),
2594
- /**
2595
- * Drop a constraint (SQL databases only)
2596
- */
2597
- dropConstraint: (collection, constraintName) => this.schemaDropConstraint(collection, constraintName),
2598
- /**
2599
- * Rename a collection/table
2600
- */
2601
- rename: (oldName, newName) => this.schemaRename(oldName, newName),
2602
- /**
2603
- * Check if a collection/table exists
2604
- */
2605
- exists: (name) => this.schemaExists(name),
2606
- /**
2607
- * List all collections/tables
2608
- */
2609
- list: (schemaName) => this.schemaList(schemaName),
2610
- /**
2611
- * Get detailed schema information for a collection
2612
- */
2613
- describe: (name) => this.schemaDescribe(name),
2614
- /**
2615
- * List indexes on a collection
2616
- */
2617
- indexes: (collection) => this.schemaListIndexes(collection),
2618
- };
2619
- }
2620
- // ==================== PRIVATE SCHEMA IMPLEMENTATION ====================
2621
- /**
2622
- * Create a collection with Mongoose-style definition
2623
- */
2624
- async schemaCreate(name, definition, options) {
2625
- var _a;
2626
- const schemaManager = this.getSchemaManager();
2627
- const fields = this.convertToFieldDefinitions(definition, options === null || options === void 0 ? void 0 : options.timestamps);
2628
- // Convert simple index definitions to the expected format
2629
- const indexes = (_a = options === null || options === void 0 ? void 0 : options.indexes) === null || _a === void 0 ? void 0 : _a.map(idx => ({
2630
- name: idx.name || `idx_${name}_${Array.isArray(idx.fields) ? (typeof idx.fields[0] === 'string' ? idx.fields.join('_') : idx.fields.map((f) => f.name).join('_')) : idx.fields}`,
2631
- fields: this.normalizeIndexFields(idx.fields),
2632
- unique: idx.unique,
2633
- }));
2634
- return schemaManager.createCollection(name, fields, {
2635
- autoApply: true,
2636
- indexes,
2637
- sqlOptions: options === null || options === void 0 ? void 0 : options.sqlOptions,
2638
- mongoOptions: options === null || options === void 0 ? void 0 : options.mongoOptions,
2639
- dynamoOptions: options === null || options === void 0 ? void 0 : options.dynamoOptions,
2640
- cassandraOptions: options === null || options === void 0 ? void 0 : options.cassandraOptions,
2641
- });
2642
- }
2643
- /**
2644
- * Drop a collection
2645
- */
2646
- async schemaDrop(name, options) {
2647
- const schemaManager = this.getSchemaManager();
2648
- return schemaManager.dropCollection(name, {
2649
- autoApply: true,
2650
- ifExists: options === null || options === void 0 ? void 0 : options.ifExists,
2651
- cascade: options === null || options === void 0 ? void 0 : options.cascade,
2652
- });
2653
- }
2654
- /**
2655
- * Add a field to a collection
2656
- */
2657
- async schemaAddField(collection, fieldName, definition) {
2658
- const schemaManager = this.getSchemaManager();
2659
- const field = this.convertFieldDefinition(fieldName, definition);
2660
- return schemaManager.addField(collection, field, { autoApply: true });
2661
- }
2662
- /**
2663
- * Drop a field from a collection
2664
- */
2665
- async schemaDropField(collection, fieldName) {
2666
- const schemaManager = this.getSchemaManager();
2667
- return schemaManager.dropField(collection, fieldName, { autoApply: true });
2668
- }
2669
- /**
2670
- * Rename a field
2671
- */
2672
- async schemaRenameField(collection, oldName, newName) {
2673
- const schemaManager = this.getSchemaManager();
2674
- return schemaManager.renameField(collection, oldName, newName, { autoApply: true });
2675
- }
2676
- /**
2677
- * Modify a field's definition
2678
- */
2679
- async schemaModifyField(collection, fieldName, changes) {
2680
- const schemaManager = this.getSchemaManager();
2681
- const fieldChanges = {};
2682
- if (changes.type) {
2683
- fieldChanges.type = this.normalizeFieldType(changes.type);
2684
- }
2685
- if (changes.minLength !== undefined) {
2686
- fieldChanges.minLength = changes.minLength;
2687
- }
2688
- if (changes.maxLength !== undefined) {
2689
- fieldChanges.maxLength = changes.maxLength;
2690
- }
2691
- if (changes.precision !== undefined) {
2692
- fieldChanges.precision = changes.precision;
2693
- }
2694
- if (changes.scale !== undefined) {
2695
- fieldChanges.scale = changes.scale;
2696
- }
2697
- if (changes.required !== undefined) {
2698
- fieldChanges.nullable = !changes.required;
2699
- }
2700
- if (changes.unique !== undefined) {
2701
- fieldChanges.unique = changes.unique;
2702
- }
2703
- if (changes.default !== undefined) {
2704
- fieldChanges.defaultValue = changes.default;
2705
- }
2706
- if (changes.enum !== undefined) {
2707
- fieldChanges.enumValues = changes.enum;
2708
- }
2709
- return schemaManager.modifyField(collection, fieldName, fieldChanges, { autoApply: true });
2710
- }
2711
- /**
2712
- * Create an index
2713
- */
2714
- async schemaCreateIndex(collection, fields, options) {
2715
- const schemaManager = this.getSchemaManager();
2716
- const normalizedFields = this.normalizeIndexFields(fields);
2717
- const indexName = (options === null || options === void 0 ? void 0 : options.name) || `idx_${collection}_${normalizedFields.map(f => f.name).join('_')}`;
2718
- return schemaManager.createIndex(collection, indexName, normalizedFields, {
2719
- autoApply: true,
2720
- unique: options === null || options === void 0 ? void 0 : options.unique,
2721
- sparse: options === null || options === void 0 ? void 0 : options.sparse,
2722
- sqlOptions: (options === null || options === void 0 ? void 0 : options.where) ? { where: options.where } : undefined,
2723
- mongoOptions: (options === null || options === void 0 ? void 0 : options.expireAfterSeconds) ? { expireAfterSeconds: options.expireAfterSeconds } : undefined,
2724
- });
2725
- }
2726
- /**
2727
- * Drop an index
2728
- */
2729
- async schemaDropIndex(collection, indexName) {
2730
- const schemaManager = this.getSchemaManager();
2731
- return schemaManager.dropIndex(collection, indexName, { autoApply: true, ifExists: true });
2732
- }
2733
- /**
2734
- * Add a constraint (SQL only)
2735
- */
2736
- async schemaAddConstraint(collection, constraint) {
2737
- const schemaManager = this.getSchemaManager();
2738
- return schemaManager.addConstraint(collection, constraint, { autoApply: true });
2739
- }
2740
- /**
2741
- * Drop a constraint (SQL only)
2742
- */
2743
- async schemaDropConstraint(collection, constraintName) {
2744
- const schemaManager = this.getSchemaManager();
2745
- return schemaManager.dropConstraint(collection, constraintName, { autoApply: true });
2746
- }
2747
- /**
2748
- * Rename a collection
2749
- */
2750
- async schemaRename(oldName, newName) {
2751
- const schemaManager = this.getSchemaManager();
2752
- return schemaManager.renameCollection(oldName, newName, { autoApply: true });
2753
- }
2754
- /**
2755
- * Check if collection exists
2756
- */
2757
- async schemaExists(name) {
2758
- const schemaManager = this.getSchemaManager();
2759
- return schemaManager.collectionExists(name);
2760
- }
2761
- /**
2762
- * List all collections
2763
- */
2764
- async schemaList(schemaName) {
2765
- const schemaManager = this.getSchemaManager();
2766
- return schemaManager.listCollections(schemaName);
2767
- }
2768
- /**
2769
- * Describe a collection's schema
2770
- */
2771
- async schemaDescribe(name) {
2772
- const schemaManager = this.getSchemaManager();
2773
- return schemaManager.getCollectionSchema(name);
2774
- }
2775
- /**
2776
- * List indexes on a collection
2777
- */
2778
- async schemaListIndexes(collection) {
2779
- const schemaManager = this.getSchemaManager();
2780
- return schemaManager.listIndexes(collection);
2781
- }
2782
- // ==================== SCHEMA CONVERSION HELPERS ====================
2783
- /**
2784
- * Convert Mongoose-style schema definition to IFieldDefinition array
2785
- */
2786
- convertToFieldDefinitions(definition, timestamps) {
2787
- const fields = [];
2788
- for (const [name, config] of Object.entries(definition)) {
2789
- fields.push(this.convertFieldDefinition(name, config));
2790
- }
2791
- if (timestamps) {
2792
- fields.push({ name: 'created_at', type: 'timestamp', defaultValue: 'NOW()', nullable: false }, { name: 'updated_at', type: 'timestamp', defaultValue: 'NOW()', nullable: false });
2793
- }
2794
- return fields;
2795
- }
2796
- /**
2797
- * Convert a single field definition
2798
- */
2799
- convertFieldDefinition(name, config) {
2800
- // Handle shorthand: { name: 'string' }
2801
- if (typeof config === 'string') {
2802
- return { name, type: this.normalizeFieldType(config) };
2803
- }
2804
- // Validate autoIncrement only works with numeric types
2805
- if (config.autoIncrement) {
2806
- const normalizedType = this.normalizeFieldType(config.type);
2807
- const numericTypes = ['integer', 'int', 'bigint', 'smallint', 'number', 'float', 'double', 'decimal'];
2808
- if (!numericTypes.includes(normalizedType.toLowerCase())) {
2809
- throw new database_error_1.DatabaseError(`autoIncrement can only be used with numeric types (integer, bigint, number, etc.), but field '${name}' has type '${config.type}'`, enums_1.DatabaseErrorType.VALIDATION_ERROR);
2810
- }
2811
- }
2812
- // Handle full definition
2813
- return {
2814
- name,
2815
- type: this.normalizeFieldType(config.type),
2816
- nullable: config.required === undefined ? true : !config.required,
2817
- unique: config.unique,
2818
- primaryKey: config.primaryKey,
2819
- autoGenerate: config.autoIncrement,
2820
- defaultValue: config.default,
2821
- minLength: config.minLength,
2822
- maxLength: config.maxLength,
2823
- precision: config.precision,
2824
- scale: config.scale,
2825
- enumValues: config.enum,
2826
- comment: config.comment,
2827
- };
2828
- }
2829
- /**
2830
- * Normalize Mongoose-style type names to FieldType
2831
- */
2832
- normalizeFieldType(type) {
2833
- const typeMap = {
2834
- // String types
2835
- 'String': 'string',
2836
- // Numeric types
2837
- 'Number': 'double', // JS number is 64-bit float
2838
- 'Integer': 'integer', // 32-bit signed integer
2839
- 'BigInt': 'bigint', // 64-bit signed integer
2840
- 'Float': 'float', // 32-bit floating point
2841
- 'Double': 'double', // 64-bit floating point
2842
- 'Decimal': 'decimal', // Exact precision (for money)
2843
- // Other types
2844
- 'Boolean': 'boolean',
2845
- 'Date': 'datetime',
2846
- 'ObjectId': 'uuid',
2847
- 'Array': 'array',
2848
- 'Object': 'json',
2849
- 'Mixed': 'json',
2850
- };
2851
- return typeMap[type] || type;
2852
- }
2853
- /**
2854
- * Normalize index fields to IIndexFieldDefinition array
2855
- */
2856
- normalizeIndexFields(fields) {
2857
- if (fields.length === 0) {
2858
- return [];
2859
- }
2860
- // Check if first element is a string
2861
- if (typeof fields[0] === 'string') {
2862
- return fields.map(name => ({ name }));
2863
- }
2864
- return fields;
2865
- }
2866
- /**
2867
- * Get adapter by context key (used by DatabaseConnection)
2868
- * @internal
2869
- */
2870
- getAdapterByContextKey(contextKey) {
2871
- const adapter = this.adapters.get(contextKey);
2872
- if (!adapter) {
2873
- throw new database_error_1.DatabaseError(`No adapter found for context '${contextKey}'. Call connect() first.`, enums_1.DatabaseErrorType.CONNECTION_ERROR);
2874
- }
2875
- return adapter;
2876
- }
2877
- // ==================== DASHBOARD ====================
2878
- /**
2879
- * Fetch database dashboard metrics from logs
2880
- *
2881
- * @example
2882
- * ```ts
2883
- * const dashboard = await databases.fetchDashboard({
2884
- * product: 'my-product',
2885
- * database: 'my-database',
2886
- * env: 'production',
2887
- * });
2888
- * console.log(dashboard.dau, dashboard.activityTimeline);
2889
- * ```
2890
- */
2891
- async fetchDashboard(options) {
2892
- if (!this.config) {
2893
- throw new database_error_1.DatabaseError('DatabaseService not configured. Please provide config when initializing.', enums_1.DatabaseErrorType.CONFIGURATION_ERROR);
2894
- }
2895
- const { product, database, env } = options;
2896
- const { LogApiService } = await Promise.resolve().then(() => __importStar(require('../api/services/logsApi.service')));
2897
- const logsApi = new LogApiService(this.config.env_type);
2898
- try {
2899
- const dashboard = await logsApi.fetchDatabaseDashboard({
2900
- product_tag: product,
2901
- database_tag: database,
2902
- env,
2903
- }, {
2904
- workspace_id: this.config.workspace_id,
2905
- user_id: this.config.user_id,
2906
- public_key: this.config.public_key,
2907
- token: this.config.token,
2908
- });
2909
- return {
2910
- dau: dashboard.dau || { current: 0, previous: 0, change: 0 },
2911
- wau: dashboard.wau || { current: 0, previous: 0, change: 0 },
2912
- mau: dashboard.mau || { current: 0, previous: 0, change: 0 },
2913
- totalOperations: dashboard.totalOperations || 0,
2914
- successfulOperations: dashboard.successfulOperations || 0,
2915
- failedOperations: dashboard.failedOperations || 0,
2916
- newOperationsThisWeek: dashboard.newOperationsThisWeek || 0,
2917
- avgExecutionTime: dashboard.avgExecutionTime || { current: '0ms', previous: '0ms', change: 0 },
2918
- activityTimeline: dashboard.activityTimeline || [],
2919
- peakHours: dashboard.peakHours || [],
2920
- environmentBreakdown: dashboard.environmentBreakdown || [],
2921
- methodBreakdown: dashboard.methodBreakdown || [],
2922
- };
2923
- }
2924
- catch (error) {
2925
- throw new database_error_1.DatabaseError(`Failed to fetch database dashboard: ${error}`, enums_1.DatabaseErrorType.QUERY_ERROR);
2926
- }
2927
- }
2928
- }
2929
- exports.DatabaseService = DatabaseService;
2930
- /**
2931
- * Connection-scoped database interface.
2932
- * Provides isolated schema, query, and aggregation operations for a specific database/environment.
2933
- */
2934
- class DatabaseConnection {
2935
- constructor(service, database, env, product) {
2936
- this.service = service;
2937
- this._database = database;
2938
- this._env = env;
2939
- this._product = product;
2940
- this.contextKey = `${database}:${env}`;
2941
- this.triggerProcessor = new trigger_processor_1.TriggerProcessor({}, null);
2942
- }
2943
- /** Database tag */
2944
- get database() {
2945
- return this._database;
2946
- }
2947
- /** Environment slug */
2948
- get env() {
2949
- return this._env;
2950
- }
2951
- /** Product tag */
2952
- get product() {
2953
- return this._product;
2954
- }
2955
- /** Get the adapter for this connection */
2956
- getAdapter() {
2957
- return this.service.getAdapterByContextKey(this.contextKey);
2958
- }
2959
- /**
2960
- * Schema operations scoped to this connection
2961
- */
2962
- get schema() {
2963
- const adapter = () => this.getAdapter();
2964
- const service = this.service;
2965
- return {
2966
- create: async (name, definition, options) => {
2967
- var _a;
2968
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
2969
- const fields = service.convertToFieldDefinitions(definition, options === null || options === void 0 ? void 0 : options.timestamps);
2970
- const indexes = (_a = options === null || options === void 0 ? void 0 : options.indexes) === null || _a === void 0 ? void 0 : _a.map(idx => ({
2971
- name: idx.name || `idx_${name}_${Array.isArray(idx.fields) ? (typeof idx.fields[0] === 'string' ? idx.fields.join('_') : idx.fields.map((f) => f.name).join('_')) : idx.fields}`,
2972
- fields: service.normalizeIndexFields(idx.fields),
2973
- unique: idx.unique,
2974
- }));
2975
- return schemaManager.createCollection(name, fields, {
2976
- autoApply: true,
2977
- indexes,
2978
- sqlOptions: options === null || options === void 0 ? void 0 : options.sqlOptions,
2979
- mongoOptions: options === null || options === void 0 ? void 0 : options.mongoOptions,
2980
- dynamoOptions: options === null || options === void 0 ? void 0 : options.dynamoOptions,
2981
- cassandraOptions: options === null || options === void 0 ? void 0 : options.cassandraOptions,
2982
- });
2983
- },
2984
- drop: async (name, options) => {
2985
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
2986
- return schemaManager.dropCollection(name, {
2987
- autoApply: true,
2988
- ifExists: options === null || options === void 0 ? void 0 : options.ifExists,
2989
- cascade: options === null || options === void 0 ? void 0 : options.cascade,
2990
- });
2991
- },
2992
- addField: async (collection, fieldName, definition) => {
2993
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
2994
- const field = service.convertFieldDefinition(fieldName, definition);
2995
- return schemaManager.addField(collection, field, { autoApply: true });
2996
- },
2997
- dropField: async (collection, fieldName) => {
2998
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
2999
- return schemaManager.dropField(collection, fieldName, { autoApply: true });
3000
- },
3001
- renameField: async (collection, oldName, newName) => {
3002
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3003
- return schemaManager.renameField(collection, oldName, newName, { autoApply: true });
3004
- },
3005
- modifyField: async (collection, fieldName, changes) => {
3006
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3007
- const fieldChanges = {};
3008
- if (changes.type)
3009
- fieldChanges.type = service.normalizeFieldType(changes.type);
3010
- if (changes.minLength !== undefined)
3011
- fieldChanges.minLength = changes.minLength;
3012
- if (changes.maxLength !== undefined)
3013
- fieldChanges.maxLength = changes.maxLength;
3014
- if (changes.precision !== undefined)
3015
- fieldChanges.precision = changes.precision;
3016
- if (changes.scale !== undefined)
3017
- fieldChanges.scale = changes.scale;
3018
- if (changes.required !== undefined)
3019
- fieldChanges.nullable = !changes.required;
3020
- if (changes.unique !== undefined)
3021
- fieldChanges.unique = changes.unique;
3022
- if (changes.default !== undefined)
3023
- fieldChanges.defaultValue = changes.default;
3024
- if (changes.enum !== undefined)
3025
- fieldChanges.enumValues = changes.enum;
3026
- return schemaManager.modifyField(collection, fieldName, fieldChanges, { autoApply: true });
3027
- },
3028
- createIndex: async (collection, fields, options) => {
3029
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3030
- const normalizedFields = service.normalizeIndexFields(fields);
3031
- const indexName = (options === null || options === void 0 ? void 0 : options.name) || `idx_${collection}_${normalizedFields.map((f) => f.name).join('_')}`;
3032
- return schemaManager.createIndex(collection, indexName, normalizedFields, {
3033
- autoApply: true,
3034
- unique: options === null || options === void 0 ? void 0 : options.unique,
3035
- sparse: options === null || options === void 0 ? void 0 : options.sparse,
3036
- sqlOptions: (options === null || options === void 0 ? void 0 : options.where) ? { where: options.where } : undefined,
3037
- mongoOptions: (options === null || options === void 0 ? void 0 : options.expireAfterSeconds) ? { expireAfterSeconds: options.expireAfterSeconds } : undefined,
3038
- });
3039
- },
3040
- dropIndex: async (collection, indexName) => {
3041
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3042
- return schemaManager.dropIndex(collection, indexName, { autoApply: true, ifExists: true });
3043
- },
3044
- addConstraint: async (collection, constraint) => {
3045
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3046
- return schemaManager.addConstraint(collection, constraint, { autoApply: true });
3047
- },
3048
- dropConstraint: async (collection, constraintName) => {
3049
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3050
- return schemaManager.dropConstraint(collection, constraintName, { autoApply: true });
3051
- },
3052
- rename: async (oldName, newName) => {
3053
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3054
- return schemaManager.renameCollection(oldName, newName, { autoApply: true });
3055
- },
3056
- exists: async (name) => {
3057
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3058
- return schemaManager.collectionExists(name);
3059
- },
3060
- list: async (schemaName) => {
3061
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3062
- return schemaManager.listCollections(schemaName);
3063
- },
3064
- describe: async (name) => {
3065
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3066
- return schemaManager.getCollectionSchema(name);
3067
- },
3068
- indexes: async (collection) => {
3069
- const schemaManager = new schema_manager_1.SchemaManager(adapter());
3070
- return schemaManager.listIndexes(collection);
3071
- },
3072
- };
3073
- }
3074
- // Query operations scoped to this connection
3075
- query(options) {
3076
- return this.service.query(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3077
- }
3078
- insert(options) {
3079
- return this.service.insert(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3080
- }
3081
- update(options) {
3082
- return this.service.update(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3083
- }
3084
- delete(options) {
3085
- return this.service.delete(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3086
- }
3087
- upsert(options) {
3088
- return this.service.upsert(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3089
- }
3090
- raw(options) {
3091
- return this.service.raw(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3092
- }
3093
- // Aggregation operations scoped to this connection
3094
- count(options) {
3095
- return this.service.count(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3096
- }
3097
- sum(options) {
3098
- return this.service.sum(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3099
- }
3100
- avg(options) {
3101
- return this.service.avg(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3102
- }
3103
- min(options) {
3104
- return this.service.min(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3105
- }
3106
- max(options) {
3107
- return this.service.max(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3108
- }
3109
- aggregate(options) {
3110
- return this.service.aggregate(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3111
- }
3112
- groupBy(options) {
3113
- return this.service.groupBy(Object.assign(Object.assign({}, options), { database: this._database, env: this._env }));
3114
- }
3115
- /**
3116
- * Trigger operations scoped to this connection
3117
- */
3118
- get triggers() {
3119
- const connection = this;
3120
- return {
3121
- /**
3122
- * Create a trigger and store it on the backend
3123
- * @param data - Trigger configuration (tag should be just the trigger name, database tag is added automatically)
3124
- */
3125
- create: async (data) => {
3126
- var _a;
3127
- if (!connection._product) {
3128
- throw new Error('Product tag is required to create triggers. Use connect() with product parameter.');
3129
- }
3130
- // Auto-prefix with database tag if not already prefixed
3131
- const tag = ((_a = data.tag) === null || _a === void 0 ? void 0 : _a.includes(':')) ? data.tag : `${connection._database}:${data.tag}`;
3132
- return connection.service.createTrigger(connection._product, Object.assign(Object.assign({}, data), { tag }));
3133
- },
3134
- /**
3135
- * Update an existing trigger on the backend
3136
- * @param data - Trigger configuration
3137
- */
3138
- update: async (data) => {
3139
- var _a;
3140
- if (!connection._product) {
3141
- throw new Error('Product tag is required to update triggers. Use connect() with product parameter.');
3142
- }
3143
- const tag = ((_a = data.tag) === null || _a === void 0 ? void 0 : _a.includes(':')) ? data.tag : `${connection._database}:${data.tag}`;
3144
- return connection.service.updateTrigger(connection._product, Object.assign(Object.assign({}, data), { tag }));
3145
- },
3146
- /**
3147
- * Fetch a specific trigger from the backend
3148
- * @param triggerTag - The trigger tag (without database prefix)
3149
- */
3150
- fetch: async (triggerTag) => {
3151
- if (!connection._product) {
3152
- throw new Error('Product tag is required to fetch triggers. Use connect() with product parameter.');
3153
- }
3154
- const tag = triggerTag.includes(':') ? triggerTag : `${connection._database}:${triggerTag}`;
3155
- return connection.service.fetchTrigger(connection._product, tag);
3156
- },
3157
- /**
3158
- * Fetch all triggers for this database from the backend
3159
- * @deprecated Use list() instead
3160
- */
3161
- fetchAll: async () => {
3162
- if (!connection._product) {
3163
- throw new Error('Product tag is required to fetch triggers. Use connect() with product parameter.');
3164
- }
3165
- return connection.service.fetchTriggers(connection._product, connection._database);
3166
- },
3167
- /**
3168
- * List all triggers for this database from the backend
3169
- * @param options - Optional filters (table, event, enabled)
3170
- */
3171
- list: async (options) => {
3172
- if (!connection._product) {
3173
- throw new Error('Product tag is required to list triggers. Use connect() with product parameter.');
3174
- }
3175
- let triggers = await connection.service.fetchTriggers(connection._product, connection._database);
3176
- // Apply filters if provided
3177
- if (options === null || options === void 0 ? void 0 : options.table) {
3178
- triggers = triggers.filter(t => { var _a; return (_a = t.tables) === null || _a === void 0 ? void 0 : _a.includes(options.table); });
3179
- }
3180
- if (options === null || options === void 0 ? void 0 : options.event) {
3181
- triggers = triggers.filter(t => { var _a; return (_a = t.events) === null || _a === void 0 ? void 0 : _a.includes(options.event); });
3182
- }
3183
- if ((options === null || options === void 0 ? void 0 : options.enabled) !== undefined) {
3184
- triggers = triggers.filter(t => t.enabled === options.enabled);
3185
- }
3186
- return triggers;
3187
- },
3188
- /**
3189
- * Delete a trigger from the backend
3190
- * @param triggerTag - The trigger tag (without database prefix)
3191
- */
3192
- delete: async (triggerTag) => {
3193
- if (!connection._product) {
3194
- throw new Error('Product tag is required to delete triggers. Use connect() with product parameter.');
3195
- }
3196
- const tag = triggerTag.includes(':') ? triggerTag : `${connection._database}:${triggerTag}`;
3197
- await connection.service.deleteTrigger(connection._product, tag);
3198
- return true;
3199
- },
3200
- /**
3201
- * Register a trigger in memory for the current session (does not persist to backend)
3202
- * @deprecated Use create() for persistent triggers
3203
- */
3204
- register: (table, trigger) => {
3205
- connection.triggerProcessor.register(table, trigger);
3206
- },
3207
- /**
3208
- * Register multiple triggers in memory (does not persist to backend)
3209
- * @deprecated Use create() for persistent triggers
3210
- */
3211
- registerAll: (triggers) => {
3212
- connection.triggerProcessor.registerAll(triggers);
3213
- },
3214
- /**
3215
- * Unregister a trigger from memory
3216
- */
3217
- unregister: (table, triggerName) => {
3218
- return connection.triggerProcessor.unregister(table, triggerName);
3219
- },
3220
- /**
3221
- * Get all triggers for a table and event
3222
- */
3223
- getTriggersForEvent: (table, event) => {
3224
- return connection.triggerProcessor.getTriggersForEvent(table, event);
3225
- },
3226
- /**
3227
- * Execute all triggers for an event
3228
- */
3229
- execute: async (event, context) => {
3230
- return connection.triggerProcessor.executeTriggers(event, Object.assign(Object.assign({}, context), { database: connection._database, env: connection._env }));
3231
- },
3232
- /**
3233
- * Load triggers from the backend and register them in memory
3234
- */
3235
- load: async () => {
3236
- if (!connection._product) {
3237
- throw new Error('Product tag is required to load triggers. Use connect() with product parameter.');
3238
- }
3239
- const backendTriggers = await connection.service.fetchTriggers(connection._product, connection._database);
3240
- for (const trigger of backendTriggers) {
3241
- // Convert backend trigger format to ITriggerDefinition
3242
- const definition = {
3243
- name: trigger.tag,
3244
- description: trigger.description,
3245
- events: trigger.events, // TriggerEventType maps to TriggerEvent
3246
- tables: trigger.tables,
3247
- condition: trigger.condition,
3248
- actions: trigger.actions.map(action => (Object.assign(Object.assign({}, action.config), { type: action.type, name: action.name, condition: action.condition, timing: action.timing, retry: action.retry, timeout: action.timeout, continueOnError: action.continueOnError }))),
3249
- enabled: trigger.enabled,
3250
- priority: trigger.priority,
3251
- tags: trigger.tags,
3252
- };
3253
- // Register for all tables specified, or use '*' for all
3254
- const tables = trigger.tables && trigger.tables.length > 0 ? trigger.tables : ['*'];
3255
- for (const table of tables) {
3256
- connection.triggerProcessor.register(table, definition);
3257
- }
3258
- }
3259
- },
3260
- /**
3261
- * Set the Ductape instance for trigger actions
3262
- */
3263
- setDuctapeInstance: (instance) => {
3264
- connection.triggerProcessor.setDuctapeInstance(instance);
3265
- },
3266
- /**
3267
- * Get the trigger processor instance
3268
- */
3269
- getProcessor: () => {
3270
- return connection.triggerProcessor;
3271
- },
3272
- /**
3273
- * Trigger action builders
3274
- */
3275
- Trigger: trigger_processor_1.Trigger,
3276
- /**
3277
- * Trigger events enum
3278
- */
3279
- TriggerEvent: trigger_interface_1.TriggerEvent,
3280
- /**
3281
- * Trigger timing enum
3282
- */
3283
- TriggerTiming: trigger_interface_1.TriggerTiming,
3284
- /**
3285
- * Trigger action types enum
3286
- */
3287
- TriggerActionType: trigger_interface_1.TriggerActionType,
3288
- };
3289
- }
3290
- }
3291
- exports.DatabaseConnection = DatabaseConnection;
3292
- // Export singleton instance for convenience
3293
- exports.databaseService = new DatabaseService();
3294
- //# sourceMappingURL=databases.service.js.map