@miguelmorales13/nestkit 0.11.0 → 0.16.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 (90) hide show
  1. package/README.md +469 -9
  2. package/dist/audit/audit.module.d.ts +23 -0
  3. package/dist/audit/audit.options.d.ts +16 -0
  4. package/dist/audit/audit.port.d.ts +37 -0
  5. package/dist/audit/audit.service.d.ts +29 -0
  6. package/dist/audit/index.cjs +72 -0
  7. package/dist/audit/index.d.ts +7 -0
  8. package/dist/audit/index.js +72 -0
  9. package/dist/audit/sinks.d.ts +18 -0
  10. package/dist/auth/index.cjs +4 -3
  11. package/dist/auth/index.js +2 -1
  12. package/dist/auth/oauth/index.cjs +6 -5
  13. package/dist/auth/oauth/index.js +2 -1
  14. package/dist/bootstrap/index.cjs +6 -5
  15. package/dist/bootstrap/index.js +5 -4
  16. package/dist/chunk-47FXU74G.cjs +205 -0
  17. package/dist/{chunk-54ZXIB5T.cjs → chunk-4GT66KQS.cjs} +4 -4
  18. package/dist/{chunk-J7TURDAL.cjs → chunk-67B7IYAV.cjs} +2 -2
  19. package/dist/{chunk-NVCI3CQI.cjs → chunk-C5DV4RAX.cjs} +6 -1
  20. package/dist/{chunk-KDAA6GFF.js → chunk-DABTRWA6.js} +12 -7
  21. package/dist/{chunk-ZA56XBCK.cjs → chunk-EBPEMVZU.cjs} +15 -0
  22. package/dist/{chunk-EYURGACO.js → chunk-JV4EAOF2.js} +1 -1
  23. package/dist/chunk-KP2ZHJSR.js +35 -0
  24. package/dist/{chunk-7I2Y7V52.js → chunk-KRC47OX6.js} +1 -1
  25. package/dist/chunk-LK3OINS7.js +205 -0
  26. package/dist/{chunk-A3B2EY4V.js → chunk-MLOQDUBN.js} +6 -1
  27. package/dist/chunk-TCAMLNUZ.js +27 -0
  28. package/dist/{chunk-V2M75FN3.cjs → chunk-U7QK24HL.cjs} +2 -2
  29. package/dist/{chunk-AOCF5QCZ.js → chunk-UIVBPNH4.js} +4 -4
  30. package/dist/{chunk-TJHRABML.cjs → chunk-UWDHAZVE.cjs} +12 -7
  31. package/dist/chunk-XHW4CTBS.js +57 -0
  32. package/dist/chunk-XX5ROVSC.cjs +57 -0
  33. package/dist/chunk-Y72D5L6I.cjs +27 -0
  34. package/dist/crud/crud.controller.d.ts +3 -1
  35. package/dist/crud/crud.service.d.ts +63 -4
  36. package/dist/crud/index.cjs +7 -2
  37. package/dist/crud/index.d.ts +2 -1
  38. package/dist/crud/index.js +6 -1
  39. package/dist/crud/list-query.dto.d.ts +23 -0
  40. package/dist/crud/repository.port.d.ts +33 -1
  41. package/dist/errors/index.cjs +4 -4
  42. package/dist/errors/index.js +4 -4
  43. package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
  44. package/dist/idempotency/idempotency.module.d.ts +27 -0
  45. package/dist/idempotency/idempotency.options.d.ts +29 -0
  46. package/dist/idempotency/idempotency.port.d.ts +43 -0
  47. package/dist/idempotency/index.cjs +206 -0
  48. package/dist/idempotency/index.d.ts +7 -0
  49. package/dist/idempotency/index.js +206 -0
  50. package/dist/idempotency/memory.store.d.ts +24 -0
  51. package/dist/index.cjs +26 -15
  52. package/dist/index.js +27 -16
  53. package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
  54. package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
  55. package/dist/invoicing/amounts.d.ts +52 -0
  56. package/dist/invoicing/index.cjs +577 -0
  57. package/dist/invoicing/index.d.ts +11 -0
  58. package/dist/invoicing/index.js +577 -0
  59. package/dist/invoicing/invoicing.module.d.ts +42 -0
  60. package/dist/invoicing/invoicing.options.d.ts +51 -0
  61. package/dist/invoicing/invoicing.port.d.ts +156 -0
  62. package/dist/invoicing/lines.d.ts +21 -0
  63. package/dist/invoicing/provider-http.d.ts +21 -0
  64. package/dist/payments/adapters/clip.terminal.d.ts +101 -0
  65. package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
  66. package/dist/payments/index.cjs +795 -0
  67. package/dist/payments/index.d.ts +12 -0
  68. package/dist/payments/index.js +795 -0
  69. package/dist/payments/money.d.ts +20 -0
  70. package/dist/payments/payments-webhook.controller.d.ts +30 -0
  71. package/dist/payments/payments.module.d.ts +45 -0
  72. package/dist/payments/payments.options.d.ts +84 -0
  73. package/dist/payments/payments.port.d.ts +174 -0
  74. package/dist/payments/provider-http.d.ts +26 -0
  75. package/dist/response/api-response.d.ts +7 -0
  76. package/dist/response/index.cjs +12 -4
  77. package/dist/response/index.d.ts +2 -0
  78. package/dist/response/index.js +12 -4
  79. package/dist/response/paginated.d.ts +25 -0
  80. package/dist/response/response.interceptor.d.ts +4 -0
  81. package/dist/tracking/index.cjs +3 -3
  82. package/dist/tracking/index.d.ts +1 -1
  83. package/dist/tracking/index.js +2 -2
  84. package/dist/tracking/request-context.d.ts +22 -0
  85. package/package.json +25 -3
  86. package/dist/chunk-3CLYZC3T.cjs +0 -104
  87. package/dist/chunk-EBO6UKHL.js +0 -20
  88. package/dist/chunk-JOVBJDJ2.js +0 -104
  89. /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
  90. /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
