-
-
Notifications
You must be signed in to change notification settings - Fork 367
Expand file tree
/
Copy pathsdk.tsx
More file actions
314 lines (278 loc) · 9.93 KB
/
Copy pathsdk.tsx
File metadata and controls
314 lines (278 loc) · 9.93 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/* oxlint-disable eslint(complexity) */
import type { Breadcrumb, BreadcrumbHint, Integration, Scope } from '@sentry/core';
import {
debug,
getClient,
getGlobalScope,
getIntegrationsToSetup,
getIsolationScope,
initAndBind,
makeDsn,
stackParserFromStackParserOptions,
withScope as coreWithScope,
} from '@sentry/core';
import { defaultStackParser, makeFetchTransport, Profiler } from '@sentry/react';
import * as React from 'react';
import type { ReactNativeClientOptions, ReactNativeOptions, ReactNativeWrapperOptions } from './options';
import { ReactNativeClient } from './client';
import { FeedbackFormProvider } from './feedback/FeedbackFormProvider';
import { getDevServer } from './integrations/debugsymbolicatorutils';
import { getDefaultIntegrations } from './integrations/default';
import { shouldEnableNativeNagger } from './options';
import { enableSyncToNative } from './scopeSync';
import { TouchEventBoundary } from './touchevents';
import { ReactNativeProfiler } from './tracing';
import { _appLoaded } from './tracing/integrations/appStart';
import { useEncodePolyfill } from './transports/encodePolyfill';
import { DEFAULT_BUFFER_SIZE, makeNativeTransportFactory } from './transports/native';
import { getDefaultEnvironment, isExpoGo, isRunningInMetroDevServer, isWeb } from './utils/environment';
import { getDefaultRelease } from './utils/release';
import { safeFactory, safeTracesSampler } from './utils/safe';
import { RN_GLOBAL_OBJ } from './utils/worldwide';
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,
propagateTraceparent: false,
};
/**
* Inits the SDK and returns the final options.
*/
export function init(passedOptions: ReactNativeOptions): void {
if (isRunningInMetroDevServer()) {
return;
}
const userOptions = {
...RN_GLOBAL_OBJ.__SENTRY_OPTIONS__,
...passedOptions,
};
const maxQueueSize =
userOptions.maxQueueSize ?? userOptions.transportOptions?.bufferSize ?? DEFAULT_OPTIONS.maxQueueSize;
const enableNative =
userOptions.enableNative === undefined || userOptions.enableNative ? NATIVE.isNativeAvailable() : false;
useEncodePolyfill();
if (enableNative) {
enableSyncToNative(getGlobalScope());
enableSyncToNative(getIsolationScope());
}
const getURLFromDSN = (dsn: string | undefined): string | undefined => {
if (!dsn) {
return undefined;
}
const dsnComponents = makeDsn(dsn);
if (!dsnComponents) {
debug.error('Failed to extract url from DSN: ', dsn);
return undefined;
}
const port = dsnComponents.port ? `:${dsnComponents.port}` : '';
return `${dsnComponents.protocol}://${dsnComponents.host}${port}`;
};
const userBeforeBreadcrumb = safeFactory(userOptions.beforeBreadcrumb, {
loggerMessage: 'The beforeBreadcrumb threw an error',
});
// Exclude Dev Server and Sentry Dsn request from Breadcrumbs
const devServerUrl = getDevServer()?.url;
const dsn = getURLFromDSN(userOptions.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,
...userOptions,
release: userOptions.release ?? getDefaultRelease(),
enableNative,
enableNativeNagger: shouldEnableNativeNagger(userOptions.enableNativeNagger),
// If custom transport factory fails the SDK won't initialize
transport:
userOptions.transport ||
makeNativeTransportFactory({
enableNative,
}) ||
makeFetchTransport,
transportOptions: {
...DEFAULT_OPTIONS.transportOptions,
...(userOptions.transportOptions ?? {}),
bufferSize: maxQueueSize,
},
maxQueueSize,
integrations: [],
stackParser: stackParserFromStackParserOptions(userOptions.stackParser || defaultStackParser),
beforeBreadcrumb: chainedBeforeBreadcrumb,
initialScope: safeFactory(userOptions.initialScope, { loggerMessage: 'The initialScope threw an error' }),
};
if (!('autoInitializeNativeSdk' in userOptions) && RN_GLOBAL_OBJ.__SENTRY_OPTIONS__ && !__DEV__) {
// Options file is present in a release build, native SDK is expected to be initialized
// before JS from the native app entry point (e.g. AppDelegate, MainApplication).
// In dev builds, we always re-initialize from JS to set up the native log bridge
// and provide runtime values (devServerUrl, defaultSidecarUrl, etc.).
// oxlint-disable-next-line eslint(no-console)
console.info(
'[Sentry] Using options file. Native SDK is expected to be initialized before JS, skipping automatic native initialization from JS.',
);
options.autoInitializeNativeSdk = false;
}
if ('tracesSampler' in options) {
options.tracesSampler = safeTracesSampler(options.tracesSampler);
}
if (!('environment' in options)) {
options.environment = getDefaultEnvironment();
}
const defaultIntegrations: false | Integration[] =
userOptions.defaultIntegrations === undefined ? getDefaultIntegrations(options) : userOptions.defaultIntegrations;
options.integrations = getIntegrationsToSetup({
integrations: safeFactory(userOptions.integrations, { loggerMessage: 'The integrations threw an error' }),
defaultIntegrations,
});
initAndBind(ReactNativeClient, options);
if (isExpoGo()) {
debug.log('Offline caching, native errors features are not available in Expo Go.');
debug.log('Use EAS Build / Native Release Build to test these features.');
}
if (RN_GLOBAL_OBJ.__SENTRY_OPTIONS__) {
debug.log('Sentry JS initialized with options from the options file.');
}
}
/**
* 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',
updateProps: {},
};
const ProfilerComponent = isWeb() ? Profiler : ReactNativeProfiler;
const RootApp: React.FC<P> = appProps => {
return (
<TouchEventBoundary {...(options?.touchEventBoundaryProps ?? {})}>
<ProfilerComponent {...profilerProps}>
<FeedbackFormProvider>
<RootComponent {...appProps} />
</FeedbackFormProvider>
</ProfilerComponent>
</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();
}
/**
* Signals that the application has finished loading and is ready for user interaction.
*
* Call this when your app is truly ready — after async initialization, data loading,
* splash screen dismissal, auth session restore, etc. This marks the end of the app start span,
* giving you a more accurate measurement of perceived startup time.
*
* If not called, the SDK falls back to the root component mount time (via `Sentry.wrap()`)
* or JS bundle execution start.
*
* @experimental This API is subject to change in future versions.
*
* @example
* ```ts
* await loadRemoteConfig();
* await restoreSession();
* SplashScreen.hide();
* Sentry.appLoaded();
* ```
*/
export function appLoaded(): void {
// oxlint-disable-next-line typescript-eslint(no-floating-promises)
_appLoaded();
}
/**
* 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;
}
} catch (_) {}
debug.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) {
debug.error('Failed to close the SDK');
}
}
/**
* 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) {
debug.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();
}