@miguelmorales13/nestkit 0.31.3 → 0.32.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 (59) hide show
  1. package/README.md +236 -0
  2. package/dist/chunk-2RQINZCR.cjs +17 -0
  3. package/dist/{chunk-LU3HO7B3.js → chunk-3WISEIHK.js} +4 -15
  4. package/dist/chunk-HMHUOXGB.cjs +63 -0
  5. package/dist/chunk-L2QK2HN5.js +17 -0
  6. package/dist/chunk-PBAPT3L5.js +63 -0
  7. package/dist/chunk-QVLTEABJ.cjs +248 -0
  8. package/dist/chunk-XKI3DJVA.js +248 -0
  9. package/dist/{chunk-33KFVAUZ.cjs → chunk-ZBOQKXGZ.cjs} +7 -18
  10. package/dist/index.cjs +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/payments/connect/terminal-connections.d.ts +7 -0
  13. package/dist/payments/index.cjs +36 -7
  14. package/dist/payments/index.js +31 -2
  15. package/dist/resilience/index.cjs +48 -262
  16. package/dist/resilience/index.js +19 -233
  17. package/dist/security/index.cjs +4 -2
  18. package/dist/security/index.js +5 -3
  19. package/dist/telephony/adapters/meta-whatsapp.telephony.d.ts +21 -0
  20. package/dist/telephony/adapters/simulated.telephony.d.ts +49 -0
  21. package/dist/telephony/adapters/twilio.telephony.d.ts +54 -0
  22. package/dist/telephony/index.cjs +2269 -0
  23. package/dist/telephony/index.d.ts +20 -0
  24. package/dist/telephony/index.js +2269 -0
  25. package/dist/telephony/provider-http.d.ts +35 -0
  26. package/dist/telephony/relay/access.d.ts +72 -0
  27. package/dist/telephony/relay/backend.d.ts +81 -0
  28. package/dist/telephony/relay/index.cjs +483 -0
  29. package/dist/telephony/relay/index.d.ts +9 -0
  30. package/dist/telephony/relay/index.js +483 -0
  31. package/dist/telephony/relay/server.d.ts +89 -0
  32. package/dist/telephony/relay/session.d.ts +100 -0
  33. package/dist/telephony/rules/call-limits.d.ts +48 -0
  34. package/dist/telephony/rules/call-token.d.ts +30 -0
  35. package/dist/telephony/rules/destination-policy.d.ts +21 -0
  36. package/dist/telephony/rules/dial-destination.d.ts +21 -0
  37. package/dist/telephony/rules/event-deduper.d.ts +15 -0
  38. package/dist/telephony/rules/handoff.d.ts +7 -0
  39. package/dist/telephony/rules/index.d.ts +20 -0
  40. package/dist/telephony/rules/opt-out.d.ts +32 -0
  41. package/dist/telephony/rules/phone.d.ts +9 -0
  42. package/dist/telephony/rules/provider-gate.d.ts +31 -0
  43. package/dist/telephony/rules/redact.d.ts +11 -0
  44. package/dist/telephony/rules/sanitize.d.ts +10 -0
  45. package/dist/telephony/rules/sliding-window.d.ts +10 -0
  46. package/dist/telephony/rules/ttl-cache.d.ts +14 -0
  47. package/dist/telephony/rules/usage-counter.d.ts +16 -0
  48. package/dist/telephony/telephony.errors.d.ts +46 -0
  49. package/dist/telephony/telephony.facade.d.ts +71 -0
  50. package/dist/telephony/telephony.module.d.ts +38 -0
  51. package/dist/telephony/telephony.options.d.ts +187 -0
  52. package/dist/telephony/telephony.port.d.ts +421 -0
  53. package/dist/telephony/telephony.registry.d.ts +24 -0
  54. package/dist/telephony/telephony.webhook.controller.d.ts +22 -0
  55. package/dist/telephony/telephony.webhooks.d.ts +53 -0
  56. package/dist/whatsapp/index.cjs +28 -0
  57. package/dist/whatsapp/index.js +28 -0
  58. package/dist/whatsapp/whatsapp-client.d.ts +5 -0
  59. package/package.json +12 -2
