@nestjs/observe 0.3.25 → 0.3.27

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 (109) hide show
  1. package/README.md +55 -2
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +201 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -0,0 +1,166 @@
1
+ import { types } from "node:util";
2
+ /**
3
+ * Every error the agent has looked at, with the frames it keeps for it - or
4
+ * nothing, for a stack it left as it was. Decided once, on first contact.
5
+ */
6
+ const heldStacks = new WeakMap();
7
+ /**
8
+ * Stands in for the message while the stack is written. Made of characters no
9
+ * message an error is given by accident contains, so it is found where it is.
10
+ */
11
+ const MESSAGE_MARKER = "\u0000nestjs-observe:message\u0000";
12
+ /**
13
+ * Whether the message can be set aside for the marker and put back exactly:
14
+ * an own data property that is writable, or none at all - `new Error()` - on
15
+ * an error that can take one. A message behind an accessor (`DOMException`)
16
+ * runs code to set, and is not touched.
17
+ */
18
+ function messageIsReplaceable(err) {
19
+ for (let holder = err; holder !== null; holder = Object.getPrototypeOf(holder)) {
20
+ const descriptor = Reflect.getOwnPropertyDescriptor(holder, "message");
21
+ if (descriptor !== undefined) {
22
+ return ("value" in descriptor &&
23
+ descriptor.writable === true &&
24
+ (holder === err || Object.isExtensible(err)));
25
+ }
26
+ }
27
+ return Object.isExtensible(err);
28
+ }
29
+ function holdStack(err) {
30
+ // Sealing makes `stack` non-configurable, and so the accessor impossible:
31
+ // the stack is read as it is. Asked before anything else, since asking for
32
+ // the descriptor of a stack not written yet writes it on Node 20.
33
+ if (types.isProxy(err) ||
34
+ Object.isSealed(err) ||
35
+ !messageIsReplaceable(err)) {
36
+ return undefined;
37
+ }
38
+ const ownMessage = Object.hasOwn(err, "message");
39
+ const message = err.message;
40
+ let written;
41
+ let markedFirstLine;
42
+ try {
43
+ err.message = MESSAGE_MARKER;
44
+ written = err.stack;
45
+ markedFirstLine = Error.prototype.toString.call(err);
46
+ }
47
+ finally {
48
+ if (ownMessage) {
49
+ err.message = message;
50
+ }
51
+ else {
52
+ delete err.message;
53
+ }
54
+ }
55
+ if (typeof written !== "string") {
56
+ return undefined;
57
+ }
58
+ const at = written.indexOf(MESSAGE_MARKER);
59
+ if (at === -1) {
60
+ // Written before the agent saw it: left as it is.
61
+ return undefined;
62
+ }
63
+ const before = written.slice(0, at);
64
+ const after = written.slice(at + MESSAGE_MARKER.length);
65
+ const lineEnd = after.indexOf("\n");
66
+ const restOfLine = lineEnd === -1 ? after : after.slice(0, lineEnd);
67
+ const frames = lineEnd === -1 ? "" : after.slice(lineEnd);
68
+ // The first line as V8 writes it - `name: message`, or the name alone for
69
+ // an empty message - is written again the same way; any other shape (Node's
70
+ // `TypeError [ERR_X]: message`) keeps what surrounds the message.
71
+ const firstLine = `${before}${MESSAGE_MARKER}${restOfLine}` === markedFirstLine
72
+ ? () => Error.prototype.toString.call(err)
73
+ : () => `${before}${err.message}${restOfLine}`;
74
+ const own = Reflect.getOwnPropertyDescriptor(err, "stack");
75
+ const enumerable = own?.enumerable ?? false;
76
+ const settle = (value) => Reflect.defineProperty(err, "stack", {
77
+ value,
78
+ writable: true,
79
+ enumerable,
80
+ configurable: true,
81
+ });
82
+ if (own?.configurable !== true || frames.includes(MESSAGE_MARKER)) {
83
+ // Written with the marker, and no way to keep it from the application:
84
+ // write it out now, as it would have been written at this read.
85
+ settle(firstLine() + frames.split(MESSAGE_MARKER).join(String(message)));
86
+ return undefined;
87
+ }
88
+ const held = {
89
+ frames,
90
+ firstLine,
91
+ get: () => {
92
+ // The application's read: the one that fixes the first line.
93
+ const text = held.firstLine() + held.frames;
94
+ settle(text);
95
+ return text;
96
+ },
97
+ };
98
+ const installed = Reflect.defineProperty(err, "stack", {
99
+ get: held.get,
100
+ set: settle,
101
+ enumerable,
102
+ configurable: true,
103
+ });
104
+ if (!installed) {
105
+ settle(firstLine() + frames);
106
+ return undefined;
107
+ }
108
+ return held;
109
+ }
110
+ /** The frames the agent keeps for an error, if it still does. */
111
+ function heldStackOf(err) {
112
+ if (!heldStacks.has(err)) {
113
+ let held;
114
+ try {
115
+ held = holdStack(err);
116
+ }
117
+ catch {
118
+ // A name, message or stack that throws on being read or set: such an
119
+ // error is read as it is, which throws without the agent too.
120
+ held = undefined;
121
+ }
122
+ heldStacks.set(err, held);
123
+ }
124
+ const held = heldStacks.get(err);
125
+ return held !== undefined &&
126
+ Object.getOwnPropertyDescriptor(err, "stack")?.get === held.get
127
+ ? held
128
+ : undefined;
129
+ }
130
+ /**
131
+ * An error's stack as it reads now, for the agent's own use: its first line
132
+ * is still the application's to change.
133
+ */
134
+ export function readStack(err) {
135
+ const held = heldStackOf(err);
136
+ return held === undefined ? err.stack : held.firstLine() + held.frames;
137
+ }
138
+ /**
139
+ * Rewrites the frames of an error's stack, likewise.
140
+ *
141
+ * `rewrite` is given the frames alone where the agent keeps them, and the
142
+ * whole text where the stack is a plain string - so it must only match what
143
+ * follows a line break.
144
+ */
145
+ export function rewriteStackFrames(err, rewrite) {
146
+ const held = heldStackOf(err);
147
+ if (held !== undefined) {
148
+ held.frames = rewrite(held.frames);
149
+ return;
150
+ }
151
+ const stack = err.stack;
152
+ if (typeof stack !== "string") {
153
+ return;
154
+ }
155
+ const rewritten = rewrite(stack);
156
+ if (rewritten === stack) {
157
+ return;
158
+ }
159
+ try {
160
+ err.stack = rewritten;
161
+ }
162
+ catch {
163
+ // Some errors ship a read-only `stack`; what the agent rewrites there is
164
+ // cosmetic, so leaving it as it is beats masking the original failure.
165
+ }
166
+ }
@@ -8,6 +8,17 @@ const HASH_LENGTH = 8;
8
8
  */
