@app-swiss-knife/react-native-sdk 0.3.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +465 -0
- package/LICENSE +21 -0
- package/README.md +229 -42
- package/SwissKnifePurchases.podspec +1 -1
- package/android/build.gradle +24 -2
- package/android/consumer-rules.pro +12 -0
- package/android/src/main/AndroidManifest.xml +15 -1
- package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
- package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
- package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
- package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
- package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
- package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
- package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
- package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
- package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
- package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
- package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
- package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +641 -208
- package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
- package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
- package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
- package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +69 -35
- package/android/vendor/java/com/appswissknife/net/IngestClient.kt +756 -98
- package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
- package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
- package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
- package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
- package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
- package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
- package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
- package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
- package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
- package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
- package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
- package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
- package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
- package/android/vendor-rustore/AndroidManifest.xml +59 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
- package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
- package/app.plugin.js +287 -0
- package/ios/SwissKnifePurchases.m +20 -0
- package/ios/SwissKnifePurchases.swift +97 -3
- package/ios/SwissKnifePushBootstrap.m +34 -0
- package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
- package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
- package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +531 -100
- package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
- package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
- package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
- package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
- package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
- package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
- package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
- package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
- package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
- package/lib/commonjs/attribution.js +4 -3
- package/lib/commonjs/attribution.js.map +1 -1
- package/lib/commonjs/identity.js +12 -11
- package/lib/commonjs/identity.js.map +1 -1
- package/lib/commonjs/index.js +16 -5
- package/lib/commonjs/index.js.map +1 -1
- package/lib/commonjs/internal/config.js +105 -8
- package/lib/commonjs/internal/config.js.map +1 -1
- package/lib/commonjs/internal/telemetry-context.js +70 -0
- package/lib/commonjs/internal/telemetry-context.js.map +1 -0
- package/lib/commonjs/modules/analytics.js +18 -25
- package/lib/commonjs/modules/analytics.js.map +1 -1
- package/lib/commonjs/modules/crash-reporting.js +353 -31
- package/lib/commonjs/modules/crash-reporting.js.map +1 -1
- package/lib/commonjs/modules/log.js +1 -1
- package/lib/commonjs/modules/notifications.js +500 -0
- package/lib/commonjs/modules/notifications.js.map +1 -0
- package/lib/commonjs/modules/performance.js +57 -8
- package/lib/commonjs/modules/performance.js.map +1 -1
- package/lib/commonjs/native/module.js +6 -0
- package/lib/commonjs/native/module.js.map +1 -1
- package/lib/commonjs/native/spec.js +12 -5
- package/lib/commonjs/native/spec.js.map +1 -1
- package/lib/commonjs/purchases.js +4 -4
- package/lib/commonjs/types.js +12 -15
- package/lib/commonjs/types.js.map +1 -1
- package/lib/module/attribution.js +4 -3
- package/lib/module/attribution.js.map +1 -1
- package/lib/module/identity.js +12 -11
- package/lib/module/identity.js.map +1 -1
- package/lib/module/index.js +8 -4
- package/lib/module/index.js.map +1 -1
- package/lib/module/internal/config.js +103 -8
- package/lib/module/internal/config.js.map +1 -1
- package/lib/module/internal/telemetry-context.js +63 -0
- package/lib/module/internal/telemetry-context.js.map +1 -0
- package/lib/module/modules/analytics.js +18 -25
- package/lib/module/modules/analytics.js.map +1 -1
- package/lib/module/modules/crash-reporting.js +353 -31
- package/lib/module/modules/crash-reporting.js.map +1 -1
- package/lib/module/modules/log.js +1 -1
- package/lib/module/modules/notifications.js +491 -0
- package/lib/module/modules/notifications.js.map +1 -0
- package/lib/module/modules/performance.js +57 -8
- package/lib/module/modules/performance.js.map +1 -1
- package/lib/module/native/module.js +6 -1
- package/lib/module/native/module.js.map +1 -1
- package/lib/module/native/spec.js +11 -4
- package/lib/module/native/spec.js.map +1 -1
- package/lib/module/purchases.js +4 -4
- package/lib/module/types.js +12 -15
- package/lib/module/types.js.map +1 -1
- package/lib/typescript/commonjs/attribution.d.ts +3 -2
- package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
- package/lib/typescript/commonjs/identity.d.ts.map +1 -1
- package/lib/typescript/commonjs/index.d.ts +3 -1
- package/lib/typescript/commonjs/index.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/config.d.ts +16 -2
- package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
- package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts +50 -12
- package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
- package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
- package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/module.d.ts +2 -0
- package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
- package/lib/typescript/commonjs/native/spec.d.ts +33 -4
- package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
- package/lib/typescript/commonjs/purchases.d.ts +4 -4
- package/lib/typescript/commonjs/types.d.ts +4 -5
- package/lib/typescript/commonjs/types.d.ts.map +1 -1
- package/lib/typescript/module/attribution.d.ts +3 -2
- package/lib/typescript/module/attribution.d.ts.map +1 -1
- package/lib/typescript/module/identity.d.ts.map +1 -1
- package/lib/typescript/module/index.d.ts +3 -1
- package/lib/typescript/module/index.d.ts.map +1 -1
- package/lib/typescript/module/internal/config.d.ts +16 -2
- package/lib/typescript/module/internal/config.d.ts.map +1 -1
- package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
- package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
- package/lib/typescript/module/modules/analytics.d.ts +8 -11
- package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
- package/lib/typescript/module/modules/crash-reporting.d.ts +50 -12
- package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
- package/lib/typescript/module/modules/notifications.d.ts +110 -0
- package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
- package/lib/typescript/module/modules/performance.d.ts +13 -0
- package/lib/typescript/module/modules/performance.d.ts.map +1 -1
- package/lib/typescript/module/native/module.d.ts +2 -0
- package/lib/typescript/module/native/module.d.ts.map +1 -1
- package/lib/typescript/module/native/spec.d.ts +33 -4
- package/lib/typescript/module/native/spec.d.ts.map +1 -1
- package/lib/typescript/module/purchases.d.ts +4 -4
- package/lib/typescript/module/types.d.ts +4 -5
- package/lib/typescript/module/types.d.ts.map +1 -1
- package/package.json +13 -4
- package/src/attribution.ts +4 -3
- package/src/identity.ts +12 -11
- package/src/index.ts +18 -4
- package/src/internal/config.ts +113 -8
- package/src/internal/telemetry-context.ts +76 -0
- package/src/modules/analytics.ts +24 -33
- package/src/modules/crash-reporting.ts +476 -67
- package/src/modules/log.ts +1 -1
- package/src/modules/notifications.ts +557 -0
- package/src/modules/performance.ts +94 -14
- package/src/native/module.ts +6 -0
- package/src/native/spec.ts +45 -10
- package/src/purchases.ts +4 -4
- package/src/types.ts +12 -15
- package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
- package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
captureTelemetryContext,
|
|
3
|
+
currentTelemetryTraceId,
|
|
4
|
+
} from "../internal/telemetry-context";
|
|
1
5
|
// packages/react-native-sdk/src/modules/crash-reporting.ts
|
|
2
6
|
//
|
|
3
7
|
// Sentry-compatible crash reporting SDK for swiss-knife (React Native).
|
|
@@ -25,7 +29,7 @@
|
|
|
25
29
|
// require new native impls on both platforms + spec.ts + tests, well
|
|
26
30
|
// beyond Round-D's "wrap-up the audit" scope.
|
|
27
31
|
//
|
|
28
|
-
// Native crash capture (
|
|
32
|
+
// Native crash capture (iOS signals + NSException, ANR, Android NDK)
|
|
29
33
|
// already goes through the native `SKCrashReporting` module (see the
|
|
30
34
|
// `getNativeCrashModule()` branch below) — those native-side captures
|
|
31
35
|
// ARE on the unified transport. JS-captured errors stay on this fetch
|
|
@@ -35,28 +39,31 @@ import React from "react";
|
|
|
35
39
|
|
|
36
40
|
import { generateUUID } from "./ids";
|
|
37
41
|
import { getOfflineStorage } from "./offline-store";
|
|
38
|
-
import {
|
|
39
|
-
base64ToUint8Array,
|
|
40
|
-
uploadAttachmentWithRetry,
|
|
41
|
-
} from "./attachments";
|
|
42
|
+
import { base64ToUint8Array, uploadAttachmentWithRetry } from "./attachments";
|
|
42
43
|
|
|
43
44
|
// MARK: - Native Bridge
|
|
44
45
|
|
|
45
46
|
/**
|
|
46
47
|
* Optional native module for crash reporting. If the host app has linked
|
|
47
48
|
* the SwissKnife iOS/Android native crash SDKs, this module delegates
|
|
48
|
-
* init/setUser/addBreadcrumb to the native layer — catching
|
|
49
|
-
*
|
|
49
|
+
* init/setUser/addBreadcrumb to the native layer — catching signal crashes and
|
|
50
|
+
* uncaught NSExceptions (iOS) and NDK native crashes (Android) that JS can't
|
|
51
|
+
* see. iOS installs no Mach exception handler.
|
|
50
52
|
*/
|
|
51
53
|
interface SKCrashReportingNative {
|
|
54
|
+
/**
|
|
55
|
+
* Both bridges read these keys. Telemetry goes to `serverURL`
|
|
56
|
+
* (`<serverURL>/ingest`); there is no separate ingest host.
|
|
57
|
+
*/
|
|
52
58
|
start(config: {
|
|
53
59
|
apiKey: string;
|
|
54
60
|
serverURL: string;
|
|
55
|
-
ingestURL?: string;
|
|
56
61
|
environment: string;
|
|
57
62
|
release: string;
|
|
58
63
|
}): void;
|
|
59
|
-
setUser(
|
|
64
|
+
setUser(
|
|
65
|
+
user: { id?: string; email?: string; username?: string } | null
|
|
66
|
+
): void;
|
|
60
67
|
addBreadcrumb(breadcrumb: {
|
|
61
68
|
category?: string;
|
|
62
69
|
message?: string;
|
|
@@ -147,8 +154,15 @@ export interface CrashReportingConfig {
|
|
|
147
154
|
*/
|
|
148
155
|
enableAppStateTracking?: boolean;
|
|
149
156
|
/**
|
|
150
|
-
* Start the NATIVE crash handler
|
|
151
|
-
*
|
|
157
|
+
* Start the NATIVE crash handler via the native module. Default **true**.
|
|
158
|
+
*
|
|
159
|
+
* iOS: `signal()` handlers for SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGSEGV and
|
|
160
|
+
* SIGTRAP, the uncaught-NSException handler, and a main-thread hang (ANR)
|
|
161
|
+
* watchdog. There is no Mach exception handler and no alternate signal
|
|
162
|
+
* stack, so a crash that never reaches one of those handlers (a stack
|
|
163
|
+
* overflow, for example) is not reported. Android: uncaught JVM exceptions,
|
|
164
|
+
* an ANR watchdog, and, on Android 11+, NDK native crashes and system ANRs
|
|
165
|
+
* from the previous launch.
|
|
152
166
|
*
|
|
153
167
|
* Our native handlers chain (they capture and re-invoke the previous
|
|
154
168
|
* `NSSetUncaughtExceptionHandler` / `signal()` / Java
|
|
@@ -211,6 +225,8 @@ export interface SKParsedFrame {
|
|
|
211
225
|
}
|
|
212
226
|
|
|
213
227
|
export interface SKCrashEvent {
|
|
228
|
+
sessionId?: string;
|
|
229
|
+
traceId?: string;
|
|
214
230
|
eventId: string;
|
|
215
231
|
timestamp: number;
|
|
216
232
|
level: "debug" | "info" | "warning" | "error" | "fatal";
|
|
@@ -227,6 +243,15 @@ export interface SKCrashEvent {
|
|
|
227
243
|
dist?: string;
|
|
228
244
|
platform: string;
|
|
229
245
|
mechanism?: string;
|
|
246
|
+
/**
|
|
247
|
+
* Custom grouping key (Sentry-compatible). Events with the same
|
|
248
|
+
* fingerprint are one issue. Entries may be templates the server expands:
|
|
249
|
+
* `{{ default }}` (the normal grouping), `{{ type }}`, `{{ value }}`,
|
|
250
|
+
* `{{ message }}`, `{{ tags.<key> }}` — e.g.
|
|
251
|
+
* `["{{ default }}", "{{ tags.region }}"]` splits the default issue by
|
|
252
|
+
* region.
|
|
253
|
+
*/
|
|
254
|
+
fingerprint?: string[];
|
|
230
255
|
/** `false` for events captured by the SDK's global hooks (fatal errors,
|
|
231
256
|
* unhandled promise rejections); unset for manual captures. */
|
|
232
257
|
handled?: boolean;
|
|
@@ -235,10 +260,22 @@ export interface SKCrashEvent {
|
|
|
235
260
|
|
|
236
261
|
// MARK: - Scope
|
|
237
262
|
|
|
238
|
-
interface SKCrashScope {
|
|
263
|
+
export interface SKCrashScope {
|
|
239
264
|
setTag: (key: string, value: string) => void;
|
|
240
265
|
setExtra: (key: string, value: unknown) => void;
|
|
241
266
|
setUser: (user: SKCrashUser | null) => void;
|
|
267
|
+
/**
|
|
268
|
+
* Fingerprint for every event captured after this call (until cleared
|
|
269
|
+
* with `null` / `[]`). A per-call `captureException(err, { fingerprint })`
|
|
270
|
+
* wins over it. See `SKCrashEvent.fingerprint` for templates.
|
|
271
|
+
*/
|
|
272
|
+
setFingerprint: (fingerprint: string[] | null) => void;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
export interface SKCaptureExceptionOptions {
|
|
276
|
+
tags?: Record<string, string>;
|
|
277
|
+
/** Custom grouping key for this event; overrides the scope's. */
|
|
278
|
+
fingerprint?: string[];
|
|
242
279
|
}
|
|
243
280
|
|
|
244
281
|
// MARK: - Internals
|
|
@@ -254,7 +291,13 @@ const FATAL_SEND_TIMEOUT_MS = 2_000;
|
|
|
254
291
|
const DEFAULT_MAX_CACHE_ITEMS = 30;
|
|
255
292
|
const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
|
|
256
293
|
const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
|
|
294
|
+
/** Started/ended session events waiting on a retry (see Session Outbox). */
|
|
295
|
+
const OFFLINE_SESSIONS_KEY = "@swissknife:crash:sessions";
|
|
296
|
+
/** Cap on queued session events — drop-oldest beyond this. */
|
|
297
|
+
const MAX_PENDING_SESSIONS = 50;
|
|
257
298
|
const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
|
|
299
|
+
/** JS-side install id, only for apps without the native Identity bridge. */
|
|
300
|
+
const INSTALL_ID_KEY = "@swissknife:crash:install_id";
|
|
258
301
|
|
|
259
302
|
// MARK: - Stack Trace Parsing
|
|
260
303
|
|
|
@@ -346,6 +389,8 @@ let _breadcrumbs: RingBuffer<SKCrashBreadcrumb> = new RingBuffer(100);
|
|
|
346
389
|
let _tags: Record<string, string> = {};
|
|
347
390
|
let _extra: Record<string, unknown> = {};
|
|
348
391
|
let _user: SKCrashUser | null = null;
|
|
392
|
+
/** Scope-level fingerprint (configureScope → setFingerprint). */
|
|
393
|
+
let _fingerprint: string[] | null = null;
|
|
349
394
|
let _pendingEvents: SKCrashEvent[] = [];
|
|
350
395
|
/**
|
|
351
396
|
* Events handed to an in-flight POST: already out of `_pendingEvents`, not
|
|
@@ -363,7 +408,9 @@ let _pendingEvents: SKCrashEvent[] = [];
|
|
|
363
408
|
*/
|
|
364
409
|
let _inFlightEvents: Map<string, SKCrashEvent> = new Map();
|
|
365
410
|
let _flushTimer: ReturnType<typeof setTimeout> | null = null;
|
|
366
|
-
let _originalGlobalHandler:
|
|
411
|
+
let _originalGlobalHandler:
|
|
412
|
+
| ((error: unknown, isFatal?: boolean) => void)
|
|
413
|
+
| null = null;
|
|
367
414
|
let _sessionId: string | null = null;
|
|
368
415
|
let _sessionStartTime: number | null = null;
|
|
369
416
|
let _sessionErrorCount = 0;
|
|
@@ -414,8 +461,20 @@ let _screenshotCaptureOverride:
|
|
|
414
461
|
// `Identity.current()` also carries an `anonymousId`, and stamping it into
|
|
415
462
|
// `user.id` would make "affected users" non-zero for every app that never
|
|
416
463
|
// logs in. That both inflates the number and diverges from Analytics, whose
|
|
417
|
-
// `user_id` is the identified subject only. The anonymous id
|
|
418
|
-
// separately
|
|
464
|
+
// `user_id` is the identified subject only. The anonymous id travels
|
|
465
|
+
// separately, as the wire event's `installId` (see below) — the server counts
|
|
466
|
+
// affected users by user id, else install id, without conflating the two.
|
|
467
|
+
|
|
468
|
+
// ## installId — the stable per-install id
|
|
469
|
+
//
|
|
470
|
+
// Most crashes have no identified subject, so the server counts affected
|
|
471
|
+
// users by `installId` when `user.id` is absent. It is the Identity bridge's
|
|
472
|
+
// `anonymousId` (`$SKAnonymousID:<device id>` — the same value native crashes
|
|
473
|
+
// carry on their ingest envelope and `app_users.anonymous_id` stores, so the
|
|
474
|
+
// dashboard can link an anonymous install to its profile). Apps without the
|
|
475
|
+
// native Identity bridge get a random id persisted in AsyncStorage; without
|
|
476
|
+
// AsyncStorage no installId is sent at all, because a per-launch id would
|
|
477
|
+
// count every relaunch as a new user.
|
|
419
478
|
|
|
420
479
|
/**
|
|
421
480
|
* Last resolved identified subject id from the native Identity bridge.
|
|
@@ -424,6 +483,14 @@ let _screenshotCaptureOverride:
|
|
|
424
483
|
* stamped, which is exactly today's behaviour for apps that never log in.
|
|
425
484
|
*/
|
|
426
485
|
let _identityUserId: string | null = null;
|
|
486
|
+
/** Last resolved `Identity.current().anonymousId` (stable per install). */
|
|
487
|
+
let _identityAnonymousId: string | null = null;
|
|
488
|
+
/** AsyncStorage-persisted install id; used only when no Identity bridge. */
|
|
489
|
+
let _jsInstallId: string | null = null;
|
|
490
|
+
/** In-flight `loadJsInstallId`, so a flush racing init can wait for it. */
|
|
491
|
+
let _jsInstallIdLoad: Promise<void> | null = null;
|
|
492
|
+
/** `_jsInstallIdLoad` has settled — flush skips the wait (and its hops). */
|
|
493
|
+
let _jsInstallIdSettled = false;
|
|
427
494
|
/** In-flight read, so N events in a burst share one bridge hop. */
|
|
428
495
|
let _identityRefresh: Promise<void> | null = null;
|
|
429
496
|
/** Monotonic read counter — a superseded read must not clobber a newer one. */
|
|
@@ -436,18 +503,22 @@ let _identityGeneration = 0;
|
|
|
436
503
|
* unreachable and "we did read Identity" would pass vacuously.
|
|
437
504
|
*/
|
|
438
505
|
let _identityResolverOverride:
|
|
439
|
-
| (() => Promise<
|
|
506
|
+
| (() => Promise<IdentitySnapshot>)
|
|
440
507
|
| null
|
|
441
508
|
| undefined;
|
|
442
509
|
|
|
510
|
+
/** The fields of the native `Identity.current()` snapshot this module reads. */
|
|
511
|
+
interface IdentitySnapshot {
|
|
512
|
+
userId?: string | null;
|
|
513
|
+
anonymousId?: string | null;
|
|
514
|
+
}
|
|
515
|
+
|
|
443
516
|
/** Budget for the send-time identity re-resolve. Kept well under
|
|
444
517
|
* FATAL_SEND_TIMEOUT_MS so a slow bridge can never eat the fatal path's
|
|
445
518
|
* one chance to deliver before the process dies. */
|
|
446
519
|
const IDENTITY_RESOLVE_TIMEOUT_MS = 250;
|
|
447
520
|
|
|
448
|
-
function getIdentityResolver():
|
|
449
|
-
| (() => Promise<{ userId?: string | null }>)
|
|
450
|
-
| null {
|
|
521
|
+
function getIdentityResolver(): (() => Promise<IdentitySnapshot>) | null {
|
|
451
522
|
if (_identityResolverOverride !== undefined) {
|
|
452
523
|
return _identityResolverOverride;
|
|
453
524
|
}
|
|
@@ -461,8 +532,7 @@ function getIdentityResolver():
|
|
|
461
532
|
};
|
|
462
533
|
const native = mod.getNativeModule();
|
|
463
534
|
if (typeof native?.identityCurrent !== "function") return null;
|
|
464
|
-
return () =>
|
|
465
|
-
native.identityCurrent!() as Promise<{ userId?: string | null }>;
|
|
535
|
+
return () => native.identityCurrent!() as Promise<IdentitySnapshot>;
|
|
466
536
|
} catch {
|
|
467
537
|
// Identity bridge not linked (bare Expo app, tests, plain Node).
|
|
468
538
|
return null;
|
|
@@ -494,6 +564,11 @@ function startIdentityRead(): Promise<void> {
|
|
|
494
564
|
const userId = snapshot?.userId;
|
|
495
565
|
_identityUserId =
|
|
496
566
|
typeof userId === "string" && userId.length > 0 ? userId : null;
|
|
567
|
+
// Never blanked by a later empty answer: the id is per install.
|
|
568
|
+
const anonymousId = snapshot?.anonymousId;
|
|
569
|
+
if (typeof anonymousId === "string" && anonymousId.length > 0) {
|
|
570
|
+
_identityAnonymousId = anonymousId;
|
|
571
|
+
}
|
|
497
572
|
} catch {
|
|
498
573
|
// Bridge hiccup — keep the last known subject.
|
|
499
574
|
} finally {
|
|
@@ -571,9 +646,76 @@ function mergeIdentityInto(
|
|
|
571
646
|
return { ...(user ?? {}), id };
|
|
572
647
|
}
|
|
573
648
|
|
|
649
|
+
/** Resolve when `p` settles or after `ms`, whichever is first. Never rejects. */
|
|
650
|
+
function withTimeout(p: Promise<void>, ms: number): Promise<void> {
|
|
651
|
+
return new Promise<void>((resolve) => {
|
|
652
|
+
const timer = setTimeout(resolve, ms);
|
|
653
|
+
void p.then(
|
|
654
|
+
() => {
|
|
655
|
+
clearTimeout(timer);
|
|
656
|
+
resolve();
|
|
657
|
+
},
|
|
658
|
+
() => {
|
|
659
|
+
clearTimeout(timer);
|
|
660
|
+
resolve();
|
|
661
|
+
}
|
|
662
|
+
);
|
|
663
|
+
});
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
/**
|
|
667
|
+
* The install id to stamp on outgoing events, or undefined when none is
|
|
668
|
+
* known. The Identity bridge's anonymous id wins; the JS-persisted id is used
|
|
669
|
+
* only when there is no bridge at all — mixing the two on one device (e.g. a
|
|
670
|
+
* slow bridge read) would count that device twice.
|
|
671
|
+
*/
|
|
672
|
+
function resolveInstallId(): string | undefined {
|
|
673
|
+
if (_identityAnonymousId) return _identityAnonymousId;
|
|
674
|
+
if (getIdentityResolver() !== null) return undefined;
|
|
675
|
+
return _jsInstallId ?? undefined;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Load (or mint and persist) the JS-side install id. Only for apps without
|
|
680
|
+
* the Identity bridge; a no-op without AsyncStorage. Never throws.
|
|
681
|
+
*/
|
|
682
|
+
function loadJsInstallId(): Promise<void> {
|
|
683
|
+
_jsInstallIdLoad ??= readOrMintJsInstallId().finally(() => {
|
|
684
|
+
_jsInstallIdSettled = true;
|
|
685
|
+
});
|
|
686
|
+
return _jsInstallIdLoad;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
async function readOrMintJsInstallId(): Promise<void> {
|
|
690
|
+
if (_jsInstallId || getIdentityResolver() !== null) return;
|
|
691
|
+
const storage = getOfflineStorage();
|
|
692
|
+
if (!storage) return;
|
|
693
|
+
try {
|
|
694
|
+
const stored = await storage.getItem(INSTALL_ID_KEY);
|
|
695
|
+
if (stored) {
|
|
696
|
+
_jsInstallId = stored;
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
const minted = generateUUID();
|
|
700
|
+
await storage.setItem(INSTALL_ID_KEY, minted);
|
|
701
|
+
// Only use an id that made it to disk — see the module note above.
|
|
702
|
+
_jsInstallId = minted;
|
|
703
|
+
} catch {
|
|
704
|
+
// Storage hiccup: send no installId rather than a per-launch one.
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
|
|
574
708
|
// MARK: - Pending Queue (memory + best-effort disk mirror)
|
|
575
709
|
|
|
710
|
+
const capturedContexts = new WeakMap<SKCrashEvent, Promise<void>>();
|
|
711
|
+
|
|
576
712
|
function enqueueEvent(event: SKCrashEvent): void {
|
|
713
|
+
event.traceId ??= currentTelemetryTraceId();
|
|
714
|
+
const captured = captureTelemetryContext().then((context) => {
|
|
715
|
+
event.sessionId ??= context.sessionId;
|
|
716
|
+
persistQueue();
|
|
717
|
+
});
|
|
718
|
+
capturedContexts.set(event, captured);
|
|
577
719
|
_pendingEvents.push(event);
|
|
578
720
|
if (_pendingEvents.length > MAX_PENDING_EVENTS) {
|
|
579
721
|
const dropped = _pendingEvents.splice(
|
|
@@ -661,7 +803,10 @@ function persistQueue(): void {
|
|
|
661
803
|
// In-flight events are older than anything pending, so they lead and
|
|
662
804
|
// drop-oldest still trims from the front. Dedupe defensively: a batch
|
|
663
805
|
// mid-requeue can briefly be reachable from both sides.
|
|
664
|
-
const live = dedupeEventsById([
|
|
806
|
+
const live = dedupeEventsById([
|
|
807
|
+
..._inFlightEvents.values(),
|
|
808
|
+
..._pendingEvents,
|
|
809
|
+
]);
|
|
665
810
|
// NB: slice(-0) would return the WHOLE array — guard the zero-cap case.
|
|
666
811
|
const snapshot = eventCap > 0 ? live.slice(-eventCap) : [];
|
|
667
812
|
void (async () => {
|
|
@@ -845,6 +990,20 @@ function clearAmbiguousStreak(): void {
|
|
|
845
990
|
|
|
846
991
|
// MARK: - Session Tracking
|
|
847
992
|
|
|
993
|
+
/**
|
|
994
|
+
* Request headers for every `/api/sdk/errors/*` call. Carries the install id
|
|
995
|
+
* (when known) so the server's per-device rate limit buckets this install
|
|
996
|
+
* separately from every other device of the app.
|
|
997
|
+
*/
|
|
998
|
+
function requestHeaders(apiKey: string): Record<string, string> {
|
|
999
|
+
const installId = resolveInstallId();
|
|
1000
|
+
return {
|
|
1001
|
+
"Content-Type": "application/json",
|
|
1002
|
+
"X-API-Key": apiKey,
|
|
1003
|
+
...(installId ? { "X-SK-Install-Id": installId } : {}),
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
|
|
848
1007
|
interface SessionPayload {
|
|
849
1008
|
sessionId: string;
|
|
850
1009
|
status: "started" | "ended" | "crashed";
|
|
@@ -880,11 +1039,26 @@ function buildSessionPayload(status: SessionPayload["status"]): SessionPayload {
|
|
|
880
1039
|
};
|
|
881
1040
|
}
|
|
882
1041
|
|
|
1042
|
+
/**
|
|
1043
|
+
* Outcome of one session POST. `retryable` covers 429, 5xx and transport
|
|
1044
|
+
* errors — the server (or network) may answer differently in a moment;
|
|
1045
|
+
* any other 4xx is a permanent reject. `retryAfterMs` is the server's
|
|
1046
|
+
* `Retry-After`, when it sent one.
|
|
1047
|
+
*/
|
|
1048
|
+
type SessionSendResult =
|
|
1049
|
+
| { ok: true }
|
|
1050
|
+
| { ok: false; retryable: boolean; retryAfterMs: number | null };
|
|
1051
|
+
|
|
1052
|
+
function parseRetryAfterMs(header: string | null): number | null {
|
|
1053
|
+
const sec = header ? Number(header) : NaN;
|
|
1054
|
+
return Number.isFinite(sec) && sec >= 0 ? sec * 1000 : null;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
883
1057
|
async function postSessionPayload(
|
|
884
1058
|
payload: SessionPayload,
|
|
885
1059
|
timeoutMs?: number
|
|
886
|
-
): Promise<
|
|
887
|
-
if (!_config) return false;
|
|
1060
|
+
): Promise<SessionSendResult> {
|
|
1061
|
+
if (!_config) return { ok: false, retryable: false, retryAfterMs: null };
|
|
888
1062
|
|
|
889
1063
|
const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
|
|
890
1064
|
const url = `${baseURL}/api/sdk/errors/session`;
|
|
@@ -899,22 +1073,107 @@ async function postSessionPayload(
|
|
|
899
1073
|
try {
|
|
900
1074
|
const res = await fetch(url, {
|
|
901
1075
|
method: "POST",
|
|
902
|
-
headers:
|
|
903
|
-
"Content-Type": "application/json",
|
|
904
|
-
"X-API-Key": _config.apiKey,
|
|
905
|
-
},
|
|
1076
|
+
headers: requestHeaders(_config.apiKey),
|
|
906
1077
|
body: JSON.stringify(payload),
|
|
907
1078
|
...(controller ? { signal: controller.signal } : {}),
|
|
908
1079
|
});
|
|
909
|
-
|
|
1080
|
+
if (res.ok) return { ok: true };
|
|
1081
|
+
return {
|
|
1082
|
+
ok: false,
|
|
1083
|
+
retryable: res.status === 429 || res.status >= 500,
|
|
1084
|
+
retryAfterMs: parseRetryAfterMs(res.headers.get("Retry-After")),
|
|
1085
|
+
};
|
|
910
1086
|
} catch (e) {
|
|
911
1087
|
console.warn("[SwissKnife CrashReporting] session event error:", e);
|
|
912
|
-
return false;
|
|
1088
|
+
return { ok: false, retryable: true, retryAfterMs: null };
|
|
913
1089
|
} finally {
|
|
914
1090
|
if (timer) clearTimeout(timer);
|
|
915
1091
|
}
|
|
916
1092
|
}
|
|
917
1093
|
|
|
1094
|
+
// MARK: - Session Outbox
|
|
1095
|
+
//
|
|
1096
|
+
// `started` / `ended` session events used to be fire-and-forget: a 429 or a
|
|
1097
|
+
// 5xx dropped them, and crash-free-session rates quietly lost their
|
|
1098
|
+
// denominator. A failed retryable send now waits here — in order, persisted
|
|
1099
|
+
// to the offline store, capped — and is retried after the server's
|
|
1100
|
+
// `Retry-After` (or an exponential backoff when it sent none). The crashed
|
|
1101
|
+
// session keeps its own dedicated persistence (`OFFLINE_SESSION_KEY`).
|
|
1102
|
+
|
|
1103
|
+
/** Session events awaiting a retry, oldest first. */
|
|
1104
|
+
let _pendingSessions: SessionPayload[] = [];
|
|
1105
|
+
let _sessionRetryTimer: ReturnType<typeof setTimeout> | null = null;
|
|
1106
|
+
let _sessionBackoffMs = BACKOFF_INITIAL_MS;
|
|
1107
|
+
let _sessionDrainInFlight = false;
|
|
1108
|
+
/**
|
|
1109
|
+
* False from `init` until `restorePersistedState` has merged the previous
|
|
1110
|
+
* launch's outbox. Until then this launch must not WRITE `OFFLINE_SESSIONS_KEY`
|
|
1111
|
+
* (it would overwrite the stored outbox before restore reads it) nor drain
|
|
1112
|
+
* (the older events must go first). Restore persists + drains once merged.
|
|
1113
|
+
*/
|
|
1114
|
+
let _sessionsRestored = true;
|
|
1115
|
+
|
|
1116
|
+
function persistPendingSessions(): void {
|
|
1117
|
+
if (!_sessionsRestored) return;
|
|
1118
|
+
const storage = getOfflineStorage();
|
|
1119
|
+
if (!storage) return;
|
|
1120
|
+
const write =
|
|
1121
|
+
_pendingSessions.length === 0
|
|
1122
|
+
? storage.removeItem(OFFLINE_SESSIONS_KEY)
|
|
1123
|
+
: storage.setItem(OFFLINE_SESSIONS_KEY, JSON.stringify(_pendingSessions));
|
|
1124
|
+
void write.catch(() => {});
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
function scheduleSessionRetry(retryAfterMs: number | null): void {
|
|
1128
|
+
const delayMs = retryAfterMs ?? _sessionBackoffMs;
|
|
1129
|
+
_sessionBackoffMs = Math.min(_sessionBackoffMs * 2, BACKOFF_MAX_MS);
|
|
1130
|
+
if (_sessionRetryTimer !== null) clearTimeout(_sessionRetryTimer);
|
|
1131
|
+
_sessionRetryTimer = setTimeout(() => {
|
|
1132
|
+
_sessionRetryTimer = null;
|
|
1133
|
+
void drainPendingSessions();
|
|
1134
|
+
}, delayMs);
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function queueSessionForRetry(
|
|
1138
|
+
payload: SessionPayload,
|
|
1139
|
+
retryAfterMs: number | null
|
|
1140
|
+
): void {
|
|
1141
|
+
_pendingSessions.push(payload);
|
|
1142
|
+
if (_pendingSessions.length > MAX_PENDING_SESSIONS) {
|
|
1143
|
+
_pendingSessions.splice(0, _pendingSessions.length - MAX_PENDING_SESSIONS);
|
|
1144
|
+
}
|
|
1145
|
+
// Before restore has merged the stored outbox, just hold it in memory:
|
|
1146
|
+
// restore persists and drains the merged queue.
|
|
1147
|
+
if (!_sessionsRestored) return;
|
|
1148
|
+
persistPendingSessions();
|
|
1149
|
+
// A drain in flight, or a retry already booked, will pick this one up.
|
|
1150
|
+
if (!_sessionDrainInFlight && _sessionRetryTimer === null) {
|
|
1151
|
+
scheduleSessionRetry(retryAfterMs);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
/** Send queued session events in order until one fails retryably. */
|
|
1156
|
+
async function drainPendingSessions(): Promise<void> {
|
|
1157
|
+
if (_sessionDrainInFlight || !_config || !_sessionsRestored) return;
|
|
1158
|
+
_sessionDrainInFlight = true;
|
|
1159
|
+
try {
|
|
1160
|
+
while (_pendingSessions.length > 0) {
|
|
1161
|
+
const head = _pendingSessions[0];
|
|
1162
|
+
const result = await postSessionPayload(head);
|
|
1163
|
+
if (!result.ok && result.retryable) {
|
|
1164
|
+
scheduleSessionRetry(result.retryAfterMs);
|
|
1165
|
+
return;
|
|
1166
|
+
}
|
|
1167
|
+
// Delivered, or permanently rejected (a retry would only spin).
|
|
1168
|
+
if (_pendingSessions[0] === head) _pendingSessions.shift();
|
|
1169
|
+
_sessionBackoffMs = BACKOFF_INITIAL_MS;
|
|
1170
|
+
persistPendingSessions();
|
|
1171
|
+
}
|
|
1172
|
+
} finally {
|
|
1173
|
+
_sessionDrainInFlight = false;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
|
|
918
1177
|
/**
|
|
919
1178
|
* Deliberately has NO `await` before `postSessionPayload` — not even to
|
|
920
1179
|
* re-resolve the identity. `endSession` nulls `_sessionId` and zeroes the
|
|
@@ -927,7 +1186,18 @@ async function sendSessionEvent(
|
|
|
927
1186
|
status: "started" | "ended" | "crashed"
|
|
928
1187
|
): Promise<void> {
|
|
929
1188
|
if (!_config || !_sessionId) return;
|
|
930
|
-
|
|
1189
|
+
const payload = buildSessionPayload(status);
|
|
1190
|
+
// Something is already waiting on a backoff: queue behind it so the
|
|
1191
|
+
// server still sees `started` before `ended`, and so we do not hammer a
|
|
1192
|
+
// server that just told us to wait.
|
|
1193
|
+
if (_pendingSessions.length > 0 || _sessionDrainInFlight) {
|
|
1194
|
+
queueSessionForRetry(payload, null);
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
const result = await postSessionPayload(payload);
|
|
1198
|
+
if (!result.ok && result.retryable) {
|
|
1199
|
+
queueSessionForRetry(payload, result.retryAfterMs);
|
|
1200
|
+
}
|
|
931
1201
|
}
|
|
932
1202
|
|
|
933
1203
|
function startSession(): void {
|
|
@@ -970,7 +1240,7 @@ async function deliverCrashedSession(): Promise<void> {
|
|
|
970
1240
|
_sessionStartTime = null;
|
|
971
1241
|
_sessionErrorCount = 0;
|
|
972
1242
|
if (!payload) return;
|
|
973
|
-
const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
|
|
1243
|
+
const { ok } = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
|
|
974
1244
|
if (ok) {
|
|
975
1245
|
const storage = getOfflineStorage();
|
|
976
1246
|
if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
|
|
@@ -988,7 +1258,12 @@ function handleAppStateChange(nextState: string): void {
|
|
|
988
1258
|
/** Test seam — see `_nativeCrashModuleOverride` for why. `undefined` =
|
|
989
1259
|
* resolve from react-native. */
|
|
990
1260
|
let _appStateOverride:
|
|
991
|
-
| {
|
|
1261
|
+
| {
|
|
1262
|
+
addEventListener: (
|
|
1263
|
+
e: string,
|
|
1264
|
+
h: (s: string) => void
|
|
1265
|
+
) => { remove: () => void };
|
|
1266
|
+
}
|
|
992
1267
|
| null
|
|
993
1268
|
| undefined;
|
|
994
1269
|
|
|
@@ -996,7 +1271,8 @@ function installAppStateListener(): void {
|
|
|
996
1271
|
if (_appStateSubscription) return; // double-init guard
|
|
997
1272
|
if (_appStateOverride !== undefined) {
|
|
998
1273
|
_appStateSubscription =
|
|
999
|
-
_appStateOverride?.addEventListener("change", handleAppStateChange) ??
|
|
1274
|
+
_appStateOverride?.addEventListener("change", handleAppStateChange) ??
|
|
1275
|
+
null;
|
|
1000
1276
|
return;
|
|
1001
1277
|
}
|
|
1002
1278
|
// AppState is a React Native API. Guard so tests/Node imports don't blow up.
|
|
@@ -1024,13 +1300,48 @@ function installAppStateListener(): void {
|
|
|
1024
1300
|
*/
|
|
1025
1301
|
function restorePersistedState(): void {
|
|
1026
1302
|
const storage = getOfflineStorage();
|
|
1027
|
-
if (!storage)
|
|
1303
|
+
if (!storage) {
|
|
1304
|
+
_sessionsRestored = true;
|
|
1305
|
+
return;
|
|
1306
|
+
}
|
|
1307
|
+
_sessionsRestored = false;
|
|
1028
1308
|
_restorePromise = (async () => {
|
|
1309
|
+
// Read the stored session outbox FIRST, before any other await: nothing
|
|
1310
|
+
// this launch does may replace it before it is merged (see
|
|
1311
|
+
// `_sessionsRestored`).
|
|
1312
|
+
let storedSessions: SessionPayload[] = [];
|
|
1313
|
+
try {
|
|
1314
|
+
const rawSessions = await storage.getItem(OFFLINE_SESSIONS_KEY);
|
|
1315
|
+
if (rawSessions) {
|
|
1316
|
+
const restored = JSON.parse(rawSessions) as SessionPayload[];
|
|
1317
|
+
if (Array.isArray(restored)) {
|
|
1318
|
+
storedSessions = restored.filter(
|
|
1319
|
+
(p) => p && typeof p.sessionId === "string"
|
|
1320
|
+
);
|
|
1321
|
+
}
|
|
1322
|
+
}
|
|
1323
|
+
} catch {
|
|
1324
|
+
// Unreadable outbox: dropped; the merged persist below overwrites it.
|
|
1325
|
+
}
|
|
1326
|
+
// Earlier launch's sessions go first; anything this launch has already
|
|
1327
|
+
// queued stays behind them. Dedupe on (sessionId, status).
|
|
1328
|
+
const seen = new Set<string>();
|
|
1329
|
+
_pendingSessions = [...storedSessions, ..._pendingSessions]
|
|
1330
|
+
.filter((p) => {
|
|
1331
|
+
const k = `${p.sessionId}|${p.status}`;
|
|
1332
|
+
if (seen.has(k)) return false;
|
|
1333
|
+
seen.add(k);
|
|
1334
|
+
return true;
|
|
1335
|
+
})
|
|
1336
|
+
.slice(-MAX_PENDING_SESSIONS);
|
|
1337
|
+
_sessionsRestored = true;
|
|
1338
|
+
persistPendingSessions();
|
|
1339
|
+
|
|
1029
1340
|
try {
|
|
1030
1341
|
const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
|
|
1031
1342
|
if (rawSession) {
|
|
1032
1343
|
const payload = JSON.parse(rawSession) as SessionPayload;
|
|
1033
|
-
if (payload?.sessionId && (await postSessionPayload(payload))) {
|
|
1344
|
+
if (payload?.sessionId && (await postSessionPayload(payload)).ok) {
|
|
1034
1345
|
await storage.removeItem(OFFLINE_SESSION_KEY);
|
|
1035
1346
|
}
|
|
1036
1347
|
}
|
|
@@ -1038,6 +1349,14 @@ function restorePersistedState(): void {
|
|
|
1038
1349
|
// undeliverable this launch — keep for the next one
|
|
1039
1350
|
}
|
|
1040
1351
|
|
|
1352
|
+
if (_pendingSessions.length > 0 && _sessionRetryTimer === null) {
|
|
1353
|
+
try {
|
|
1354
|
+
await drainPendingSessions();
|
|
1355
|
+
} catch {
|
|
1356
|
+
// retried on the next backoff / launch
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1041
1360
|
try {
|
|
1042
1361
|
const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
|
|
1043
1362
|
if (rawShots) {
|
|
@@ -1048,9 +1367,7 @@ function restorePersistedState(): void {
|
|
|
1048
1367
|
if (Array.isArray(shots)) {
|
|
1049
1368
|
_offlineScreenshots = shots.filter(
|
|
1050
1369
|
(s) =>
|
|
1051
|
-
s &&
|
|
1052
|
-
typeof s.eventId === "string" &&
|
|
1053
|
-
typeof s.base64 === "string"
|
|
1370
|
+
s && typeof s.eventId === "string" && typeof s.base64 === "string"
|
|
1054
1371
|
);
|
|
1055
1372
|
}
|
|
1056
1373
|
}
|
|
@@ -1271,7 +1588,9 @@ export function buildStaticContexts(
|
|
|
1271
1588
|
: platform.OS === "android"
|
|
1272
1589
|
? "Android"
|
|
1273
1590
|
: String(platform.OS)),
|
|
1274
|
-
version: String(
|
|
1591
|
+
version: String(
|
|
1592
|
+
constants.Release ?? constants.osVersion ?? platform.Version ?? ""
|
|
1593
|
+
),
|
|
1275
1594
|
};
|
|
1276
1595
|
const device: Record<string, unknown> = {};
|
|
1277
1596
|
if (typeof constants.Model === "string") device.model = constants.Model;
|
|
@@ -1307,6 +1626,15 @@ function getStaticContexts(): Record<string, unknown> {
|
|
|
1307
1626
|
|
|
1308
1627
|
// MARK: - Build Event
|
|
1309
1628
|
|
|
1629
|
+
/** A usable fingerprint: the string entries, or null when none remain. */
|
|
1630
|
+
function normalizeFingerprint(fingerprint: unknown): string[] | null {
|
|
1631
|
+
if (!Array.isArray(fingerprint)) return null;
|
|
1632
|
+
const entries = fingerprint.filter(
|
|
1633
|
+
(entry): entry is string => typeof entry === "string" && entry.length > 0
|
|
1634
|
+
);
|
|
1635
|
+
return entries.length > 0 ? entries : null;
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1310
1638
|
function buildEvent(
|
|
1311
1639
|
level: SKCrashEvent["level"],
|
|
1312
1640
|
partial: Partial<SKCrashEvent> = {}
|
|
@@ -1329,6 +1657,7 @@ function buildEvent(
|
|
|
1329
1657
|
extra: { ..._extra },
|
|
1330
1658
|
user: resolveSubject(),
|
|
1331
1659
|
breadcrumbs: _breadcrumbs.snapshot(),
|
|
1660
|
+
...(_fingerprint ? { fingerprint: [..._fingerprint] } : {}),
|
|
1332
1661
|
...partial,
|
|
1333
1662
|
contexts,
|
|
1334
1663
|
};
|
|
@@ -1340,10 +1669,22 @@ function installGlobalHandler(): void {
|
|
|
1340
1669
|
if (_originalGlobalHandler) return; // double-init guard
|
|
1341
1670
|
// ErrorUtils is a React Native global. We guard with typeof so this module
|
|
1342
1671
|
// can also be imported in plain Node (tests) without blowing up.
|
|
1343
|
-
const ErrorUtils = (
|
|
1672
|
+
const ErrorUtils = (
|
|
1673
|
+
globalThis as {
|
|
1674
|
+
ErrorUtils?: {
|
|
1675
|
+
getGlobalHandler: () => Function;
|
|
1676
|
+
setGlobalHandler: (
|
|
1677
|
+
h: (error: unknown, isFatal?: boolean) => void
|
|
1678
|
+
) => void;
|
|
1679
|
+
};
|
|
1680
|
+
}
|
|
1681
|
+
).ErrorUtils;
|
|
1344
1682
|
if (!ErrorUtils) return;
|
|
1345
1683
|
|
|
1346
|
-
_originalGlobalHandler = ErrorUtils.getGlobalHandler() as (
|
|
1684
|
+
_originalGlobalHandler = ErrorUtils.getGlobalHandler() as (
|
|
1685
|
+
error: unknown,
|
|
1686
|
+
isFatal?: boolean
|
|
1687
|
+
) => void;
|
|
1347
1688
|
ErrorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {
|
|
1348
1689
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
1349
1690
|
const level: SKCrashEvent["level"] = isFatal ? "fatal" : "error";
|
|
@@ -1576,7 +1917,11 @@ function installPromiseRejectionTracking(): void {
|
|
|
1576
1917
|
// Mirror image of the install: only restore what we managed to replace,
|
|
1577
1918
|
// and go through the same non-throwing path.
|
|
1578
1919
|
if (composed) {
|
|
1579
|
-
trySetHostProperty(
|
|
1920
|
+
trySetHostProperty(
|
|
1921
|
+
hermes,
|
|
1922
|
+
"enablePromiseRejectionTracker",
|
|
1923
|
+
engineEnable
|
|
1924
|
+
);
|
|
1580
1925
|
}
|
|
1581
1926
|
original({ allRejections: false, onUnhandled: () => {} });
|
|
1582
1927
|
};
|
|
@@ -1698,6 +2043,22 @@ function installConsoleBreadcrumbs(): void {
|
|
|
1698
2043
|
|
|
1699
2044
|
export const CrashReporting = {
|
|
1700
2045
|
init(config: CrashReportingConfig): void {
|
|
2046
|
+
// An empty key (typically a build-time env var that was not set) can
|
|
2047
|
+
// never authenticate. Same rule as `configure()` (internal/config.ts
|
|
2048
|
+
// assertApiKey), but logged instead of thrown: `init` usually runs in
|
|
2049
|
+
// module scope, where a throw keeps the app from booting. Nothing is
|
|
2050
|
+
// installed and the native crash module is not started, so the native
|
|
2051
|
+
// layer is not wired with the empty key and a later `init` with the real
|
|
2052
|
+
// key works.
|
|
2053
|
+
const apiKey: unknown = config?.apiKey;
|
|
2054
|
+
if (typeof apiKey !== "string" || apiKey.trim() === "") {
|
|
2055
|
+
console.error(
|
|
2056
|
+
`[SwissKnife CrashReporting] init requires a non-empty apiKey (got ${
|
|
2057
|
+
typeof apiKey === "string" ? JSON.stringify(apiKey) : String(apiKey)
|
|
2058
|
+
}); crash reporting is off.`
|
|
2059
|
+
);
|
|
2060
|
+
return;
|
|
2061
|
+
}
|
|
1701
2062
|
// Defaults keep today's behaviour byte-for-byte: every handler is on
|
|
1702
2063
|
// unless the host explicitly opts out. The opt-outs exist for apps whose
|
|
1703
2064
|
// incumbent reporter owns a given global — see each field's doc comment
|
|
@@ -1718,6 +2079,7 @@ export const CrashReporting = {
|
|
|
1718
2079
|
// path re-resolves anyway — this only shortens the window in which an
|
|
1719
2080
|
// early event has to fall back to the send-time pull.
|
|
1720
2081
|
void refreshIdentitySubject();
|
|
2082
|
+
void loadJsInstallId();
|
|
1721
2083
|
// Every global-slot install is best-effort. `initSwissKnife()` is normally
|
|
1722
2084
|
// called in module scope, so anything that throws here takes the host's
|
|
1723
2085
|
// root module down with it and the app never boots (v0.2.3 did exactly
|
|
@@ -1733,8 +2095,8 @@ export const CrashReporting = {
|
|
|
1733
2095
|
if (_config.enableAppStateTracking) installAppStateListener();
|
|
1734
2096
|
|
|
1735
2097
|
// Initialize native crash handler if the native module is linked.
|
|
1736
|
-
// This catches
|
|
1737
|
-
// crashes + system ANRs (Android) that pure JS cannot observe.
|
|
2098
|
+
// This catches signal crashes + uncaught NSExceptions (iOS) and NDK
|
|
2099
|
+
// native crashes + system ANRs (Android) that pure JS cannot observe.
|
|
1738
2100
|
const nativeMod = _config.enableNativeCrashHandler
|
|
1739
2101
|
? getNativeCrashModule()
|
|
1740
2102
|
: null;
|
|
@@ -1743,13 +2105,15 @@ export const CrashReporting = {
|
|
|
1743
2105
|
nativeMod.start({
|
|
1744
2106
|
apiKey: config.apiKey,
|
|
1745
2107
|
serverURL: config.serverURL || "",
|
|
1746
|
-
ingestURL: (config as { ingestURL?: string }).ingestURL,
|
|
1747
2108
|
environment: config.environment || "production",
|
|
1748
2109
|
release: config.release || "",
|
|
1749
2110
|
});
|
|
1750
2111
|
} catch (e) {
|
|
1751
2112
|
// Non-fatal — JS crash reporting still works
|
|
1752
|
-
console.warn(
|
|
2113
|
+
console.warn(
|
|
2114
|
+
"[SwissKnife CrashReporting] native module init failed:",
|
|
2115
|
+
e
|
|
2116
|
+
);
|
|
1753
2117
|
}
|
|
1754
2118
|
}
|
|
1755
2119
|
|
|
@@ -1760,15 +2124,20 @@ export const CrashReporting = {
|
|
|
1760
2124
|
}
|
|
1761
2125
|
},
|
|
1762
2126
|
|
|
1763
|
-
captureException(
|
|
2127
|
+
captureException(
|
|
2128
|
+
error: Error,
|
|
2129
|
+
options?: SKCaptureExceptionOptions
|
|
2130
|
+
): { eventId: string } {
|
|
1764
2131
|
const fallbackId = generateUUID();
|
|
1765
2132
|
if (!_config) return { eventId: fallbackId };
|
|
1766
2133
|
_sessionErrorCount++;
|
|
2134
|
+
const fingerprint = normalizeFingerprint(options?.fingerprint);
|
|
1767
2135
|
let event: SKCrashEvent | null = buildEvent("error", {
|
|
1768
2136
|
exceptionType: error.name,
|
|
1769
2137
|
exceptionValue: error.message,
|
|
1770
2138
|
stacktrace: error.stack ? parseStackTrace(error.stack) : undefined,
|
|
1771
2139
|
tags: options?.tags ? { ..._tags, ...options.tags } : { ..._tags },
|
|
2140
|
+
...(fingerprint ? { fingerprint } : {}),
|
|
1772
2141
|
});
|
|
1773
2142
|
event = applyBeforeSend(event);
|
|
1774
2143
|
if (!event) return { eventId: fallbackId };
|
|
@@ -1828,10 +2197,7 @@ export const CrashReporting = {
|
|
|
1828
2197
|
|
|
1829
2198
|
fetch(url, {
|
|
1830
2199
|
method: "POST",
|
|
1831
|
-
headers:
|
|
1832
|
-
"Content-Type": "application/json",
|
|
1833
|
-
"X-API-Key": _config.apiKey,
|
|
1834
|
-
},
|
|
2200
|
+
headers: requestHeaders(_config.apiKey),
|
|
1835
2201
|
body: JSON.stringify(feedback),
|
|
1836
2202
|
}).catch((e) => {
|
|
1837
2203
|
console.warn("[SwissKnife CrashReporting] feedback error:", e);
|
|
@@ -1872,7 +2238,9 @@ export const CrashReporting = {
|
|
|
1872
2238
|
message: crumb.message,
|
|
1873
2239
|
level: crumb.level,
|
|
1874
2240
|
});
|
|
1875
|
-
} catch {
|
|
2241
|
+
} catch {
|
|
2242
|
+
/* non-fatal */
|
|
2243
|
+
}
|
|
1876
2244
|
}
|
|
1877
2245
|
},
|
|
1878
2246
|
|
|
@@ -1916,7 +2284,9 @@ export const CrashReporting = {
|
|
|
1916
2284
|
if (nativeMod) {
|
|
1917
2285
|
try {
|
|
1918
2286
|
nativeMod.setUser(user);
|
|
1919
|
-
} catch {
|
|
2287
|
+
} catch {
|
|
2288
|
+
/* non-fatal */
|
|
2289
|
+
}
|
|
1920
2290
|
}
|
|
1921
2291
|
},
|
|
1922
2292
|
|
|
@@ -1927,7 +2297,9 @@ export const CrashReporting = {
|
|
|
1927
2297
|
if (nativeMod) {
|
|
1928
2298
|
try {
|
|
1929
2299
|
nativeMod.setTag(key, value);
|
|
1930
|
-
} catch {
|
|
2300
|
+
} catch {
|
|
2301
|
+
/* non-fatal */
|
|
2302
|
+
}
|
|
1931
2303
|
}
|
|
1932
2304
|
},
|
|
1933
2305
|
|
|
@@ -1937,9 +2309,18 @@ export const CrashReporting = {
|
|
|
1937
2309
|
|
|
1938
2310
|
configureScope(callback: (scope: SKCrashScope) => void): void {
|
|
1939
2311
|
callback({
|
|
1940
|
-
setTag: (key, value) => {
|
|
1941
|
-
|
|
1942
|
-
|
|
2312
|
+
setTag: (key, value) => {
|
|
2313
|
+
_tags[key] = value;
|
|
2314
|
+
},
|
|
2315
|
+
setExtra: (key, value) => {
|
|
2316
|
+
_extra[key] = value;
|
|
2317
|
+
},
|
|
2318
|
+
setUser: (user) => {
|
|
2319
|
+
_user = user;
|
|
2320
|
+
},
|
|
2321
|
+
setFingerprint: (fingerprint) => {
|
|
2322
|
+
_fingerprint = normalizeFingerprint(fingerprint);
|
|
2323
|
+
},
|
|
1943
2324
|
});
|
|
1944
2325
|
},
|
|
1945
2326
|
|
|
@@ -1972,11 +2353,18 @@ export const CrashReporting = {
|
|
|
1972
2353
|
// `init` and `init` before `logIn` both end up stamped. Bounded by
|
|
1973
2354
|
// IDENTITY_RESOLVE_TIMEOUT_MS so the fatal path keeps its budget.
|
|
1974
2355
|
await resolveIdentitySubjectNow();
|
|
2356
|
+
// A flush racing `init` waits for the AsyncStorage read, bounded like the
|
|
2357
|
+
// identity pull (no timer when there is nothing in flight).
|
|
2358
|
+
if (_jsInstallIdLoad && !_jsInstallIdSettled) {
|
|
2359
|
+
await withTimeout(_jsInstallIdLoad, IDENTITY_RESOLVE_TIMEOUT_MS);
|
|
2360
|
+
}
|
|
1975
2361
|
|
|
1976
2362
|
// The /api/sdk/errors/event/batch endpoint:
|
|
1977
2363
|
// - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
|
|
1978
2364
|
// - rejects `user: null` (schema marks `user` optional, not nullable)
|
|
1979
2365
|
// Coerce both on the wire so the internal SDK shape stays ergonomic.
|
|
2366
|
+
await Promise.all(batch.map((event) => capturedContexts.get(event)));
|
|
2367
|
+
const installId = resolveInstallId();
|
|
1980
2368
|
const serialized = batch.map((e) => {
|
|
1981
2369
|
const { user: builtUser, ...rest } = e;
|
|
1982
2370
|
// Idempotent: leaves an id that build time already resolved alone.
|
|
@@ -1984,6 +2372,9 @@ export const CrashReporting = {
|
|
|
1984
2372
|
return {
|
|
1985
2373
|
...rest,
|
|
1986
2374
|
...(user ? { user } : {}),
|
|
2375
|
+
// Stamped at send time, like the subject: an event captured before
|
|
2376
|
+
// the bridge first answered still ships with it.
|
|
2377
|
+
...(installId ? { installId } : {}),
|
|
1987
2378
|
timestamp:
|
|
1988
2379
|
typeof e.timestamp === "number"
|
|
1989
2380
|
? new Date(e.timestamp).toISOString()
|
|
@@ -2001,10 +2392,7 @@ export const CrashReporting = {
|
|
|
2001
2392
|
try {
|
|
2002
2393
|
const res = await fetch(url, {
|
|
2003
2394
|
method: "POST",
|
|
2004
|
-
headers:
|
|
2005
|
-
"Content-Type": "application/json",
|
|
2006
|
-
"X-API-Key": _config.apiKey,
|
|
2007
|
-
},
|
|
2395
|
+
headers: requestHeaders(_config.apiKey),
|
|
2008
2396
|
body: JSON.stringify({ events: serialized }),
|
|
2009
2397
|
...(controller ? { signal: controller.signal } : {}),
|
|
2010
2398
|
});
|
|
@@ -2124,6 +2512,7 @@ export const CrashReporting = {
|
|
|
2124
2512
|
_tags = {};
|
|
2125
2513
|
_extra = {};
|
|
2126
2514
|
_user = null;
|
|
2515
|
+
_fingerprint = null;
|
|
2127
2516
|
_pendingEvents = [];
|
|
2128
2517
|
_inFlightEvents = new Map();
|
|
2129
2518
|
if (_flushTimer !== null) {
|
|
@@ -2136,6 +2525,14 @@ export const CrashReporting = {
|
|
|
2136
2525
|
_sessionErrorCount = 0;
|
|
2137
2526
|
_backoffMs = BACKOFF_INITIAL_MS;
|
|
2138
2527
|
_backoffUntil = 0;
|
|
2528
|
+
_pendingSessions = [];
|
|
2529
|
+
if (_sessionRetryTimer !== null) {
|
|
2530
|
+
clearTimeout(_sessionRetryTimer);
|
|
2531
|
+
_sessionRetryTimer = null;
|
|
2532
|
+
}
|
|
2533
|
+
_sessionBackoffMs = BACKOFF_INITIAL_MS;
|
|
2534
|
+
_sessionDrainInFlight = false;
|
|
2535
|
+
_sessionsRestored = true;
|
|
2139
2536
|
clearAmbiguousStreak();
|
|
2140
2537
|
if (_disableRejectionTracking) {
|
|
2141
2538
|
// Teardown is the mirror image of install and can fail the same way —
|
|
@@ -2152,6 +2549,10 @@ export const CrashReporting = {
|
|
|
2152
2549
|
_screenshotCaptureOverride = undefined;
|
|
2153
2550
|
_nativeCrashModuleOverride = undefined;
|
|
2154
2551
|
_identityUserId = null;
|
|
2552
|
+
_identityAnonymousId = null;
|
|
2553
|
+
_jsInstallId = null;
|
|
2554
|
+
_jsInstallIdLoad = null;
|
|
2555
|
+
_jsInstallIdSettled = false;
|
|
2155
2556
|
_identityRefresh = null;
|
|
2156
2557
|
// Bump the generation so a read still in flight cannot land after the
|
|
2157
2558
|
// reset and repopulate the subject the reset just cleared.
|
|
@@ -2195,6 +2596,13 @@ export const CrashReporting = {
|
|
|
2195
2596
|
return _sessionId;
|
|
2196
2597
|
},
|
|
2197
2598
|
|
|
2599
|
+
_snapshotPendingSessions(): Array<{ sessionId: string; status: string }> {
|
|
2600
|
+
return _pendingSessions.map((p) => ({
|
|
2601
|
+
sessionId: p.sessionId,
|
|
2602
|
+
status: p.status,
|
|
2603
|
+
}));
|
|
2604
|
+
},
|
|
2605
|
+
|
|
2198
2606
|
_restorePromiseForTests(): Promise<void> | null {
|
|
2199
2607
|
return _restorePromise;
|
|
2200
2608
|
},
|
|
@@ -2231,13 +2639,11 @@ export const CrashReporting = {
|
|
|
2231
2639
|
* `null` = Identity bridge absent; `undefined` = resolve from react-native.
|
|
2232
2640
|
* Clears the cached subject so the next resolve goes through the seam. */
|
|
2233
2641
|
_setIdentityResolverForTests(
|
|
2234
|
-
resolver:
|
|
2235
|
-
| (() => Promise<{ userId?: string | null }>)
|
|
2236
|
-
| null
|
|
2237
|
-
| undefined
|
|
2642
|
+
resolver: (() => Promise<IdentitySnapshot>) | null | undefined
|
|
2238
2643
|
): void {
|
|
2239
2644
|
_identityResolverOverride = resolver;
|
|
2240
2645
|
_identityUserId = null;
|
|
2646
|
+
_identityAnonymousId = null;
|
|
2241
2647
|
_identityRefresh = null;
|
|
2242
2648
|
_identityGeneration++;
|
|
2243
2649
|
},
|
|
@@ -2276,7 +2682,10 @@ export interface SKErrorBoundaryState {
|
|
|
2276
2682
|
error: Error | null;
|
|
2277
2683
|
}
|
|
2278
2684
|
|
|
2279
|
-
export class SKErrorBoundary extends React.Component<
|
|
2685
|
+
export class SKErrorBoundary extends React.Component<
|
|
2686
|
+
SKErrorBoundaryProps,
|
|
2687
|
+
SKErrorBoundaryState
|
|
2688
|
+
> {
|
|
2280
2689
|
constructor(props: SKErrorBoundaryProps) {
|
|
2281
2690
|
super(props);
|
|
2282
2691
|
this.state = { hasError: false, error: null };
|