@@ -1,4 +1,31 @@
1
1
  import type { BaseEntity } from '../entities/base.entity.js';
2
+ /** What a list query asks of the adapter, already validated and capped. */
3
+ export interface FindAllOptions<T> {
4
+ /** Equality filter. Only the fields the service allows ever reach here. */
5
+ filter?: Partial<T>;
6
+ /** How many rows to return. Always set by `BaseCrudService`. */
7
+ limit?: number;
8
+ offset?: number;
9
+ /**
10
+ * Column to order by — **already checked against an allowlist**. Adapters
11
+ * build SQL by interpolating this name, so an adapter must never accept one
12
+ * straight from a request.
13
+ */
14
+ sortBy?: string;
15
+ sortOrder?: 'asc' | 'desc';
16
+ }
17
+ /**
18
+ * One page of rows plus the total the filter matches.
19
+ *
20
+ * The total is what a pager needs and the one thing the adapter cannot skip:
21
+ * `items.length` only says how full the page is. An adapter that genuinely
22
+ * cannot count cheaply should still return something honest — the count of a
23
+ * bounded query — rather than a number nobody can act on.
24
+ */
25
+ export interface PageResult<T> {
26
+ items: T[];
27
+ total: number;
28
+ }
2
29
  /**
3
30
  * Persistence port every adapter (Postgres, Supabase, future Mongo, or a
4
31
  * hand-rolled one) implements. `tenantId` is optional so the same port
@@ -7,7 +34,12 @@ import type { BaseEntity } from '../entities/base.entity.js';
7
34
  */
8
35
  export interface Repository<T extends BaseEntity, ID = string> {
9
36
  findById(id: ID, tenantId?: string): Promise<T | null>;
10
- findAll(filter?: Partial<T>, tenantId?: string): Promise<T[]>;
37
+ /**
38
+ * A page of rows. Always bounded: `BaseCrudService` fills in a limit even
39
+ * when the caller asked for none, because the unbounded version of this
40
+ * method is a table scan waiting for the table to grow.
41
+ */
42
+ findAll(options?: FindAllOptions<T>, tenantId?: string): Promise<PageResult<T>>;
11
43
  create(data: Omit<T, 'id' | 'createdAt' | 'updatedAt'>, tenantId?: string): Promise<T>;
12
44
  update(id: ID, data: Partial<T>, tenantId?: string): Promise<T>;
13
45
  delete(id: ID, tenantId?: string): Promise<void>;
@@ -1,15 +1,15 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});require('../chunk-7SOM7EZP.cjs');
2
2
 
3
3
 
4
+ var _chunk67B7IYAVcjs = require('../chunk-67B7IYAV.cjs');
5
+ require('../chunk-EBPEMVZU.cjs');
4
6
 
5
7
 
6
8
 
7
9
 
8
- var _chunkFDNGAYTZcjs = require('../chunk-FDNGAYTZ.cjs');
9
10
 
10
11
 
11
- var _chunkJ7TURDALcjs = require('../chunk-J7TURDAL.cjs');
12
- require('../chunk-ZA56XBCK.cjs');
12
+ var _chunkFDNGAYTZcjs = require('../chunk-FDNGAYTZ.cjs');
13
13
 
14
14
 
15
15
  var _chunkR7BVS6CIcjs = require('../chunk-R7BVS6CI.cjs');
@@ -22,4 +22,4 @@ require('../chunk-2REOCMUD.cjs');
22
22
 
23
23
 
24
24
 
