@nathapp/nestjs-common 2.1.4 → 3.0.0-rc.4

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 (151) hide show
  1. package/CLAUDE.md +29 -0
  2. package/README.md +134 -0
  3. package/dist/config/index.d.ts +4 -4
  4. package/dist/config/index.js.map +1 -1
  5. package/dist/config/server-security.config.d.ts +1 -0
  6. package/dist/config/server-security.config.js +19 -2
  7. package/dist/config/server-security.config.js.map +1 -1
  8. package/dist/decorator/index.d.ts +2 -2
  9. package/dist/decorator/index.js.map +1 -1
  10. package/dist/entities/base-entity.d.ts +3 -0
  11. package/dist/entities/base-entity.js +8 -0
  12. package/dist/entities/base-entity.js.map +1 -0
  13. package/dist/entities/index.d.ts +1 -0
  14. package/dist/entities/index.js +18 -0
  15. package/dist/entities/index.js.map +1 -0
  16. package/dist/exception/app.exception.d.ts +4 -3
  17. package/dist/exception/app.exception.js +1 -1
  18. package/dist/exception/app.exception.js.map +1 -1
  19. package/dist/exception/default-i18n-validation-exception.filter.js +1 -1
  20. package/dist/exception/default-i18n-validation-exception.filter.js.map +1 -1
  21. package/dist/exception/exception.constants.d.ts +1 -0
  22. package/dist/exception/exception.constants.js +5 -0
  23. package/dist/exception/exception.constants.js.map +1 -0
  24. package/dist/exception/exception.module.d.ts +7 -0
  25. package/dist/exception/exception.module.js +41 -0
  26. package/dist/exception/exception.module.js.map +1 -0
  27. package/dist/exception/exceptions/auth.exception.d.ts +4 -0
  28. package/dist/exception/exceptions/auth.exception.js +12 -0
  29. package/dist/exception/exceptions/auth.exception.js.map +1 -0
  30. package/dist/exception/exceptions/forbidden-app.exception.d.ts +4 -0
  31. package/dist/exception/exceptions/forbidden-app.exception.js +12 -0
  32. package/dist/exception/exceptions/forbidden-app.exception.js.map +1 -0
  33. package/dist/exception/exceptions/index.d.ts +6 -0
  34. package/dist/exception/exceptions/index.js +16 -0
  35. package/dist/exception/exceptions/index.js.map +1 -0
  36. package/dist/exception/exceptions/internal-app.exception.d.ts +4 -0
  37. package/dist/exception/exceptions/internal-app.exception.js +12 -0
  38. package/dist/exception/exceptions/internal-app.exception.js.map +1 -0
  39. package/dist/exception/exceptions/not-found-app.exception.d.ts +4 -0
  40. package/dist/exception/exceptions/not-found-app.exception.js +12 -0
  41. package/dist/exception/exceptions/not-found-app.exception.js.map +1 -0
  42. package/dist/exception/exceptions/throttle-app.exception.d.ts +4 -0
  43. package/dist/exception/exceptions/throttle-app.exception.js +12 -0
  44. package/dist/exception/exceptions/throttle-app.exception.js.map +1 -0
  45. package/dist/exception/exceptions/validation-app.exception.d.ts +4 -0
  46. package/dist/exception/exceptions/validation-app.exception.js +12 -0
  47. package/dist/exception/exceptions/validation-app.exception.js.map +1 -0
  48. package/dist/exception/global-exception.filter.d.ts +8 -54
  49. package/dist/exception/global-exception.filter.js +45 -163
  50. package/dist/exception/global-exception.filter.js.map +1 -1
  51. package/dist/exception/handler/app-exception.handler.d.ts +7 -0
  52. package/dist/exception/handler/app-exception.handler.js +44 -0
  53. package/dist/exception/handler/app-exception.handler.js.map +1 -0
  54. package/dist/exception/handler/bad-request.handler.d.ts +6 -0
  55. package/dist/exception/handler/bad-request.handler.js +30 -0
  56. package/dist/exception/handler/bad-request.handler.js.map +1 -0
  57. package/dist/exception/handler/exception-handler.interface.d.ts +14 -0
  58. package/dist/exception/handler/exception-handler.interface.js +3 -0
  59. package/dist/exception/handler/exception-handler.interface.js.map +1 -0
  60. package/dist/exception/handler/forbidden.handler.d.ts +6 -0
  61. package/dist/exception/handler/forbidden.handler.js +27 -0
  62. package/dist/exception/handler/forbidden.handler.js.map +1 -0
  63. package/dist/exception/handler/index.d.ts +11 -0
  64. package/dist/exception/handler/index.js +38 -0
  65. package/dist/exception/handler/index.js.map +1 -0
  66. package/dist/exception/handler/microservice.handler.d.ts +6 -0
  67. package/dist/exception/handler/microservice.handler.js +27 -0
  68. package/dist/exception/handler/microservice.handler.js.map +1 -0
  69. package/dist/exception/handler/not-found.handler.d.ts +6 -0
  70. package/dist/exception/handler/not-found.handler.js +27 -0
  71. package/dist/exception/handler/not-found.handler.js.map +1 -0
  72. package/dist/exception/handler/throttler.handler.d.ts +6 -0
  73. package/dist/exception/handler/throttler.handler.js +33 -0
  74. package/dist/exception/handler/throttler.handler.js.map +1 -0
  75. package/dist/exception/handler/unknown.handler.d.ts +6 -0
  76. package/dist/exception/handler/unknown.handler.js +35 -0
  77. package/dist/exception/handler/unknown.handler.js.map +1 -0
  78. package/dist/exception/handler/username-not-found.handler.d.ts +6 -0
  79. package/dist/exception/handler/username-not-found.handler.js +28 -0
  80. package/dist/exception/handler/username-not-found.handler.js.map +1 -0
  81. package/dist/exception/index.d.ts +7 -4
  82. package/dist/exception/index.js +12 -3
  83. package/dist/exception/index.js.map +1 -1
  84. package/dist/exception/micro-service.exception.js +1 -1
  85. package/dist/exception/micro-service.exception.js.map +1 -1
  86. package/dist/exception/user-not-found.exception.js +1 -1
  87. package/dist/http/index.d.ts +3 -3
  88. package/dist/index.d.ts +2 -1
  89. package/dist/index.js +2 -1
  90. package/dist/index.js.map +1 -1
  91. package/dist/interceptor/serializable.interceptor.d.ts +4 -2
  92. package/dist/interceptor/serializable.interceptor.js +75 -18
  93. package/dist/interceptor/serializable.interceptor.js.map +1 -1
  94. package/dist/ip/index.d.ts +3 -2
  95. package/dist/ip/index.js +4 -1
  96. package/dist/ip/index.js.map +1 -1
  97. package/dist/ip/request-ip.d.ts +4 -2
  98. package/dist/ip/request-ip.js +92 -30
  99. package/dist/ip/request-ip.js.map +1 -1
  100. package/dist/ip/trusted-proxy-presets.d.ts +3 -0
  101. package/dist/ip/trusted-proxy-presets.js +114 -0
  102. package/dist/ip/trusted-proxy-presets.js.map +1 -0
  103. package/dist/module/configurable-module.builder.js +3 -1
  104. package/dist/module/configurable-module.builder.js.map +1 -1
  105. package/dist/module/index.d.ts +5 -5
  106. package/dist/module/index.js.map +1 -1
  107. package/dist/pagination/index.d.ts +1 -0
  108. package/dist/pagination/index.js +18 -0
  109. package/dist/pagination/index.js.map +1 -0
  110. package/dist/pagination/page.d.ts +39 -0
  111. package/dist/pagination/page.js +87 -0
  112. package/dist/pagination/page.js.map +1 -0
  113. package/dist/serialize/localize.string.js.map +1 -1
  114. package/dist/utils/package-utils.js +3 -0
  115. package/dist/utils/package-utils.js.map +1 -1
  116. package/dist/validation/index.d.ts +1 -0
  117. package/dist/validation/index.js +1 -0
  118. package/dist/validation/index.js.map +1 -1
  119. package/dist/validation/validators.d.ts +3 -0
  120. package/dist/validation/validators.js +29 -0
  121. package/dist/validation/validators.js.map +1 -0
  122. package/docs/20260214-coverage-plan.md +52 -0
  123. package/docs/20260214-fix-plan-common-bugs.md +90 -0
  124. package/docs/20260214-fix-plan-common-cleanup.md +119 -0
  125. package/docs/20260214-fix-plan-exception-redesign.md +274 -0
  126. package/docs/20260214-fix-plan-nestjs-prisma.md +454 -0
  127. package/docs/20260214-fix-plan-pagination-move-and-rename.md +148 -0
  128. package/docs/20260214-review-common.md +426 -0
  129. package/docs/20260215-fix-plan-review-enhancements.md +110 -0
  130. package/docs/20260215-fix-plan-trust-proxy-presets.md +227 -0
  131. package/docs/20260215-review-nestjs-common.md +1015 -0
  132. package/docs/trust-proxy-security.md +475 -0
  133. package/package.json +1 -1
  134. package/dist/exception/app-exception.filter.d.ts +0 -9
  135. package/dist/exception/app-exception.filter.js +0 -52
  136. package/dist/exception/app-exception.filter.js.map +0 -1
  137. package/dist/i18n/i18n.constants.d.ts +0 -0
  138. package/dist/i18n/i18n.constants.js +0 -1
  139. package/dist/i18n/i18n.constants.js.map +0 -1
  140. package/dist/middleware/index.d.ts +0 -4
  141. package/dist/middleware/index.js +0 -14
  142. package/dist/middleware/index.js.map +0 -1
  143. package/dist/middleware/log.provider.d.ts +0 -38
  144. package/dist/middleware/log.provider.js +0 -147
  145. package/dist/middleware/log.provider.js.map +0 -1
  146. package/dist/middleware/logger-option.factory.d.ts +0 -17
  147. package/dist/middleware/logger-option.factory.js +0 -73
  148. package/dist/middleware/logger-option.factory.js.map +0 -1
  149. package/dist/middleware/logger.middleware.d.ts +0 -8
  150. package/dist/middleware/logger.middleware.js +0 -97
  151. package/dist/middleware/logger.middleware.js.map +0 -1
