-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
sdk.ts
246 lines (226 loc) · 7.05 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
import { getCurrentHub, initAndBind, Integrations as CoreIntegrations } from '@sentry/core';
import { Hub } from '@sentry/types';
import { addInstrumentationHandler, getGlobalObject, isDebugBuild, logger, resolvedSyncPromise } from '@sentry/utils';
import { BrowserOptions } from './backend';
import { BrowserClient } from './client';
import { ReportDialogOptions, wrap as internalWrap } from './helpers';
import { Breadcrumbs, Dedupe, GlobalHandlers, LinkedErrors, TryCatch, UserAgent } from './integrations';
export const defaultIntegrations = [
new CoreIntegrations.InboundFilters(),
new CoreIntegrations.FunctionToString(),
new TryCatch(),
new Breadcrumbs(),
new GlobalHandlers(),
new LinkedErrors(),
new Dedupe(),
new UserAgent(),
];
/**
* 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) {
const window = getGlobalObject<Window>();
// 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;
}
initAndBind(BrowserClient, options);
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 = {}): void {
const hub = getCurrentHub();
const scope = hub.getScope();
if (scope) {
options.user = {
...scope.getUser(),
...options.user,
};
}
if (!options.eventId) {
options.eventId = hub.lastEventId();
}
const client = hub.getClient<BrowserClient>();
if (client) {
client.showReportDialog(options);
}
}
/**
* This is the getter for lastEventId.
*
* @returns The last event id of a captured event.
*/
export function lastEventId(): string | undefined {
return getCurrentHub().lastEventId();
}
/**
* 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();
}
/**
* Call `flush()` on the current client, if there is one. See {@link Client.flush}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause
* the client to wait until all events are sent before resolving the promise.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export function flush(timeout?: number): PromiseLike<boolean> {
const client = getCurrentHub().getClient<BrowserClient>();
if (client) {
return client.flush(timeout);
}
if (isDebugBuild()) {
logger.warn('Cannot flush events. No client defined.');
}
return resolvedSyncPromise(false);
}
/**
* Call `close()` on the current client, if there is one. See {@link Client.close}.
*
* @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this
* parameter will cause the client to wait until all events are sent before disabling itself.
* @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it
* doesn't (or if there's no client defined).
*/
export function close(timeout?: number): PromiseLike<boolean> {
const client = getCurrentHub().getClient<BrowserClient>();
if (client) {
return client.close(timeout);
}
if (isDebugBuild()) {
logger.warn('Cannot flush events and disable SDK. No client defined.');
}
return resolvedSyncPromise(false);
}
/**
* 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 {
const window = getGlobalObject<Window>();
const document = window.document;
if (typeof document === 'undefined') {
if (isDebugBuild()) {
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());
}
});
}