@nathapp/nestjs-common 4.5.0 → 4.6.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 (33) hide show
  1. package/AGENTS.md +16 -4
  2. package/CLAUDE.md +15 -3
  3. package/GEMINI.md +16 -4
  4. package/README.md +59 -0
  5. package/codex.md +16 -4
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.js +1 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/interceptor/serializable.interceptor.d.ts +9 -0
  10. package/dist/interceptor/serializable.interceptor.js +319 -8
  11. package/dist/interceptor/serializable.interceptor.js.map +1 -1
  12. package/dist/outbound-http/address.d.ts +1 -0
  13. package/dist/outbound-http/address.js +26 -0
  14. package/dist/outbound-http/address.js.map +1 -0
  15. package/dist/outbound-http/assert-outbound-url.d.ts +10 -0
  16. package/dist/outbound-http/assert-outbound-url.js +62 -0
  17. package/dist/outbound-http/assert-outbound-url.js.map +1 -0
  18. package/dist/outbound-http/errors.d.ts +7 -0
  19. package/dist/outbound-http/errors.js +26 -0
  20. package/dist/outbound-http/errors.js.map +1 -0
  21. package/dist/outbound-http/guarded-http-client.d.ts +24 -0
  22. package/dist/outbound-http/guarded-http-client.js +108 -0
  23. package/dist/outbound-http/guarded-http-client.js.map +1 -0
  24. package/dist/outbound-http/index.d.ts +5 -0
  25. package/dist/outbound-http/index.js +24 -0
  26. package/dist/outbound-http/index.js.map +1 -0
  27. package/dist/outbound-http/native-request.d.ts +7 -0
  28. package/dist/outbound-http/native-request.js +108 -0
  29. package/dist/outbound-http/native-request.js.map +1 -0
  30. package/dist/outbound-http/policy.d.ts +16 -0
  31. package/dist/outbound-http/policy.js +40 -0
  32. package/dist/outbound-http/policy.js.map +1 -0
  33. package/package.json +1 -1
package/AGENTS.md CHANGED
@@ -15,7 +15,9 @@ These instructions apply to all AI coding agents in this project.
15
15
 
16
16
  **Language:** TypeScript
17
17
 
18
- **Key dependencies:** @nathapp/typescript-config, @nestjs/throttler, typescript
18
+ **Key dependencies:** @nestjs/config, @nathapp/typescript-config, @nestjs/throttler, typescript
19
+
20
+ **Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check && npm run type-check:test`
19
21
 
20
22
  ---
21
23
  # @nathapp/nestjs-common
@@ -23,8 +25,18 @@ These instructions apply to all AI coding agents in this project.
23
25
  Foundation package — exceptions, filters, interceptors, validation, pagination, shared types.
24
26
 
25
27
  ## Commands
26
- - Test: `npx jest --config test/jest-test.json --no-coverage`
27
- - Build: `npx tsc`
28
+
29
+ Run from `packages/nestjs-common/`. Replace the example test path with a path relative to this package.
30
+
31
+ | Purpose | Command |
32
+ | --- | --- |
33
+ | Build this package | `npm run build` |
34
+ | Run specific test files | `npm test -- --runTestsByPath path/to/file.spec.ts` |
35
+ | Run the default suite | `npm test` |
36
+ | Run the default suite with coverage | `npm run test:cov` |
37
+ | Type-check library source | `npm run type-check` |
38
+ | Type-check test source | `npm run type-check:test` |
39
+ | Lint library and test source | `npm run lint` |
28
40
 
29
41
  ## Exception System
30
42
  - `GlobalExceptionsFilter` with handler chain pattern — extensible via `ExceptionHandler` interface.
@@ -46,4 +58,4 @@ Foundation package — exceptions, filters, interceptors, validation, pagination
46
58
 
47
59
  ## IMPORTANT
48
60
  - Many packages depend on this — changes here affect the entire monorepo.
49
- - Rebuild (`npx tsc`) after changes before testing dependent packages.
61
+ - Rebuild (`npm run build`) after changes before testing dependent packages.
package/CLAUDE.md CHANGED
@@ -15,14 +15,26 @@ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
15
15
 
16
16
  **Key dependencies:** @nestjs/config, @nathapp/typescript-config, @nestjs/throttler, typescript
17
17
 
18
+ **Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check && npm run type-check:test`
19
+
18
20
  ---
19
21
  # @nathapp/nestjs-common
20
22
 
21
23
  Foundation package — exceptions, filters, interceptors, validation, pagination, shared types.
22
24
 
23
25
  ## Commands
