@sentry/node 8.9.2 → 8.11.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 (68) hide show
  1. package/cjs/index.js +2 -0
  2. package/cjs/index.js.map +1 -1
  3. package/cjs/integrations/anr/index.js +1 -1
  4. package/cjs/integrations/anr/index.js.map +1 -1
  5. package/cjs/integrations/context.js +4 -5
  6. package/cjs/integrations/context.js.map +1 -1
  7. package/cjs/integrations/contextlines.js +334 -69
  8. package/cjs/integrations/contextlines.js.map +1 -1
  9. package/cjs/integrations/local-variables/local-variables-async.js +10 -7
  10. package/cjs/integrations/local-variables/local-variables-async.js.map +1 -1
  11. package/cjs/integrations/local-variables/local-variables-sync.js +9 -5
  12. package/cjs/integrations/local-variables/local-variables-sync.js.map +1 -1
  13. package/cjs/otel/instrument.js +3 -2
  14. package/cjs/otel/instrument.js.map +1 -1
  15. package/cjs/proxy/parse-proxy-response.js +1 -1
  16. package/cjs/proxy/parse-proxy-response.js.map +1 -1
  17. package/cjs/sdk/api.js +83 -13
  18. package/cjs/sdk/api.js.map +1 -1
  19. package/cjs/sdk/index.js +1 -0
  20. package/cjs/sdk/index.js.map +1 -1
  21. package/cjs/sdk/initOtel.js +1 -1
  22. package/cjs/sdk/initOtel.js.map +1 -1
  23. package/cjs/transports/http.js +1 -1
  24. package/cjs/transports/http.js.map +1 -1
  25. package/cjs/utils/redisCache.js +3 -2
  26. package/cjs/utils/redisCache.js.map +1 -1
  27. package/esm/index.js +1 -0
  28. package/esm/index.js.map +1 -1
  29. package/esm/integrations/anr/index.js +1 -1
  30. package/esm/integrations/anr/index.js.map +1 -1
  31. package/esm/integrations/anr/worker-script.js +2 -2
  32. package/esm/integrations/context.js +4 -5
  33. package/esm/integrations/context.js.map +1 -1
  34. package/esm/integrations/contextlines.js +334 -72
  35. package/esm/integrations/contextlines.js.map +1 -1
  36. package/esm/integrations/local-variables/local-variables-async.js +10 -7
  37. package/esm/integrations/local-variables/local-variables-async.js.map +1 -1
  38. package/esm/integrations/local-variables/local-variables-sync.js +9 -5
  39. package/esm/integrations/local-variables/local-variables-sync.js.map +1 -1
  40. package/esm/integrations/local-variables/worker-script.js +2 -2
  41. package/esm/otel/instrument.js +3 -2
  42. package/esm/otel/instrument.js.map +1 -1
  43. package/esm/proxy/parse-proxy-response.js +1 -1
  44. package/esm/proxy/parse-proxy-response.js.map +1 -1
  45. package/esm/sdk/api.js +83 -13
  46. package/esm/sdk/api.js.map +1 -1
  47. package/esm/sdk/index.js +2 -1
  48. package/esm/sdk/index.js.map +1 -1
  49. package/esm/sdk/initOtel.js +1 -1
  50. package/esm/sdk/initOtel.js.map +1 -1
  51. package/esm/transports/http.js +1 -1
  52. package/esm/transports/http.js.map +1 -1
  53. package/esm/utils/redisCache.js +3 -2
  54. package/esm/utils/redisCache.js.map +1 -1
  55. package/package.json +5 -5
  56. package/types/index.d.ts +1 -0
  57. package/types/index.d.ts.map +1 -1
  58. package/types/integrations/context.d.ts.map +1 -1
  59. package/types/integrations/contextlines.d.ts +11 -6
  60. package/types/integrations/contextlines.d.ts.map +1 -1
  61. package/types/integrations/local-variables/local-variables-async.d.ts.map +1 -1
  62. package/types/integrations/local-variables/local-variables-sync.d.ts.map +1 -1
  63. package/types/otel/instrument.d.ts.map +1 -1
  64. package/types/sdk/api.d.ts.map +1 -1
  65. package/types/sdk/index.d.ts.map +1 -1
  66. package/types/utils/redisCache.d.ts.map +1 -1
  67. package/types-ts3.8/index.d.ts +1 -0
  68. package/types-ts3.8/integrations/contextlines.d.ts +11 -6
