@nestjs/observe 0.3.26 → 0.3.28

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 (61) hide show
  1. package/README.md +38 -2
  2. package/dist/agent/observe-agent.shared-buffer.js +5 -0
  3. package/dist/agent/telemetry-wire-contract.js +3 -3
  4. package/dist/cli/link.js +24 -2
  5. package/dist/cli/package-manager.d.ts +6 -0
  6. package/dist/cli/package-manager.js +60 -3
  7. package/dist/cli/project-files.d.ts +25 -5
  8. package/dist/cli/project-files.js +98 -15
  9. package/dist/custom-metrics/summary.js +17 -10
  10. package/dist/instrument/create-instance-decorator.instrument.js +390 -38
  11. package/dist/instrument/raw-receiver.d.ts +6 -0
  12. package/dist/instrument/raw-receiver.js +32 -0
  13. package/dist/interfaces/observe-options.interface.d.ts +14 -5
  14. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  15. package/dist/otlp/otlp-span.mapper.js +19 -1
  16. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  17. package/dist/otlp/otlp-trace-exporter.service.js +232 -38
  18. package/dist/outgoing/http.integration.js +36 -11
  19. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  20. package/dist/outgoing/mongodb.integration.js +93 -18
  21. package/dist/outgoing/mssql.integration.js +9 -4
  22. package/dist/outgoing/mysql2.integration.js +3 -1
  23. package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
  24. package/dist/outgoing/pg.integration.js +5 -0
  25. package/dist/outgoing/sql-statement.util.js +36 -10
  26. package/dist/protocols/bull-observe-agent.service.js +21 -0
  27. package/dist/protocols/deferred-trace-completion.d.ts +8 -2
  28. package/dist/protocols/deferred-trace-completion.js +40 -3
  29. package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
  30. package/dist/protocols/graphql-observe-agent.service.js +188 -14
  31. package/dist/protocols/graphql-operation-parser.js +45 -14
  32. package/dist/protocols/http-observe-agent.service.d.ts +14 -7
  33. package/dist/protocols/http-observe-agent.service.js +57 -14
  34. package/dist/protocols/job-trace-runner.d.ts +7 -0
  35. package/dist/protocols/job-trace-runner.js +72 -8
  36. package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
  37. package/dist/protocols/rpc-observe-agent.service.js +146 -10
  38. package/dist/protocols/ws-observe-agent.service.js +1 -1
  39. package/dist/services/logger-patcher.service.js +13 -3
  40. package/dist/services/operation-trace.registry.d.ts +13 -0
  41. package/dist/services/operation-trace.registry.js +195 -65
  42. package/dist/services/stdout-forwarder.service.js +22 -2
  43. package/dist/services/tracer.service.d.ts +19 -14
  44. package/dist/services/tracer.service.js +57 -34
  45. package/dist/utils/capture-request.util.js +36 -8
  46. package/dist/utils/context-accessor.util.d.ts +16 -0
  47. package/dist/utils/context-accessor.util.js +28 -0
  48. package/dist/utils/default-trace-id-generator.util.js +5 -7
  49. package/dist/utils/error-stack.util.d.ts +13 -0
  50. package/dist/utils/error-stack.util.js +166 -0
  51. package/dist/utils/log-line.parser.d.ts +8 -0
  52. package/dist/utils/log-line.parser.js +13 -4
  53. package/dist/utils/log-redactor.js +184 -10
  54. package/dist/utils/redact-url-query.d.ts +16 -5
  55. package/dist/utils/redact-url-query.js +20 -7
  56. package/dist/utils/source-context.util.d.ts +6 -0
  57. package/dist/utils/source-context.util.js +68 -33
  58. package/dist/utils/source-map-resolver.util.js +25 -4
  59. package/dist/utils/store-copy.util.d.ts +10 -0
  60. package/dist/utils/store-copy.util.js +43 -0
  61. package/package.json +4 -3
@@ -1,6 +1,11 @@
1
1
  import { Reflector } from "@nestjs/core";
2
+ import { X509Certificate } from "node:crypto";
3
+ import { Stream } from "node:stream";
2
4
  import { types } from "node:util";
3
5
  import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
