@miguelmorales13/nestkit 0.10.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 (97) hide show
  1. package/README.md +518 -12
  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 +81 -13
  13. package/dist/auth/oauth/index.js +75 -7
  14. package/dist/auth/oauth/oauth-auth.service.d.ts +29 -1
  15. package/dist/auth/oauth/oauth.options.d.ts +11 -0
  16. package/dist/bootstrap/index.cjs +6 -5
  17. package/dist/bootstrap/index.js +5 -4
  18. package/dist/chunk-47FXU74G.cjs +205 -0
  19. package/dist/{chunk-54ZXIB5T.cjs → chunk-4GT66KQS.cjs} +4 -4
  20. package/dist/{chunk-J7TURDAL.cjs → chunk-67B7IYAV.cjs} +2 -2
  21. package/dist/{chunk-NVCI3CQI.cjs → chunk-C5DV4RAX.cjs} +6 -1
  22. package/dist/{chunk-KDAA6GFF.js → chunk-DABTRWA6.js} +12 -7
  23. package/dist/{chunk-ZA56XBCK.cjs → chunk-EBPEMVZU.cjs} +15 -0
  24. package/dist/{chunk-EYURGACO.js → chunk-JV4EAOF2.js} +1 -1
  25. package/dist/chunk-KP2ZHJSR.js +35 -0
  26. package/dist/{chunk-7I2Y7V52.js → chunk-KRC47OX6.js} +1 -1
  27. package/dist/chunk-LK3OINS7.js +205 -0
  28. package/dist/{chunk-A3B2EY4V.js → chunk-MLOQDUBN.js} +6 -1
  29. package/dist/chunk-TCAMLNUZ.js +27 -0
  30. package/dist/{chunk-V2M75FN3.cjs → chunk-U7QK24HL.cjs} +2 -2
  31. package/dist/{chunk-AOCF5QCZ.js → chunk-UIVBPNH4.js} +4 -4
  32. package/dist/{chunk-TJHRABML.cjs → chunk-UWDHAZVE.cjs} +12 -7
  33. package/dist/chunk-XHW4CTBS.js +57 -0
  34. package/dist/chunk-XX5ROVSC.cjs +57 -0
  35. package/dist/chunk-Y72D5L6I.cjs +27 -0
  36. package/dist/crud/crud.controller.d.ts +3 -1
  37. package/dist/crud/crud.service.d.ts +63 -4
  38. package/dist/crud/index.cjs +7 -2
  39. package/dist/crud/index.d.ts +2 -1
  40. package/dist/crud/index.js +6 -1
  41. package/dist/crud/list-query.dto.d.ts +23 -0
  42. package/dist/crud/repository.port.d.ts +33 -1
  43. package/dist/errors/index.cjs +4 -4
  44. package/dist/errors/index.js +4 -4
  45. package/dist/idempotency/idempotency.interceptor.d.ts +35 -0
  46. package/dist/idempotency/idempotency.module.d.ts +27 -0
  47. package/dist/idempotency/idempotency.options.d.ts +29 -0
  48. package/dist/idempotency/idempotency.port.d.ts +43 -0
  49. package/dist/idempotency/index.cjs +206 -0
  50. package/dist/idempotency/index.d.ts +7 -0
  51. package/dist/idempotency/index.js +206 -0
  52. package/dist/idempotency/memory.store.d.ts +24 -0
  53. package/dist/index.cjs +24 -13
  54. package/dist/index.js +29 -18
  55. package/dist/invoicing/adapters/facturama.invoicing.d.ts +50 -0
  56. package/dist/invoicing/adapters/facturapi.invoicing.d.ts +35 -0
  57. package/dist/invoicing/amounts.d.ts +52 -0
  58. package/dist/invoicing/index.cjs +577 -0
  59. package/dist/invoicing/index.d.ts +11 -0
  60. package/dist/invoicing/index.js +577 -0
  61. package/dist/invoicing/invoicing.module.d.ts +42 -0
  62. package/dist/invoicing/invoicing.options.d.ts +51 -0
  63. package/dist/invoicing/invoicing.port.d.ts +156 -0
  64. package/dist/invoicing/lines.d.ts +21 -0
  65. package/dist/invoicing/provider-http.d.ts +21 -0
  66. package/dist/media/index.cjs +57 -7
  67. package/dist/media/index.d.ts +2 -2
  68. package/dist/media/index.js +56 -6
  69. package/dist/media/media.options.d.ts +20 -0
  70. package/dist/media/media.service.d.ts +18 -1
  71. package/dist/payments/adapters/clip.terminal.d.ts +101 -0
  72. package/dist/payments/adapters/mercadopago.terminal.d.ts +74 -0
  73. package/dist/payments/index.cjs +795 -0
  74. package/dist/payments/index.d.ts +12 -0
  75. package/dist/payments/index.js +795 -0
  76. package/dist/payments/money.d.ts +20 -0
  77. package/dist/payments/payments-webhook.controller.d.ts +30 -0
  78. package/dist/payments/payments.module.d.ts +45 -0
  79. package/dist/payments/payments.options.d.ts +84 -0
  80. package/dist/payments/payments.port.d.ts +174 -0
  81. package/dist/payments/provider-http.d.ts +26 -0
  82. package/dist/response/api-response.d.ts +7 -0
  83. package/dist/response/index.cjs +12 -4
  84. package/dist/response/index.d.ts +2 -0
  85. package/dist/response/index.js +12 -4
  86. package/dist/response/paginated.d.ts +25 -0
  87. package/dist/response/response.interceptor.d.ts +4 -0
  88. package/dist/tracking/index.cjs +3 -3
  89. package/dist/tracking/index.d.ts +1 -1
  90. package/dist/tracking/index.js +2 -2
  91. package/dist/tracking/request-context.d.ts +22 -0
  92. package/package.json +25 -3
  93. package/dist/chunk-3CLYZC3T.cjs +0 -104
  94. package/dist/chunk-EBO6UKHL.js +0 -20
  95. package/dist/chunk-JOVBJDJ2.js +0 -104
  96. /package/dist/{chunk-MR2IFCZE.cjs → chunk-H2EHN366.cjs} +0 -0
  97. /package/dist/{chunk-NAK4WDKS.js → chunk-ODPSIFOB.js} +0 -0
