@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,392 @@
1
+ import {
2
+ __decorateClass,
3
+ __decorateParam
4
+ } from "../chunk-D3DDJWUD.js";
5
+
6
+ // src/scheduling/lock-store.port.ts
7
+ var LOCK_STORE = /* @__PURE__ */ Symbol("LOCK_STORE");
8
+
9
+ // src/scheduling/memory.store.ts
10
+ var MemoryLockStore = class {
11
+ constructor(now = Date.now) {
12
+ this.now = now;
13
+ this.locks = /* @__PURE__ */ new Map();
14
+ }
15
+ async tryAcquire(key, token, ttlMs) {
16
+ const current = this.locks.get(key);
17
+ if (current && current.until > this.now()) return false;
18
+ this.locks.set(key, { token, until: this.now() + ttlMs });
19
+ return true;
20
+ }
21
+ async extend(key, token, ttlMs) {
22
+ const current = this.locks.get(key);
23
+ if (!current || current.token !== token || current.until <= this.now()) return false;
24
+ current.until = this.now() + ttlMs;
25
+ return true;
26
+ }
27
+ async release(key, token) {
28
+ const current = this.locks.get(key);
29
+ if (!current || current.token !== token) return false;
30
+ this.locks.delete(key);
31
+ return true;
32
+ }
33
+ };
34
+
35
+ // src/scheduling/redis.store.ts
36
+ var RELEASE_IF_OWNER = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) else return 0 end`;
37
+ var EXTEND_IF_OWNER = `if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('PEXPIRE', KEYS[1], ARGV[2]) else return 0 end`;
38
+ var RedisLockStore = class {
39
+ constructor(client, prefix = "nestkit:lock:") {
40
+ this.client = client;
41
+ this.prefix = prefix;
42
+ }
43
+ async tryAcquire(key, token, ttlMs) {
44
+ const reply = await this.client.set(this.prefix + key, token, "PX", Math.ceil(ttlMs), "NX");
45
+ return reply === "OK";
46
+ }
47
+ async extend(key, token, ttlMs) {
48
+ const reply = await this.client.eval(
49
+ EXTEND_IF_OWNER,
50
+ 1,
51
+ this.prefix + key,
52
+ token,
53
+ Math.ceil(ttlMs)
54
+ );
55
+ return Number(reply) === 1;
56
+ }
57
+ async release(key, token) {
58
+ const reply = await this.client.eval(RELEASE_IF_OWNER, 1, this.prefix + key, token);
59
+ return Number(reply) === 1;
60
+ }
61
+ };
62
+
63
+ // src/scheduling/sql.store.ts
64
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
65
+ function checkTable(table) {
66
+ if (!IDENTIFIER.test(table)) throw new Error(`SqlLockStore: invalid table name "${table}"`);
67
+ return table;
68
+ }
69
+ var SqlLockStore = class _SqlLockStore {
70
+ constructor(query, options = {}) {
71
+ this.query = query;
72
+ this.table = checkTable(options.table ?? "cron_lock");
73
+ }
74
+ static createTableSql(table = "cron_lock") {
75
+ return `CREATE TABLE IF NOT EXISTS ${checkTable(table)} (
76
+ name text PRIMARY KEY,
77
+ owner text NOT NULL,
78
+ until timestamptz NOT NULL,
79
+ acquired_at timestamptz NOT NULL DEFAULT now()
80
+ )`;
81
+ }
82
+ async ensureTable() {
83
+ await this.query(_SqlLockStore.createTableSql(this.table), []);
84
+ }
85
+ async tryAcquire(key, token, ttlMs) {
86
+ const rows = await this.query(
87
+ `INSERT INTO ${this.table} (name, owner, until, acquired_at)
88
+ VALUES ($1, $2, now() + make_interval(secs => $3::double precision / 1000), now())
89
+ ON CONFLICT (name) DO UPDATE
90
+ SET owner = EXCLUDED.owner, until = EXCLUDED.until, acquired_at = EXCLUDED.acquired_at
91
+ WHERE ${this.table}.until <= now()
92
+ RETURNING owner`,
93
+ [key, token, ttlMs]
94
+ );
95
+ return Array.isArray(rows) && rows.length > 0;
96
+ }
97
+ async extend(key, token, ttlMs) {
98
+ const rows = await this.query(
99
+ `UPDATE ${this.table} SET until = now() + make_interval(secs => $3::double precision / 1000)
100
+ WHERE name = $1 AND owner = $2 AND until > now() RETURNING owner`,
101
+ [key, token, ttlMs]
102
+ );
103
+ return affected(rows);
104
+ }
105
+ async release(key, token) {
106
+ const rows = await this.query(
107
+ `DELETE FROM ${this.table} WHERE name = $1 AND owner = $2 RETURNING owner`,
108
+ [key, token]
109
+ );
110
+ return affected(rows);
111
+ }
112
+ };
113
+ function affected(result) {
114
+ if (Array.isArray(result)) {
115
+ if (result.length === 2 && Array.isArray(result[0])) return result[0].length > 0;
116
+ return result.length > 0;
117
+ }
118
+ const count = result?.rowCount;
119
+ return typeof count === "number" && count > 0;
120
+ }
121
+
122
+ // src/scheduling/fallback.store.ts
123
+ var FallbackLockStore = class {
124
+ constructor(primary, options = {}) {
125
+ this.primary = primary;
126
+ this.granted = /* @__PURE__ */ new Map();
127
+ this.lastWarn = /* @__PURE__ */ new Map();
128
+ this.now = options.now ?? Date.now;
129
+ this.fallback = options.fallback ?? new MemoryLockStore(this.now);
130
+ this.onFail = options.onFail;
131
+ this.mode = options.onStoreDown ?? "memory";
132
+ }
133
+ async tryAcquire(key, token, ttlMs) {
134
+ try {
135
+ const ok = await this.primary.tryAcquire(key, token, ttlMs);
136
+ if (ok) this.granted.set(`${key}\0${token}`, "primary");
137
+ return ok;
138
+ } catch (error) {
139
+ this.warn(error, "tryAcquire");
140
+ if (this.mode === "skip") return false;
141
+ const ok = await this.fallback.tryAcquire(key, token, ttlMs);
142
+ if (ok) this.granted.set(`${key}\0${token}`, "fallback");
143
+ return ok;
144
+ }
145
+ }
146
+ async extend(key, token, ttlMs) {
147
+ if (this.granted.get(`${key}\0${token}`) === "fallback") {
148
+ return this.fallback.extend(key, token, ttlMs);
149
+ }
150
+ try {
151
+ return await this.primary.extend(key, token, ttlMs);
152
+ } catch (error) {
153
+ this.warn(error, "extend");
154
+ return false;
155
+ }
156
+ }
157
+ async release(key, token) {
158
+ const id = `${key}\0${token}`;
159
+ const where = this.granted.get(id);
160
+ this.granted.delete(id);
161
+ if (where === "fallback") return this.fallback.release(key, token);
162
+ try {
163
+ return await this.primary.release(key, token);
164
+ } catch (error) {
165
+ this.warn(error, "release");
166
+ return false;
167
+ }
168
+ }
169
+ warn(error, operation) {
170
+ const now = this.now();
171
+ if ((this.lastWarn.get(operation) ?? 0) > now - 6e4) return;
172
+ this.lastWarn.set(operation, now);
173
+ try {
174
+ this.onFail?.(error, operation);
175
+ } catch {
176
+ }
177
+ }
178
+ };
179
+
180
+ // src/scheduling/scheduling.options.ts
181
+ var SCHEDULING_OPTIONS = /* @__PURE__ */ Symbol("SCHEDULING_OPTIONS");
182
+
183
+ // src/scheduling/cron-lock.service.ts
184
+ import { randomUUID } from "crypto";
185
+ import { hostname } from "os";
186
+ import {
187
+ Inject,
188
+ Injectable,
189
+ Logger
190
+ } from "@nestjs/common";
191
+ var currentRunner = null;
192
+ function setCronRunner(runner) {
193
+ currentRunner = runner;
194
+ }
195
+ function getCronRunner() {
196
+ return currentRunner;
197
+ }
198
+ var CronLockService = class {
199
+ constructor(store, options) {
200
+ this.store = store;
201
+ this.options = options;
202
+ this.log = new Logger("CronLock");
203
+ this.running = /* @__PURE__ */ new Set();
204
+ this.instanceId = options.instanceId ?? `${hostname()}:${process.pid}:${randomUUID().slice(0, 8)}`;
205
+ }
206
+ onModuleInit() {
207
+ setCronRunner(this);
208
+ }
209
+ onApplicationShutdown() {
210
+ if (getCronRunner() === this) setCronRunner(null);
211
+ }
212
+ /** `true` if the job ran in this instance. */
213
+ async runLocked(name, job, opts = {}) {
214
+ if (this.running.has(name)) {
215
+ this.log.warn(`"${name}": previous run still going in this instance; skipping`);
216
+ return false;
217
+ }
218
+ this.running.add(name);
219
+ try {
220
+ const jitter = Math.max(0, opts.jitterMs ?? this.options.jitterMs ?? 0);
221
+ if (jitter > 0) await this.sleep(Math.floor((this.options.random ?? Math.random)() * jitter));
222
+ const tolerance = Math.max(
223
+ 0,
224
+ opts.toleranceMs ?? this.options.toleranceMs ?? jitter + 1e4
225
+ );
226
+ const lease = Math.max(this.options.ttlMs ?? 12e4, tolerance);
227
+ const token = `${this.instanceId}:${randomUUID()}`;
228
+ if (!await this.store.tryAcquire(name, token, lease)) return false;
229
+ const renew = setInterval(
230
+ () => void this.store.extend(name, token, lease).catch(() => void 0),
231
+ Math.max(1, Math.floor(lease / 3))
232
+ );
233
+ renew.unref?.();
234
+ const started = Date.now();
235
+ try {
236
+ await job();
237
+ } finally {
238
+ clearInterval(renew);
239
+ const remaining = tolerance - (Date.now() - started);
240
+ await (remaining > 0 ? this.store.extend(name, token, remaining) : this.store.release(name, token)).catch(
241
+ (e) => this.log.warn(`"${name}": lock not settled (${String(e)}); it expires by itself`)
242
+ );
243
+ }
244
+ return true;
245
+ } finally {
246
+ this.running.delete(name);
247
+ }
248
+ }
249
+ sleep(ms) {
250
+ return this.options.sleep ? this.options.sleep(ms) : new Promise((r) => setTimeout(r, ms));
251
+ }
252
+ };
253
+ CronLockService = __decorateClass([
254
+ Injectable(),
255
+ __decorateParam(0, Inject(LOCK_STORE)),
256
+ __decorateParam(1, Inject(SCHEDULING_OPTIONS))
257
+ ], CronLockService);
258
+
259
+ // src/scheduling/cron-unico.decorator.ts
260
+ import { Logger as Logger2 } from "@nestjs/common";
261
+ import { Cron } from "@nestjs/schedule";
262
+ var log = new Logger2("CronUnico");
263
+ var warnedNoRunner = false;
264
+ function CronUnico(expression, options) {
265
+ return (target, key) => {
266
+ const sibling = `__cronUnico_${String(key)}`;
267
+ async function wrapper(...args) {
268
+ const original = () => this[key].apply(this, args);
269
+ const runner = getCronRunner();
270
+ if (!runner) {
271
+ if (!warnedNoRunner) {
272
+ warnedNoRunner = true;
273
+ log.warn("SchedulingModule not registered: crons run without coordination");
274
+ }
275
+ await original();
276
+ return;
277
+ }
278
+ await runner.runLocked(options.name, original, {
279
+ jitterMs: options.jitterMs,
280
+ toleranceMs: options.toleranceMs
281
+ });
282
+ }
283
+ Object.defineProperty(target, sibling, {
284
+ value: wrapper,
285
+ writable: true,
286
+ configurable: true,
287
+ enumerable: false
288
+ });
289
+ const descriptor = Object.getOwnPropertyDescriptor(target, sibling);
290
+ Cron(expression, options.cron ?? {})(target, sibling, descriptor);
291
+ };
292
+ }
293
+
294
+ // src/scheduling/scheduling.module.ts
295
+ import { Global, Module } from "@nestjs/common";
296
+ function resolveStore(options) {
297
+ if (!options.store) return new MemoryLockStore();
298
+ return new FallbackLockStore(options.store, {
299
+ onFail: options.onFail,
300
+ onStoreDown: options.onStoreDown
301
+ });
302
+ }
303
+ var SchedulingModule = class {
304
+ static forRoot(options = {}) {
305
+ const providers = [
306
+ { provide: SCHEDULING_OPTIONS, useValue: options },
307
+ { provide: LOCK_STORE, useFactory: () => resolveStore(options) },
308
+ CronLockService
309
+ ];
310
+ return {
311
+ module: SchedulingModule,
312
+ providers,
313
+ exports: [LOCK_STORE, SCHEDULING_OPTIONS, CronLockService]
314
+ };
315
+ }
316
+ static forRootAsync(config) {
317
+ const providers = [
318
+ { provide: SCHEDULING_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
319
+ {
320
+ provide: LOCK_STORE,
321
+ useFactory: (options) => resolveStore(options),
322
+ inject: [SCHEDULING_OPTIONS]
323
+ },
324
+ CronLockService
325
+ ];
326
+ return {
327
+ module: SchedulingModule,
328
+ imports: config.imports ?? [],
329
+ providers,
330
+ exports: [LOCK_STORE, SCHEDULING_OPTIONS, CronLockService]
331
+ };
332
+ }
333
+ };
334
+ SchedulingModule = __decorateClass([
335
+ Global(),
336
+ Module({})
337
+ ], SchedulingModule);
338
+
339
+ // src/scheduling/redis.module.ts
340
+ import {
341
+ Global as Global2,
342
+ Inject as Inject2,
343
+ Injectable as Injectable2,
344
+ Module as Module2
345
+ } from "@nestjs/common";
346
+ var REDIS_CLIENT = /* @__PURE__ */ Symbol("REDIS_CLIENT");
347
+ var RedisCloser = class {
348
+ constructor(client) {
349
+ this.client = client;
350
+ }
351
+ async onApplicationShutdown() {
352
+ if (!this.client) return;
353
+ try {
354
+ if (this.client.quit) await this.client.quit();
355
+ else this.client.disconnect?.();
356
+ } catch {
357
+ this.client.disconnect?.();
358
+ }
359
+ }
360
+ };
361
+ RedisCloser = __decorateClass([
362
+ Injectable2(),
363
+ __decorateParam(0, Inject2(REDIS_CLIENT))
364
+ ], RedisCloser);
365
+ var RedisModule = class {
366
+ static forRoot(options) {
367
+ return {
368
+ module: RedisModule,
369
+ providers: [{ provide: REDIS_CLIENT, useFactory: options.create }, RedisCloser],
370
+ exports: [REDIS_CLIENT]
371
+ };
372
+ }
373
+ };
374
+ RedisModule = __decorateClass([
375
+ Global2(),
376
+ Module2({})
377
+ ], RedisModule);
378
+ export {
379
+ CronLockService,
380
+ CronUnico,
381
+ FallbackLockStore,
382
+ LOCK_STORE,
383
+ MemoryLockStore,
384
+ REDIS_CLIENT,
385
+ RedisLockStore,
386
+ RedisModule,
387
+ SCHEDULING_OPTIONS,
388
+ SchedulingModule,
389
+ SqlLockStore,
390
+ getCronRunner,
391
+ setCronRunner
392
+ };
@@ -0,0 +1,19 @@
1
+ /** DI token for the {@link LockStore} in use. */
2
+ export declare const LOCK_STORE: unique symbol;
3
+ /**
4
+ * Where cross-instance locks live.
5
+ *
6
+ * Every operation is keyed by `(key, token)`: the token identifies one run of
7
+ * one instance, so an instance can never extend or release a lock that has
8
+ * since expired and been taken by another one. `tryAcquire` must be **atomic**
9
+ * (take-if-free-or-expired in one operation); a read followed by a write loses
10
+ * exactly the race this exists for.
11
+ */
12
+ export interface LockStore {
13
+ /** Take `key` for `ttlMs` if nobody holds it. `true` when it is now ours. */
14
+ tryAcquire(key: string, token: string, ttlMs: number): Promise<boolean>;
15
+ /** Set the remaining life to `ttlMs`, only while `token` still owns it. */
16
+ extend(key: string, token: string, ttlMs: number): Promise<boolean>;
17
+ /** Give the lock up, only while `token` still owns it. */
18
+ release(key: string, token: string): Promise<boolean>;
19
+ }
@@ -0,0 +1,15 @@
1
+ import type { LockStore } from './lock-store.port.js';
2
+ /**
3
+ * In-process lock. Correct for one instance and **blind to every other one**:
4
+ * it is the safe default for development and the fallback when the shared
5
+ * store is down. Several runners sharing one `MemoryLockStore` object is how
6
+ * the specs simulate a cluster.
7
+ */
8
+ export declare class MemoryLockStore implements LockStore {
9
+ private readonly now;
10
+ private readonly locks;
11
+ constructor(now?: () => number);
12
+ tryAcquire(key: string, token: string, ttlMs: number): Promise<boolean>;
13
+ extend(key: string, token: string, ttlMs: number): Promise<boolean>;
14
+ release(key: string, token: string): Promise<boolean>;
15
+ }
@@ -0,0 +1,31 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ /** DI token for the shared Redis client. Inject with `@Inject(REDIS_CLIENT)`. */
3
+ export declare const REDIS_CLIENT: unique symbol;
4
+ /** What the module needs from a client to close it: `ioredis` has both. */
5
+ export interface ClosableRedis {
6
+ quit?(): Promise<unknown>;
7
+ disconnect?(): void;
8
+ }
9
+ export interface RedisModuleOptions<T extends ClosableRedis = ClosableRedis> {
10
+ /**
11
+ * Build the client, e.g. `() => new Redis(process.env.REDIS_URL!, { maxRetriesPerRequest: 1,
12
+ * enableOfflineQueue: false })`. Return `null` when Redis is not configured: consumers then
13
+ * get `null` and stay in memory. The package imports nothing from `ioredis`.
14
+ */
15
+ create: () => T | null | Promise<T | null>;
16
+ }
17
+ /**
18
+ * One Redis connection for everything that must be shared between instances
19
+ * (cron locks, idempotency, rate limits, pub/sub), closed on shutdown.
20
+ *
21
+ * ```ts
22
+ * RedisModule.forRoot({ create: () => (url ? new Redis(url) : null) })
23
+ * SchedulingModule.forRootAsync({
24
+ * inject: [REDIS_CLIENT],
25
+ * useFactory: (redis) => ({ store: redis ? new RedisLockStore(redis) : undefined }),
26
+ * })
27
+ * ```
28
+ */
29
+ export declare class RedisModule {
30
+ static forRoot<T extends ClosableRedis>(options: RedisModuleOptions<T>): DynamicModule;
31
+ }
@@ -0,0 +1,24 @@
1
+ import type { LockStore } from './lock-store.port.js';
2
+ /**
3
+ * The slice of an `ioredis` client the lock needs. Structural on purpose: the
4
+ * package imports nothing from `ioredis`, so it stays an optional peer — pass
5
+ * your own `new Redis(url)` (any client with these two methods works).
6
+ */
7
+ export interface RedisLockClient {
8
+ set(key: string, value: string, ...args: (string | number)[]): Promise<unknown>;
9
+ eval(script: string, numKeys: number, ...args: (string | number)[]): Promise<unknown>;
10
+ }
11
+ /**
12
+ * Redis lock: `SET key token NX PX ttl` to take (one command per instance and
13
+ * run), compare-and-act scripts to extend or release. Errors propagate — wrap
14
+ * it in `FallbackLockStore` (what `SchedulingModule` does) to degrade instead
15
+ * of failing the cron.
16
+ */
17
+ export declare class RedisLockStore implements LockStore {
18
+ private readonly client;
19
+ private readonly prefix;
20
+ constructor(client: RedisLockClient, prefix?: string);
21
+ tryAcquire(key: string, token: string, ttlMs: number): Promise<boolean>;
22
+ extend(key: string, token: string, ttlMs: number): Promise<boolean>;
23
+ release(key: string, token: string): Promise<boolean>;
24
+ }
@@ -0,0 +1,24 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import { type SchedulingOptions } from './scheduling.options.js';
3
+ /**
4
+ * Locks for crons that must run once across N instances.
5
+ *
6
+ * ```ts
7
+ * ScheduleModule.forRoot(),
8
+ * SchedulingModule.forRoot() // memory, one instance
9
+ * SchedulingModule.forRoot({ store: new RedisLockStore(redis), jitterMs: 5_000 })
10
+ * SchedulingModule.forRoot({ store: new SqlLockStore((q, p) => dataSource.query(q, p)) })
11
+ * ```
12
+ *
13
+ * If the shared store throws, the lock degrades to process memory (or skips
14
+ * the run with `onStoreDown: 'skip'`) and `onFail` is called — a Redis outage
15
+ * never stops the jobs.
16
+ */
17
+ export declare class SchedulingModule {
18
+ static forRoot(options?: SchedulingOptions): DynamicModule;
19
+ static forRootAsync(config: {
20
+ imports?: any[];
21
+ inject?: any[];
22
+ useFactory: (...args: any[]) => SchedulingOptions | Promise<SchedulingOptions>;
23
+ }): DynamicModule;
24
+ }
@@ -0,0 +1,27 @@
1
+ import type { LockOperation } from './fallback.store.js';
2
+ import type { LockStore } from './lock-store.port.js';
3
+ /** DI token carrying the resolved {@link SchedulingOptions}. */
4
+ export declare const SCHEDULING_OPTIONS: unique symbol;
5
+ export interface SchedulingOptions {
6
+ /** Shared lock store (Redis, SQL…). Defaults to process memory (single instance). */
7
+ store?: LockStore;
8
+ /** Lease while a run is in progress, renewed every third of it. Default 120 000 ms. */
9
+ ttlMs?: number;
10
+ /** Default random wait before asking for the lock, `[0, jitterMs)`. Default 0. */
11
+ jitterMs?: number;
12
+ /**
13
+ * Default time the lock is held counted from the start of a run, even if it
14
+ * finishes sooner, so a late instance (clock skew, jitter) does not repeat
15
+ * it. Default: jitter + 10 000 ms. Keep it below the cron period.
16
+ */
17
+ toleranceMs?: number;
18
+ /** Called when the store fails and the lock degrades (see `onStoreDown`). */
19
+ onFail?: (error: unknown, operation: LockOperation) => void;
20
+ /** Store failure policy: run per-instance on memory (default) or skip the run. */
21
+ onStoreDown?: 'memory' | 'skip';
22
+ /** Identifier of this instance; default host + pid + random. */
23
+ instanceId?: string;
24
+ /** Test seams. */
25
+ sleep?: (ms: number) => Promise<void>;
26
+ random?: () => number;
27
+ }
@@ -0,0 +1,26 @@
1
+ import type { LockStore } from './lock-store.port.js';
2
+ /** Minimal SQL runner: a TypeORM `DataSource.query` or an adapted `pg` client. Postgres syntax, `$n` params. */
3
+ export type SqlQuery = (sql: string, params: unknown[]) => Promise<unknown>;
4
+ export interface SqlLockStoreOptions {
5
+ /** Table name. Defaults to `cron_lock`. Letters, digits and `_` only (optionally `schema.table`). */
6
+ table?: string;
7
+ }
8
+ /**
9
+ * Postgres lease table: `INSERT … ON CONFLICT DO UPDATE … WHERE until <= now()`,
10
+ * one atomic statement. A lease row, not `pg_advisory_lock`: a session lock
11
+ * does not survive a transaction-mode pooler (PgBouncer, Neon) and would pin a
12
+ * connection for the whole run.
13
+ *
14
+ * Create the table with `SqlLockStore.createTableSql()` in a migration, or
15
+ * call `ensureTable()` once at boot.
16
+ */
17
+ export declare class SqlLockStore implements LockStore {
18
+ private readonly query;
19
+ private readonly table;
20
+ constructor(query: SqlQuery, options?: SqlLockStoreOptions);
21
+ static createTableSql(table?: string): string;
22
+ ensureTable(): Promise<void>;
23
+ tryAcquire(key: string, token: string, ttlMs: number): Promise<boolean>;
24
+ extend(key: string, token: string, ttlMs: number): Promise<boolean>;
25
+ release(key: string, token: string): Promise<boolean>;
26
+ }