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