@@ -1,7 +1,8 @@
1
1
  import {
2
2
  readState,
3
3
  signState
4
- } from "../chunk-LU3HO7B3.js";
4
+ } from "../chunk-3WISEIHK.js";
5
+ import "../chunk-L2QK2HN5.js";
5
6
  import "../chunk-DQYAIQQ5.js";
6
7
  import "../chunk-5LVGCTJ3.js";
7
8
  import "../chunk-X4PQJZ4G.js";
@@ -1408,9 +1409,37 @@ var TerminalConnections = class {
1408
1409
  expira: tokens.expiresAt.toISOString()
1409
1410
  };
1410
1411
  const terminals = await this.adapter("mercadopago", credentials, signed.scopeId).listTerminals();
1411
- const id = await this.save(signed.scopeId, "mercadopago", credentials, terminals);
1412
+ const id = await this.renewMercadoPago(signed.scopeId, credentials, terminals) ?? await this.save(signed.scopeId, "mercadopago", credentials, terminals);
1412
1413
  return { scopeId: signed.scopeId, actorId: signed.actorId, id, terminals: terminals.length };
1413
1414
  }
1415
+ /**
1416
+ * Re-authorizing an account the tenant already connected renews that row (credentials, active) instead of piling up
1417
+ * copies of it; alias, primary flag and chosen terminal stay. Returns null — a new row is due — when the account is
1418
+ * new, or when it holds terminals that no row has taken yet (that is how a second terminal is added). A row still
1419
+ * waiting for its terminal is reused first.
1420
+ */
1421
+ async renewMercadoPago(scopeId, credentials, terminals) {
1422
+ if (!credentials.mpUserId) return null;
1423
+ const cipher = this.requireCipher();
1424
+ const same = this.sorted(await this.o.store.list(scopeId)).filter((r) => {
1425
+ if (r.provider !== "mercadopago") return false;
1426
+ try {
1427
+ return cipher.decryptJson(r.encryptedCredentials).mpUserId === credentials.mpUserId;
1428
+ } catch {
1429
+ return false;
1430
+ }
1431
+ });
1432
+ const only = terminals.length === 1 ? terminals[0] : null;
1433
+ const allTaken = terminals.every((t) => same.some((r) => r.terminalId === t.id));
1434
+ const row = (only && same.find((r) => r.terminalId === only.id)) ?? same.find((r) => !r.terminalId) ?? (allTaken ? same[0] : void 0);
1435
+ if (!row) return null;
1436
+ await this.o.store.update(row.id, {
1437
+ encryptedCredentials: cipher.encryptJson(credentials),
1438
+ active: true,
1439
+ ...only && !row.terminalId && { terminalId: only.id, terminalName: terminalName(only) }
1440
+ });
1441
+ return row.id;
1442
+ }
1414
1443
  /** Inserts a new row (never overwrites); the tenant's first terminal becomes primary on its own. */