24
- - Test: `npx jest --config test/jest-test.json --no-coverage`
25
- - Build: `npx tsc`
26
+
27
+ Run from `packages/nestjs-common/`. Replace the example test path with a path relative to this package.
28
+
29
+ | Purpose | Command |
30
+ | --- | --- |
31
+ | Build this package | `npm run build` |
32
+ | Run specific test files | `npm test -- --runTestsByPath path/to/file.spec.ts` |
33
+ | Run the default suite | `npm test` |
34
+ | Run the default suite with coverage | `npm run test:cov` |
35
+ | Type-check library source | `npm run type-check` |
36
+ | Type-check test source | `npm run type-check:test` |
37
+ | Lint library and test source | `npm run lint` |
26
38
 
27
39
  ## Exception System
28
40
  - `GlobalExceptionsFilter` with handler chain pattern — extensible via `ExceptionHandler` interface.
@@ -44,4 +56,4 @@ Foundation package — exceptions, filters, interceptors, validation, pagination
44
56
 
45
57
  ## IMPORTANT
46
58
  - Many packages depend on this — changes here affect the entire monorepo.
47
- - Rebuild (`npx tsc`) after changes before testing dependent packages.
59
+ - Rebuild (`npm run build`) after changes before testing dependent packages.
package/GEMINI.md CHANGED
@@ -13,7 +13,9 @@ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
13
13
 
14
14
  **Language:** TypeScript
15
15
 
16
- **Key dependencies:** @nathapp/typescript-config, @nestjs/throttler, typescript
16
+ **Key dependencies:** @nestjs/config, @nathapp/typescript-config, @nestjs/throttler, typescript
17
+
18
+ **Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check && npm run type-check:test`
17
19
 
18
20
  ---
19
21
  # @nathapp/nestjs-common
@@ -21,8 +23,18 @@ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
21
23
  Foundation package — exceptions, filters, interceptors, validation, pagination, shared types.
22
24
 
23
25
  ## Commands
24
- - Test: `npx jest --config test/jest-test.json --no-coverage`
25
- - Build: `npx tsc`
26
+
27
+ Run from `packages/nestjs-common/`. Replace the example test path with a path relative to this package.
28
+
29
+ | Purpose | Command |
30
+ | --- | --- |
31
+ | Build this package | `npm run build` |
32
+ | Run specific test files | `npm test -- --runTestsByPath path/to/file.spec.ts` |
33
+ | Run the default suite | `npm test` |
34
+ | Run the default suite with coverage | `npm run test:cov` |
35
+ | Type-check library source | `npm run type-check` |
36
+ | Type-check test source | `npm run type-check:test` |
37
+ | Lint library and test source | `npm run lint` |
26
38
 
27
39
  ## Exception System
28
40
  - `GlobalExceptionsFilter` with handler chain pattern — extensible via `ExceptionHandler` interface.
@@ -44,4 +56,4 @@ Foundation package — exceptions, filters, interceptors, validation, pagination
44
56
 
45
57
  ## IMPORTANT
46
58
  - Many packages depend on this — changes here affect the entire monorepo.
47
- - Rebuild (`npx tsc`) after changes before testing dependent packages.
59
+ - Rebuild (`npm run build`) after changes before testing dependent packages.
package/README.md CHANGED
@@ -186,3 +186,62 @@ export class AppService {
186
186
  this.globalFilter.registerHandler(new RateLimitExceptionHandler());
187
187
  }
188
188
  }
189
+
190
+
191
+ # Outbound HTTP guard
192
+
193
+ `GuardedHttpClient` and `assertOutboundUrl` protect server-side requests to URLs that a tenant or client can influence (OIDC discovery, token and JWKS URLs, dynamic-registration `jwks_uri`). Plain `fetch` accepts any scheme, follows redirects, has no timeout or size cap and reaches private networks.
194
+
195
+ ## What is blocked by default
196
+
197
+ - Schemes other than `https:` (`http:` only with `allowHttp` or an allow-listed host).
198
+ - URLs with userinfo (`https://user:pw@host/`).
199
+ - Any host whose address is not public unicast: private, loopback, link-local (including `169.254.169.254`), carrier-grade NAT, unique-local, unspecified, multicast, broadcast, reserved and transition ranges. IPv4-mapped IPv6 (`::ffff:127.0.0.1`) is classified by its IPv4 part. Also blocked: IPv4-compatible IPv6 (`::/96`), local-use NAT64 (`64:ff9b:1::/48`), site-local (`fec0::/10`), IPv6 documentation (`3fff::/20`) and SRv6 SIDs (`5f00::/16`). `localhost` and `*.localhost` are blocked without DNS.
200
+ - Hostnames are resolved with all answers checked; if any answer is blocked, the request is refused. DNS failure is refused.
201
+ - Redirects (any 3xx) are never followed.
202
+ - Exchanges slower than `timeoutMs` (covers the body read) and bodies larger than `maxBytes`.
203
+
204
+ Failures reject with `OutboundUrlBlockedError`, whose `reason` is one of `invalid-url`, `scheme`, `credentials`, `private-address`, `dns-failure`, `redirect`, `timeout`, `too-large`, `network`. Its `url` field (origin and pathname only) is safe to log.
205
+
206
+ ## Policy
207
+
208
+ | Field | Default | Meaning |
209
+ |-------|---------|---------|
210
+ | `allowedHosts` | `[]` | Hostnames that skip the IP-range check. Exact match, case-insensitive, trailing dot ignored, no wildcards. |
211
+ | `allowHttp` | `false` | Permit `http:` for any host. An allow-listed host may always use `http:`. |
212
+ | `timeoutMs` | `5000` | Positive integer. Whole-exchange timeout. |
213
+ | `maxBytes` | `1048576` | Positive integer. Maximum response body size. |
214
+
215
+ Invalid numeric values throw a `TypeError` naming the field when the policy is resolved (`resolveOutboundHttpPolicy`) or the client is constructed.
216
+
217
+ ## Escape hatch
218
+
219
+ To reach an in-cluster service such as a Keycloak on a private address, list its hostname in `allowedHosts`. That host skips the address check only; credentials in the URL, redirects, timeout and size limits still apply.
220
+
221
+ ## Usage
222
+
223
+ ```typescript
224
+ import { GuardedHttpClient, OutboundUrlBlockedError } from '@nathapp/nestjs-common';
225
+
226
+ const http = new GuardedHttpClient({ allowedHosts: ['keycloak.auth.svc.cluster.local'], allowHttp: false });
227
+
228
+ try {
229
+ const res = await http.get(`${issuer}/.well-known/openid-configuration`);
230
+ if (!res.ok) throw new Error(`discovery failed: ${res.status}`);
231
+ const config = await res.json();
232
+ const token = await http.postForm(tokenUrl, { grant_type: 'authorization_code', code }, { accept: 'application/json' });
233
+ } catch (error) {
234
+ if (error instanceof OutboundUrlBlockedError) {
235
+ logger.warn(`blocked ${error.reason} ${error.url}`);
236
+ }
237
+ throw error;
238
+ }
239
+ ```
240
+
241
+ Non-2xx responses are returned, not thrown. `json()` rejects with the native `SyntaxError` on invalid JSON.
242
+
243
+ ## DNS address pinning
244
+
245
+ `GuardedHttpClient` resolves each guarded hostname once per request. Its native HTTP(S) transport connects using only the checked addresses and keeps the original hostname for HTTP and TLS. Hosts in `allowedHosts` use normal DNS resolution.
246
+
247
+ The standalone `assertOutboundUrl()` checks a URL at lookup time. Use `GuardedHttpClient` when the connection must use those same addresses. The optional `deps.fetch` transport override is intended for test doubles.
package/codex.md CHANGED
@@ -13,7 +13,9 @@ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
13
13
 