9
9
  const fitted = new Map();
10
10
  const MAX_REMEMBERED = 1_000;
11
+ /**
12
+ * Longest value that is remembered, and most of a value that is hashed.
13
+ *
14
+ * A value is as long as whoever named the thing made it - a span or a metric
15
+ * named after a client's string - and a whole read of it, by the hash or as a
16
+ * key of the cache, cost as much as it was long, on every value; the cache
17
+ * then held a thousand of them whole. Past this, the hash covers the head and
18
+ * the length, so values that share a head stay apart unless they also share
19
+ * a length.
20
+ */
21
+ const MAX_READ_LENGTH = 1024;
11
22
  /**
12
23
  * `value`, at most `maxLength` characters long, for a field the collector
13
24
  * bounds. The collector does not cut a longer value down: it refuses the whole
@@ -21,8 +32,9 @@ export function fitToLength(value, maxLength) {
21
32
  if (value.length <= maxLength) {
22
33
  return value;
23
34
  }
24
- const key = `${maxLength}:${value}`;
25
- const remembered = fitted.get(key);
35
+ const remembers = value.length <= MAX_READ_LENGTH;
36
+ const key = remembers ? `${maxLength}:${value}` : undefined;
37
+ const remembered = key === undefined ? undefined : fitted.get(key);
26
38
  if (remembered !== undefined) {
27
39
  return remembered;
28
40
  }
@@ -31,14 +43,25 @@ export function fitToLength(value, maxLength) {
31
43
  if (last >= 0xd800 && last <= 0xdbff) {
32
44
  head -= 1;
33
45
  }
34
- const hash = createHash("sha256")
35
- .update(value)
36
- .digest("hex")
37
- .slice(0, HASH_LENGTH);
38
- const cut = `${value.slice(0, head)}~${hash}`;
39
- if (fitted.size >= MAX_REMEMBERED) {
40
- fitted.clear();
46
+ const hash = createHash("sha256");
47
+ if (remembers) {
48
+ hash.update(value);
49
+ }
50
+ else {
51
+ hash.update(value.slice(0, MAX_READ_LENGTH)).update(`:${value.length}`);
52
+ }
53
+ // Its own copy: a slice keeps the whole of the value it was cut from alive
54
+ // for as long as the cut is held - by the cache, by the batch.
55
+ const cut = copyOf(`${value.slice(0, head)}~${hash.digest("hex").slice(0, HASH_LENGTH)}`);
56
+ if (key !== undefined) {
57
+ if (fitted.size >= MAX_REMEMBERED) {
58
+ fitted.clear();
59
+ }
60
+ fitted.set(key, cut);
41
61
  }
42
- fitted.set(key, cut);
43
62
  return cut;
44
63
  }
64
+ /** A flat string of its own, sharing nothing with what it was built from. */
65
+ function copyOf(text) {
66
+ return JSON.parse(JSON.stringify(text));
67
+ }
@@ -17,8 +17,30 @@ export interface ParsedLogLine {
17
17
  level?: LogLevel;
18
18
  context?: string;
19
19
  message: string;
20
+ /**
21
+ * On a text line whose context was read off a bracket: the bracket and the
22
+ * message as they were written, in one piece. The bracket is only a guess
23
+ * at a context - a line logged without one reads the same when its message
24
+ * opens with `[` - so whoever redacts the two needs them whole.
25
+ */
26
+ unsplit?: string;
20
27
  traceId?: string;
28
+ /**
29
+ * On a text line whose `traceId` was read off its end: that end as it was
30
+ * written, marker and all, which `message` no longer has. The parser cannot
31
+ * tell the logger's suffix from a message that happens to end the same
32
+ * way - in a secret, say - so whoever redacts the message needs it to see
33
+ * the line whole.
34
+ */
35
+ traceIdSuffix?: string;
21
36
  attributes?: Record<string, unknown>;
37
+ /**
38
+ * What the line was read as: a record of a JSON logger, a line carrying
39
+ * Nest's text prefix, or neither. A JSON record is always a whole message;
40
+ * a `plain` line may be the rest of a message whose prefix was on the line
41
+ * above it.
42
+ */
43
+ format: "json" | "nest" | "plain";
22
44
  }
