Repository navigation
Expand file tree
/
Copy pathmisc.ts
More file actions
279 lines (246 loc) · 9.47 KB
/
Copy pathmisc.ts
File metadata and controls
279 lines (246 loc) · 9.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Event, Mechanism, StackFrame } from '@sentry/types';
import { getGlobalObject } from './global';
import { snipLine } from './string';
/**
* Extended Window interface that allows for Crypto API usage in IE browsers
*/
interface MsCryptoWindow extends Window {
msCrypto?: Crypto;
}
/**
* UUID4 generator
*
* @returns string Generated UUID4.
*/
export function uuid4(): string {
const global = getGlobalObject() as MsCryptoWindow;
const crypto = global.crypto || global.msCrypto;
if (!(crypto === void 0) && crypto.getRandomValues) {
// Use window.crypto API if available
const arr = new Uint16Array(8);
crypto.getRandomValues(arr);
// set 4 in byte 7
// eslint-disable-next-line no-bitwise
arr[3] = (arr[3] & 0xfff) | 0x4000;
// set 2 most significant bits of byte 9 to '10'
// eslint-disable-next-line no-bitwise
arr[4] = (arr[4] & 0x3fff) | 0x8000;
const pad = (num: number): string => {
let v = num.toString(16);
while (v.length < 4) {
v = `0${v}`;
}
return v;
};
return (
pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])
);
}
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, c => {
// eslint-disable-next-line no-bitwise
const r = (Math.random() * 16) | 0;
// eslint-disable-next-line no-bitwise
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
/**
* Parses string form of URL into an object
* // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B
* // intentionally using regex and not <a/> href parsing trick because React Native and other
* // environments where DOM might not be available
* @returns parsed URL object
*/
export function parseUrl(
url: string,
): {
host?: string;
path?: string;
protocol?: string;
relative?: string;
} {
if (!url) {
return {};
}
const match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/);
if (!match) {
return {};
}
// coerce to undefined values to empty string so we don't get 'undefined'
const query = match[6] || '';
const fragment = match[8] || '';
return {
host: match[4],
path: match[5],
protocol: match[2],
relative: match[5] + query + fragment, // everything minus origin
};
}
/**
* Extracts either message or type+value from an event that can be used for user-facing logs
* @returns event's description
*/
export function getEventDescription(event: Event): string {
if (event.message) {
return event.message;
}
if (event.exception && event.exception.values && event.exception.values[0]) {
const exception = event.exception.values[0];
if (exception.type && exception.value) {
return `${exception.type}: ${exception.value}`;
}
return exception.type || exception.value || event.event_id || '<unknown>';
}
return event.event_id || '<unknown>';
}
/**
* Adds exception values, type and value to an synthetic Exception.
* @param event The event to modify.
* @param value Value of the exception.
* @param type Type of the exception.
* @hidden
*/
export function addExceptionTypeValue(event: Event, value?: string, type?: string): void {
event.exception = event.exception || {};
event.exception.values = event.exception.values || [];
event.exception.values[0] = event.exception.values[0] || {};
event.exception.values[0].value = event.exception.values[0].value || value || '';
event.exception.values[0].type = event.exception.values[0].type || type || 'Error';
}
/**
* Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.
*
* @param event The event to modify.
* @param newMechanism Mechanism data to add to the event.
* @hidden
*/
export function addExceptionMechanism(event: Event, newMechanism?: Partial<Mechanism>): void {
if (!event.exception || !event.exception.values) {
return;
}
const exceptionValue0 = event.exception.values[0];
const defaultMechanism = { type: 'generic', handled: true };
const currentMechanism = exceptionValue0.mechanism;
exceptionValue0.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
if (newMechanism && 'data' in newMechanism) {
const mergedData = { ...currentMechanism?.data, ...newMechanism.data };
exceptionValue0.mechanism.data = mergedData;
}
}
// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
const SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
/**
* Represents Semantic Versioning object
*/
interface SemVer {
major?: number;
minor?: number;
patch?: number;
prerelease?: string;
buildmetadata?: string;
}
/**
* Parses input into a SemVer interface
* @param input string representation of a semver version
*/
export function parseSemver(input: string): SemVer {
const match = input.match(SEMVER_REGEXP) || [];
const major = parseInt(match[1], 10);
const minor = parseInt(match[2], 10);
const patch = parseInt(match[3], 10);
return {
buildmetadata: match[5],
major: isNaN(major) ? undefined : major,
minor: isNaN(minor) ? undefined : minor,
patch: isNaN(patch) ? undefined : patch,
prerelease: match[4],
};
}
const defaultRetryAfter = 60 * 1000; // 60 seconds
/**
* Extracts Retry-After value from the request header or returns default value
* @param now current unix timestamp
* @param header string representation of 'Retry-After' header
*/
export function parseRetryAfterHeader(now: number, header?: string | number | null): number {
if (!header) {
return defaultRetryAfter;
}
const headerDelay = parseInt(`${header}`, 10);
if (!isNaN(headerDelay)) {
return headerDelay * 1000;
}
const headerDate = Date.parse(`${header}`);
if (!isNaN(headerDate)) {
return headerDate - now;
}
return defaultRetryAfter;
}
/**
* This function adds context (pre/post/line) lines to the provided frame
*
* @param lines string[] containing all lines
* @param frame StackFrame that will be mutated
* @param linesOfContext number of context lines we want to add pre/post
*/
export function addContextToFrame(lines: string[], frame: StackFrame, linesOfContext: number = 5): void {
const lineno = frame.lineno || 0;
const maxLines = lines.length;
const sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0);
frame.pre_context = lines
.slice(Math.max(0, sourceLine - linesOfContext), sourceLine)
.map((line: string) => snipLine(line, 0));
frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0);
frame.post_context = lines
.slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)
.map((line: string) => snipLine(line, 0));
}
/**
* Strip the query string and fragment off of a given URL or path (if present)
*
* @param urlPath Full URL or path, including possible query string and/or fragment
* @returns URL or path without query string or fragment
*/
export function stripUrlQueryAndFragment(urlPath: string): string {
// eslint-disable-next-line no-useless-escape
return urlPath.split(/[\?#]/, 1)[0];
}
/**
* Checks whether or not we've already captured the given exception (note: not an identical exception - the very object
* in question), and marks it captured if not.
*
* This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and
* record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so
* that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because
* the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not
* caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This
* function helps us ensure that even if we encounter the same error more than once, we only record it the first time we
* see it.
*
* Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on
* them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent
* object wrapper forms so that this check will always work. However, because we need to flag the exact object which
* will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification
* must be done before the exception captured.
*
* @param A thrown exception to check or flag as having been seen
* @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)
*/
export function checkOrSetAlreadyCaught(exception: unknown): boolean {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if ((exception as any)?.__sentry_captured__) {
return true;
}
try {
// set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the
// `ExtraErrorData` integration
Object.defineProperty(exception, '__sentry_captured__', {
value: true,
});
} catch (err) {
// `exception` is a primitive, so we can't mark it seen
}
return false;
}