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