-
-
Notifications
You must be signed in to change notification settings - Fork 342
/
Copy pathwrapper.ts
565 lines (478 loc) · 15 KB
/
wrapper.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
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
/* eslint-disable max-lines */
import {
BaseEnvelopeItemHeaders,
Breadcrumb,
Envelope,
EnvelopeItem,
Event,
Package,
SeverityLevel,
User,
} from '@sentry/types';
import { logger, normalize, SentryError } from '@sentry/utils';
import { NativeModules, Platform } from 'react-native';
import {
NativeAppStartResponse,
NativeDeviceContextsResponse,
NativeFramesResponse,
NativeReleaseResponse,
SentryNativeBridgeModule,
} from './definitions';
import { isHardCrash } from './misc';
import { ReactNativeOptions } from './options';
import { RequiredKeysUser } from './user';
import { utf8ToBytes } from './vendor';
const RNSentry = NativeModules.RNSentry as SentryNativeBridgeModule | undefined;
interface SentryNativeWrapper {
enableNative: boolean;
nativeIsReady: boolean;
platform: typeof Platform.OS;
_NativeClientError: Error;
_DisabledNativeError: Error;
_processItem(envelopeItem: EnvelopeItem): EnvelopeItem;
_processLevels(event: Event): Event;
_processLevel(level: SeverityLevel): SeverityLevel;
_serializeObject(data: { [key: string]: unknown }): { [key: string]: string };
_isModuleLoaded(
module: SentryNativeBridgeModule | undefined
): module is SentryNativeBridgeModule;
_getBreadcrumbs(event: Event): Breadcrumb[] | undefined;
isNativeTransportAvailable(): boolean;
initNativeSdk(options: ReactNativeOptions): PromiseLike<boolean>;
closeNativeSdk(): PromiseLike<void>;
sendEnvelope(envelope: Envelope): Promise<void>;
fetchNativeRelease(): PromiseLike<NativeReleaseResponse>;
fetchNativeDeviceContexts(): PromiseLike<NativeDeviceContextsResponse>;
fetchNativeAppStart(): PromiseLike<NativeAppStartResponse | null>;
fetchNativeFrames(): PromiseLike<NativeFramesResponse | null>;
fetchNativeSdkInfo(): PromiseLike<Package | null>;
disableNativeFramesTracking(): void;
enableNativeFramesTracking(): void;
addBreadcrumb(breadcrumb: Breadcrumb): void;
setContext(key: string, context: { [key: string]: unknown } | null): void;
clearBreadcrumbs(): void;
setExtra(key: string, extra: unknown): void;
setUser(user: User | null): void;
setTag(key: string, value: string): void;
nativeCrash(): void;
}
/**
* Our internal interface for calling native functions
*/
export const NATIVE: SentryNativeWrapper = {
/**
* Sending the envelope over the bridge to native
* @param envelope Envelope
*/
async sendEnvelope(envelope: Envelope): Promise<void> {
if (!this.enableNative) {
logger.warn('Event was skipped as native SDK is not enabled.');
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const [EOL] = utf8ToBytes('\n');
const [envelopeHeader, envelopeItems] = envelope;
const headerString = JSON.stringify(envelopeHeader);
const envelopeBytes: number[] = utf8ToBytes(headerString);
envelopeBytes.push(EOL);
let hardCrashed: boolean = false;
for (const rawItem of envelopeItems) {
const [itemHeader, itemPayload] = this._processItem(rawItem);
let bytesPayload: number[] = [];
if (typeof itemPayload === 'string') {
bytesPayload = utf8ToBytes(itemPayload);
} else if (itemPayload instanceof Uint8Array) {
bytesPayload = [...itemPayload];
} else {
bytesPayload = utf8ToBytes(JSON.stringify(itemPayload));
if (!hardCrashed) {
hardCrashed = isHardCrash(itemPayload);
}
}
// Content type is not inside BaseEnvelopeItemHeaders.
(itemHeader as BaseEnvelopeItemHeaders).content_type = 'application/json';
(itemHeader as BaseEnvelopeItemHeaders).length = bytesPayload.length;
const serializedItemHeader = JSON.stringify(itemHeader);
envelopeBytes.push(...utf8ToBytes(serializedItemHeader));
envelopeBytes.push(EOL);
bytesPayload.forEach(byte => envelopeBytes.push(byte));
envelopeBytes.push(EOL);
}
await RNSentry.captureEnvelope(envelopeBytes, { store: hardCrashed });
},
/**
* Starts native with the provided options.
* @param options ReactNativeOptions
*/
async initNativeSdk(originalOptions: ReactNativeOptions): Promise<boolean> {
const options = {
enableNative: true,
autoInitializeNativeSdk: true,
...originalOptions,
};
if (!options.enableNative) {
if (options.enableNativeNagger) {
logger.warn('Note: Native Sentry SDK is disabled.');
}
this.enableNative = false;
return false;
}
if (!options.autoInitializeNativeSdk) {
if (options.enableNativeNagger) {
logger.warn(
'Note: Native Sentry SDK was not initialized automatically, you will need to initialize it manually. If you wish to disable the native SDK and get rid of this warning, pass enableNative: false'
);
}
return false;
}
if (!options.dsn) {
logger.warn(
'Warning: No DSN was provided. The Sentry SDK will be disabled. Native SDK will also not be initalized.'
);
return false;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
// filter out all the options that would crash native.
/* eslint-disable @typescript-eslint/unbound-method,@typescript-eslint/no-unused-vars */
const {
beforeSend,
beforeBreadcrumb,
integrations,
...filteredOptions
} = options;
/* eslint-enable @typescript-eslint/unbound-method,@typescript-eslint/no-unused-vars */
const nativeIsReady = await RNSentry.initNativeSdk(filteredOptions);
this.nativeIsReady = nativeIsReady;
return nativeIsReady;
},
/**
* Fetches the release from native
*/
async fetchNativeRelease(): Promise<NativeReleaseResponse> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeRelease();
},
/**
* Fetches the Sdk info for the native sdk.
* NOTE: Only available on iOS.
*/
async fetchNativeSdkInfo(): Promise<Package | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
if (this.platform !== 'ios') {
return null;
}
return RNSentry.fetchNativeSdkInfo();
},
/**
* Fetches the device contexts. Not used on Android.
*/
async fetchNativeDeviceContexts(): Promise<NativeDeviceContextsResponse> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
if (this.platform !== 'ios') {
// Only ios uses deviceContexts, return an empty object.
return {};
}
return RNSentry.fetchNativeDeviceContexts();
},
async fetchNativeAppStart(): Promise<NativeAppStartResponse | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeAppStart();
},
async fetchNativeFrames(): Promise<NativeFramesResponse | null> {
if (!this.enableNative) {
throw this._DisabledNativeError;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
return RNSentry.fetchNativeFrames();
},
/**
* Triggers a native crash.
* Use this only for testing purposes.
*/
nativeCrash(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.crash();
},
/**
* Sets the user in the native scope.
* Passing null clears the user.
*/
setUser(user: User | null): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
// separate and serialize all non-default user keys.
let userKeys = null;
let userDataKeys = null;
if (user) {
const { id, ip_address, email, username, segment, ...otherKeys } = user;
const requiredUser: RequiredKeysUser = {
id,
ip_address,
email,
username,
segment,
};
userKeys = this._serializeObject(requiredUser);
userDataKeys = this._serializeObject(otherKeys);
}
RNSentry.setUser(userKeys, userDataKeys);
},
/**
* Sets a tag in the native module.
* @param key string
* @param value string
*/
setTag(key: string, value: string): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
const stringifiedValue =
typeof value === 'string' ? value : JSON.stringify(value);
RNSentry.setTag(key, stringifiedValue);
},
/**
* Sets an extra in the native scope, will stringify
* extra value if it isn't already a string.
* @param key string
* @param extra any
*/
setExtra(key: string, extra: unknown): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
// we stringify the extra as native only takes in strings.
const stringifiedExtra =
typeof extra === 'string' ? extra : JSON.stringify(extra);
RNSentry.setExtra(key, stringifiedExtra);
},
/**
* Adds breadcrumb to the native scope.
* @param breadcrumb Breadcrumb
*/
addBreadcrumb(breadcrumb: Breadcrumb): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.addBreadcrumb({
...breadcrumb,
// Process and convert deprecated levels
level: breadcrumb.level
? this._processLevel(breadcrumb.level)
: undefined,
data: breadcrumb.data
? normalize(breadcrumb.data)
: undefined,
});
},
/**
* Clears breadcrumbs on the native scope.
*/
clearBreadcrumbs(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.clearBreadcrumbs();
},
/**
* Sets context on the native scope. Not implemented in Android yet.
* @param key string
* @param context key-value map
*/
setContext(key: string, context: { [key: string]: unknown } | null): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
throw this._NativeClientError;
}
RNSentry.setContext(
key,
context !== null ? normalize(context) : null
);
},
/**
* Closes the Native Layer SDK
*/
async closeNativeSdk(): Promise<void> {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
return RNSentry.closeNativeSdk().then(() => {
this.enableNative = false;
});
},
disableNativeFramesTracking(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
RNSentry.disableNativeFramesTracking();
},
enableNativeFramesTracking(): void {
if (!this.enableNative) {
return;
}
if (!this._isModuleLoaded(RNSentry)) {
return;
}
RNSentry.enableNativeFramesTracking();
},
isNativeTransportAvailable(): boolean {
return this.enableNative && this._isModuleLoaded(RNSentry);
},
/**
* Gets the event from envelopeItem and applies the level filter to the selected event.
* @param data An envelope item containing the event.
* @returns The event from envelopeItem or undefined.
*/
_processItem(item: EnvelopeItem): EnvelopeItem {
const [itemHeader, itemPayload] = item;
if (itemHeader.type == 'event' || itemHeader.type == 'transaction') {
const event = this._processLevels(itemPayload as Event);
if (NATIVE.platform === 'android') {
if ('message' in event) {
// @ts-ignore Android still uses the old message object, without this the serialization of events will break.
event.message = { message: event.message };
}
event.breadcrumbs = this._getBreadcrumbs(event);
}
return [itemHeader, event];
}
return item;
},
/**
* Serializes all values of root-level keys into strings.
* @param data key-value map.
* @returns An object where all root-level values are strings.
*/
_serializeObject(data: {
[key: string]: unknown;
}): { [key: string]: string } {
const serialized: { [key: string]: string } = {};
Object.keys(data).forEach((dataKey) => {
const value = data[dataKey];
serialized[dataKey] =
typeof value === 'string' ? value : JSON.stringify(value);
});
return serialized;
},
/**
* Convert js severity level in event.level and event.breadcrumbs to more widely supported levels.
* @param event
* @returns Event with more widely supported Severity level strings
*/
_processLevels(event: Event): Event {
const processed: Event = {
...event,
level: event.level ? this._processLevel(event.level) : undefined,
breadcrumbs: event.breadcrumbs?.map((breadcrumb) => ({
...breadcrumb,
level: breadcrumb.level
? this._processLevel(breadcrumb.level)
: undefined,
})),
};
return processed;
},
/**
* Convert js severity level which has critical and log to more widely supported levels.
* @param level
* @returns More widely supported Severity level strings
*/
_processLevel(level: SeverityLevel): SeverityLevel {
if (level == 'log' as SeverityLevel) {
return 'debug' as SeverityLevel;
}
else if (level == 'critical' as SeverityLevel) {
return 'fatal' as SeverityLevel;
}
return level;
},
/**
* Checks whether the RNSentry module is loaded.
*/
_isModuleLoaded(
module: SentryNativeBridgeModule | undefined
): module is SentryNativeBridgeModule {
return !!module;
},
_DisabledNativeError: new SentryError('Native is disabled'),
_NativeClientError: new SentryError(
"Native Client is not available, can't start on native."
),
/**
* Get breadcrumbs (removes breadcrumbs from handled exceptions on Android)
*
* We do this to avoid duplicate breadcrumbs on Android as sentry-android applies the breadcrumbs
* from the native scope onto every envelope sent through it. This scope will contain the breadcrumbs
* sent through the scope sync feature. This causes duplicate breadcrumbs.
* We then remove the breadcrumbs in all cases but if it is handled == false,
* this is a signal that the app would crash and android would lose the breadcrumbs by the time the app is restarted to read
* the envelope.
*/
_getBreadcrumbs(event: Event): Breadcrumb[] | undefined {
let breadcrumbs: Breadcrumb[] | undefined = event.breadcrumbs;
const hardCrashed = isHardCrash(event);
if (NATIVE.platform === 'android'
&& event.breadcrumbs
&& !hardCrashed) {
breadcrumbs = [];
}
return breadcrumbs;
},
enableNative: true,
nativeIsReady: false,
platform: Platform.OS,
};