@miguelmorales13/nestkit 0.25.0 → 0.28.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 (281) hide show
  1. package/README.md +5 -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 +123 -115
  19. package/dist/auth/oauth/index.js +25 -17
  20. package/dist/auth/oauth/oauth-provider.d.ts +9 -0
  21. package/dist/auth/oauth/providers/apple.d.ts +3 -1
  22. package/dist/bootstrap/apply-defaults.d.ts +9 -0
  23. package/dist/bootstrap/index.cjs +6 -5
  24. package/dist/bootstrap/index.js +5 -4
  25. package/dist/chunk-3TUMVLPJ.js +14 -0
  26. package/dist/{chunk-PA24P76K.js → chunk-45SW7FBE.js} +1 -1
  27. package/dist/{chunk-RF75KC63.cjs → chunk-47IYXZHW.cjs} +2 -2
  28. package/dist/{chunk-TUNDBBQF.js → chunk-4WWOKZIO.js} +4 -4
  29. package/dist/{chunk-A2DGK4ZL.js → chunk-5LVGCTJ3.js} +1 -1
  30. package/dist/chunk-A6YGIZCQ.cjs +14 -0
  31. package/dist/chunk-A7FI6HXV.js +40 -0
  32. package/dist/chunk-CU4FUIVJ.cjs +8 -0
  33. package/dist/{chunk-FH5UNWWW.cjs → chunk-D35TBVRO.cjs} +4 -4
  34. package/dist/{chunk-4MGIQFAJ.js → chunk-D3DDJWUD.js} +5 -0
  35. package/dist/chunk-DVGPEBUL.js +8 -0
  36. package/dist/{chunk-VKOPDDCC.js → chunk-ENZ7LQRE.js} +1 -1
  37. package/dist/{chunk-3AUOOEQO.cjs → chunk-F77X4QUN.cjs} +2 -2
  38. package/dist/chunk-FBNV5X6C.js +61 -0
  39. package/dist/{chunk-APUFKA4K.cjs → chunk-FDZQCLLK.cjs} +6 -6
  40. package/dist/{chunk-DYHSOULW.js → chunk-IGSNB5BX.js} +1 -1
  41. package/dist/chunk-IVWPA6QH.cjs +90 -0
  42. package/dist/{chunk-MSTXS3MU.cjs → chunk-JJKGQNGD.cjs} +2 -2
  43. package/dist/{chunk-FNUZGYUF.cjs → chunk-JRFE7NSO.cjs} +12 -4
  44. package/dist/{chunk-HVHYZXBB.cjs → chunk-KNU5RN3O.cjs} +3 -3
  45. package/dist/{chunk-52IOOHNX.cjs → chunk-KQPJCVN3.cjs} +26 -26
  46. package/dist/chunk-LGFHLAY3.cjs +61 -0
  47. package/dist/{chunk-2REOCMUD.cjs → chunk-LRX7AMSS.cjs} +6 -1
  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-UNEVXCFW.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 +31 -30
  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/index.cjs +7 -7
  179. package/dist/payments/index.js +1 -1
  180. package/dist/pinterest/index.cjs +3 -3
  181. package/dist/pinterest/index.js +1 -1
  182. package/dist/privacy/anonymizer.d.ts +14 -0
  183. package/dist/privacy/index.cjs +768 -0
  184. package/dist/privacy/index.d.ts +13 -0
  185. package/dist/privacy/index.js +768 -0
  186. package/dist/privacy/memory.store.d.ts +15 -0
  187. package/dist/privacy/privacy.module.d.ts +30 -0
  188. package/dist/privacy/privacy.options.d.ts +43 -0
  189. package/dist/privacy/privacy.port.d.ts +25 -0
  190. package/dist/privacy/privacy.service.d.ts +69 -0
  191. package/dist/privacy/privacy.types.d.ts +125 -0
  192. package/dist/privacy/sql.d.ts +7 -0
  193. package/dist/privacy/sql.store.d.ts +21 -0
  194. package/dist/privacy/zip.d.ts +23 -0
  195. package/dist/push/index.cjs +13 -13
  196. package/dist/push/index.js +5 -5
  197. package/dist/resilience/alert-channels.d.ts +39 -0
  198. package/dist/resilience/alert-errors.interceptor.d.ts +10 -0
  199. package/dist/resilience/alert-on-failure.decorator.d.ts +10 -0
  200. package/dist/resilience/alert.service.d.ts +77 -0
  201. package/dist/resilience/index.cjs +863 -0
  202. package/dist/resilience/index.d.ts +18 -0
  203. package/dist/resilience/index.js +863 -0
  204. package/dist/resilience/memory-alert-store.d.ts +26 -0
  205. package/dist/resilience/provider-health.controller.d.ts +14 -0
  206. package/dist/resilience/provider-unavailable.exception.d.ts +11 -0
  207. package/dist/resilience/resilience.module.d.ts +34 -0
  208. package/dist/resilience/resilience.options.d.ts +28 -0
  209. package/dist/resilience/resilience.types.d.ts +167 -0
  210. package/dist/resilience/resilient-fetch.d.ts +38 -0
  211. package/dist/resilience/runtime.d.ts +24 -0
  212. package/dist/resilience/typeorm/alert.entity.d.ts +21 -0
  213. package/dist/resilience/typeorm/index.cjs +102 -0
  214. package/dist/resilience/typeorm/index.d.ts +3 -0
  215. package/dist/resilience/typeorm/index.js +102 -0
  216. package/dist/resilience/typeorm/typeorm-alert-store.d.ts +39 -0
  217. package/dist/resilience/validate-destination.d.ts +63 -0
  218. package/dist/response/index.cjs +3 -3
  219. package/dist/response/index.js +2 -2
  220. package/dist/scheduling/cron-lock.service.d.ts +36 -0
  221. package/dist/scheduling/cron-unico.decorator.d.ts +27 -0
  222. package/dist/scheduling/fallback.store.d.ts +34 -0
  223. package/dist/scheduling/index.cjs +392 -0
  224. package/dist/scheduling/index.d.ts +18 -0
  225. package/dist/scheduling/index.js +392 -0
  226. package/dist/scheduling/lock-store.port.d.ts +19 -0
  227. package/dist/scheduling/memory.store.d.ts +15 -0
  228. package/dist/scheduling/redis.module.d.ts +31 -0
  229. package/dist/scheduling/redis.store.d.ts +24 -0
  230. package/dist/scheduling/scheduling.module.d.ts +24 -0
  231. package/dist/scheduling/scheduling.options.d.ts +27 -0
  232. package/dist/scheduling/sql.store.d.ts +26 -0
  233. package/dist/secrets/index.cjs +274 -0
  234. package/dist/secrets/index.d.ts +8 -0
  235. package/dist/secrets/index.js +274 -0
  236. package/dist/secrets/secrets.errors.d.ts +6 -0
  237. package/dist/secrets/secrets.module.d.ts +21 -0
  238. package/dist/secrets/secrets.options.d.ts +32 -0
  239. package/dist/secrets/secrets.service.d.ts +54 -0
  240. package/dist/secrets/secrets.transformer.d.ts +33 -0
  241. package/dist/security/hash.d.ts +8 -0
  242. package/dist/security/index.cjs +119 -2
  243. package/dist/security/index.d.ts +5 -0
  244. package/dist/security/index.js +119 -2
  245. package/dist/security/mask.d.ts +22 -0
  246. package/dist/security/signed-grant.d.ts +30 -0
  247. package/dist/storage/index.cjs +2 -2
  248. package/dist/storage/index.js +1 -1
  249. package/dist/stripe/index.cjs +7 -7
  250. package/dist/stripe/index.js +1 -1
  251. package/dist/telegram/index.cjs +2 -2
  252. package/dist/telegram/index.js +1 -1
  253. package/dist/tenancy/app-role.d.ts +24 -0
  254. package/dist/tenancy/db-helpers.d.ts +12 -0
  255. package/dist/tenancy/index.cjs +205 -0
  256. package/dist/tenancy/index.d.ts +14 -0
  257. package/dist/tenancy/index.js +205 -0
  258. package/dist/tenancy/pg/index.cjs +34 -0
  259. package/dist/tenancy/pg/index.d.ts +2 -0
  260. package/dist/tenancy/pg/index.js +34 -0
  261. package/dist/tenancy/pg/with-tenant.d.ts +23 -0
  262. package/dist/tenancy/request-context.d.ts +18 -0
  263. package/dist/tenancy/rls-guardrail.d.ts +38 -0
  264. package/dist/tenancy/scope.d.ts +5 -0
  265. package/dist/tenancy/tenancy.errors.d.ts +5 -0
  266. package/dist/tenancy/tenancy.middleware.d.ts +8 -0
  267. package/dist/tenancy/tenancy.module.d.ts +37 -0
  268. package/dist/tenancy/tenancy.options.d.ts +34 -0
  269. package/dist/tenancy/typeorm/index.cjs +41 -0
  270. package/dist/tenancy/typeorm/index.d.ts +2 -0
  271. package/dist/tenancy/typeorm/index.js +41 -0
  272. package/dist/tenancy/typeorm/with-tenant.d.ts +23 -0
  273. package/dist/tiktok/index.cjs +3 -3
  274. package/dist/tiktok/index.js +1 -1
  275. package/dist/tracking/index.cjs +3 -3
  276. package/dist/tracking/index.js +2 -2
  277. package/dist/umami/index.cjs +4 -4
  278. package/dist/umami/index.js +1 -1
  279. package/dist/whatsapp/index.cjs +2 -2
  280. package/dist/whatsapp/index.js +1 -1
  281. package/package.json +107 -2
