@crawlee/basic 4.0.0-beta.170 → 4.0.0-beta.172
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.
- package/index.d.ts +10 -0
- package/index.js +10 -0
- package/internals/autoscaling/autoscaled_pool.d.ts +196 -0
- package/internals/autoscaling/autoscaled_pool.js +385 -0
- package/internals/autoscaling/concurrency_system.d.ts +267 -0
- package/internals/autoscaling/concurrency_system.js +364 -0
- package/internals/autoscaling/cpu_load_signal.d.ts +43 -0
- package/internals/autoscaling/cpu_load_signal.js +46 -0
- package/internals/autoscaling/event_loop_load_signal.d.ts +51 -0
- package/internals/autoscaling/event_loop_load_signal.js +60 -0
- package/internals/autoscaling/index.d.ts +9 -0
- package/internals/autoscaling/index.js +9 -0
- package/internals/autoscaling/load_signal.d.ts +98 -0
- package/internals/autoscaling/load_signal.js +103 -0
- package/internals/autoscaling/memory_load_signal.d.ts +47 -0
- package/internals/autoscaling/memory_load_signal.js +104 -0
- package/internals/autoscaling/snapshotter.d.ts +84 -0
- package/internals/autoscaling/snapshotter.js +67 -0
- package/internals/autoscaling/storage_backend_load_signal.d.ts +56 -0
- package/internals/autoscaling/storage_backend_load_signal.js +73 -0
- package/internals/autoscaling/system_status.d.ts +122 -0
- package/internals/autoscaling/system_status.js +139 -0
- package/internals/autoscaling/weighted_avg.d.ts +5 -0
- package/internals/autoscaling/weighted_avg.js +14 -0
- package/internals/basic-crawler.d.ts +11 -2
- package/internals/basic-crawler.js +13 -1
- package/internals/cookie_utils.d.ts +44 -0
- package/internals/cookie_utils.js +122 -0
- package/internals/crawler-run.d.ts +3 -1
- package/internals/crawler-run.js +1 -1
- package/internals/crawlers/context_pipeline.d.ts +70 -0
- package/internals/crawlers/context_pipeline.js +122 -0
- package/internals/crawlers/crawler_commons.d.ts +193 -0
- package/internals/crawlers/crawler_commons.js +1 -0
- package/internals/crawlers/error_snapshotter.d.ts +57 -0
- package/internals/crawlers/error_snapshotter.js +117 -0
- package/internals/crawlers/error_tracker.d.ts +54 -0
- package/internals/crawlers/error_tracker.js +308 -0
- package/internals/crawlers/index.d.ts +5 -0
- package/internals/crawlers/index.js +4 -0
- package/internals/crawlers/internals/types.d.ts +7 -0
- package/internals/crawlers/internals/types.js +1 -0
- package/internals/crawlers/statistics.d.ts +318 -0
- package/internals/crawlers/statistics.js +525 -0
- package/internals/enqueue_links/enqueue_links.d.ts +152 -0
- package/internals/enqueue_links/enqueue_links.js +76 -0
- package/internals/enqueue_links/index.d.ts +2 -0
- package/internals/enqueue_links/index.js +2 -0
- package/internals/enqueue_links/shared.d.ts +98 -0
- package/internals/enqueue_links/shared.js +259 -0
- package/internals/errors.d.ts +58 -0
- package/internals/errors.js +72 -0
- package/internals/http.d.ts +9 -0
- package/internals/http.js +28 -0
- package/internals/router.d.ts +306 -0
- package/internals/router.js +310 -0
- package/internals/session_pool/consts.d.ts +3 -0
- package/internals/session_pool/consts.js +3 -0
- package/internals/session_pool/errors.d.ts +7 -0
- package/internals/session_pool/errors.js +11 -0
- package/internals/session_pool/fingerprint.d.ts +9 -0
- package/internals/session_pool/fingerprint.js +30 -0
- package/internals/session_pool/index.d.ts +4 -0
- package/internals/session_pool/index.js +4 -0
- package/internals/session_pool/session.d.ts +153 -0
- package/internals/session_pool/session.js +221 -0
- package/internals/session_pool/session_pool.d.ts +242 -0
- package/internals/session_pool/session_pool.js +429 -0
- package/internals/sitemap_request_loader.d.ts +196 -0
- package/internals/sitemap_request_loader.js +432 -0
- package/internals/throttling_request_manager.d.ts +217 -0
- package/internals/throttling_request_manager.js +829 -0
- package/package.json +11 -7
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* ErrorSnapshotter class is used to capture a screenshot of the page and a snapshot of the HTML when an error occurs during web crawling.
|
|
4
|
+
*
|
|
5
|
+
* This functionality is opt-in, and can be enabled via the crawler options:
|
|
6
|
+
*
|
|
7
|
+
* ```ts
|
|
8
|
+
* const crawler = new BasicCrawler({
|
|
9
|
+
* // ...
|
|
10
|
+
* statistics: new Statistics({ saveErrorSnapshots: true }),
|
|
11
|
+
* });
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export class ErrorSnapshotter {
|
|
15
|
+
static MAX_ERROR_CHARACTERS = 30;
|
|
16
|
+
static MAX_HASH_LENGTH = 30;
|
|
17
|
+
static MAX_FILENAME_LENGTH = 250;
|
|
18
|
+
static BASE_MESSAGE = 'An error occurred';
|
|
19
|
+
static SNAPSHOT_PREFIX = 'ERROR_SNAPSHOT';
|
|
20
|
+
/**
|
|
21
|
+
* Capture a snapshot of the error context.
|
|
22
|
+
*/
|
|
23
|
+
async captureSnapshot(error, context) {
|
|
24
|
+
try {
|
|
25
|
+
const page = context?.page;
|
|
26
|
+
const body = context?.body;
|
|
27
|
+
const keyValueStore = await context?.getKeyValueStore();
|
|
28
|
+
// If the key-value store is not available, or the body and page are not available, return empty filenames
|
|
29
|
+
if (!keyValueStore || (!body && !page)) {
|
|
30
|
+
return {};
|
|
31
|
+
}
|
|
32
|
+
const fileName = this.generateFilename(error);
|
|
33
|
+
let screenshotFileName;
|
|
34
|
+
let htmlFileName;
|
|
35
|
+
if (page) {
|
|
36
|
+
const capturedFiles = await this.contextCaptureSnapshot(context, fileName);
|
|
37
|
+
if (capturedFiles) {
|
|
38
|
+
screenshotFileName = capturedFiles.screenshotFileName;
|
|
39
|
+
htmlFileName = capturedFiles.htmlFileName;
|
|
40
|
+
}
|
|
41
|
+
// If the snapshot for browsers failed to capture the HTML, try to capture it from the page content
|
|
42
|
+
if (!htmlFileName) {
|
|
43
|
+
const html = await page.content();
|
|
44
|
+
htmlFileName = html ? await this.saveHTMLSnapshot(html, keyValueStore, fileName) : undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
else if (typeof body === 'string') {
|
|
48
|
+
// for non-browser contexts
|
|
49
|
+
htmlFileName = await this.saveHTMLSnapshot(body, keyValueStore, fileName);
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
screenshotFileName,
|
|
53
|
+
screenshotFileUrl: screenshotFileName && (await keyValueStore.getPublicUrl(screenshotFileName)),
|
|
54
|
+
htmlFileName,
|
|
55
|
+
htmlFileUrl: htmlFileName && (await keyValueStore.getPublicUrl(htmlFileName)),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return {};
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Captures a snapshot of the current page using the context.saveSnapshot function.
|
|
64
|
+
* This function is applicable for browser contexts only.
|
|
65
|
+
* Returns an object containing the filenames of the screenshot and HTML file.
|
|
66
|
+
*/
|
|
67
|
+
async contextCaptureSnapshot(context, fileName) {
|
|
68
|
+
try {
|
|
69
|
+
await context.saveSnapshot({ key: fileName });
|
|
70
|
+
return {
|
|
71
|
+
screenshotFileName: `${fileName}.jpg`,
|
|
72
|
+
htmlFileName: `${fileName}.html`,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Save the HTML snapshot of the page, and return the key it was stored under.
|
|
81
|
+
*/
|
|
82
|
+
async saveHTMLSnapshot(html, keyValueStore, fileName) {
|
|
83
|
+
try {
|
|
84
|
+
await keyValueStore.setValue(fileName, html, { contentType: 'text/html' });
|
|
85
|
+
// The record key is `fileName` - returning it with an `.html` suffix (as v3 did,
|
|
86
|
+
// where local storage put the extension in the key) would break `getPublicUrl`.
|
|
87
|
+
return fileName;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Generate a unique fileName for each error snapshot.
|
|
95
|
+
*/
|
|
96
|
+
generateFilename(error) {
|
|
97
|
+
const { SNAPSHOT_PREFIX, BASE_MESSAGE, MAX_HASH_LENGTH, MAX_ERROR_CHARACTERS, MAX_FILENAME_LENGTH } = ErrorSnapshotter;
|
|
98
|
+
// Create a hash of the error stack trace
|
|
99
|
+
const errorStackHash = crypto
|
|
100
|
+
.createHash('sha1')
|
|
101
|
+
.update(error.stack || error.message || '')
|
|
102
|
+
.digest('hex')
|
|
103
|
+
.slice(0, MAX_HASH_LENGTH);
|
|
104
|
+
const errorMessagePrefix = (error.message || BASE_MESSAGE).slice(0, MAX_ERROR_CHARACTERS).trim();
|
|
105
|
+
/**
|
|
106
|
+
* Remove non-word characters from the start and end of a string.
|
|
107
|
+
*/
|
|
108
|
+
const sanitizeString = (str) => {
|
|
109
|
+
return str.replace(/^\W+|\W+$/g, '');
|
|
110
|
+
};
|
|
111
|
+
// Generate fileName and remove disallowed characters
|
|
112
|
+
const fileName = `${SNAPSHOT_PREFIX}_${sanitizeString(errorStackHash)}_${sanitizeString(errorMessagePrefix)}`
|
|
113
|
+
.replace(/\W+/g, '-') // Replace non-word characters with a dash
|
|
114
|
+
.slice(0, MAX_FILENAME_LENGTH);
|
|
115
|
+
return fileName;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { CrawlingContext } from '../crawlers/crawler_commons.js';
|
|
2
|
+
import { ErrorSnapshotter } from './error_snapshotter.js';
|
|
3
|
+
import type { SnapshottableProperties } from './internals/types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Node.js Error interface
|
|
6
|
+
*/
|
|
7
|
+
export interface ErrnoException extends Error {
|
|
8
|
+
errno?: number;
|
|
9
|
+
code?: string | number;
|
|
10
|
+
path?: string;
|
|
11
|
+
syscall?: string;
|
|
12
|
+
cause?: any;
|
|
13
|
+
}
|
|
14
|
+
export interface ErrorTrackerOptions {
|
|
15
|
+
showErrorCode: boolean;
|
|
16
|
+
showErrorName: boolean;
|
|
17
|
+
showStackTrace: boolean;
|
|
18
|
+
showFullStack: boolean;
|
|
19
|
+
showErrorMessage: boolean;
|
|
20
|
+
showFullMessage: boolean;
|
|
21
|
+
saveErrorSnapshots: boolean;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* This class tracks errors and computes a summary of information like:
|
|
25
|
+
* - where the errors happened
|
|
26
|
+
* - what the error names are
|
|
27
|
+
* - what the error codes are
|
|
28
|
+
* - what is the general error message
|
|
29
|
+
*
|
|
30
|
+
* This is extremely useful when there are dynamic error messages, such as argument validation.
|
|
31
|
+
*
|
|
32
|
+
* Since the structure of the `tracker.result` object differs when using different options,
|
|
33
|
+
* it's typed as `Record<string, unknown>`. The most deep object has a `count` property, which is a number.
|
|
34
|
+
*
|
|
35
|
+
* It's possible to get the total amount of errors via the `tracker.total` property.
|
|
36
|
+
*/
|
|
37
|
+
export declare class ErrorTracker {
|
|
38
|
+
#private;
|
|
39
|
+
result: Record<string, unknown>;
|
|
40
|
+
total: number;
|
|
41
|
+
errorSnapshotter?: ErrorSnapshotter;
|
|
42
|
+
constructor(options?: Partial<ErrorTrackerOptions>);
|
|
43
|
+
private updateGroup;
|
|
44
|
+
add(error: ErrnoException): void;
|
|
45
|
+
/**
|
|
46
|
+
* This method is async, because it captures a snapshot of the error context.
|
|
47
|
+
* We added this new method to avoid breaking changes.
|
|
48
|
+
*/
|
|
49
|
+
addAsync(error: ErrnoException, context?: CrawlingContext): Promise<void>;
|
|
50
|
+
getUniqueErrorCount(): number;
|
|
51
|
+
getMostPopularErrors(count: number): [number, string[]][];
|
|
52
|
+
captureSnapshot(storage: Record<string, unknown>, error: ErrnoException, context: CrawlingContext & SnapshottableProperties): Promise<void>;
|
|
53
|
+
reset(): void;
|
|
54
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { inspect } from 'node:util';
|
|
2
|
+
import { ErrorSnapshotter } from './error_snapshotter.js';
|
|
3
|
+
const extractPathFromStackTraceLine = (line) => {
|
|
4
|
+
const lastStartingRoundBracketIndex = line.lastIndexOf('(');
|
|
5
|
+
if (lastStartingRoundBracketIndex !== -1) {
|
|
6
|
+
const closingRoundBracketIndex = line.indexOf(')', lastStartingRoundBracketIndex);
|
|
7
|
+
if (closingRoundBracketIndex !== -1) {
|
|
8
|
+
return line.slice(lastStartingRoundBracketIndex + 1, closingRoundBracketIndex);
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return line;
|
|
12
|
+
};
|
|
13
|
+
// https://v8.dev/docs/stack-trace-api#appendix%3A-stack-trace-format
|
|
14
|
+
const getPathFromStackTrace = (stack) => {
|
|
15
|
+
for (const line of stack) {
|
|
16
|
+
const path = extractPathFromStackTraceLine(line);
|
|
17
|
+
if (path.startsWith('node:') || path.includes('/node_modules/') || path.includes('\\node_modules\\')) {
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
return path;
|
|
21
|
+
}
|
|
22
|
+
return extractPathFromStackTraceLine(stack[0]);
|
|
23
|
+
};
|
|
24
|
+
const getStackTraceGroup = (error, storage, showFullStack) => {
|
|
25
|
+
const stack = error.stack?.split('\n').map((line) => line.trim());
|
|
26
|
+
let sliceAt = -1;
|
|
27
|
+
if (stack) {
|
|
28
|
+
for (let i = 0; i < stack.length; i++) {
|
|
29
|
+
if (stack[i].startsWith('at ') || stack[i].startsWith('eval at ')) {
|
|
30
|
+
sliceAt = i;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
let normalizedStackTrace = null;
|
|
36
|
+
if (sliceAt !== -1) {
|
|
37
|
+
normalizedStackTrace = showFullStack
|
|
38
|
+
? stack
|
|
39
|
+
.slice(sliceAt)
|
|
40
|
+
.map((x) => x.trim())
|
|
41
|
+
.join('\n')
|
|
42
|
+
: getPathFromStackTrace(stack.slice(sliceAt));
|
|
43
|
+
}
|
|
44
|
+
if (!normalizedStackTrace) {
|
|
45
|
+
normalizedStackTrace = 'missing stack trace';
|
|
46
|
+
}
|
|
47
|
+
if (!(normalizedStackTrace in storage)) {
|
|
48
|
+
storage[normalizedStackTrace] = Object.create(null);
|
|
49
|
+
}
|
|
50
|
+
return storage[normalizedStackTrace];
|
|
51
|
+
};
|
|
52
|
+
const getErrorCodeGroup = (error, storage) => {
|
|
53
|
+
let { code } = error;
|
|
54
|
+
if (code === undefined) {
|
|
55
|
+
code = 'missing error code';
|
|
56
|
+
}
|
|
57
|
+
if (!(code in storage)) {
|
|
58
|
+
storage[code] = Object.create(null);
|
|
59
|
+
}
|
|
60
|
+
return storage[String(code)];
|
|
61
|
+
};
|
|
62
|
+
const getErrorNameGroup = (error, storage) => {
|
|
63
|
+
const { name } = error;
|
|
64
|
+
if (!(name in storage)) {
|
|
65
|
+
storage[name] = Object.create(null);
|
|
66
|
+
}
|
|
67
|
+
return storage[name];
|
|
68
|
+
};
|
|
69
|
+
const findBiggestWordIntersection = (a, b) => {
|
|
70
|
+
let maxStreak = 0;
|
|
71
|
+
let bStreakIndex = -1;
|
|
72
|
+
let aStreakIndex = -1;
|
|
73
|
+
for (let aIndex = 0; aIndex < a.length; aIndex++) {
|
|
74
|
+
let bIndex = -1;
|
|
75
|
+
do {
|
|
76
|
+
let aWalkIndex = aIndex;
|
|
77
|
+
bIndex = b.indexOf(a[aIndex], bIndex + 1);
|
|
78
|
+
let bWalkIndex = bIndex;
|
|
79
|
+
let streak = 0;
|
|
80
|
+
while (aWalkIndex < a.length && bWalkIndex < b.length && b[bWalkIndex++] === a[aWalkIndex++]) {
|
|
81
|
+
streak++;
|
|
82
|
+
}
|
|
83
|
+
if (streak > maxStreak) {
|
|
84
|
+
maxStreak = streak;
|
|
85
|
+
aStreakIndex = aIndex;
|
|
86
|
+
bStreakIndex = bIndex;
|
|
87
|
+
}
|
|
88
|
+
} while (bIndex !== -1);
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
maxStreak,
|
|
92
|
+
aStreakIndex,
|
|
93
|
+
bStreakIndex,
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
const arrayCount = (array, target) => {
|
|
97
|
+
let result = 0;
|
|
98
|
+
for (const item of array) {
|
|
99
|
+
if (item === target) {
|
|
100
|
+
result++;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return result;
|
|
104
|
+
};
|
|
105
|
+
const calculatePlaceholder = (a, b) => {
|
|
106
|
+
const { maxStreak, aStreakIndex, bStreakIndex } = findBiggestWordIntersection(a, b);
|
|
107
|
+
if (maxStreak === 0) {
|
|
108
|
+
return ['_'];
|
|
109
|
+
}
|
|
110
|
+
const leftA = a.slice(0, aStreakIndex);
|
|
111
|
+
const leftB = b.slice(0, bStreakIndex);
|
|
112
|
+
const rightA = a.slice(aStreakIndex + maxStreak);
|
|
113
|
+
const rightB = b.slice(bStreakIndex + maxStreak);
|
|
114
|
+
const output = [];
|
|
115
|
+
if (leftA.length !== 0 || leftB.length !== 0) {
|
|
116
|
+
output.push(...calculatePlaceholder(leftA, leftB));
|
|
117
|
+
}
|
|
118
|
+
output.push(...a.slice(aStreakIndex, aStreakIndex + maxStreak));
|
|
119
|
+
if (rightA.length !== 0 || rightB.length !== 0) {
|
|
120
|
+
output.push(...calculatePlaceholder(rightA, rightB));
|
|
121
|
+
}
|
|
122
|
+
return output;
|
|
123
|
+
};
|
|
124
|
+
const normalizedCalculatePlaceholder = (a, b) => {
|
|
125
|
+
const output = calculatePlaceholder(a, b);
|
|
126
|
+
// We can't be too general
|
|
127
|
+
if (arrayCount(output, '_') / output.length >= 0.5) {
|
|
128
|
+
return ['_'];
|
|
129
|
+
}
|
|
130
|
+
return output;
|
|
131
|
+
};
|
|
132
|
+
// Merge A (missing placeholders) into B (can contain placeholders but does not have to)
|
|
133
|
+
const mergeMessages = (a, b, storage) => {
|
|
134
|
+
const placeholder = normalizedCalculatePlaceholder(a.split(' '), b.split(' ')).join(' ');
|
|
135
|
+
if (placeholder === '_') {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
const count = storage[a].count + storage[b].count;
|
|
139
|
+
delete storage[a];
|
|
140
|
+
delete storage[b];
|
|
141
|
+
storage[placeholder] = Object.assign(Object.create(null), {
|
|
142
|
+
count,
|
|
143
|
+
});
|
|
144
|
+
return placeholder;
|
|
145
|
+
};
|
|
146
|
+
const getErrorMessageGroup = (error, storage, showFullMessage) => {
|
|
147
|
+
let { message } = error;
|
|
148
|
+
if (!message) {
|
|
149
|
+
try {
|
|
150
|
+
message =
|
|
151
|
+
typeof error === 'string'
|
|
152
|
+
? error
|
|
153
|
+
: `Unknown error message. Received non-error object: ${JSON.stringify(error)}`;
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
message = `Unknown error message. Received non-error object, and could not stringify it: ${inspect(error, {
|
|
157
|
+
depth: 0,
|
|
158
|
+
})}`;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
if (!showFullMessage) {
|
|
162
|
+
const newLineIndex = message.indexOf('\n');
|
|
163
|
+
message = message.slice(0, newLineIndex === -1 ? undefined : newLineIndex);
|
|
164
|
+
}
|
|
165
|
+
if (!(message in storage)) {
|
|
166
|
+
storage[message] = Object.assign(Object.create(null), {
|
|
167
|
+
count: 0,
|
|
168
|
+
});
|
|
169
|
+
// This actually safe, since we Object.create(null) so no prototype pollution can happen.
|
|
170
|
+
// eslint-disable-next-line no-restricted-syntax, guard-for-in
|
|
171
|
+
for (const existingMessage in storage) {
|
|
172
|
+
const newMessage = mergeMessages(message, existingMessage, storage);
|
|
173
|
+
if (newMessage) {
|
|
174
|
+
message = newMessage;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return storage[message];
|
|
180
|
+
};
|
|
181
|
+
const increaseCount = (group) => {
|
|
182
|
+
if (!('count' in group)) {
|
|
183
|
+
// In case users don't want to display error message
|
|
184
|
+
group.count = 0;
|
|
185
|
+
}
|
|
186
|
+
group.count++;
|
|
187
|
+
};
|
|
188
|
+
/**
|
|
189
|
+
* This class tracks errors and computes a summary of information like:
|
|
190
|
+
* - where the errors happened
|
|
191
|
+
* - what the error names are
|
|
192
|
+
* - what the error codes are
|
|
193
|
+
* - what is the general error message
|
|
194
|
+
*
|
|
195
|
+
* This is extremely useful when there are dynamic error messages, such as argument validation.
|
|
196
|
+
*
|
|
197
|
+
* Since the structure of the `tracker.result` object differs when using different options,
|
|
198
|
+
* it's typed as `Record<string, unknown>`. The most deep object has a `count` property, which is a number.
|
|
199
|
+
*
|
|
200
|
+
* It's possible to get the total amount of errors via the `tracker.total` property.
|
|
201
|
+
*/
|
|
202
|
+
export class ErrorTracker {
|
|
203
|
+
#options;
|
|
204
|
+
result;
|
|
205
|
+
total;
|
|
206
|
+
errorSnapshotter;
|
|
207
|
+
constructor(options = {}) {
|
|
208
|
+
this.#options = {
|
|
209
|
+
showErrorCode: true,
|
|
210
|
+
showErrorName: true,
|
|
211
|
+
showStackTrace: true,
|
|
212
|
+
showFullStack: false,
|
|
213
|
+
showErrorMessage: true,
|
|
214
|
+
showFullMessage: false,
|
|
215
|
+
saveErrorSnapshots: false,
|
|
216
|
+
...options,
|
|
217
|
+
};
|
|
218
|
+
if (this.#options.saveErrorSnapshots) {
|
|
219
|
+
this.errorSnapshotter = new ErrorSnapshotter();
|
|
220
|
+
}
|
|
221
|
+
this.result = Object.create(null);
|
|
222
|
+
this.total = 0;
|
|
223
|
+
}
|
|
224
|
+
updateGroup(error) {
|
|
225
|
+
let group = this.result;
|
|
226
|
+
if (this.#options.showStackTrace) {
|
|
227
|
+
group = getStackTraceGroup(error, group, this.#options.showFullStack);
|
|
228
|
+
}
|
|
229
|
+
if (this.#options.showErrorCode) {
|
|
230
|
+
group = getErrorCodeGroup(error, group);
|
|
231
|
+
}
|
|
232
|
+
if (this.#options.showErrorName) {
|
|
233
|
+
group = getErrorNameGroup(error, group);
|
|
234
|
+
}
|
|
235
|
+
if (this.#options.showErrorMessage) {
|
|
236
|
+
group = getErrorMessageGroup(error, group, this.#options.showFullMessage);
|
|
237
|
+
}
|
|
238
|
+
increaseCount(group);
|
|
239
|
+
return group;
|
|
240
|
+
}
|
|
241
|
+
add(error) {
|
|
242
|
+
this.total++;
|
|
243
|
+
this.updateGroup(error);
|
|
244
|
+
if (typeof error.cause === 'object' && error.cause !== null) {
|
|
245
|
+
this.add(error.cause);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* This method is async, because it captures a snapshot of the error context.
|
|
250
|
+
* We added this new method to avoid breaking changes.
|
|
251
|
+
*/
|
|
252
|
+
async addAsync(error, context) {
|
|
253
|
+
this.total++;
|
|
254
|
+
const group = this.updateGroup(error);
|
|
255
|
+
// Capture a snapshot (screenshot and HTML) on the first occurrence of an error
|
|
256
|
+
if (group.count === 1 && context) {
|
|
257
|
+
await this.captureSnapshot(group, error, context).catch(() => { });
|
|
258
|
+
}
|
|
259
|
+
if (typeof error.cause === 'object' && error.cause !== null) {
|
|
260
|
+
await this.addAsync(error.cause);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
getUniqueErrorCount() {
|
|
264
|
+
let count = 0;
|
|
265
|
+
const goDeeper = (group) => {
|
|
266
|
+
if ('count' in group) {
|
|
267
|
+
count++;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
// eslint-disable-next-line guard-for-in, no-restricted-syntax
|
|
271
|
+
for (const key in group) {
|
|
272
|
+
goDeeper(group[key]);
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
goDeeper(this.result);
|
|
276
|
+
return count;
|
|
277
|
+
}
|
|
278
|
+
getMostPopularErrors(count) {
|
|
279
|
+
const result = [];
|
|
280
|
+
const goDeeper = (group, path) => {
|
|
281
|
+
if ('count' in group) {
|
|
282
|
+
result.push([group.count, path]);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
// eslint-disable-next-line guard-for-in, no-restricted-syntax
|
|
286
|
+
for (const key in group) {
|
|
287
|
+
goDeeper(group[key], [...path, key]);
|
|
288
|
+
}
|
|
289
|
+
};
|
|
290
|
+
goDeeper(this.result, []);
|
|
291
|
+
return result.sort((a, b) => b[0] - a[0]).slice(0, count);
|
|
292
|
+
}
|
|
293
|
+
async captureSnapshot(storage, error, context) {
|
|
294
|
+
if (!this.errorSnapshotter) {
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const { screenshotFileUrl, htmlFileUrl } = await this.errorSnapshotter.captureSnapshot(error, context);
|
|
298
|
+
storage.firstErrorScreenshotUrl = screenshotFileUrl;
|
|
299
|
+
storage.firstErrorHtmlUrl = htmlFileUrl;
|
|
300
|
+
}
|
|
301
|
+
reset() {
|
|
302
|
+
// This actually safe, since we Object.create(null) so no prototype pollution can happen.
|
|
303
|
+
// eslint-disable-next-line no-restricted-syntax, guard-for-in
|
|
304
|
+
for (const key in this.result) {
|
|
305
|
+
delete this.result[key];
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|