25
- exports.AppException = _chunkR7BVS6CIcjs.AppException; exports.ConflictAppException = _chunkFDNGAYTZcjs.ConflictAppException; exports.ForbiddenAppException = _chunkFDNGAYTZcjs.ForbiddenAppException; exports.GlobalExceptionFilter = _chunkJ7TURDALcjs.GlobalExceptionFilter; exports.NotFoundAppException = _chunkFDNGAYTZcjs.NotFoundAppException; exports.UnauthorizedAppException = _chunkFDNGAYTZcjs.UnauthorizedAppException; exports.ValidationAppException = _chunkFDNGAYTZcjs.ValidationAppException;
25
+ exports.AppException = _chunkR7BVS6CIcjs.AppException; exports.ConflictAppException = _chunkFDNGAYTZcjs.ConflictAppException; exports.ForbiddenAppException = _chunkFDNGAYTZcjs.ForbiddenAppException; exports.GlobalExceptionFilter = _chunk67B7IYAVcjs.GlobalExceptionFilter; exports.NotFoundAppException = _chunkFDNGAYTZcjs.NotFoundAppException; exports.UnauthorizedAppException = _chunkFDNGAYTZcjs.UnauthorizedAppException; exports.ValidationAppException = _chunkFDNGAYTZcjs.ValidationAppException;
@@ -1,4 +1,8 @@
1
1
  import "../chunk-DQYAIQQ5.js";