14
14
  **Language:** TypeScript
15
15
 
16
- **Key dependencies:** @nathapp/typescript-config, @nestjs/throttler, typescript
16
+ **Key dependencies:** @nestjs/config, @nathapp/typescript-config, @nestjs/throttler, typescript
17
+
18
+ **Commands:** test: `npm run test` | lint: `npm run lint` | typecheck: `npm run type-check && npm run type-check:test`
17
19
 
18
20
  ---
19
21
  # @nathapp/nestjs-common
@@ -21,8 +23,18 @@ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
21
23
  Foundation package — exceptions, filters, interceptors, validation, pagination, shared types.
22
24
 
23
25
  ## Commands
24
- - Test: `npx jest --config test/jest-test.json --no-coverage`
25
- - Build: `npx tsc`
26
+
27
+ Run from `packages/nestjs-common/`. Replace the example test path with a path relative to this package.
28
+
29
+ | Purpose | Command |
30
+ | --- | --- |
31
+ | Build this package | `npm run build` |
32
+ | Run specific test files | `npm test -- --runTestsByPath path/to/file.spec.ts` |
33
+ | Run the default suite | `npm test` |
34
+ | Run the default suite with coverage | `npm run test:cov` |
35
+ | Type-check library source | `npm run type-check` |
36
+ | Type-check test source | `npm run type-check:test` |
37
+ | Lint library and test source | `npm run lint` |
26
38
 
27
39
  ## Exception System
28
40
  - `GlobalExceptionsFilter` with handler chain pattern — extensible via `ExceptionHandler` interface.
@@ -44,4 +56,4 @@ Foundation package — exceptions, filters, interceptors, validation, pagination
44
56
 
45
57
  ## IMPORTANT
46
58
  - Many packages depend on this — changes here affect the entire monorepo.
47
- - Rebuild (`npx tsc`) after changes before testing dependent packages.
59
+ - Rebuild (`npm run build`) after changes before testing dependent packages.
package/dist/index.d.ts CHANGED
@@ -10,6 +10,7 @@ export * from "./i18n";
10
10
  export * from "./interceptor";
