@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,589 @@
1
+ // packages/react-native-sdk/src/modules/performance.ts
2
+ //
3
+ // Sentry-compatible performance monitoring SDK for swiss-knife (React Native).
4
+ // Provides Transaction/Span tracking with automatic navigation and HTTP
5
+ // fetch instrumentation.
6
+ //
7
+ // ## Round-D audit note: deliberate JS-side fetch
8
+ //
9
+ // Same rationale as `crash-reporting.ts` — transactions captured purely
10
+ // in JS (via `fetch` patches + auto-instrumented spans) ship directly
11
+ // to `/api/sdk/errors/transaction` without a typed bridge round-trip.
12
+ // Native-side performance hooks (cold-start, app-resume, ANR-adjacent
13
+ // stalls) already go through the unified transport on iOS + Android.
14
+ // Migrating the JS path through a `performanceCaptureTransaction` spec
15
+ // method is a follow-up wave; Round-D's scope ended at iOS/Android.
16
+
17
+ // MARK: - Types
18
+
19
+ export interface PerformanceConfig {
20
+ apiKey: string;
21
+ serverURL?: string;
22
+ environment?: string;
23
+ release?: string;
24
+ enableAutoHTTP?: boolean;
25
+ /** Transaction sample rate (0.0 to 1.0, default 1.0). */
26
+ tracesSampleRate?: number;
27
+ /**
28
+ * Per-transaction sampler, called at `startTransaction` time. Overrides
29
+ * `tracesSampleRate` for that transaction. The returned rate is clamped
30
+ * to 0..1; a non-finite return value or a throw falls back to
31
+ * `tracesSampleRate`.
32
+ */
33
+ tracesSampler?: (context: { name: string; op?: string }) => number;
34
+ }
35
+
36
+ /** Stall aggregation attached to the transaction payload as `measurements`. */
37
+ export interface SKStallMeasurements {
38
+ stallCount: number;
39
+ stallTotalMs: number;
40
+ stallLongestMs: number;
41
+ }
42
+
43
+ export interface SKTransaction {
44
+ traceId: string;
45
+ spanId: string;
46
+ name: string;
47
+ op: string;
48
+ startChild(op: string, description?: string): SKSpan;
49
+ finish(status?: string): void;
50
+ setTag(key: string, value: string): void;
51
+ setData(key: string, value: unknown): void;
52
+ }
53
+
54
+ export interface SKSpan {
55
+ spanId: string;
56
+ parentSpanId: string;
57
+ op: string;
58
+ description?: string;
59
+ startChild(op: string, description?: string): SKSpan;
60
+ finish(status?: string): void;
61
+ setTag(key: string, value: string): void;
62
+ setData(key: string, value: unknown): void;
63
+ }
64
+
65
+ // MARK: - Internals
66
+ // Post-#136 audit: id helpers used to live inline here and in
67
+ // `analytics.ts`. They have been centralized in `./ids.ts` so future
68
+ // callers can import rather than copy-paste.
69
+
70
+ import { generateTraceId, generateSpanId } from "./ids";
71
+ import { CrashReporting } from "./crash-reporting";
72
+
73
+ // MARK: - Stall Tracking (wave-2 C6)
74
+ //
75
+ // While at least one transaction is open, a 50ms interval timer measures
76
+ // event-loop drift: if a tick arrives more than 100ms later than scheduled,
77
+ // the JS thread stalled. Each stall is aggregated into EVERY currently-open
78
+ // transaction (a blocked event loop stalls them all). The timer runs ONLY
79
+ // while transactions are open — zero overhead otherwise.
80
+
81
+ const STALL_TICK_INTERVAL_MS = 50;
82
+ const STALL_DRIFT_THRESHOLD_MS = 100;
83
+
84
+ let _stallTimer: ReturnType<typeof setInterval> | null = null;
85
+ let _stallLastTick = 0;
86
+ const _openTransactions = new Set<TransactionImpl>();
87
+
88
+ function registerOpenTransaction(tx: TransactionImpl): void {
89
+ _openTransactions.add(tx);
90
+ if (_stallTimer === null) {
91
+ _stallLastTick = Date.now();
92
+ _stallTimer = setInterval(() => {
93
+ recordStallTick(Date.now());
94
+ }, STALL_TICK_INTERVAL_MS);
95
+ }
96
+ }
97
+
98
+ function unregisterOpenTransaction(tx: TransactionImpl): void {
99
+ _openTransactions.delete(tx);
100
+ if (_openTransactions.size === 0 && _stallTimer !== null) {
101
+ clearInterval(_stallTimer);
102
+ _stallTimer = null;
103
+ }
104
+ }
105
+
106
+ /** Tick handler, split out so tests can drive it with explicit clocks. */
107
+ function recordStallTick(now: number): void {
108
+ const drift = now - _stallLastTick - STALL_TICK_INTERVAL_MS;
109
+ _stallLastTick = now;
110
+ if (drift <= STALL_DRIFT_THRESHOLD_MS) return;
111
+ for (const tx of _openTransactions) {
112
+ tx._recordStall(drift);
113
+ }
114
+ }
115
+
116
+ // MARK: - Span Implementation
117
+
118
+ interface SpanPayload {
119
+ spanId: string;
120
+ parentSpanId: string;
121
+ op: string;
122
+ description?: string;
123
+ startTimestamp: string;
124
+ endTimestamp: string;
125
+ status: string;
126
+ tags?: Record<string, string>;
127
+ data?: Record<string, unknown>;
128
+ }
129
+
130
+ class SpanImpl implements SKSpan {
131
+ readonly spanId: string;
132
+ readonly parentSpanId: string;
133
+ readonly op: string;
134
+ readonly description?: string;
135
+
136
+ private startTime: Date;
137
+ private endTime: Date | null = null;
138
+ private status = "ok";
139
+ private tags: Record<string, string> = {};
140
+ private _data: Record<string, unknown> = {};
141
+ private children: SpanImpl[] = [];
142
+
143
+ constructor(op: string, description: string | undefined, parentSpanId: string) {
144
+ this.spanId = generateSpanId();
145
+ this.parentSpanId = parentSpanId;
146
+ this.op = op;
147
+ this.description = description;
148
+ this.startTime = new Date();
149
+ }
150
+
151
+ startChild(op: string, description?: string): SKSpan {
152
+ const child = new SpanImpl(op, description, this.spanId);
153
+ this.children.push(child);
154
+ return child;
155
+ }
156
+
157
+ finish(status = "ok"): void {
158
+ if (this.endTime) return; // already finished
159
+ this.endTime = new Date();
160
+ this.status = status;
161
+ }
162
+
163
+ setTag(key: string, value: string): void {
164
+ this.tags[key] = value;
165
+ }
166
+
167
+ setData(key: string, value: unknown): void {
168
+ this._data[key] = value;
169
+ }
170
+
171
+ _toPayload(): SpanPayload {
172
+ const end = this.endTime ?? new Date();
173
+ const payload: SpanPayload = {
174
+ spanId: this.spanId,
175
+ parentSpanId: this.parentSpanId,
176
+ op: this.op,
177
+ startTimestamp: this.startTime.toISOString(),
178
+ endTimestamp: end.toISOString(),
179
+ status: this.status,
180
+ };
181
+ if (this.description) payload.description = this.description;
182
+ if (Object.keys(this.tags).length > 0) payload.tags = this.tags;
183
+ if (Object.keys(this._data).length > 0) payload.data = this._data;
184
+ return payload;
185
+ }
186
+
187
+ _allSpans(): SpanImpl[] {
188
+ const result: SpanImpl[] = [this];
189
+ for (const child of this.children) {
190
+ result.push(...child._allSpans());
191
+ }
192
+ return result;
193
+ }
194
+ }
195
+
196
+ // MARK: - Transaction Implementation
197
+
198
+ class TransactionImpl implements SKTransaction {
199
+ readonly traceId: string;
200
+ readonly spanId: string;
201
+ readonly name: string;
202
+ readonly op: string;
203
+
204
+ private startTime: Date;
205
+ private endTime: Date | null = null;
206
+ private status = "ok";
207
+ private tags: Record<string, string> = {};
208
+ private _data: Record<string, unknown> = {};
209
+ private spans: SpanImpl[] = [];
210
+ private stalls: SKStallMeasurements = {
211
+ stallCount: 0,
212
+ stallTotalMs: 0,
213
+ stallLongestMs: 0,
214
+ };
215
+
216
+ constructor(name: string, op: string) {
217
+ this.traceId = generateTraceId();
218
+ this.spanId = generateSpanId();
219
+ this.name = name;
220
+ this.op = op;
221
+ this.startTime = new Date();
222
+ // Stall tracking runs for every real (non-sampled-out) transaction,
223
+ // including the navigation-tracker ones constructed directly.
224
+ registerOpenTransaction(this);
225
+ }
226
+
227
+ /** Called by the stall timer while this transaction is open. */
228
+ _recordStall(driftMs: number): void {
229
+ const drift = Math.round(driftMs);
230
+ this.stalls.stallCount += 1;
231
+ this.stalls.stallTotalMs += drift;
232
+ if (drift > this.stalls.stallLongestMs) {
233
+ this.stalls.stallLongestMs = drift;
234
+ }
235
+ }
236
+
237
+ startChild(op: string, description?: string): SKSpan {
238
+ const span = new SpanImpl(op, description, this.spanId);
239
+ this.spans.push(span);
240
+ return span;
241
+ }
242
+
243
+ finish(status = "ok"): void {
244
+ if (this.endTime) return; // already finished
245
+ this.endTime = new Date();
246
+ this.status = status;
247
+
248
+ // Stall timer stops when the last open transaction finishes.
249
+ unregisterOpenTransaction(this);
250
+
251
+ // Clear active transaction reference
252
+ if (_activeTransaction === this) {
253
+ _activeTransaction = null;
254
+ }
255
+
256
+ // Auto-finish any unfinished child spans
257
+ for (const span of this._allChildSpans()) {
258
+ span.finish("ok");
259
+ }
260
+
261
+ // Queue for the debounced send
262
+ enqueueTransaction(this);
263
+ }
264
+
265
+ setTag(key: string, value: string): void {
266
+ this.tags[key] = value;
267
+ }
268
+
269
+ setData(key: string, value: unknown): void {
270
+ this._data[key] = value;
271
+ }
272
+
273
+ _toPayload(): Record<string, unknown> {
274
+ const end = this.endTime ?? new Date();
275
+ const childPayloads = this._allChildSpans().map((s) => s._toPayload());
276
+
277
+ const payload: Record<string, unknown> = {
278
+ traceId: this.traceId,
279
+ name: this.name,
280
+ op: this.op,
281
+ startTimestamp: this.startTime.toISOString(),
282
+ endTimestamp: end.toISOString(),
283
+ status: this.status,
284
+ spans: childPayloads,
285
+ release: _config?.release,
286
+ environment: _config?.environment ?? "production",
287
+ measurements: { ...this.stalls },
288
+ contexts: {
289
+ os: { name: "React Native" },
290
+ device: {},
291
+ },
292
+ };
293
+
294
+ if (Object.keys(this.tags).length > 0) payload.tags = this.tags;
295
+
296
+ return payload;
297
+ }
298
+
299
+ _allChildSpans(): SpanImpl[] {
300
+ const result: SpanImpl[] = [];
301
+ for (const span of this.spans) {
302
+ result.push(...span._allSpans());
303
+ }
304
+ return result;
305
+ }
306
+ }
307
+
308
+ // MARK: - Module State
309
+
310
+ // No-op transaction (returned when sampling drops a transaction)
311
+ const noopSpan: SKSpan = {
312
+ spanId: "", parentSpanId: "", op: "",
313
+ startChild() { return noopSpan; }, finish() {}, setTag() {}, setData() {},
314
+ };
315
+ const noopTransaction: SKTransaction = {
316
+ traceId: "", spanId: "", name: "", op: "",
317
+ startChild() { return noopSpan; }, finish() {}, setTag() {}, setData() {},
318
+ };
319
+
320
+ let _config: PerformanceConfig | null = null;
321
+ let _originalFetch: typeof fetch | null = null;
322
+ let _activeTransaction: TransactionImpl | null = null;
323
+ let _txQueue: TransactionImpl[] = [];
324
+ let _txFlushTimer: ReturnType<typeof setTimeout> | null = null;
325
+
326
+ // MARK: - Sampling
327
+
328
+ /**
329
+ * Effective sample rate for one transaction: `tracesSampler` (clamped 0..1)
330
+ * when configured and well-behaved, else `tracesSampleRate` (default 1.0).
331
+ */
332
+ function resolveSampleRate(name: string, op?: string): number {
333
+ const fallback = _config?.tracesSampleRate ?? 1.0;
334
+ const sampler = _config?.tracesSampler;
335
+ if (!sampler) return fallback;
336
+ try {
337
+ const rate = sampler({ name, op });
338
+ if (typeof rate !== "number" || !Number.isFinite(rate)) return fallback;
339
+ return Math.min(1, Math.max(0, rate));
340
+ } catch (e) {
341
+ console.warn(
342
+ "[SwissKnife Performance] tracesSampler threw — falling back to tracesSampleRate:",
343
+ e
344
+ );
345
+ return fallback;
346
+ }
347
+ }
348
+
349
+ // MARK: - Send
350
+
351
+ const TX_FLUSH_DEBOUNCE_MS = 500;
352
+
353
+ /** Debounce finished transactions like error events — one wakeup per burst. */
354
+ function enqueueTransaction(transaction: TransactionImpl): void {
355
+ if (!_config) return;
356
+ _txQueue.push(transaction);
357
+ if (_txFlushTimer !== null) return;
358
+ _txFlushTimer = setTimeout(() => {
359
+ _txFlushTimer = null;
360
+ void flushTransactions();
361
+ }, TX_FLUSH_DEBOUNCE_MS);
362
+ }
363
+
364
+ // No batch endpoint exists for transactions server-side, so the debounced
365
+ // queue drains serially over the single-transaction endpoint (one request
366
+ // in flight at a time instead of a POST per finish()).
367
+ async function flushTransactions(): Promise<void> {
368
+ if (!_config || _txQueue.length === 0) return;
369
+
370
+ const batch = _txQueue;
371
+ _txQueue = [];
372
+
373
+ const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
374
+ const url = `${baseURL}/api/sdk/errors/transaction`;
375
+ // Use original fetch if we've patched it
376
+ const fetchFn = _originalFetch ?? fetch;
377
+
378
+ for (const transaction of batch) {
379
+ try {
380
+ const res = await fetchFn(url, {
381
+ method: "POST",
382
+ headers: {
383
+ "Content-Type": "application/json",
384
+ "X-API-Key": _config.apiKey,
385
+ },
386
+ body: JSON.stringify(transaction._toPayload()),
387
+ });
388
+
389
+ if (!res.ok) {
390
+ console.warn(
391
+ `[SwissKnife Performance] send failed: HTTP ${res.status}`
392
+ );
393
+ }
394
+ } catch (e) {
395
+ console.warn("[SwissKnife Performance] send error:", e);
396
+ }
397
+ }
398
+ }
399
+
400
+ // MARK: - Auto HTTP Instrumentation
401
+
402
+ function installFetchInstrumentation(): void {
403
+ if (typeof globalThis.fetch !== "function") return;
404
+
405
+ _originalFetch = globalThis.fetch;
406
+
407
+ globalThis.fetch = async function patchedFetch(
408
+ input: RequestInfo | URL,
409
+ init?: RequestInit
410
+ ): Promise<Response> {
411
+ const method =
412
+ init?.method?.toUpperCase() ??
413
+ (input instanceof Request ? input.method : "GET");
414
+ const urlStr =
415
+ typeof input === "string"
416
+ ? input
417
+ : input instanceof URL
418
+ ? input.toString()
419
+ : input.url;
420
+
421
+ const tx = Performance.startTransaction(
422
+ `${method} ${new URL(urlStr, "http://localhost").pathname}`,
423
+ "http.client"
424
+ );
425
+ tx.setData("url", urlStr);
426
+ tx.setData("method", method);
427
+
428
+ // Inject trace propagation headers if there's an active transaction
429
+ const traceHeaders = Performance.traceHeaders();
430
+ if (Object.keys(traceHeaders).length > 0) {
431
+ const existingHeaders = init?.headers ?? {};
432
+ const mergedHeaders = {
433
+ ...(existingHeaders instanceof Headers
434
+ ? Object.fromEntries(existingHeaders.entries())
435
+ : Array.isArray(existingHeaders)
436
+ ? Object.fromEntries(existingHeaders)
437
+ : existingHeaders),
438
+ ...traceHeaders,
439
+ };
440
+ init = { ...init, headers: mergedHeaders };
441
+ }
442
+
443
+ try {
444
+ const response = await _originalFetch!(input, init);
445
+ tx.setData("status_code", response.status);
446
+ tx.finish(response.ok ? "ok" : "internal_error");
447
+ return response;
448
+ } catch (error) {
449
+ tx.finish("internal_error");
450
+ throw error;
451
+ }
452
+ } as typeof fetch;
453
+ }
454
+
455
+ // MARK: - React Navigation Integration
456
+
457
+ /**
458
+ * Creates an onStateChange handler for React Navigation that automatically
459
+ * tracks screen transitions as transactions.
460
+ *
461
+ * Usage:
462
+ * ```
463
+ * const onStateChange = Performance.createNavigationTracker();
464
+ * <NavigationContainer onStateChange={onStateChange}>
465
+ * ```
466
+ */
467
+ function createNavigationTracker(): (state: unknown) => void {
468
+ let currentRoute: string | null = null;
469
+ let currentTransaction: TransactionImpl | null = null;
470
+
471
+ function getActiveRouteName(state: unknown): string | null {
472
+ if (!state || typeof state !== "object") return null;
473
+ const s = state as { index?: number; routes?: Array<{ name: string; state?: unknown }> };
474
+ if (!s.routes || s.index === undefined) return null;
475
+ const route = s.routes[s.index];
476
+ if (!route) return null;
477
+ // If the route has a nested state, recurse
478
+ if (route.state) {
479
+ return getActiveRouteName(route.state) ?? route.name;
480
+ }
481
+ return route.name;
482
+ }
483
+
484
+ return (state: unknown) => {
485
+ const routeName = getActiveRouteName(state);
486
+ if (!routeName || routeName === currentRoute) return;
487
+
488
+ // Finish previous screen transaction
489
+ if (currentTransaction) {
490
+ currentTransaction.finish("ok");
491
+ }
492
+
493
+ // Route changes are also crash-reporting breadcrumbs (Sentry parity) —
494
+ // the ring buffer is a safe no-op when CrashReporting isn't initialized.
495
+ CrashReporting.addBreadcrumb({
496
+ category: "navigation",
497
+ message: routeName,
498
+ data: { ...(currentRoute ? { from: currentRoute } : {}), to: routeName },
499
+ level: "info",
500
+ });
501
+
502
+ currentRoute = routeName;
503
+ currentTransaction = new TransactionImpl(routeName, "navigation");
504
+ };
505
+ }
506
+
507
+ // MARK: - Main Export
508
+
509
+ export const Performance = {
510
+ init(config: PerformanceConfig): void {
511
+ _config = {
512
+ environment: "production",
513
+ enableAutoHTTP: false,
514
+ ...config,
515
+ };
516
+
517
+ if (_config.enableAutoHTTP) {
518
+ installFetchInstrumentation();
519
+ }
520
+ },
521
+
522
+ startTransaction(name: string, op: string): SKTransaction {
523
+ const rate = resolveSampleRate(name, op);
524
+ if (rate <= 0) return noopTransaction;
525
+ if (rate < 1.0 && Math.random() > rate) return noopTransaction;
526
+ const tx = new TransactionImpl(name, op);
527
+ _activeTransaction = tx;
528
+ return tx;
529
+ },
530
+
531
+ /**
532
+ * Returns the current trace propagation headers for the active transaction.
533
+ * Add these to outbound HTTP requests to correlate spans across services.
534
+ */
535
+ traceHeaders(): Record<string, string> {
536
+ if (!_activeTransaction) return {};
537
+ const sampled = (_config?.tracesSampleRate ?? 1.0) > 0 ? "1" : "0";
538
+ return {
539
+ "sk-trace-id": _activeTransaction.traceId,
540
+ "sk-parent-span-id": _activeTransaction.spanId,
541
+ "sk-sampled": sampled,
542
+ };
543
+ },
544
+
545
+ createNavigationTracker,
546
+
547
+ /** Drain the queued transactions immediately (skips the debounce). */
548
+ async flush(): Promise<void> {
549
+ if (_txFlushTimer !== null) {
550
+ clearTimeout(_txFlushTimer);
551
+ _txFlushTimer = null;
552
+ }
553
+ await flushTransactions();
554
+ },
555
+
556
+ // MARK: - Test Hooks
557
+
558
+ _reset(): void {
559
+ _config = null;
560
+ _activeTransaction = null;
561
+ _txQueue = [];
562
+ if (_txFlushTimer !== null) {
563
+ clearTimeout(_txFlushTimer);
564
+ _txFlushTimer = null;
565
+ }
566
+ _openTransactions.clear();
567
+ if (_stallTimer !== null) {
568
+ clearInterval(_stallTimer);
569
+ _stallTimer = null;
570
+ }
571
+ if (_originalFetch) {
572
+ globalThis.fetch = _originalFetch;
573
+ _originalFetch = null;
574
+ }
575
+ },
576
+
577
+ /** Drive the stall-tick handler with an explicit clock (tests only). */
578
+ _recordStallTickForTests(nowMs: number): void {
579
+ recordStallTick(nowMs);
580
+ },
581
+
582
+ _stallTimerRunningForTests(): boolean {
583
+ return _stallTimer !== null;
584
+ },
585
+
586
+ _openTransactionCountForTests(): number {
587
+ return _openTransactions.size;
588
+ },
589
+ };
@@ -0,0 +1,47 @@
1
+ // src/native/module.ts
2
+ import {
3
+ NativeModules,
4
+ NativeEventEmitter,
5
+ TurboModuleRegistry,
6
+ } from "react-native";
7
+ import type { SwissKnifePurchasesNativeModule } from "./spec";
8
+
9
+ const MODULE_NAME = "SwissKnifePurchases";
10
+
11
+ const NOT_LINKED_MESSAGE =
12
+ `The "${MODULE_NAME}" native module is not linked. This SDK requires a native ` +
13
+ `build — it cannot run in a bare JS/web context or Expo Go. Did you rebuild the ` +
14
+ `app after installing (pod install / Gradle sync) and use a development build?`;
15
+
16
+ let cached: SwissKnifePurchasesNativeModule | null = null;
17
+ let cachedEmitter: NativeEventEmitter | null = null;
18
+
19
+ function resolve(): SwissKnifePurchasesNativeModule | null {
20
+ // New Architecture: TurboModuleRegistry. Falls back to the legacy bridge.
21
+ const turbo =
22
+ TurboModuleRegistry?.get?.<SwissKnifePurchasesNativeModule>(MODULE_NAME) ??
23
+ null;
24
+ if (turbo) return turbo;
25
+ const legacy = (NativeModules as Record<string, unknown>)[MODULE_NAME];
26
+ return (legacy as SwissKnifePurchasesNativeModule | undefined) ?? null;
27
+ }
28
+
29
+ export function getNativeModule(): SwissKnifePurchasesNativeModule {
30
+ if (cached) return cached;
31
+ const mod = resolve();
32
+ if (!mod) throw new Error(NOT_LINKED_MESSAGE);
33
+ cached = mod;
34
+ return mod;
35
+ }
36
+
37
+ export function getEventEmitter(): NativeEventEmitter {
38
+ if (cachedEmitter) return cachedEmitter;
39
+ cachedEmitter = new NativeEventEmitter(getNativeModule());
40
+ return cachedEmitter;
41
+ }
42
+
43
+ // Test seam: reset memoized references so each test starts clean.
44
+ export function __resetNativeModuleForTests(): void {
45
+ cached = null;
46
+ cachedEmitter = null;
47
+ }