-
-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathsdk.tsx
257 lines (228 loc) · 7.99 KB
/
sdk.tsx
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
/* eslint-disable complexity */
import { getClient, getGlobalScope,getIntegrationsToSetup, getIsolationScope,initAndBind, withScope as coreWithScope } from '@sentry/core';
import {
defaultStackParser,
makeFetchTransport,
} from '@sentry/react';
import type { Breadcrumb, BreadcrumbHint, Integration, Scope, UserFeedback } from '@sentry/types';
import { logger, stackParserFromStackParserOptions } from '@sentry/utils';
import * as React from 'react';
import { ReactNativeClient } from './client';
import { getDevServer } from './integrations/debugsymbolicatorutils';
import { getDefaultIntegrations } from './integrations/default';
import type { ReactNativeClientOptions, ReactNativeOptions, ReactNativeWrapperOptions } from './options';
import { shouldEnableNativeNagger } from './options';
import { enableSyncToNative } from './scopeSync';
import { TouchEventBoundary } from './touchevents';
import { ReactNativeProfiler } from './tracing';
import { useEncodePolyfill } from './transports/encodePolyfill';
import { DEFAULT_BUFFER_SIZE, makeNativeTransportFactory } from './transports/native';
import { getDefaultEnvironment, isExpoGo, isRunningInMetroDevServer } from './utils/environment';
import { safeFactory, safeTracesSampler } from './utils/safe';
import { NATIVE } from './wrapper';
const DEFAULT_OPTIONS: ReactNativeOptions = {
enableNativeCrashHandling: true,
enableNativeNagger: true,
autoInitializeNativeSdk: true,
enableAutoPerformanceTracing: true,
enableWatchdogTerminationTracking: true,
patchGlobalPromise: true,
sendClientReports: true,
maxQueueSize: DEFAULT_BUFFER_SIZE,
attachStacktrace: true,
enableCaptureFailedRequests: false,
enableNdk: true,
enableAppStartTracking: true,
enableNativeFramesTracking: true,
enableStallTracking: true,
enableUserInteractionTracing: false,
};
/**
* Inits the SDK and returns the final options.
*/
export function init(passedOptions: ReactNativeOptions): void {
if (isRunningInMetroDevServer()) {
return;
}
const maxQueueSize = passedOptions.maxQueueSize
// eslint-disable-next-line deprecation/deprecation
?? passedOptions.transportOptions?.bufferSize
?? DEFAULT_OPTIONS.maxQueueSize;
const enableNative = passedOptions.enableNative === undefined || passedOptions.enableNative
? NATIVE.isNativeAvailable()
: false;
useEncodePolyfill();
if (enableNative) {
enableSyncToNative(getGlobalScope());
enableSyncToNative(getIsolationScope());
}
const getURLFromDSN = (dsn: string | null): string | undefined => {
if (!dsn) {
return undefined;
}
try {
const url = new URL(dsn);
return `${url.protocol}//${url.host}`;
} catch (e) {
logger.error('Failed to extract url from DSN', e);
return undefined;
}
};
const userBeforeBreadcrumb = safeFactory(passedOptions.beforeBreadcrumb, { loggerMessage: 'The beforeBreadcrumb threw an error' });
// Exclude Dev Server and Sentry Dsn request from Breadcrumbs
const devServerUrl = getDevServer()?.url;
const dsn = getURLFromDSN(passedOptions.dsn);
const defaultBeforeBreadcrumb = (breadcrumb: Breadcrumb, _hint?: BreadcrumbHint): Breadcrumb | null => {
const type = breadcrumb.type || '';
const url = typeof breadcrumb.data?.url === 'string' ? breadcrumb.data.url : '';
if (type === 'http' && ((devServerUrl && url.startsWith(devServerUrl)) || (dsn && url.startsWith(dsn)))) {
return null;
}
return breadcrumb;
};
const chainedBeforeBreadcrumb = (breadcrumb: Breadcrumb, hint?: BreadcrumbHint): Breadcrumb | null => {
let modifiedBreadcrumb = breadcrumb;
if (userBeforeBreadcrumb) {
const result = userBeforeBreadcrumb(breadcrumb, hint);
if (result === null) {
return null;
}
modifiedBreadcrumb = result;
}
return defaultBeforeBreadcrumb(modifiedBreadcrumb, hint);
};
const options: ReactNativeClientOptions = {
...DEFAULT_OPTIONS,
...passedOptions,
enableNative,
enableNativeNagger: shouldEnableNativeNagger(passedOptions.enableNativeNagger),
// If custom transport factory fails the SDK won't initialize
transport: passedOptions.transport
|| makeNativeTransportFactory({
enableNative,
})
|| makeFetchTransport,
transportOptions: {
...DEFAULT_OPTIONS.transportOptions,
...(passedOptions.transportOptions ?? {}),
bufferSize: maxQueueSize,
},
maxQueueSize,
integrations: [],
stackParser: stackParserFromStackParserOptions(passedOptions.stackParser || defaultStackParser),
beforeBreadcrumb: chainedBeforeBreadcrumb,
initialScope: safeFactory(passedOptions.initialScope, { loggerMessage: 'The initialScope threw an error' }),
};
if ('tracesSampler' in options) {
options.tracesSampler = safeTracesSampler(options.tracesSampler);
}
if (!('environment' in options)) {
options.environment = getDefaultEnvironment();
}
const defaultIntegrations: false | Integration[] = passedOptions.defaultIntegrations === undefined
? getDefaultIntegrations(options)
: passedOptions.defaultIntegrations;
options.integrations = getIntegrationsToSetup({
integrations: safeFactory(passedOptions.integrations, { loggerMessage: 'The integrations threw an error' }),
defaultIntegrations,
});
initAndBind(ReactNativeClient, options);
if (isExpoGo()) {
logger.info('Offline caching, native errors features are not available in Expo Go.');
logger.info('Use EAS Build / Native Release Build to test these features.');
}
}
/**
* Inits the Sentry React Native SDK with automatic instrumentation and wrapped features.
*/
export function wrap<P extends Record<string, unknown>>(
RootComponent: React.ComponentType<P>,
options?: ReactNativeWrapperOptions
): React.ComponentType<P> {
const profilerProps = {
...(options?.profilerProps ?? {}),
name: RootComponent.displayName ?? 'Root',
};
const RootApp: React.FC<P> = (appProps) => {
return (
<TouchEventBoundary {...(options?.touchEventBoundaryProps ?? {})}>
<ReactNativeProfiler {...profilerProps}>
<RootComponent {...appProps} />
</ReactNativeProfiler>
</TouchEventBoundary>
);
};
return RootApp;
}
/**
* If native client is available it will trigger a native crash.
* Use this only for testing purposes.
*/
export function nativeCrash(): void {
NATIVE.nativeCrash();
}
/**
* Flushes all pending events in the queue to disk.
* Use this before applying any realtime updates such as code-push or expo updates.
*/
export async function flush(): Promise<boolean> {
try {
const client = getClient();
if (client) {
const result = await client.flush();
return result;
}
// eslint-disable-next-line no-empty
} catch (_) { }
logger.error('Failed to flush the event queue.');
return false;
}
/**
* Closes the SDK, stops sending events.
*/
export async function close(): Promise<void> {
try {
const client = getClient();
if (client) {
await client.close();
}
} catch (e) {
logger.error('Failed to close the SDK');
}
}
/**
* Captures user feedback and sends it to Sentry.
*/
export function captureUserFeedback(feedback: UserFeedback): void {
getClient<ReactNativeClient>()?.captureUserFeedback(feedback);
}
/**
* Creates a new scope with and executes the given operation within.
* The scope is automatically removed once the operation
* finishes or throws.
*
* This is essentially a convenience function for:
*
* pushScope();
* callback();
* popScope();
*
* @param callback that will be enclosed into push/popScope.
*/
export function withScope<T>(callback: (scope: Scope) => T): T | undefined {
const safeCallback = (scope: Scope): T | undefined => {
try {
return callback(scope);
} catch (e) {
logger.error('Error while running withScope callback', e);
return undefined;
}
};
return coreWithScope(safeCallback);
}
/**
* Returns if the app crashed in the last run.
*/
export async function crashedLastRun(): Promise<boolean | null> {
return NATIVE.crashedLastRun();
}