11
11
  export * from "./ip";
12
12
  export * from "./logging";
13
+ export * from "./outbound-http";
13
14
  export * from "./module";
14
15
  export * from "./pagination";
15
16
  export * from "./serialize";
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ __exportStar(require("./i18n"), exports);
26
26
  __exportStar(require("./interceptor"), exports);
27
27
  __exportStar(require("./ip"), exports);
28
28
  __exportStar(require("./logging"), exports);
29
+ __exportStar(require("./outbound-http"), exports);
29
30
  __exportStar(require("./module"), exports);
30
31
  __exportStar(require("./pagination"), exports);
31
32
  __exportStar(require("./serialize"), exports);
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,2CAAyB;AACzB,6CAA2B;AAC3B,8CAA4B;AAC5B,6CAA2B;AAC3B,8CAA4B;AAC5B,yCAAuB;AACvB,iDAA+B;AAC/B,yCAAuB;AACvB,gDAA8B;AAC9B,uCAAqB;AACrB,4CAA0B;AAC1B,2CAAyB;AACzB,+CAA6B;AAC7B,8CAA4B;AAC5B,0CAAwB;AACxB,+CAA6B"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,0CAAwB;AACxB,2CAAyB;AACzB,6CAA2B;AAC3B,8CAA4B;AAC5B,6CAA2B;AAC3B,8CAA4B;AAC5B,yCAAuB;AACvB,iDAA+B;AAC/B,yCAAuB;AACvB,gDAA8B;AAC9B,uCAAqB;AACrB,4CAA0B;AAC1B,kDAAgC;AAChC,2CAAyB;AACzB,+CAA6B;AAC7B,8CAA4B;AAC5B,0CAAwB;AACxB,+CAA6B"}
@@ -5,14 +5,23 @@ export declare class SerializableInterceptor extends ClassSerializerInterceptor
5
5
  protected readonly reflector: any;
6
6
  protected readonly defaultOptions: ClassSerializerInterceptorOptions;
7
7
  private readonly logger;
8
+ private readonly getterSources;
9
+ private readonly getterTrees;
10
+ private readonly recordCopies;
11
+ private readonly classInputs;
8
12
  private fallbackLanguage;
9
13
  constructor(reflector: any, defaultOptions?: ClassSerializerInterceptorOptions);
10
14
  intercept(context: ExecutionContext, next: CallHandler<any>): any;
11
15
  customSerialize(response: PlainLiteralObject | Array<PlainLiteralObject>, options: ClassTransformOptions, lang: string): PlainLiteralObject | PlainLiteralObject[] | StreamableFile;
12
16
  serializeObject(obj: PlainLiteralObject, options: ClassTransformOptions, lang: string): PlainLiteralObject;
13
17
  private serializePreparedObject;
18
+ private transformSerializable;
14
19
  private deepClone;
15
20
  private cloneSpecialValue;
21
+ private sameDataFields;
22
+ private sameFieldValue;
23
+ private sameEntries;
24
+ private readPreparedGetter;
16
25
  private walkValue;
17
26
  transformObject(obj: PlainLiteralObject, lang: string, depth?: number): PlainLiteralObject;
18
27
  transformLocaleString(obj: LocaleString, lang: string): string;
@@ -17,12 +17,16 @@ exports.SerializableInterceptor = void 0;
17
17
  const common_1 = require("@nestjs/common");
18
18
  const class_transformer_1 = require("class-transformer");
19
19
  const rxjs_1 = require("rxjs");
20
+ const node_module_1 = require("node:module");
20
21
  const serialize_1 = require("../serialize");
21
22
  const constant_1 = require("../constant");
22
23
  const MAX_DEPTH = 100;
23
24
  const MAX_SAFE_DEPTH = MAX_DEPTH * 2;
24
25
  const OMIT_VALUE = Symbol('omit-value');
25
26
  const UNSAFE_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