6
+ import { copyStore } from "../utils/store-copy.util.js";
7
+ import { rewriteStackFrames } from "../utils/error-stack.util.js";
8
+ import { registerRawReceiver } from "./raw-receiver.js";
4
9
  /**
5
10
  * Stand-in "class name" for instrumented standalone functions. Unlike methods,
6
11
  * they have no enclosing class to borrow a name from, so every span they emit
@@ -74,6 +79,62 @@ function isMongoDriverHandle(instance) {
74
79
  }
75
80
  return false;
76
81
  }
82
+ /**
83
+ * Whether an instance is data and nothing else: an object literal, a
84
+ * null-prototype record or an array with no function and no accessor among
85
+ * its own members - the options object or list behind a `useValue`, or what a
86
+ * `useFactory` returns.
87
+ *
88
+ * It has no method of its own to trace, and a proxy around it breaks what the
89
+ * value itself supports: the structured clone algorithm consults no trap and
90
+ * refuses a proxy whatever its target is, so `structuredClone`, `postMessage`,
91
+ * `workerData` and `v8.serialize` all threw on an injected options object.
92
+ * What it inherits from `Object` or `Array` (`columns.map`) is no longer
93
+ * traced either.
94
+ *
95
+ * Members are read as descriptors, so no getter runs here; an accessor may
96
+ * hand out a function, and so counts as one. A proxy is never data: it
97
+ * answers these questions with its traps - a nestjs-cls proxy provider reads
98
+ * as `{}` until a request resolves it - and could not be cloned to begin with.
99
+ */
100
+ function isPlainData(instance) {
101
+ if (types.isProxy(instance)) {
102
+ return false;
103
+ }
104
+ const proto = Object.getPrototypeOf(instance);
105
+ if (proto !== null &&
106
+ proto !== Object.prototype &&
107
+ proto !== Array.prototype) {
108
+ return false;
109
+ }
110
+ for (const key of Reflect.ownKeys(instance)) {
111
+ const own = Reflect.getOwnPropertyDescriptor(instance, key);
112
+ if (own === undefined ||
113
+ own.get !== undefined ||
114
+ own.set !== undefined ||
115
+ typeof own.value === "function") {
116
+ return false;
117
+ }
118
+ }
119
+ return true;
120
+ }
121
+ /**
122
+ * Whether an instance is a key or a certificate of `node:crypto`: a
123
+ * `KeyObject`, a Web Crypto `CryptoKey` or an `X509Certificate`.
124
+ *
125
+ * Node recognises each by a brand of its own (`#slots in key`, an internal
126
+ * slot) wherever one is handed in as an argument - to `createHmac`, `sign`,
127
+ * `subtle.sign`, `cert.checkIssued`, and through them `jsonwebtoken` - and no
128
+ * proxy carries it, so an injected key failed every call it was given to
129
+ * ("The "key" argument must be of type ... KeyObject"). Its methods run
130
+ * against the raw instance either way; handed out as a proxy, it is no longer
131
+ * the object Node made.
132
+ */
133
+ function isCryptoHandle(instance) {
134
+ return (types.isKeyObject(instance) ||
135
+ types.isCryptoKey(instance) ||
136
+ instance instanceof X509Certificate);
137
+ }
77
138
  /**
78
139
  * Library classes traced only in part, each with a method only it has, which
79
140
  * tells it from an application's own class of the same name - `ValidationPipe`
@@ -89,6 +150,21 @@ function isMongoDriverHandle(instance) {
89
150
  * - `@nestjs/config`'s `ConfigService` keeps what an application calls. Each
90
151
  * `get` made four or five more spans of its private helpers - 2.7M of its
91
152
  * 4.6M a day, in 220 projects.
153
+ * - `@nestjs/throttler`'s `ThrottlerGuard` keeps `canActivate`, and its
154
+ * in-memory `ThrottlerStorageService` nothing. Per named throttler, every
155
+ * request made 19 more spans: `resolveValue` and `toNumber` three times
156
+ * each, `handleRequest`, `getRequestResponse`, `setResponseHeader` three
157
+ * times, and `increment` with seven calls of the store's helpers - with
158
+ * `shouldSkip`, 40 a request for two throttlers where one is kept now. They
159
+ * were in 61 to 77 of 187 active projects, about 1.5M a week, and up to ~50
160
+ * of the events a health-check-only app was billed for each probe.
161
+ * The store is a `Map` and a timer: `increment` does no I/O, so its time is
162
+ * all in the `canActivate` span already. A store that does, such as a Redis
163
+ * one, is another class and keeps its own spans and its client's.
164
+ *
165
+ * An application's subclass - a `GqlThrottlerGuard` overriding
166
+ * `getRequestResponse`, a guard overriding `getTracker` or `shouldSkip` -
167
+ * keeps a span for each method it overrides.
92
168
  *
93
169
  * Folding cannot reach any of them (`collapseRepeatedSpans`), because each
94
170
  * repeats only a few times under its parent.
@@ -117,14 +193,38 @@ const PARTLY_TRACED_CLASSES = new Map([
117
193
  traced: new Set(["get", "getOrThrow", "set", "setEnvFilePaths"]),
118
194
  },
119
195
  ],
196
+ // `throwThrottlingException` is on every ThrottlerGuard from 4.x to 6.8,
197
+ // and `fireHitCount` on every ThrottlerStorageService since 6.0, which
198
+ // covers every release that supports Nest 11 and 12.
199
+ [
200
+ "ThrottlerGuard",
201
+ {
202
+ marker: "throwThrottlingException",
203
+ traced: new Set(["canActivate"]),
204
+ },
205
+ ],
206
+ ["ThrottlerStorageService", { marker: "fireHitCount", traced: new Set() }],
120
207
  ]);
121
- /** The methods a prototype's class keeps traced, if it is one of those. */
208
+ /**
209
+ * The methods a prototype's class keeps traced, if it is one of those.
210
+ *
211
+ * The marker has to be the class's own, and new with it. A subclass an
212
+ * application names after the class it extends (`import { ValidationPipe as
213
+ * NestValidationPipe }`) inherits the marker, or overrides it, and is still
214
+ * the application's: taken for the library's, its methods were handed out
215
+ * unwrapped, and one that reads a private member (`this.#x`) threw on the
216
+ * proxy it then ran against.
217
+ */
122
218
  function partlyTracedMethodsOf(proto) {
123
219
  const candidate = proto;
124
220
  const entry = PARTLY_TRACED_CLASSES.get(candidate.constructor?.name ?? "");
125
- return entry !== undefined && typeof candidate[entry.marker] === "function"
126
- ? entry.traced
127
- : null;
221
+ if (entry === undefined ||
222
+ !Object.hasOwn(proto, entry.marker) ||
223
+ typeof candidate[entry.marker] !== "function") {
224
+ return null;
225
+ }
226
+ const parent = Object.getPrototypeOf(proto);
227
+ return parent === null || !(entry.marker in parent) ? entry.traced : null;
128
228
  }
