@app-swiss-knife/react-native-sdk 0.1.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.
Files changed (218) hide show
  1. package/README.md +182 -0
  2. package/SwissKnifePurchases.podspec +40 -0
  3. package/android/build.gradle +89 -0
  4. package/android/gradle.properties +3 -0
  5. package/android/src/main/AndroidManifest.xml +26 -0
  6. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +216 -0
  7. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingPackage.kt +17 -0
  8. package/android/src/main/java/com/swissknife/purchases/Conversions.kt +15 -0
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +371 -0
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +497 -0
  11. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesPackage.kt +25 -0
  12. package/android/vendor/GENERATED.md +10 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +533 -0
  14. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +326 -0
  15. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +296 -0
  16. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +503 -0
  17. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +188 -0
  18. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +204 -0
  19. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +447 -0
  20. package/android/vendor/java/com/appswissknife/context/AppLifecycle.kt +120 -0
  21. package/android/vendor/java/com/appswissknife/context/Clock.kt +70 -0
  22. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +138 -0
  23. package/android/vendor/java/com/appswissknife/context/IDs.kt +55 -0
  24. package/android/vendor/java/com/appswissknife/context/Reachability.kt +145 -0
  25. package/android/vendor/java/com/appswissknife/context/Session.kt +192 -0
  26. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +945 -0
  27. package/android/vendor/java/com/appswissknife/crashreporting/SKScreenshot.kt +201 -0
  28. package/android/vendor/java/com/appswissknife/device/DeviceID.kt +172 -0
  29. package/android/vendor/java/com/appswissknife/diagnostics/SKLog.kt +97 -0
  30. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +495 -0
  31. package/android/vendor/java/com/appswissknife/identity/Identity.kt +522 -0
  32. package/android/vendor/java/com/appswissknife/models/CustomerInfo.kt +67 -0
  33. package/android/vendor/java/com/appswissknife/models/Enums.kt +35 -0
  34. package/android/vendor/java/com/appswissknife/models/Offerings.kt +80 -0
  35. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +89 -0
  36. package/android/vendor/java/com/appswissknife/models/StoreTransaction.kt +17 -0
  37. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +507 -0
  38. package/android/vendor/java/com/appswissknife/net/ExponentialBackoff.kt +69 -0
  39. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +582 -0
  40. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +320 -0
  41. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +219 -0
  42. package/android/vendor/java/com/appswissknife/performance/SKFrameTracker.kt +94 -0
  43. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +428 -0
  44. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +560 -0
  45. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +100 -0
  46. package/android/vendor/java/com/appswissknife/purchases/PriceEnrichmentProvider.kt +36 -0
  47. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +120 -0
  48. package/android/vendor/res/xml/swissknife_data_extraction_rules.xml +20 -0
  49. package/ios/SwissKnifeCrashReporting.m +32 -0
  50. package/ios/SwissKnifeCrashReporting.swift +186 -0
  51. package/ios/SwissKnifeJSON.swift +347 -0
  52. package/ios/SwissKnifePurchases.m +124 -0
  53. package/ios/SwissKnifePurchases.swift +523 -0
  54. package/ios/vendor/GENERATED.md +10 -0
  55. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +488 -0
  56. package/ios/vendor/SwissKnifeiOS/AttributesClient.swift +460 -0
  57. package/ios/vendor/SwissKnifeiOS/Attribution/Attribution.swift +307 -0
  58. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionNetwork.swift +92 -0
  59. package/ios/vendor/SwissKnifeiOS/Attribution/AttributionState.swift +141 -0
  60. package/ios/vendor/SwissKnifeiOS/Context/AppLifecycle.swift +130 -0
  61. package/ios/vendor/SwissKnifeiOS/Context/Clock.swift +100 -0
  62. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +190 -0
  63. package/ios/vendor/SwissKnifeiOS/Context/IDs.swift +64 -0
  64. package/ios/vendor/SwissKnifeiOS/Context/Reachability.swift +121 -0
  65. package/ios/vendor/SwissKnifeiOS/Context/Session.swift +223 -0
  66. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +1287 -0
  67. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKScreenshot.swift +175 -0
  68. package/ios/vendor/SwissKnifeiOS/DeviceID.swift +161 -0
  69. package/ios/vendor/SwissKnifeiOS/Diagnostics/SKLog.swift +128 -0
  70. package/ios/vendor/SwissKnifeiOS/Identity/Identity.swift +323 -0
  71. package/ios/vendor/SwissKnifeiOS/Identity/IdentityNetwork.swift +70 -0
  72. package/ios/vendor/SwissKnifeiOS/Net/BackendHttpClient.swift +329 -0
  73. package/ios/vendor/SwissKnifeiOS/Net/ExponentialBackoff.swift +87 -0
  74. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +681 -0
  75. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +409 -0
  76. package/ios/vendor/SwissKnifeiOS/Performance/SKFrameTracker.swift +89 -0
  77. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +440 -0
  78. package/ios/vendor/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift +87 -0
  79. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +646 -0
  80. package/ios/vendor/SwissKnifeiOS/Services/OfferingsService.swift +458 -0
  81. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +374 -0
  82. package/ios/vendor/SwissKnifeiOS/SwissKnife+Analytics.swift +46 -0
  83. package/ios/vendor/SwissKnifeiOS/SwissKnife+DeviceID.swift +30 -0
  84. package/ios/vendor/SwissKnifeiOS/SwissKnife+Session.swift +47 -0
  85. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +417 -0
  86. package/ios/vendor/SwissKnifeiOS/Types.swift +496 -0
  87. package/lib/commonjs/attribution.js +55 -0
  88. package/lib/commonjs/attribution.js.map +1 -0
  89. package/lib/commonjs/identity.js +126 -0
  90. package/lib/commonjs/identity.js.map +1 -0
  91. package/lib/commonjs/index.js +118 -0
  92. package/lib/commonjs/index.js.map +1 -0
  93. package/lib/commonjs/modules/analytics.js +646 -0
  94. package/lib/commonjs/modules/analytics.js.map +1 -0
  95. package/lib/commonjs/modules/attachments.js +169 -0
  96. package/lib/commonjs/modules/attachments.js.map +1 -0
  97. package/lib/commonjs/modules/crash-reporting.js +1327 -0
  98. package/lib/commonjs/modules/crash-reporting.js.map +1 -0
  99. package/lib/commonjs/modules/ids.js +50 -0
  100. package/lib/commonjs/modules/ids.js.map +1 -0
  101. package/lib/commonjs/modules/log.js +59 -0
  102. package/lib/commonjs/modules/log.js.map +1 -0
  103. package/lib/commonjs/modules/offline-store.js +44 -0
  104. package/lib/commonjs/modules/offline-store.js.map +1 -0
  105. package/lib/commonjs/modules/performance.js +494 -0
  106. package/lib/commonjs/modules/performance.js.map +1 -0
  107. package/lib/commonjs/native/module.js +41 -0
  108. package/lib/commonjs/native/module.js.map +1 -0
  109. package/lib/commonjs/native/spec.js +26 -0
  110. package/lib/commonjs/native/spec.js.map +1 -0
  111. package/lib/commonjs/package.json +1 -0
  112. package/lib/commonjs/purchases.js +194 -0
  113. package/lib/commonjs/purchases.js.map +1 -0
  114. package/lib/commonjs/types.js +236 -0
  115. package/lib/commonjs/types.js.map +1 -0
  116. package/lib/module/attribution.js +51 -0
  117. package/lib/module/attribution.js.map +1 -0
  118. package/lib/module/identity.js +122 -0
  119. package/lib/module/identity.js.map +1 -0
  120. package/lib/module/index.js +36 -0
  121. package/lib/module/index.js.map +1 -0
  122. package/lib/module/modules/analytics.js +642 -0
  123. package/lib/module/modules/analytics.js.map +1 -0
  124. package/lib/module/modules/attachments.js +162 -0
  125. package/lib/module/modules/attachments.js.map +1 -0
  126. package/lib/module/modules/crash-reporting.js +1320 -0
  127. package/lib/module/modules/crash-reporting.js.map +1 -0
  128. package/lib/module/modules/ids.js +44 -0
  129. package/lib/module/modules/ids.js.map +1 -0
  130. package/lib/module/modules/log.js +54 -0
  131. package/lib/module/modules/log.js.map +1 -0
  132. package/lib/module/modules/offline-store.js +39 -0
  133. package/lib/module/modules/offline-store.js.map +1 -0
  134. package/lib/module/modules/performance.js +491 -0
  135. package/lib/module/modules/performance.js.map +1 -0
  136. package/lib/module/native/module.js +34 -0
  137. package/lib/module/native/module.js.map +1 -0
  138. package/lib/module/native/spec.js +22 -0
  139. package/lib/module/native/spec.js.map +1 -0
  140. package/lib/module/package.json +1 -0
  141. package/lib/module/purchases.js +187 -0
  142. package/lib/module/purchases.js.map +1 -0
  143. package/lib/module/types.js +230 -0
  144. package/lib/module/types.js.map +1 -0
  145. package/lib/typescript/commonjs/attribution.d.ts +24 -0
  146. package/lib/typescript/commonjs/attribution.d.ts.map +1 -0
  147. package/lib/typescript/commonjs/identity.d.ts +37 -0
  148. package/lib/typescript/commonjs/identity.d.ts.map +1 -0
  149. package/lib/typescript/commonjs/index.d.ts +15 -0
  150. package/lib/typescript/commonjs/index.d.ts.map +1 -0
  151. package/lib/typescript/commonjs/modules/analytics.d.ts +127 -0
  152. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -0
  153. package/lib/typescript/commonjs/modules/attachments.d.ts +50 -0
  154. package/lib/typescript/commonjs/modules/attachments.d.ts.map +1 -0
  155. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +175 -0
  156. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -0
  157. package/lib/typescript/commonjs/modules/ids.d.ts +17 -0
  158. package/lib/typescript/commonjs/modules/ids.d.ts.map +1 -0
  159. package/lib/typescript/commonjs/modules/log.d.ts +12 -0
  160. package/lib/typescript/commonjs/modules/log.d.ts.map +1 -0
  161. package/lib/typescript/commonjs/modules/offline-store.d.ts +9 -0
  162. package/lib/typescript/commonjs/modules/offline-store.d.ts.map +1 -0
  163. package/lib/typescript/commonjs/modules/performance.d.ts +75 -0
  164. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -0
  165. package/lib/typescript/commonjs/native/module.d.ts +6 -0
  166. package/lib/typescript/commonjs/native/module.d.ts.map +1 -0
  167. package/lib/typescript/commonjs/native/spec.d.ts +119 -0
  168. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -0
  169. package/lib/typescript/commonjs/package.json +1 -0
  170. package/lib/typescript/commonjs/purchases.d.ts +68 -0
  171. package/lib/typescript/commonjs/purchases.d.ts.map +1 -0
  172. package/lib/typescript/commonjs/types.d.ts +384 -0
  173. package/lib/typescript/commonjs/types.d.ts.map +1 -0
  174. package/lib/typescript/module/attribution.d.ts +24 -0
  175. package/lib/typescript/module/attribution.d.ts.map +1 -0
  176. package/lib/typescript/module/identity.d.ts +37 -0
  177. package/lib/typescript/module/identity.d.ts.map +1 -0
  178. package/lib/typescript/module/index.d.ts +15 -0
  179. package/lib/typescript/module/index.d.ts.map +1 -0
  180. package/lib/typescript/module/modules/analytics.d.ts +127 -0
  181. package/lib/typescript/module/modules/analytics.d.ts.map +1 -0
  182. package/lib/typescript/module/modules/attachments.d.ts +50 -0
  183. package/lib/typescript/module/modules/attachments.d.ts.map +1 -0
  184. package/lib/typescript/module/modules/crash-reporting.d.ts +175 -0
  185. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -0
  186. package/lib/typescript/module/modules/ids.d.ts +17 -0
  187. package/lib/typescript/module/modules/ids.d.ts.map +1 -0
  188. package/lib/typescript/module/modules/log.d.ts +12 -0
  189. package/lib/typescript/module/modules/log.d.ts.map +1 -0
  190. package/lib/typescript/module/modules/offline-store.d.ts +9 -0
  191. package/lib/typescript/module/modules/offline-store.d.ts.map +1 -0
  192. package/lib/typescript/module/modules/performance.d.ts +75 -0
  193. package/lib/typescript/module/modules/performance.d.ts.map +1 -0
  194. package/lib/typescript/module/native/module.d.ts +6 -0
  195. package/lib/typescript/module/native/module.d.ts.map +1 -0
  196. package/lib/typescript/module/native/spec.d.ts +119 -0
  197. package/lib/typescript/module/native/spec.d.ts.map +1 -0
  198. package/lib/typescript/module/package.json +1 -0
  199. package/lib/typescript/module/purchases.d.ts +68 -0
  200. package/lib/typescript/module/purchases.d.ts.map +1 -0
  201. package/lib/typescript/module/types.d.ts +384 -0
  202. package/lib/typescript/module/types.d.ts.map +1 -0
  203. package/package.json +115 -0
  204. package/react-native.config.js +23 -0
  205. package/src/attribution.ts +56 -0
  206. package/src/identity.ts +133 -0
  207. package/src/index.ts +54 -0
  208. package/src/modules/analytics.ts +689 -0
  209. package/src/modules/attachments.ts +222 -0
  210. package/src/modules/crash-reporting.ts +1577 -0
  211. package/src/modules/ids.ts +41 -0
  212. package/src/modules/log.ts +56 -0
  213. package/src/modules/offline-store.ts +51 -0
  214. package/src/modules/performance.ts +589 -0
  215. package/src/native/module.ts +47 -0
  216. package/src/native/spec.ts +183 -0
  217. package/src/purchases.ts +214 -0
  218. package/src/types.ts +470 -0