1415
1444
  async save(scopeId, provider, credentials, terminals) {
1416
1445
  const cipher = this.requireCipher();
@@ -1,9 +1,23 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
4
3
 
5
4
 
6
- var _chunkQ5Y33L7Bcjs = require('../chunk-Q5Y33L7B.cjs');
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+ var _chunkQVLTEABJcjs = require('../chunk-QVLTEABJ.cjs');
17
+
18
+
19
+ var _chunkHDFPSA2Vcjs = require('../chunk-HDFPSA2V.cjs');
20
+ require('../chunk-Q5Y33L7B.cjs');
7
21
  require('../chunk-PNK5WMPP.cjs');
8
22
 
9
23
 
@@ -21,119 +35,6 @@ var _core = require('@nestjs/core');
21
35
 
22
36
  var _rxjs = require('rxjs');
23
37
 
24
- // src/resilience/memory-alert-store.ts
25
- var _crypto = require('crypto');
26
- var MemoryAlertStore = class {
27
- constructor() {
28
- this.records = [];
29
- }
30
- async findOpen(key) {
31
- return _nullishCoalesce(this.records.find(
32
- (r) => r.resolvedAt === null && r.provider === key.provider && r.type === key.type && r.tenantId === (_nullishCoalesce(key.tenantId, () => ( null)))
33
- ), () => ( null));
34
- }
35
- async create(input) {
36
- const record = {
37
- id: _crypto.randomUUID.call(void 0, ),
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, ..._nullishCoalesce(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(_nullishCoalesce(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 = _nullishCoalesce(options.porDefecto, () => ( {}));
100
- const a = _nullishCoalesce(options.alertas, () => ( {}));
101
- return {
102
- proveedores: _nullishCoalesce(options.proveedores, () => ( {})),
103
- porDefecto: {
104
- ...d,
105
- timeoutMs: _nullishCoalesce(d.timeoutMs, () => ( 15e3)),
106
- reintentos: _nullishCoalesce(d.reintentos, () => ( 2)),
107
- backoff: { ...DEFAULT_BACKOFF, ..._nullishCoalesce(d.backoff, () => ( {})) }
108
- },
109
- alertas: {
110
- almacen: _nullishCoalesce(a.almacen, () => ( new MemoryAlertStore())),
111
- canales: _nullishCoalesce(a.canales, () => ( [])),
112
- ventanaDedupeMs: _nullishCoalesce(a.ventanaDedupeMs, () => ( 30 * 6e4)),
113
- topePorMinuto: _nullishCoalesce(a.topePorMinuto, () => ( 15)),
114
- origen: _nullishCoalesce(a.origen, () => ( `api \xB7 ${_nullishCoalesce(process.env["NODE_ENV"], () => ( "development"))}`)),
115
- interceptorGlobal: _nullishCoalesce(a.interceptorGlobal, () => ( false))
116
- },
117
- rutaSalud: options.rutaSalud,
118
- salud: _nullishCoalesce(options.salud, () => ( {})),
119
- codigoErrorProveedor: _nullishCoalesce(options.codigoErrorProveedor, () => ( DEFAULT_ERROR_CODE)),
120
- mensajeProveedor: _nullishCoalesce(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
38
  // src/resilience/alert-on-failure.decorator.ts
138
39
  function errorInfo(e) {
139
40
  if (e instanceof Error) return { name: e.name, message: e.message, stack: _optionalChain([e, 'access', _ => _.stack, 'optionalAccess', _2 => _2.slice, 'call', _3 => _3(0, 2500)]) };
@@ -147,7 +48,7 @@ function AlertarFallo(name) {
147
48
  return await original.apply(this, args);
148
49
  } catch (e) {
149
50
  const err = errorInfo(e);
150
- _optionalChain([getRuntime, 'call', _4 => _4(), 'access', _5 => _5.notifier, 'optionalAccess', _6 => _6.notify, 'call', _7 => _7({
51
+ _optionalChain([_chunkQVLTEABJcjs.getRuntime.call(void 0, ), 'access', _4 => _4.notifier, 'optionalAccess', _5 => _5.notify, 'call', _6 => _6({
151
52
  title: `Fall\xF3 el job \xAB${name}\xBB: ${err.message}`.slice(0, 200),
152
53
  level: "error",
153
54
  source: `job \xB7 ${_nullishCoalesce(process.env["NODE_ENV"], () => ( "development"))}`,
@@ -168,9 +69,9 @@ var AlertErrorsInterceptor = class {
168
69
  const status = e instanceof _common.HttpException ? e.getStatus() : 500;
169
70
  if (status >= 500) {
170
71
  const req = ctx.switchToHttp().getRequest();
171
- const route = `${_nullishCoalesce(_optionalChain([req, 'optionalAccess', _8 => _8.method]), () => ( "?"))} ${_nullishCoalesce(_optionalChain([req, 'optionalAccess', _9 => _9.route, 'optionalAccess', _10 => _10.path]), () => ( "?"))}`;
72
+ const route = `${_nullishCoalesce(_optionalChain([req, 'optionalAccess', _7 => _7.method]), () => ( "?"))} ${_nullishCoalesce(_optionalChain([req, 'optionalAccess', _8 => _8.route, 'optionalAccess', _9 => _9.path]), () => ( "?"))}`;
172
73
  const err = errorInfo(e);
173
- _optionalChain([getRuntime, 'call', _11 => _11(), 'access', _12 => _12.notifier, 'optionalAccess', _13 => _13.notify, 'call', _14 => _14({
74
+ _optionalChain([_chunkQVLTEABJcjs.getRuntime.call(void 0, ), 'access', _10 => _10.notifier, 'optionalAccess', _11 => _11.notify, 'call', _12 => _12({
174
75
  title: `Error no controlado: ${err.message}`.slice(0, 200),
175
76
  level: "error",
176
77
  fields: { ruta: route, estado: status },
@@ -203,10 +104,10 @@ var AlertService = class {
203
104
  this.now = Date.now;
204
105
  }
205
106
  onModuleInit() {
206
- registerAlerts(this, this);
107
+ _chunkQVLTEABJcjs.registerAlerts.call(void 0, this, this);
207
108
  }
208
109
  onModuleDestroy() {
209
- registerAlerts(null, null);
110
+ _chunkQVLTEABJcjs.registerAlerts.call(void 0, null, null);
210
111
  }
211
112
  // ── ProviderSink (lo llama fetchResiliente) ─────────────────────────────────────────────
212
113
  success(provider) {
@@ -323,7 +224,7 @@ var AlertService = class {
323
224
  prev.skipped += 1;
324
225
  return false;
325
226
  }
326
- repeated = _nullishCoalesce(_optionalChain([prev, 'optionalAccess', _15 => _15.skipped]), () => ( 0));
227
+ repeated = _nullishCoalesce(_optionalChain([prev, 'optionalAccess', _13 => _13.skipped]), () => ( 0));
327
228
  }
328
229
  const sent = await this.dispatch({ ...msg, repeated: repeated || void 0 });
329
230
  if (sent && dedupeKey) {
@@ -340,7 +241,7 @@ var AlertService = class {
340
241
  }
341
242
  // ── avisos ───────────────────────────────────────────────────────────────────────────────
342
243
  nameOf(provider) {
343
- return _nullishCoalesce(_optionalChain([this, 'access', _16 => _16.options, 'access', _17 => _17.proveedores, 'access', _18 => _18[provider], 'optionalAccess', _19 => _19.nombre]), () => ( provider));
244
+ return _nullishCoalesce(_optionalChain([this, 'access', _14 => _14.options, 'access', _15 => _15.proveedores, 'access', _16 => _16[provider], 'optionalAccess', _17 => _17.nombre]), () => ( provider));
344
245
  }
345
246
  toMessage(a, state) {
346
247
  const name = this.nameOf(a.provider);
@@ -376,12 +277,12 @@ var AlertService = class {
376
277
  };
377
278
  AlertService = exports.AlertService = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
378
279
  _common.Injectable.call(void 0, ),
379
- _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, ALERT_STORE)),
380
- _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, RESILIENCE_OPTIONS))
280
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, _chunkQVLTEABJcjs.ALERT_STORE)),
281
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, _chunkQVLTEABJcjs.RESILIENCE_OPTIONS))
381
282
  ], AlertService);
382
283
 
383
284
  // src/resilience/provider-health.controller.ts
384
-
285
+ var _crypto = require('crypto');
385
286
 
386
287
 
387
288
 
@@ -418,7 +319,7 @@ function createProviderHealthController(path) {
418
319
  [...keys].map((p) => {
419
320
  const st = this.alerts.stateOf(p);
420
321
  const mine = open.filter((a) => a.provider === p);
421
- const configured = _nullishCoalesce(_optionalChain([this, 'access', _20 => _20.options, 'access', _21 => _21.proveedores, 'access', _22 => _22[p], 'optionalAccess', _23 => _23.configurado, 'optionalCall', _24 => _24()]), () => ( true));
322
+ const configured = _nullishCoalesce(_optionalChain([this, 'access', _18 => _18.options, 'access', _19 => _19.proveedores, 'access', _20 => _20[p], 'optionalAccess', _21 => _21.configurado, 'optionalCall', _22 => _22()]), () => ( true));
422
323
  return [
423
324
  p,
424
325
  {
@@ -448,7 +349,7 @@ function createProviderHealthController(path) {
448
349
  firstAt: a.firstAt,
449
350
  lastAt: a.lastAt
450
351
  })),
451
- ...await _asyncNullishCoalesce(await _optionalChain([this, 'access', _25 => _25.options, 'access', _26 => _26.salud, 'access', _27 => _27.extra, 'optionalCall', _28 => _28()]), async () => ( {}))
352
+ ...await _asyncNullishCoalesce(await _optionalChain([this, 'access', _23 => _23.options, 'access', _24 => _24.salud, 'access', _25 => _25.extra, 'optionalCall', _26 => _26()]), async () => ( {}))
452
353
  };
453
354
  }
454
355
  };
@@ -459,7 +360,7 @@ function createProviderHealthController(path) {
459
360
  ], ProviderHealthController.prototype, "health", 1);
460
361
  ProviderHealthController = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
461
362
  _common.Controller.call(void 0, path),
462
- _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, RESILIENCE_OPTIONS))
363
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, _chunkQVLTEABJcjs.RESILIENCE_OPTIONS))
463
364
  ], ProviderHealthController);
464
365
  return ProviderHealthController;
465
366
  }
@@ -467,9 +368,9 @@ function createProviderHealthController(path) {
467
368
  // src/resilience/resilience.module.ts
468
369
  var ResilienceModule = class {
469
370
  static forRoot(options = {}) {
470
- const resolved = resolveOptions(options);
371
+ const resolved = _chunkQVLTEABJcjs.resolveOptions.call(void 0, options);
471
372
  return ResilienceModule.build(
472
- [{ provide: RESILIENCE_OPTIONS, useFactory: () => ResilienceModule.install(resolved) }],
373
+ [{ provide: _chunkQVLTEABJcjs.RESILIENCE_OPTIONS, useFactory: () => ResilienceModule.install(resolved) }],
473
374
  [],
474
375
  options.rutaSalud,
475
376
  resolved.alertas.interceptorGlobal
@@ -483,9 +384,9 @@ var ResilienceModule = class {
483
384
  return ResilienceModule.build(
484
385
  [
485
386
  {
486
- provide: RESILIENCE_OPTIONS,
387
+ provide: _chunkQVLTEABJcjs.RESILIENCE_OPTIONS,
487
388
  useFactory: async (...args) => ResilienceModule.install(
488
- resolveOptions({
389
+ _chunkQVLTEABJcjs.resolveOptions.call(void 0, {
489
390
  ...await config.useFactory(...args)
490
391
  })
491
392
  ),
@@ -498,16 +399,16 @@ var ResilienceModule = class {
498
399
  );
499
400
  }
500
401
  static install(resolved) {
501
- configureRuntime(resolved);
402
+ _chunkQVLTEABJcjs.configureRuntime.call(void 0, resolved);
502
403
  return resolved;
503
404
  }
504
405
  static build(optionProviders, imports, healthPath, globalInterceptor) {
505
406
  const providers = [
506
407
  ...optionProviders,
507
408
  {
508
- provide: ALERT_STORE,
409
+ provide: _chunkQVLTEABJcjs.ALERT_STORE,
509
410
  useFactory: (o) => o.alertas.almacen,
510
- inject: [RESILIENCE_OPTIONS]
411
+ inject: [_chunkQVLTEABJcjs.RESILIENCE_OPTIONS]
511
412
  },
512
413
  AlertService,
513
414
  AlertErrorsInterceptor,
@@ -519,7 +420,7 @@ var ResilienceModule = class {
519
420
  imports,
520
421
  providers,
521
422
  controllers,
522
- exports: [RESILIENCE_OPTIONS, ALERT_STORE, AlertService, AlertErrorsInterceptor]
423
+ exports: [_chunkQVLTEABJcjs.RESILIENCE_OPTIONS, _chunkQVLTEABJcjs.ALERT_STORE, AlertService, AlertErrorsInterceptor]
523
424
  };
524
425
  }
525
426
  };
@@ -528,121 +429,6 @@ ResilienceModule = exports.ResilienceModule = _chunkLRX7AMSScjs.__decorateClass.
528
429
  _common.Module.call(void 0, {})
529
430
  ], ResilienceModule);
530
431
 
531
- // src/resilience/provider-unavailable.exception.ts
532
-
533
- var log = new (0, _common.Logger)("ProviderUnavailable");
534
- var ProviderUnavailableException = class extends _chunkQ5Y33L7Bcjs.AppException {
535
- constructor(provider, info) {
536
- const cfg = getRuntime().options;
537
- const name = _nullishCoalesce(_optionalChain([cfg, 'access', _29 => _29.proveedores, 'access', _30 => _30[provider], 'optionalAccess', _31 => _31.nombre]), () => ( provider));
538
- log.warn(
539
- `${provider} no disponible: ${info.reason} status=${_nullishCoalesce(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
- _common.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 (e3) {
570
- return _nullishCoalesce(url.split("?")[0], () => ( url));
571
- }
572
- }
573
- function fetchResiliente(o) {
574
- const resilient = async (input, init) => {
575
- const { options } = getRuntime();
576
- const cfg = _nullishCoalesce(options.proveedores[o.proveedor], () => ( {}));
577
- const def = options.porDefecto;
578
- const timeoutMs = _nullishCoalesce(_nullishCoalesce(o.timeoutMs, () => ( cfg.timeoutMs)), () => ( def.timeoutMs));
579
- const retries = _nullishCoalesce(_nullishCoalesce(o.reintentos, () => ( cfg.reintentos)), () => ( def.reintentos));
580
- const backoff = { ...def.backoff, ..._nullishCoalesce(cfg.backoff, () => ( {})), ..._nullishCoalesce(o.backoff, () => ( {})) };
581
- const retryable = new Set(_nullishCoalesce(_nullishCoalesce(_nullishCoalesce(o.statusReintentables, () => ( cfg.statusReintentables)), () => ( def.statusReintentables)), () => ( DEFAULT_RETRYABLE_STATUS)));
582
- const idempotent = _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(o.idempotente, () => ( cfg.idempotente)), () => ( def.idempotente)), () => ( false));
583
- const doFetch = _nullishCoalesce(o.fetchImpl, () => ( fetch));
584
- const wait = _nullishCoalesce(o.sleep, () => ( sleep));
585
- const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
586
- const method = (_nullishCoalesce(_optionalChain([init, 'optionalAccess', _32 => _32.method]), () => ( "GET"))).toUpperCase();
587
- const safe = SIDE_EFFECT_FREE.has(method) || idempotent || hasIdempotencyHeader(_optionalChain([init, 'optionalAccess', _33 => _33.headers]));
588
- const sink = getRuntime().sink;
589
- for (let attempt = 0; ; attempt++) {
590
- const signal = _optionalChain([init, 'optionalAccess', _34 => _34.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 (_optionalChain([init, 'optionalAccess', _35 => _35.signal, 'optionalAccess', _36 => _36.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
- _optionalChain([sink, 'optionalAccess', _37 => _37.failure, 'call', _38 => _38(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 _optionalChain([res, 'access', _39 => _39.body, 'optionalAccess', _40 => _40.cancel, 'call', _41 => _41(), 'access', _42 => _42.catch, 'call', _43 => _43(() => 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) _optionalChain([sink, 'optionalAccess', _44 => _44.failure, 'call', _45 => _45(o.proveedor, { ...info, tenantId: void 0 })]);
625
- else if (res.status === 401 || res.status === 403) _optionalChain([sink, 'optionalAccess', _46 => _46.credentials, 'call', _47 => _47(o.proveedor, info)]);
626
- else _optionalChain([sink, 'optionalAccess', _48 => _48.success, 'call', _49 => _49(o.proveedor)]);
627
- return res;
628
- }
629
- };
630
- return resilient;
631
- }
632
- async function withRetries(fn, isTransient, opts = {}) {
633
- const retries = _nullishCoalesce(opts.reintentos, () => ( getRuntime().options.porDefecto.reintentos));
634
- const backoff = { ...getRuntime().options.porDefecto.backoff, ..._nullishCoalesce(opts.backoff, () => ( {})) };
635
- const wait = _nullishCoalesce(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
432
  // src/resilience/alert-channels.ts
647
433
  var WebhookAlertChannel = class {
648
434
  constructor(config) {
@@ -767,15 +553,15 @@ function matchesHost(host, patterns) {
767
553
  async function resolveValidated(urlStr, policy) {
768
554
  const strict = _nullishCoalesce(policy.estricto, () => ( process.env["NODE_ENV"] === "production"));
769
555
  const codes = {
770
- invalido: _nullishCoalesce(_optionalChain([policy, 'access', _50 => _50.codigos, 'optionalAccess', _51 => _51.invalido]), () => ( "DESTINATION_INVALID")),
771
- noPermitido: _nullishCoalesce(_optionalChain([policy, 'access', _52 => _52.codigos, 'optionalAccess', _53 => _53.noPermitido]), () => ( "DESTINATION_NOT_ALLOWED")),
772
- noResuelve: _nullishCoalesce(_optionalChain([policy, 'access', _54 => _54.codigos, 'optionalAccess', _55 => _55.noResuelve]), () => ( "DESTINATION_UNRESOLVABLE"))
556
+ invalido: _nullishCoalesce(_optionalChain([policy, 'access', _27 => _27.codigos, 'optionalAccess', _28 => _28.invalido]), () => ( "DESTINATION_INVALID")),
557
+ noPermitido: _nullishCoalesce(_optionalChain([policy, 'access', _29 => _29.codigos, 'optionalAccess', _30 => _30.noPermitido]), () => ( "DESTINATION_NOT_ALLOWED")),
558
+ noResuelve: _nullishCoalesce(_optionalChain([policy, 'access', _31 => _31.codigos, 'optionalAccess', _32 => _32.noResuelve]), () => ( "DESTINATION_UNRESOLVABLE"))
773
559
  };
774
560
  const denied = () => new (0, _chunkHDFPSA2Vcjs.ValidationAppException)("Ese destino no est\xE1 permitido.", {}, codes.noPermitido);
775
561
  let url;
776
562
  try {
777
563
  url = new URL(urlStr);
778
- } catch (e4) {
564
+ } catch (e3) {
779
565
  throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)("Esa URL no es v\xE1lida.", { url: urlStr }, codes.invalido);
780
566
  }
781
567
  const protocols = _nullishCoalesce(policy.protocolos, () => ( (strict ? ["https:"] : ["http:", "https:"])));
@@ -787,17 +573,17 @@ async function resolveValidated(urlStr, policy) {
787
573
  );
788
574
  if (url.username || url.password) throw denied();
789
575
  const host = url.hostname.replace(/^\[|\]$/g, "");
790
- if (_optionalChain([policy, 'access', _56 => _56.puertosPermitidos, 'optionalAccess', _57 => _57.length])) {
576
+ if (_optionalChain([policy, 'access', _33 => _33.puertosPermitidos, 'optionalAccess', _34 => _34.length])) {
791
577
  const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
792
578
  if (!policy.puertosPermitidos.includes(port)) throw denied();
793
579
  }
794
- if (_optionalChain([policy, 'access', _58 => _58.hostsBloqueados, 'optionalAccess', _59 => _59.length]) && matchesHost(host, policy.hostsBloqueados)) throw denied();
795
- if (_optionalChain([policy, 'access', _60 => _60.hostsPermitidos, 'optionalAccess', _61 => _61.length]) && !matchesHost(host, policy.hostsPermitidos)) throw denied();
580
+ if (_optionalChain([policy, 'access', _35 => _35.hostsBloqueados, 'optionalAccess', _36 => _36.length]) && matchesHost(host, policy.hostsBloqueados)) throw denied();
581
+ if (_optionalChain([policy, 'access', _37 => _37.hostsPermitidos, 'optionalAccess', _38 => _38.length]) && !matchesHost(host, policy.hostsPermitidos)) throw denied();
796
582
  if (strict && (host === "localhost" || host.endsWith(".localhost"))) throw denied();
797
583
  let addresses;
798
584
  try {
799
585
  addresses = await (_nullishCoalesce(policy.resolver, () => ( ((h) => _promises.lookup.call(void 0, h, { all: true })))))(host);
800
- } catch (e5) {
586
+ } catch (e4) {
801
587
  throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)("No pudimos resolver ese destino.", {}, codes.noResuelve);
802
588
  }
803
589
  if (addresses.length === 0) throw new (0, _chunkHDFPSA2Vcjs.ValidationAppException)("No pudimos resolver ese destino.", {}, codes.noResuelve);
@@ -813,7 +599,7 @@ async function validarDestino(urlStr, policy = {}) {
813
599
  var revalidarTrasRedirect = validarDestino;
814
600
  function pinnedLookup(ip, family) {
815
601
  return (_host, options, callback) => {
816
- if (_optionalChain([options, 'optionalAccess', _62 => _62.all])) callback(null, [{ address: ip, family }], void 0);
602
+ if (_optionalChain([options, 'optionalAccess', _39 => _39.all])) callback(null, [{ address: ip, family }], void 0);
817
603
  else callback(null, ip, family);
818
604
  };
819
605
  }
@@ -826,7 +612,7 @@ async function validarDestinoFijo(urlStr, policy = {}) {
826
612
  const mod = "undici";
827
613
  const undici = await Promise.resolve().then(() => _interopRequireWildcard(require(mod)));
828
614
  dispatcher = new undici.Agent({ connect: { lookup: lookupFn } });
829
- } catch (e6) {
615
+ } catch (e5) {
830
616
  dispatcher = void 0;
831
617
  }
832
618
  return { url, address: chosen.address, family: chosen.family, lookup: lookupFn, dispatcher };
@@ -860,4 +646,4 @@ async function validarDestinoFijo(urlStr, policy = {}) {
860
646
 
861
647
 
862
648
 
863
- exports.ALERT_CREDENTIALS = ALERT_CREDENTIALS; exports.ALERT_STORE = ALERT_STORE; exports.ALERT_UNAVAILABLE = ALERT_UNAVAILABLE; exports.AlertErrorsInterceptor = AlertErrorsInterceptor; exports.AlertService = AlertService; exports.AlertarFallo = AlertarFallo; exports.DEFAULT_ERROR_CODE = DEFAULT_ERROR_CODE; exports.EmailAlertChannel = EmailAlertChannel; exports.MemoryAlertChannel = MemoryAlertChannel; exports.MemoryAlertStore = MemoryAlertStore; exports.ProviderUnavailableException = ProviderUnavailableException; exports.RESILIENCE_OPTIONS = RESILIENCE_OPTIONS; exports.ResilienceModule = ResilienceModule; exports.WebhookAlertChannel = WebhookAlertChannel; exports.configureRuntime = configureRuntime; exports.createProviderHealthController = createProviderHealthController; exports.esIpPrivada = esIpPrivada; exports.fetchResiliente = fetchResiliente; exports.getRuntime = getRuntime; exports.resetRuntime = resetRuntime; exports.resolveOptions = resolveOptions; exports.retryDelay = retryDelay; exports.revalidarTrasRedirect = revalidarTrasRedirect; exports.stripQuery = stripQuery; exports.tokenMatches = tokenMatches; exports.validarDestino = validarDestino; exports.validarDestinoFijo = validarDestinoFijo; exports.withRetries = withRetries;
649
+ exports.ALERT_CREDENTIALS = ALERT_CREDENTIALS; exports.ALERT_STORE = _chunkQVLTEABJcjs.ALERT_STORE; exports.ALERT_UNAVAILABLE = ALERT_UNAVAILABLE; exports.AlertErrorsInterceptor = AlertErrorsInterceptor; exports.AlertService = AlertService; exports.AlertarFallo = AlertarFallo; exports.DEFAULT_ERROR_CODE = _chunkQVLTEABJcjs.DEFAULT_ERROR_CODE; exports.EmailAlertChannel = EmailAlertChannel; exports.MemoryAlertChannel = MemoryAlertChannel; exports.MemoryAlertStore = _chunkQVLTEABJcjs.MemoryAlertStore; exports.ProviderUnavailableException = _chunkQVLTEABJcjs.ProviderUnavailableException; exports.RESILIENCE_OPTIONS = _chunkQVLTEABJcjs.RESILIENCE_OPTIONS; exports.ResilienceModule = ResilienceModule; exports.WebhookAlertChannel = WebhookAlertChannel; exports.configureRuntime = _chunkQVLTEABJcjs.configureRuntime; exports.createProviderHealthController = createProviderHealthController; exports.esIpPrivada = esIpPrivada; exports.fetchResiliente = _chunkQVLTEABJcjs.fetchResiliente; exports.getRuntime = _chunkQVLTEABJcjs.getRuntime; exports.resetRuntime = _chunkQVLTEABJcjs.resetRuntime; exports.resolveOptions = _chunkQVLTEABJcjs.resolveOptions; exports.retryDelay = _chunkQVLTEABJcjs.retryDelay; exports.revalidarTrasRedirect = revalidarTrasRedirect; exports.stripQuery = _chunkQVLTEABJcjs.stripQuery; exports.tokenMatches = tokenMatches; exports.validarDestino = validarDestino; exports.validarDestinoFijo = validarDestinoFijo; exports.withRetries = _chunkQVLTEABJcjs.withRetries;