129
229
  /** Whether an instance is one of those classes, or extends one. */
130
230
  function extendsPartlyTracedClass(instance) {
@@ -189,7 +289,13 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
189
289
  const callTraced = named(frameName, (thisArg, args, requestId, stepId) => {
190
290
  try {
191
291
  const result = call(thisArg, args);
192
- if (result instanceof Promise) {
292
+ // Only a promise with the native `then` is chained or watched. A
293
+ // `then` the promise brought itself is the caller's to call: on a
294
+ // lazy promise (`p-lazy`, a postgres.js query) that call is what
295
+ // starts the work, and the caller may never make it. Such a
296
+ // promise is handed back like any other thenable, and its span
297
+ // ends with the call.
298
+ if (result instanceof Promise && hasNativeThen(result)) {
193
299
  // Closing the span is a side effect: a registry failure must
194
300
  // leave the caller with the value or rejection it would have
195
301
  // seen without the span.
@@ -216,8 +322,8 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
216
322
  // rejected where those handlers do not reach: dropped by the
217
323
  // caller, it was an unhandled rejection, and under Node's default
218
324
  // it ended a process that handled the failure. Handed back, it
219
- // also keeps what it carries beyond its value (`json()` on a
220
- // `got` request, `kill()` on an `execa` child, a subclass).
325
+ // also keeps what it carries beyond its value (`kill()` on an
326
+ // `execa` child, a subclass that keeps the native `then`).
221
327
  // Watching marks it handled, so a rejection nobody handles no
222
328
  // longer raises `unhandledRejection`; the span still records it.
223
329
  result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
@@ -264,9 +370,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
264
370
  }
265
371
  // Everything the caller's context holds, with this span as the caller
266
372
  // of whatever it calls. A copy, so the caller's context still names
267
- // the caller once this call returns.
268
- const spanStore = new Map(store);
269
- spanStore.set(CALLER_METADATA_KEY, newStepId);
373
+ // the caller once this call returns. Only the caller is the span's
374
+ // own: an attribute set in the call is written through to the
375
+ // caller's context too - see `copyStore`.
376
+ const spanStore = copyStore(store, [CALLER_METADATA_KEY, newStepId]);
270
377
  return als.run(spanStore, callTraced, thisArg, args, requestId, newStepId);
271
378
  }
272
379
  finally {
@@ -324,16 +431,29 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
324
431
  let slotBacked;
325
432
  let bareBuiltIn;
326
433
  let partlyTraced;
434
+ let nodeStream;
435
+ let classInstance;
327
436
  try {
328
437
  // Inspected here, inside the guard, for the same reason as the checks
329
438
  // below: reading a provider's constructor can run a trap that throws.
330
- if (isFrameworkNoise(instance)) {
439
+ //
440
+ // A frozen object is handed back as it is: a proxy has to answer a read
441
+ // of each of its members with the member itself, so there is nothing
442
+ // it could trace - see `isReadOnlyDataProperty`. So is plain data, which
443
+ // has nothing to trace and which a proxy keeps from being cloned, and
444
+ // a key or certificate of Node's own.
445
+ if (isFrameworkNoise(instance) ||
446
+ Object.isFrozen(instance) ||
447
+ isPlainData(instance) ||
448
+ isCryptoHandle(instance)) {
331
449
  return instance;
332
450
  }
333
- hasPrivateMembers = usesNativePrivateMembers(instance);
451
+ hasPrivateMembers = usesPrivateMembers(instance);
334
452
  slotBacked = isSlotBackedBuiltIn(instance);
335
453
  bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
336
454
  partlyTraced = extendsPartlyTracedClass(instance);
455
+ nodeStream = isNodeStream(instance);
456
+ classInstance = isClassInstance(instance);
337
457
  }
338
458
  catch {
339
459
  // Reading the prototype ran a trap that threw (nestjs-cls proxy
@@ -351,13 +471,26 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
351
471
  }
352
472
  // Slot-backed subclasses share the private-member trade-off: methods run
353
473
  // against the raw instance so the natives they inherit keep working.
354
- const requiresRawReceiver = hasPrivateMembers || slotBacked;
474
+ //
475
+ // So does a Node stream, for what it is fed by. The HTTP parser, zlib, a
476
+ // socket's handle or the generator behind `Readable.from` holds the raw
477
+ // stream and emits on it, and Node tells a stream's listeners apart by
478
+ // identity: the async iterator's "readable" listener compares its `this`
479
+ // with the stream the iterator was made on. Made on the proxy by a traced
480
+ // call, it never woke up, so `for await` over an injected request body
481
+ // hung - and threw "callback is not a function" outside any request,
482
+ // ending the process, once the client closed its socket.
483
+ const requiresRawReceiver = hasPrivateMembers || slotBacked || nodeStream;
355
484
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
356
485
  const methodRefsCache = new WeakMap();
357
486
  // Functions read off the instance that are handed out as they are:
358
487
  // constructors and callable objects.
359
488
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
360
489
  const passedThrough = new WeakSet();
490
+ // And the instance's own functions, see the `get` trap.
491
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
492
+ const ownFunctions = new WeakSet();
493
+ const ownFunctionsPassThrough = classInstance && !requiresRawReceiver;
361
494
  const proxy = new Proxy(instance, {
362
495
  // Runs for every property read through the proxy - each `this.field`
363
496
  // and `this.dependency.method` inside a traced call - so the common
@@ -377,6 +510,15 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
377
510
  if (typeof attributeValue !== "function" || prop === "constructor") {
378
511
  return attributeValue;
379
512
  }
513
+ // A member the instance can never change is handed out as it is and
514
+ // runs untraced: the engine accepts no other answer. Asked ahead of
515
+ // both caches, which go by the function: the same one may also sit
516
+ // under a writable key, and an instance can be frozen after its
517
+ // method was wrapped.
518
+ const own = Reflect.getOwnPropertyDescriptor(target, prop);
519
+ if (isReadOnlyDataProperty(own)) {
520
+ return attributeValue;
521
+ }
380
522
  // When "originalMethod" is already proxied, return the cached version
381
523
  const cached = methodRefsCache.get(attributeValue);
382
524
  if (cached) {
@@ -385,6 +527,31 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
385
527
  if (passedThrough.has(attributeValue)) {
386
528
  return attributeValue;
387
529
  }
530
+ // A function a class instance holds itself - an arrow-function field,
531
+ // a method its constructor bound, a callback it stored - was made with
532
+ // the raw instance in hand, and the class compares it by identity
533
+ // from code that never reads it through the proxy. mssql's
534
+ // `Transaction` adds `this._abort` to the pooled connection in
535
+ // `_begin` and removes it inside `_abort`, an arrow function whose
536
+ // `this` is the raw instance: wrapped, the listener stayed, and the
537
+ // next rollback on that connection ended the process. Such a function
538
+ // is handed out as it is, and gets no span of its own.
539
+ //
540
+ // Remembered apart from `passedThrough` and honoured only for a read
541
+ // of an own property, so the same function read under a prototype
542
+ // name is still a method. Not for a class whose methods run against
543
+ // the raw instance: those never read their functions through here,
544
+ // and a plain function it holds relies on the wrapper for that
545
+ // receiver.
546
+ if (own !== undefined && ownFunctionsPassThrough) {
547
+ if (ownFunctions.has(attributeValue)) {
548
+ return attributeValue;
549
+ }
550
+ if (isInstanceOwnFunction(target, prop, attributeValue)) {
551
+ ownFunctions.add(attributeValue);
552
+ return attributeValue;
553
+ }
554
+ }
388
555
  const shouldProxy =
389
556
  // A constructor held in a field - pg-pool's `this.Promise` - is
390
557
  // invoked with `new` and read for statics (`this.Promise.reject`);
@@ -467,7 +634,24 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
467
634
  methodRefsCache.set(attributeValue, wrapped);
468
635
  return wrapped;
469
636
  },
637
+ // An assignment made on the provider runs a setter against the raw
638
+ // instance, as a read runs a getter: one that writes `this.#x` threw
639
+ // "Cannot write private member" with the proxy as `this`. Only for the
640
+ // classes whose methods get the raw instance; an object that inherits
641
+ // from the proxy assigns to itself, as it would without it.
642
+ ...(requiresRawReceiver && {
643
+ set: (target, prop, value, receiver) => receiver === proxy
644
+ ? Reflect.set(target, prop, value)
645
+ : Reflect.set(target, prop, value, receiver),
646
+ }),
470
647
  });
648
+ // The raw instance only reaches the methods read through the proxy. A
649
+ // caller that reads one off the class prototype and applies it to the
650
+ // proxy - as `@nestjs/graphql` does with a resolver's - has to be handed
651
+ // the instance, and finds it through `rawReceiverOf`.
652
+ if (requiresRawReceiver) {
653
+ registerRawReceiver(proxy, instance);
654
+ }
471
655
  return proxy;
472
656
  };
473
657
  return (instance) => {
@@ -480,6 +664,82 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
480
664
  return instance;
481
665
  };
482
666
  }
667
+ /**
668
+ * Whether a property is an own data property that is neither writable nor
669
+ * configurable: what `Object.freeze` makes of every member, and what
670
+ * `Object.defineProperty(obj, key, { value })` creates by default.
671
+ *
672
+ * A proxy's `get` trap has to answer a read of such a property with the
673
+ * target's own value. The engine compares the two after the trap returns and
674
+ * throws a TypeError when they differ ("'get' on proxy: property ... is a
675
+ * read-only and non-configurable data property on the proxy target but the
676
+ * proxy did not return its actual value"), so a traced wrapper in its place
677
+ * failed the read itself, before anything was called.
678
+ *
679
+ * A method found on the prototype has no own descriptor, so a class instance
680
+ * keeps its spans.
681
+ */
682
+ function isReadOnlyDataProperty(own) {
683
+ return (own !== undefined && own.configurable === false && own.writable === false);
684
+ }
685
+ /**
686
+ * Whether an instance was built by a class, or anything else that hands it a
687
+ * prototype of its own - as opposed to an object literal, a null-prototype
688
+ * object, an ES module namespace or an array, whose own functions are the
689
+ * methods a caller means to trace, and which have no constructor that could
690
+ * have kept a reference to one of them.
691
+ */
692
+ function isClassInstance(instance) {
693
+ const proto = Object.getPrototypeOf(instance);
694
+ return (proto !== null && proto !== Object.prototype && !Array.isArray(instance));
695
+ }
696
+ /**
697
+ * Whether a function an instance holds as an own property is the instance's
698
+ * own, rather than a method of its class held a second time.
699
+ *
700
+ * Not when the prototype chain holds that very function, under any name
701
+ * (`this.build = this.render`): it is a method, and one wrapper stands in for
702
+ * it whichever name it is read by. Nor when the class has a method of the
703
+ * same name that carries metadata (`this.create = this.create.bind(this)` in
704
+ * a controller): Nest reads such a handler off the instance, and unwrapped, a
705
+ * request it served without calling anything else had no span, and was
706
+ * dropped for it.
707
+ *
708
+ * Read as descriptors, so no getter runs; asked once per function, since the
709
+ * answer is kept.
710
+ */
711
+ function isInstanceOwnFunction(instance, prop, fn) {
712
+ for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
713
+ const sameName = Reflect.getOwnPropertyDescriptor(proto, prop)?.value;
714
+ if (typeof sameName === "function" &&
715
+ Reflect.getMetadataKeys(sameName).length > 0) {
716
+ return false;
717
+ }
718
+ for (const key of Reflect.ownKeys(proto)) {
719
+ const descriptor = Reflect.getOwnPropertyDescriptor(proto, key);
720
+ if (descriptor?.value === fn ||
721
+ descriptor?.get === fn ||
722
+ descriptor?.set === fn) {
723
+ return false;
724
+ }
725
+ }
726
+ }
727
+ return true;
728
+ }
729
+ /**
730
+ * Whether `promise.then` is the native method: no override on a subclass, no
731
+ * `then` of the promise's own. Calling the native one only registers the
732
+ * callbacks; calling anything else runs code the promise brought with it.
733
+ */
734
+ function hasNativeThen(promise) {
735
+ try {
736
+ return promise.then === Promise.prototype.then;
737
+ }
738
+ catch {
739
+ // A `then` getter that throws: nothing to watch it by.
740
+ return false;
741
+ }
742
+ }
483
743
  /** Runs span bookkeeping whose failure must not reach the caller. */
484
744
  function ignoreFailure(fn) {
485
745
  try {
@@ -525,18 +785,14 @@ function relabelProxyFrame(err, className, methodName) {
525
785
  stackHeaderLength(err) > MAX_RELABELLED_HEADER_LENGTH) {
526
786
  return;
527
787
  }
528
- const stack = err.stack;
529
- if (typeof stack !== "string") {
530
- return;
531
- }
532
788
  // `async` prefixes the type name on frames resumed from an await. Spaces
533
789
  // and tabs only after the newline, not `\s`: a newline matched there too,
534
790
  // and a message of newlines then rescanned the run after each one.
535
791
  const frame = new RegExp(`(\\n[ \\t]*at (?:async )?)Proxy\\.${escapeRegExp(methodName)}\\b`);
536
- if (!frame.test(stack)) {
537
- return;
538
- }
539
- err.stack = stack.replace(frame, `$1${className}.${methodName}`);
792
+ // Not `err.stack` read and assigned back: that read would fix the
793
+ // error's message in its stack, whatever a caller does to the message
794
+ // afterwards - see `readStack`.
795
+ rewriteStackFrames(err, (stack) => stack.replace(frame, `$1${className}.${methodName}`));
540
796
  }
541
797
  catch {
542
798
  // Left as it is.
@@ -620,6 +876,9 @@ function isCallableObject(fn) {
620
876
  * `%TypedArray%.prototype` (reached via `Uint8Array`'s parent) covers every
621
877
  * typed array - and, through it, Node's `Buffer`. `Array` is deliberately
622
878
  * absent: its methods are generic and proxy-safe.
879
+ *
880
+ * The `Intl` services are read off the namespace instead of being spelled
881
+ * out, see `intlServicePrototypes()`.
623
882
  */
624
883
  const SLOT_BACKED_PROTOTYPES = new Set([
625
884
  Map.prototype,
@@ -637,7 +896,33 @@ const SLOT_BACKED_PROTOTYPES = new Set([
637
896
  WeakRef.prototype,
638
897
  FinalizationRegistry.prototype,
639
898
  Object.getPrototypeOf(Uint8Array.prototype),
899
+ ...intlServicePrototypes(),
640
900
  ]);
901
+ /**
902
+ * Prototypes of the `Intl` services (`NumberFormat`, `DateTimeFormat`,
903
+ * `Collator`, `PluralRules`, `Locale`, ...). Their methods, and the `format`
904
+ * and `compare` accessors that hand out a bound function, read
905
+ * `[[InitializedNumberFormat]]` and the like off their receiver, so a
906
+ * formatter registered as a provider threw "called on incompatible receiver"
907
+ * on its first use.
908
+ *
909
+ * Which services there are depends on the runtime - `DurationFormat` only
910
+ * arrived in Node 23, and a Node built without ICU has no `Intl` at all - so
911
+ * the constructors are collected from the namespace. Its plain functions
912
+ * (`getCanonicalLocales`, `supportedValuesOf`) have no `prototype`.
913
+ */
914
+ function intlServicePrototypes() {
915
+ if (typeof Intl === "undefined") {
916
+ return [];
917
+ }
918
+ return Object.getOwnPropertyNames(Intl).flatMap((name) => {
919
+ const service = Reflect.get(Intl, name);
920
+ const prototype = typeof service === "function" ? service.prototype : undefined;
921
+ return typeof prototype === "object" && prototype !== null
922
+ ? [prototype]
923
+ : [];
924
+ });
925
+ }
641
926
  /**
642
927
  * Whether the instance's prototype chain passes through a slot-backed
643
928
  * built-in, meaning its (inherited) native methods would throw if invoked with
@@ -653,6 +938,26 @@ function isSlotBackedBuiltIn(instance) {
653
938
  }
654
939
  return false;
655
940
  }
941
+ /**
942
+ * Whether an instance is a Node stream: a `Readable`, `Writable` or anything
943
+ * built on them (an `IncomingMessage`, a socket, a zlib or file stream), and
944
+ * the legacy `Stream` under an `OutgoingMessage`.
945
+ *
946
+ * Matched by shape as well as by class: `readable-stream` is the same code
947
+ * published to npm, its current major no longer extends Node's `Stream`, and
948
+ * its async iterator makes the same identity check. The state object is what
949
+ * every copy's methods reach for first.
950
+ */
951
+ function isNodeStream(instance) {
952
+ if (instance instanceof Stream) {
953
+ return true;
954
+ }
955
+ const candidate = instance;
956
+ return ((typeof candidate._readableState === "object" &&
957
+ candidate._readableState !== null) ||
958
+ (typeof candidate._writableState === "object" &&
959
+ candidate._writableState !== null));
960
+ }
656
961
  /**
657
962
  * Whether a constructor is engine- or platform-provided rather than user
658
963
  * code. A slot-backed instance whose entire chain is native (`new Map()`,
@@ -672,11 +977,26 @@ function isNativeFunction(fn) {
672
977
  return true;
673
978
  }
674
979
  }
675
- // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
676
980
  const privateMemberCache = new WeakMap();
677
981
  /**
678
- * Whether any class in the instance's prototype chain declares native private
679
- * members (`#field`, `#method()`).
982
+ * What a compiler leaves of `#name` when the target is below ES2022: the
983
+ * member moves into a `WeakMap` or `WeakSet` keyed by the instance, and every
984
+ * access goes through a helper that checks its receiver against it. That is
985
+ * the same brand check, with no `#` left in the class source.
986
+ *
987
+ * Covers the helpers of tsc and tslib (`__classPrivateFieldGet`), Babel and
988
+ * oxc (`_classPrivateFieldGet2`, `_assertClassBrand`), SWC
989
+ * (`_class_private_field_get`) and esbuild (`__privateGet`). Matched anywhere
990
+ * in a name, since an imported helper is reached through a namespace or under
991
+ * a numbered alias (`tslib_1.__classPrivateFieldGet`). Not the loose-mode
992
+ * helpers of Babel and SWC (`_classPrivateFieldLooseBase`): loose mode keeps
993
+ * the member on the instance under a string key, which reads through the
994
+ * proxy like any other property.
995
+ */
996
+ const COMPILED_PRIVATE_MEMBER = /classPrivate(?:Field|Method|Getter|Setter)(?!Loose)|assertClassBrand|class_private_(?:field|method)_(?!loose)|__private(?:Get|Set|Add|Method|In|Wrapper)\b/;
997
+ /**
998
+ * Whether any class in the instance's prototype chain declares private
999
+ * members (`#field`, `#method()`), native or compiled away.
680
1000
  *
681
1001
  * Detection reads the class source: private members can only be touched from
682
1002
  * inside the lexical class body, so a class whose text contains no `#name`
@@ -684,34 +1004,66 @@ const privateMemberCache = new WeakMap();
684
1004
  * false-positive, which merely selects the raw-instance receiver - every call
685
1005
  * still works, only nested self-call spans are lost - so the cheap test is
686
1006
  * safe to lean on.
1007
+ *
1008
+ * A compiled class is told by its helper calls, under the same trade-off:
1009
+ * they stay in the class body, where the `#name` was. A `WeakMap` keyed by
1010
+ * `this` that an application writes by hand leaves no such trace, and is not
1011
+ * covered.
687
1012
  */
688
- function usesNativePrivateMembers(instance) {
1013
+ function usesPrivateMembers(instance) {
689
1014
  let proto = Object.getPrototypeOf(instance);
690
1015
  while (proto && proto !== Object.prototype) {
691
- const ctor = proto.constructor;
692
- if (typeof ctor === "function" && ctor !== Object) {
693
- let hasPrivate = privateMemberCache.get(ctor);
694
- if (hasPrivate === undefined) {
695
- hasPrivate = declaresPrivateMembers(ctor);
696
- privateMemberCache.set(ctor, hasPrivate);
697
- }
698
- if (hasPrivate) {
699
- return true;
700
- }
1016
+ let hasPrivate = privateMemberCache.get(proto);
1017
+ if (hasPrivate === undefined) {
1018
+ hasPrivate = prototypeUsesPrivateMembers(proto);
1019
+ privateMemberCache.set(proto, hasPrivate);
1020
+ }
1021
+ if (hasPrivate) {
1022
+ return true;
701
1023
  }
702
1024
  proto = Object.getPrototypeOf(proto);
703
1025
  }
704
1026
  return false;
705
1027
  }
1028
+ /**
1029
+ * Whether the class a prototype belongs to declares native private members.
1030
+ *
1031
+ * `constructor` leads to that class only while it is the one the class
1032
+ * definition put there, which is when its `prototype` is this very object. A
1033
+ * helper that mixes classes in by copying the own properties of their
1034
+ * prototypes - the TypeScript handbook's `applyMixins`, ioredis's
1035
+ * `applyMixin` - copies `constructor` along, and the receiving prototype then
1036
+ * names the last class mixed in, whose source says nothing about the one
1037
+ * being inspected. That one's own body can no longer be reached from here,
1038
+ * but its methods and accessors can: each one's text is a part of the class
1039
+ * body, and a brand check made on `this` shows in it.
1040
+ */
1041
+ function prototypeUsesPrivateMembers(proto) {
1042
+ const ctor = Object.hasOwn(proto, "constructor")
1043
+ ? Object.getOwnPropertyDescriptor(proto, "constructor")?.value
1044
+ : undefined;
1045
+ if (typeof ctor === "function" && ctor.prototype === proto) {
1046
+ return ctor !== Object && declaresPrivateMembers(ctor);
1047
+ }
1048
+ return Reflect.ownKeys(proto).some((key) => {
1049
+ if (key === "constructor") {
1050
+ return false;
1051
+ }
1052
+ // Read as descriptors, so that no getter runs.
1053
+ const descriptor = Reflect.getOwnPropertyDescriptor(proto, key);
1054
+ return [descriptor?.value, descriptor?.get, descriptor?.set].some((member) => typeof member === "function" && declaresPrivateMembers(member));
1055
+ });
1056
+ }
706
1057
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
707
- function declaresPrivateMembers(ctor) {
1058
+ function declaresPrivateMembers(fn) {
708
1059
  try {
1060
+ const source = Function.prototype.toString.call(fn);
709
1061
  // `#` starting a private name is never preceded by an identifier
710
1062
  // character; `obj.#x` and `#x in obj` and declarations all match.
711
- return /(^|[^\w$])#[\w$]/.test(Function.prototype.toString.call(ctor));
1063
+ return (/(^|[^\w$])#[\w$]/.test(source) || COMPILED_PRIVATE_MEMBER.test(source));
712
1064
  }
713
1065
  catch {
714
- // A constructor whose source is unavailable (bound functions, some
1066
+ // A function whose source is unavailable (bound functions, some
715
1067
  // natives) cannot be a class body with private members.
716
1068
  return false;
717
1069
  }
@@ -0,0 +1,6 @@
1
+ export declare function registerRawReceiver(proxy: object, instance: object): void;
2
+ /**
3
+ * The instance a provider's prototype methods have to be applied to, when
4
+ * that is not the provider itself - `undefined` for anything else.
5
+ */
6
+ export declare function rawReceiverOf(provider: object): object | undefined;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The instance behind each proxy the instance decorator hands out for a class
3
+ * whose methods only the instance itself can be the receiver of: one with
4
+ * private members, or one built on a slot-backed built-in.
5
+ *
6
+ * The proxy runs every method read through it against that instance. A
7
+ * method read anywhere else - off the class prototype - and applied to the
8
+ * proxy gets no such help, and throws on its first `this.#x`. Whoever has to
9
+ * apply one that way asks here for the receiver to use instead.
10
+ *
11
+ * Kept out of the decorator's module, which the package exports in full: the
12
+ * instance behind a proxy is the agent's to hand over, not an application's
13
+ * to look up. Module-level and weak, so a proxy names its instance for as
14
+ * long as the two live, whichever agent made it.
15
+ */
16
+ const rawReceivers = new WeakMap();
17
+ export function registerRawReceiver(proxy, instance) {
18
+ rawReceivers.set(proxy, instance);
19
+ }
20
+ /**
21
+ * The instance a provider's prototype methods have to be applied to, when
22
+ * that is not the provider itself - `undefined` for anything else.
23
+ */
24
+ export function rawReceiverOf(provider) {
25
+ let receiver = rawReceivers.get(provider);
26
+ // A provider handed out a second time (`useExisting`, a factory returning
27
+ // another provider) is a proxy of the first proxy.
28
+ while (receiver !== undefined && rawReceivers.has(receiver)) {
29
+ receiver = rawReceivers.get(receiver);
30
+ }
31
+ return receiver;
32
+ }