@@ -1,9 +1,9 @@
1
- import {
2
- ResponseInterceptor
3
- } from "./chunk-KDAA6GFF.js";
4
1
  import {
5
2
  GlobalExceptionFilter
6
- } from "./chunk-7I2Y7V52.js";
3
+ } from "./chunk-KRC47OX6.js";
4
+ import {
5
+ ResponseInterceptor
6
+ } from "./chunk-DABTRWA6.js";
7
7
 
8
8
  // src/bootstrap/apply-defaults.ts
9
9
  import {
@@ -1,6 +1,9 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
2
 
3
- var _chunkZA56XBCKcjs = require('./chunk-ZA56XBCK.cjs');
3
+ var _chunkY72D5L6Icjs = require('./chunk-Y72D5L6I.cjs');
4
+
5
+
6
+ var _chunkEBPEMVZUcjs = require('./chunk-EBPEMVZU.cjs');
4
7
 
5
8
 
6
9
  var _chunk2REOCMUDcjs = require('./chunk-2REOCMUD.cjs');
@@ -11,12 +14,14 @@ var _operators = require('rxjs/operators');
11
14
  var ResponseInterceptor = class {
12
15
  intercept(_context, next) {
13
16
  return next.handle().pipe(
14
- _operators.map.call(void 0, (data) => ({
15
- success: true,
16
- data,
17
- requestId: _nullishCoalesce(_chunkZA56XBCKcjs.RequestContext.getRequestId(), () => ( "unknown")),
18
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
19
- }))
17
+ _operators.map.call(void 0, (data) => {
18
+ const envelope = {
19
+ success: true,
20
+ requestId: _nullishCoalesce(_chunkEBPEMVZUcjs.RequestContext.getRequestId(), () => ( "unknown")),
21
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
22
+ };
23
+ return _chunkY72D5L6Icjs.isPaginated.call(void 0, data) ? { ...envelope, data: data.items, meta: data.meta } : { ...envelope, data };
24
+ })
20
25
  );
21
26
  }
22
27
  };
@@ -0,0 +1,57 @@
1
+ import {
2
+ RequestContext
3
+ } from "./chunk-KP2ZHJSR.js";
4
+ import {
5
+ __decorateClass,
6
+ __decorateParam
7
+ } from "./chunk-4MGIQFAJ.js";
8
+
9
+ // src/audit/audit.port.ts
10
+ var AUDIT_SINK = /* @__PURE__ */ Symbol("AUDIT_SINK");
11
+
12
+ // src/audit/audit.options.ts
13
+ var AUDIT_OPTIONS = /* @__PURE__ */ Symbol("AUDIT_OPTIONS");
14
+
15
+ // src/audit/audit.service.ts
16
+ import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
17
+ function withRequestContext(event) {
18
+ const actor = RequestContext.getActor();
19
+ return {
20
+ ...event,
21
+ actorId: event.actorId ?? actor?.id,
22
+ tenantId: event.tenantId ?? actor?.tenantId,
23
+ requestId: event.requestId ?? RequestContext.getRequestId(),
24
+ at: event.at ?? /* @__PURE__ */ new Date()
25
+ };
26
+ }
27
+ var AuditService = class {
28
+ constructor(sink, options = {}) {
29
+ this.sink = sink;
30
+ this.options = options;
31
+ this.logger = new Logger(AuditService.name);
32
+ }
33
+ async record(event) {
34
+ const complete = withRequestContext(event);
35
+ try {
36
+ await this.sink.record(complete);
37
+ } catch (error) {
38
+ if (this.options.onError === "fail") throw error;
39
+ this.logger.error(
40
+ `Audit sink failed for ${complete.action} ${complete.resource}: ${error instanceof Error ? error.message : String(error)}`
41
+ );
42
+ }
43
+ }
44
+ };
45
+ AuditService = __decorateClass([
46
+ Injectable(),
47
+ __decorateParam(0, Inject(AUDIT_SINK)),
48
+ __decorateParam(1, Optional()),
49
+ __decorateParam(1, Inject(AUDIT_OPTIONS))
50
+ ], AuditService);
51
+
52
+ export {
53
+ AUDIT_SINK,
54
+ AUDIT_OPTIONS,
55
+ withRequestContext,
56
+ AuditService
57
+ };
@@ -0,0 +1,57 @@
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
+ var _chunkEBPEMVZUcjs = require('./chunk-EBPEMVZU.cjs');
4
+
5
+
6
+
7
+ var _chunk2REOCMUDcjs = require('./chunk-2REOCMUD.cjs');
8
+
9
+ // src/audit/audit.port.ts
10
+ var AUDIT_SINK = /* @__PURE__ */ Symbol("AUDIT_SINK");
11
+
12
+ // src/audit/audit.options.ts
13
+ var AUDIT_OPTIONS = /* @__PURE__ */ Symbol("AUDIT_OPTIONS");
14
+
15
+ // src/audit/audit.service.ts
16
+ var _common = require('@nestjs/common');
17
+ function withRequestContext(event) {
18
+ const actor = _chunkEBPEMVZUcjs.RequestContext.getActor();
19
+ return {
20
+ ...event,
21
+ actorId: _nullishCoalesce(event.actorId, () => ( _optionalChain([actor, 'optionalAccess', _ => _.id]))),
22
+ tenantId: _nullishCoalesce(event.tenantId, () => ( _optionalChain([actor, 'optionalAccess', _2 => _2.tenantId]))),
23
+ requestId: _nullishCoalesce(event.requestId, () => ( _chunkEBPEMVZUcjs.RequestContext.getRequestId())),
24
+ at: _nullishCoalesce(event.at, () => ( /* @__PURE__ */ new Date()))
25
+ };
26
+ }
27
+ var AuditService = class {
28
+ constructor(sink, options = {}) {
29
+ this.sink = sink;
30
+ this.options = options;
31
+ this.logger = new (0, _common.Logger)(AuditService.name);
32
+ }
33
+ async record(event) {
34
+ const complete = withRequestContext(event);
35
+ try {
36
+ await this.sink.record(complete);
37
+ } catch (error) {
38
+ if (this.options.onError === "fail") throw error;
39
+ this.logger.error(
40
+ `Audit sink failed for ${complete.action} ${complete.resource}: ${error instanceof Error ? error.message : String(error)}`
41
+ );
42
+ }
43
+ }
44
+ };
45
+ AuditService = exports.AuditService = _chunk2REOCMUDcjs.__decorateClass.call(void 0, [
46
+ _common.Injectable.call(void 0, ),
47
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 0, _common.Inject.call(void 0, AUDIT_SINK)),
48
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Optional.call(void 0, )),
49
+ _chunk2REOCMUDcjs.__decorateParam.call(void 0, 1, _common.Inject.call(void 0, AUDIT_OPTIONS))
50
+ ], AuditService);
51
+
52
+
53
+
54
+
55
+
56
+
57
+ exports.AUDIT_SINK = AUDIT_SINK; exports.AUDIT_OPTIONS = AUDIT_OPTIONS; exports.withRequestContext = withRequestContext; exports.AuditService = AuditService;
@@ -0,0 +1,27 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});// src/response/paginated.ts
2
+ var PAGINATED = /* @__PURE__ */ Symbol.for("nestkit.paginated");
3
+ function buildPageMeta(total, page, limit) {
4
+ const pages = limit > 0 ? Math.ceil(total / limit) : 0;
5
+ return {
6
+ page,
7
+ limit,
8
+ total,
9
+ pages,
10
+ hasNext: page < pages,
11
+ hasPrevious: page > 1 && total > 0
12
+ };
13
+ }
14
+ function paginated(items, meta) {
15
+ const page = { items, meta };
16
+ Object.defineProperty(page, PAGINATED, { value: true, enumerable: false });
17
+ return page;
18
+ }
19
+ function isPaginated(value) {
20
+ return typeof value === "object" && value !== null && value[PAGINATED] === true;
21
+ }
22
+
23
+
24
+
25
+
26
+
27
+ exports.buildPageMeta = buildPageMeta; exports.paginated = paginated; exports.isPaginated = isPaginated;
@@ -1,6 +1,8 @@
1
1
  import { type Type } from '@nestjs/common';
