-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathInstabug.ts
678 lines (603 loc) · 20.2 KB
/
Instabug.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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
import type React from 'react';
import { Platform, findNodeHandle, processColor } from 'react-native';
import type {
NavigationContainerRefWithCurrent,
NavigationState as NavigationStateV5,
} from '@react-navigation/native';
import type { ComponentDidAppearEvent } from 'react-native-navigation';
import type { NavigationAction, NavigationState as NavigationStateV4 } from 'react-navigation';
import type { InstabugConfig } from '../models/InstabugConfig';
import Report from '../models/Report';
import { emitter, NativeEvents, NativeInstabug } from '../native/NativeInstabug';
import { registerW3CFlagsListener } from '../utils/FeatureFlags';
import {
ColorTheme,
Locale,
LogLevel,
NetworkInterceptionMode,
ReproStepsMode,
StringKey,
WelcomeMessageMode,
} from '../utils/Enums';
import InstabugUtils, { stringifyIfNotString } from '../utils/InstabugUtils';
import * as NetworkLogger from './NetworkLogger';
import { captureUnhandledRejections } from '../utils/UnhandledRejectionTracking';
import type { ReproConfig } from '../models/ReproConfig';
import type { FeatureFlag } from '../models/FeatureFlag';
import InstabugConstants from '../utils/InstabugConstants';
import { InstabugRNConfig } from '../utils/config';
import { Logger } from '../utils/logger';
let _currentScreen: string | null = null;
let _lastScreen: string | null = null;
let _isFirstScreen = false;
const firstScreen = 'Initial Screen';
/**
* Enables or disables Instabug functionality.
* @param isEnabled A boolean to enable/disable Instabug.
*/
export const setEnabled = (isEnabled: boolean) => {
NativeInstabug.setEnabled(isEnabled);
};
/**
* Reports that the screen name been changed (Current View field on dashboard).
* only for android.
*
* Normally reportScreenChange handles taking a screenshot for reproduction
* steps and the Current View field on the dashboard. But we've faced issues
* in android where we needed to separate them, that's why we only call it
* for android.
*
* @param screenName string containing the screen name
*/
function reportCurrentViewForAndroid(screenName: string | null) {
if (Platform.OS === 'android' && screenName != null) {
NativeInstabug.reportCurrentViewChange(screenName);
}
}
/**
* Initializes the SDK.
* This is the main SDK method that does all the magic. This is the only
* method that SHOULD be called.
* Should be called in constructor of the AppRegistry component
* @param config SDK configurations. See {@link InstabugConfig} for more info.
*/
export const init = (config: InstabugConfig) => {
InstabugUtils.captureJsErrors();
captureUnhandledRejections();
if (Platform.OS === 'android') {
registerW3CFlagsListener();
}
// Default networkInterceptionMode to JavaScript
if (config.networkInterceptionMode == null) {
config.networkInterceptionMode = NetworkInterceptionMode.javascript;
}
if (config.networkInterceptionMode === NetworkInterceptionMode.javascript) {
NetworkLogger.setEnabled(true);
}
NativeInstabug.init(
config.token,
config.invocationEvents,
config.debugLogsLevel ?? LogLevel.error,
config.networkInterceptionMode === NetworkInterceptionMode.native,
config.codePushVersion,
);
_isFirstScreen = true;
_currentScreen = firstScreen;
InstabugRNConfig.debugLogsLevel = config.debugLogsLevel ?? LogLevel.error;
reportCurrentViewForAndroid(firstScreen);
setTimeout(() => {
if (_currentScreen === firstScreen) {
NativeInstabug.reportScreenChange(firstScreen);
_currentScreen = null;
}
}, 1000);
};
/**
* Sets the Code Push version to be sent with each report.
* @param version the Code Push version.
*/
export const setCodePushVersion = (version: string) => {
NativeInstabug.setCodePushVersion(version);
};
/**
* Attaches user data to each report being sent.
* Each call to this method overrides the user data to be attached.
* Maximum size of the string is 1,000 characters.
* @param data A string to be attached to each report, with a maximum size of 1,000 characters.
*/
export const setUserData = (data: string) => {
NativeInstabug.setUserData(data);
};
/**
* Sets whether the SDK is tracking user steps or not.
* Enabling user steps would give you an insight on the scenario a user has
* performed before encountering a bug or a crash. User steps are attached
* with each report being sent.
* @param isEnabled A boolean to set user steps tracking to being enabled or disabled.
*/
export const setTrackUserSteps = (isEnabled: boolean) => {
NativeInstabug.setTrackUserSteps(isEnabled);
};
/**
* Sets whether IBGLog should also print to Xcode's console log or not.
* @param printsToConsole A boolean to set whether printing to
* Xcode's console is enabled or not.
*/
export const setIBGLogPrintsToConsole = (printsToConsole: boolean) => {
if (Platform.OS === 'ios') {
NativeInstabug.setIBGLogPrintsToConsole(printsToConsole);
}
};
/**
* The session profiler is enabled by default and it attaches to the bug and
* crash reports the following information during the last 60 seconds before the report is sent.
* @param isEnabled A boolean parameter to enable or disable the feature.
*/
export const setSessionProfilerEnabled = (isEnabled: boolean) => {
NativeInstabug.setSessionProfilerEnabled(isEnabled);
};
/**
* Sets the SDK's locale.
* Use to change the SDK's UI to different language.
* Defaults to the device's current locale.
* @param sdkLocale A locale to set the SDK to.
*/
export const setLocale = (sdkLocale: Locale) => {
NativeInstabug.setLocale(sdkLocale);
};
/**
* Sets the color theme of the SDK's whole UI.
* @param sdkTheme
*/
export const setColorTheme = (sdkTheme: ColorTheme) => {
NativeInstabug.setColorTheme(sdkTheme);
};
/**
* Sets the primary color of the SDK's UI.
* Sets the color of UI elements indicating interactivity or call to action.
* To use, import processColor and pass to it with argument the color hex
* as argument.
* @param color A color to set the UI elements of the SDK to.
*/
export const setPrimaryColor = (color: string) => {
NativeInstabug.setPrimaryColor(processColor(color));
};
/**
* Appends a set of tags to previously added tags of reported feedback,
* bug or crash.
* @param tags An array of tags to append to current tags.
*/
export const appendTags = (tags: string[]) => {
NativeInstabug.appendTags(tags);
};
/**
* Manually removes all tags of reported feedback, bug or crash.
*/
export const resetTags = () => {
NativeInstabug.resetTags();
};
/**
* Gets all tags of reported feedback, bug or crash.
*/
export const getTags = async (): Promise<string[] | null> => {
const tags = await NativeInstabug.getTags();
return tags;
};
/**
* Overrides any of the strings shown in the SDK with custom ones.
* Allows you to customize any of the strings shown to users in the SDK.
* @param key Key of string to override.
* @param string String value to override the default one.
*/
export const setString = (key: StringKey, string: string) => {
// Suffix the repro steps list item numbering title with a # to unify the string key's
// behavior between Android and iOS
if (Platform.OS === 'android' && key === StringKey.reproStepsListItemNumberingTitle) {
string = `${string} #`;
}
NativeInstabug.setString(string, key);
};
/**
* Sets the default value of the user's email and ID and hides the email field from the reporting UI
* and set the user's name to be included with all reports.
* It also reset the chats on device to that email and removes user attributes,
* user data and completed surveys.
* @param email Email address to be set as the user's email.
* @param name Name of the user to be set.
* @param [id] ID of the user to be set.
*/
export const identifyUser = (email: string, name: string, id?: string) => {
NativeInstabug.identifyUser(email, name, id);
};
/**
* Sets the default value of the user's email to nil and show email field and remove user name
* from all reports
* It also reset the chats on device and removes user attributes, user data and completed surveys.
*/
export const logOut = () => {
NativeInstabug.logOut();
};
/**
* Logs a user event that happens through the lifecycle of the application.
* Logged user events are going to be sent with each report, as well as at the end of a session.
* @param name Event name.
*/
export const logUserEvent = (name: string) => {
NativeInstabug.logUserEvent(name);
};
/**
* Appends a log message to Instabug internal log.
* These logs are then sent along the next uploaded report.
* All log messages are timestamped.
* Logs aren't cleared per single application run.
* If you wish to reset the logs, use {@link clearLogs()}
* Note: logs passed to this method are **NOT** printed to Logcat.
*
* @param message the message
*/
export const logVerbose = (message: string) => {
if (!message) {
return;
}
message = stringifyIfNotString(message);
NativeInstabug.logVerbose(message);
};
/**
* Appends a log message to Instabug internal log.
* These logs are then sent along the next uploaded report.
* All log messages are timestamped.
* Logs aren't cleared per single application run.
* If you wish to reset the logs, use {@link clearLogs()}
* Note: logs passed to this method are **NOT** printed to Logcat.
*
* @param message the message
*/
export const logInfo = (message: string) => {
if (!message) {
return;
}
message = stringifyIfNotString(message);
NativeInstabug.logInfo(message);
};
/**
* Appends a log message to Instabug internal log.
* These logs are then sent along the next uploaded report.
* All log messages are timestamped.
* Logs aren't cleared per single application run.
* If you wish to reset the logs, use {@link clearLogs()}
* Note: logs passed to this method are **NOT** printed to Logcat.
*
* @param message the message
*/
export const logDebug = (message: string) => {
if (!message) {
return;
}
message = stringifyIfNotString(message);
NativeInstabug.logDebug(message);
};
/**
* Appends a log message to Instabug internal log.
* These logs are then sent along the next uploaded report.
* All log messages are timestamped.
* Logs aren't cleared per single application run.
* If you wish to reset the logs, use {@link clearLogs()}
* Note: logs passed to this method are **NOT** printed to Logcat.
*
* @param message the message
*/
export const logError = (message: string) => {
if (!message) {
return;
}
message = stringifyIfNotString(message);
NativeInstabug.logError(message);
};
/**
* Appends a log message to Instabug internal log.
* These logs are then sent along the next uploaded report.
* All log messages are timestamped.
* Logs aren't cleared per single application run.
* If you wish to reset the logs, use {@link clearLogs()}
* Note: logs passed to this method are **NOT** printed to Logcat.
*
* @param message the message
*/
export const logWarn = (message: string) => {
if (!message) {
return;
}
message = stringifyIfNotString(message);
NativeInstabug.logWarn(message);
};
/**
* Clear all Instabug logs, console logs, network logs and user steps.
*/
export const clearLogs = () => {
NativeInstabug.clearLogs();
};
/**
* Sets the repro steps mode for bugs and crashes.
*
* @param config The repro steps config.
*
* @example
* ```js
* Instabug.setReproStepsConfig({
* bug: ReproStepsMode.enabled,
* crash: ReproStepsMode.disabled,
* sessionReplay: ReproStepsMode.enabled,
* });
* ```
*/
export const setReproStepsConfig = (config: ReproConfig) => {
let bug = config.bug ?? ReproStepsMode.enabled;
let crash = config.crash ?? ReproStepsMode.enabledWithNoScreenshots;
let sessionReplay = config.sessionReplay ?? ReproStepsMode.enabled;
if (config.all != null) {
bug = config.all;
crash = config.all;
sessionReplay = config.all;
}
NativeInstabug.setReproStepsConfig(bug, crash, sessionReplay);
};
/**
* Sets user attribute to overwrite it's value or create a new one if it doesn't exist.
*
* @param key the attribute
* @param value the value
*/
export const setUserAttribute = (key: string, value: string) => {
if (!key || typeof key !== 'string' || typeof value !== 'string') {
Logger.error(InstabugConstants.SET_USER_ATTRIBUTES_ERROR_TYPE_MESSAGE);
return;
}
NativeInstabug.setUserAttribute(key, value);
};
/**
* Returns the user attribute associated with a given key.
* @param key The attribute key as string
*/
export const getUserAttribute = async (key: string): Promise<string | null> => {
const attribute = await NativeInstabug.getUserAttribute(key);
return attribute;
};
/**
* Removes user attribute if exists.
*
* @param key the attribute key as string
* @see {@link setUserAttribute}
*/
export const removeUserAttribute = (key: string) => {
if (!key || typeof key !== 'string') {
Logger.error(InstabugConstants.REMOVE_USER_ATTRIBUTES_ERROR_TYPE_MESSAGE);
return;
}
NativeInstabug.removeUserAttribute(key);
};
/**
* Returns all user attributes.
* set user attributes, or an empty dictionary if no user attributes have been set.
*/
export const getAllUserAttributes = async (): Promise<Record<string, string>> => {
const attributes = await NativeInstabug.getAllUserAttributes();
return attributes;
};
/**
* Clears all user attributes if exists.
*/
export const clearAllUserAttributes = () => {
NativeInstabug.clearAllUserAttributes();
};
/**
* Shows the welcome message in a specific mode.
* @param mode An enum to set the welcome message mode to live, or beta.
*/
export const showWelcomeMessage = (mode: WelcomeMessageMode) => {
NativeInstabug.showWelcomeMessageWithMode(mode);
};
/**
* Sets the welcome message mode to live, beta or disabled.
* @param mode An enum to set the welcome message mode to live, beta or disabled.
*/
export const setWelcomeMessageMode = (mode: WelcomeMessageMode) => {
NativeInstabug.setWelcomeMessageMode(mode);
};
/**
* Add file to be attached to the bug report.
* @param filePath
* @param fileName
*/
export const addFileAttachment = (filePath: string, fileName: string) => {
if (Platform.OS === 'android') {
NativeInstabug.setFileAttachment(filePath, fileName);
} else {
NativeInstabug.setFileAttachment(filePath);
}
};
/**
* Hides component from screenshots, screen recordings and view hierarchy.
* @param viewRef the ref of the component to hide
*/
export const addPrivateView = (viewRef: number | React.Component | React.ComponentClass) => {
const nativeTag = findNodeHandle(viewRef);
NativeInstabug.addPrivateView(nativeTag);
};
/**
* Removes component from the set of hidden views. The component will show again in
* screenshots, screen recordings and view hierarchy.
* @param viewRef the ref of the component to remove from hidden views
*/
export const removePrivateView = (viewRef: number | React.Component | React.ComponentClass) => {
const nativeTag = findNodeHandle(viewRef);
NativeInstabug.removePrivateView(nativeTag);
};
/**
* Shows default Instabug prompt.
*/
export const show = () => {
NativeInstabug.show();
};
export const onReportSubmitHandler = (handler?: (report: Report) => void) => {
emitter.addListener(NativeEvents.PRESENDING_HANDLER, (report) => {
const { tags, consoleLogs, instabugLogs, userAttributes, fileAttachments } = report;
const reportObj = new Report(tags, consoleLogs, instabugLogs, userAttributes, fileAttachments);
handler && handler(reportObj);
});
NativeInstabug.setPreSendingHandler(handler);
};
export const onNavigationStateChange = (
prevState: NavigationStateV4,
currentState: NavigationStateV4,
_action: NavigationAction,
) => {
const currentScreen = InstabugUtils.getActiveRouteName(currentState);
const prevScreen = InstabugUtils.getActiveRouteName(prevState);
if (prevScreen !== currentScreen) {
reportCurrentViewForAndroid(currentScreen);
if (_currentScreen != null && _currentScreen !== firstScreen) {
NativeInstabug.reportScreenChange(_currentScreen);
_currentScreen = null;
}
_currentScreen = currentScreen;
setTimeout(() => {
if (currentScreen && _currentScreen === currentScreen) {
NativeInstabug.reportScreenChange(currentScreen);
_currentScreen = null;
}
}, 1000);
}
};
export const onStateChange = (state?: NavigationStateV5) => {
if (!state) {
return;
}
const currentScreen = InstabugUtils.getFullRoute(state);
reportCurrentViewForAndroid(currentScreen);
if (_currentScreen !== null && _currentScreen !== firstScreen) {
NativeInstabug.reportScreenChange(_currentScreen);
_currentScreen = null;
}
_currentScreen = currentScreen;
setTimeout(() => {
if (_currentScreen === currentScreen) {
NativeInstabug.reportScreenChange(currentScreen);
_currentScreen = null;
}
}, 1000);
};
/**
* Sets a listener for screen change
* @param navigationRef a refrence of a navigation container
*
*/
export const setNavigationListener = (
navigationRef: NavigationContainerRefWithCurrent<ReactNavigation.RootParamList>,
) => {
return navigationRef.addListener('state', () => {
onStateChange(navigationRef.getRootState());
});
};
export const reportScreenChange = (screenName: string) => {
NativeInstabug.reportScreenChange(screenName);
};
/**
* Add experiments to next report.
* @param experiments An array of experiments to add to the next report.
*
* @deprecated Please migrate to the new Feature Flags APIs: {@link addFeatureFlags}.
*/
export const addExperiments = (experiments: string[]) => {
NativeInstabug.addExperiments(experiments);
};
/**
* Remove experiments from next report.
* @param experiments An array of experiments to remove from the next report.
*
* @deprecated Please migrate to the new Feature Flags APIs: {@link removeFeatureFlags}.
*/
export const removeExperiments = (experiments: string[]) => {
NativeInstabug.removeExperiments(experiments);
};
/**
* Clear all experiments
*
* @deprecated Please migrate to the new Feature Flags APIs: {@link removeAllFeatureFlags}.
*/
export const clearAllExperiments = () => {
NativeInstabug.clearAllExperiments();
};
/**
* Add feature flags to the next report.
* @param featureFlags An array of feature flags to add to the next report.
*/
export const addFeatureFlags = (featureFlags: FeatureFlag[]) => {
const entries = featureFlags.map((item) => [item.name, item.variant || '']);
const flags = Object.fromEntries(entries);
NativeInstabug.addFeatureFlags(flags);
};
/**
* Add a feature flag to the to next report.
*/
export const addFeatureFlag = (featureFlag: FeatureFlag) => {
addFeatureFlags([featureFlag]);
};
/**
* Remove feature flags from the next report.
* @param featureFlags An array of feature flags to remove from the next report.
*/
export const removeFeatureFlags = (featureFlags: string[]) => {
NativeInstabug.removeFeatureFlags(featureFlags);
};
/**
* Remove a feature flag from the next report.
* @param name the name of the feature flag to remove from the next report.
*/
export const removeFeatureFlag = (name: string) => {
removeFeatureFlags([name]);
};
/**
* Clear all feature flags
*/
export const removeAllFeatureFlags = () => {
NativeInstabug.removeAllFeatureFlags();
};
/**
* This API has to be call when using custom app rating prompt
*/
export const willRedirectToStore = () => {
NativeInstabug.willRedirectToStore();
};
/**
* This API has be called when changing the default Metro server port (8081) to exclude the DEV URL from network logging.
*/
export const setMetroDevServerPort = (port: number) => {
InstabugRNConfig.metroDevServerPort = port.toString();
};
export const componentDidAppearListener = (event: ComponentDidAppearEvent) => {
if (_isFirstScreen) {
_lastScreen = event.componentName;
_isFirstScreen = false;
return;
}
if (_lastScreen !== event.componentName) {
NativeInstabug.reportScreenChange(event.componentName);
_lastScreen = event.componentName;
}
};
/**
* Sets listener to W3ExternalTraceID flag changes
* @param handler A callback that gets the update value of the flag
*/
export const _registerW3CFlagsChangeListener = (
handler: (payload: {
isW3ExternalTraceIDEnabled: boolean;
isW3ExternalGeneratedHeaderEnabled: boolean;
isW3CaughtHeaderEnabled: boolean;
}) => void,
) => {
emitter.addListener(NativeEvents.ON_W3C_FLAGS_CHANGE, (payload) => {
handler(payload);
});
NativeInstabug.registerW3CFlagsChangeListener();
};