@miguelmorales13/nestkit 0.26.0 → 0.29.0

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 (289) hide show
  1. package/README.md +69 -0
  2. package/dist/alerts/alert-on-failure.decorator.d.ts +5 -0
  3. package/dist/alerts/alert-sinks.d.ts +29 -0
  4. package/dist/alerts/alerts.module.d.ts +19 -0
  5. package/dist/alerts/alerts.options.d.ts +1 -0
  6. package/dist/alerts/alerts.service.d.ts +28 -0
  7. package/dist/alerts/alerts.types.d.ts +66 -0
  8. package/dist/alerts/index.cjs +276 -0
  9. package/dist/alerts/index.d.ts +10 -0
  10. package/dist/alerts/index.js +276 -0
  11. package/dist/alerts/logger-with-alerts.d.ts +18 -0
  12. package/dist/alerts/process-guards.d.ts +21 -0
  13. package/dist/alerts/runtime.d.ts +4 -0
  14. package/dist/audit/index.cjs +13 -13
  15. package/dist/audit/index.js +2 -2
  16. package/dist/auth/index.cjs +21 -21
  17. package/dist/auth/index.js +3 -3
  18. package/dist/auth/oauth/index.cjs +101 -101
  19. package/dist/auth/oauth/index.js +3 -3
  20. package/dist/bootstrap/apply-defaults.d.ts +9 -0
  21. package/dist/bootstrap/index.cjs +7 -6
  22. package/dist/bootstrap/index.js +6 -5
  23. package/dist/chunk-33KFVAUZ.cjs +151 -0
  24. package/dist/chunk-3TUMVLPJ.js +14 -0
  25. package/dist/{chunk-PA24P76K.js → chunk-45SW7FBE.js} +1 -1
  26. package/dist/{chunk-RF75KC63.cjs → chunk-47IYXZHW.cjs} +2 -2
  27. package/dist/{chunk-TUNDBBQF.js → chunk-4WWOKZIO.js} +4 -4
  28. package/dist/{chunk-2DUEQKOI.js → chunk-5LVGCTJ3.js} +4 -4
  29. package/dist/chunk-A6YGIZCQ.cjs +14 -0
  30. package/dist/chunk-A7FI6HXV.js +40 -0
  31. package/dist/chunk-CU4FUIVJ.cjs +8 -0
  32. package/dist/{chunk-FH5UNWWW.cjs → chunk-D35TBVRO.cjs} +4 -4
  33. package/dist/{chunk-4MGIQFAJ.js → chunk-D3DDJWUD.js} +5 -0
  34. package/dist/chunk-DVGPEBUL.js +8 -0
  35. package/dist/{chunk-VKOPDDCC.js → chunk-ENZ7LQRE.js} +1 -1
  36. package/dist/{chunk-3AUOOEQO.cjs → chunk-F77X4QUN.cjs} +2 -2
  37. package/dist/chunk-FBNV5X6C.js +61 -0
  38. package/dist/{chunk-APUFKA4K.cjs → chunk-FDZQCLLK.cjs} +6 -6
  39. package/dist/{chunk-DYHSOULW.js → chunk-IGSNB5BX.js} +1 -1
  40. package/dist/chunk-IVWPA6QH.cjs +90 -0
  41. package/dist/{chunk-LSDY6ETG.cjs → chunk-JJKGQNGD.cjs} +5 -5
  42. package/dist/{chunk-ALIKVFOV.cjs → chunk-JRFE7NSO.cjs} +12 -4
  43. package/dist/{chunk-HVHYZXBB.cjs → chunk-KNU5RN3O.cjs} +3 -3
  44. package/dist/{chunk-52IOOHNX.cjs → chunk-KQPJCVN3.cjs} +26 -26
  45. package/dist/chunk-LGFHLAY3.cjs +61 -0
  46. package/dist/{chunk-2REOCMUD.cjs → chunk-LRX7AMSS.cjs} +6 -1
  47. package/dist/chunk-LU3HO7B3.js +151 -0
  48. package/dist/{chunk-4PFAKLT3.js → chunk-MUWHGBIB.js} +1 -1
  49. package/dist/{chunk-ZJMLEP5H.js → chunk-NJYLQDB3.js} +1 -1
  50. package/dist/{chunk-IFNYRZP2.js → chunk-OSRH6KYZ.js} +4 -4
  51. package/dist/{chunk-6RAPVLJM.js → chunk-OTE77ONL.js} +1 -1
  52. package/dist/chunk-UDACUMLO.cjs +40 -0
  53. package/dist/{chunk-PFHHLB7B.js → chunk-UGAAJRPO.js} +10 -2
  54. package/dist/{chunk-SPTDXUED.cjs → chunk-URLDTS2Q.cjs} +2 -2
  55. package/dist/{chunk-W2T2VFLC.cjs → chunk-VALDHJOO.cjs} +5 -5
  56. package/dist/chunk-WFCQDOSN.js +90 -0
  57. package/dist/consent/consent.interceptor.d.ts +20 -0
  58. package/dist/consent/consent.module.d.ts +25 -0
  59. package/dist/consent/consent.options.d.ts +30 -0
  60. package/dist/consent/consent.port.d.ts +17 -0
  61. package/dist/consent/consent.service.d.ts +44 -0
  62. package/dist/consent/guard/index.cjs +13 -0
  63. package/dist/consent/guard/index.d.ts +31 -0
  64. package/dist/consent/guard/index.js +13 -0
  65. package/dist/consent/index.cjs +271 -0
  66. package/dist/consent/index.d.ts +13 -0
  67. package/dist/consent/index.js +271 -0
  68. package/dist/consent/memory.store.d.ts +7 -0
  69. package/dist/consent/shared/index.cjs +11 -0
  70. package/dist/consent/shared/index.d.ts +19 -0
  71. package/dist/consent/shared/index.js +11 -0
  72. package/dist/consent/typeorm.store.d.ts +22 -0
  73. package/dist/crud/index.cjs +4 -4
  74. package/dist/crud/index.js +3 -3
  75. package/dist/database/postgres/index.cjs +3 -3
  76. package/dist/database/postgres/index.js +2 -2
  77. package/dist/database/supabase/index.cjs +3 -3
  78. package/dist/database/supabase/index.js +2 -2
  79. package/dist/database/typeorm/index.cjs +2 -2
  80. package/dist/database/typeorm/index.js +1 -1
  81. package/dist/devices/device-check.interceptor.d.ts +20 -0
  82. package/dist/devices/devices.module.d.ts +28 -0
  83. package/dist/devices/devices.options.d.ts +53 -0
  84. package/dist/devices/devices.port.d.ts +62 -0
  85. package/dist/devices/devices.service.d.ts +58 -0
  86. package/dist/devices/index.cjs +327 -0
  87. package/dist/devices/index.d.ts +8 -0
  88. package/dist/devices/index.js +327 -0
  89. package/dist/devices/memory.store.d.ts +12 -0
  90. package/dist/email/index.cjs +2 -2
  91. package/dist/email/index.js +1 -1
  92. package/dist/email/nodemailer/index.cjs +2 -2
  93. package/dist/email/nodemailer/index.js +1 -1
  94. package/dist/email/resend/index.cjs +2 -2
  95. package/dist/email/resend/index.js +1 -1
  96. package/dist/entities/index.cjs +1 -1
  97. package/dist/entities/index.js +1 -1
  98. package/dist/errors/index.cjs +7 -7
  99. package/dist/errors/index.js +7 -7
  100. package/dist/events/buses.d.ts +27 -0
  101. package/dist/events/events.controller.d.ts +15 -0
  102. package/dist/events/events.module.d.ts +29 -0
  103. package/dist/events/events.options.d.ts +50 -0
  104. package/dist/events/events.service.d.ts +49 -0
  105. package/dist/events/events.types.d.ts +77 -0
  106. package/dist/events/index.cjs +557 -0
  107. package/dist/events/index.d.ts +10 -0
  108. package/dist/events/index.js +557 -0
  109. package/dist/events/memory-ticket.store.d.ts +9 -0
  110. package/dist/google-business/google-business-http.d.ts +41 -0
  111. package/dist/google-business/google-business.errors.d.ts +75 -0
  112. package/dist/google-business/google-business.mappers.d.ts +52 -0
  113. package/dist/google-business/google-business.module.d.ts +26 -0
  114. package/dist/google-business/google-business.options.d.ts +40 -0
  115. package/dist/google-business/google-business.ports.d.ts +18 -0
  116. package/dist/google-business/google-business.service.d.ts +120 -0
  117. package/dist/google-business/google-business.types.d.ts +155 -0
  118. package/dist/google-business/index.cjs +1025 -0
  119. package/dist/google-business/index.d.ts +15 -0
  120. package/dist/google-business/index.js +1025 -0
  121. package/dist/google-business/testing/google-simulator.d.ts +61 -0
  122. package/dist/hardening/body-limits.d.ts +24 -0
  123. package/dist/hardening/http.types.d.ts +26 -0
  124. package/dist/hardening/index.cjs +179 -0
  125. package/dist/hardening/index.d.ts +19 -0
  126. package/dist/hardening/index.js +179 -0
  127. package/dist/hardening/memory-rate-limit.store.d.ts +10 -0
  128. package/dist/hardening/origin-secret.d.ts +29 -0
  129. package/dist/hardening/rate-limit.decorator.d.ts +8 -0
  130. package/dist/hardening/rate-limit.guard.d.ts +18 -0
  131. package/dist/hardening/rate-limit.module.d.ts +23 -0
  132. package/dist/hardening/rate-limit.options.d.ts +35 -0
  133. package/dist/hardening/rate-limit.port.d.ts +11 -0
  134. package/dist/hardening/redis-rate-limit.store.d.ts +23 -0
  135. package/dist/hardening/trust-proxy.d.ts +22 -0
  136. package/dist/health/health.controller.d.ts +32 -0
  137. package/dist/health/health.module.d.ts +15 -0
  138. package/dist/health/health.options.d.ts +24 -0
  139. package/dist/health/index.cjs +103 -0
  140. package/dist/health/index.d.ts +5 -0
  141. package/dist/health/index.js +103 -0
  142. package/dist/i18n/index.cjs +3 -3
  143. package/dist/i18n/index.js +2 -2
  144. package/dist/idempotency/idempotency.interceptor.d.ts +1 -0
  145. package/dist/idempotency/idempotency.options.d.ts +15 -0
  146. package/dist/idempotency/index.cjs +214 -7
  147. package/dist/idempotency/index.d.ts +5 -0
  148. package/dist/idempotency/index.js +210 -3
  149. package/dist/idempotency/no-idempotency.decorator.d.ts +8 -0
  150. package/dist/idempotency/postgres.store.d.ts +49 -0
  151. package/dist/idempotency/redis.store.d.ts +59 -0
  152. package/dist/index.cjs +21 -20
  153. package/dist/index.js +33 -32
  154. package/dist/invoicing/index.cjs +2 -2
  155. package/dist/invoicing/index.js +1 -1
  156. package/dist/jobs/defer-job.d.ts +10 -0
  157. package/dist/jobs/index.cjs +318 -0
  158. package/dist/jobs/index.d.ts +8 -0
  159. package/dist/jobs/index.js +318 -0
  160. package/dist/jobs/jobs-admin.controller.d.ts +18 -0
  161. package/dist/jobs/jobs.module.d.ts +33 -0
  162. package/dist/jobs/jobs.options.d.ts +62 -0
  163. package/dist/jobs/jobs.service.d.ts +53 -0
  164. package/dist/jobs/jobs.sql.d.ts +11 -0
  165. package/dist/media/index.cjs +14 -14
  166. package/dist/media/index.js +1 -1
  167. package/dist/meta/index.cjs +3 -3
  168. package/dist/meta/index.js +1 -1
  169. package/dist/notifications/index.cjs +375 -0
  170. package/dist/notifications/index.d.ts +8 -0
  171. package/dist/notifications/index.js +375 -0
  172. package/dist/notifications/memory.stores.d.ts +23 -0
  173. package/dist/notifications/notifications.controller.d.ts +11 -0
  174. package/dist/notifications/notifications.module.d.ts +31 -0
  175. package/dist/notifications/notifications.options.d.ts +33 -0
  176. package/dist/notifications/notifications.port.d.ts +97 -0
  177. package/dist/notifications/notifier.service.d.ts +31 -0
  178. package/dist/payments/connect/credentials-cipher.d.ts +14 -0
  179. package/dist/payments/connect/mercadopago-refund.d.ts +118 -0
  180. package/dist/payments/connect/mercadopago-signature.d.ts +6 -0
  181. package/dist/payments/connect/online-checkout.d.ts +69 -0
  182. package/dist/payments/connect/rejection.d.ts +7 -0
  183. package/dist/payments/connect/status.d.ts +20 -0
  184. package/dist/payments/connect/terminal-connections.d.ts +291 -0
  185. package/dist/payments/index.cjs +908 -10
  186. package/dist/payments/index.d.ts +10 -0
  187. package/dist/payments/index.js +900 -2
  188. package/dist/pinterest/index.cjs +3 -3
  189. package/dist/pinterest/index.js +1 -1
  190. package/dist/privacy/anonymizer.d.ts +14 -0
  191. package/dist/privacy/index.cjs +768 -0
  192. package/dist/privacy/index.d.ts +13 -0
  193. package/dist/privacy/index.js +768 -0
  194. package/dist/privacy/memory.store.d.ts +15 -0
  195. package/dist/privacy/privacy.module.d.ts +30 -0
  196. package/dist/privacy/privacy.options.d.ts +43 -0
  197. package/dist/privacy/privacy.port.d.ts +25 -0
  198. package/dist/privacy/privacy.service.d.ts +69 -0
  199. package/dist/privacy/privacy.types.d.ts +125 -0
  200. package/dist/privacy/sql.d.ts +7 -0
  201. package/dist/privacy/sql.store.d.ts +21 -0
  202. package/dist/privacy/zip.d.ts +23 -0
  203. package/dist/push/index.cjs +13 -13
  204. package/dist/push/index.js +5 -5
  205. package/dist/resilience/alert-channels.d.ts +39 -0
  206. package/dist/resilience/alert-errors.interceptor.d.ts +10 -0
  207. package/dist/resilience/alert-on-failure.decorator.d.ts +10 -0
  208. package/dist/resilience/alert.service.d.ts +77 -0
  209. package/dist/resilience/index.cjs +863 -0
  210. package/dist/resilience/index.d.ts +18 -0
  211. package/dist/resilience/index.js +863 -0
  212. package/dist/resilience/memory-alert-store.d.ts +26 -0
  213. package/dist/resilience/provider-health.controller.d.ts +14 -0
  214. package/dist/resilience/provider-unavailable.exception.d.ts +11 -0
  215. package/dist/resilience/resilience.module.d.ts +34 -0
  216. package/dist/resilience/resilience.options.d.ts +28 -0
  217. package/dist/resilience/resilience.types.d.ts +167 -0
  218. package/dist/resilience/resilient-fetch.d.ts +38 -0
  219. package/dist/resilience/runtime.d.ts +24 -0
  220. package/dist/resilience/typeorm/alert.entity.d.ts +21 -0
  221. package/dist/resilience/typeorm/index.cjs +102 -0
  222. package/dist/resilience/typeorm/index.d.ts +3 -0
  223. package/dist/resilience/typeorm/index.js +102 -0
  224. package/dist/resilience/typeorm/typeorm-alert-store.d.ts +39 -0
  225. package/dist/resilience/validate-destination.d.ts +63 -0
  226. package/dist/response/index.cjs +3 -3
  227. package/dist/response/index.js +2 -2
  228. package/dist/scheduling/cron-lock.service.d.ts +36 -0
  229. package/dist/scheduling/cron-unico.decorator.d.ts +27 -0
  230. package/dist/scheduling/fallback.store.d.ts +34 -0
  231. package/dist/scheduling/index.cjs +392 -0
  232. package/dist/scheduling/index.d.ts +18 -0
  233. package/dist/scheduling/index.js +392 -0
  234. package/dist/scheduling/lock-store.port.d.ts +19 -0
  235. package/dist/scheduling/memory.store.d.ts +15 -0
  236. package/dist/scheduling/redis.module.d.ts +31 -0
  237. package/dist/scheduling/redis.store.d.ts +24 -0
  238. package/dist/scheduling/scheduling.module.d.ts +24 -0
  239. package/dist/scheduling/scheduling.options.d.ts +27 -0
  240. package/dist/scheduling/sql.store.d.ts +26 -0
  241. package/dist/secrets/index.cjs +274 -0
  242. package/dist/secrets/index.d.ts +8 -0
  243. package/dist/secrets/index.js +274 -0
  244. package/dist/secrets/secrets.errors.d.ts +6 -0
  245. package/dist/secrets/secrets.module.d.ts +21 -0
  246. package/dist/secrets/secrets.options.d.ts +32 -0
  247. package/dist/secrets/secrets.service.d.ts +54 -0
  248. package/dist/secrets/secrets.transformer.d.ts +33 -0
  249. package/dist/security/hash.d.ts +8 -0
  250. package/dist/security/index.cjs +27 -35
  251. package/dist/security/index.d.ts +5 -0
  252. package/dist/security/index.js +24 -32
  253. package/dist/security/mask.d.ts +22 -0
  254. package/dist/security/signed-grant.d.ts +30 -0
  255. package/dist/storage/index.cjs +2 -2
  256. package/dist/storage/index.js +1 -1
  257. package/dist/stripe/index.cjs +7 -7
  258. package/dist/stripe/index.js +1 -1
  259. package/dist/telegram/index.cjs +2 -2
  260. package/dist/telegram/index.js +1 -1
  261. package/dist/tenancy/app-role.d.ts +24 -0
  262. package/dist/tenancy/db-helpers.d.ts +12 -0
  263. package/dist/tenancy/index.cjs +205 -0
  264. package/dist/tenancy/index.d.ts +14 -0
  265. package/dist/tenancy/index.js +205 -0
  266. package/dist/tenancy/pg/index.cjs +34 -0
  267. package/dist/tenancy/pg/index.d.ts +2 -0
  268. package/dist/tenancy/pg/index.js +34 -0
  269. package/dist/tenancy/pg/with-tenant.d.ts +23 -0
  270. package/dist/tenancy/request-context.d.ts +18 -0
  271. package/dist/tenancy/rls-guardrail.d.ts +38 -0
  272. package/dist/tenancy/scope.d.ts +5 -0
  273. package/dist/tenancy/tenancy.errors.d.ts +5 -0
  274. package/dist/tenancy/tenancy.middleware.d.ts +8 -0
  275. package/dist/tenancy/tenancy.module.d.ts +37 -0
  276. package/dist/tenancy/tenancy.options.d.ts +34 -0
  277. package/dist/tenancy/typeorm/index.cjs +41 -0
  278. package/dist/tenancy/typeorm/index.d.ts +2 -0
  279. package/dist/tenancy/typeorm/index.js +41 -0
  280. package/dist/tenancy/typeorm/with-tenant.d.ts +23 -0
  281. package/dist/tiktok/index.cjs +3 -3
  282. package/dist/tiktok/index.js +1 -1
  283. package/dist/tracking/index.cjs +3 -3
  284. package/dist/tracking/index.js +2 -2
  285. package/dist/umami/index.cjs +4 -4
  286. package/dist/umami/index.js +1 -1
  287. package/dist/whatsapp/index.cjs +2 -2
  288. package/dist/whatsapp/index.js +1 -1
  289. package/package.json +108 -3