23
45
  export declare function stripAnsi(value: string): string;
24
46
  export declare function parseLogLine(line: string): ParsedLogLine;
@@ -13,12 +13,20 @@
13
13
  * understand is still the log the user is looking for.
14
14
  */
15
15
  /**
16
- * CSI escape sequences - colour codes and cursor moves. Narrower than a
17
- * general-purpose ANSI stripper on purpose: this only has to undo what console
18
- * loggers emit, and a tight pattern cannot eat real log content.
16
+ * CSI escape sequences - colour codes, and the cursor and erase moves a
17
+ * progress bar writes. Narrower than a general-purpose ANSI stripper on
18
+ * purpose: this only has to undo what console loggers emit, and a tight
19
+ * pattern cannot eat real log content.
20
+ *
21
+ * Only well-formed ones, ending in one of those few letters. The pattern this
22
+ * replaced took any run of digits and `;` and any letter behind `ESC [`, and
23
+ * the escape may come from a client: a value ending in `ESC [;` in front of
24
+ * the application's own `Password=x` took the `P` with it, and what was left
25
+ * - `assword=x` - names no credential. It runs before redaction, on error
26
+ * messages and stacks as well as on forwarded lines.
19
27
  */
20
28
  // eslint-disable-next-line no-control-regex
21
- const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
29
+ const ANSI_PATTERN = /\x1B\[(?:\d{1,3}(?:;\d{1,3})*)?[GHJKm]/g;
22
30
  /**
23
31
  * Nest's default ConsoleLogger line:
24
32
  * [Nest] 1234 - 07/29/2026, 10:42:18 AM LOG [AppController] message
@@ -35,7 +43,7 @@ const ANSI_PATTERN = /\x1B\[[0-9;]*[A-Za-z]/g;
35
43
  * The timestamp opens with a non-space, exactly one whitespace character
36
44
  * precedes the level, and nothing after the level can fail.
37
45
  */
38
- const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+\S.*?\s(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(?:\[([^\]]+)\]\s*)?([\s\S]*)$/;
46
+ const NEST_TEXT_PATTERN = /^\[Nest\]\s+\d+\s+-\s+\S.*?\s(FATAL|ERROR|WARN|LOG|DEBUG|VERBOSE)\s+(\[([^\]]+)\]\s*)?([\s\S]*)$/;
39
47
  /**
40
48
  * Marker LoggerPatcherService puts before the trace id it appends when a trace
41
49
  * is in scope. Parsing the id back off recovers it even for lines whose async
@@ -80,7 +88,8 @@ export function stripAnsi(value) {
80
88
  }
81
89
  export function parseLogLine(line) {
82
90
  const clean = stripAnsi(line).trimEnd();
83
- return parseStructured(clean) ?? parseNestText(clean) ?? { message: clean };
91
+ return (parseStructured(clean) ??
92
+ parseNestText(clean) ?? { message: clean, format: "plain" });
84
93
  }
85
94
  function parseStructured(line) {
86
95
  // Cheap guard so the common text case never pays for a thrown parse error.
@@ -114,6 +123,7 @@ function parseStructured(line) {
114
123
  traceId: typeof record.traceId === "string" ? record.traceId : undefined,
115
124
  message: record.message,
116
125
  attributes: Object.keys(attributes).length > 0 ? attributes : undefined,
126
+ format: "json",
117
127
  };
118
128
  }
119
129
  function parseNestText(line) {
@@ -121,13 +131,16 @@ function parseNestText(line) {
121
131
  if (!match) {
122
132
  return null;
123
133
  }
124
- const [, level, context, rest] = match;
134
+ const [, level, bracket, context, rest] = match;
125
135
  const { message, traceId } = splitTraceIdSuffix(rest);
126
136
  return {
127
137
  level: toLogLevel(level),
128
138
  context: context || undefined,
129
139
  traceId,
140
+ traceIdSuffix: traceId === undefined ? undefined : rest.slice(message.length),
130
141
  message,
142
+ unsplit: bracket === undefined ? undefined : bracket + message,
143
+ format: "nest",
131
144
  };
132
145
  }
133
146
  /**
@@ -12,6 +12,12 @@ export declare class LogRedactor {
12
12
  * reach (a URL's query string) is held to the same list.
13
13
  */
14
14
  isSensitiveKey(key: string): boolean;
15
+ /**
16
+ * Colour codes are taken out first. The forwarder strips them off a raw
17
+ * line, but a JSON logger writes the escape as `\u001b`, so they only come
18
+ * back once the line is decoded - and between a key and its value, or in
19
+ * front of a card number, they stop every rule matching.
20
+ */
15
21
  redactMessage(message: string): string;
16
22
  /**
17
23
  * Redacts lines of source code read for a code frame.
@@ -27,4 +33,12 @@ export declare class LogRedactor {
27
33
  private apply;
28
34
  redactAttributes(attributes: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
29
35
  private redactValue;
36
+ /**
37
+ * A key is a name, but not always: a JSON body parsed as a form is one key
38
+ * holding the whole document. Only a key long enough to hold a secret, or
39
+ * holding a pair, is read - the rest are the ordinary names they look like.
40
+ */
41
+ private redactKey;
42
+ /** A card number written as a JSON number: `{"number": 4111111111111111}`. */
43
+ private isCardNumber;
30
44
  }