-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
sdk.ts
254 lines (229 loc) · 7.16 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
import type { Hub } from '@sentry/core';
import {
getCurrentHub,
getIntegrationsToSetup,
getReportDialogEndpoint,
initAndBind,
Integrations as CoreIntegrations,
} from '@sentry/core';
import type { UserFeedback } from '@sentry/types';
import { addInstrumentationHandler, logger, stackParserFromStackParserOptions, supportsFetch } from '@sentry/utils';
import type { BrowserClientOptions, BrowserOptions } from './client';
import { BrowserClient } from './client';
import type { ReportDialogOptions } from './helpers';
import { WINDOW, wrap as internalWrap } from './helpers';
import { Breadcrumbs, Dedupe, GlobalHandlers, HttpContext, LinkedErrors, TryCatch } from './integrations';
import { defaultStackParser } from './stack-parsers';
import { makeFetchTransport, makeXHRTransport } from './transports';
export const defaultIntegrations = [
new CoreIntegrations.InboundFilters(),
new CoreIntegrations.FunctionToString(),
new TryCatch(),
new Breadcrumbs(),
new GlobalHandlers(),
new LinkedErrors(),
new Dedupe(),
new HttpContext(),
];
/**
* 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 { configureScope } from '@sentry/browser';
* configureScope((scope: Scope) => {
* scope.setExtra({ battery: 0.7 });
* scope.setTag({ user_mode: 'admin' });
* scope.setUser({ id: '4711' });
* });
* ```
*
* @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(options: BrowserOptions = {}): void {
if (options.defaultIntegrations === undefined) {
options.defaultIntegrations = defaultIntegrations;
}
if (options.release === undefined) {
// This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value
if (typeof __SENTRY_RELEASE__ === 'string') {
options.release = __SENTRY_RELEASE__;
}
// This supports the variable that sentry-webpack-plugin injects
if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {
options.release = WINDOW.SENTRY_RELEASE.id;
}
}
if (options.autoSessionTracking === undefined) {
options.autoSessionTracking = true;
}
if (options.sendClientReports === undefined) {
options.sendClientReports = true;
}
const clientOptions: BrowserClientOptions = {
...options,
stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),
integrations: getIntegrationsToSetup(options),
transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),
};
initAndBind(BrowserClient, clientOptions);
if (options.autoSessionTracking) {
startSessionTracking();
}
}
/**
* 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 = {}, hub: Hub = getCurrentHub()): 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 { client, scope } = hub.getStackTop();
const dsn = options.dsn || (client && 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) {
options.eventId = hub.lastEventId();
}
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 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();
}
/**
* Wrap code within a try/catch block so the SDK is able to capture errors.
*
* @param fn A function to wrap.
*
* @returns The result of wrapped function call.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function wrap(fn: (...args: any) => any): any {
return internalWrap(fn)();
}
function startSessionOnHub(hub: Hub): void {
hub.startSession({ ignoreDuration: true });
hub.captureSession();
}
/**
* Enable automatic Session Tracking for the initial page load.
*/
function startSessionTracking(): void {
if (typeof WINDOW.document === 'undefined') {
__DEBUG_BUILD__ &&
logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');
return;
}
const hub = getCurrentHub();
// The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and
// @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are
// pinned at the same version in package.json, but there are edge cases where it's possible. See
// https://github.com/getsentry/sentry-javascript/issues/3207 and
// https://github.com/getsentry/sentry-javascript/issues/3234 and
// https://github.com/getsentry/sentry-javascript/issues/3278.
if (!hub.captureSession) {
return;
}
// The session duration for browser sessions does not track a meaningful
// concept that can be used as a metric.
// Automatically captured sessions are akin to page views, and thus we
// discard their duration.
startSessionOnHub(hub);
// We want to create a session for every navigation as well
addInstrumentationHandler('history', ({ from, to }) => {
// Don't create an additional session for the initial route or if the location did not change
if (!(from === undefined || from === to)) {
startSessionOnHub(getCurrentHub());
}
});
}
/**
* Captures user feedback and sends it to Sentry.
*/
export function captureUserFeedback(feedback: UserFeedback): void {
const client = getCurrentHub().getClient<BrowserClient>();
if (client) {
client.captureUserFeedback(feedback);
}
}