@@ -1,131 +1,393 @@
1
1
  import { _optionalChain } from '@sentry/utils';
2
- import { promises } from 'node:fs';
2
+ import { createReadStream } from 'node:fs';
3
+ import { createInterface } from 'node:readline';
3
4
  import { defineIntegration } from '@sentry/core';
4
- import { LRUMap, addContextToFrame } from '@sentry/utils';
5
+ import { LRUMap, logger, snipLine } from '@sentry/utils';
6
+ import { DEBUG_BUILD } from '../debug-build.js';
5
7
 
6
- const FILE_CONTENT_CACHE = new LRUMap(100);
8
+ const LRU_FILE_CONTENTS_CACHE = new LRUMap(10);
9
+ const LRU_FILE_CONTENTS_FS_READ_FAILED = new LRUMap(20);
7
10
  const DEFAULT_LINES_OF_CONTEXT = 7;
8
11
  const INTEGRATION_NAME = 'ContextLines';
12
+ // Determines the upper bound of lineno/colno that we will attempt to read. Large colno values are likely to be
13
+ // minified code while large lineno values are likely to be bundled code.
14
+ // Exported for testing purposes.
15
+ const MAX_CONTEXTLINES_COLNO = 1000;
16
+ const MAX_CONTEXTLINES_LINENO = 10000;
9
17
 
10
- const readFileAsync = promises.readFile;
18
+ /**
19
+ * Get or init map value
20
+ */
21
+ function emplace(map, key, contents) {
22
+ const value = map.get(key);
11
23
 
12
- /** Exported only for tests, as a type-safe variant. */
13
- const _contextLinesIntegration = ((options = {}) => {
14
- const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
24
+ if (value === undefined) {
25
+ map.set(key, contents);
26
+ return contents;
27
+ }
15
28
 
16
- return {
17
- name: INTEGRATION_NAME,
18
- processEvent(event) {
19
- return addSourceContext(event, contextLines);
20
- },
21
- };
22
- }) ;
29
+ return value;
30
+ }
23
31
 
24
32
  /**
25
- * Capture the lines before and after the frame's context.
33
+ * Determines if context lines should be skipped for a file.
34
+ * - .min.(mjs|cjs|js) files are and not useful since they dont point to the original source
35
+ * - node: prefixed modules are part of the runtime and cannot be resolved to a file
36
+ * - data: skip json, wasm and inline js https://nodejs.org/api/esm.html#data-imports
26
37
  */