2
+ import {
3
+ GlobalExceptionFilter
4
+ } from "../chunk-KRC47OX6.js";
5
+ import "../chunk-KP2ZHJSR.js";
2
6
  import {
3
7
  ConflictAppException,
4
8
  ForbiddenAppException,
@@ -6,10 +10,6 @@ import {
6
10
  UnauthorizedAppException,
7
11
  ValidationAppException
8
12
  } from "../chunk-ORWJ7LES.js";
9
- import {
10
- GlobalExceptionFilter
11
- } from "../chunk-7I2Y7V52.js";
12
- import "../chunk-EBO6UKHL.js";
13
13
  import {
14
14
  AppException
15
15
  } from "../chunk-YFYHLYHN.js";
@@ -0,0 +1,35 @@
1
+ import { type CallHandler, type ExecutionContext, type NestInterceptor } from '@nestjs/common';
2
+ import { type Observable } from 'rxjs';
3
+ import { type IdempotencyOptions } from './idempotency.options.js';
4
+ import { type IdempotencyStorePort } from './idempotency.port.js';
5
+ /**
6
+ * Replays the answer to a request that was already handled.
7
+ *
8
+ * The problem it solves is not exotic: a client on a slow connection taps
9
+ * twice, or a proxy retries a timed-out POST. Before `payments` and `invoicing`
10
+ * that meant a duplicated row; now it means a second card charge, or a second
11
+ * CFDI — and a CFDI cannot be deleted, only cancelled with a reason filed at
12
+ * the SAT.
13
+ *
14
+ * Three outcomes for a key that has been seen:
15
+ * - **finished** → the stored answer is returned, with `Idempotent-Replay: true`.
16
+ * - **still running** → 409, rather than waiting. Holding the second request
17
+ * open ties its lifetime to the first one's, and a client that retried
18
+ * because things were slow is the worst one to make wait again.
19
+ * - **same key, different body** → 422. Replaying an answer to a request nobody
20
+ * made is worse than failing: the client would read "created" about an object
21
+ * that does not exist.
22
+ *
23
+ * Only successful answers are remembered. An error releases the key so a retry
24
+ * genuinely retries — which means a handler that failed *after* its side effect
25
+ * will run it twice. That is why the side effect carries its own key too:
26
+ * `payments.charge()` and Mercado Pago's `X-Idempotency-Key` are the layer that
27
+ * survives this one.
28
+ */
29
+ export declare class IdempotencyInterceptor implements NestInterceptor {
30
+ private readonly store;
31
+ private readonly options;
32
+ constructor(store: IdempotencyStorePort, options?: IdempotencyOptions);
33
+ intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>;
34
+ private mismatch;
35
+ }
@@ -0,0 +1,27 @@
1
+ import { type DynamicModule } from '@nestjs/common';
2
+ import { type IdempotencyOptions } from './idempotency.options.js';
3
+ /**
4
+ * Replay protection for the endpoints that change things.
5
+ *
6
+ * ```ts
7
+ * // app.module.ts
8
+ * IdempotencyModule.forRoot() // memoria, una sola instancia
9
+ * IdempotencyModule.forRoot({ store: new RedisIdempotencyStore(redis) })
10
+ *
11
+ * // main.ts, o en un controller con @UseInterceptors
12
+ * app.useGlobalInterceptors(app.get(IdempotencyInterceptor));
13
+ * ```
14
+ *
15
+ * Deliberately **not** wired into `applyNestKitDefaults`: it needs a store
16
+ * whose lifetime the app owns, and switching it on globally changes the
17
+ * contract of every mutating endpoint at once. Mounting it is a decision, not
18
+ * a default.
19
+ */
20
+ export declare class IdempotencyModule {
21
+ static forRoot(options?: IdempotencyOptions): DynamicModule;
22
+ static forRootAsync(config: {
23
+ imports?: any[];
24
+ inject?: any[];
25
+ useFactory: (...args: any[]) => IdempotencyOptions | Promise<IdempotencyOptions>;
26
+ }): DynamicModule;
27
+ }
@@ -0,0 +1,29 @@
1
+ import type { IdempotencyStorePort } from './idempotency.port.js';
2
+ /** DI token carrying the resolved {@link IdempotencyOptions}. */
3
+ export declare const IDEMPOTENCY_OPTIONS: unique symbol;
4
+ export interface IdempotencyOptions {
5
+ /** Header carrying the key. Defaults to `idempotency-key`, the name Stripe made standard. */
6
+ headerName?: string;
7
+ /** Methods this applies to. Defaults to POST, PUT, PATCH and DELETE — the ones that change things. */
8
+ methods?: string[];
9
+ /** How long an answer stays replayable. Defaults to 24 hours. */
10
+ ttlMs?: number;
11
+ /**
12
+ * Reject an unsafe request that arrives without a key. Off by default:
13
+ * turning it on breaks every existing client at once, so it belongs to a
14
+ * deliberate rollout.
15
+ */
16
+ require?: boolean;
17
+ /**
18
+ * Who the key belongs to. Two customers sending the same key —
19
+ * `"order-1"` is not imaginative — must not read each other's answers.
20
+ *
21
+ * Defaults to the authenticated subject (`req.user.sub`, which is what
22
+ * `JwtAuthGuard` attaches). Unauthenticated requests fall back to a shared
23
+ * scope, so on a public endpoint **set this to something per-caller** or keys
24
+ * are global.
25
+ */
26
+ scope?: (request: unknown) => string | undefined;
27
+ /** Where keys live. Defaults to an in-process store — single instance only. */
28
+ store?: IdempotencyStorePort;
29
+ }
@@ -0,0 +1,43 @@
1
+ /** DI token for the idempotency store. Inject with `@Inject(IDEMPOTENCY_STORE)`. */
2
+ export declare const IDEMPOTENCY_STORE: unique symbol;
3
+ /** What is replayed when the same key comes back. */
4
+ export interface IdempotencyRecord {
5
+ status: number;
6
+ body: unknown;
7
+ /** Hash of the request that first used this key. */
8
+ fingerprint: string;
9
+ completedAt: Date;
10
+ }
11
+ export type BeginResult =
12
+ /** The key is ours; run the handler. */
13
+ {
14
+ state: 'claimed';
15
+ }
16
+ /** Another request holds the key and has not finished. */
17
+ | {
18
+ state: 'in_progress';
19
+ fingerprint: string;
20
+ }
21
+ /** The key was used before and there is an answer to replay. */
22
+ | {
23
+ state: 'completed';
24
+ record: IdempotencyRecord;
25
+ };
26
+ /**
27
+ * Where claimed keys and their answers live.
28
+ *
29
+ * `begin` has to be **atomic**: claim-if-absent in one operation. A read
30
+ * followed by a write loses exactly the race this whole module exists for —
31
+ * two identical requests arriving together, which is what a double tap on a
32
+ * slow connection produces.
33
+ */
34
+ export interface IdempotencyStorePort {
35
+ begin(key: string, fingerprint: string, ttlMs: number): Promise<BeginResult>;
36
+ /** Store the answer and stop holding the key as in-progress. */
37
+ complete(key: string, record: IdempotencyRecord, ttlMs: number): Promise<void>;
38
+ /**
39
+ * Give the key up without an answer, so a retry can try again. Used when the
40
+ * handler failed in a way that might not fail twice.
41
+ */
42
+ release(key: string): Promise<void>;
43
+ }
@@ -0,0 +1,206 @@
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 _chunkFDNGAYTZcjs = require('../chunk-FDNGAYTZ.cjs');
5
+ require('../chunk-R7BVS6CI.cjs');
6
+
7
+
8
+
9
+ var _chunk2REOCMUDcjs = require('../chunk-2REOCMUD.cjs');
10
+
11
+ // src/idempotency/idempotency.port.ts
12
+ var IDEMPOTENCY_STORE = /* @__PURE__ */ Symbol("IDEMPOTENCY_STORE");
13
+
14
+ // src/idempotency/idempotency.options.ts
15
+ var IDEMPOTENCY_OPTIONS = /* @__PURE__ */ Symbol("IDEMPOTENCY_OPTIONS");
16
+
17
+ // src/idempotency/memory.store.ts
18
+ var MemoryIdempotencyStore = class {
19
+ constructor(maxEntries = 1e4) {
20
+ this.maxEntries = maxEntries;
21
+ this.entries = /* @__PURE__ */ new Map();
22
+ }
23
+ async begin(key, fingerprint, ttlMs) {
24
+ this.evictExpired();
25
+ const existing = this.entries.get(key);
26
+ if (existing) {
27
+ return existing.record ? { state: "completed", record: existing.record } : { state: "in_progress", fingerprint: existing.fingerprint };
28
+ }
29
+ if (this.entries.size >= this.maxEntries) {
30
+ const oldest = this.entries.keys().next();
31
+ if (!oldest.done) this.entries.delete(oldest.value);
32
+ }
33
+ this.entries.set(key, { fingerprint, expiresAt: Date.now() + ttlMs });
34
+ return { state: "claimed" };
35
+ }
36
+ async complete(key, record, ttlMs) {
37
+ this.entries.set(key, { fingerprint: record.fingerprint, expiresAt: Date.now() + ttlMs, record });
38
+ }
39
+ async release(key) {
40
+ this.entries.delete(key);
41
+ }
42
+ /** Visible for tests and for a health endpoint that wants to report size. */
43
+ get size() {
44
+ return this.entries.size;
45
+ }
46
+ evictExpired() {
47
+ const now = Date.now();
48
+ for (const [key, entry] of this.entries) {
49
+ if (entry.expiresAt <= now) this.entries.delete(key);
50
+ }
51
+ }
52
+ };
53
+
54
+ // src/idempotency/idempotency.interceptor.ts
55
+ var _crypto = require('crypto');
56
+
57
+
58
+
59
+ var _common = require('@nestjs/common');
60
+ var _rxjs = require('rxjs');
61
+ var _operators = require('rxjs/operators');
62
+ var DEFAULT_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
63
+ var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
64
+ function headerOf(request, name) {
65
+ const value = _nullishCoalesce(_optionalChain([request, 'access', _ => _.headers, 'optionalAccess', _2 => _2[name]]), () => ( _optionalChain([request, 'access', _3 => _3.headers, 'optionalAccess', _4 => _4[name.toLowerCase()]])));
66
+ return Array.isArray(value) ? value[0] : value;
67
+ }
68
+ function stableStringify(value) {
69
+ if (value === null || typeof value !== "object") return _nullishCoalesce(JSON.stringify(value), () => ( "null"));
70
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
71
+ const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1);
72
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
73
+ }
74
+ function setHeader(response, name, value) {
75
+ if (typeof _optionalChain([response, 'optionalAccess', _5 => _5.header]) === "function") response.header(name, value);
76
+ else if (typeof _optionalChain([response, 'optionalAccess', _6 => _6.setHeader]) === "function") response.setHeader(name, value);
77
+ }
78
+ var IdempotencyInterceptor = class {
79
+ constructor(store, options = {}) {
80
+ this.store = store;
81
+ this.options = options;
82
+ }
83
+ intercept(context, next) {
84
+ const http = context.switchToHttp();
85
+ const request = http.getRequest();
86
+ const response = http.getResponse();
87
+ const methods = _nullishCoalesce(this.options.methods, () => ( DEFAULT_METHODS));
88
+ const method = String(_nullishCoalesce(_optionalChain([request, 'optionalAccess', _7 => _7.method]), () => ( "GET"))).toUpperCase();
89
+ if (!methods.includes(method)) return next.handle();
90
+ const headerName = _nullishCoalesce(this.options.headerName, () => ( "idempotency-key"));
91
+ const key = headerOf(request, headerName);
92
+ if (!key) {
93
+ if (this.options.require) {
94
+ throw new (0, _chunkFDNGAYTZcjs.ValidationAppException)(
95
+ `This endpoint requires an ${headerName} header`,
96
+ { header: headerName },
97
+ "IDEMPOTENCY_KEY_REQUIRED"
98
+ );
99
+ }
100
+ return next.handle();
101
+ }
102
+ const ttlMs = _nullishCoalesce(this.options.ttlMs, () => ( DEFAULT_TTL_MS));
103
+ const scope = this.options.scope ? this.options.scope(request) : _optionalChain([request, 'optionalAccess', _8 => _8.user, 'optionalAccess', _9 => _9.sub]);
104
+ const storeKey = `${_nullishCoalesce(scope, () => ( "anonymous"))}:${key}`;
105
+ const path = _nullishCoalesce(_nullishCoalesce(_optionalChain([request, 'optionalAccess', _10 => _10.originalUrl]), () => ( _optionalChain([request, 'optionalAccess', _11 => _11.url]))), () => ( ""));
106
+ const fingerprint = _crypto.createHash.call(void 0, "sha256").update(`${method} ${path} ${stableStringify(_nullishCoalesce(_optionalChain([request, 'optionalAccess', _12 => _12.body]), () => ( null)))}`).digest("hex");
107
+ return _rxjs.from.call(void 0, this.store.begin(storeKey, fingerprint, ttlMs)).pipe(
108
+ _operators.switchMap.call(void 0, (begin) => {
109
+ if (begin.state === "completed") {
110
+ if (begin.record.fingerprint !== fingerprint) throw this.mismatch(headerName);
111
+ setHeader(response, "idempotent-replay", "true");
112
+ if (typeof _optionalChain([response, 'optionalAccess', _13 => _13.status]) === "function") response.status(begin.record.status);
113
+ return _rxjs.of.call(void 0, begin.record.body);
114
+ }
115
+ if (begin.state === "in_progress") {
116
+ if (begin.fingerprint !== fingerprint) throw this.mismatch(headerName);
117
+ throw new (0, _chunkFDNGAYTZcjs.ConflictAppException)(
118
+ "A request with this idempotency key is still being processed",
119
+ { key },
120
+ "IDEMPOTENCY_IN_PROGRESS"
121
+ );
122
+ }
123
+ return next.handle().pipe(
124
+ // Awaited, not fire-and-forget: an answer that has not been stored
125
+ // yet is not replayable, and the retry this protects against is
126
+ // exactly the one that arrives immediately.
127
+ _operators.concatMap.call(void 0, async (body) => {
128
+ await this.store.complete(
129
+ storeKey,
130
+ { status: Number(_nullishCoalesce(_optionalChain([response, 'optionalAccess', _14 => _14.statusCode]), () => ( 200))), body, fingerprint, completedAt: /* @__PURE__ */ new Date() },
131
+ ttlMs
132
+ );
133
+ return body;
134
+ }),
135
+ _operators.catchError.call(void 0, (error) => {
136
+ return _rxjs.from.call(void 0, this.store.release(storeKey)).pipe(
137
+ _operators.switchMap.call(void 0, () => {
138
+ throw error;
139
+ })
140
+ );
141
+ })
142
+ );
143
+ })
144
+ );
145
+ }
146
+ mismatch(headerName) {
147
+ return new (0, _chunkFDNGAYTZcjs.ValidationAppException)(
148
+ `This ${headerName} was already used for a different request`,
149
+ void 0,
150
+ "IDEMPOTENCY_KEY_REUSED"
151
+ );
152
+ }
153
+ };
154
+ IdempotencyInterceptor = exports.IdempotencyInterceptor = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
155
+ _common.Injectable.call(void 0, ),
156
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, IDEMPOTENCY_STORE)),
157
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, IDEMPOTENCY_OPTIONS))
158
+ ], IdempotencyInterceptor);
159
+
160
+ // src/idempotency/idempotency.module.ts
161
+
162
+ var IdempotencyModule = class {
163
+ static forRoot(options = {}) {
164
+ const providers = [
165
+ { provide: IDEMPOTENCY_OPTIONS, useValue: options },
166
+ {
167
+ provide: IDEMPOTENCY_STORE,
168
+ useFactory: () => _nullishCoalesce(options.store, () => ( new MemoryIdempotencyStore()))
169
+ },
170
+ IdempotencyInterceptor
171
+ ];
172
+ return {
173
+ module: IdempotencyModule,
174
+ providers,
175
+ exports: [IDEMPOTENCY_STORE, IDEMPOTENCY_OPTIONS, IdempotencyInterceptor]
176
+ };
177
+ }
178
+ static forRootAsync(config) {
179
+ const providers = [
180
+ { provide: IDEMPOTENCY_OPTIONS, useFactory: config.useFactory, inject: _nullishCoalesce(config.inject, () => ( [])) },
181
+ {
182
+ provide: IDEMPOTENCY_STORE,
183
+ useFactory: (options) => _nullishCoalesce(options.store, () => ( new MemoryIdempotencyStore())),
184
+ inject: [IDEMPOTENCY_OPTIONS]
185
+ },
186
+ IdempotencyInterceptor
187
+ ];
188
+ return {
189
+ module: IdempotencyModule,
190
+ imports: _nullishCoalesce(config.imports, () => ( [])),
191
+ providers,
192
+ exports: [IDEMPOTENCY_STORE, IDEMPOTENCY_OPTIONS, IdempotencyInterceptor]
193
+ };
194
+ }
195
+ };
196
+ IdempotencyModule = exports.IdempotencyModule = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
197
+ _common.Global.call(void 0, ),
198
+ _common.Module.call(void 0, {})
199
+ ], IdempotencyModule);
200
+
201
+
202
+
203
+
204
+
205
+
206
+ exports.IDEMPOTENCY_OPTIONS = IDEMPOTENCY_OPTIONS; exports.IDEMPOTENCY_STORE = IDEMPOTENCY_STORE; exports.IdempotencyInterceptor = IdempotencyInterceptor; exports.IdempotencyModule = IdempotencyModule; exports.MemoryIdempotencyStore = MemoryIdempotencyStore;
@@ -0,0 +1,7 @@
1
+ export { IDEMPOTENCY_STORE } from './idempotency.port.js';
2
+ export type { IdempotencyStorePort, IdempotencyRecord, BeginResult } from './idempotency.port.js';
3
+ export { IDEMPOTENCY_OPTIONS } from './idempotency.options.js';
4
+ export type { IdempotencyOptions } from './idempotency.options.js';
5
+ export { MemoryIdempotencyStore } from './memory.store.js';
6
+ export { IdempotencyInterceptor } from './idempotency.interceptor.js';
7
+ export { IdempotencyModule } from './idempotency.module.js';
@@ -0,0 +1,206 @@
1
+ import {
2
+ ConflictAppException,
3
+ ValidationAppException
4
+ } from "../chunk-ORWJ7LES.js";
5
+ import "../chunk-YFYHLYHN.js";
6
+ import {
7
+ __decorateClass,
8
+ __decorateParam
9
+ } from "../chunk-4MGIQFAJ.js";
10
+
11
+ // src/idempotency/idempotency.port.ts
12
+ var IDEMPOTENCY_STORE = /* @__PURE__ */ Symbol("IDEMPOTENCY_STORE");
13
+
14
+ // src/idempotency/idempotency.options.ts
15
+ var IDEMPOTENCY_OPTIONS = /* @__PURE__ */ Symbol("IDEMPOTENCY_OPTIONS");
16
+
17
+ // src/idempotency/memory.store.ts
18
+ var MemoryIdempotencyStore = class {
19
+ constructor(maxEntries = 1e4) {
20
+ this.maxEntries = maxEntries;
21
+ this.entries = /* @__PURE__ */ new Map();
22
+ }
23
+ async begin(key, fingerprint, ttlMs) {
24
+ this.evictExpired();
25
+ const existing = this.entries.get(key);
26
+ if (existing) {
27
+ return existing.record ? { state: "completed", record: existing.record } : { state: "in_progress", fingerprint: existing.fingerprint };
28
+ }
29
+ if (this.entries.size >= this.maxEntries) {
30
+ const oldest = this.entries.keys().next();
31
+ if (!oldest.done) this.entries.delete(oldest.value);
32
+ }
33
+ this.entries.set(key, { fingerprint, expiresAt: Date.now() + ttlMs });
34
+ return { state: "claimed" };
35
+ }
36
+ async complete(key, record, ttlMs) {
37
+ this.entries.set(key, { fingerprint: record.fingerprint, expiresAt: Date.now() + ttlMs, record });
38
+ }
39
+ async release(key) {
40
+ this.entries.delete(key);
41
+ }
42
+ /** Visible for tests and for a health endpoint that wants to report size. */
43
+ get size() {
44
+ return this.entries.size;
45
+ }
46
+ evictExpired() {
47
+ const now = Date.now();
48
+ for (const [key, entry] of this.entries) {
49
+ if (entry.expiresAt <= now) this.entries.delete(key);
50
+ }
51
+ }
52
+ };
53
+
54
+ // src/idempotency/idempotency.interceptor.ts
55
+ import { createHash } from "crypto";
56
+ import {
57
+ Inject,
58
+ Injectable
59
+ } from "@nestjs/common";
60
+ import { from, of } from "rxjs";
61
+ import { catchError, concatMap, switchMap } from "rxjs/operators";
62
+ var DEFAULT_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
63
+ var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
64
+ function headerOf(request, name) {
65
+ const value = request.headers?.[name] ?? request.headers?.[name.toLowerCase()];
66
+ return Array.isArray(value) ? value[0] : value;
67
+ }
68
+ function stableStringify(value) {
69
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
70
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
71
+ const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : 1);
72
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
73
+ }
74
+ function setHeader(response, name, value) {
75
+ if (typeof response?.header === "function") response.header(name, value);
76
+ else if (typeof response?.setHeader === "function") response.setHeader(name, value);
77
+ }
78
+ var IdempotencyInterceptor = class {
79
+ constructor(store, options = {}) {
80
+ this.store = store;
81
+ this.options = options;
82
+ }
83
+ intercept(context, next) {
84
+ const http = context.switchToHttp();
85
+ const request = http.getRequest();
86
+ const response = http.getResponse();
87
+ const methods = this.options.methods ?? DEFAULT_METHODS;
88
+ const method = String(request?.method ?? "GET").toUpperCase();
89
+ if (!methods.includes(method)) return next.handle();
90
+ const headerName = this.options.headerName ?? "idempotency-key";
91
+ const key = headerOf(request, headerName);
92
+ if (!key) {
93
+ if (this.options.require) {
94
+ throw new ValidationAppException(
95
+ `This endpoint requires an ${headerName} header`,
96
+ { header: headerName },
97
+ "IDEMPOTENCY_KEY_REQUIRED"
98
+ );
99
+ }
100
+ return next.handle();
101
+ }
102
+ const ttlMs = this.options.ttlMs ?? DEFAULT_TTL_MS;
103
+ const scope = this.options.scope ? this.options.scope(request) : request?.user?.sub;
104
+ const storeKey = `${scope ?? "anonymous"}:${key}`;
105
+ const path = request?.originalUrl ?? request?.url ?? "";
106
+ const fingerprint = createHash("sha256").update(`${method} ${path} ${stableStringify(request?.body ?? null)}`).digest("hex");
107
+ return from(this.store.begin(storeKey, fingerprint, ttlMs)).pipe(
108
+ switchMap((begin) => {
109
+ if (begin.state === "completed") {
110
+ if (begin.record.fingerprint !== fingerprint) throw this.mismatch(headerName);
111
+ setHeader(response, "idempotent-replay", "true");
112
+ if (typeof response?.status === "function") response.status(begin.record.status);
113
+ return of(begin.record.body);
114
+ }
115
+ if (begin.state === "in_progress") {
116
+ if (begin.fingerprint !== fingerprint) throw this.mismatch(headerName);
117
+ throw new ConflictAppException(
118
+ "A request with this idempotency key is still being processed",
119
+ { key },
120
+ "IDEMPOTENCY_IN_PROGRESS"
121
+ );
122
+ }
123
+ return next.handle().pipe(
124
+ // Awaited, not fire-and-forget: an answer that has not been stored
125
+ // yet is not replayable, and the retry this protects against is
126
+ // exactly the one that arrives immediately.
127
+ concatMap(async (body) => {
128
+ await this.store.complete(
129
+ storeKey,
130
+ { status: Number(response?.statusCode ?? 200), body, fingerprint, completedAt: /* @__PURE__ */ new Date() },
131
+ ttlMs
132
+ );
133
+ return body;
134
+ }),
135
+ catchError((error) => {
136
+ return from(this.store.release(storeKey)).pipe(
137
+ switchMap(() => {
138
+ throw error;
139
+ })
140
+ );
141
+ })
142
+ );
143
+ })
144
+ );
145
+ }
146
+ mismatch(headerName) {
147
+ return new ValidationAppException(
148
+ `This ${headerName} was already used for a different request`,
149
+ void 0,
150
+ "IDEMPOTENCY_KEY_REUSED"
151
+ );
152
+ }
153
+ };
154
+ IdempotencyInterceptor = __decorateClass([
155
+ Injectable(),
156
+ __decorateParam(0, Inject(IDEMPOTENCY_STORE)),
157
+ __decorateParam(1, Inject(IDEMPOTENCY_OPTIONS))
158
+ ], IdempotencyInterceptor);
159
+
160
+ // src/idempotency/idempotency.module.ts
161
+ import { Global, Module } from "@nestjs/common";
162
+ var IdempotencyModule = class {
163
+ static forRoot(options = {}) {
164
+ const providers = [
165
+ { provide: IDEMPOTENCY_OPTIONS, useValue: options },
166
+ {
167
+ provide: IDEMPOTENCY_STORE,
168
+ useFactory: () => options.store ?? new MemoryIdempotencyStore()
169
+ },
170
+ IdempotencyInterceptor
171
+ ];
172
+ return {
173
+ module: IdempotencyModule,
174
+ providers,
175
+ exports: [IDEMPOTENCY_STORE, IDEMPOTENCY_OPTIONS, IdempotencyInterceptor]
176
+ };
177
+ }
178
+ static forRootAsync(config) {
179
+ const providers = [
180
+ { provide: IDEMPOTENCY_OPTIONS, useFactory: config.useFactory, inject: config.inject ?? [] },
181
+ {
182
+ provide: IDEMPOTENCY_STORE,
183
+ useFactory: (options) => options.store ?? new MemoryIdempotencyStore(),
184
+ inject: [IDEMPOTENCY_OPTIONS]
185
+ },
186
+ IdempotencyInterceptor
187
+ ];
188
+ return {
189
+ module: IdempotencyModule,
190
+ imports: config.imports ?? [],
191
+ providers,
192
+ exports: [IDEMPOTENCY_STORE, IDEMPOTENCY_OPTIONS, IdempotencyInterceptor]
193
+ };
194
+ }
195
+ };
196
+ IdempotencyModule = __decorateClass([
197
+ Global(),
198
+ Module({})
199
+ ], IdempotencyModule);
200
+ export {
201
+ IDEMPOTENCY_OPTIONS,
202
+ IDEMPOTENCY_STORE,
203
+ IdempotencyInterceptor,
204
+ IdempotencyModule,
205
+ MemoryIdempotencyStore
206
+ };
@@ -0,0 +1,24 @@
1
+ import type { BeginResult, IdempotencyRecord, IdempotencyStorePort } from './idempotency.port.js';
2
+ /**
3
+ * In-process store. Correct for a single instance, and **wrong the moment
4
+ * there are two**: each process would hold its own keys, so the same retry
5
+ * landing on a different replica runs the handler again — which is the exact
6
+ * double charge this is meant to prevent. Behind a load balancer, back it with
7
+ * Redis or a table instead.
8
+ *
9
+ * Bounded, like `media`'s store, because it lives in the process heap. Unlike
10
+ * `media`, it **evicts the oldest** rather than rejecting: an evicted key only
11
+ * costs the protection of a retry that probably already happened, while
12
+ * refusing new keys would stop the API from accepting work at all.
13
+ */
14
+ export declare class MemoryIdempotencyStore implements IdempotencyStorePort {
15
+ private readonly maxEntries;
16
+ private readonly entries;
17
+ constructor(maxEntries?: number);
18
+ begin(key: string, fingerprint: string, ttlMs: number): Promise<BeginResult>;
19
+ complete(key: string, record: IdempotencyRecord, ttlMs: number): Promise<void>;
20
+ release(key: string): Promise<void>;
21
+ /** Visible for tests and for a health endpoint that wants to report size. */
22
+ get size(): number;
23
+ private evictExpired;
24
+ }