@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,440 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Performance/SKPerformance.swift
2
+ //
3
+ // Sentry-compatible performance monitoring SDK for swiss-knife (iOS).
4
+ // Provides Transaction/Span tracking with automatic app-start and screen-load
5
+ // instrumentation.
6
+
7
+ import Foundation
8
+
9
+ #if canImport(UIKit)
10
+ import UIKit
11
+ #endif
12
+
13
+ // MARK: - Span Status
14
+
15
+ public enum SKSpanStatus: String, Codable {
16
+ case ok
17
+ case cancelled
18
+ case unknown
19
+ case invalidArgument = "invalid_argument"
20
+ case deadlineExceeded = "deadline_exceeded"
21
+ case notFound = "not_found"
22
+ case permissionDenied = "permission_denied"
23
+ case resourceExhausted = "resource_exhausted"
24
+ case unimplemented
25
+ case unavailable
26
+ case internalError = "internal_error"
27
+ case aborted
28
+ }
29
+
30
+ // MARK: - Span
31
+
32
+ public final class SKSpan {
33
+ public let spanId: String
34
+ public let parentSpanId: String
35
+ public let op: String
36
+ public let description: String?
37
+
38
+ private let startTime: Date
39
+ private var endTime: Date?
40
+ private var status: SKSpanStatus = .ok
41
+ private var tags: [String: String] = [:]
42
+ private var data: [String: String] = [:]
43
+ private var children: [SKSpan] = []
44
+
45
+ internal init(op: String, description: String?, parentSpanId: String) {
46
+ self.spanId = SKPerformance.generateSpanId()
47
+ self.parentSpanId = parentSpanId
48
+ self.op = op
49
+ self.description = description
50
+ // Use the canonical SDK clock so server-skew correction (applied
51
+ // by `BackendHttpClient` via the response `Date` header) lands on
52
+ // the same timeline as ingest envelopes.
53
+ self.startTime = Clock.now()
54
+ }
55
+
56
+ public func startChild(op: String, description: String? = nil) -> SKSpan {
57
+ let child = SKSpan(op: op, description: description, parentSpanId: spanId)
58
+ children.append(child)
59
+ return child
60
+ }
61
+
62
+ public func finish(status: SKSpanStatus = .ok) {
63
+ guard endTime == nil else { return } // already finished
64
+ self.endTime = Clock.now()
65
+ self.status = status
66
+ }
67
+
68
+ public func setTag(_ key: String, value: String) {
69
+ tags[key] = value
70
+ }
71
+
72
+ public func setData(_ key: String, value: String) {
73
+ data[key] = value
74
+ }
75
+
76
+ internal func toPayload() -> [String: Any] {
77
+ let end = endTime ?? Clock.now()
78
+ let durationMs = end.timeIntervalSince(startTime) * 1000
79
+
80
+ var payload: [String: Any] = [
81
+ "spanId": spanId,
82
+ "parentSpanId": parentSpanId,
83
+ "op": op,
84
+ "startTimestamp": SKPerformance.iso8601String(from: startTime),
85
+ "endTimestamp": SKPerformance.iso8601String(from: end),
86
+ "status": status.rawValue,
87
+ ]
88
+
89
+ if let desc = description {
90
+ payload["description"] = desc
91
+ }
92
+ if !tags.isEmpty {
93
+ payload["tags"] = tags
94
+ }
95
+ if !data.isEmpty {
96
+ payload["data"] = data
97
+ }
98
+
99
+ return payload
100
+ }
101
+
102
+ internal func allSpans() -> [SKSpan] {
103
+ var result = [self]
104
+ for child in children {
105
+ result.append(contentsOf: child.allSpans())
106
+ }
107
+ return result
108
+ }
109
+ }
110
+
111
+ // MARK: - Transaction
112
+
113
+ public final class SKTransaction {
114
+ public let traceId: String
115
+ public let spanId: String
116
+ public let name: String
117
+ public let op: String
118
+ public let sampled: Bool
119
+ public private(set) var spans: [SKSpan] = []
120
+
121
+ private let startTime: Date
122
+ private var endTime: Date?
123
+ private var status: SKSpanStatus = .ok
124
+ private var tags: [String: String] = [:]
125
+ private var data: [String: String] = [:]
126
+ private weak var performance: SKPerformance?
127
+
128
+ internal init(name: String, op: String, performance: SKPerformance, sampled: Bool = true) {
129
+ self.traceId = SKPerformance.generateTraceId()
130
+ self.spanId = SKPerformance.generateSpanId()
131
+ self.name = name
132
+ self.op = op
133
+ self.sampled = sampled
134
+ self.startTime = Clock.now()
135
+ self.performance = performance
136
+ }
137
+
138
+ public func startChild(op: String, description: String? = nil) -> SKSpan {
139
+ let span = SKSpan(op: op, description: description, parentSpanId: spanId)
140
+ spans.append(span)
141
+ return span
142
+ }
143
+
144
+ public func finish(status: SKSpanStatus = .ok) {
145
+ guard endTime == nil else { return } // already finished
146
+ self.endTime = Clock.now()
147
+ self.status = status
148
+ // Clear active transaction reference
149
+ if performance?.currentTransaction === self {
150
+ performance?.currentTransaction = nil
151
+ }
152
+ guard sampled else { return }
153
+ for span in allChildSpans() {
154
+ span.finish(status: .ok)
155
+ }
156
+ performance?.sendTransaction(self)
157
+ }
158
+
159
+ public func setTag(_ key: String, value: String) {
160
+ tags[key] = value
161
+ }
162
+
163
+ public func setData(_ key: String, value: String) {
164
+ data[key] = value
165
+ }
166
+
167
+ internal func toPayload() -> [String: Any] {
168
+ let end = endTime ?? Clock.now()
169
+ let childPayloads = allChildSpans().map { $0.toPayload() }
170
+
171
+ // Sentry-compatible wire shape, but sourced from the canonical
172
+ // DeviceContext primitive instead of inline `ProcessInfo` calls.
173
+ // Field names stay the same so the backend's Sentry parser is
174
+ // unaffected; only the values are now in lockstep with envelope
175
+ // ContextSnapshot.device.
176
+ let device = DeviceContextProvider.current()
177
+ var contexts: [String: Any] = [:]
178
+ var osDict: [String: String] = [:]
179
+ osDict["name"] = device.osName
180
+ osDict["version"] = device.osVersion
181
+ contexts["os"] = osDict
182
+
183
+ var deviceDict: [String: String] = [:]
184
+ deviceDict["model"] = device.deviceModel
185
+ contexts["device"] = deviceDict
186
+
187
+ var payload: [String: Any] = [
188
+ "traceId": traceId,
189
+ "name": name,
190
+ "op": op,
191
+ "startTimestamp": SKPerformance.iso8601String(from: startTime),
192
+ "endTimestamp": SKPerformance.iso8601String(from: end),
193
+ "status": status.rawValue,
194
+ "spans": childPayloads,
195
+ "contexts": contexts,
196
+ ]
197
+
198
+ if !tags.isEmpty {
199
+ payload["tags"] = tags
200
+ }
201
+
202
+ return payload
203
+ }
204
+
205
+ private func allChildSpans() -> [SKSpan] {
206
+ var result: [SKSpan] = []
207
+ for span in spans {
208
+ result.append(contentsOf: span.allSpans())
209
+ }
210
+ return result
211
+ }
212
+
213
+ }
214
+
215
+ // MARK: - Performance Manager
216
+
217
+ public final class SKPerformance {
218
+ public static let shared = SKPerformance()
219
+
220
+ public struct Configuration {
221
+ public let apiKey: String
222
+ public var serverURL: String
223
+ public var environment: String
224
+ public var release: String?
225
+ public var enableAutoAppStart: Bool
226
+ public var enableAutoScreenLoad: Bool
227
+ public var enableAutoHTTP: Bool
228
+ public var tracesSampleRate: Double
229
+
230
+ public init(
231
+ apiKey: String,
232
+ serverURL: String = "",
233
+ environment: String = "production",
234
+ release: String? = nil,
235
+ enableAutoAppStart: Bool = true,
236
+ enableAutoScreenLoad: Bool = true,
237
+ enableAutoHTTP: Bool = false,
238
+ tracesSampleRate: Double = 1.0
239
+ ) {
240
+ self.apiKey = apiKey
241
+ self.serverURL = serverURL
242
+ self.environment = environment
243
+ self.release = release
244
+ self.enableAutoAppStart = enableAutoAppStart
245
+ self.enableAutoScreenLoad = enableAutoScreenLoad
246
+ self.enableAutoHTTP = enableAutoHTTP
247
+ self.tracesSampleRate = tracesSampleRate
248
+ }
249
+ }
250
+
251
+ private var configuration: Configuration?
252
+ private let queue = DispatchQueue(label: "com.swissknife.performance", qos: .utility)
253
+ private var appStartTransaction: SKTransaction?
254
+
255
+ /// The most recently started (and not yet finished) transaction.
256
+ /// Used by `traceHeaders()` to propagate distributed tracing context.
257
+ public internal(set) var currentTransaction: SKTransaction?
258
+
259
+ /// IngestClient seam — production wires the shared singleton; tests
260
+ /// can swap a custom instance via `_setIngestForTesting`. Transactions
261
+ /// (and any future SKPerformance session events) flow exclusively
262
+ /// through this — there is NO direct HTTP transport path left in
263
+ /// SKPerformance.
264
+ internal var ingest: IngestClient = IngestClient.shared
265
+
266
+ private init() {}
267
+
268
+ // MARK: - Start
269
+
270
+ public func start(configuration: Configuration) {
271
+ self.configuration = configuration
272
+
273
+ if configuration.enableAutoAppStart {
274
+ startAppStartTransaction()
275
+ }
276
+
277
+ if configuration.enableAutoScreenLoad {
278
+ installScreenLoadTracking()
279
+ }
280
+ }
281
+
282
+ // MARK: - Public API
283
+
284
+ public func startTransaction(name: String, op: String) -> SKTransaction {
285
+ let rate = configuration?.tracesSampleRate ?? 1.0
286
+ let sampled = rate >= 1.0 || Double.random(in: 0...1) <= rate
287
+ let tx = SKTransaction(name: name, op: op, performance: self, sampled: sampled)
288
+ currentTransaction = tx
289
+ return tx
290
+ }
291
+
292
+ // MARK: - Auto-Instrumentation: App Start
293
+
294
+ private func startAppStartTransaction() {
295
+ appStartTransaction = startTransaction(name: "App Start", op: "app.start")
296
+
297
+ #if canImport(UIKit)
298
+ NotificationCenter.default.addObserver(
299
+ forName: UIApplication.didBecomeActiveNotification,
300
+ object: nil,
301
+ queue: nil
302
+ ) { [weak self] _ in
303
+ guard let self, let tx = self.appStartTransaction else { return }
304
+ self.appStartTransaction = nil
305
+ tx.finish(status: .ok)
306
+ // Only observe first activation
307
+ NotificationCenter.default.removeObserver(self)
308
+ }
309
+ #endif
310
+ }
311
+
312
+ // MARK: - Auto-Instrumentation: Screen Load
313
+
314
+ private func installScreenLoadTracking() {
315
+ #if canImport(UIKit)
316
+ swizzleViewDidAppear()
317
+ #endif
318
+ }
319
+
320
+ #if canImport(UIKit)
321
+ private static var swizzled = false
322
+
323
+ private func swizzleViewDidAppear() {
324
+ guard !SKPerformance.swizzled else { return }
325
+ SKPerformance.swizzled = true
326
+
327
+ let originalSelector = #selector(UIViewController.viewDidAppear(_:))
328
+ let swizzledSelector = #selector(UIViewController.sk_viewDidAppear(_:))
329
+
330
+ guard let originalMethod = class_getInstanceMethod(UIViewController.self, originalSelector),
331
+ let swizzledMethod = class_getInstanceMethod(UIViewController.self, swizzledSelector) else {
332
+ return
333
+ }
334
+
335
+ method_exchangeImplementations(originalMethod, swizzledMethod)
336
+ }
337
+ #endif
338
+
339
+ // MARK: - Send Transaction
340
+
341
+ internal func sendTransaction(_ transaction: SKTransaction) {
342
+ queue.async { [weak self] in
343
+ self?.sendTransactionPayload(transaction)
344
+ }
345
+ }
346
+
347
+ /// Route the finished transaction through IngestClient as a
348
+ /// `transaction`-typed item. Envelope-level context (event_id,
349
+ /// identity, session, device, timestamp) is stamped by IngestClient
350
+ /// at flush time — we only carry the domain payload here.
351
+ private func sendTransactionPayload(_ transaction: SKTransaction) {
352
+ guard let config = configuration else { return }
353
+
354
+ var payload = transaction.toPayload()
355
+ if let release = config.release {
356
+ payload["release"] = release
357
+ }
358
+ payload["environment"] = config.environment
359
+ ingest.enqueue(type: .transaction, jsonObject: payload)
360
+ }
361
+
362
+ // MARK: - ID Generation
363
+
364
+ internal static func generateTraceId() -> String {
365
+ return UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
366
+ }
367
+
368
+ internal static func generateSpanId() -> String {
369
+ let uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
370
+ return String(uuid.prefix(16))
371
+ }
372
+
373
+ internal static func iso8601String(from date: Date) -> String {
374
+ let formatter = ISO8601DateFormatter()
375
+ formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
376
+ return formatter.string(from: date)
377
+ }
378
+
379
+ // MARK: - Test Hooks
380
+
381
+ internal func _resetForTesting() {
382
+ configuration = nil
383
+ appStartTransaction = nil
384
+ currentTransaction = nil
385
+ ingest = IngestClient.shared
386
+ }
387
+
388
+ /// Test seam — swap in a custom IngestClient instance so tests can
389
+ /// assert what was enqueued without exercising the shared singleton's
390
+ /// disk queue.
391
+ internal func _setIngestForTesting(_ client: IngestClient) {
392
+ self.ingest = client
393
+ }
394
+
395
+ /// Test seam — expose `SKTransaction.toPayload()` without changing its
396
+ /// access level. Used by the device-context / Clock-skew regression tests.
397
+ internal static func _payloadForTesting(_ tx: SKTransaction) -> [String: Any] {
398
+ tx.toPayload()
399
+ }
400
+ }
401
+
402
+ // MARK: - UIViewController Swizzling Extension
403
+
404
+ #if canImport(UIKit)
405
+ extension UIViewController {
406
+ @objc dynamic func sk_viewDidAppear(_ animated: Bool) {
407
+ // Call original (implementations are swapped)
408
+ sk_viewDidAppear(animated)
409
+
410
+ // Skip system view controllers
411
+ let className = String(describing: type(of: self))
412
+ let systemPrefixes = ["UI", "_UI", "NS", "_NS", "AV", "SF", "WK"]
413
+ let isSystem = systemPrefixes.contains(where: { className.hasPrefix($0) })
414
+
415
+ if !isSystem {
416
+ // Auto navigation breadcrumb
417
+ SKCrashReporting.shared.addBreadcrumb(
418
+ SKBreadcrumb(category: "navigation", message: "Displayed \(className)", level: .info)
419
+ )
420
+
421
+ let tx = SKPerformance.shared.startTransaction(
422
+ name: className,
423
+ op: "ui.load"
424
+ )
425
+ // Screen load is effectively instantaneous — start and finish
426
+ tx.finish(status: .ok)
427
+ }
428
+ }
429
+ }
430
+ #endif
431
+
432
+ // MARK: - SKCrashReporting Extension
433
+
434
+ extension SKCrashReporting {
435
+ /// Convenience — starts a performance transaction tied to the crash-reporting
436
+ /// configuration. Delegates to `SKPerformance.shared`.
437
+ public func startTransaction(name: String, op: String) -> SKTransaction {
438
+ return SKPerformance.shared.startTransaction(name: name, op: op)
439
+ }
440
+ }
@@ -0,0 +1,87 @@
1
+ // packages/swiss-knife-ios/Sources/SwissKnifeiOS/Performance/SKURLSessionDelegate.swift
2
+ //
3
+ // URLSession delegate that automatically records HTTP breadcrumbs and creates
4
+ // performance spans for network requests under the active transaction.
5
+ //
6
+ // Usage:
7
+ // ```swift
8
+ // let delegate = SKURLSessionDelegate(wrapping: yourExistingDelegate)
9
+ // let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
10
+ // ```
11
+
12
+ import Foundation
13
+
14
+ public class SKURLSessionDelegate: NSObject, URLSessionTaskDelegate {
15
+
16
+ private let originalDelegate: URLSessionTaskDelegate?
17
+
18
+ public init(wrapping original: URLSessionTaskDelegate? = nil) {
19
+ self.originalDelegate = original
20
+ super.init()
21
+ }
22
+
23
+ // MARK: - URLSessionTaskDelegate
24
+
25
+ public func urlSession(
26
+ _ session: URLSession,
27
+ task: URLSessionTask,
28
+ didFinishCollecting metrics: URLSessionTaskMetrics
29
+ ) {
30
+ guard let url = task.originalRequest?.url,
31
+ let method = task.originalRequest?.httpMethod else {
32
+ // Forward to original delegate
33
+ originalDelegate?.urlSession?(session, task: task, didFinishCollecting: metrics)
34
+ return
35
+ }
36
+
37
+ let duration = metrics.taskInterval.duration
38
+ let statusCode = (task.response as? HTTPURLResponse)?.statusCode ?? 0
39
+
40
+ // Record HTTP breadcrumb
41
+ SKCrashReporting.shared.captureHTTPBreadcrumb(
42
+ method: method,
43
+ url: url.absoluteString,
44
+ statusCode: statusCode,
45
+ duration: duration
46
+ )
47
+
48
+ // Create span under active transaction if one exists
49
+ if let tx = SKPerformance.shared.currentTransaction {
50
+ let span = tx.startChild(op: "http.client", description: "\(method) \(url.path)")
51
+ span.setData("http.status_code", value: "\(statusCode)")
52
+ span.setData("http.url", value: url.absoluteString)
53
+ span.setData("http.method", value: method)
54
+ span.setData("duration_ms", value: "\(Int(duration * 1000))")
55
+ span.finish(status: statusCode >= 400 ? .internalError : .ok)
56
+ }
57
+
58
+ // Forward to original delegate
59
+ originalDelegate?.urlSession?(session, task: task, didFinishCollecting: metrics)
60
+ }
61
+
62
+ public func urlSession(
63
+ _ session: URLSession,
64
+ task: URLSessionTask,
65
+ didCompleteWithError error: Error?
66
+ ) {
67
+ // Forward to original delegate
68
+ originalDelegate?.urlSession?(session, task: task, didCompleteWithError: error)
69
+ }
70
+
71
+ // MARK: - Forward other delegate calls
72
+
73
+ public func urlSession(
74
+ _ session: URLSession,
75
+ task: URLSessionTask,
76
+ willPerformHTTPRedirection response: HTTPURLResponse,
77
+ newRequest request: URLRequest,
78
+ completionHandler: @escaping (URLRequest?) -> Void
79
+ ) {
80
+ if let orig = originalDelegate,
81
+ orig.responds(to: #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:))) {
82
+ orig.urlSession?(session, task: task, willPerformHTTPRedirection: response, newRequest: request, completionHandler: completionHandler)
83
+ } else {
84
+ completionHandler(request)
85
+ }
86
+ }
87
+ }