-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathsdk.ts
284 lines (254 loc) · 8.21 KB
/
sdk.ts
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
280
281
282
283
284
import type { Client, Integration, Options, ReportDialogOptions } from '@sentry/core';
import {
consoleSandbox,
dedupeIntegration,
functionToStringIntegration,
getCurrentScope,
getIntegrationsToSetup,
getLocationHref,
getReportDialogEndpoint,
inboundFiltersIntegration,
initAndBind,
lastEventId,
logger,
stackParserFromStackParserOptions,
supportsFetch,
} from '@sentry/core';
import type { BrowserClientOptions, BrowserOptions } from './client';
import { BrowserClient } from './client';
import { DEBUG_BUILD } from './debug-build';
import { WINDOW } from './helpers';
import { breadcrumbsIntegration } from './integrations/breadcrumbs';
import { browserApiErrorsIntegration } from './integrations/browserapierrors';
import { browserSessionIntegration } from './integrations/browsersession';
import { globalHandlersIntegration } from './integrations/globalhandlers';
import { httpContextIntegration } from './integrations/httpcontext';
import { linkedErrorsIntegration } from './integrations/linkederrors';
import { defaultStackParser } from './stack-parsers';
import { makeFetchTransport } from './transports/fetch';
/** Get the default integrations for the browser SDK. */
export function getDefaultIntegrations(_options: Options): Integration[] {
/**
* Note: Please make sure this stays in sync with Angular SDK, which re-exports
* `getDefaultIntegrations` but with an adjusted set of integrations.
*
* Ensure to keep this in sync with `BrowserOptions`!
*/
return [
inboundFiltersIntegration(),
functionToStringIntegration(),
browserApiErrorsIntegration(),
breadcrumbsIntegration(),
globalHandlersIntegration(),
linkedErrorsIntegration(),
dedupeIntegration(),
httpContextIntegration(),
browserSessionIntegration(),
];
}
/** Exported only for tests. */
export function applyDefaultOptions(optionsArg: BrowserOptions = {}): BrowserOptions {
const defaultOptions: BrowserOptions = {
defaultIntegrations: getDefaultIntegrations(optionsArg),
release:
typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value
? __SENTRY_RELEASE__
: WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects
sendClientReports: true,
};
return {
...defaultOptions,
...dropTopLevelUndefinedKeys(optionsArg),
};
}
/**
* In contrast to the regular `dropUndefinedKeys` method,
* this one does not deep-drop keys, but only on the top level.
*/
function dropTopLevelUndefinedKeys<T extends object>(obj: T): Partial<T> {
const mutatetedObj: Partial<T> = {};
for (const k of Object.getOwnPropertyNames(obj)) {
const key = k as keyof T;
if (obj[key] !== undefined) {
mutatetedObj[key] = obj[key];
}
}
return mutatetedObj;
}
type ExtensionProperties = {
chrome?: Runtime;
browser?: Runtime;
nw?: unknown;
};
type Runtime = {
runtime?: {
id?: string;
};
};
function shouldShowBrowserExtensionError(): boolean {
const windowWithMaybeExtension =
typeof WINDOW.window !== 'undefined' && (WINDOW as typeof WINDOW & ExtensionProperties);
if (!windowWithMaybeExtension) {
// No need to show the error if we're not in a browser window environment (e.g. service workers)
return false;
}
const extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser';
const extensionObject = windowWithMaybeExtension[extensionKey];
const runtimeId = extensionObject?.runtime?.id;
const href = getLocationHref() || '';
const extensionProtocols = ['chrome-extension:', 'moz-extension:', 'ms-browser-extension:', 'safari-web-extension:'];
// Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage
const isDedicatedExtensionPage =
!!runtimeId && WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}//`));
// Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine
// see: https://github.com/getsentry/sentry-javascript/issues/12668
const isNWjs = typeof windowWithMaybeExtension.nw !== 'undefined';
return !!runtimeId && !isDedicatedExtensionPage && !isNWjs;
}
/**
* A magic string that build tooling can leverage in order to inject a release value into the SDK.
*/
declare const __SENTRY_RELEASE__: string | undefined;
/**
* The Sentry Browser SDK Client.
*
* To use this SDK, call the {@link init} function as early as possible when
* loading the web page. To set context information or send manual events, use
* the provided methods.
*
* @example
*
* ```
*
* import { init } from '@sentry/browser';
*
* init({
* dsn: '__DSN__',
* // ...
* });
* ```
*
* @example
* ```
*
* import { addBreadcrumb } from '@sentry/browser';
* addBreadcrumb({
* message: 'My Breadcrumb',
* // ...
* });
* ```
*
* @example
*
* ```
*
* import * as Sentry from '@sentry/browser';
* Sentry.captureMessage('Hello, world!');
* Sentry.captureException(new Error('Good bye'));
* Sentry.captureEvent({
* message: 'Manual',
* stacktrace: [
* // ...
* ],
* });
* ```
*
* @see {@link BrowserOptions} for documentation on configuration options.
*/
export function init(browserOptions: BrowserOptions = {}): Client | undefined {
const options = applyDefaultOptions(browserOptions);
if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) {
consoleSandbox(() => {
// eslint-disable-next-line no-console
console.error(
'[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',
);
});
return;
}
if (DEBUG_BUILD) {
if (!supportsFetch()) {
logger.warn(
'No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.',
);
}
}
const clientOptions: BrowserClientOptions = {
...options,
stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
integrations: getIntegrationsToSetup(options),
transport: options.transport || makeFetchTransport,
};
return initAndBind(BrowserClient, clientOptions);
}
/**
* Present the user with a report dialog.
*
* @param options Everything is optional, we try to fetch all info need from the global scope.
*/
export function showReportDialog(options: ReportDialogOptions = {}): void {
// doesn't work without a document (React Native)
if (!WINDOW.document) {
DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');
return;
}
const scope = getCurrentScope();
const client = scope.getClient();
const dsn = client?.getDsn();
if (!dsn) {
DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');
return;
}
if (scope) {
options.user = {
...scope.getUser(),
...options.user,
};
}
if (!options.eventId) {
const eventId = lastEventId();
if (eventId) {
options.eventId = eventId;
}
}
const script = WINDOW.document.createElement('script');
script.async = true;
script.crossOrigin = 'anonymous';
script.src = getReportDialogEndpoint(dsn, options);
if (options.onLoad) {
script.onload = options.onLoad;
}
const { onClose } = options;
if (onClose) {
const reportDialogClosedMessageHandler = (event: MessageEvent): void => {
if (event.data === '__sentry_reportdialog_closed__') {
try {
onClose();
} finally {
WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);
}
}
};
WINDOW.addEventListener('message', reportDialogClosedMessageHandler);
}
const injectionPoint = WINDOW.document.head || WINDOW.document.body;
if (injectionPoint) {
injectionPoint.appendChild(script);
} else {
DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');
}
}
/**
* This function is here to be API compatible with the loader.
* @hidden
*/
export function forceLoad(): void {
// Noop
}
/**
* This function is here to be API compatible with the loader.
* @hidden
*/
export function onLoad(callback: () => void): void {
callback();
}