27
- const contextLinesIntegration = defineIntegration(_contextLinesIntegration);
38
+ function shouldSkipContextLinesForFile(path) {
39
+ // Test the most common prefix and extension first. These are the ones we
40
+ // are most likely to see in user applications and are the ones we can break out of first.
41
+ if (path.startsWith('node:')) return true;
42
+ if (path.endsWith('.min.js')) return true;
43
+ if (path.endsWith('.min.cjs')) return true;
44
+ if (path.endsWith('.min.mjs')) return true;
45
+ if (path.startsWith('data:')) return true;
46
+ return false;
47
+ }
48
+
49
+ /**
50
+ * Determines if we should skip contextlines based off the max lineno and colno values.
51
+ */
52
+ function shouldSkipContextLinesForFrame(frame) {
53
+ if (frame.lineno !== undefined && frame.lineno > MAX_CONTEXTLINES_LINENO) return true;
54
+ if (frame.colno !== undefined && frame.colno > MAX_CONTEXTLINES_COLNO) return true;
55
+ return false;
56
+ }
57
+ /**
58
+ * Checks if we have all the contents that we need in the cache.
59
+ */
60
+ function rangeExistsInContentCache(file, range) {
61
+ const contents = LRU_FILE_CONTENTS_CACHE.get(file);
62
+ if (contents === undefined) return false;
63
+
64
+ for (let i = range[0]; i <= range[1]; i++) {
65
+ if (contents[i] === undefined) {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ return true;
71
+ }
72
+
73
+ /**
74
+ * Creates contiguous ranges of lines to read from a file. In the case where context lines overlap,
75
+ * the ranges are merged to create a single range.
76
+ */
77
+ function makeLineReaderRanges(lines, linecontext) {
78
+ if (!lines.length) {
79
+ return [];
80
+ }
81
+
82
+ let i = 0;
83
+ const line = lines[0];
84
+
85
+ if (typeof line !== 'number') {
86
+ return [];
87
+ }
88
+
89
+ let current = makeContextRange(line, linecontext);
90
+ const out = [];
91
+ // eslint-disable-next-line no-constant-condition
92
+ while (true) {
93
+ if (i === lines.length - 1) {
94
+ out.push(current);
95
+ break;
96
+ }
97
+
98
+ // If the next line falls into the current range, extend the current range to lineno + linecontext.
99
+ const next = lines[i + 1];
100
+ if (typeof next !== 'number') {
101
+ break;
102
+ }
103
+ if (next <= current[1]) {
104
+ current[1] = next + linecontext;
105
+ } else {
106
+ out.push(current);
107
+ current = makeContextRange(next, linecontext);
108
+ }
109
+
110
+ i++;
111
+ }
112
+
113
+ return out;
114
+ }
115
+
116
+ /**
117
+ * Extracts lines from a file and stores them in a cache.
118
+ */
119
+ function getContextLinesFromFile(path, ranges, output) {
120
+ return new Promise((resolve, _reject) => {
121
+ // It is important *not* to have any async code between createInterface and the 'line' event listener
122
+ // as it will cause the 'line' event to
123
+ // be emitted before the listener is attached.
124
+ const stream = createReadStream(path);
125
+ const lineReaded = createInterface({
126
+ input: stream,
127
+ });
128
+
129
+ // Init at zero and increment at the start of the loop because lines are 1 indexed.
130
+ let lineNumber = 0;
131
+ let currentRangeIndex = 0;
132
+ const range = ranges[currentRangeIndex];
133
+ if (range === undefined) {
134
+ // We should never reach this point, but if we do, we should resolve the promise to prevent it from hanging.
135
+ resolve();
136
+ return;
137
+ }
138
+ let rangeStart = range[0];
139
+ let rangeEnd = range[1];
140
+
141
+ // We use this inside Promise.all, so we need to resolve the promise even if there is an error
142
+ // to prevent Promise.all from short circuiting the rest.
143
+ function onStreamError(e) {
144
+ // Mark file path as failed to read and prevent multiple read attempts.
145
+ LRU_FILE_CONTENTS_FS_READ_FAILED.set(path, 1);
146
+ DEBUG_BUILD && logger.error(`Failed to read file: ${path}. Error: ${e}`);
147
+ lineReaded.close();
148
+ lineReaded.removeAllListeners();
149
+ resolve();
150
+ }
151
+
152
+ // We need to handle the error event to prevent the process from crashing in < Node 16
153
+ // https://github.com/nodejs/node/pull/31603
154
+ stream.on('error', onStreamError);
155
+ lineReaded.on('error', onStreamError);
156
+ lineReaded.on('close', resolve);
157
+
158
+ lineReaded.on('line', line => {
159
+ lineNumber++;
160
+ if (lineNumber < rangeStart) return;
28
161
 
162
+ // !Warning: This mutates the cache by storing the snipped line into the cache.
163
+ output[lineNumber] = snipLine(line, 0);
164
+
165
+ if (lineNumber >= rangeEnd) {
166
+ if (currentRangeIndex === ranges.length - 1) {
167
+ // We need to close the file stream and remove listeners, else the reader will continue to run our listener;
168
+ lineReaded.close();
169
+ lineReaded.removeAllListeners();
170
+ return;
171
+ }
172
+ currentRangeIndex++;
173
+ const range = ranges[currentRangeIndex];
174
+ if (range === undefined) {
175
+ // This should never happen as it means we have a bug in the context.
176
+ lineReaded.close();
177
+ lineReaded.removeAllListeners();
178
+ return;
179
+ }
180
+ rangeStart = range[0];
181
+ rangeEnd = range[1];
182
+ }
183
+ });
184
+ });
185
+ }
186
+
187
+ /**
188
+ * Adds surrounding (context) lines of the line that an exception occurred on to the event.
189
+ * This is done by reading the file line by line and extracting the lines. The extracted lines are stored in
190
+ * a cache to prevent multiple reads of the same file. Failures to read a file are similarly cached to prevent multiple
191
+ * failing reads from happening.
192
+ */
193
+ /* eslint-disable complexity */
29
194
  async function addSourceContext(event, contextLines) {
30
195
  // keep a lookup map of which files we've already enqueued to read,
31
196
  // so we don't enqueue the same file multiple times which would cause multiple i/o reads
32
- const enqueuedReadSourceFileTasks = {};
33
- const readSourceFileTasks = [];
197
+ const filesToLines = {};
34
198
 
35
- if (contextLines > 0 && _optionalChain([event, 'access', _2 => _2.exception, 'optionalAccess', _3 => _3.values])) {
199
+ if (contextLines > 0 && _optionalChain([event, 'access', _ => _.exception, 'optionalAccess', _2 => _2.values])) {
36
200
  for (const exception of event.exception.values) {
37
- if (!_optionalChain([exception, 'access', _4 => _4.stacktrace, 'optionalAccess', _5 => _5.frames])) {
201
+ if (!_optionalChain([exception, 'access', _3 => _3.stacktrace, 'optionalAccess', _4 => _4.frames, 'optionalAccess', _5 => _5.length])) {
38
202
  continue;
39
203
  }
40
204
 
41
- // We want to iterate in reverse order as calling cache.get will bump the file in our LRU cache.
42
- // This ends up prioritizes source context for frames at the top of the stack instead of the bottom.
205
+ // Maps preserve insertion order, so we iterate in reverse, starting at the
206
+ // outermost frame and closer to where the exception has occurred (poor mans priority)
43
207
  for (let i = exception.stacktrace.frames.length - 1; i >= 0; i--) {
44
208
  const frame = exception.stacktrace.frames[i];
45
- // Call cache.get to bump the file to the top of the cache and ensure we have not already
46
- // enqueued a read operation for this filename
47
- if (frame.filename && !enqueuedReadSourceFileTasks[frame.filename] && !FILE_CONTENT_CACHE.get(frame.filename)) {
48
- readSourceFileTasks.push(_readSourceFile(frame.filename));
49
- enqueuedReadSourceFileTasks[frame.filename] = 1;
209
+ const filename = _optionalChain([frame, 'optionalAccess', _6 => _6.filename]);
210
+
211
+ if (
212
+ !frame ||
213
+ typeof filename !== 'string' ||
214
+ typeof frame.lineno !== 'number' ||
215
+ shouldSkipContextLinesForFile(filename) ||
216
+ shouldSkipContextLinesForFrame(frame)
217
+ ) {
218
+ continue;
50
219
  }
220
+
221
+ const filesToLinesOutput = filesToLines[filename];
222
+ if (!filesToLinesOutput) filesToLines[filename] = [];
223
+ // @ts-expect-error this is defined above
224
+ filesToLines[filename].push(frame.lineno);
51
225
  }
52
226
  }
53
227
  }
54
228
 
55
- // check if files to read > 0, if so, await all of them to be read before adding source contexts.
56
- // Normally, Promise.all here could be short circuited if one of the promises rejects, but we
57
- // are guarding from that by wrapping the i/o read operation in a try/catch.
58
- if (readSourceFileTasks.length > 0) {
59
- await Promise.all(readSourceFileTasks);
229
+ const files = Object.keys(filesToLines);
230
+ if (files.length == 0) {
231
+ return event;
232
+ }
233
+
234
+ const readlinePromises = [];
235
+ for (const file of files) {
236
+ // If we failed to read this before, dont try reading it again.
237
+ if (LRU_FILE_CONTENTS_FS_READ_FAILED.get(file)) {
238
+ continue;
239
+ }
240
+
241
+ const filesToLineRanges = filesToLines[file];
242
+ if (!filesToLineRanges) {
243
+ continue;
244
+ }
245
+
246
+ // Sort ranges so that they are sorted by line increasing order and match how the file is read.
247
+ filesToLineRanges.sort((a, b) => a - b);
248
+ // Check if the contents are already in the cache and if we can avoid reading the file again.
249
+ const ranges = makeLineReaderRanges(filesToLineRanges, contextLines);
250
+ if (ranges.every(r => rangeExistsInContentCache(file, r))) {
251
+ continue;
252
+ }
253
+
254
+ const cache = emplace(LRU_FILE_CONTENTS_CACHE, file, {});
255
+ readlinePromises.push(getContextLinesFromFile(file, ranges, cache));
60
256
  }
61
257
 
258
+ // The promise rejections are caught in order to prevent them from short circuiting Promise.all
259
+ await Promise.all(readlinePromises).catch(() => {
260
+ DEBUG_BUILD && logger.log('Failed to read one or more source files and resolve context lines');
261
+ });
262
+
62
263
  // Perform the same loop as above, but this time we can assume all files are in the cache
63
264
  // and attempt to add source context to frames.
64
- if (contextLines > 0 && _optionalChain([event, 'access', _6 => _6.exception, 'optionalAccess', _7 => _7.values])) {
265
+ if (contextLines > 0 && _optionalChain([event, 'access', _7 => _7.exception, 'optionalAccess', _8 => _8.values])) {
65
266
  for (const exception of event.exception.values) {
66
- if (exception.stacktrace && exception.stacktrace.frames) {
67
- await addSourceContextToFrames(exception.stacktrace.frames, contextLines);
267
+ if (exception.stacktrace && exception.stacktrace.frames && exception.stacktrace.frames.length > 0) {
268
+ addSourceContextToFrames(exception.stacktrace.frames, contextLines, LRU_FILE_CONTENTS_CACHE);
68
269
  }
69
270
  }
70
271
  }
71
272
 
72
273
  return event;
73
274
  }
275
+ /* eslint-enable complexity */
74
276
 
75
277
  /** Adds context lines to frames */
76
- function addSourceContextToFrames(frames, contextLines) {
278
+ function addSourceContextToFrames(
279
+ frames,
280
+ contextLines,
281
+ cache,
282
+ ) {
77
283
  for (const frame of frames) {
78
284
  // Only add context if we have a filename and it hasn't already been added
79
- if (frame.filename && frame.context_line === undefined) {
80
- const sourceFileLines = FILE_CONTENT_CACHE.get(frame.filename);
81
-
82
- if (sourceFileLines) {
83
- try {
84
- addContextToFrame(sourceFileLines, frame, contextLines);
85
- } catch (e) {
86
- // anomaly, being defensive in case
87
- // unlikely to ever happen in practice but can definitely happen in theory
88
- }
285
+ if (frame.filename && frame.context_line === undefined && typeof frame.lineno === 'number') {
286
+ const contents = cache.get(frame.filename);
287
+ if (contents === undefined) {
288
+ continue;
89
289
  }
290
+
291
+ addContextToFrame(frame.lineno, frame, contextLines, contents);
90
292
  }
91
293
  }
92
294
  }
93
295
 
94
296
  /**
95
- * Reads file contents and caches them in a global LRU cache.
96
- * If reading fails, mark the file as null in the cache so we don't try again.
97
- *
98
- * @param filename filepath to read content from.
297
+ * Clears the context lines from a frame, used to reset a frame to its original state
298
+ * if we fail to resolve all context lines for it.
299
+ */
300
+ function clearLineContext(frame) {
301
+ delete frame.pre_context;
302
+ delete frame.context_line;
303
+ delete frame.post_context;
304
+ }
305
+
306
+ /**
307
+ * Resolves context lines before and after the given line number and appends them to the frame;
99
308
  */
100
- async function _readSourceFile(filename) {
101
- const cachedFile = FILE_CONTENT_CACHE.get(filename);
309
+ function addContextToFrame(
310
+ lineno,
311
+ frame,
312
+ contextLines,
313
+ contents,
314
+ ) {
315
+ // When there is no line number in the frame, attaching context is nonsensical and will even break grouping.
316
+ // We already check for lineno before calling this, but since StackFrame lineno ism optional, we check it again.
317
+ if (frame.lineno === undefined || contents === undefined) {
318
+ DEBUG_BUILD && logger.error('Cannot resolve context for frame with no lineno or file contents');
319
+ return;
320
+ }
321
+
322
+ frame.pre_context = [];
323
+ for (let i = makeRangeStart(lineno, contextLines); i < lineno; i++) {
324
+ // We always expect the start context as line numbers cannot be negative. If we dont find a line, then
325
+ // something went wrong somewhere. Clear the context and return without adding any linecontext.
326
+ const line = contents[i];
327
+ if (line === undefined) {
328
+ clearLineContext(frame);
329
+ DEBUG_BUILD && logger.error(`Could not find line ${i} in file ${frame.filename}`);
330
+ return;
331
+ }
102
332
 
103
- // We have already attempted to read this file and failed, do not try again
104
- if (cachedFile === null) {
105
- return null;
333
+ frame.pre_context.push(line);
106
334
  }
107
335
 
108
- // We have a cache hit, return it
109
- if (cachedFile !== undefined) {
110
- return cachedFile;
336
+ // We should always have the context line. If we dont, something went wrong, so we clear the context and return
337
+ // without adding any linecontext.
338
+ if (contents[lineno] === undefined) {
339
+ clearLineContext(frame);
340
+ DEBUG_BUILD && logger.error(`Could not find line ${lineno} in file ${frame.filename}`);
341
+ return;
111
342
  }
112
343
 
113
- // Guard from throwing if readFile fails, this enables us to use Promise.all and
114
- // not have it short circuiting if one of the promises rejects + since context lines are added
115
- // on a best effort basis, we want to throw here anyways.
116
-
117
- // If we made it to here, it means that our file is not cache nor marked as failed, so attempt to read it
118
- let content = null;
119
- try {
120
- const rawFileContents = await readFileAsync(filename, 'utf-8');
121
- content = rawFileContents.split('\n');
122
- } catch (_) {
123
- // if we fail, we will mark the file as null in the cache and short circuit next time we try to read it
344
+ frame.context_line = contents[lineno];
345
+
346
+ const end = makeRangeEnd(lineno, contextLines);
347
+ frame.post_context = [];
348
+ for (let i = lineno + 1; i <= end; i++) {
349
+ // Since we dont track when the file ends, we cant clear the context if we dont find a line as it could
350
+ // just be that we reached the end of the file.
351
+ const line = contents[i];
352
+ if (line === undefined) {
353
+ break;
354
+ }
355
+ frame.post_context.push(line);
124
356
  }
357
+ }
358
+
359
+ // Helper functions for generating line context ranges. They take a line number and the number of lines of context to
360
+ // include before and after the line and generate an inclusive range of indices.
125
361
 
126
- FILE_CONTENT_CACHE.set(filename, content);
127
- return content;
362
+ // Compute inclusive end context range
363
+ function makeRangeStart(line, linecontext) {
364
+ return Math.max(1, line - linecontext);
128
365
  }
366
+ // Compute inclusive start context range
367
+ function makeRangeEnd(line, linecontext) {
368
+ return line + linecontext;
369
+ }
370
+ // Determine start and end indices for context range (inclusive);
371
+ function makeContextRange(line, linecontext) {
372
+ return [makeRangeStart(line, linecontext), makeRangeEnd(line, linecontext)];
373
+ }
374
+
375
+ /** Exported only for tests, as a type-safe variant. */
376
+ const _contextLinesIntegration = ((options = {}) => {
377
+ const contextLines = options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT;
378
+
379
+ return {
380
+ name: INTEGRATION_NAME,
381
+ processEvent(event) {
382
+ return addSourceContext(event, contextLines);
383
+ },
384
+ };
385
+ }) ;
386
+
387
+ /**
388
+ * Capture the lines before and after the frame's context.
389
+ */
390
+ const contextLinesIntegration = defineIntegration(_contextLinesIntegration);
129
391
 
130
- export { _contextLinesIntegration, contextLinesIntegration };
392
+ export { MAX_CONTEXTLINES_COLNO, MAX_CONTEXTLINES_LINENO, _contextLinesIntegration, addContextToFrame, contextLinesIntegration };
131
393
  //# sourceMappingURL=contextlines.js.map