2
+ import type { Paginated } from '../response/paginated.js';
2
3
  import type { BaseEntity } from '../entities/base.entity.js';
3
4
  import type { BaseCrudService } from './crud.service.js';
5
+ import { ListQuery } from './list-query.dto.js';
4
6
  export interface CreateCrudControllerOptions {
5
7
  /** Route prefix for the generated controller. Defaults to no prefix. */
6
8
  path?: string;
@@ -31,7 +33,7 @@ export interface CreateCrudControllerOptions {
31
33
  * }) {}
32
34
  */
33
35
  export declare function createCrudController<T extends BaseEntity>(serviceToken: Type<BaseCrudService<T>>, options?: CreateCrudControllerOptions): Type<{
34
- findAll(filter: Partial<T> | undefined, req: unknown): Promise<T[]>;
36
+ findAll(query: ListQuery, req: unknown): Promise<Paginated<T>>;
35
37
  findById(id: string, req: unknown): Promise<T | null>;
36
38
  create(data: Omit<T, 'id' | 'createdAt' | 'updatedAt'>, req: unknown): Promise<T>;
37
39
  update(id: string, data: Partial<T>, req: unknown): Promise<T>;
@@ -1,6 +1,9 @@
1
+ import type { AuditSinkPort } from '../audit/audit.port.js';
2
+ import { type Paginated } from '../response/paginated.js';
1
3
  import type { BaseEntity } from '../entities/base.entity.js';
4
+ import type { ListQuery } from './list-query.dto.js';
2
5
  import type { Repository } from './repository.port.js';
3
- export interface BaseCrudServiceOptions {
6
+ export interface BaseCrudServiceOptions<T extends BaseEntity = BaseEntity> {
4
7
  /**
5
8
  * 'hard' (default): delete() calls repository.delete().
6
9
  * 'soft': delete() calls repository.update(id, { deletedAt: new Date() })
@@ -11,6 +14,45 @@ export interface BaseCrudServiceOptions {
11
14
  * if you always soft-delete.
12
15
  */
13
16
  deleteStrategy?: 'soft' | 'hard';
17
+ /** Page size when the caller does not ask for one. Defaults to 20. */
18
+ defaultLimit?: number;
19
+ /**
20
+ * Largest page this service will serve, whatever the query string says.
21
+ * Defaults to 100.
22
+ */
23
+ maxLimit?: number;
24
+ /**
25
+ * Fields a caller may filter by. **Empty by default, and that is the
26
+ * point**: the previous behaviour forwarded the whole query string to the
27
+ * repository, so any column — a password hash, an internal flag, another
28
+ * tenant's marker — could be used to probe rows one guess at a time.
29
+ * Opening a field is one line; leaving it open by accident is a leak.
30
+ */
31
+ filterable?: (keyof T & string)[];
32
+ /**
33
+ * Fields a caller may sort by. Empty by default for the same reason plus a
34
+ * sharper one: adapters interpolate this name into SQL.
35
+ */
36
+ sortable?: (keyof T & string)[];
37
+ /**
38
+ * Records every create, update and delete this service performs.
39
+ *
40
+ * `recorder` is anything with `record(event)`: the raw `AuditSinkPort`, or
41
+ * `AuditService` — pass the service to inherit its policy for a failing
42
+ * sink, because this class does not catch. One place decides whether a lost
43
+ * entry stops the operation, and it is not this one.
44
+ */
45
+ audit?: {
46
+ recorder: AuditSinkPort;
47
+ /** Name of the thing being changed, as the trail should read: `invoice`, `widget`. */
48
+ resource: string;
49
+ /**
50
+ * Read the row before updating or deleting it, so the entry carries what
51
+ * it used to say. Off by default: it is an extra query per write, and a
52
+ * trail without it still answers who and when.
53
+ */
54
+ includeBefore?: boolean;
55
+ };
14
56
  }
15
57
  /**
16
58
  * Generic CRUD orchestration on top of a Repository<T> port. Optional to
@@ -19,11 +61,28 @@ export interface BaseCrudServiceOptions {
19
61
  */
20
62
  export declare class BaseCrudService<T extends BaseEntity> {
21
63
  protected readonly repository: Repository<T>;
22
- protected readonly options: BaseCrudServiceOptions;
23
- constructor(repository: Repository<T>, options?: BaseCrudServiceOptions);
64
+ protected readonly options: BaseCrudServiceOptions<T>;
65
+ constructor(repository: Repository<T>, options?: BaseCrudServiceOptions<T>);
24
66
  findById(id: string, tenantId?: string): Promise<T | null>;
25
- findAll(filter?: Partial<T>, tenantId?: string): Promise<T[]>;
67
+ /**
68
+ * One page of rows.
69
+ *
70
+ * Everything a caller can influence is bounded here rather than in the
71
+ * controller, so calling the service directly is as safe as going through
72
+ * HTTP: the limit is capped, and filter and sort fields are checked against
73
+ * the allowlists before they reach the adapter.
74
+ */
75
+ findAll(query?: ListQuery, tenantId?: string): Promise<Paginated<T>>;
76
+ /**
77
+ * Keeps only the query fields this service declares filterable. Anything
78
+ * else is dropped silently — a rejection would tell a caller which columns
79
+ * exist, which is the question they were asking.
80
+ */
81
+ protected allowedFilter(query: Record<string, unknown>): Partial<T> | undefined;
26
82
  create(data: Omit<T, 'id' | 'createdAt' | 'updatedAt'>, tenantId?: string): Promise<T>;
27
83
  update(id: string, data: Partial<T>, tenantId?: string): Promise<T>;
28
84
  delete(id: string, tenantId?: string): Promise<void>;
85
+ /** Only when the trail is configured to want it — otherwise it is a query for nothing. */
86
+ private readBefore;
87
+ private audit;
29
88
  }
@@ -1,9 +1,14 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
3
 
4
- var _chunk3CLYZC3Tcjs = require('../chunk-3CLYZC3T.cjs');
4
+
5
+ var _chunk47FXU74Gcjs = require('../chunk-47FXU74G.cjs');
6
+ require('../chunk-XX5ROVSC.cjs');
7
+ require('../chunk-Y72D5L6I.cjs');
8
+ require('../chunk-EBPEMVZU.cjs');
5
9
  require('../chunk-2REOCMUD.cjs');
6
10
 
7
11
 
8
12
 
9
- exports.BaseCrudService = _chunk3CLYZC3Tcjs.BaseCrudService; exports.createCrudController = _chunk3CLYZC3Tcjs.createCrudController;
13
+
14
+ exports.BaseCrudService = _chunk47FXU74Gcjs.BaseCrudService; exports.ListQuery = _chunk47FXU74Gcjs.ListQuery; exports.createCrudController = _chunk47FXU74Gcjs.createCrudController;
@@ -1,4 +1,5 @@
1
- export type { Repository } from './repository.port.js';
1
+ export type { Repository, FindAllOptions, PageResult } from './repository.port.js';
2
+ export { ListQuery } from './list-query.dto.js';
2
3
  export { BaseCrudService } from './crud.service.js';
3
4
  export type { BaseCrudServiceOptions } from './crud.service.js';
4
5
  export { createCrudController } from './crud.controller.js';
@@ -1,9 +1,14 @@
1
1
  import {
2
2
  BaseCrudService,
3
+ ListQuery,
3
4
  createCrudController
4
- } from "../chunk-JOVBJDJ2.js";
5
+ } from "../chunk-LK3OINS7.js";
6
+ import "../chunk-XHW4CTBS.js";
7
+ import "../chunk-TCAMLNUZ.js";
8
+ import "../chunk-KP2ZHJSR.js";
5
9
  import "../chunk-4MGIQFAJ.js";
6
10
  export {
7
11
  BaseCrudService,
12
+ ListQuery,
8
13
  createCrudController
9
14
  };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Query string of a list endpoint, as a real DTO.
3
+ *
4
+ * Being a class with decorators is the point: the global `ValidationPipe` runs
5
+ * with `whitelist: true`, which only strips unknown properties when there is a
6
+ * class to compare against. The previous signature typed the query as
7
+ * `Partial<T>`, and a bare type carries no metadata — so nothing was stripped
8
+ * and every column of the entity was filterable from the URL.
9
+ *
10
+ * `@Type(() => Number)` is not decoration: query values arrive as strings, and
11
+ * `?limit=20` without it is the string `"20"`, which `@IsInt()` rejects.
12
+ */
13
+ export declare class ListQuery {
14
+ page?: number;
15
+ /**
16
+ * Capped at 200 here and again, per service, by `maxLimit`. The hard cap
17
+ * exists so a forgotten configuration cannot turn into `?limit=1000000`.
18
+ */
19
+ limit?: number;
20
+ /** Ignored unless the service lists the field in `sortable`. */
21
+ sortBy?: string;
22
+ sortOrder?: 'asc' | 'desc';
23
+ }
@@ -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
+ }