@@ -17,4 +17,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./match.constraint"), exports);
18
18
  __exportStar(require("./i18n-validation.constraint"), exports);
19
19
  __exportStar(require("./validation"), exports);
20
+ __exportStar(require("./validators"), exports);
20
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/validation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC;AACnC,+DAA6C;AAC7C,+CAA6B"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/validation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC;AACnC,+DAA6C;AAC7C,+CAA6B;AAC7B,+CAA6B"}
@@ -0,0 +1,3 @@
1
+ export declare function isValidLocaleCode(code: string): boolean;
2
+ export declare function sanitizeHeader(value: string, maxLength?: number): string;
3
+ export declare function clampNumber(value: number, min: number, max: number): number;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isValidLocaleCode = isValidLocaleCode;
4
+ exports.sanitizeHeader = sanitizeHeader;
5
+ exports.clampNumber = clampNumber;
6
+ function isValidLocaleCode(code) {
7
+ if (!code || typeof code !== 'string') {
8
+ return false;
9
+ }
10
+ const localePattern = /^[a-z]{2}_[A-Z]{2}$/;
11
+ return localePattern.test(code);
12
+ }
13
+ function sanitizeHeader(value, maxLength = 255) {
14
+ if (!value || typeof value !== 'string') {
15
+ return '';
16
+ }
17
+ const sanitized = value.replace(/[^\w.-]/g, '');
18
+ return sanitized.slice(0, maxLength);
19
+ }
20
+ function clampNumber(value, min, max) {
21
+ if (typeof value !== 'number' || isNaN(value)) {
22
+ return min;
23
+ }
24
+ if (typeof min !== 'number' || isNaN(min) || typeof max !== 'number' || isNaN(max)) {
25
+ return value;
26
+ }
27
+ return Math.max(min, Math.min(max, value));
28
+ }
29
+ //# sourceMappingURL=validators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validators.js","sourceRoot":"","sources":["../../lib/validation/validators.ts"],"names":[],"mappings":";;AAOA,8CAQC;AAUD,wCAUC;AAUD,kCAUC;AAhDD,SAAgB,iBAAiB,CAAC,IAAY;IAC5C,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;QACtC,OAAO,KAAK,CAAC;IACf,CAAC;IAGD,MAAM,aAAa,GAAG,qBAAqB,CAAC;IAC5C,OAAO,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAClC,CAAC;AAUD,SAAgB,cAAc,CAAC,KAAa,EAAE,YAAoB,GAAG;IACnE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QACxC,OAAO,EAAE,CAAC;IACZ,CAAC;IAGD,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC;IAGhD,OAAO,SAAS,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC;AACvC,CAAC;AAUD,SAAgB,WAAW,CAAC,KAAa,EAAE,GAAW,EAAE,GAAW;IACjE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;QAC9C,OAAO,GAAG,CAAC;IACb,CAAC;IAED,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;QACnF,OAAO,KAAK,CAAC;IACf,CAAC;IAED,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC;AAC7C,CAAC"}
@@ -0,0 +1,52 @@
1
+ # Coverage Plan: nestjs-common → 80%+
2
+
3
+ **Date:** 2026-02-14
4
+ **Branch:** feat/monorepo-enterprise-upgrade
5
+ **Current:** 80% stmts, 52% branch, 58% funcs, 79% lines
6
+ **Target:** 85%+ stmts, 65%+ branch, 70%+ funcs, 85%+ lines
7
+
8
+ ## Priority Files (by coverage gap)
9
+
10
+ ### 1. `lib/exception/i18n-validation-exception.filter.ts` (25% → 80%+)
11
+ - Test with and without i18n service
12
+ - Test validation error formatting
13
+ - Test HTTP and WS contexts
14
+
15
+ ### 2. `lib/exception/default-i18n-validation-exception.filter.ts` (28% → 80%+)
16
+ - Test default validation formatting
17
+ - Test error structure
18
+
19
+ ### 3. `lib/module/async-options-provider.ts` (31% → 80%+)
20
+ - Test createAsyncOptionsProviders with useFactory, useClass, useExisting
21
+ - Test provider array generation
22
+
23
+ ### 4. `lib/validation/match.constraint.ts` (52% → 80%+)
24
+ - Test @Match decorator
25
+ - Test matching and non-matching values
26
+
27
+ ### 5. `lib/validation/i18n-validation.constraint.ts` (33% → 80%+)
28
+ - Test i18n validation constraint
29
+
30
+ ### 6. `lib/validation/validation.ts` (67% → 80%+)
31
+ - Test all validation pipe decorators
32
+
33
+ ### 7. `lib/config/server-security.config.ts` (52% → 80%+)
34
+ - Test security config defaults and overrides
35
+
36
+ ### 8. `lib/module/configurable-module.builder.ts` (61% → 80%+)
37
+ - Test builder pattern: forRoot, forRootAsync, forFeature
38
+
39
+ ### 9. `lib/ip/request-ip.ts` (74% → 80%+)
40
+ - Test additional header parsing edge cases
41
+
42
+ ### 10. `lib/exception/i18n.wrapper.ts` (60% → 80%+)
43
+ - Test i18n wrapper initialization
44
+
45
+ ## Test Strategy
46
+ - Mode: test-after
47
+ - All tests go in `test/` directory matching the source structure
48
+ - Follow existing test patterns
49
+ - Mock NestJS dependencies (ExecutionContext, ArgumentsHost, etc.)
50
+
51
+ ## Commits
52
+ - `test(nestjs-common): improve coverage for exception filters, validation, and module utilities`
@@ -0,0 +1,90 @@
1
+ # Fix Plan: nestjs-common Critical Bugs
2
+
3
+ **Date:** 2026-02-14
4
+ **Branch:** `feat/monorepo-enterprise-upgrade`
5
+ **Review:** `packages/nestjs-common/docs/20260214-review-common.md`
6
+
7
+ ## Phase 1: HTTP Status Fixes (C1-C3)
8
+
9
+ ### Fix 1: C1 — AppException ignores httpStatus
10
+ **File:** `packages/nestjs-common/lib/exception/app.exception.ts`
11
+ **Change:** Pass `httpStatus || 500` to `super()` instead of hardcoded `500`
12
+ ```typescript
13
+ // Before
14
+ super({ code, args, prefix }, 500);
15
+ // After
16
+ super({ code, args, prefix }, httpStatus || 500);
17
+ ```
18
+
19
+ ### Fix 2: C2 — UsernameNotFoundException returns 500
20
+ **File:** `packages/nestjs-common/lib/exception/user-not-found.exception.ts`
21
+ **Change:** Change `super(message, 500)` → `super(message, 404)`
22
+
23
+ ### Fix 3: C3 — ThrottlerException returns 500 instead of 429
24
+ **File:** `packages/nestjs-common/lib/exception/global-exception.filter.ts`
25
+ **Change:** In `handleThrottlerException`, change `const httpStatus = 500` → `const httpStatus = 429`
26
+
27
+ **Commit:** `fix: correct HTTP status codes for AppException, UsernameNotFoundException, and ThrottlerException (C1-C3)`
28
+
29
+ ## Phase 2: Null Safety Fixes (C4-C5)
30
+
31
+ ### Fix 4: C4 — defaultResponseFormatter crashes on null constraints
32
+ **File:** `packages/nestjs-common/lib/exception/default-i18n-validation-exception.filter.ts`
33
+ **Change:** Add null check before accessing `firstError.constraints`
34
+ ```typescript
35
+ if (firstError?.constraints) {
36
+ message = firstError.constraints[Object.keys(firstError.constraints)[0]];
37
+ }
38
+ ```
39
+
40
+ ### Fix 5: C5 — SerializableInterceptor array check bug
41
+ **File:** `packages/nestjs-common/lib/interceptor/serializable.interceptor.ts`
42
+ **Change:** Fix `Array.isArray(obj)` → `Array.isArray(value)` in `transformObject`
43
+ ```typescript
44
+ // Before
45
+ } else if (Array.isArray(obj)) {
46
+ obj[key] = value.map(...)
47
+ // After
48
+ } else if (Array.isArray(value)) {
49
+ obj[key] = value.map((item: PlainLiteralObject) => this.transformObject(item, lang));
50
+ }
51
+ ```
52
+
53
+ **Commit:** `fix: null constraint crash and array corruption in serialization (C4-C5)`
54
+
55
+ ## Phase 3: Remove Unused AppExceptionFilter
56
+
57
+ ### Fix 6: Remove AppExceptionFilter
58
+ **File:** `packages/nestjs-common/lib/exception/app-exception.filter.ts`
59
+ **Change:** Delete the file entirely. Remove export from barrel files (`lib/exception/index.ts` and `lib/index.ts`).
60
+
61
+ **Commit:** `refactor: remove unused AppExceptionFilter`
62
+
63
+ ## Phase 4: Add Tests for SerializableInterceptor (C6)
64
+
65
+ ### Fix 7: C6 — Unit tests for SerializableInterceptor
66
+ **File:** Create `packages/nestjs-common/test/interceptor/serializable.interceptor.spec.ts`
67
+ **Test cases:**
68
+ - Basic object transformation with LocaleString fields
69
+ - Basic object transformation with LocaleObject fields
70
+ - Nested object transformation
71
+ - **Array field transformation** (validates C5 fix)
72
+ - Null/undefined value handling
73
+ - Objects without locale fields pass through unchanged
74
+ - Empty object handling
75
+ - `isObject` utility method
76
+ - Integration with NestJS interceptor pipeline (mock ExecutionContext + CallHandler)
77
+
78
+ **Commit:** `test: add unit tests for SerializableInterceptor (C6)`
79
+
80
+ ## Test Strategy
81
+ - After Phase 1: Run existing exception filter tests — `bun test packages/nestjs-common/test/exception`
82
+ - After Phase 2: Run existing tests + manually verify serialization
83
+ - After Phase 3: Run full test suite — ensure no imports break
84
+ - After Phase 4: Run new interceptor tests — `bun test packages/nestjs-common/test/interceptor`
85
+ - Final: Run full suite `bun test packages/nestjs-common` — target 80%+ coverage
86
+
87
+ ## Important Notes
88
+ - Do NOT push to remote — local commits only
89
+ - Use existing test patterns from `packages/nestjs-common/test/` as reference
90
+ - Check barrel exports after each removal to ensure nothing breaks
@@ -0,0 +1,119 @@
1
+ # Fix Plan: nestjs-common Cleanup (Phase A-B-C)
2
+
3
+ **Date:** 2026-02-14
4
+ **Branch:** `feat/monorepo-enterprise-upgrade`
5
+ **Review:** `packages/nestjs-common/docs/20260214-review-common.md`
6
+
7
+ ## Phase A: Strip Deprecated Code
8
+
9
+ ### A1: Remove deprecated logger middleware module
10
+ **Files to delete:**
11
+ - `packages/nestjs-common/lib/middleware/log.provider.ts`
12
+ - `packages/nestjs-common/lib/middleware/logger-option.factory.ts`
13
+ - `packages/nestjs-common/lib/middleware/logger.middleware.ts`
14
+ - `packages/nestjs-common/lib/middleware/index.ts`
15
+
16
+ **Files to delete (tests):**
17
+ - `packages/nestjs-common/test/middleware/log.provider.spec.ts`
18
+ - `packages/nestjs-common/test/middleware/logger-middleware-express.e2e.spec.ts`
19
+ - `packages/nestjs-common/test/middleware/logger-middleware-fastify.e2e.spec.ts`
20
+
21
+ **Files to update:**
22
+ - `packages/nestjs-common/lib/index.ts` — remove `export * from "./middleware"`
23
+
24
+ **Reason:** William confirmed nestjs-logging already exists in monorepo. This is ~300 lines of deprecated dead code.
25
+
26
+ ### A2: Remove commented-out code in GlobalExceptionsFilter
27
+ **File:** `packages/nestjs-common/lib/exception/global-exception.filter.ts`
28
+ **Change:** Remove the commented-out `HandleTwoFactorException` method (around line 179-188).
29
+
30
+ ### A3: Remove empty i18n.constants.ts
31
+ **File:** `packages/nestjs-common/lib/i18n/i18n.constants.ts`
32
+ **Change:** Delete if empty. Update barrel exports if needed.
33
+
34
+ ### A4: Fix typos
35
+ - `packages/nestjs-common/lib/exception/global-exception.filter.ts`: `handleCaptchException` → `handleCaptchaException`
36
+ - `packages/nestjs-common/lib/module/configurable-module.builder.ts`: `"at last one Module"` → `"at least one Module"`
37
+
38
+ ### A5: Clean over-exported internals
39
+ **File:** `packages/nestjs-common/lib/ip/index.ts`
40
+ **Change:** Only export `getClientIp`, `mw`, `configureTrustProxy`, `isTrustProxyConfigured`, `TrustProxyOptions`. Stop exporting `getClientIpFromXForwardedFor` and `getClientIpByHeader` (internal implementation details).
41
+
42
+ **Commit:** `refactor: strip deprecated middleware, dead code, and clean exports`
43
+
44
+ ## Phase B: Framework-Agnostic & Exception Standardization
45
+
46
+ ### B1: Fix headerPriority mutation of DEFAULT array
47
+ **File:** `packages/nestjs-common/lib/ip/request-ip.ts`
48
+ **Change:** Clone DEFAULT on init: `let headerPriority = [...DEFAULT]`
49
+
50
+ ### B2: Decorators already framework-agnostic
51
+ The `ReqClientInfo` and `RealIP` decorators use `ctx.switchToHttp().getRequest()` which works with both Express and Fastify. The `request.headers` API is the same in both. The IP module already handles Fastify (`req.raw` unwrapping). **No changes needed.**
52
+
53
+ ### B3: GlobalExceptionsFilter already framework-agnostic
54
+ It uses `httpAdapterHost` which is the NestJS abstraction layer. **No changes needed.**
55
+
56
+ ### B4: Fix HttpMicroServiceException HTTP 200 status
57
+ **File:** `packages/nestjs-common/lib/exception/micro-service.exception.ts`
58
+ **Change:** Change `super({ ret, message }, 200)` → `super({ ret, message }, 500)`. An error exception should not return 200.
59
+
60
+ ### B5: Remove app-exception.filter.e2e.spec.ts
61
+ **File:** `packages/nestjs-common/test/exception/app-exception.filter.e2e.spec.ts`
62
+ **Change:** Delete this test file — it tests the now-removed `AppExceptionFilter`.
63
+
64
+ ### B6: Fix global-exception-filter.e2e.spec.ts import error
65
+ **File:** `packages/nestjs-common/test/exception/global-exception-filter.e2e.spec.ts`
66
+ **Change:** Find and fix the `JoiConfig` import error. Check if it imports from `../../lib/config` or similar — the export name may have changed. Fix the import to match the actual exported name.
67
+
68
+ **Commit:** `fix: framework-agnostic hardening and exception consistency`
69
+
70
+ ## Phase C: Test Coverage → 80%
71
+
72
+ ### C1: Add unit tests for AppException class
73
+ **File:** Create `packages/nestjs-common/test/exception/app.exception.spec.ts`
74
+ **Tests:**
75
+ - Constructor with all params
76
+ - `httpStatus` getter returns provided value
77
+ - `getStatus()` returns correct HTTP status (not always 500 — validates C1 fix)
78
+ - `code`, `args`, `prefix` getters
79
+ - Default httpStatus (500) when not provided
80
+
81
+ ### C2: Add unit tests for exception classes
82
+ **File:** Create `packages/nestjs-common/test/exception/exceptions.spec.ts`
83
+ **Tests:**
84
+ - `UsernameNotFoundException` returns 404
85
+ - `CaptchaException` status code
86
+ - `TwoFactorRequiredException` and `TwoFactorInvalidException`
87
+ - `HttpMicroServiceException` returns 500 (after B4 fix)
88
+
89
+ ### C3: Add unit tests for serialize utilities
90
+ **File:** Create `packages/nestjs-common/test/serialize/localize.spec.ts`
91
+ **Tests:**
92
+ - `parseLocaleString` with valid JSON
93
+ - `parseLocaleString` with invalid JSON (fallback)
94
+ - `parseLocaleString` with non-object JSON (e.g., `"42"`)
95
+ - `parseLocaleObject` with valid/invalid input
96
+ - `remapLocaleObject`
97
+
98
+ ### C4: Add unit tests for package-utils
99
+ **File:** Create `packages/nestjs-common/test/utils/package-utils.spec.ts`
100
+ **Tests:**
101
+ - `isPackageInstalled` with installed package (e.g., `@nestjs/common`)
102
+ - `isPackageInstalled` with non-existent package
103
+ - `loadPackage` with valid package
104
+ - `loadPackage` with invalid package name
105
+
106
+ **Commit:** `test: add unit tests for exceptions, serialization, and utils — target 80% coverage`
107
+
108
+ ## Test Strategy
109
+ - After Phase A: `bun test packages/nestjs-common` — ensure no remaining code references deleted middleware
110
+ - After Phase B: `bun test packages/nestjs-common` — verify exception tests pass
111
+ - After Phase C: `bun test packages/nestjs-common` — verify all new + existing tests pass
112
+ - Final: Build to ensure no compilation errors: `bun run build --filter=@nathapp/nestjs-common`
113
+
114
+ ## Important Notes
115
+ - Do NOT push to remote — local commits only
116
+ - Use existing test patterns from `packages/nestjs-common/test/` as reference
117
+ - The middleware tests reference controllers in `test/app/controller/` — check if `logger-test.controller.ts` needs removal too
118
+ - Check if any other package in the monorepo imports from `@nathapp/nestjs-common`'s middleware module
119
+ - When fixing the JoiConfig import in B6, check `packages/nestjs-common/lib/config/utils/joi-util.ts` for the actual export name
@@ -0,0 +1,274 @@
1
+ # Fix Plan: Exception Hierarchy & Extensible Filter
2
+
3
+ **Date:** 2026-02-14
4
+ **Branch:** `feat/monorepo-enterprise-upgrade`
5
+
6
+ ## Phase 1: Exception Hierarchy
7
+
8
+ ### 1.1: Create base exception hierarchy
9
+ **File:** Create `packages/nestjs-common/lib/exception/exceptions/` directory with:
10
+
11
+ - `auth.exception.ts` — `AuthException extends AppException` (httpStatus: 401, errorCode: CommonExceptionCode.UNAUTHORIZED)
12
+ - `forbidden-app.exception.ts` — `ForbiddenAppException extends AppException` (httpStatus: 403, errorCode: CommonExceptionCode.FORBIDDEN)
13
+ - `not-found-app.exception.ts` — `NotFoundAppException extends AppException` (httpStatus: 404, errorCode: CommonExceptionCode.NOT_FOUND)
14
+ - `validation-app.exception.ts` — `ValidationAppException extends AppException` (httpStatus: 400, errorCode: CommonExceptionCode.REQUEST_PARAMETER_ERROR)
15
+ - `throttle-app.exception.ts` — `ThrottleAppException extends AppException` (httpStatus: 429, errorCode: CommonExceptionCode.TOO_MANY_REQUESTS)
16
+ - `internal-app.exception.ts` — `InternalAppException extends AppException` (httpStatus: 500, errorCode: CommonExceptionCode.INTERNAL_ERROR)
17
+ - `index.ts` — barrel export
18
+
19
+ Each exception:
20
+ - Extends `AppException`
21
+ - Sets correct `httpStatus` via super()
22
+ - Sets correct `errorCode` via super()
23
+ - Accepts optional `args` and `prefix` for i18n
24
+
25
+ ### 1.2: Refactor existing exceptions to use hierarchy
26
+ - `CaptchaException` — already extends `AppException` ✅ (keep as-is, httpStatus 412 via super)
27
+ - `TwoFactorRequiredException` — already extends `AppException` ✅
28
+ - `TwoFactorInvalidException` — already extends `AppException` ✅
29
+ - `UsernameNotFoundException` — **refactor**: extend `NotFoundAppException` instead of `HttpException`. Keep class name. Ensure httpStatus is 404.
30
+ - `HttpMicroServiceException` — **mark `@deprecated`** with JSDoc. Keep it working. Do NOT change its base class (too risky, used in nestjs-microservices).
31
+
32
+ ### 1.3: Update barrel exports
33
+ **File:** `packages/nestjs-common/lib/exception/index.ts`
34
+ **Change:** Add exports for all new exception classes.
35
+
36
+ **Commit:** `feat: standardize exception hierarchy with proper HTTP status mapping`
37
+
38
+ ## Phase 2: ExceptionHandler Interface & Built-in Handlers
39
+
40
+ ### 2.1: Create ExceptionHandler interface
41
+ **File:** Create `packages/nestjs-common/lib/exception/handler/exception-handler.interface.ts`
42
+
43
+ ```typescript
44
+ export interface ExceptionContext {
45
+ lang: string;
46
+ request: any;
47
+ translate: (code: number, lang: string, args?: any, prefix?: string) => Promise<string>;
48
+ }
49
+
50
+ export interface ExceptionResult {
51
+ httpStatus: number;
52
+ errorCode: number;
53
+ message: string;
54
+ }
55
+
56
+ export interface ExceptionHandler {
57
+ canHandle(exception: unknown): boolean;
58
+ handle(exception: unknown, context: ExceptionContext): Promise<ExceptionResult> | ExceptionResult;
59
+ }
60
+ ```
61
+
62
+ ### 2.2: Create built-in handlers
63
+ **File:** Create `packages/nestjs-common/lib/exception/handler/` directory with:
64
+
65
+ - `app-exception.handler.ts` — handles `AppException` and all subclasses. Uses exception's own httpStatus and errorCode. Translates message via i18n.
66
+ - `forbidden.handler.ts` — handles NestJS `ForbiddenException`
67
+ - `not-found.handler.ts` — handles NestJS `NotFoundException`
68
+ - `bad-request.handler.ts` — handles NestJS `BadRequestException` (validation errors)
69
+ - `microservice.handler.ts` — handles `HttpMicroServiceException`
70
+ - `throttler.handler.ts` — handles ThrottlerException **without** `isPackageInstalled` hack. Instead: `canHandle()` checks `exception.constructor.name === 'ThrottlerException'` OR uses a try/catch dynamic import at handler construction time.
71
+ - `unknown.handler.ts` — fallback handler, always returns true for `canHandle()`
72
+ - `index.ts` — barrel + `builtInHandlers` array in correct priority order
73
+
74
+ **Important:** The handler order matters. `AppException` handler must come before `unknown`. The `unknown` handler is always last.
75
+
76
+ ### 2.3: Create EXCEPTION_HANDLERS token
77
+ **File:** Create `packages/nestjs-common/lib/exception/exception.constants.ts`
78
+ ```typescript
79
+ export const EXCEPTION_HANDLERS = Symbol('EXCEPTION_HANDLERS');
80
+ ```
81
+
82
+ **Commit:** `feat: add ExceptionHandler interface and built-in handlers`
83
+
84
+ ## Phase 3: Extensible GlobalExceptionsFilter
85
+
86
+ ### 3.1: Refactor GlobalExceptionsFilter
87
+ **File:** `packages/nestjs-common/lib/exception/global-exception.filter.ts`
88
+
89
+ **Changes:**
90
+ - Add static `customHandlers` Map for static registration (with dedup by constructor name)
91
+ - Add static `registerHandler(handler: ExceptionHandler)` method
92
+ - Accept `@Optional() @Inject(EXCEPTION_HANDLERS) handlers?: ExceptionHandler[]` in constructor
93
+ - Merge: built-in handlers + static handlers + injected handlers
94
+ - `catch()` method: iterate handlers with try/catch, first match wins, unknown handler is fallback
95
+ - Remove all the individual `handleXxx` methods (they move to handler classes)
96
+ - Keep `translate()` method as it's shared via ExceptionContext
97
+
98
+ ```typescript
99
+ @Catch()
100
+ export class GlobalExceptionsFilter implements ExceptionFilter {
101
+ private static customHandlers = new Map<string, ExceptionHandler>();
102
+ private readonly handlers: ExceptionHandler[];
103
+ private readonly logger = new Logger(GlobalExceptionsFilter.name);
104
+
105
+ constructor(
106
+ private readonly httpAdapterHost: HttpAdapterHost,
107
+ @Optional() private readonly i18nService: I18nService,
108
+ @Optional() @Inject(EXCEPTION_HANDLERS) injectedHandlers?: ExceptionHandler[],
109
+ ) {
110
+ this.handlers = [
111
+ ...(injectedHandlers || []),
112
+ ...Array.from(GlobalExceptionsFilter.customHandlers.values()),
113
+ ...builtInHandlers, // unknown handler is always last
114
+ ];
115
+ }
116
+
117
+ static registerHandler(handler: ExceptionHandler): void {
118
+ const name = handler.constructor.name;
119
+ if (!GlobalExceptionsFilter.customHandlers.has(name)) {
120
+ GlobalExceptionsFilter.customHandlers.set(name, handler);
121
+ }
122
+ }
123
+
124
+ static clearHandlers(): void {
125
+ GlobalExceptionsFilter.customHandlers.clear();
126
+ }
127
+
128
+ async catch(exception: unknown, host: ArgumentsHost): Promise<void> {
129
+ const { httpAdapter } = this.httpAdapterHost;
130
+ const ctx = host.switchToHttp();
131
+ const response = ctx.getResponse();
132
+ const request = ctx.getRequest();
133
+ const lang = request.i18nLang;
134
+
135
+ const context: ExceptionContext = {
136
+ lang,
137
+ request,
138
+ translate: (code, lang, args, prefix) => this.translate(code, lang, args, prefix),
139
+ };
140
+
141
+ let result: ExceptionResult | undefined;
142
+ for (const handler of this.handlers) {
143
+ try {
144
+ if (handler.canHandle(exception)) {
145
+ result = await handler.handle(exception, context);
146
+ break;
147
+ }
148
+ } catch (handlerError) {
149
+ this.logger.error(
150
+ `Exception handler ${handler.constructor.name} failed: ${handlerError}`,
151
+ handlerError instanceof Error ? handlerError.stack : undefined,
152
+ );
153
+ }
154
+ }
155
+
156
+ if (!result) {
157
+ result = { httpStatus: 500, errorCode: -1, message: 'Internal Server Error' };
158
+ }
159
+
160
+ httpAdapter.reply(
161
+ response,
162
+ JsonResponse.Error(result.errorCode, result.message),
163
+ result.httpStatus,
164
+ );
165
+ }
166
+
167
+ // Keep translate as shared utility
168
+ async translate(...) { ... }
169
+ }
170
+ ```
171
+
172
+ **Commit:** `refactor: make GlobalExceptionsFilter extensible with handler chain pattern`
173
+
174
+ ## Phase 4: ExceptionModule
175
+
176
+ ### 4.1: Create ExceptionModule
177
+ **File:** Create `packages/nestjs-common/lib/exception/exception.module.ts`
178
+
179
+ ```typescript
180
+ @Module({})
181
+ export class ExceptionModule {
182
+ static forRoot(options?: { handlers?: Type<ExceptionHandler>[] }): DynamicModule {
183
+ const handlerProviders = (options?.handlers || []).map(handler => ({
184
+ provide: EXCEPTION_HANDLERS,
185
+ useClass: handler,
186
+ // NestJS doesn't support multi, so collect them in a factory
187
+ }));
188
+
189
+ return {
190
+ module: ExceptionModule,
191
+ global: true,
192
+ providers: [
193
+ // Collect all handler classes into a single array provider
194
+ {
195
+ provide: EXCEPTION_HANDLERS,
196
+ useFactory: (...handlers: ExceptionHandler[]) => handlers,
197
+ inject: options?.handlers || [],
198
+ },
199
+ ...(options?.handlers || []), // Register handler classes as providers for DI
200
+ {
201
+ provide: APP_FILTER,
202
+ useClass: GlobalExceptionsFilter,
203
+ },
204
+ ],
205
+ exports: [EXCEPTION_HANDLERS],
206
+ };
207
+ }
208
+ }
209
+ ```
210
+
211
+ ### 4.2: Update barrel exports
212
+ **File:** `packages/nestjs-common/lib/exception/index.ts`
213
+ **Change:** Export `ExceptionModule`, `ExceptionHandler`, `ExceptionResult`, `ExceptionContext`, `EXCEPTION_HANDLERS`
214
+
215
+ **Commit:** `feat: add ExceptionModule for easy handler registration`
216
+
217
+ ## Phase 5: Tests
218
+
219
+ ### 5.1: Unit tests for new exception classes
220
+ **File:** Update `packages/nestjs-common/test/exception/exceptions.spec.ts` (or the file created in the previous fix plan)
221
+ **Tests:**
222
+ - Each new exception has correct httpStatus
223
+ - Each new exception has correct errorCode
224
+ - `UsernameNotFoundException` still returns 404
225
+ - `HttpMicroServiceException` still works (deprecated but functional)
226
+
227
+ ### 5.2: Unit tests for exception handlers
228
+ **File:** Create `packages/nestjs-common/test/exception/handlers.spec.ts`
229
+ **Tests:**
230
+ - Each built-in handler `canHandle()` returns true for correct exception type
231
+ - Each built-in handler `canHandle()` returns false for wrong exception type
232
+ - Each built-in handler `handle()` returns correct ExceptionResult
233
+ - ThrottlerExceptionHandler works with mock ThrottlerException
234
+ - Unknown handler always returns true for canHandle
235
+
236
+ ### 5.3: Update GlobalExceptionsFilter e2e tests
237
+ **File:** `packages/nestjs-common/test/exception/global-exception-filter.e2e.spec.ts`
238
+ **Changes:**
239
+ - Update test module to use `ExceptionModule.forRoot()` instead of manual filter setup
240
+ - Add test for custom handler registration
241
+ - Add test for static `registerHandler()`
242
+ - Ensure all existing exception paths still work
243
+
244
+ ### 5.4: Unit test for ExceptionModule
245
+ **File:** Create `packages/nestjs-common/test/exception/exception.module.spec.ts`
246
+ **Tests:**
247
+ - `forRoot()` without handlers works
248
+ - `forRoot()` with custom handlers includes them
249
+ - Custom handler is called before built-in handlers
250
+
251
+ **Commit:** `test: add tests for exception hierarchy, handlers, and ExceptionModule`
252
+
253
+ ## Phase 6: Update E2E test expectations
254
+
255
+ After all changes, run `bun test packages/nestjs-common` and fix any remaining test expectation mismatches caused by the refactored filter.
256
+
257
+ **Commit:** `test: update e2e test expectations for refactored exception handling`
258
+
259
+ ## Test Strategy
260
+ - After Phase 1: `bun test packages/nestjs-common` — ensure existing tests pass (no breaking changes yet)
261
+ - After Phase 2-3: Unit test handlers individually
262
+ - After Phase 4: Test ExceptionModule integration
263
+ - After Phase 5-6: Full suite `bun test packages/nestjs-common`
264
+ - Final: `bun run build --filter=@nathapp/nestjs-common`
265
+
266
+ ## Important Notes
267
+ - Do NOT push to remote — local commits only
268
+ - Keep old exception class names working (backward compat)
269
+ - `HttpMicroServiceException` — only add `@deprecated` JSDoc, do NOT change base class
270
+ - Handler priority: injected > static > built-in > unknown (last)
271
+ - ThrottlerException handler: use `exception.constructor.name === 'ThrottlerException'` check instead of `isPackageInstalled` at runtime. This avoids the dynamic require on every request.
272
+ - The `translate` method must remain accessible to handlers via `ExceptionContext`
273
+ - `ExceptionModule.forRoot()` should be `global: true` so the filter applies everywhere
274
+ - Use `APP_FILTER` from `@nestjs/core` for registering the global filter