@@ -0,0 +1,1577 @@
1
+ // packages/react-native-sdk/src/modules/crash-reporting.ts
2
+ //
3
+ // Sentry-compatible crash reporting SDK for swiss-knife (React Native).
4
+ // Captures uncaught JS errors, parses stack traces, manages breadcrumbs,
5
+ // and batches events to the swiss-knife error ingestion endpoint.
6
+ //
7
+ // ## Round-D audit note: deliberate JS-side fetch
8
+ //
9
+ // The Round C/D Wave-3 transport unification collapsed every iOS + Android
10
+ // HTTP call onto the unified `BackendHttpClient` (and the IngestClient
11
+ // envelope above it). On the RN side this module continues to call
12
+ // `/api/sdk/errors/event/batch`, `/feedback`, and `/session` directly via
13
+ // `fetch`. This is intentional and load-bearing for two reasons:
14
+ //
15
+ // 1. **JS-only crash capture path.** `installGlobalHandler()` hooks
16
+ // `ErrorUtils.setGlobalHandler` to catch uncaught JS errors. Those
17
+ // events need to ship from JS without round-tripping through a native
18
+ // method the host app may not have linked (the native modules are
19
+ // optional — the bare Expo sample apps do not bundle them).
20
+ //
21
+ // 2. **Existing wire-shape contract.** The serialized payload's
22
+ // ISO-timestamp + optional-not-nullable `user` coercion is asserted
23
+ // across this module's tests and the maestro-app E2E. Bridging
24
+ // through a hypothetical `crashCaptureBatch` spec method would
25
+ // require new native impls on both platforms + spec.ts + tests, well
26
+ // beyond Round-D's "wrap-up the audit" scope.
27
+ //
28
+ // Native crash capture (Mach exceptions, signal crashes, ANR, NDK)
29
+ // already goes through the native `SKCrashReporting` module (see the
30
+ // `getNativeCrashModule()` branch below) — those native-side captures
31
+ // ARE on the unified transport. JS-captured errors stay on this fetch
32
+ // path until a follow-up wave adds a typed bridge method.
33
+
34
+ import React from "react";
35
+
36
+ import { generateUUID } from "./ids";
37
+ import { getOfflineStorage } from "./offline-store";
38
+ import {
39
+ base64ToUint8Array,
40
+ uploadAttachmentWithRetry,
41
+ } from "./attachments";
42
+
43
+ // MARK: - Native Bridge
44
+
45
+ /**
46
+ * Optional native module for crash reporting. If the host app has linked
47
+ * the SwissKnife iOS/Android native crash SDKs, this module delegates
48
+ * init/setUser/addBreadcrumb to the native layer — catching Mach exceptions,
49
+ * signal crashes (iOS), and NDK native crashes (Android) that JS can't see.
50
+ */
51
+ interface SKCrashReportingNative {
52
+ start(config: {
53
+ apiKey: string;
54
+ serverURL: string;
55
+ ingestURL?: string;
56
+ environment: string;
57
+ release: string;
58
+ }): void;
59
+ setUser(user: { id?: string; email?: string; username?: string } | null): void;
60
+ addBreadcrumb(breadcrumb: {
61
+ category?: string;
62
+ message?: string;
63
+ level?: string;
64
+ }): void;
65
+ setTag(key: string, value: string): void;
66
+ /**
67
+ * Wave-2 C1: capture a masked screenshot of the current window. Returns
68
+ * base64 JPEG (no `data:` prefix) or null. Optional — older native SDKs
69
+ * don't implement it, so every call site must feature-detect.
70
+ */
71
+ captureScreenshot?(): Promise<string | null>;
72
+ }
73
+
74
+ function getNativeCrashModule(): SKCrashReportingNative | null {
75
+ try {
76
+ // Dynamic require to avoid vitest/bundler trying to parse react-native Flow code
77
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
78
+ const { NativeModules } = require("react-native");
79
+ const mod = NativeModules?.SKCrashReporting;
80
+ if (mod && typeof mod.start === "function") {
81
+ return mod as SKCrashReportingNative;
82
+ }
83
+ } catch {
84
+ // NativeModules not available (tests, plain Node)
85
+ }
86
+ return null;
87
+ }
88
+
89
+ // MARK: - Types
90
+
91
+ export interface CrashReportingConfig {
92
+ apiKey: string;
93
+ serverURL?: string;
94
+ environment?: string;
95
+ release?: string;
96
+ /** Distribution identifier (e.g. build number). Sent top-level on every
97
+ * event and mirrored into `contexts.app.dist`. */
98
+ dist?: string;
99
+ maxBreadcrumbs?: number;
100
+ enableAutoBreadcrumbs?: boolean;
101
+ /** Called before sending each event. Return null to drop the event. */
102
+ beforeSend?: (event: SKCrashEvent) => SKCrashEvent | null;
103
+ /**
104
+ * Called for EVERY breadcrumb (manual and auto-instrumented) before it is
105
+ * buffered. Return null to drop the crumb; return a (possibly mutated)
106
+ * crumb to keep it. A throwing hook drops the crumb.
107
+ */
108
+ beforeBreadcrumb?: (
109
+ breadcrumb: SKCrashBreadcrumb
110
+ ) => SKCrashBreadcrumb | null;
111
+ /** Error event sample rate (0.0 to 1.0, default 1.0). */
112
+ sampleRate?: number;
113
+ /** Performance transaction sample rate (0.0 to 1.0, default 1.0). */
114
+ tracesSampleRate?: number;
115
+ /**
116
+ * Cap on items persisted to the offline store (events + fatal-path
117
+ * screenshots each count as one item). Drop-oldest. Default 30.
118
+ */
119
+ maxCacheItems?: number;
120
+ /** Attach a synthetic stacktrace (current call stack) to captureMessage
121
+ * events. Default false. */
122
+ attachStacktrace?: boolean;
123
+ /**
124
+ * Capture a masked screenshot via the native bridge on captureException
125
+ * and on the fatal path, and upload it as an event attachment after the
126
+ * event has been delivered. No-op when the native module (or its
127
+ * captureScreenshot method) is absent. Default false.
128
+ */
129
+ attachScreenshot?: boolean;
130
+ }
131
+
132
+ export interface SKCrashBreadcrumb {
133
+ category?: string;
134
+ message?: string;
135
+ data?: Record<string, unknown>;
136
+ level?: string;
137
+ timestamp?: number;
138
+ }
139
+
140
+ export interface SKCrashUser {
141
+ id?: string;
142
+ email?: string;
143
+ username?: string;
144
+ }
145
+
146
+ export interface SKParsedFrame {
147
+ filename?: string;
148
+ function?: string;
149
+ lineno?: number;
150
+ colno?: number;
151
+ inApp: boolean;
152
+ }
153
+
154
+ export interface SKCrashEvent {
155
+ eventId: string;
156
+ timestamp: number;
157
+ level: "debug" | "info" | "warning" | "error" | "fatal";
158
+ message?: string;
159
+ exceptionType?: string;
160
+ exceptionValue?: string;
161
+ stacktrace?: SKParsedFrame[];
162
+ breadcrumbs?: SKCrashBreadcrumb[];
163
+ tags?: Record<string, string>;
164
+ extra?: Record<string, unknown>;
165
+ user?: SKCrashUser | null;
166
+ environment?: string;
167
+ release?: string;
168
+ dist?: string;
169
+ platform: string;
170
+ mechanism?: string;
171
+ /** `false` for events captured by the SDK's global hooks (fatal errors,
172
+ * unhandled promise rejections); unset for manual captures. */
173
+ handled?: boolean;
174
+ contexts?: Record<string, unknown>;
175
+ }
176
+
177
+ // MARK: - Scope
178
+
179
+ interface SKCrashScope {
180
+ setTag: (key: string, value: string) => void;
181
+ setExtra: (key: string, value: unknown) => void;
182
+ setUser: (user: SKCrashUser | null) => void;
183
+ }
184
+
185
+ // MARK: - Internals
186
+
187
+ const FLUSH_DEBOUNCE_MS = 500;
188
+ /** Requeue/offline buffer cap — drop-oldest beyond this. */
189
+ const MAX_PENDING_EVENTS = 100;
190
+ const BACKOFF_INITIAL_MS = 1_000;
191
+ const BACKOFF_MAX_MS = 60_000;
192
+ /** Budget for the direct send attempt racing a fatal crash. */
193
+ const FATAL_SEND_TIMEOUT_MS = 2_000;
194
+ /** Default cap on offline-store items (events + screenshots), drop-oldest. */
195
+ const DEFAULT_MAX_CACHE_ITEMS = 30;
196
+ const OFFLINE_QUEUE_KEY = "@swissknife:crash:queue";
197
+ const OFFLINE_SESSION_KEY = "@swissknife:crash:session";
198
+ const OFFLINE_SCREENSHOTS_KEY = "@swissknife:crash:screenshots";
199
+
200
+ // MARK: - Stack Trace Parsing
201
+
202
+ /**
203
+ * Parse a JS Error stack string into structured frames.
204
+ * Handles both V8/Hermes formats:
205
+ * at functionName (filename.js:line:col)
206
+ * at filename.js:line:col
207
+ */
208
+ export function parseStackTrace(stack: string): SKParsedFrame[] {
209
+ const lines = stack.split("\n");
210
+ const frames: SKParsedFrame[] = [];
211
+
212
+ for (const line of lines) {
213
+ const trimmed = line.trim();
214
+ if (!trimmed || trimmed === "Error") continue;
215
+
216
+ // V8: "at functionName (filename.js:42:10)"
217
+ const atMatch = trimmed.match(/^at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
218
+ if (atMatch) {
219
+ const [, func, filename, lineno, colno] = atMatch;
220
+ frames.push({
221
+ function: func || "<anonymous>",
222
+ filename,
223
+ lineno: parseInt(lineno, 10),
224
+ colno: parseInt(colno, 10),
225
+ inApp: !isThirdParty(filename),
226
+ });
227
+ continue;
228
+ }
229
+
230
+ // Hermes / RN: "functionName@filename.js:42:10"
231
+ const hermetMatch = trimmed.match(/^(.+?)@(.+?):(\d+):(\d+)$/);
232
+ if (hermetMatch) {
233
+ const [, func, filename, lineno, colno] = hermetMatch;
234
+ frames.push({
235
+ function: func || "<anonymous>",
236
+ filename,
237
+ lineno: parseInt(lineno, 10),
238
+ colno: parseInt(colno, 10),
239
+ inApp: !isThirdParty(filename),
240
+ });
241
+ continue;
242
+ }
243
+ }
244
+
245
+ return frames;
246
+ }
247
+
248
+ function isThirdParty(filename?: string): boolean {
249
+ if (!filename) return false;
250
+ return (
251
+ filename.includes("node_modules") ||
252
+ filename.startsWith("native") ||
253
+ filename.includes("[native code]")
254
+ );
255
+ }
256
+
257
+ // MARK: - Ring Buffer
258
+
259
+ class RingBuffer<T> {
260
+ private buffer: T[] = [];
261
+ private readonly capacity: number;
262
+
263
+ constructor(capacity: number) {
264
+ this.capacity = Math.max(1, capacity);
265
+ }
266
+
267
+ append(item: T): void {
268
+ if (this.buffer.length >= this.capacity) {
269
+ this.buffer.shift();
270
+ }
271
+ this.buffer.push(item);
272
+ }
273
+
274
+ snapshot(): T[] {
275
+ return [...this.buffer];
276
+ }
277
+
278
+ clear(): void {
279
+ this.buffer = [];
280
+ }
281
+ }
282
+
283
+ // MARK: - Module State
284
+
285
+ let _config: CrashReportingConfig | null = null;
286
+ let _breadcrumbs: RingBuffer<SKCrashBreadcrumb> = new RingBuffer(100);
287
+ let _tags: Record<string, string> = {};
288
+ let _extra: Record<string, unknown> = {};
289
+ let _user: SKCrashUser | null = null;
290
+ let _pendingEvents: SKCrashEvent[] = [];
291
+ let _flushTimer: ReturnType<typeof setTimeout> | null = null;
292
+ let _originalGlobalHandler: ((error: unknown, isFatal?: boolean) => void) | null = null;
293
+ let _sessionId: string | null = null;
294
+ let _sessionStartTime: number | null = null;
295
+ let _sessionErrorCount = 0;
296
+ let _appStateSubscription: { remove: () => void } | null = null;
297
+ let _originalFetch: typeof fetch | null = null;
298
+ let _originalConsoleWarn: typeof console.warn | null = null;
299
+ let _originalConsoleError: typeof console.error | null = null;
300
+ let _backoffMs = BACKOFF_INITIAL_MS;
301
+ let _backoffUntil = 0;
302
+ let _rejectionTrackingInstalled = false;
303
+ let _disableRejectionTracking: (() => void) | null = null;
304
+ let _cachedContexts: Record<string, unknown> | null = null;
305
+ let _restorePromise: Promise<void> | null = null;
306
+ /** In-memory screenshots keyed by eventId, awaiting event delivery. */
307
+ let _screenshotPromises: Map<string, Promise<string | null>> = new Map();
308
+ /** Fatal-path screenshots mirrored to the offline store for next-launch upload. */
309
+ let _offlineScreenshots: Array<{ eventId: string; base64: string }> = [];
310
+ /** Test seam: `undefined` = resolve from NativeModules; else use override. */
311
+ let _screenshotCaptureOverride:
312
+ | (() => Promise<string | null>)
313
+ | null
314
+ | undefined;
315
+
316
+ // MARK: - Pending Queue (memory + best-effort disk mirror)
317
+
318
+ function enqueueEvent(event: SKCrashEvent): void {
319
+ _pendingEvents.push(event);
320
+ if (_pendingEvents.length > MAX_PENDING_EVENTS) {
321
+ const dropped = _pendingEvents.splice(
322
+ 0,
323
+ _pendingEvents.length - MAX_PENDING_EVENTS
324
+ );
325
+ discardScreenshotsFor(dropped);
326
+ }
327
+ persistQueue();
328
+ }
329
+
330
+ /** Put failed sends back AHEAD of anything captured since; drop-oldest beyond cap. */
331
+ function requeueEvents(events: SKCrashEvent[]): void {
332
+ const merged = [...events, ..._pendingEvents];
333
+ discardScreenshotsFor(merged.slice(0, -MAX_PENDING_EVENTS));
334
+ _pendingEvents = merged.slice(-MAX_PENDING_EVENTS);
335
+ persistQueue();
336
+ }
337
+
338
+ /** Events that will never deliver must not pin their screenshots in memory. */
339
+ function discardScreenshotsFor(dropped: SKCrashEvent[]): void {
340
+ for (const event of dropped) {
341
+ _screenshotPromises.delete(event.eventId);
342
+ }
343
+ }
344
+
345
+ /** Offline-store item cap (events + screenshots), drop-oldest beyond it. */
346
+ function maxCacheItems(): number {
347
+ const configured = _config?.maxCacheItems;
348
+ if (typeof configured === "number" && Number.isFinite(configured)) {
349
+ return Math.max(0, Math.floor(configured));
350
+ }
351
+ return DEFAULT_MAX_CACHE_ITEMS;
352
+ }
353
+
354
+ /**
355
+ * Mirror the pending queue to disk (fire-and-forget) so events survive a
356
+ * process kill and drain on the next init. Waits for the init-time restore
357
+ * to finish first so a fresh capture can't clobber a not-yet-loaded queue.
358
+ *
359
+ * The slice respects `maxCacheItems`: persisted screenshots occupy cache
360
+ * slots too, so the event slice shrinks by however many screenshots are
361
+ * currently stored (newest events win — drop-oldest).
362
+ */
363
+ function persistQueue(): void {
364
+ const storage = getOfflineStorage();
365
+ if (!storage) return;
366
+ const eventCap = Math.max(0, maxCacheItems() - _offlineScreenshots.length);
367
+ // NB: slice(-0) would return the WHOLE array — guard the zero-cap case.
368
+ const snapshot = eventCap > 0 ? _pendingEvents.slice(-eventCap) : [];
369
+ void (async () => {
370
+ try {
371
+ if (_restorePromise) await _restorePromise;
372
+ await storage.setItem(OFFLINE_QUEUE_KEY, JSON.stringify(snapshot));
373
+ } catch {
374
+ // best-effort — memory queue still holds the events
375
+ }
376
+ })();
377
+ }
378
+
379
+ /** Mirror the fatal-path screenshots to disk (fire-and-forget). */
380
+ function persistOfflineScreenshots(): void {
381
+ const storage = getOfflineStorage();
382
+ if (!storage) return;
383
+ const snapshot = [..._offlineScreenshots];
384
+ void (async () => {
385
+ try {
386
+ if (_restorePromise) await _restorePromise;
387
+ await storage.setItem(OFFLINE_SCREENSHOTS_KEY, JSON.stringify(snapshot));
388
+ } catch {
389
+ // best-effort
390
+ }
391
+ })();
392
+ }
393
+
394
+ /** Store a fatal-path screenshot offline; screenshots count as cache items. */
395
+ function addOfflineScreenshot(eventId: string, base64: string): void {
396
+ _offlineScreenshots.push({ eventId, base64 });
397
+ const cap = maxCacheItems();
398
+ if (_offlineScreenshots.length > cap) {
399
+ _offlineScreenshots.splice(0, _offlineScreenshots.length - cap);
400
+ }
401
+ persistOfflineScreenshots();
402
+ // Screenshots take cache slots away from events — re-mirror the queue.
403
+ persistQueue();
404
+ }
405
+
406
+ function removeOfflineScreenshot(eventId: string): void {
407
+ const before = _offlineScreenshots.length;
408
+ _offlineScreenshots = _offlineScreenshots.filter(
409
+ (s) => s.eventId !== eventId
410
+ );
411
+ if (_offlineScreenshots.length !== before) {
412
+ persistOfflineScreenshots();
413
+ persistQueue();
414
+ }
415
+ }
416
+
417
+ // MARK: - Backoff
418
+
419
+ /**
420
+ * Compute the retry delay for a transient failure: `Retry-After` (seconds)
421
+ * when the server sent one, else the current exponential backoff step.
422
+ */
423
+ function applyBackoff(retryAfterHeader: string | null): number {
424
+ const retryAfterSec = retryAfterHeader ? Number(retryAfterHeader) : NaN;
425
+ const delayMs =
426
+ Number.isFinite(retryAfterSec) && retryAfterSec >= 0
427
+ ? retryAfterSec * 1000
428
+ : _backoffMs;
429
+ _backoffUntil = Date.now() + delayMs;
430
+ _backoffMs = Math.min(_backoffMs * 2, BACKOFF_MAX_MS);
431
+ return delayMs;
432
+ }
433
+
434
+ // MARK: - Batch Response
435
+
436
+ interface BatchResultEntry {
437
+ index?: number;
438
+ eventId?: string;
439
+ status?: string;
440
+ reason?: string;
441
+ }
442
+
443
+ /**
444
+ * Parse the batch response `{ accepted, results: [{index, eventId, status}] }`
445
+ * and map 'retryable' entries back to their events (by eventId, falling back
446
+ * to index). Anything else — 'accepted', 'duplicate', 'rejected', a legacy
447
+ * response shape, or an unparseable body on HTTP 200 — is treated as terminal.
448
+ */
449
+ async function extractRetryableEvents(
450
+ res: Response,
451
+ batch: SKCrashEvent[]
452
+ ): Promise<SKCrashEvent[]> {
453
+ let parsed: { results?: BatchResultEntry[] } | null = null;
454
+ try {
455
+ parsed = (await res.json()) as { results?: BatchResultEntry[] };
456
+ } catch {
457
+ return [];
458
+ }
459
+ const results = parsed?.results;
460
+ if (!Array.isArray(results)) return [];
461
+ const retryable: SKCrashEvent[] = [];
462
+ for (const entry of results) {
463
+ if (!entry || entry.status !== "retryable") continue;
464
+ const byId = entry.eventId
465
+ ? batch.find((e) => e.eventId === entry.eventId)
466
+ : undefined;
467
+ const byIndex =
468
+ typeof entry.index === "number" ? batch[entry.index] : undefined;
469
+ const event = byId ?? byIndex;
470
+ if (event && !retryable.includes(event)) retryable.push(event);
471
+ }
472
+ return retryable;
473
+ }
474
+
475
+ // MARK: - Session Tracking
476
+
477
+ interface SessionPayload {
478
+ sessionId: string;
479
+ status: "started" | "ended" | "crashed";
480
+ duration: number;
481
+ errorsCount: number;
482
+ releaseVersion?: string;
483
+ environment?: string;
484
+ userId?: string;
485
+ osName?: string;
486
+ osVersion?: string;
487
+ deviceModel?: string;
488
+ }
489
+
490
+ function buildSessionPayload(status: SessionPayload["status"]): SessionPayload {
491
+ const duration =
492
+ _sessionStartTime !== null ? (Date.now() - _sessionStartTime) / 1000 : 0;
493
+ const contexts = getStaticContexts();
494
+ const os = contexts.os as { name?: string; version?: string } | undefined;
495
+ const device = contexts.device as { model?: string } | undefined;
496
+ return {
497
+ sessionId: _sessionId!,
498
+ status,
499
+ duration,
500
+ errorsCount: _sessionErrorCount,
501
+ releaseVersion: _config?.release,
502
+ environment: _config?.environment,
503
+ ...(_user?.id ? { userId: _user.id } : {}),
504
+ ...(os?.name ? { osName: os.name, osVersion: os.version } : {}),
505
+ ...(device?.model ? { deviceModel: device.model } : {}),
506
+ };
507
+ }
508
+
509
+ async function postSessionPayload(
510
+ payload: SessionPayload,
511
+ timeoutMs?: number
512
+ ): Promise<boolean> {
513
+ if (!_config) return false;
514
+
515
+ const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
516
+ const url = `${baseURL}/api/sdk/errors/session`;
517
+
518
+ let controller: AbortController | null = null;
519
+ let timer: ReturnType<typeof setTimeout> | null = null;
520
+ if (timeoutMs) {
521
+ controller = new AbortController();
522
+ timer = setTimeout(() => controller!.abort(), timeoutMs);
523
+ }
524
+
525
+ try {
526
+ const res = await fetch(url, {
527
+ method: "POST",
528
+ headers: {
529
+ "Content-Type": "application/json",
530
+ "X-API-Key": _config.apiKey,
531
+ },
532
+ body: JSON.stringify(payload),
533
+ ...(controller ? { signal: controller.signal } : {}),
534
+ });
535
+ return res.ok;
536
+ } catch (e) {
537
+ console.warn("[SwissKnife CrashReporting] session event error:", e);
538
+ return false;
539
+ } finally {
540
+ if (timer) clearTimeout(timer);
541
+ }
542
+ }
543
+
544
+ async function sendSessionEvent(
545
+ status: "started" | "ended" | "crashed"
546
+ ): Promise<void> {
547
+ if (!_config || !_sessionId) return;
548
+ await postSessionPayload(buildSessionPayload(status));
549
+ }
550
+
551
+ function startSession(): void {
552
+ _sessionId = generateUUID();
553
+ _sessionStartTime = Date.now();
554
+ _sessionErrorCount = 0;
555
+ void sendSessionEvent("started");
556
+ }
557
+
558
+ /**
559
+ * Send the terminal session event, then clear local session state so a
560
+ * FRESH session starts on the next foreground/init (Sentry semantics —
561
+ * previously the same session id lived for the whole process).
562
+ */
563
+ function endSession(status: "ended" | "crashed"): void {
564
+ if (!_sessionId) return;
565
+ void sendSessionEvent(status);
566
+ _sessionId = null;
567
+ _sessionStartTime = null;
568
+ _sessionErrorCount = 0;
569
+ }
570
+
571
+ /**
572
+ * Persist crashed-session state so the session close survives the dying
573
+ * process and is delivered on next launch (cleared once a send succeeds).
574
+ */
575
+ function persistCrashedSession(): void {
576
+ const storage = getOfflineStorage();
577
+ if (!storage || !_sessionId) return;
578
+ const payload = buildSessionPayload("crashed");
579
+ void storage
580
+ .setItem(OFFLINE_SESSION_KEY, JSON.stringify(payload))
581
+ .catch(() => {});
582
+ }
583
+
584
+ /** Short-timeout direct delivery of the crashed session; clears local state. */
585
+ async function deliverCrashedSession(): Promise<void> {
586
+ const payload = _sessionId ? buildSessionPayload("crashed") : null;
587
+ _sessionId = null;
588
+ _sessionStartTime = null;
589
+ _sessionErrorCount = 0;
590
+ if (!payload) return;
591
+ const ok = await postSessionPayload(payload, FATAL_SEND_TIMEOUT_MS);
592
+ if (ok) {
593
+ const storage = getOfflineStorage();
594
+ if (storage) void storage.removeItem(OFFLINE_SESSION_KEY).catch(() => {});
595
+ }
596
+ }
597
+
598
+ function handleAppStateChange(nextState: string): void {
599
+ if (nextState === "background" || nextState === "inactive") {
600
+ endSession("ended");
601
+ } else if (nextState === "active" && !_sessionId) {
602
+ startSession();
603
+ }
604
+ }
605
+
606
+ function installAppStateListener(): void {
607
+ if (_appStateSubscription) return; // double-init guard
608
+ // AppState is a React Native API. Guard so tests/Node imports don't blow up.
609
+ try {
610
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
611
+ const { AppState } = require("react-native");
612
+ if (AppState && AppState.addEventListener) {
613
+ _appStateSubscription = AppState.addEventListener(
614
+ "change",
615
+ handleAppStateChange
616
+ );
617
+ }
618
+ } catch {
619
+ // react-native not available (tests, plain Node)
620
+ }
621
+ }
622
+
623
+ // MARK: - Offline Restore
624
+
625
+ /**
626
+ * On init: deliver the crashed-session state from a previous launch (if any),
627
+ * then re-load events that never made it out before the last process died.
628
+ * Redelivery after a send-then-die race is safe — the server dedupes on
629
+ * eventId.
630
+ */
631
+ function restorePersistedState(): void {
632
+ const storage = getOfflineStorage();
633
+ if (!storage) return;
634
+ _restorePromise = (async () => {
635
+ try {
636
+ const rawSession = await storage.getItem(OFFLINE_SESSION_KEY);
637
+ if (rawSession) {
638
+ const payload = JSON.parse(rawSession) as SessionPayload;
639
+ if (payload?.sessionId && (await postSessionPayload(payload))) {
640
+ await storage.removeItem(OFFLINE_SESSION_KEY);
641
+ }
642
+ }
643
+ } catch {
644
+ // undeliverable this launch — keep for the next one
645
+ }
646
+
647
+ try {
648
+ const rawShots = await storage.getItem(OFFLINE_SCREENSHOTS_KEY);
649
+ if (rawShots) {
650
+ const shots = JSON.parse(rawShots) as Array<{
651
+ eventId: string;
652
+ base64: string;
653
+ }>;
654
+ if (Array.isArray(shots)) {
655
+ _offlineScreenshots = shots.filter(
656
+ (s) =>
657
+ s &&
658
+ typeof s.eventId === "string" &&
659
+ typeof s.base64 === "string"
660
+ );
661
+ }
662
+ }
663
+ } catch {
664
+ // corrupted screenshot store — drop it rather than fail every launch
665
+ void storage.removeItem(OFFLINE_SCREENSHOTS_KEY).catch(() => {});
666
+ }
667
+
668
+ try {
669
+ const rawQueue = await storage.getItem(OFFLINE_QUEUE_KEY);
670
+ if (rawQueue) {
671
+ const events = JSON.parse(rawQueue) as SKCrashEvent[];
672
+ if (Array.isArray(events) && events.length > 0) {
673
+ const restored = events.filter(
674
+ (e) => e && typeof e.eventId === "string"
675
+ );
676
+ const merged = [...restored, ..._pendingEvents];
677
+ _pendingEvents = merged.slice(-MAX_PENDING_EVENTS);
678
+ scheduledFlush();
679
+ }
680
+ }
681
+ } catch {
682
+ // corrupted queue — drop it rather than fail every launch
683
+ void storage.removeItem(OFFLINE_QUEUE_KEY).catch(() => {});
684
+ }
685
+
686
+ // Screenshots whose event is no longer pending were persisted after a
687
+ // fatal event that DID get delivered before the process died — the
688
+ // server already has the event, so upload the attachment right away.
689
+ // Screenshots for still-pending events upload after the flush succeeds.
690
+ const pendingIds = new Set(_pendingEvents.map((e) => e.eventId));
691
+ const orphaned = _offlineScreenshots
692
+ .filter((s) => !pendingIds.has(s.eventId))
693
+ .map((s) => s.eventId);
694
+ if (orphaned.length > 0) {
695
+ await deliverPendingScreenshots(orphaned);
696
+ }
697
+ })();
698
+ }
699
+
700
+ // MARK: - Flush
701
+
702
+ function scheduledFlush(delayMs: number = FLUSH_DEBOUNCE_MS): void {
703
+ if (_flushTimer !== null) return; // already scheduled
704
+ _flushTimer = setTimeout(() => {
705
+ _flushTimer = null;
706
+ void CrashReporting.flush();
707
+ }, delayMs);
708
+ }
709
+
710
+ // MARK: - Sampling + beforeSend
711
+
712
+ function applyBeforeSend(event: SKCrashEvent): SKCrashEvent | null {
713
+ if (!_config) return event;
714
+ const sampleRate = _config.sampleRate ?? 1.0;
715
+ if (sampleRate < 1.0 && Math.random() > sampleRate) return null;
716
+ if (_config.beforeSend) {
717
+ try {
718
+ // Sentry semantics: null/undefined → drop the event.
719
+ return _config.beforeSend(event) ?? null;
720
+ } catch (e) {
721
+ // Sentry semantics: a throwing beforeSend drops the event (previously
722
+ // the unmodified event was sent, leaking whatever it tried to scrub).
723
+ console.warn(
724
+ "[SwissKnife CrashReporting] beforeSend threw — dropping event:",
725
+ e
726
+ );
727
+ return null;
728
+ }
729
+ }
730
+ return event;
731
+ }
732
+
733
+ // MARK: - Screenshots (wave-2 C2)
734
+
735
+ /**
736
+ * Resolve the native screenshot capture function, if the linked native SDK
737
+ * exposes one. Feature-detected independently of `start` so the capability
738
+ * check exactly matches the contract ("call captureScreenshot() if present").
739
+ */
740
+ function getScreenshotCapture(): (() => Promise<string | null>) | null {
741
+ if (_screenshotCaptureOverride !== undefined) {
742
+ return _screenshotCaptureOverride;
743
+ }
744
+ try {
745
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
746
+ const { NativeModules } = require("react-native");
747
+ const mod = NativeModules?.SKCrashReporting as
748
+ | SKCrashReportingNative
749
+ | undefined;
750
+ if (mod && typeof mod.captureScreenshot === "function") {
751
+ return () => mod.captureScreenshot!();
752
+ }
753
+ } catch {
754
+ // NativeModules not available (tests, plain Node)
755
+ }
756
+ return null;
757
+ }
758
+
759
+ /**
760
+ * Kick a screenshot capture for `eventId` (fire-and-forget). The base64 is
761
+ * held in memory until the event's flush succeeds, then uploaded. On the
762
+ * fatal path (`persist: true`) it is ALSO mirrored to the offline store so
763
+ * the next launch can upload it if this process dies first.
764
+ */
765
+ function maybeCaptureScreenshot(
766
+ eventId: string,
767
+ options?: { persist?: boolean }
768
+ ): void {
769
+ if (_config?.attachScreenshot !== true) return;
770
+ const capture = getScreenshotCapture();
771
+ if (!capture) return; // native module absent → skip silently
772
+
773
+ let promise: Promise<string | null>;
774
+ try {
775
+ promise = Promise.resolve(capture()).then(
776
+ (base64) =>
777
+ typeof base64 === "string" && base64.length > 0 ? base64 : null,
778
+ () => null
779
+ );
780
+ } catch {
781
+ return; // a synchronously-throwing bridge must never break capture
782
+ }
783
+
784
+ _screenshotPromises.set(eventId, promise);
785
+ if (options?.persist) {
786
+ void promise.then((base64) => {
787
+ if (base64) addOfflineScreenshot(eventId, base64);
788
+ });
789
+ }
790
+ }
791
+
792
+ /**
793
+ * Upload the screenshot for a DELIVERED event (fire-and-forget, single
794
+ * retry inside `uploadAttachmentWithRetry`). Never throws; never blocks
795
+ * event delivery — callers invoke it with `void`.
796
+ */
797
+ async function deliverScreenshotForEvent(eventId: string): Promise<void> {
798
+ if (!_config) return;
799
+
800
+ let base64: string | null = null;
801
+ const pending = _screenshotPromises.get(eventId);
802
+ if (pending) {
803
+ _screenshotPromises.delete(eventId);
804
+ try {
805
+ base64 = await pending;
806
+ } catch {
807
+ base64 = null;
808
+ }
809
+ }
810
+ if (!base64) {
811
+ // Restored-from-disk fatal screenshots (previous launch).
812
+ const offline = _offlineScreenshots.find((s) => s.eventId === eventId);
813
+ if (offline) base64 = offline.base64;
814
+ }
815
+ if (!base64) return;
816
+
817
+ try {
818
+ const result = await uploadAttachmentWithRetry({
819
+ serverURL: _config.serverURL || "https://api.swiss-knife.dev",
820
+ apiKey: _config.apiKey,
821
+ eventId,
822
+ kind: "screenshot",
823
+ contentType: "image/jpeg",
824
+ data: base64ToUint8Array(base64),
825
+ // Bypass the breadcrumb-patching fetch wrapper when installed.
826
+ fetchFn: _originalFetch ?? globalThis.fetch,
827
+ });
828
+ // Delivered or permanently rejected — either way the offline copy is
829
+ // done. Only a transient double-failure keeps it for the next launch.
830
+ if (result !== "transient") removeOfflineScreenshot(eventId);
831
+ } catch {
832
+ // fire-and-forget — never propagate
833
+ }
834
+ }
835
+
836
+ /** Sequential upload for a set of just-delivered events. */
837
+ async function deliverPendingScreenshots(eventIds: string[]): Promise<void> {
838
+ for (const eventId of eventIds) {
839
+ await deliverScreenshotForEvent(eventId);
840
+ }
841
+ }
842
+
843
+ // MARK: - Device / OS Contexts
844
+
845
+ interface RNPlatformConstants {
846
+ systemName?: string;
847
+ osVersion?: string;
848
+ Release?: string;
849
+ Model?: string;
850
+ Brand?: string;
851
+ Manufacturer?: string;
852
+ Fingerprint?: string;
853
+ }
854
+
855
+ export interface PlatformLike {
856
+ OS: string;
857
+ Version?: string | number;
858
+ isTesting?: boolean;
859
+ constants?: RNPlatformConstants;
860
+ }
861
+
862
+ /**
863
+ * Derive `contexts.device` / `contexts.os` from react-native's Platform.
864
+ * JS-only — iOS exposes no device model over Platform, so `model` is
865
+ * Android-only; simulator detection uses the Android build fingerprint
866
+ * (with `Platform.isTesting` as the cross-platform fallback).
867
+ */
868
+ export function buildStaticContexts(
869
+ platform: PlatformLike
870
+ ): Record<string, unknown> {
871
+ const constants = platform.constants ?? {};
872
+ const os: Record<string, unknown> = {
873
+ name:
874
+ constants.systemName ??
875
+ (platform.OS === "ios"
876
+ ? "iOS"
877
+ : platform.OS === "android"
878
+ ? "Android"
879
+ : String(platform.OS)),
880
+ version: String(constants.Release ?? constants.osVersion ?? platform.Version ?? ""),
881
+ };
882
+ const device: Record<string, unknown> = {};
883
+ if (typeof constants.Model === "string") device.model = constants.Model;
884
+ if (typeof constants.Manufacturer === "string") {
885
+ device.manufacturer = constants.Manufacturer;
886
+ }
887
+ if (typeof constants.Fingerprint === "string") {
888
+ device.simulator = /generic|emulator|sdk_gphone|vbox/i.test(
889
+ constants.Fingerprint
890
+ );
891
+ } else if (platform.isTesting === true) {
892
+ device.simulator = true;
893
+ }
894
+ return { device, os };
895
+ }
896
+
897
+ /** Cached once — Platform values never change within a process. */
898
+ function getStaticContexts(): Record<string, unknown> {
899
+ if (_cachedContexts) return _cachedContexts;
900
+ let contexts: Record<string, unknown> = {};
901
+ try {
902
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
903
+ const { Platform } = require("react-native");
904
+ if (Platform && typeof Platform.OS === "string") {
905
+ contexts = buildStaticContexts(Platform as PlatformLike);
906
+ }
907
+ } catch {
908
+ // react-native not available (tests, plain Node)
909
+ }
910
+ _cachedContexts = contexts;
911
+ return contexts;
912
+ }
913
+
914
+ // MARK: - Build Event
915
+
916
+ function buildEvent(
917
+ level: SKCrashEvent["level"],
918
+ partial: Partial<SKCrashEvent> = {}
919
+ ): SKCrashEvent {
920
+ const contexts: Record<string, unknown> = { ...getStaticContexts() };
921
+ const app: Record<string, unknown> = {};
922
+ if (_config?.release) app.version = _config.release;
923
+ if (_config?.dist) app.dist = _config.dist;
924
+ if (Object.keys(app).length > 0) contexts.app = app;
925
+ if (partial.contexts) Object.assign(contexts, partial.contexts);
926
+ return {
927
+ eventId: generateUUID(),
928
+ timestamp: Date.now(),
929
+ level,
930
+ platform: "javascript",
931
+ environment: _config?.environment,
932
+ release: _config?.release,
933
+ ...(_config?.dist ? { dist: _config.dist } : {}),
934
+ tags: { ..._tags },
935
+ extra: { ..._extra },
936
+ user: _user,
937
+ breadcrumbs: _breadcrumbs.snapshot(),
938
+ ...partial,
939
+ contexts,
940
+ };
941
+ }
942
+
943
+ // MARK: - Global Error Handler
944
+
945
+ function installGlobalHandler(): void {
946
+ if (_originalGlobalHandler) return; // double-init guard
947
+ // ErrorUtils is a React Native global. We guard with typeof so this module
948
+ // can also be imported in plain Node (tests) without blowing up.
949
+ const ErrorUtils = (globalThis as { ErrorUtils?: { getGlobalHandler: () => Function; setGlobalHandler: (h: (error: unknown, isFatal?: boolean) => void) => void } }).ErrorUtils;
950
+ if (!ErrorUtils) return;
951
+
952
+ _originalGlobalHandler = ErrorUtils.getGlobalHandler() as (error: unknown, isFatal?: boolean) => void;
953
+ ErrorUtils.setGlobalHandler((error: unknown, isFatal?: boolean) => {
954
+ const err = error instanceof Error ? error : new Error(String(error));
955
+ const level: SKCrashEvent["level"] = isFatal ? "fatal" : "error";
956
+ _sessionErrorCount++;
957
+ let event: SKCrashEvent | null = buildEvent(level, {
958
+ exceptionType: err.name,
959
+ exceptionValue: err.message,
960
+ stacktrace: err.stack ? parseStackTrace(err.stack) : undefined,
961
+ mechanism: isFatal ? "onerror" : "generic",
962
+ handled: false,
963
+ });
964
+ event = applyBeforeSend(event);
965
+ if (event) {
966
+ // Enqueue hits the disk mirror too, so a dying process can
967
+ // re-deliver on next launch even if the send below never lands.
968
+ enqueueEvent(event);
969
+ // Fatal-path screenshots persist to the offline store so the next
970
+ // launch can upload them if this process dies before the POST.
971
+ maybeCaptureScreenshot(event.eventId, { persist: isFatal === true });
972
+ }
973
+
974
+ if (isFatal) {
975
+ // Persist crashed-session state first, then race short-timeout direct
976
+ // sends (event batch + session close) against process death.
977
+ persistCrashedSession();
978
+ if (event) {
979
+ void CrashReporting.flush({ timeoutMs: FATAL_SEND_TIMEOUT_MS });
980
+ }
981
+ void deliverCrashedSession();
982
+ } else if (event) {
983
+ // Can't debounce — the app may be about to unwind.
984
+ void CrashReporting.flush();
985
+ }
986
+
987
+ _originalGlobalHandler?.(error, isFatal);
988
+ });
989
+ }
990
+
991
+ // MARK: - Unhandled Promise Rejections
992
+
993
+ function stringifyRejectionReason(reason: unknown): string {
994
+ if (typeof reason === "string") return reason;
995
+ try {
996
+ return JSON.stringify(reason) ?? String(reason);
997
+ } catch {
998
+ return String(reason);
999
+ }
1000
+ }
1001
+
1002
+ function onUnhandledRejection(_id: number, rejection: unknown): void {
1003
+ if (!_config) return;
1004
+ const err = rejection instanceof Error ? rejection : null;
1005
+ _sessionErrorCount++;
1006
+ let event: SKCrashEvent | null = buildEvent("error", {
1007
+ exceptionType: err ? err.name : "UnhandledRejection",
1008
+ exceptionValue: err
1009
+ ? err.message
1010
+ : `Non-Error promise rejection: ${stringifyRejectionReason(rejection)}`,
1011
+ // Non-Error reasons carry no useful stack — omit so the server
1012
+ // fingerprints on type+value instead of SDK-internal frames.
1013
+ stacktrace: err?.stack ? parseStackTrace(err.stack) : undefined,
1014
+ mechanism: "onunhandledrejection",
1015
+ handled: false,
1016
+ });
1017
+ event = applyBeforeSend(event);
1018
+ if (event) {
1019
+ enqueueEvent(event);
1020
+ scheduledFlush();
1021
+ }
1022
+ }
1023
+
1024
+ function installPromiseRejectionTracking(): void {
1025
+ if (_rejectionTrackingInstalled) return; // double-init guard
1026
+
1027
+ const options = {
1028
+ allRejections: true,
1029
+ onUnhandled: onUnhandledRejection,
1030
+ onHandled: () => {},
1031
+ };
1032
+
1033
+ // Hermes ships its own tracker hook.
1034
+ const hermes = (
1035
+ globalThis as {
1036
+ HermesInternal?: {
1037
+ enablePromiseRejectionTracker?: (opts: {
1038
+ allRejections: boolean;
1039
+ onUnhandled: (id: number, rejection: unknown) => void;
1040
+ onHandled?: (id: number) => void;
1041
+ }) => void;
1042
+ };
1043
+ }
1044
+ ).HermesInternal;
1045
+ if (hermes?.enablePromiseRejectionTracker) {
1046
+ hermes.enablePromiseRejectionTracker(options);
1047
+ _rejectionTrackingInstalled = true;
1048
+ _disableRejectionTracking = () => {
1049
+ hermes.enablePromiseRejectionTracker?.({
1050
+ allRejections: false,
1051
+ onUnhandled: () => {},
1052
+ });
1053
+ };
1054
+ return;
1055
+ }
1056
+
1057
+ // JSC fallback: the same rejection-tracking module React Native core wires
1058
+ // up for its LogBox warnings (bundled with RN via the `promise` polyfill).
1059
+ try {
1060
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
1061
+ const tracking = require("promise/setimmediate/rejection-tracking") as {
1062
+ enable: (opts: typeof options) => void;
1063
+ disable: () => void;
1064
+ };
1065
+ tracking.enable(options);
1066
+ _rejectionTrackingInstalled = true;
1067
+ _disableRejectionTracking = () => tracking.disable();
1068
+ } catch {
1069
+ // promise polyfill unavailable (plain Node/tests) — no rejection capture
1070
+ }
1071
+ }
1072
+
1073
+ // MARK: - Auto-Breadcrumbs: HTTP
1074
+
1075
+ function installHTTPBreadcrumbs(): void {
1076
+ if (typeof globalThis.fetch !== "function") return;
1077
+ // Don't double-patch if performance module already patched it
1078
+ if (_originalFetch) return;
1079
+
1080
+ _originalFetch = globalThis.fetch;
1081
+
1082
+ globalThis.fetch = async function breadcrumbFetch(
1083
+ input: RequestInfo | URL,
1084
+ init?: RequestInit
1085
+ ): Promise<Response> {
1086
+ const url =
1087
+ typeof input === "string"
1088
+ ? input
1089
+ : input instanceof URL
1090
+ ? input.toString()
1091
+ : input.url;
1092
+ const method =
1093
+ init?.method?.toUpperCase() ??
1094
+ (input instanceof Request ? input.method : "GET");
1095
+ const startTime = Date.now();
1096
+
1097
+ try {
1098
+ const response = await _originalFetch!(input, init);
1099
+ CrashReporting.addBreadcrumb({
1100
+ category: "http",
1101
+ message: `${method} ${url}`,
1102
+ data: {
1103
+ method,
1104
+ url,
1105
+ status_code: String(response.status),
1106
+ duration_ms: String(Date.now() - startTime),
1107
+ },
1108
+ level: response.ok ? "info" : "warning",
1109
+ });
1110
+ return response;
1111
+ } catch (error) {
1112
+ CrashReporting.addBreadcrumb({
1113
+ category: "http",
1114
+ message: `${method} ${url} (failed)`,
1115
+ data: { method, url, error: String(error) },
1116
+ level: "error",
1117
+ });
1118
+ throw error;
1119
+ }
1120
+ } as typeof fetch;
1121
+ }
1122
+
1123
+ // MARK: - Auto-Breadcrumbs: Console
1124
+
1125
+ function installConsoleBreadcrumbs(): void {
1126
+ // Double-init guard — re-patching would make the wrappers call themselves
1127
+ // through the reassigned _originalConsole* refs (infinite recursion).
1128
+ if (_originalConsoleWarn) return;
1129
+ _originalConsoleWarn = console.warn;
1130
+ console.warn = (...args: unknown[]) => {
1131
+ CrashReporting.addBreadcrumb({
1132
+ category: "console",
1133
+ message: args.map(String).join(" "),
1134
+ level: "warning",
1135
+ });
1136
+ _originalConsoleWarn!.apply(console, args);
1137
+ };
1138
+
1139
+ _originalConsoleError = console.error;
1140
+ console.error = (...args: unknown[]) => {
1141
+ CrashReporting.addBreadcrumb({
1142
+ category: "console",
1143
+ message: args.map(String).join(" "),
1144
+ level: "error",
1145
+ });
1146
+ _originalConsoleError!.apply(console, args);
1147
+ };
1148
+ }
1149
+
1150
+ // MARK: - Main Export
1151
+
1152
+ export const CrashReporting = {
1153
+ init(config: CrashReportingConfig): void {
1154
+ _config = {
1155
+ maxBreadcrumbs: 100,
1156
+ environment: "production",
1157
+ enableAutoBreadcrumbs: true,
1158
+ ...config,
1159
+ };
1160
+ _breadcrumbs = new RingBuffer(_config.maxBreadcrumbs!);
1161
+ installGlobalHandler();
1162
+ installPromiseRejectionTracking();
1163
+ restorePersistedState();
1164
+ startSession();
1165
+ installAppStateListener();
1166
+
1167
+ // Initialize native crash handler if the native module is linked.
1168
+ // This catches Mach exceptions + signal crashes (iOS) and NDK native
1169
+ // crashes + system ANRs (Android) that pure JS cannot observe.
1170
+ const nativeMod = getNativeCrashModule();
1171
+ if (nativeMod) {
1172
+ try {
1173
+ nativeMod.start({
1174
+ apiKey: config.apiKey,
1175
+ serverURL: config.serverURL || "",
1176
+ ingestURL: (config as { ingestURL?: string }).ingestURL,
1177
+ environment: config.environment || "production",
1178
+ release: config.release || "",
1179
+ });
1180
+ } catch (e) {
1181
+ // Non-fatal — JS crash reporting still works
1182
+ console.warn("[SwissKnife CrashReporting] native module init failed:", e);
1183
+ }
1184
+ }
1185
+
1186
+ // Install automatic breadcrumbs
1187
+ if (_config.enableAutoBreadcrumbs) {
1188
+ installHTTPBreadcrumbs();
1189
+ installConsoleBreadcrumbs();
1190
+ }
1191
+ },
1192
+
1193
+ captureException(error: Error, options?: { tags?: Record<string, string> }): { eventId: string } {
1194
+ const fallbackId = generateUUID();
1195
+ if (!_config) return { eventId: fallbackId };
1196
+ _sessionErrorCount++;
1197
+ let event: SKCrashEvent | null = buildEvent("error", {
1198
+ exceptionType: error.name,
1199
+ exceptionValue: error.message,
1200
+ stacktrace: error.stack ? parseStackTrace(error.stack) : undefined,
1201
+ tags: options?.tags ? { ..._tags, ...options.tags } : { ..._tags },
1202
+ });
1203
+ event = applyBeforeSend(event);
1204
+ if (!event) return { eventId: fallbackId };
1205
+ enqueueEvent(event);
1206
+ maybeCaptureScreenshot(event.eventId);
1207
+ scheduledFlush();
1208
+ return { eventId: event.eventId };
1209
+ },
1210
+
1211
+ captureEvent(partial: Partial<SKCrashEvent>): { eventId: string } {
1212
+ const fallbackId = generateUUID();
1213
+ if (!_config) return { eventId: fallbackId };
1214
+ let event: SKCrashEvent | null = buildEvent(
1215
+ partial.level ?? "error",
1216
+ partial
1217
+ );
1218
+ event = applyBeforeSend(event);
1219
+ if (!event) return { eventId: fallbackId };
1220
+ enqueueEvent(event);
1221
+ scheduledFlush();
1222
+ return { eventId: event.eventId };
1223
+ },
1224
+
1225
+ captureMessage(
1226
+ message: string,
1227
+ level: "debug" | "info" | "warning" | "error" | "fatal" = "info"
1228
+ ): void {
1229
+ if (!_config) return;
1230
+ const partial: Partial<SKCrashEvent> = { message };
1231
+ if (_config.attachStacktrace === true) {
1232
+ // Synthetic stacktrace: the current call stack, minus the SDK's own
1233
+ // frame(s), so the top frame is the captureMessage call site.
1234
+ const syntheticStack = new Error(message).stack;
1235
+ if (syntheticStack) {
1236
+ const frames = parseStackTrace(syntheticStack).filter(
1237
+ (frame) => !frame.filename?.includes("crash-reporting")
1238
+ );
1239
+ if (frames.length > 0) partial.stacktrace = frames;
1240
+ }
1241
+ }
1242
+ let event: SKCrashEvent | null = buildEvent(level, partial);
1243
+ event = applyBeforeSend(event);
1244
+ if (!event) return;
1245
+ enqueueEvent(event);
1246
+ scheduledFlush();
1247
+ },
1248
+
1249
+ captureUserFeedback(feedback: {
1250
+ eventId: string;
1251
+ name?: string;
1252
+ email?: string;
1253
+ comments: string;
1254
+ }): void {
1255
+ if (!_config) return;
1256
+ const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
1257
+ const url = `${baseURL}/api/sdk/errors/feedback`;
1258
+
1259
+ fetch(url, {
1260
+ method: "POST",
1261
+ headers: {
1262
+ "Content-Type": "application/json",
1263
+ "X-API-Key": _config.apiKey,
1264
+ },
1265
+ body: JSON.stringify(feedback),
1266
+ }).catch((e) => {
1267
+ console.warn("[SwissKnife CrashReporting] feedback error:", e);
1268
+ });
1269
+ },
1270
+
1271
+ addBreadcrumb(breadcrumb: SKCrashBreadcrumb): void {
1272
+ let crumb: SKCrashBreadcrumb | null = {
1273
+ ...breadcrumb,
1274
+ timestamp: Date.now(),
1275
+ };
1276
+ // beforeBreadcrumb applies to EVERY crumb — manual calls and the
1277
+ // auto-instrumented http/console/navigation crumbs all route through
1278
+ // here. null (or a throw) drops the crumb entirely, including the
1279
+ // native-layer forward below.
1280
+ const hook = _config?.beforeBreadcrumb;
1281
+ if (hook) {
1282
+ try {
1283
+ crumb = hook(crumb) ?? null;
1284
+ } catch (e) {
1285
+ // Use the UNPATCHED warn — the console auto-breadcrumb wrapper
1286
+ // routes back through addBreadcrumb and would recurse forever.
1287
+ (_originalConsoleWarn ?? console.warn)(
1288
+ "[SwissKnife CrashReporting] beforeBreadcrumb threw — dropping breadcrumb:",
1289
+ e
1290
+ );
1291
+ crumb = null;
1292
+ }
1293
+ }
1294
+ if (!crumb) return;
1295
+ _breadcrumbs.append(crumb);
1296
+ // Forward to native layer for crash-time breadcrumbs
1297
+ const nativeMod = getNativeCrashModule();
1298
+ if (nativeMod) {
1299
+ try {
1300
+ nativeMod.addBreadcrumb({
1301
+ category: crumb.category,
1302
+ message: crumb.message,
1303
+ level: crumb.level,
1304
+ });
1305
+ } catch { /* non-fatal */ }
1306
+ }
1307
+ },
1308
+
1309
+ setUser(user: SKCrashUser | null): void {
1310
+ _user = user;
1311
+ // Forward to native layer for crash-time user context
1312
+ const nativeMod = getNativeCrashModule();
1313
+ if (nativeMod) {
1314
+ try {
1315
+ nativeMod.setUser(user);
1316
+ } catch { /* non-fatal */ }
1317
+ }
1318
+ },
1319
+
1320
+ setTag(key: string, value: string): void {
1321
+ _tags[key] = value;
1322
+ // Forward to native layer for crash-time tag context
1323
+ const nativeMod = getNativeCrashModule();
1324
+ if (nativeMod) {
1325
+ try {
1326
+ nativeMod.setTag(key, value);
1327
+ } catch { /* non-fatal */ }
1328
+ }
1329
+ },
1330
+
1331
+ setExtra(key: string, value: unknown): void {
1332
+ _extra[key] = value;
1333
+ },
1334
+
1335
+ configureScope(callback: (scope: SKCrashScope) => void): void {
1336
+ callback({
1337
+ setTag: (key, value) => { _tags[key] = value; },
1338
+ setExtra: (key, value) => { _extra[key] = value; },
1339
+ setUser: (user) => { _user = user; },
1340
+ });
1341
+ },
1342
+
1343
+ async flush(options?: { timeoutMs?: number }): Promise<void> {
1344
+ if (_pendingEvents.length === 0 || !_config) return;
1345
+
1346
+ // Respect an active backoff window (fatal sends bypass it — that's the
1347
+ // last chance to deliver before the process dies).
1348
+ const now = Date.now();
1349
+ if (!options?.timeoutMs && now < _backoffUntil) {
1350
+ scheduledFlush(_backoffUntil - now);
1351
+ return;
1352
+ }
1353
+
1354
+ const batch = [..._pendingEvents];
1355
+ _pendingEvents = [];
1356
+
1357
+ const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
1358
+ const url = `${baseURL}/api/sdk/errors/event/batch`;
1359
+
1360
+ // The /api/sdk/errors/event/batch endpoint:
1361
+ // - expects `timestamp` as an ISO string (SDK builds it as Date.now() number)
1362
+ // - rejects `user: null` (schema marks `user` optional, not nullable)
1363
+ // Coerce both on the wire so the internal SDK shape stays ergonomic.
1364
+ const serialized = batch.map((e) => {
1365
+ const { user, ...rest } = e;
1366
+ return {
1367
+ ...rest,
1368
+ ...(user ? { user } : {}),
1369
+ timestamp:
1370
+ typeof e.timestamp === "number"
1371
+ ? new Date(e.timestamp).toISOString()
1372
+ : e.timestamp,
1373
+ };
1374
+ });
1375
+
1376
+ let controller: AbortController | null = null;
1377
+ let timer: ReturnType<typeof setTimeout> | null = null;
1378
+ if (options?.timeoutMs) {
1379
+ controller = new AbortController();
1380
+ timer = setTimeout(() => controller!.abort(), options.timeoutMs);
1381
+ }
1382
+
1383
+ try {
1384
+ const res = await fetch(url, {
1385
+ method: "POST",
1386
+ headers: {
1387
+ "Content-Type": "application/json",
1388
+ "X-API-Key": _config.apiKey,
1389
+ },
1390
+ body: JSON.stringify({ events: serialized }),
1391
+ ...(controller ? { signal: controller.signal } : {}),
1392
+ });
1393
+
1394
+ if (res.ok) {
1395
+ _backoffMs = BACKOFF_INITIAL_MS;
1396
+ _backoffUntil = 0;
1397
+ // Per-event statuses: requeue ONLY 'retryable' (transient server
1398
+ // failure); 'accepted'/'duplicate'/'rejected' are terminal.
1399
+ const retryable = await extractRetryableEvents(res, batch);
1400
+ if (retryable.length > 0) {
1401
+ requeueEvents(retryable);
1402
+ scheduledFlush();
1403
+ } else {
1404
+ persistQueue();
1405
+ }
1406
+ // Screenshot attachments upload only AFTER their event has been
1407
+ // delivered, fire-and-forget — never blocks or fails the flush.
1408
+ const retryableIds = new Set(retryable.map((e) => e.eventId));
1409
+ const deliveredIds = batch
1410
+ .map((e) => e.eventId)
1411
+ .filter((id) => !retryableIds.has(id));
1412
+ void deliverPendingScreenshots(deliveredIds);
1413
+ return;
1414
+ }
1415
+
1416
+ if (res.status === 429 || res.status >= 500) {
1417
+ // Whole-request transient failure — requeue everything with
1418
+ // exponential backoff, honoring Retry-After when present.
1419
+ const delayMs = applyBackoff(res.headers.get("Retry-After"));
1420
+ requeueEvents(batch);
1421
+ if (!options?.timeoutMs) scheduledFlush(delayMs);
1422
+ return;
1423
+ }
1424
+
1425
+ // Other 4xx = permanent (validation) — drop the batch, log once.
1426
+ const body = await res.text().catch(() => "");
1427
+ console.warn(
1428
+ `[SwissKnife CrashReporting] flush rejected: HTTP ${res.status} body=${body.slice(0, 200)}`
1429
+ );
1430
+ // Dropped events will never be delivered — discard their screenshots.
1431
+ for (const e of batch) {
1432
+ _screenshotPromises.delete(e.eventId);
1433
+ removeOfflineScreenshot(e.eventId);
1434
+ }
1435
+ persistQueue();
1436
+ } catch (e) {
1437
+ console.warn("[SwissKnife CrashReporting] flush error:", e);
1438
+ const delayMs = applyBackoff(null);
1439
+ requeueEvents(batch);
1440
+ if (!options?.timeoutMs) scheduledFlush(delayMs);
1441
+ } finally {
1442
+ if (timer) clearTimeout(timer);
1443
+ }
1444
+ },
1445
+
1446
+ // MARK: - Test Hooks
1447
+
1448
+ _reset(): void {
1449
+ _config = null;
1450
+ _breadcrumbs = new RingBuffer(100);
1451
+ _tags = {};
1452
+ _extra = {};
1453
+ _user = null;
1454
+ _pendingEvents = [];
1455
+ if (_flushTimer !== null) {
1456
+ clearTimeout(_flushTimer);
1457
+ _flushTimer = null;
1458
+ }
1459
+ _originalGlobalHandler = null;
1460
+ _sessionId = null;
1461
+ _sessionStartTime = null;
1462
+ _sessionErrorCount = 0;
1463
+ _backoffMs = BACKOFF_INITIAL_MS;
1464
+ _backoffUntil = 0;
1465
+ if (_disableRejectionTracking) {
1466
+ _disableRejectionTracking();
1467
+ _disableRejectionTracking = null;
1468
+ }
1469
+ _rejectionTrackingInstalled = false;
1470
+ _cachedContexts = null;
1471
+ _restorePromise = null;
1472
+ _screenshotPromises = new Map();
1473
+ _offlineScreenshots = [];
1474
+ _screenshotCaptureOverride = undefined;
1475
+ if (_appStateSubscription) {
1476
+ _appStateSubscription.remove();
1477
+ _appStateSubscription = null;
1478
+ }
1479
+ // Restore patched globals
1480
+ if (_originalFetch) {
1481
+ globalThis.fetch = _originalFetch;
1482
+ _originalFetch = null;
1483
+ }
1484
+ if (_originalConsoleWarn) {
1485
+ console.warn = _originalConsoleWarn;
1486
+ _originalConsoleWarn = null;
1487
+ }
1488
+ if (_originalConsoleError) {
1489
+ console.error = _originalConsoleError;
1490
+ _originalConsoleError = null;
1491
+ }
1492
+ },
1493
+
1494
+ _snapshotBreadcrumbs(): SKCrashBreadcrumb[] {
1495
+ return _breadcrumbs.snapshot();
1496
+ },
1497
+
1498
+ _snapshotPendingEvents(): SKCrashEvent[] {
1499
+ return [..._pendingEvents];
1500
+ },
1501
+
1502
+ _snapshotBackoff(): { backoffMs: number; backoffUntil: number } {
1503
+ return { backoffMs: _backoffMs, backoffUntil: _backoffUntil };
1504
+ },
1505
+
1506
+ _snapshotSessionId(): string | null {
1507
+ return _sessionId;
1508
+ },
1509
+
1510
+ _restorePromiseForTests(): Promise<void> | null {
1511
+ return _restorePromise;
1512
+ },
1513
+
1514
+ /** Test seam: override native screenshot capture (offline-store pattern).
1515
+ * `null` = native absent; `undefined` = resolve from NativeModules. */
1516
+ _setScreenshotCaptureForTests(
1517
+ fn: (() => Promise<string | null>) | null | undefined
1518
+ ): void {
1519
+ _screenshotCaptureOverride = fn;
1520
+ },
1521
+
1522
+ _snapshotOfflineScreenshots(): Array<{ eventId: string; base64: string }> {
1523
+ return [..._offlineScreenshots];
1524
+ },
1525
+
1526
+ _pendingScreenshotCountForTests(): number {
1527
+ return _screenshotPromises.size;
1528
+ },
1529
+
1530
+ _simulateAppState(nextState: string): void {
1531
+ handleAppStateChange(nextState);
1532
+ },
1533
+ };
1534
+
1535
+ // MARK: - React Error Boundary
1536
+
1537
+ export interface SKErrorBoundaryProps {
1538
+ children: React.ReactNode;
1539
+ fallback?: React.ReactNode;
1540
+ onError?: (error: Error, info: React.ErrorInfo) => void;
1541
+ }
1542
+
1543
+ export interface SKErrorBoundaryState {
1544
+ hasError: boolean;
1545
+ error: Error | null;
1546
+ }
1547
+
1548
+ export class SKErrorBoundary extends React.Component<SKErrorBoundaryProps, SKErrorBoundaryState> {
1549
+ constructor(props: SKErrorBoundaryProps) {
1550
+ super(props);
1551
+ this.state = { hasError: false, error: null };
1552
+ }
1553
+
1554
+ static getDerivedStateFromError(error: Error): SKErrorBoundaryState {
1555
+ return { hasError: true, error };
1556
+ }
1557
+
1558
+ componentDidCatch(error: Error, info: React.ErrorInfo): void {
1559
+ CrashReporting.captureException(error, {
1560
+ tags: { mechanism: "react.error_boundary" },
1561
+ });
1562
+ CrashReporting.addBreadcrumb({
1563
+ category: "react",
1564
+ message: "Error boundary caught an error",
1565
+ data: { componentStack: info.componentStack ?? undefined },
1566
+ level: "error",
1567
+ });
1568
+ this.props.onError?.(error, info);
1569
+ }
1570
+
1571
+ render(): React.ReactNode {
1572
+ if (this.state.hasError) {
1573
+ return this.props.fallback ?? null;
1574
+ }
1575
+ return this.props.children;
1576
+ }
1577
+ }