@@ -0,0 +1,863 @@
1
+ import {
2
+ ValidationAppException
3
+ } from "../chunk-ZFIDAX7K.js";
4
+ import {
5
+ AppException
6
+ } from "../chunk-M3GQDRWR.js";
7
+ import "../chunk-VVMRZEIW.js";
8
+ import {
9
+ __decorateClass,
10
+ __decorateParam
11
+ } from "../chunk-D3DDJWUD.js";
12
+
13
+ // src/resilience/resilience.module.ts
14
+ import { Global, Module } from "@nestjs/common";
15
+ import { APP_INTERCEPTOR } from "@nestjs/core";
16
+
17
+ // src/resilience/alert-errors.interceptor.ts
18
+ import {
19
+ HttpException,
20
+ Injectable
21
+ } from "@nestjs/common";
22
+ import { catchError, throwError } from "rxjs";
23
+
24
+ // src/resilience/memory-alert-store.ts
25
+ import { randomUUID } from "crypto";
26
+ var MemoryAlertStore = class {
27
+ constructor() {
28
+ this.records = [];
29
+ }
30
+ async findOpen(key) {
31
+ return this.records.find(
32
+ (r) => r.resolvedAt === null && r.provider === key.provider && r.type === key.type && r.tenantId === (key.tenantId ?? null)
33
+ ) ?? null;
34
+ }
35
+ async create(input) {
36
+ const record = {
37
+ id: randomUUID(),
38
+ provider: input.provider,
39
+ type: input.type,
40
+ scope: input.scope,
41
+ tenantId: input.tenantId,
42
+ message: input.message,
43
+ details: input.details,
44
+ times: 1,
45
+ firstAt: input.at,
46
+ lastAt: input.at,
47
+ notifiedAt: null,
48
+ resolvedAt: null
49
+ };
50
+ this.records.push(record);
51
+ return record;
52
+ }
53
+ async touch(id, patch) {
54
+ const r = this.records.find((x) => x.id === id);
55
+ if (!r) throw new Error(`Alerta ${id} no existe`);
56
+ r.times += 1;
57
+ r.lastAt = patch.at;
58
+ r.message = patch.message;
59
+ r.details = { ...r.details, ...patch.details ?? {} };
60
+ return r;
61
+ }
62
+ async markNotified(id, at) {
63
+ const r = this.records.find((x) => x.id === id);
64
+ if (r) r.notifiedAt = at;
65
+ }
66
+ async listOpen(filter = {}) {
67
+ return this.records.filter(
68
+ (r) => r.resolvedAt === null && (!filter.provider || r.provider === filter.provider) && (!filter.tenantId || r.tenantId === filter.tenantId)
69
+ ).sort((a, b) => b.lastAt.getTime() - a.lastAt.getTime());
70
+ }
71
+ async resolve(ids, at) {
72
+ for (const r of this.records) if (ids.includes(r.id) && r.resolvedAt === null) r.resolvedAt = at;
73
+ }
74
+ async list(opts) {
75
+ const limit = Math.min(opts.limit ?? 30, 100);
76
+ const cursor = opts.cursor ? new Date(opts.cursor).getTime() : Infinity;
77
+ const rows = this.records.filter((r) => (!opts.onlyOpen || r.resolvedAt === null) && r.lastAt.getTime() < cursor).sort((a, b) => b.lastAt.getTime() - a.lastAt.getTime());
78
+ const items = rows.slice(0, limit);
79
+ return { items, next: rows.length > limit ? items.at(-1).lastAt.toISOString() : null };
80
+ }
81
+ };
82
+
83
+ // src/resilience/resilience.options.ts
84
+ var RESILIENCE_OPTIONS = /* @__PURE__ */ Symbol("RESILIENCE_OPTIONS");
85
+ var ALERT_STORE = /* @__PURE__ */ Symbol("ALERT_STORE");
86
+ var DEFAULT_RETRYABLE_STATUS = [408, 425, 429, 500, 502, 503, 504];
87
+ var DEFAULT_ERROR_CODE = "PROVIDER_UNAVAILABLE";
88
+ var DEFAULT_BACKOFF = {
89
+ baseMs: 400,
90
+ factor: 2,
91
+ maxMs: 3e4,
92
+ jitterMs: 100
93
+ };
94
+ function defaultMessage(_provider, name, info) {
95
+ const why = info.reason === "timeout" ? "tiempo agotado" : info.reason === "http" ? `HTTP ${info.status}` : "sin conexi\xF3n";
96
+ return `${name} no responde (${why}). Intenta de nuevo en un momento.`;
97
+ }
98
+ function resolveOptions(options = {}) {
99
+ const d = options.porDefecto ?? {};
100
+ const a = options.alertas ?? {};
101
+ return {
102
+ proveedores: options.proveedores ?? {},
103
+ porDefecto: {
104
+ ...d,
105
+ timeoutMs: d.timeoutMs ?? 15e3,
106
+ reintentos: d.reintentos ?? 2,
107
+ backoff: { ...DEFAULT_BACKOFF, ...d.backoff ?? {} }
108
+ },
109
+ alertas: {
110
+ almacen: a.almacen ?? new MemoryAlertStore(),
111
+ canales: a.canales ?? [],
112
+ ventanaDedupeMs: a.ventanaDedupeMs ?? 30 * 6e4,
113
+ topePorMinuto: a.topePorMinuto ?? 15,
114
+ origen: a.origen ?? `api \xB7 ${process.env["NODE_ENV"] ?? "development"}`,
115
+ interceptorGlobal: a.interceptorGlobal ?? false
116
+ },
117
+ rutaSalud: options.rutaSalud,
118
+ salud: options.salud ?? {},
119
+ codigoErrorProveedor: options.codigoErrorProveedor ?? DEFAULT_ERROR_CODE,
120
+ mensajeProveedor: options.mensajeProveedor ?? defaultMessage
121
+ };
122
+ }
123
+
124
+ // src/resilience/runtime.ts
125
+ var current = { options: resolveOptions(), sink: null, notifier: null };
126
+ var getRuntime = () => current;
127
+ function configureRuntime(options) {
128
+ current = { ...current, options };
129
+ }
130
+ function registerAlerts(sink, notifier) {
131
+ current = { ...current, sink, notifier };
132
+ }
133
+ function resetRuntime() {
134
+ current = { options: resolveOptions(), sink: null, notifier: null };
135
+ }
136
+
137
+ // src/resilience/alert-on-failure.decorator.ts
138
+ function errorInfo(e) {
139
+ if (e instanceof Error) return { name: e.name, message: e.message, stack: e.stack?.slice(0, 2500) };
140
+ return { message: String(e) };
141
+ }
142
+ function AlertarFallo(name) {
143
+ return (_target, _key, descriptor) => {
144
+ const original = descriptor.value;
145
+ descriptor.value = async function(...args) {
146
+ try {
147
+ return await original.apply(this, args);
148
+ } catch (e) {
149
+ const err = errorInfo(e);
150
+ getRuntime().notifier?.notify({
151
+ title: `Fall\xF3 el job \xAB${name}\xBB: ${err.message}`.slice(0, 200),
152
+ level: "error",
153
+ source: `job \xB7 ${process.env["NODE_ENV"] ?? "development"}`,
154
+ error: err,
155
+ dedupeKey: `job|${name}`
156
+ });
157
+ throw e;
158
+ }
159
+ };
160
+ };
161
+ }
162
+
163
+ // src/resilience/alert-errors.interceptor.ts
164
+ var AlertErrorsInterceptor = class {
165
+ intercept(ctx, next) {
166
+ return next.handle().pipe(
167
+ catchError((e) => {
168
+ const status = e instanceof HttpException ? e.getStatus() : 500;
169
+ if (status >= 500) {
170
+ const req = ctx.switchToHttp().getRequest();
171
+ const route = `${req?.method ?? "?"} ${req?.route?.path ?? "?"}`;
172
+ const err = errorInfo(e);
173
+ getRuntime().notifier?.notify({
174
+ title: `Error no controlado: ${err.message}`.slice(0, 200),
175
+ level: "error",
176
+ fields: { ruta: route, estado: status },
177
+ error: err,
178
+ dedupeKey: `err|${route}|${err.message}`
179
+ });
180
+ }
181
+ return throwError(() => e);
182
+ })
183
+ );
184
+ }
185
+ };
186
+ AlertErrorsInterceptor = __decorateClass([
187
+ Injectable()
188
+ ], AlertErrorsInterceptor);
189
+
190
+ // src/resilience/alert.service.ts
191
+ import { Inject, Injectable as Injectable2, Logger } from "@nestjs/common";
192
+ var ALERT_UNAVAILABLE = "unavailable";
193
+ var ALERT_CREDENTIALS = "credentials";
194
+ var AlertService = class {
195
+ constructor(store, options) {
196
+ this.store = store;
197
+ this.options = options;
198
+ this.log = new Logger("Alerts");
199
+ this.state = /* @__PURE__ */ new Map();
200
+ this.seen = /* @__PURE__ */ new Map();
201
+ this.sentAt = [];
202
+ /** Reloj; se reemplaza en pruebas. */
203
+ this.now = Date.now;
204
+ }
205
+ onModuleInit() {
206
+ registerAlerts(this, this);
207
+ }
208
+ onModuleDestroy() {
209
+ registerAlerts(null, null);
210
+ }
211
+ // ── ProviderSink (lo llama fetchResiliente) ─────────────────────────────────────────────
212
+ success(provider) {
213
+ const s = this.stateOf(provider);
214
+ const was = s.consecutiveFailures > 0;
215
+ s.lastSuccess = new Date(this.now());
216
+ s.consecutiveFailures = 0;
217
+ if (was) void this.recovered(provider).catch((e) => this.log.warn(`recovered: ${String(e)}`));
218
+ }
219
+ failure(provider, info) {
220
+ const s = this.stateOf(provider);
221
+ s.lastFailure = new Date(this.now());
222
+ s.consecutiveFailures += 1;
223
+ void this.report({
224
+ provider,
225
+ type: ALERT_UNAVAILABLE,
226
+ message: `${this.nameOf(provider)} no responde (${info.reason === "http" ? `HTTP ${info.status}` : info.reason}) tras ${info.attempts} intento(s).`,
227
+ details: { reason: info.reason, status: info.status, url: info.url, detail: info.detail },
228
+ tenantId: info.tenantId
229
+ }).catch((e) => this.log.warn(`report: ${String(e)}`));
230
+ }
231
+ credentials(provider, info) {
232
+ void this.report({
233
+ provider,
234
+ type: ALERT_CREDENTIALS,
235
+ message: `${this.nameOf(provider)} rechaz\xF3 las credenciales (HTTP ${info.status}).`,
236
+ details: { status: info.status, url: info.url },
237
+ tenantId: info.tenantId
238
+ }).catch((e) => this.log.warn(`report: ${String(e)}`));
239
+ }
240
+ // ── API ──────────────────────────────────────────────────────────────────────────────────
241
+ /** Abre la alerta o acumula sobre la abierta; avisa según la ventana. */
242
+ async report(a) {
243
+ try {
244
+ const at = new Date(this.now());
245
+ const open = await this.store.findOpen({ provider: a.provider, type: a.type, tenantId: a.tenantId });
246
+ const alert = open ? await this.store.touch(open.id, { message: a.message, details: a.details, at }) : await this.store.create({
247
+ provider: a.provider,
248
+ type: a.type,
249
+ scope: a.tenantId ? "tenant" : "platform",
250
+ tenantId: a.tenantId ?? null,
251
+ message: a.message,
252
+ details: a.details ?? {},
253
+ at
254
+ });
255
+ this.log.warn(`[${alert.provider}/${alert.type}] ${alert.message} (\xD7${alert.times})`);
256
+ const window = this.options.alertas.ventanaDedupeMs;
257
+ if (!alert.notifiedAt || at.getTime() - alert.notifiedAt.getTime() >= window) {
258
+ if (await this.dispatch(this.toMessage(alert, "open"))) await this.store.markNotified(alert.id, at);
259
+ }
260
+ } catch (e) {
261
+ this.log.error(`No se pudo registrar la alerta ${a.provider}/${a.type}: ${e.message}`);
262
+ }
263
+ }
264
+ /** El proveedor volvió: cierra sus alertas de los tipos dados y avisa una vez. */
265
+ async recovered(provider, types = [ALERT_UNAVAILABLE]) {
266
+ try {
267
+ const open = (await this.store.listOpen({ provider })).filter((x) => types.includes(x.type));
268
+ if (open.length === 0) return;
269
+ const at = new Date(this.now());
270
+ await this.store.resolve(open.map((x) => x.id), at);
271
+ for (const x of open) {
272
+ this.log.log(`[${x.provider}/${x.type}] resuelta tras ${x.times} aviso(s)`);
273
+ await this.dispatch(this.toMessage({ ...x, resolvedAt: at }, "resolved"));
274
+ }
275
+ } catch (e) {
276
+ this.log.error(`No se pudo cerrar la alerta de ${provider}: ${e.message}`);
277
+ }
278
+ }
279
+ /** El tenant arregló sus credenciales: cierra sus alertas de ese tipo. Nunca lanza. */
280
+ async resolveForTenant(tenantId, providers, type) {
281
+ try {
282
+ const open = (await this.store.listOpen({ tenantId })).filter(
283
+ (x) => x.type === type && providers.includes(x.provider)
284
+ );
285
+ if (open.length) await this.store.resolve(open.map((x) => x.id), new Date(this.now()));
286
+ } catch (e) {
287
+ this.log.error(`No se cerraron las alertas del tenant ${tenantId}: ${e.message}`);
288
+ }
289
+ }
290
+ openAlerts() {
291
+ return this.store.listOpen();
292
+ }
293
+ list(opts) {
294
+ if (!this.store.list) throw new Error("El AlertStore en uso no implementa list()");
295
+ return this.store.list(opts);
296
+ }
297
+ /** Cierre manual desde una pantalla de administración. */
298
+ async resolveManual(id) {
299
+ await this.store.resolve([id], new Date(this.now()));
300
+ }
301
+ stateOf(provider) {
302
+ let s = this.state.get(provider);
303
+ if (!s) this.state.set(provider, s = { lastSuccess: null, lastFailure: null, consecutiveFailures: 0 });
304
+ return s;
305
+ }
306
+ /**
307
+ * Aviso ad hoc (errores no controlados, jobs) sin pasar por el almacén. Dispara y olvida.
308
+ * Con `dedupeKey`, el mismo aviso sale a lo sumo una vez por ventana; lo omitido se cuenta en
309
+ * `repeated` del siguiente.
310
+ */
311
+ notify(message) {
312
+ void this.notifyNow(message).catch(() => void 0);
313
+ }
314
+ /** Versión esperable de {@link notify}; `true` si salió. Nunca rechaza. */
315
+ async notifyNow(message) {
316
+ try {
317
+ const { dedupeKey, ...msg } = message;
318
+ const t = this.now();
319
+ let repeated = 0;
320
+ if (dedupeKey) {
321
+ const prev = this.seen.get(dedupeKey);
322
+ if (prev && t - prev.at < this.options.alertas.ventanaDedupeMs) {
323
+ prev.skipped += 1;
324
+ return false;
325
+ }
326
+ repeated = prev?.skipped ?? 0;
327
+ }
328
+ const sent = await this.dispatch({ ...msg, repeated: repeated || void 0 });
329
+ if (sent && dedupeKey) {
330
+ this.seen.set(dedupeKey, { at: t, skipped: 0 });
331
+ if (this.seen.size > 200) {
332
+ for (const [k, v] of this.seen)
333
+ if (t - v.at >= this.options.alertas.ventanaDedupeMs) this.seen.delete(k);
334
+ }
335
+ }
336
+ return sent;
337
+ } catch {
338
+ return false;
339
+ }
340
+ }
341
+ // ── avisos ───────────────────────────────────────────────────────────────────────────────
342
+ nameOf(provider) {
343
+ return this.options.proveedores[provider]?.nombre ?? provider;
344
+ }
345
+ toMessage(a, state) {
346
+ const name = this.nameOf(a.provider);
347
+ const counter = a.times > 1 ? ` (\xD7${a.times})` : "";
348
+ return {
349
+ title: state === "open" ? `[ALERTA] ${name}: ${a.message}${counter}`.slice(0, 200) : `[RESUELTA] ${name} volvi\xF3 (${a.type}, ${a.times} fallo(s)).`,
350
+ text: a.message,
351
+ level: state === "resolved" ? "success" : a.type === ALERT_UNAVAILABLE ? "error" : "warn",
352
+ source: this.options.alertas.origen,
353
+ fields: { proveedor: a.provider, tipo: a.type, veces: a.times, ambito: a.scope },
354
+ alert: { ...a, state }
355
+ };
356
+ }
357
+ /** Manda a todos los canales respetando el tope por minuto. `true` si salió (aunque un canal falle). */
358
+ async dispatch(message) {
359
+ const channels = this.options.alertas.canales;
360
+ if (channels.length === 0) return true;
361
+ const t = this.now();
362
+ this.sentAt = this.sentAt.filter((x) => t - x < 6e4);
363
+ if (this.sentAt.length >= this.options.alertas.topePorMinuto) return false;
364
+ this.sentAt.push(t);
365
+ const full = { ...message, source: message.source ?? this.options.alertas.origen };
366
+ await Promise.all(
367
+ channels.map(
368
+ (c) => (
369
+ // Un canal caído no debe generar otra alerta ni tumbar a los demás.
370
+ c.send(full).catch((e) => this.log.error(`Canal de alertas fall\xF3: ${e.message}`))
371
+ )
372
+ )
373
+ );
374
+ return true;
375
+ }
376
+ };
377
+ AlertService = __decorateClass([
378
+ Injectable2(),
379
+ __decorateParam(0, Inject(ALERT_STORE)),
380
+ __decorateParam(1, Inject(RESILIENCE_OPTIONS))
381
+ ], AlertService);
382
+
383
+ // src/resilience/provider-health.controller.ts
384
+ import { timingSafeEqual } from "crypto";
385
+ import {
386
+ Controller,
387
+ Get,
388
+ Headers as Headers2,
389
+ Inject as Inject2,
390
+ NotFoundException,
391
+ Res,
392
+ UnauthorizedException
393
+ } from "@nestjs/common";
394
+ function tokenMatches(received, expected) {
395
+ if (!received) return false;
396
+ const a = Buffer.from(received);
397
+ const b = Buffer.from(expected);
398
+ if (a.length !== b.length) {
399
+ timingSafeEqual(a, Buffer.alloc(a.length));
400
+ return false;
401
+ }
402
+ return timingSafeEqual(a, b);
403
+ }
404
+ function createProviderHealthController(path) {
405
+ let ProviderHealthController = class {
406
+ constructor(alerts, options) {
407
+ this.alerts = alerts;
408
+ this.options = options;
409
+ }
410
+ async health(headers, res) {
411
+ const expected = this.options.salud.token;
412
+ if (!expected) throw new NotFoundException();
413
+ const header = (this.options.salud.cabecera ?? "x-health-token").toLowerCase();
414
+ if (!tokenMatches(headers[header], expected)) throw new UnauthorizedException();
415
+ const open = await this.alerts.openAlerts();
416
+ const keys = /* @__PURE__ */ new Set([...Object.keys(this.options.proveedores), ...open.map((a) => a.provider)]);
417
+ const providers = Object.fromEntries(
418
+ [...keys].map((p) => {
419
+ const st = this.alerts.stateOf(p);
420
+ const mine = open.filter((a) => a.provider === p);
421
+ const configured = this.options.proveedores[p]?.configurado?.() ?? true;
422
+ return [
423
+ p,
424
+ {
425
+ configured,
426
+ status: !configured ? "unconfigured" : mine.some((a) => a.scope === "platform") ? "degraded" : "ok",
427
+ lastSuccess: st.lastSuccess,
428
+ lastFailure: st.lastFailure,
429
+ consecutiveFailures: st.consecutiveFailures,
430
+ alerts: mine.length
431
+ }
432
+ ];
433
+ })
434
+ );
435
+ const ok = open.every((a) => a.scope !== "platform");
436
+ res.status(ok ? 200 : 503);
437
+ return {
438
+ ok,
439
+ providers,
440
+ alerts: open.map((a) => ({
441
+ id: a.id,
442
+ provider: a.provider,
443
+ type: a.type,
444
+ scope: a.scope,
445
+ tenantId: a.tenantId,
446
+ message: a.message,
447
+ times: a.times,
448
+ firstAt: a.firstAt,
449
+ lastAt: a.lastAt
450
+ })),
451
+ ...await this.options.salud.extra?.() ?? {}
452
+ };
453
+ }
454
+ };
455
+ __decorateClass([
456
+ Get(),
457
+ __decorateParam(0, Headers2()),
458
+ __decorateParam(1, Res({ passthrough: true }))
459
+ ], ProviderHealthController.prototype, "health", 1);
460
+ ProviderHealthController = __decorateClass([
461
+ Controller(path),
462
+ __decorateParam(1, Inject2(RESILIENCE_OPTIONS))
463
+ ], ProviderHealthController);
464
+ return ProviderHealthController;
465
+ }
466
+
467
+ // src/resilience/resilience.module.ts
468
+ var ResilienceModule = class {
469
+ static forRoot(options = {}) {
470
+ const resolved = resolveOptions(options);
471
+ return ResilienceModule.build(
472
+ [{ provide: RESILIENCE_OPTIONS, useFactory: () => ResilienceModule.install(resolved) }],
473
+ [],
474
+ options.rutaSalud,
475
+ resolved.alertas.interceptorGlobal
476
+ );
477
+ }
478
+ /**
479
+ * `rutaSalud` va aparte de la fábrica porque la ruta de un controlador se fija al decorarlo,
480
+ * antes de que la fábrica asíncrona corra. El resto (token incluido) sí viene de ella.
481
+ */
482
+ static forRootAsync(config) {
483
+ return ResilienceModule.build(
484
+ [
485
+ {
486
+ provide: RESILIENCE_OPTIONS,
487
+ useFactory: async (...args) => ResilienceModule.install(
488
+ resolveOptions({
489
+ ...await config.useFactory(...args)
490
+ })
491
+ ),
492
+ inject: config.inject ?? []
493
+ }
494
+ ],
495
+ config.imports ?? [],
496
+ config.rutaSalud,
497
+ config.interceptorGlobal ?? false
498
+ );
499
+ }
500
+ static install(resolved) {
501
+ configureRuntime(resolved);
502
+ return resolved;
503
+ }
504
+ static build(optionProviders, imports, healthPath, globalInterceptor) {
505
+ const providers = [
506
+ ...optionProviders,
507
+ {
508
+ provide: ALERT_STORE,
509
+ useFactory: (o) => o.alertas.almacen,
510
+ inject: [RESILIENCE_OPTIONS]
511
+ },
512
+ AlertService,
513
+ AlertErrorsInterceptor,
514
+ ...globalInterceptor ? [{ provide: APP_INTERCEPTOR, useExisting: AlertErrorsInterceptor }] : []
515
+ ];
516
+ const controllers = healthPath ? [createProviderHealthController(healthPath)] : [];
517
+ return {
518
+ module: ResilienceModule,
519
+ imports,
520
+ providers,
521
+ controllers,
522
+ exports: [RESILIENCE_OPTIONS, ALERT_STORE, AlertService, AlertErrorsInterceptor]
523
+ };
524
+ }
525
+ };
526
+ ResilienceModule = __decorateClass([
527
+ Global(),
528
+ Module({})
529
+ ], ResilienceModule);
530
+
531
+ // src/resilience/provider-unavailable.exception.ts
532
+ import { HttpStatus, Logger as Logger2 } from "@nestjs/common";
533
+ var log = new Logger2("ProviderUnavailable");
534
+ var ProviderUnavailableException = class extends AppException {
535
+ constructor(provider, info) {
536
+ const cfg = getRuntime().options;
537
+ const name = cfg.proveedores[provider]?.nombre ?? provider;
538
+ log.warn(
539
+ `${provider} no disponible: ${info.reason} status=${info.status ?? "-"} url=${info.url} intentos=${info.attempts}${info.detail ? ` detalle=${info.detail}` : ""}`
540
+ );
541
+ super(
542
+ cfg.codigoErrorProveedor,
543
+ cfg.mensajeProveedor(provider, name, info),
544
+ HttpStatus.BAD_GATEWAY,
545
+ { provider, reason: info.reason, status: info.status, attempts: info.attempts }
546
+ );
547
+ this.provider = provider;
548
+ }
549
+ };
550
+
551
+ // src/resilience/resilient-fetch.ts
552
+ var SIDE_EFFECT_FREE = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
553
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
554
+ function retryDelay(n, backoff, retryAfter) {
555
+ const asked = retryAfter ? Number(retryAfter) * 1e3 : NaN;
556
+ if (Number.isFinite(asked) && asked > 0) return Math.min(asked, backoff.maxMs);
557
+ const wait = backoff.baseMs * backoff.factor ** n + Math.floor(Math.random() * (backoff.jitterMs + 1));
558
+ return Math.min(wait, backoff.maxMs);
559
+ }
560
+ function hasIdempotencyHeader(headers) {
561
+ if (!headers) return false;
562
+ for (const k of new Headers(headers).keys()) if (/idempotency/i.test(k)) return true;
563
+ return false;
564
+ }
565
+ function stripQuery(url) {
566
+ try {
567
+ const u = new URL(url);
568
+ return `${u.origin}${u.pathname}`;
569
+ } catch {
570
+ return url.split("?")[0] ?? url;
571
+ }
572
+ }
573
+ function fetchResiliente(o) {
574
+ const resilient = async (input, init) => {
575
+ const { options } = getRuntime();
576
+ const cfg = options.proveedores[o.proveedor] ?? {};
577
+ const def = options.porDefecto;
578
+ const timeoutMs = o.timeoutMs ?? cfg.timeoutMs ?? def.timeoutMs;
579
+ const retries = o.reintentos ?? cfg.reintentos ?? def.reintentos;
580
+ const backoff = { ...def.backoff, ...cfg.backoff ?? {}, ...o.backoff ?? {} };
581
+ const retryable = new Set(o.statusReintentables ?? cfg.statusReintentables ?? def.statusReintentables ?? DEFAULT_RETRYABLE_STATUS);
582
+ const idempotent = o.idempotente ?? cfg.idempotente ?? def.idempotente ?? false;
583
+ const doFetch = o.fetchImpl ?? fetch;
584
+ const wait = o.sleep ?? sleep;
585
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
586
+ const method = (init?.method ?? "GET").toUpperCase();
587
+ const safe = SIDE_EFFECT_FREE.has(method) || idempotent || hasIdempotencyHeader(init?.headers);
588
+ const sink = getRuntime().sink;
589
+ for (let attempt = 0; ; attempt++) {
590
+ const signal = init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(timeoutMs)]) : AbortSignal.timeout(timeoutMs);
591
+ let res;
592
+ try {
593
+ res = await doFetch(input, { ...init, signal });
594
+ } catch (e) {
595
+ const err = e;
596
+ if (init?.signal?.aborted) throw e;
597
+ const reason = err.name === "TimeoutError" || err.name === "AbortError" ? "timeout" : "network";
598
+ const info2 = {
599
+ reason,
600
+ attempts: attempt + 1,
601
+ url: stripQuery(url),
602
+ tenantId: o.tenantId,
603
+ detail: err.message
604
+ };
605
+ if (safe && attempt < retries) {
606
+ await wait(retryDelay(attempt, backoff));
607
+ continue;
608
+ }
609
+ sink?.failure(o.proveedor, { ...info2, tenantId: void 0 });
610
+ throw new ProviderUnavailableException(o.proveedor, info2);
611
+ }
612
+ if (retryable.has(res.status) && safe && attempt < retries) {
613
+ await res.body?.cancel().catch(() => void 0);
614
+ await wait(retryDelay(attempt, backoff, res.headers.get("retry-after")));
615
+ continue;
616
+ }
617
+ const info = {
618
+ reason: "http",
619
+ status: res.status,
620
+ attempts: attempt + 1,
621
+ url: stripQuery(url),
622
+ tenantId: o.tenantId
623
+ };
624
+ if (res.status >= 500 || res.status === 429) sink?.failure(o.proveedor, { ...info, tenantId: void 0 });
625
+ else if (res.status === 401 || res.status === 403) sink?.credentials(o.proveedor, info);
626
+ else sink?.success(o.proveedor);
627
+ return res;
628
+ }
629
+ };
630
+ return resilient;
631
+ }
632
+ async function withRetries(fn, isTransient, opts = {}) {
633
+ const retries = opts.reintentos ?? getRuntime().options.porDefecto.reintentos;
634
+ const backoff = { ...getRuntime().options.porDefecto.backoff, ...opts.backoff ?? {} };
635
+ const wait = opts.sleep ?? sleep;
636
+ for (let attempt = 0; ; attempt++) {
637
+ try {
638
+ return await fn();
639
+ } catch (e) {
640
+ if (!isTransient(e) || attempt >= retries) throw e;
641
+ await wait(retryDelay(attempt, backoff));
642
+ }
643
+ }
644
+ }
645
+
646
+ // src/resilience/alert-channels.ts
647
+ var WebhookAlertChannel = class {
648
+ constructor(config) {
649
+ this.config = config;
650
+ }
651
+ async send(message) {
652
+ const f = this.config.fetchImpl ?? fetch;
653
+ const body = this.config.body ? this.config.body(message) : { text: message.title, content: message.title, ...message };
654
+ await f(this.config.url, {
655
+ method: "POST",
656
+ headers: { "content-type": "application/json", ...this.config.headers ?? {} },
657
+ body: JSON.stringify(body),
658
+ signal: AbortSignal.timeout(this.config.timeoutMs ?? 5e3)
659
+ });
660
+ }
661
+ };
662
+ var EmailAlertChannel = class {
663
+ constructor(config) {
664
+ this.config = config;
665
+ }
666
+ async send(message) {
667
+ if (this.config.to.length === 0) return;
668
+ const detail = JSON.stringify(message.alert ?? message.fields ?? {}, null, 2);
669
+ await this.config.mailer.send({
670
+ to: this.config.to,
671
+ subject: message.title,
672
+ text: `${message.title}
673
+
674
+ ${message.text ?? ""}
675
+
676
+ ${detail}`
677
+ });
678
+ }
679
+ };
680
+ var MemoryAlertChannel = class {
681
+ constructor() {
682
+ this.messages = [];
683
+ }
684
+ async send(message) {
685
+ this.messages.push(message);
686
+ }
687
+ };
688
+
689
+ // src/resilience/validate-destination.ts
690
+ import { lookup } from "dns/promises";
691
+ var PRIVATE_V4 = [
692
+ ["10.0.0.0", 8],
693
+ ["172.16.0.0", 12],
694
+ ["192.168.0.0", 16],
695
+ ["127.0.0.0", 8],
696
+ ["169.254.0.0", 16],
697
+ ["0.0.0.0", 8],
698
+ ["100.64.0.0", 10],
699
+ // CGNAT (RFC 6598)
700
+ ["224.0.0.0", 4],
701
+ // multicast
702
+ ["240.0.0.0", 4],
703
+ // reservado
704
+ ["192.0.0.0", 24],
705
+ // IETF protocol assignments
706
+ ["198.18.0.0", 15]
707
+ // benchmarking
708
+ ];
709
+ function v4ToNumber(ip) {
710
+ const p = ip.split(".").map(Number);
711
+ return (p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]) >>> 0 >>> 0;
712
+ }
713
+ function inV4Range(ip, base, bits) {
714
+ const mask = bits === 0 ? 0 : 4294967295 << 32 - bits >>> 0;
715
+ return (v4ToNumber(ip) & mask) >>> 0 === (v4ToNumber(base) & mask) >>> 0;
716
+ }
717
+ var isV4Private = (ip) => PRIVATE_V4.some(([b, n]) => inV4Range(ip, b, n));
718
+ function hextets(ip) {
719
+ const parts = ip.split("::");
720
+ if (parts.length > 2) return null;
721
+ const head = parts[0] ? parts[0].split(":").filter(Boolean) : [];
722
+ const tail = parts.length > 1 && parts[1] ? parts[1].split(":").filter(Boolean) : [];
723
+ const missing = 8 - head.length - tail.length;
724
+ if (missing < 0) return null;
725
+ const groups = [...head, ...Array(parts.length > 1 ? missing : 0).fill("0"), ...tail];
726
+ if (groups.length !== 8) return null;
727
+ const nums = groups.map((h) => parseInt(h, 16));
728
+ return nums.some((n) => Number.isNaN(n)) ? null : nums;
729
+ }
730
+ function isV6Private(ip) {
731
+ const norm = ip.toLowerCase();
732
+ if (norm === "::1" || norm === "::") return true;
733
+ const mapped = norm.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
734
+ if (mapped) return isV4Private(mapped[1]);
735
+ const g = hextets(norm);
736
+ if (!g) return true;
737
+ const embedded = g.slice(0, 5).every((x) => x === 0) && g[5] === 65535 ? [g[6], g[7]] : g[0] === 100 && g[1] === 65435 && g.slice(2, 6).every((x) => x === 0) ? [g[6], g[7]] : null;
738
+ if (embedded) {
739
+ const v4 = `${embedded[0] >> 8}.${embedded[0] & 255}.${embedded[1] >> 8}.${embedded[1] & 255}`;
740
+ return isV4Private(v4);
741
+ }
742
+ if (g[0] >= 64512 && g[0] <= 65023) return true;
743
+ if (g[0] >= 65152 && g[0] <= 65215) return true;
744
+ if (g[0] >= 65280) return true;
745
+ return false;
746
+ }
747
+ function esIpPrivada(ip, family) {
748
+ const fam = family ?? (ip.includes(":") ? 6 : 4);
749
+ return fam === 4 ? isV4Private(ip) : isV6Private(ip);
750
+ }
751
+ function matchesIp(ip, entries) {
752
+ return entries.some((e) => {
753
+ const [base, bits] = e.split("/");
754
+ if (!base) return false;
755
+ if (bits === void 0) return base === ip;
756
+ if (ip.includes(":") || base.includes(":")) return false;
757
+ return inV4Range(ip, base, Number(bits));
758
+ });
759
+ }
760
+ function matchesHost(host, patterns) {
761
+ const h = host.toLowerCase();
762
+ return patterns.some((p) => {
763
+ const pat = p.toLowerCase();
764
+ return pat.startsWith("*.") ? h.endsWith(pat.slice(1)) && h.length > pat.length - 1 : h === pat;
765
+ });
766
+ }
767
+ async function resolveValidated(urlStr, policy) {
768
+ const strict = policy.estricto ?? process.env["NODE_ENV"] === "production";
769
+ const codes = {
770
+ invalido: policy.codigos?.invalido ?? "DESTINATION_INVALID",
771
+ noPermitido: policy.codigos?.noPermitido ?? "DESTINATION_NOT_ALLOWED",
772
+ noResuelve: policy.codigos?.noResuelve ?? "DESTINATION_UNRESOLVABLE"
773
+ };
774
+ const denied = () => new ValidationAppException("Ese destino no est\xE1 permitido.", {}, codes.noPermitido);
775
+ let url;
776
+ try {
777
+ url = new URL(urlStr);
778
+ } catch {
779
+ throw new ValidationAppException("Esa URL no es v\xE1lida.", { url: urlStr }, codes.invalido);
780
+ }
781
+ const protocols = policy.protocolos ?? (strict ? ["https:"] : ["http:", "https:"]);
782
+ if (!protocols.includes(url.protocol))
783
+ throw new ValidationAppException(
784
+ strict ? "El destino debe usar https." : "Protocolo no permitido.",
785
+ {},
786
+ codes.invalido
787
+ );
788
+ if (url.username || url.password) throw denied();
789
+ const host = url.hostname.replace(/^\[|\]$/g, "");
790
+ if (policy.puertosPermitidos?.length) {
791
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
792
+ if (!policy.puertosPermitidos.includes(port)) throw denied();
793
+ }
794
+ if (policy.hostsBloqueados?.length && matchesHost(host, policy.hostsBloqueados)) throw denied();
795
+ if (policy.hostsPermitidos?.length && !matchesHost(host, policy.hostsPermitidos)) throw denied();
796
+ if (strict && (host === "localhost" || host.endsWith(".localhost"))) throw denied();
797
+ let addresses;
798
+ try {
799
+ addresses = await (policy.resolver ?? ((h) => lookup(h, { all: true })))(host);
800
+ } catch {
801
+ throw new ValidationAppException("No pudimos resolver ese destino.", {}, codes.noResuelve);
802
+ }
803
+ if (addresses.length === 0) throw new ValidationAppException("No pudimos resolver ese destino.", {}, codes.noResuelve);
804
+ if (strict) {
805
+ const allowed = policy.ipsPermitidas ?? [];
806
+ if (addresses.some((a) => esIpPrivada(a.address, a.family) && !matchesIp(a.address, allowed))) throw denied();
807
+ }
808
+ return { url, addresses };
809
+ }
810
+ async function validarDestino(urlStr, policy = {}) {
811
+ return (await resolveValidated(urlStr, policy)).url;
812
+ }
813
+ var revalidarTrasRedirect = validarDestino;
814
+ function pinnedLookup(ip, family) {
815
+ return (_host, options, callback) => {
816
+ if (options?.all) callback(null, [{ address: ip, family }], void 0);
817
+ else callback(null, ip, family);
818
+ };
819
+ }
820
+ async function validarDestinoFijo(urlStr, policy = {}) {
821
+ const { url, addresses } = await resolveValidated(urlStr, policy);
822
+ const chosen = addresses[0];
823
+ const lookupFn = pinnedLookup(chosen.address, chosen.family);
824
+ let dispatcher;
825
+ try {
826
+ const mod = "undici";
827
+ const undici = await import(mod);
828
+ dispatcher = new undici.Agent({ connect: { lookup: lookupFn } });
829
+ } catch {
830
+ dispatcher = void 0;
831
+ }
832
+ return { url, address: chosen.address, family: chosen.family, lookup: lookupFn, dispatcher };
833
+ }
834
+ export {
835
+ ALERT_CREDENTIALS,
836
+ ALERT_STORE,
837
+ ALERT_UNAVAILABLE,
838
+ AlertErrorsInterceptor,
839
+ AlertService,
840
+ AlertarFallo,
841
+ DEFAULT_ERROR_CODE,
842
+ EmailAlertChannel,
843
+ MemoryAlertChannel,
844
+ MemoryAlertStore,
845
+ ProviderUnavailableException,
846
+ RESILIENCE_OPTIONS,
847
+ ResilienceModule,
848
+ WebhookAlertChannel,
849
+ configureRuntime,
850
+ createProviderHealthController,
851
+ esIpPrivada,
852
+ fetchResiliente,
853
+ getRuntime,
854
+ resetRuntime,
855
+ resolveOptions,
856
+ retryDelay,
857
+ revalidarTrasRedirect,
858
+ stripQuery,
859
+ tokenMatches,
860
+ validarDestino,
861
+ validarDestinoFijo,
862
+ withRetries
863
+ };