27
+ const NON_SHELL_TYPES = new Set([Array, Boolean, Date, Map, Number, Object, Promise, RegExp, Set, String]);
28
+ if (typeof Buffer === 'function')
29
+ NON_SHELL_TYPES.add(Buffer);
26
30
  let SerializableInterceptor = SerializableInterceptor_1 = class SerializableInterceptor extends common_1.ClassSerializerInterceptor {
27
31
  constructor(reflector, defaultOptions = {}) {
28
32
  var _a;
@@ -33,6 +37,10 @@ let SerializableInterceptor = SerializableInterceptor_1 = class SerializableInte
33
37
  this.reflector = reflector;
34
38
  this.defaultOptions = defaultOptions;
35
39
  this.logger = new common_1.Logger(SerializableInterceptor_1.name);
40
+ this.getterSources = new WeakMap();
41
+ this.getterTrees = new WeakSet();
42
+ this.recordCopies = new WeakMap();
43
+ this.classInputs = new WeakMap();
36
44
  this.fallbackLanguage = 'en_US';
37
45
  this.isObject = (fn) => !this.isNil(fn) && typeof fn === 'object';
38
46
  this.isNil = (val) => this.isUndefined(val) || val === null;
@@ -72,9 +80,188 @@ let SerializableInterceptor = SerializableInterceptor_1 = class SerializableInte
72
80
  }
73
81
  serializePreparedObject(obj, options, lang) {
74
82
  const safeOptions = { ...options, enableCircularCheck: true };
75
- const data = obj instanceof serialize_1.Serializable ? (0, class_transformer_1.instanceToInstance)(obj, safeOptions) : obj;
83
+ const data = obj instanceof serialize_1.Serializable ? this.transformSerializable(obj, safeOptions) : obj;
76
84
  return this.transformToPlain(this.transformObject(data, lang, 0), safeOptions);
77
85
  }
86
+ transformSerializable(obj, options) {
87
+ var _a;
88
+ if (!this.getterTrees.has(obj))
89
+ return (0, class_transformer_1.instanceToInstance)(obj, options);
90
+ let Executor;
91
+ let metadata;
92
+ try {
93
+ const fromTransformer = (0, node_module_1.createRequire)(require.resolve('class-transformer'));
94
+ Executor = fromTransformer('./TransformOperationExecutor').TransformOperationExecutor;
95
+ metadata = fromTransformer('./storage').defaultMetadataStorage;
96
+ }
97
+ catch (_b) {
98
+ return (0, class_transformer_1.instanceToInstance)(obj, options);
99
+ }
100
+ if (typeof ((_a = Executor === null || Executor === void 0 ? void 0 : Executor.prototype) === null || _a === void 0 ? void 0 : _a.transform) !== 'function' || typeof Executor.prototype.getKeys !== 'function' ||
101
+ typeof (metadata === null || metadata === void 0 ? void 0 : metadata.findExposeMetadata) !== 'function') {
102
+ return (0, class_transformer_1.instanceToInstance)(obj, options);
103
+ }
104
+ const getters = this.getterSources;
105
+ const recordCopies = this.recordCopies;
106
+ const classInputs = this.classInputs;
107
+ const isSpecial = (item) => this.cloneSpecialValue(item) !== undefined;
108
+ const declaredType = (source, key, forObject) => {
109
+ var _a;
110
+ const declared = (_a = metadata.findTypeMetadata) === null || _a === void 0 ? void 0 : _a.call(metadata, source.constructor, key);
111
+ if (!declared)
112
+ return undefined;
113
+ if (!declared.typeFunction)
114
+ return declared.reflectedType;
115
+ try {
116
+ return declared.typeFunction({ newObject: forObject, object: source, property: key });
117
+ }
118
+ catch (_b) {
119
+ return undefined;
120
+ }
121
+ };
122
+ const isShellable = (type) => typeof type === 'function' && !NON_SHELL_TYPES.has(type) && !!type.prototype &&
123
+ typeof type.prototype === 'object' && Object.getPrototypeOf(type.prototype) !== null;
124
+ const shells = new WeakMap();
125
+ const createShell = (prototype, source, omitMissing) => {
126
+ const shell = Object.create(prototype);
127
+ shells.set(shell, { prototype, source, omitMissing });
128
+ const seen = new Set();
129
+ for (let owner = prototype; owner && owner !== Object.prototype; owner = Object.getPrototypeOf(owner)) {
130
+ for (const key of Object.getOwnPropertyNames(owner)) {
131
+ if (UNSAFE_KEYS.has(key) || seen.has(key))
132
+ continue;
133
+ seen.add(key);
134
+ const field = Object.getOwnPropertyDescriptor(owner, key);
135
+ const getter = field === null || field === void 0 ? void 0 : field.get;
136
+ if (!getter)
137
+ continue;
138
+ const present = !omitMissing || (source !== null && typeof source === 'object' && key in source);
139
+ let assigned = false;
140
+ let stored;
141
+ Object.defineProperty(shell, key, {
142
+ configurable: true,
143
+ enumerable: false,
144
+ get: () => {
145
+ if (assigned)
146
+ return stored;
147
+ if (!present)
148
+ return shell;
149
+ try {
150
+ return getter.call(shell);
151
+ }
152
+ catch (_a) {
153
+ return undefined;
154
+ }
155
+ },
156
+ set: (next) => {
157
+ if (!present)
158
+ return;
159
+ assigned = true;
160
+ stored = next;
161
+ },
162
+ });
163
+ }
164
+ }
165
+ return shell;
166
+ };
167
+ const nestedDestination = (source, initial, current, key, target) => {
168
+ if (current instanceof Map)
169
+ return undefined;
170
+ const declared = declaredType(source, key, target);
171
+ if (isShellable(declared))
172
+ return Array.isArray(current) ? [] : createShell(declared.prototype, current, false);
173
+ if (Array.isArray(current))
174
+ return [];
175
+ const currentClass = current !== null && typeof current === 'object' ? Object.getPrototypeOf(current) : null;
176
+ const ownClass = currentClass !== null && Object.getPrototypeOf(currentClass) !== null &&
177
+ currentClass !== Object.getPrototypeOf(initial);
178
+ if (ownClass || initial instanceof Map || initial instanceof Set || isSpecial(initial))
179
+ return undefined;
180
+ const initialPrototype = Object.getPrototypeOf(initial);
181
+ if (initialPrototype === null || initialPrototype === Object.prototype || Array.isArray(initial))
182
+ return undefined;
183
+ return createShell(initialPrototype, current, true);
184
+ };
185
+ class ReceiverAwareExecutor extends Executor {
186
+ constructor() {
187
+ super(...arguments);
188
+ this.selected = new WeakMap();
189
+ }
190
+ getKeys(target, value, isMap) {
191
+ const keys = super.getKeys(target, value, isMap);
192
+ if (getters.has(value))
193
+ this.selected.set(value, keys);
194
+ return keys;
195
+ }
196
+ transform(...args) {
197
+ var _a, _b, _c;
198
+ const [, value, requestedType] = args;
199
+ const destination = args[0];
200
+ const shell = destination !== null && typeof destination === 'object'
201
+ ? shells.get(destination)
202
+ : undefined;
203
+ if (shell && isShellable(requestedType) && requestedType.prototype !== shell.prototype &&
204
+ Object.prototype.isPrototypeOf.call(requestedType.prototype, value)) {
205
+ args[0] = createShell(requestedType.prototype, shell.source, shell.omitMissing);
206
+ }
207
+ const sources = getters.get(value);
208
+ if (!sources || typeof value.constructor !== 'function' || (requestedType && requestedType !== value.constructor)) {
209
+ const result = super.transform(...args);
210
+ const original = recordCopies.get(value);
211
+ if (original && result && typeof result === 'object' && Object.getPrototypeOf(original) === Object.getPrototypeOf(result)) {
212
+ classInputs.set(result, original);
213
+ }
214
+ return result;
215
+ }
216
+ const prototype = value.constructor.prototype;
217
+ const inherited = [...sources.keys()].filter(key => {
218
+ if (Object.hasOwn(prototype, key))
219
+ return false;
220
+ for (let base = Object.getPrototypeOf(prototype); base; base = Object.getPrototypeOf(base)) {
221
+ const field = Object.getOwnPropertyDescriptor(base, key);
222
+ if (field)
223
+ return field.get && !field.set;
224
+ }
225
+ return false;
226
+ });
227
+ const placeholders = [];
228
+ if (inherited.length && !args[0]) {
229
+ const target = new value.constructor();
230
+ const emitted = new Set(this.getKeys(value.constructor, value, false));
231
+ for (const [key, field] of Object.entries(Object.getOwnPropertyDescriptors(target))) {
232
+ if (!emitted.has(key) || !('value' in field) || field.value === null || typeof field.value !== 'object' || !field.writable)
233
+ continue;
234
+ target[key] = nestedDestination(value, field.value, value[key], key, target);
235
+ }
236
+ for (const key of inherited) {
237
+ if (Object.hasOwn(target, key))
238
+ continue;
239
+ Object.defineProperty(target, key, { configurable: true, writable: true, value: undefined });
240
+ placeholders.push(key);
241
+ }
242
+ args[0] = target;
243
+ }
244
+ const result = super.transform(...args);
245
+ for (const key of placeholders)
246
+ delete result[key];
247
+ for (const source of sources.values())
248
+ source.classTransformed = true;
249
+ getters.set(result, sources);
250
+ if (!options.ignoreDecorators) {
251
+ for (const key of (_a = this.selected.get(value)) !== null && _a !== void 0 ? _a : []) {
252
+ if (!sources.has(key))
253
+ continue;
254
+ const alias = (_c = (_b = metadata.findExposeMetadata(value.constructor, key)) === null || _b === void 0 ? void 0 : _b.options) === null || _c === void 0 ? void 0 : _c.name;
255
+ if (alias && alias !== key)
256
+ delete result[alias];
257
+ }
258
+ }
259
+ return result;
260
+ }
261
+ }
262
+ const executor = new ReceiverAwareExecutor(class_transformer_1.TransformationType.CLASS_TO_CLASS, { exposeUnsetFields: true, ...options });
263
+ return executor.transform(undefined, obj, undefined, undefined, false);
264
+ }
78
265
  deepClone(obj) {
79
266
  const result = this.walkValue(obj, this.fallbackLanguage, 0, new Set(), false);
80
267
  return result === OMIT_VALUE ? undefined : result;
@@ -88,7 +275,71 @@ let SerializableInterceptor = SerializableInterceptor_1 = class SerializableInte
88
275
  return new RegExp(value.source, value.flags);
89
276
  return undefined;
90
277
  }
278
+ sameDataFields(original, prepared) {
279
+ const fields = (obj) => Object.entries(Object.getOwnPropertyDescriptors(obj))
280
+ .filter(([, field]) => field.enumerable);
281
+ const before = fields(original);
282
+ const after = new Map(fields(prepared));
283
+ return before.length === after.size && before.every(([key, field]) => {
284
+ var _a, _b, _c, _d, _e, _f;
285
+ const item = after.get(key);
286
+ if (!item || ('value' in field) !== ('value' in item))
287
+ return false;
288
+ if (!('value' in field)) {
289
+ return ((_c = (_b = (_a = this.getterSources.get(prepared)) === null || _a === void 0 ? void 0 : _a.get(key)) === null || _b === void 0 ? void 0 : _b.read) !== null && _c !== void 0 ? _c : item.get) ===
290
+ ((_f = (_e = (_d = this.getterSources.get(original)) === null || _d === void 0 ? void 0 : _d.get(key)) === null || _e === void 0 ? void 0 : _e.read) !== null && _f !== void 0 ? _f : field.get);
291
+ }
292
+ return this.sameFieldValue(field.value, item.value);
293
+ });
294
+ }
295
+ sameFieldValue(before, after) {
296
+ if (Object.is(before, after) || (this.recordCopies.has(after) && this.recordCopies.get(after) === before))
297
+ return true;
298
+ if (before instanceof Date && after instanceof Date && Object.getPrototypeOf(before) === Date.prototype) {
299
+ return !Reflect.ownKeys(before).length && Object.is(Date.prototype.getTime.call(before), Date.prototype.getTime.call(after));
300
+ }
301
+ if (Buffer.isBuffer(before) && Buffer.isBuffer(after)) {
302
+ return Reflect.ownKeys(before).length === before.length && Buffer.compare(before, after) === 0;
303
+ }
304
+ if (before instanceof RegExp && after instanceof RegExp && Object.getPrototypeOf(before) === RegExp.prototype) {
305
+ return Reflect.ownKeys(before).length === 1 && before.source === after.source &&
306
+ before.flags === after.flags && before.lastIndex === after.lastIndex;
307
+ }
308
+ return false;
309
+ }
310
+ sameEntries(before, after) {
311
+ if (Object.getPrototypeOf(before) !== Object.getPrototypeOf(after) || Reflect.ownKeys(before).length || before.size !== after.size)
312
+ return false;
313
+ const entries = after.entries();
314
+ for (const [key, item] of before.entries()) {
315
+ const copy = entries.next().value;
316
+ if (!copy || !this.sameFieldValue(key, copy[0]) || !this.sameFieldValue(item, copy[1]))
317
+ return false;
318
+ }
319
+ return true;
320
+ }
321
+ readPreparedGetter(source, receiver) {
322
+ const captureOwn = source.ownEnumerable && !source.classTransformed;
323
+ if (!captureOwn && !this.sameDataFields(source.receiver, receiver)) {
324
+ try {
325
+ return source.read.call(receiver);
326
+ }
327
+ catch (_a) {
328
+ return OMIT_VALUE;
329
+ }
330
+ }
331
+ if (!('originalValue' in source)) {
332
+ try {
333
+ source.originalValue = source.read.call(source.receiver);
334
+ }
335
+ catch (_b) {
336
+ source.originalValue = OMIT_VALUE;
337
+ }
338
+ }
339
+ return source.originalValue;
340
+ }
91
341
  walkValue(value, lang, depth, ancestors, localize) {
342
+ var _a, _b, _c;
92
343
  if (value === null || typeof value !== 'object')
93
344
  return value;
94
345
  if (ancestors.has(value))
@@ -118,10 +369,13 @@ let SerializableInterceptor = SerializableInterceptor_1 = class SerializableInte
118
369
  return special;
119
370
  ancestors.add(value);
120
371
  let clone;
372
+ let hasGetters = false;
373
+ const trackChild = (child) => { hasGetters || (hasGetters = this.getterTrees.has(child)); };
121
374
  if (Array.isArray(value)) {
122
375
  clone = [];
123
376
  for (const item of value) {
124
377
  const child = this.walkValue(item, lang, depth + 1, ancestors, localize && depth < MAX_DEPTH);
378
+ trackChild(child);
125
379
  clone.push(child === OMIT_VALUE ? null : child);
126
380
  }
127
381
  }
@@ -130,27 +384,84 @@ let SerializableInterceptor = SerializableInterceptor_1 = class SerializableInte
130
384
  for (const [key, item] of value.entries()) {
131
385
  const clonedKey = this.walkValue(key, lang, depth + 1, ancestors, localize && depth < MAX_DEPTH);
132
386
  const clonedItem = this.walkValue(item, lang, depth + 1, ancestors, localize && depth < MAX_DEPTH);
133
- if (clonedKey !== OMIT_VALUE && clonedItem !== OMIT_VALUE)
387
+ if (clonedKey !== OMIT_VALUE && clonedItem !== OMIT_VALUE) {
134
388
  clone.set(clonedKey, clonedItem);
389
+ trackChild(clonedItem);
390
+ }
135
391
  }
136
392
  }
137
393
  else if (value instanceof Set) {
138
394
  clone = new Set();
139
395
  for (const item of value.values()) {
140
396
  const child = this.walkValue(item, lang, depth + 1, ancestors, localize && depth < MAX_DEPTH);
141
- if (child !== OMIT_VALUE)
397
+ if (child !== OMIT_VALUE) {
398
+ trackChild(child);
142
399
  clone.add(child);
400
+ }
143
401
  }
144
402
  }
145
403
  else {
146
404
  clone = Object.create(Object.getPrototypeOf(value));
147
- for (const key of Object.keys(value)) {
148
- if (UNSAFE_KEYS.has(key) || !Object.prototype.hasOwnProperty.call(value, key))
405
+ const childLocalize = localize && depth < MAX_DEPTH;
406
+ const own = Object.getOwnPropertyDescriptors(value);
407
+ for (const [key, field] of Object.entries(own)) {
408
+ if (UNSAFE_KEYS.has(key) || !field.enumerable || !('value' in field))
149
409
  continue;
150
- const child = this.walkValue(value[key], lang, depth + 1, ancestors, localize && depth < MAX_DEPTH);
151
- if (child !== OMIT_VALUE)
152
- clone[key] = child;
410
+ const child = this.walkValue(field.value, lang, depth + 1, ancestors, childLocalize);
411
+ if (child !== OMIT_VALUE) {
412
+ trackChild(child);
413
+ Object.defineProperty(clone, key, { value: child, enumerable: true, writable: true, configurable: true });
414
+ }
153
415
  }
416
+ const seen = new Set();
417
+ const sources = new Map();
418
+ const previousSources = this.getterSources.get(value);
419
+ let path;
420
+ for (let receiver = value; receiver && receiver !== Object.prototype; receiver = Object.getPrototypeOf(receiver)) {
421
+ for (const key of Object.getOwnPropertyNames(receiver)) {
422
+ if (UNSAFE_KEYS.has(key) || seen.has(key))
423
+ continue;
424
+ seen.add(key);
425
+ const field = Object.getOwnPropertyDescriptor(receiver, key);
426
+ if (!field.get)
427
+ continue;
428
+ path !== null && path !== void 0 ? path : (path = new Set(ancestors).add(clone));
429
+ const source = (_a = previousSources === null || previousSources === void 0 ? void 0 : previousSources.get(key)) !== null && _a !== void 0 ? _a : {
430
+ read: field.get, receiver: value, path, ownEnumerable: receiver === value && !!field.enumerable,
431
+ };
432
+ sources.set(key, source);
433
+ const getterPath = new Set([...path, ...source.path]);
434
+ let cached;
435
+ let resolved = false;
436
+ const resolve = () => this.walkValue(this.readPreparedGetter(source, clone), lang, depth + 1, getterPath, childLocalize);
437
+ Object.defineProperty(clone, key, {
438
+ enumerable: receiver === value && field.enumerable,
439
+ configurable: true,
440
+ get() {
441
+ if (!resolved) {
442
+ resolved = true;
443
+ cached = resolve();
444
+ }
445
+ return cached === OMIT_VALUE ? this : cached;
446
+ },
447
+ });
448
+ }
449
+ }
450
+ if (sources.size) {
451
+ this.getterSources.set(clone, sources);
452
+ hasGetters = true;
453
+ }
454
+ }
455
+ if (hasGetters)
456
+ this.getterTrees.add(clone);
457
+ const prototype = Object.getPrototypeOf(value);
458
+ const original = (_c = (_b = this.classInputs.get(value)) !== null && _b !== void 0 ? _b : this.recordCopies.get(value)) !== null && _c !== void 0 ? _c : value;
459
+ if (!hasGetters && (prototype === null || prototype === Object.prototype || prototype === Array.prototype)) {
460
+ if (this.sameDataFields(original, clone))
461
+ this.recordCopies.set(clone, original);
462
+ }
463
+ else if (!hasGetters && (prototype === Map.prototype || prototype === Set.prototype) && this.sameEntries(original, clone)) {
464
+ this.recordCopies.set(clone, original);
154
465
  }
155
466
  ancestors.delete(value);
156
467
  return clone;