@@ -0,0 +1,318 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return 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
+
3
+
4
+ var _chunkLRX7AMSScjs = require('../chunk-LRX7AMSS.cjs');
5
+
6
+ // src/jobs/jobs.options.ts
7
+ var JOBS_OPTIONS = /* @__PURE__ */ Symbol("JOBS_OPTIONS");
8
+
9
+ // src/jobs/defer-job.ts
10
+ var DeferJob = class extends Error {
11
+ constructor(retryAfterMs = null, message = "Job deferred") {
12
+ super(message);
13
+ this.retryAfterMs = retryAfterMs;
14
+ this.name = "DeferJob";
15
+ }
16
+ };
17
+
18
+ // src/jobs/jobs.sql.ts
19
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
20
+ function checkIdentifier(value, what) {
21
+ if (!IDENTIFIER.test(value)) throw new Error(`jobs: invalid ${what} "${value}"`);
22
+ return value;
23
+ }
24
+ function createTableSql(table = "job", tenantColumn = false) {
25
+ const t = checkIdentifier(table, "table name");
26
+ const base = t.replace(".", "_");
27
+ const tenant = tenantColumn ? `
28
+ ${checkIdentifier(tenantColumn, "tenant column")} text,` : "";
29
+ return `CREATE TABLE IF NOT EXISTS ${t} (
30
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
31
+ type text NOT NULL,
32
+ payload jsonb NOT NULL DEFAULT '{}'::jsonb,
33
+ status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','taken','done','failed')),
34
+ attempts integer NOT NULL DEFAULT 0,
35
+ deferrals integer NOT NULL DEFAULT 0,
36
+ run_at timestamptz NOT NULL DEFAULT now(),
37
+ last_error text,
38
+ dedupe_key text,${tenant}
39
+ locked_at timestamptz,
40
+ created_at timestamptz NOT NULL DEFAULT now(),
41
+ updated_at timestamptz NOT NULL DEFAULT now()
42
+ );
43
+ CREATE INDEX IF NOT EXISTS ${base}_due_idx ON ${t} (run_at) WHERE status IN ('pending','taken');
44
+ CREATE INDEX IF NOT EXISTS ${base}_failed_idx ON ${t} (created_at DESC) WHERE status = 'failed';
45
+ CREATE UNIQUE INDEX IF NOT EXISTS ${base}_dedupe_idx ON ${t} (dedupe_key) WHERE dedupe_key IS NOT NULL AND status IN ('pending','taken')`;
46
+ }
47
+ var WAIT = (n) => `now() + make_interval(secs => $${n}::double precision / 1000)`;
48
+
49
+ // src/jobs/jobs.service.ts
50
+ var _common = require('@nestjs/common');
51
+ var DEFAULTS = {
52
+ pollMs: 2e3,
53
+ maxAttempts: 5,
54
+ maxDeferrals: 20,
55
+ lockTimeoutMs: 10 * 6e4
56
+ };
57
+ var defaultBackoff = (attempt) => Math.min(5e3 * 2 ** Math.max(attempt - 1, 0), 36e5);
58
+ var defaultDeferral = (deferrals) => Math.min(1e3 * 2 ** deferrals, 3e5);
59
+ var JobsService = class {
60
+ constructor(options) {
61
+ this.options = options;
62
+ this.log = new (0, _common.Logger)("Jobs");
63
+ this.handlers = /* @__PURE__ */ new Map();
64
+ this.running = false;
65
+ this.stopped = false;
66
+ if (!_optionalChain([options, 'optionalAccess', _2 => _2.pool])) throw new Error("jobs: `pool` is required");
67
+ this.table = checkIdentifier(_nullishCoalesce(options.table, () => ( "job")), "table name");
68
+ this.tenantColumn = options.tenantColumn ? checkIdentifier(options.tenantColumn, "tenant column") : false;
69
+ }
70
+ /** Registers (or replaces) the handler for a type. */
71
+ register(type, handler) {
72
+ this.handlers.set(type, handler);
73
+ }
74
+ onModuleInit() {
75
+ if (this.options.autoStart === false) return;
76
+ this.start();
77
+ }
78
+ onModuleDestroy() {
79
+ this.stop();
80
+ }
81
+ start() {
82
+ this.stopped = false;
83
+ this.schedule(0);
84
+ }
85
+ stop() {
86
+ this.stopped = true;
87
+ if (this.timer) clearTimeout(this.timer);
88
+ }
89
+ /** Adds a job. Returns its id, or `null` if `dedupeKey` matched a live job. */
90
+ async enqueue(type, payload = {}, opts = {}) {
91
+ const columns = ["type", "payload", "run_at", "dedupe_key"];
92
+ const values = [type, JSON.stringify(_nullishCoalesce(payload, () => ( {}))), _nullishCoalesce(opts.runAt, () => ( /* @__PURE__ */ new Date())), _nullishCoalesce(opts.dedupeKey, () => ( null))];
93
+ if (this.tenantColumn) {
94
+ columns.push(this.tenantColumn);
95
+ values.push(_nullishCoalesce(opts.tenantId, () => ( null)));
96
+ } else if (opts.tenantId) {
97
+ throw new Error("jobs: `tenantId` needs the `tenantColumn` option");
98
+ }
99
+ const params = values.map((_, i) => i === 1 ? `$${i + 1}::jsonb` : `$${i + 1}`).join(", ");
100
+ const { rows } = await this.options.pool.query(
101
+ `INSERT INTO ${this.table} (${columns.join(", ")}) VALUES (${params})
102
+ ON CONFLICT (dedupe_key) WHERE dedupe_key IS NOT NULL AND status IN ('pending','taken') DO NOTHING
103
+ RETURNING id`,
104
+ values
105
+ );
106
+ return _nullishCoalesce(_optionalChain([rows, 'access', _3 => _3[0], 'optionalAccess', _4 => _4.id]), () => ( null));
107
+ }
108
+ /** The failed tray, newest first. */
109
+ async failed(limit = 100, tenantId) {
110
+ const tenant = this.tenantColumn;
111
+ const where = tenant && tenantId !== void 0 ? ` AND ${tenant} = $2` : "";
112
+ const params = [limit];
113
+ if (where) params.push(tenantId);
114
+ const { rows } = await this.options.pool.query(
115
+ `SELECT id, type, last_error, attempts, created_at${tenant ? `, ${tenant} AS tenant_id` : ""}
116
+ FROM ${this.table} WHERE status = 'failed'${where} ORDER BY created_at DESC LIMIT $1`,
117
+ params
118
+ );
119
+ return rows.map((r) => ({
120
+ id: r.id,
121
+ type: r.type,
122
+ error: _nullishCoalesce(r.last_error, () => ( null)),
123
+ attempts: r.attempts,
124
+ createdAt: new Date(r.created_at).toISOString(),
125
+ ...tenant ? { tenantId: _nullishCoalesce(r.tenant_id, () => ( null)) } : {}
126
+ }));
127
+ }
128
+ /**
129
+ * Puts a failed job back in the queue. Attempts reset: whoever requeues has
130
+ * fixed the cause, and keeping the counter would return it to the tray on
131
+ * the first stumble. `false` if it was not in the tray.
132
+ */
133
+ async requeue(id) {
134
+ const { rows } = await this.options.pool.query(
135
+ `UPDATE ${this.table} SET status = 'pending', attempts = 0, deferrals = 0, run_at = now(),
136
+ locked_at = NULL, updated_at = now()
137
+ WHERE id = $1 AND status = 'failed' RETURNING id`,
138
+ [id]
139
+ );
140
+ return rows.length > 0;
141
+ }
142
+ /** Takes and runs ONE job. Returns true if it took one (whatever the outcome). */
143
+ async processOne() {
144
+ const types = [...this.handlers.keys()];
145
+ if (types.length === 0) return false;
146
+ const tenant = this.tenantColumn;
147
+ const { rows } = await this.options.pool.query(
148
+ `WITH next AS (
149
+ SELECT id FROM ${this.table}
150
+ WHERE type = ANY($1::text[]) AND run_at <= now()
151
+ AND (status = 'pending' OR (status = 'taken' AND locked_at < ${this.lockCutoff()}))
152
+ ORDER BY run_at, created_at LIMIT 1 FOR UPDATE SKIP LOCKED)
153
+ UPDATE ${this.table} j SET status = 'taken', attempts = j.attempts + 1, locked_at = now(), updated_at = now()
154
+ FROM next WHERE j.id = next.id
155
+ RETURNING j.id, j.type, j.payload, j.attempts, j.deferrals${tenant ? `, j.${tenant} AS tenant_id` : ""}`,
156
+ [types, _nullishCoalesce(this.options.lockTimeoutMs, () => ( DEFAULTS.lockTimeoutMs))]
157
+ );
158
+ const row = rows[0];
159
+ if (!row) return false;
160
+ const job = {
161
+ id: row.id,
162
+ type: row.type,
163
+ payload: _nullishCoalesce(row.payload, () => ( {})),
164
+ attempts: row.attempts,
165
+ deferrals: row.deferrals,
166
+ ...tenant ? { tenantId: _nullishCoalesce(row.tenant_id, () => ( null)) } : {}
167
+ };
168
+ const handler = this.handlers.get(job.type);
169
+ try {
170
+ if (!handler) throw new Error(`No handler registered for "${job.type}"`);
171
+ await handler(job);
172
+ await this.options.pool.query(
173
+ `UPDATE ${this.table} SET status = 'done', last_error = NULL, locked_at = NULL, updated_at = now() WHERE id = $1`,
174
+ [job.id]
175
+ );
176
+ } catch (error) {
177
+ await this.handleFailure(job, error);
178
+ }
179
+ return true;
180
+ }
181
+ lockCutoff() {
182
+ return `now() - make_interval(secs => $2::double precision / 1000)`;
183
+ }
184
+ async handleFailure(job, error) {
185
+ const message = (error instanceof Error ? error.message : String(error)).slice(0, 500);
186
+ const maxDeferrals = _nullishCoalesce(this.options.maxDeferrals, () => ( DEFAULTS.maxDeferrals));
187
+ if (error instanceof DeferJob && job.deferrals < maxDeferrals) {
188
+ const wait2 = _nullishCoalesce(error.retryAfterMs, () => ( defaultDeferral(job.deferrals)));
189
+ await this.options.pool.query(
190
+ `UPDATE ${this.table} SET status = 'pending', attempts = GREATEST(attempts - 1, 0),
191
+ deferrals = deferrals + 1, run_at = ${WAIT(2)}, last_error = $3, locked_at = NULL, updated_at = now()
192
+ WHERE id = $1`,
193
+ [job.id, wait2, message]
194
+ );
195
+ this.log.warn(`Job ${job.type} deferred ${Math.ceil(wait2 / 1e3)} s: ${message}`);
196
+ return;
197
+ }
198
+ const maxAttempts = _nullishCoalesce(this.options.maxAttempts, () => ( DEFAULTS.maxAttempts));
199
+ if (error instanceof DeferJob || job.attempts >= maxAttempts) {
200
+ await this.options.pool.query(
201
+ `UPDATE ${this.table} SET status = 'failed', last_error = $2, locked_at = NULL, updated_at = now() WHERE id = $1`,
202
+ [job.id, message]
203
+ );
204
+ this.log.error(`Job ${job.type} exhausted its attempts: ${message}`);
205
+ try {
206
+ await _optionalChain([this, 'access', _5 => _5.options, 'access', _6 => _6.onDead, 'optionalCall', _7 => _7(job, error)]);
207
+ } catch (hookError) {
208
+ this.log.error(`onDead failed: ${String(hookError)}`);
209
+ }
210
+ return;
211
+ }
212
+ const wait = (_nullishCoalesce(this.options.backoff, () => ( defaultBackoff)))(job.attempts);
213
+ await this.options.pool.query(
214
+ `UPDATE ${this.table} SET status = 'pending', run_at = ${WAIT(2)}, last_error = $3, locked_at = NULL, updated_at = now()
215
+ WHERE id = $1`,
216
+ [job.id, wait, message]
217
+ );
218
+ this.log.warn(`Job ${job.type} failed (attempt ${job.attempts}): ${message}`);
219
+ }
220
+ schedule(ms) {
221
+ if (this.stopped) return;
222
+ this.timer = setTimeout(() => void this.tick(), ms);
223
+ _optionalChain([this, 'access', _8 => _8.timer, 'access', _9 => _9.unref, 'optionalCall', _10 => _10()]);
224
+ }
225
+ async tick() {
226
+ if (this.running || this.stopped) return;
227
+ this.running = true;
228
+ try {
229
+ const did = await this.processOne();
230
+ this.schedule(did ? 0 : _nullishCoalesce(this.options.pollMs, () => ( DEFAULTS.pollMs)));
231
+ } catch (error) {
232
+ this.log.error(`Worker cycle failed: ${String(error)}`);
233
+ this.schedule(_nullishCoalesce(this.options.pollMs, () => ( DEFAULTS.pollMs)));
234
+ } finally {
235
+ this.running = false;
236
+ }
237
+ }
238
+ /** The migration for this configuration. */
239
+ createTableSql() {
240
+ return createTableSql(this.table, this.tenantColumn);
241
+ }
242
+ };
243
+ JobsService = exports.JobsService = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
244
+ _common.Injectable.call(void 0, ),
245
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, JOBS_OPTIONS))
246
+ ], JobsService);
247
+
248
+ // src/jobs/jobs-admin.controller.ts
249
+
250
+ function createJobsAdminController(options = {}) {
251
+ let JobsAdminController = class {
252
+ constructor(jobs) {
253
+ this.jobs = jobs;
254
+ }
255
+ failed(limit) {
256
+ const n = Math.min(Math.max(Number(limit) || 100, 1), 500);
257
+ return this.jobs.failed(n);
258
+ }
259
+ async requeue(id) {
260
+ if (!await this.jobs.requeue(id)) throw new (0, _common.NotFoundException)("That job is not in the failed tray");
261
+ return { ok: true };
262
+ }
263
+ };
264
+ _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
265
+ _common.Get.call(void 0, "failed"),
266
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Query.call(void 0, "limit"))
267
+ ], JobsAdminController.prototype, "failed", 1);
268
+ _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
269
+ _common.Post.call(void 0, ":id/requeue"),
270
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Param.call(void 0, "id"))
271
+ ], JobsAdminController.prototype, "requeue", 1);
272
+ JobsAdminController = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
273
+ _common.Controller.call(void 0, _nullishCoalesce(options.path, () => ( "jobs"))),
274
+ _common.UseGuards.call(void 0, ..._nullishCoalesce(options.guards, () => ( []))),
275
+ _chunkLRX7AMSScjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, JobsService))
276
+ ], JobsAdminController);
277
+ return JobsAdminController;
278
+ }
279
+
280
+ // src/jobs/jobs.module.ts
281
+
282
+ var JobsModule = class {
283
+ static forRoot(options) {
284
+ const { admin, ...rest } = options;
285
+ return this.build([{ provide: JOBS_OPTIONS, useValue: rest }], [], admin);
286
+ }
287
+ static forRootAsync(config) {
288
+ return this.build(
289
+ [{ provide: JOBS_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) }],
290
+ _nullishCoalesce(config.imports, () => ( [])),
291
+ config.admin
292
+ );
293
+ }
294
+ static build(providers, imports, admin) {
295
+ const controllers = admin === void 0 || admin === false ? [] : [createJobsAdminController(admin)];
296
+ return {
297
+ module: JobsModule,
298
+ imports,
299
+ controllers,
300
+ providers: [...providers, JobsService],
301
+ exports: [JOBS_OPTIONS, JobsService]
302
+ };
303
+ }
304
+ };
305
+ /** The migration SQL (table + indexes). */
306
+ JobsModule.createTableSql = createTableSql;
307
+ JobsModule = exports.JobsModule = _chunkLRX7AMSScjs.__decorateClass.call(void 0, [
308
+ _common.Global.call(void 0, ),
309
+ _common.Module.call(void 0, {})
310
+ ], JobsModule);
311
+
312
+
313
+
314
+
315
+
316
+
317
+
318
+ exports.DeferJob = DeferJob; exports.JOBS_OPTIONS = JOBS_OPTIONS; exports.JobsModule = JobsModule; exports.JobsService = JobsService; exports.createJobsAdminController = createJobsAdminController; exports.createJobsTableSql = createTableSql;
@@ -0,0 +1,8 @@
1
+ export { JOBS_OPTIONS } from './jobs.options.js';
2
+ export type { EnqueueOptions, FailedJob, Job, JobHandler, JobsOptions, JobsPool, } from './jobs.options.js';
3
+ export { DeferJob } from './defer-job.js';
4
+ export { createTableSql as createJobsTableSql } from './jobs.sql.js';
5
+ export { JobsService } from './jobs.service.js';
6
+ export { createJobsAdminController } from './jobs-admin.controller.js';
7
+ export type { JobsAdminOptions } from './jobs-admin.controller.js';
8
+ export { JobsModule } from './jobs.module.js';
@@ -0,0 +1,318 @@
1
+ import {
2
+ __decorateClass,
3
+ __decorateParam
4
+ } from "../chunk-D3DDJWUD.js";
5
+
6
+ // src/jobs/jobs.options.ts
7
+ var JOBS_OPTIONS = /* @__PURE__ */ Symbol("JOBS_OPTIONS");
8
+
9
+ // src/jobs/defer-job.ts
10
+ var DeferJob = class extends Error {
11
+ constructor(retryAfterMs = null, message = "Job deferred") {
12
+ super(message);
13
+ this.retryAfterMs = retryAfterMs;
14
+ this.name = "DeferJob";
15
+ }
16
+ };
17
+
18
+ // src/jobs/jobs.sql.ts
19
+ var IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
20
+ function checkIdentifier(value, what) {
21
+ if (!IDENTIFIER.test(value)) throw new Error(`jobs: invalid ${what} "${value}"`);
22
+ return value;
23
+ }
24
+ function createTableSql(table = "job", tenantColumn = false) {
25
+ const t = checkIdentifier(table, "table name");
26
+ const base = t.replace(".", "_");
27
+ const tenant = tenantColumn ? `
28
+ ${checkIdentifier(tenantColumn, "tenant column")} text,` : "";
29
+ return `CREATE TABLE IF NOT EXISTS ${t} (
30
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
31
+ type text NOT NULL,
32
+ payload jsonb NOT NULL DEFAULT '{}'::jsonb,
33
+ status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','taken','done','failed')),
34
+ attempts integer NOT NULL DEFAULT 0,
35
+ deferrals integer NOT NULL DEFAULT 0,
36
+ run_at timestamptz NOT NULL DEFAULT now(),
37
+ last_error text,
38
+ dedupe_key text,${tenant}
39
+ locked_at timestamptz,
40
+ created_at timestamptz NOT NULL DEFAULT now(),
41
+ updated_at timestamptz NOT NULL DEFAULT now()
42
+ );
43
+ CREATE INDEX IF NOT EXISTS ${base}_due_idx ON ${t} (run_at) WHERE status IN ('pending','taken');
44
+ CREATE INDEX IF NOT EXISTS ${base}_failed_idx ON ${t} (created_at DESC) WHERE status = 'failed';
45
+ CREATE UNIQUE INDEX IF NOT EXISTS ${base}_dedupe_idx ON ${t} (dedupe_key) WHERE dedupe_key IS NOT NULL AND status IN ('pending','taken')`;
46
+ }
47
+ var WAIT = (n) => `now() + make_interval(secs => $${n}::double precision / 1000)`;
48
+
49
+ // src/jobs/jobs.service.ts
50
+ import { Inject, Injectable, Logger } from "@nestjs/common";
51
+ var DEFAULTS = {
52
+ pollMs: 2e3,
53
+ maxAttempts: 5,
54
+ maxDeferrals: 20,
55
+ lockTimeoutMs: 10 * 6e4
56
+ };
57
+ var defaultBackoff = (attempt) => Math.min(5e3 * 2 ** Math.max(attempt - 1, 0), 36e5);
58
+ var defaultDeferral = (deferrals) => Math.min(1e3 * 2 ** deferrals, 3e5);
59
+ var JobsService = class {
60
+ constructor(options) {
61
+ this.options = options;
62
+ this.log = new Logger("Jobs");
63
+ this.handlers = /* @__PURE__ */ new Map();
64
+ this.running = false;
65
+ this.stopped = false;
66
+ if (!options?.pool) throw new Error("jobs: `pool` is required");
67
+ this.table = checkIdentifier(options.table ?? "job", "table name");
68
+ this.tenantColumn = options.tenantColumn ? checkIdentifier(options.tenantColumn, "tenant column") : false;
69
+ }
70
+ /** Registers (or replaces) the handler for a type. */
71
+ register(type, handler) {
72
+ this.handlers.set(type, handler);
73
+ }
74
+ onModuleInit() {
75
+ if (this.options.autoStart === false) return;
76
+ this.start();
77
+ }
78
+ onModuleDestroy() {
79
+ this.stop();
80
+ }
81
+ start() {
82
+ this.stopped = false;
83
+ this.schedule(0);
84
+ }
85
+ stop() {
86
+ this.stopped = true;
87
+ if (this.timer) clearTimeout(this.timer);
88
+ }
89
+ /** Adds a job. Returns its id, or `null` if `dedupeKey` matched a live job. */
90
+ async enqueue(type, payload = {}, opts = {}) {
91
+ const columns = ["type", "payload", "run_at", "dedupe_key"];
92
+ const values = [type, JSON.stringify(payload ?? {}), opts.runAt ?? /* @__PURE__ */ new Date(), opts.dedupeKey ?? null];
93
+ if (this.tenantColumn) {
94
+ columns.push(this.tenantColumn);
95
+ values.push(opts.tenantId ?? null);
96
+ } else if (opts.tenantId) {
97
+ throw new Error("jobs: `tenantId` needs the `tenantColumn` option");
98
+ }
99
+ const params = values.map((_, i) => i === 1 ? `$${i + 1}::jsonb` : `$${i + 1}`).join(", ");
100
+ const { rows } = await this.options.pool.query(
101
+ `INSERT INTO ${this.table} (${columns.join(", ")}) VALUES (${params})
102
+ ON CONFLICT (dedupe_key) WHERE dedupe_key IS NOT NULL AND status IN ('pending','taken') DO NOTHING
103
+ RETURNING id`,
104
+ values
105
+ );
106
+ return rows[0]?.id ?? null;
107
+ }
108
+ /** The failed tray, newest first. */
109
+ async failed(limit = 100, tenantId) {
110
+ const tenant = this.tenantColumn;
111
+ const where = tenant && tenantId !== void 0 ? ` AND ${tenant} = $2` : "";
112
+ const params = [limit];
113
+ if (where) params.push(tenantId);
114
+ const { rows } = await this.options.pool.query(
115
+ `SELECT id, type, last_error, attempts, created_at${tenant ? `, ${tenant} AS tenant_id` : ""}
116
+ FROM ${this.table} WHERE status = 'failed'${where} ORDER BY created_at DESC LIMIT $1`,
117
+ params
118
+ );
119
+ return rows.map((r) => ({
120
+ id: r.id,
121
+ type: r.type,
122
+ error: r.last_error ?? null,
123
+ attempts: r.attempts,
124
+ createdAt: new Date(r.created_at).toISOString(),
125
+ ...tenant ? { tenantId: r.tenant_id ?? null } : {}
126
+ }));
127
+ }
128
+ /**
129
+ * Puts a failed job back in the queue. Attempts reset: whoever requeues has
130
+ * fixed the cause, and keeping the counter would return it to the tray on
131
+ * the first stumble. `false` if it was not in the tray.
132
+ */
133
+ async requeue(id) {
134
+ const { rows } = await this.options.pool.query(
135
+ `UPDATE ${this.table} SET status = 'pending', attempts = 0, deferrals = 0, run_at = now(),
136
+ locked_at = NULL, updated_at = now()
137
+ WHERE id = $1 AND status = 'failed' RETURNING id`,
138
+ [id]
139
+ );
140
+ return rows.length > 0;
141
+ }
142
+ /** Takes and runs ONE job. Returns true if it took one (whatever the outcome). */
143
+ async processOne() {
144
+ const types = [...this.handlers.keys()];
145
+ if (types.length === 0) return false;
146
+ const tenant = this.tenantColumn;
147
+ const { rows } = await this.options.pool.query(
148
+ `WITH next AS (
149
+ SELECT id FROM ${this.table}
150
+ WHERE type = ANY($1::text[]) AND run_at <= now()
151
+ AND (status = 'pending' OR (status = 'taken' AND locked_at < ${this.lockCutoff()}))
152
+ ORDER BY run_at, created_at LIMIT 1 FOR UPDATE SKIP LOCKED)
153
+ UPDATE ${this.table} j SET status = 'taken', attempts = j.attempts + 1, locked_at = now(), updated_at = now()
154
+ FROM next WHERE j.id = next.id
155
+ RETURNING j.id, j.type, j.payload, j.attempts, j.deferrals${tenant ? `, j.${tenant} AS tenant_id` : ""}`,
156
+ [types, this.options.lockTimeoutMs ?? DEFAULTS.lockTimeoutMs]
157
+ );
158
+ const row = rows[0];
159
+ if (!row) return false;
160
+ const job = {
161
+ id: row.id,
162
+ type: row.type,
163
+ payload: row.payload ?? {},
164
+ attempts: row.attempts,
165
+ deferrals: row.deferrals,
166
+ ...tenant ? { tenantId: row.tenant_id ?? null } : {}
167
+ };
168
+ const handler = this.handlers.get(job.type);
169
+ try {
170
+ if (!handler) throw new Error(`No handler registered for "${job.type}"`);
171
+ await handler(job);
172
+ await this.options.pool.query(
173
+ `UPDATE ${this.table} SET status = 'done', last_error = NULL, locked_at = NULL, updated_at = now() WHERE id = $1`,
174
+ [job.id]
175
+ );
176
+ } catch (error) {
177
+ await this.handleFailure(job, error);
178
+ }
179
+ return true;
180
+ }
181
+ lockCutoff() {
182
+ return `now() - make_interval(secs => $2::double precision / 1000)`;
183
+ }
184
+ async handleFailure(job, error) {
185
+ const message = (error instanceof Error ? error.message : String(error)).slice(0, 500);
186
+ const maxDeferrals = this.options.maxDeferrals ?? DEFAULTS.maxDeferrals;
187
+ if (error instanceof DeferJob && job.deferrals < maxDeferrals) {
188
+ const wait2 = error.retryAfterMs ?? defaultDeferral(job.deferrals);
189
+ await this.options.pool.query(
190
+ `UPDATE ${this.table} SET status = 'pending', attempts = GREATEST(attempts - 1, 0),
191
+ deferrals = deferrals + 1, run_at = ${WAIT(2)}, last_error = $3, locked_at = NULL, updated_at = now()
192
+ WHERE id = $1`,
193
+ [job.id, wait2, message]
194
+ );
195
+ this.log.warn(`Job ${job.type} deferred ${Math.ceil(wait2 / 1e3)} s: ${message}`);
196
+ return;
197
+ }
198
+ const maxAttempts = this.options.maxAttempts ?? DEFAULTS.maxAttempts;
199
+ if (error instanceof DeferJob || job.attempts >= maxAttempts) {
200
+ await this.options.pool.query(
201
+ `UPDATE ${this.table} SET status = 'failed', last_error = $2, locked_at = NULL, updated_at = now() WHERE id = $1`,
202
+ [job.id, message]
203
+ );
204
+ this.log.error(`Job ${job.type} exhausted its attempts: ${message}`);
205
+ try {
206
+ await this.options.onDead?.(job, error);
207
+ } catch (hookError) {
208
+ this.log.error(`onDead failed: ${String(hookError)}`);
209
+ }
210
+ return;
211
+ }
212
+ const wait = (this.options.backoff ?? defaultBackoff)(job.attempts);
213
+ await this.options.pool.query(
214
+ `UPDATE ${this.table} SET status = 'pending', run_at = ${WAIT(2)}, last_error = $3, locked_at = NULL, updated_at = now()
215
+ WHERE id = $1`,
216
+ [job.id, wait, message]
217
+ );
218
+ this.log.warn(`Job ${job.type} failed (attempt ${job.attempts}): ${message}`);
219
+ }
220
+ schedule(ms) {
221
+ if (this.stopped) return;
222
+ this.timer = setTimeout(() => void this.tick(), ms);
223
+ this.timer.unref?.();
224
+ }
225
+ async tick() {
226
+ if (this.running || this.stopped) return;
227
+ this.running = true;
228
+ try {
229
+ const did = await this.processOne();
230
+ this.schedule(did ? 0 : this.options.pollMs ?? DEFAULTS.pollMs);
231
+ } catch (error) {
232
+ this.log.error(`Worker cycle failed: ${String(error)}`);
233
+ this.schedule(this.options.pollMs ?? DEFAULTS.pollMs);
234
+ } finally {
235
+ this.running = false;
236
+ }
237
+ }
238
+ /** The migration for this configuration. */
239
+ createTableSql() {
240
+ return createTableSql(this.table, this.tenantColumn);
241
+ }
242
+ };
243
+ JobsService = __decorateClass([
244
+ Injectable(),
245
+ __decorateParam(0, Inject(JOBS_OPTIONS))
246
+ ], JobsService);
247
+
248
+ // src/jobs/jobs-admin.controller.ts
249
+ import { Controller, Get, Inject as Inject2, NotFoundException, Param, Post, Query, UseGuards } from "@nestjs/common";
250
+ function createJobsAdminController(options = {}) {
251
+ let JobsAdminController = class {
252
+ constructor(jobs) {
253
+ this.jobs = jobs;
254
+ }
255
+ failed(limit) {
256
+ const n = Math.min(Math.max(Number(limit) || 100, 1), 500);
257
+ return this.jobs.failed(n);
258
+ }
259
+ async requeue(id) {
260
+ if (!await this.jobs.requeue(id)) throw new NotFoundException("That job is not in the failed tray");
261
+ return { ok: true };
262
+ }
263
+ };
264
+ __decorateClass([
265
+ Get("failed"),
266
+ __decorateParam(0, Query("limit"))
267
+ ], JobsAdminController.prototype, "failed", 1);
268
+ __decorateClass([
269
+ Post(":id/requeue"),
270
+ __decorateParam(0, Param("id"))
271
+ ], JobsAdminController.prototype, "requeue", 1);
272
+ JobsAdminController = __decorateClass([
273
+ Controller(options.path ?? "jobs"),
274
+ UseGuards(...options.guards ?? []),
275
+ __decorateParam(0, Inject2(JobsService))
276
+ ], JobsAdminController);
277
+ return JobsAdminController;
278
+ }
279
+
280
+ // src/jobs/jobs.module.ts
281
+ import { Global, Module } from "@nestjs/common";
282
+ var JobsModule = class {
283
+ static forRoot(options) {
284
+ const { admin, ...rest } = options;
285
+ return this.build([{ provide: JOBS_OPTIONS, useValue: rest }], [], admin);
286
+ }
287
+ static forRootAsync(config) {
288
+ return this.build(
289
+ [{ provide: JOBS_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] }],
290
+ config.imports ?? [],
291
+ config.admin
292
+ );
293
+ }
294
+ static build(providers, imports, admin) {
295
+ const controllers = admin === void 0 || admin === false ? [] : [createJobsAdminController(admin)];
296
+ return {
297
+ module: JobsModule,
298
+ imports,
299
+ controllers,
300
+ providers: [...providers, JobsService],
301
+ exports: [JOBS_OPTIONS, JobsService]
302
+ };
303
+ }
304
+ };
305
+ /** The migration SQL (table + indexes). */
306
+ JobsModule.createTableSql = createTableSql;
307
+ JobsModule = __decorateClass([
308
+ Global(),
309
+ Module({})
310
+ ], JobsModule);
311
+ export {
312
+ DeferJob,
313
+ JOBS_OPTIONS,
314
+ JobsModule,
315
+ JobsService,
316
+ createJobsAdminController,
317
+ createTableSql as createJobsTableSql
318
+ };
@@ -0,0 +1,18 @@
1
+ import { type Type } from '@nestjs/common';
2
+ export interface JobsAdminOptions {
3
+ /** Route prefix. Defaults to `jobs`. */
4
+ path?: string;
5
+ /** Guards the host puts in front (auth, permissions). Without any, the routes are OPEN: always pass some. */
6
+ guards?: Type<any>[];
7
+ }
8
+ /**
9
+ * Builds the failed-tray controller:
10
+ *
11
+ * - `GET /<path>/failed?limit=` → the tray.
12
+ * - `POST /<path>/:id/requeue` → back to the queue with attempts reset.
13
+ *
14
+ * It ships no access rules of its own; the host brings its guards (the
15
+ * library does not know your roles). Requeueing re-fires charges and
16
+ * stampings, so give it a stricter permission than reading.
17
+ */
18
+ export declare function createJobsAdminController(options?: JobsAdminOptions): Type<any>;