@app-swiss-knife/react-native-sdk 0.4.0 → 0.5.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 (177) hide show
  1. package/CHANGELOG.md +385 -2
  2. package/LICENSE +21 -0
  3. package/README.md +229 -42
  4. package/SwissKnifePurchases.podspec +1 -1
  5. package/android/build.gradle +24 -2
  6. package/android/consumer-rules.pro +12 -0
  7. package/android/src/main/AndroidManifest.xml +15 -1
  8. package/android/src/main/java/com/swissknife/crashreporting/SKCrashReportingModule.kt +5 -4
  9. package/android/src/main/java/com/swissknife/purchases/SwissKnifeJson.kt +7 -2
  10. package/android/src/main/java/com/swissknife/purchases/SwissKnifePurchasesModule.kt +168 -6
  11. package/android/src/play/java/com/swissknife/purchases/StoreIntentHandler.kt +7 -0
  12. package/android/src/rustore/java/com/swissknife/purchases/StoreIntentHandler.kt +9 -0
  13. package/android/vendor/java/com/appswissknife/SwissKnife.kt +107 -38
  14. package/android/vendor/java/com/appswissknife/analytics/SKAnalytics.kt +180 -115
  15. package/android/vendor/java/com/appswissknife/attributes/AttributesClient.kt +16 -18
  16. package/android/vendor/java/com/appswissknife/attributes/SetAttributesWorker.kt +13 -13
  17. package/android/vendor/java/com/appswissknife/attribution/Attribution.kt +56 -25
  18. package/android/vendor/java/com/appswissknife/context/DeviceContext.kt +1 -1
  19. package/android/vendor/java/com/appswissknife/crashreporting/SKCrashReporting.kt +365 -206
  20. package/android/vendor/java/com/appswissknife/entitlements/EntitlementsRepository.kt +195 -26
  21. package/android/vendor/java/com/appswissknife/identity/Identity.kt +31 -6
  22. package/android/vendor/java/com/appswissknife/models/PurchasesError.kt +5 -0
  23. package/android/vendor/java/com/appswissknife/net/BackendHttpClient.kt +56 -31
  24. package/android/vendor/java/com/appswissknife/net/IngestClient.kt +673 -87
  25. package/android/vendor/java/com/appswissknife/net/OfflineQueueStore.kt +214 -30
  26. package/android/vendor/java/com/appswissknife/notifications/NotificationRenderer.kt +195 -0
  27. package/android/vendor/java/com/appswissknife/notifications/PermissionRequestActivity.kt +60 -0
  28. package/android/vendor/java/com/appswissknife/notifications/PermissionStatus.kt +41 -0
  29. package/android/vendor/java/com/appswissknife/notifications/PushEventQueue.kt +143 -0
  30. package/android/vendor/java/com/appswissknife/notifications/PushPayload.kt +72 -0
  31. package/android/vendor/java/com/appswissknife/notifications/PushRegistration.kt +89 -0
  32. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeMessagingService.kt +57 -0
  33. package/android/vendor/java/com/appswissknife/notifications/SwissKnifeNotifications.kt +438 -0
  34. package/android/vendor/java/com/appswissknife/offerings/OfferingsRepository.kt +266 -64
  35. package/android/vendor/java/com/appswissknife/performance/SKPerformance.kt +1 -0
  36. package/android/vendor/java/com/appswissknife/purchases/BillingClientGateway.kt +545 -88
  37. package/android/vendor/java/com/appswissknife/purchases/PlayPriceEnrichmentProvider.kt +55 -24
  38. package/android/vendor/java/com/appswissknife/purchases/ProductKindHint.kt +21 -0
  39. package/android/vendor/java/com/appswissknife/purchases/PurchasesGateway.kt +14 -0
  40. package/android/vendor-rustore/AndroidManifest.xml +59 -0
  41. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreGateway.kt +428 -0
  42. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStoreInitProvider.kt +43 -0
  43. package/android/vendor-rustore/java/com/appswissknife/rustore/RuStorePriceEnrichmentProvider.kt +85 -0
  44. package/app.plugin.js +287 -0
  45. package/ios/SwissKnifePurchases.m +20 -0
  46. package/ios/SwissKnifePurchases.swift +97 -3
  47. package/ios/SwissKnifePushBootstrap.m +34 -0
  48. package/ios/vendor/SwissKnifeiOS/Analytics/SKAnalytics.swift +138 -89
  49. package/ios/vendor/SwissKnifeiOS/Context/DeviceContext.swift +1 -1
  50. package/ios/vendor/SwissKnifeiOS/CrashReporting/SKCrashReporting.swift +345 -44
  51. package/ios/vendor/SwissKnifeiOS/Net/BackendBackoffGate.swift +43 -2
  52. package/ios/vendor/SwissKnifeiOS/Net/IngestClient.swift +495 -16
  53. package/ios/vendor/SwissKnifeiOS/Net/OfflineQueueStore.swift +231 -23
  54. package/ios/vendor/SwissKnifeiOS/Notifications/PushPayload.swift +87 -0
  55. package/ios/vendor/SwissKnifeiOS/Notifications/PushRegistrar.swift +322 -0
  56. package/ios/vendor/SwissKnifeiOS/Notifications/SwissKnife+Notifications.swift +403 -0
  57. package/ios/vendor/SwissKnifeiOS/Performance/SKPerformance.swift +1 -0
  58. package/ios/vendor/SwissKnifeiOS/Services/EntitlementsService.swift +11 -7
  59. package/ios/vendor/SwissKnifeiOS/Services/PurchaseService.swift +38 -7
  60. package/ios/vendor/SwissKnifeiOS/SwissKnife.swift +34 -6
  61. package/lib/commonjs/attribution.js +4 -3
  62. package/lib/commonjs/attribution.js.map +1 -1
  63. package/lib/commonjs/identity.js +12 -11
  64. package/lib/commonjs/identity.js.map +1 -1
  65. package/lib/commonjs/index.js +16 -5
  66. package/lib/commonjs/index.js.map +1 -1
  67. package/lib/commonjs/internal/config.js +105 -8
  68. package/lib/commonjs/internal/config.js.map +1 -1
  69. package/lib/commonjs/internal/telemetry-context.js +70 -0
  70. package/lib/commonjs/internal/telemetry-context.js.map +1 -0
  71. package/lib/commonjs/modules/analytics.js +18 -25
  72. package/lib/commonjs/modules/analytics.js.map +1 -1
  73. package/lib/commonjs/modules/crash-reporting.js +27 -6
  74. package/lib/commonjs/modules/crash-reporting.js.map +1 -1
  75. package/lib/commonjs/modules/log.js +1 -1
  76. package/lib/commonjs/modules/notifications.js +500 -0
  77. package/lib/commonjs/modules/notifications.js.map +1 -0
  78. package/lib/commonjs/modules/performance.js +57 -8
  79. package/lib/commonjs/modules/performance.js.map +1 -1
  80. package/lib/commonjs/native/module.js +6 -0
  81. package/lib/commonjs/native/module.js.map +1 -1
  82. package/lib/commonjs/native/spec.js +12 -5
  83. package/lib/commonjs/native/spec.js.map +1 -1
  84. package/lib/commonjs/purchases.js +4 -4
  85. package/lib/commonjs/types.js +12 -15
  86. package/lib/commonjs/types.js.map +1 -1
  87. package/lib/module/attribution.js +4 -3
  88. package/lib/module/attribution.js.map +1 -1
  89. package/lib/module/identity.js +12 -11
  90. package/lib/module/identity.js.map +1 -1
  91. package/lib/module/index.js +8 -4
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/module/internal/config.js +103 -8
  94. package/lib/module/internal/config.js.map +1 -1
  95. package/lib/module/internal/telemetry-context.js +63 -0
  96. package/lib/module/internal/telemetry-context.js.map +1 -0
  97. package/lib/module/modules/analytics.js +18 -25
  98. package/lib/module/modules/analytics.js.map +1 -1
  99. package/lib/module/modules/crash-reporting.js +27 -6
  100. package/lib/module/modules/crash-reporting.js.map +1 -1
  101. package/lib/module/modules/log.js +1 -1
  102. package/lib/module/modules/notifications.js +491 -0
  103. package/lib/module/modules/notifications.js.map +1 -0
  104. package/lib/module/modules/performance.js +57 -8
  105. package/lib/module/modules/performance.js.map +1 -1
  106. package/lib/module/native/module.js +6 -1
  107. package/lib/module/native/module.js.map +1 -1
  108. package/lib/module/native/spec.js +11 -4
  109. package/lib/module/native/spec.js.map +1 -1
  110. package/lib/module/purchases.js +4 -4
  111. package/lib/module/types.js +12 -15
  112. package/lib/module/types.js.map +1 -1
  113. package/lib/typescript/commonjs/attribution.d.ts +3 -2
  114. package/lib/typescript/commonjs/attribution.d.ts.map +1 -1
  115. package/lib/typescript/commonjs/identity.d.ts.map +1 -1
  116. package/lib/typescript/commonjs/index.d.ts +2 -0
  117. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  118. package/lib/typescript/commonjs/internal/config.d.ts +16 -2
  119. package/lib/typescript/commonjs/internal/config.d.ts.map +1 -1
  120. package/lib/typescript/commonjs/internal/telemetry-context.d.ts +22 -0
  121. package/lib/typescript/commonjs/internal/telemetry-context.d.ts.map +1 -0
  122. package/lib/typescript/commonjs/modules/analytics.d.ts +8 -11
  123. package/lib/typescript/commonjs/modules/analytics.d.ts.map +1 -1
  124. package/lib/typescript/commonjs/modules/crash-reporting.d.ts +18 -5
  125. package/lib/typescript/commonjs/modules/crash-reporting.d.ts.map +1 -1
  126. package/lib/typescript/commonjs/modules/notifications.d.ts +110 -0
  127. package/lib/typescript/commonjs/modules/notifications.d.ts.map +1 -0
  128. package/lib/typescript/commonjs/modules/performance.d.ts +13 -0
  129. package/lib/typescript/commonjs/modules/performance.d.ts.map +1 -1
  130. package/lib/typescript/commonjs/native/module.d.ts +2 -0
  131. package/lib/typescript/commonjs/native/module.d.ts.map +1 -1
  132. package/lib/typescript/commonjs/native/spec.d.ts +33 -4
  133. package/lib/typescript/commonjs/native/spec.d.ts.map +1 -1
  134. package/lib/typescript/commonjs/purchases.d.ts +4 -4
  135. package/lib/typescript/commonjs/types.d.ts +4 -5
  136. package/lib/typescript/commonjs/types.d.ts.map +1 -1
  137. package/lib/typescript/module/attribution.d.ts +3 -2
  138. package/lib/typescript/module/attribution.d.ts.map +1 -1
  139. package/lib/typescript/module/identity.d.ts.map +1 -1
  140. package/lib/typescript/module/index.d.ts +2 -0
  141. package/lib/typescript/module/index.d.ts.map +1 -1
  142. package/lib/typescript/module/internal/config.d.ts +16 -2
  143. package/lib/typescript/module/internal/config.d.ts.map +1 -1
  144. package/lib/typescript/module/internal/telemetry-context.d.ts +22 -0
  145. package/lib/typescript/module/internal/telemetry-context.d.ts.map +1 -0
  146. package/lib/typescript/module/modules/analytics.d.ts +8 -11
  147. package/lib/typescript/module/modules/analytics.d.ts.map +1 -1
  148. package/lib/typescript/module/modules/crash-reporting.d.ts +18 -5
  149. package/lib/typescript/module/modules/crash-reporting.d.ts.map +1 -1
  150. package/lib/typescript/module/modules/notifications.d.ts +110 -0
  151. package/lib/typescript/module/modules/notifications.d.ts.map +1 -0
  152. package/lib/typescript/module/modules/performance.d.ts +13 -0
  153. package/lib/typescript/module/modules/performance.d.ts.map +1 -1
  154. package/lib/typescript/module/native/module.d.ts +2 -0
  155. package/lib/typescript/module/native/module.d.ts.map +1 -1
  156. package/lib/typescript/module/native/spec.d.ts +33 -4
  157. package/lib/typescript/module/native/spec.d.ts.map +1 -1
  158. package/lib/typescript/module/purchases.d.ts +4 -4
  159. package/lib/typescript/module/types.d.ts +4 -5
  160. package/lib/typescript/module/types.d.ts.map +1 -1
  161. package/package.json +12 -4
  162. package/src/attribution.ts +4 -3
  163. package/src/identity.ts +12 -11
  164. package/src/index.ts +16 -4
  165. package/src/internal/config.ts +113 -8
  166. package/src/internal/telemetry-context.ts +76 -0
  167. package/src/modules/analytics.ts +24 -33
  168. package/src/modules/crash-reporting.ts +50 -9
  169. package/src/modules/log.ts +1 -1
  170. package/src/modules/notifications.ts +557 -0
  171. package/src/modules/performance.ts +94 -14
  172. package/src/native/module.ts +6 -0
  173. package/src/native/spec.ts +45 -10
  174. package/src/purchases.ts +4 -4
  175. package/src/types.ts +12 -15
  176. package/android/vendor/java/com/appswissknife/analytics/EventQueueStore.kt +0 -326
  177. package/android/vendor/java/com/appswissknife/analytics/FlushEventsWorker.kt +0 -296
@@ -0,0 +1,500 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Notifications = void 0;
7
+ exports.__resetNotificationsForTests = __resetNotificationsForTests;
8
+ exports.extractPayload = extractPayload;
9
+ exports.flushEvents = flushEvents;
10
+ exports.normalizePermissionStatus = normalizePermissionStatus;
11
+ exports.notifyExplicitLogout = notifyExplicitLogout;
12
+ var _module = require("../native/module.js");
13
+ var _spec = require("../native/spec.js");
14
+ var _config = require("../internal/config.js");
15
+ // src/modules/notifications.ts
16
+ //
17
+ // Push notifications (swiss-push v1). Two integration modes share one API:
18
+ //
19
+ // 1. NATIVE mode — the Swiss Knife native SDK owns permission, the OS token
20
+ // (APNs on iOS, FCM on Android), upserts the device and tracks opens.
21
+ // await Notifications.requestPermission();
22
+ // await Notifications.registerForPushNotifications();
23
+ // Notifications.addNotificationOpenedListener(open => router.push(open.link));
24
+ //
25
+ // 2. MANUAL mode — the app already owns push through `expo-notifications`
26
+ // (`getDevicePushTokenAsync()`) or `@react-native-firebase/messaging`.
27
+ // It hands us the token and forwards open/receive payloads; everything
28
+ // here is pure JS and talks to the backend with `fetch`.
29
+ // const { data, type } = await Notifications2.getDevicePushTokenAsync();
30
+ // await Notifications.registerDeviceToken(data, type === "ios" ? "apns" : "fcm");
31
+ // Notifications.trackOpened(response);
32
+ //
33
+ // Wire contract: see the push contract (endpoints /api/sdk/push/devices and
34
+ // /api/sdk/push/events; payload keys `sk` on iOS, `sk_*` on Android).
35
+
36
+ const DEFAULT_SERVER_URL = "https://api.swiss-knife.dev";
37
+
38
+ // MARK: - Types
39
+
40
+ /** Swiss Knife metadata extracted from a notification's data. */
41
+
42
+ /** A tapped notification (or action button), as delivered by native mode. */
43
+
44
+ // MARK: - Payload extraction
45
+
46
+ function asRecord(v) {
47
+ return v && typeof v === "object" && !Array.isArray(v) ? v : null;
48
+ }
49
+ function str(v) {
50
+ return typeof v === "string" && v.length > 0 ? v : undefined;
51
+ }
52
+ function fromRecord(data) {
53
+ // iOS: reserved `sk` dictionary (an object, or a JSON string when a
54
+ // library stringified nested data).
55
+ let sk = data.sk;
56
+ if (typeof sk === "string") {
57
+ try {
58
+ sk = JSON.parse(sk);
59
+ } catch {
60
+ sk = undefined;
61
+ }
62
+ }
63
+ const skRec = asRecord(sk);
64
+ if (skRec) {
65
+ const messageId = str(skRec.m);
66
+ const deliveryId = str(skRec.d);
67
+ if (messageId && deliveryId) {
68
+ return {
69
+ messageId,
70
+ deliveryId,
71
+ ...(str(skRec.link) ? {
72
+ link: str(skRec.link)
73
+ } : {}),
74
+ ...(str(skRec.img) ? {
75
+ imageUrl: str(skRec.img)
76
+ } : {})
77
+ };
78
+ }
79
+ }
80
+ // Android: flat string map, `sk_*` keys.
81
+ const messageId = str(data.sk_m);
82
+ const deliveryId = str(data.sk_d);
83
+ if (messageId && deliveryId) {
84
+ return {
85
+ messageId,
86
+ deliveryId,
87
+ ...(str(data.sk_link) ? {
88
+ link: str(data.sk_link)
89
+ } : {}),
90
+ ...(str(data.sk_img) ? {
91
+ imageUrl: str(data.sk_img)
92
+ } : {})
93
+ };
94
+ }
95
+ return null;
96
+ }
97
+
98
+ /**
99
+ * Pull the Swiss Knife payload out of whatever a push library hands you.
100
+ * Accepts the bare `data` object (iOS `sk` or Android `sk_*` shapes), and the
101
+ * common wrappers: expo-notifications' `response` / `notification` and
102
+ * RNFirebase's `remoteMessage`. Returns null for foreign notifications.
103
+ */
104
+ function extractPayload(input) {
105
+ const root = asRecord(input);
106
+ if (!root) return null;
107
+ const notification = asRecord(root.notification);
108
+ const candidates = [root, root.data, ...[root.request, notification?.request].flatMap(request => {
109
+ const req = asRecord(request);
110
+ const trigger = asRecord(req?.trigger);
111
+ return [asRecord(req?.content)?.data, ...(trigger?.type === "push" ? [trigger.payload, asRecord(trigger.remoteMessage)?.data] : [])];
112
+ }), notification?.data];
113
+ for (const c of candidates) {
114
+ const rec = asRecord(c);
115
+ if (!rec) continue;
116
+ const found = fromRecord(rec);
117
+ if (found) return found;
118
+ }
119
+ return null;
120
+ }
121
+
122
+ // MARK: - Permission mapping
123
+
124
+ /**
125
+ * Normalize a permission status from any source (our native modules, or
126
+ * expo-notifications' `granted`/`denied`/`undetermined`) to the wire enum.
127
+ */
128
+ function normalizePermissionStatus(raw) {
129
+ switch (typeof raw === "string" ? raw.toLowerCase() : "") {
130
+ case "authorized":
131
+ case "granted":
132
+ return "authorized";
133
+ case "provisional":
134
+ return "provisional";
135
+ case "ephemeral":
136
+ return "ephemeral";
137
+ case "denied":
138
+ case "blocked":
139
+ return "denied";
140
+ default:
141
+ return "not_determined";
142
+ }
143
+ }
144
+
145
+ // MARK: - HTTP
146
+
147
+ function baseUrl(serverURL) {
148
+ return (serverURL || DEFAULT_SERVER_URL).replace(/\/+$/, "");
149
+ }
150
+ class PushHttpError extends Error {
151
+ constructor(status, path) {
152
+ super(`Swiss Knife push request ${path} failed: HTTP ${status}`);
153
+ this.status = status;
154
+ }
155
+ }
156
+
157
+ /** 4xx other than 408/429 will never succeed on retry. */
158
+ function isPermanentFailure(e) {
159
+ return e instanceof PushHttpError && e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 429;
160
+ }
161
+ async function post(path, body) {
162
+ const cfg = (0, _config.getServerConfig)();
163
+ if (!cfg) {
164
+ throw new Error("Swiss Knife is not configured. Call SwissKnife.configure(), SwissKnife.configureCore() or Analytics.init() before using Notifications.");
165
+ }
166
+ const res = await fetch(`${baseUrl(cfg.serverURL)}${path}`, {
167
+ method: "POST",
168
+ headers: {
169
+ "Content-Type": "application/json",
170
+ "X-API-Key": cfg.apiKey
171
+ },
172
+ body: JSON.stringify(body)
173
+ });
174
+ if (!res.ok) {
175
+ throw new PushHttpError(res.status, path);
176
+ }
177
+ try {
178
+ return await res.json();
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+
184
+ // MARK: - Manual registration
185
+
186
+ let lastSentFingerprint = null;
187
+ let manualRegistered = false;
188
+ /** Last manual registration, so a logout can relink the device. */
189
+ let lastManual = null;
190
+ /**
191
+ * True only after an EXPLICIT logout/reset/wipe. Identity is in-memory in the
192
+ * native SDKs, so after a relaunch it is "unknown", not "logged out": then
193
+ * `user_id` is omitted (the server keeps the link). Only this flag turns
194
+ * "no user" into an explicit `user_id: null` (server unlinks).
195
+ */
196
+ let unlinkPending = false;
197
+ async function nativeOrNull(read) {
198
+ try {
199
+ return await read();
200
+ } catch {
201
+ return null;
202
+ }
203
+ }
204
+ async function buildDeviceBody(token, provider, options) {
205
+ const platform = (0, _module.getPlatformOS)();
206
+ if (platform === "ios" && provider !== "apns") {
207
+ throw new Error('iOS devices register with provider "apns" (FCM on iOS is not supported in v1).');
208
+ }
209
+ if (platform === "android" && provider !== "fcm") {
210
+ throw new Error('Android devices register with provider "fcm".');
211
+ }
212
+ const native = (0, _module.getNativeModule)();
213
+ const installId = await native.getDeviceId();
214
+ const identity = await nativeOrNull(() => native.identityCurrent());
215
+ const info = await nativeOrNull(() => native.pushDeviceInfo());
216
+ const bundleId = options.bundleId ?? info?.bundleId;
217
+ if (!bundleId) {
218
+ throw new Error("Could not determine the bundle id / package name; pass options.bundleId.");
219
+ }
220
+ const permission = options.permissionStatus !== undefined ? normalizePermissionStatus(options.permissionStatus) : normalizePermissionStatus((await nativeOrNull(() => native.pushPermissionStatus())) ?? "authorized");
221
+ const resolved = (() => {
222
+ try {
223
+ return Intl.DateTimeFormat().resolvedOptions();
224
+ } catch {
225
+ return null;
226
+ }
227
+ })();
228
+ const environment = platform === "ios" ? options.environment ?? (info?.environment === "sandbox" ? "sandbox" : "production") : undefined;
229
+ return {
230
+ install_id: installId,
231
+ platform,
232
+ provider,
233
+ token,
234
+ ...(environment ? {
235
+ environment
236
+ } : {}),
237
+ bundle_id: bundleId,
238
+ permission_status: permission,
239
+ ...(identity?.userId ? {
240
+ user_id: identity.userId
241
+ } : unlinkPending ? {
242
+ user_id: null
243
+ } : {}),
244
+ ...(identity?.anonymousId ? {
245
+ anonymous_id: identity.anonymousId
246
+ } : {}),
247
+ ...(info?.appVersion ? {
248
+ app_version: info.appVersion
249
+ } : {}),
250
+ ...(info?.sdkVersion ? {
251
+ sdk_version: info.sdkVersion
252
+ } : {}),
253
+ ...(info?.osVersion ? {
254
+ os_version: info.osVersion
255
+ } : {}),
256
+ ...(resolved?.locale ? {
257
+ locale: resolved.locale
258
+ } : {}),
259
+ ...(resolved?.timeZone ? {
260
+ timezone: resolved.timeZone
261
+ } : {})
262
+ };
263
+ }
264
+
265
+ // MARK: - Event queue (manual tracking)
266
+
267
+ const MAX_QUEUED_EVENTS = 200;
268
+ const BATCH_SIZE = 100;
269
+ let eventQueue = [];
270
+ let flushing = null;
271
+ let flushTimer = null;
272
+ function enqueue(payload, type, actionId) {
273
+ const dupe = eventQueue.some(e => e.delivery_id === payload.deliveryId && e.type === type && (e.action_id ?? "") === (actionId ?? ""));
274
+ if (dupe) return;
275
+ eventQueue.push({
276
+ delivery_id: payload.deliveryId,
277
+ message_id: payload.messageId,
278
+ type,
279
+ ...(actionId ? {
280
+ action_id: actionId
281
+ } : {}),
282
+ occurred_at: new Date().toISOString()
283
+ });
284
+ if (eventQueue.length > MAX_QUEUED_EVENTS) {
285
+ eventQueue = eventQueue.slice(eventQueue.length - MAX_QUEUED_EVENTS);
286
+ }
287
+ // Coalesce a burst into one request.
288
+ if (!flushTimer) {
289
+ flushTimer = setTimeout(() => {
290
+ flushTimer = null;
291
+ void flushEvents();
292
+ }, 0);
293
+ }
294
+ }
295
+
296
+ /** Send queued `received`/`opened` events now. Failed batches stay queued. */
297
+ function flushEvents() {
298
+ if (flushing) return flushing;
299
+ if (eventQueue.length === 0) return Promise.resolve();
300
+ const run = (async () => {
301
+ {
302
+ while (eventQueue.length > 0) {
303
+ const batch = eventQueue.slice(0, BATCH_SIZE);
304
+ try {
305
+ await post("/api/sdk/push/events", {
306
+ events: batch
307
+ });
308
+ } catch (e) {
309
+ if (isPermanentFailure(e)) {
310
+ // Rejected for good (bad payload / key): drop the batch, keep going.
311
+ eventQueue = eventQueue.slice(batch.length);
312
+ continue;
313
+ }
314
+ return; // offline / 429 / 5xx / not configured: keep for the next flush
315
+ }
316
+ eventQueue = eventQueue.slice(batch.length);
317
+ }
318
+ }
319
+ })();
320
+ // Clear AFTER assignment: an async body that finishes synchronously must not
321
+ // leave a settled promise stuck in `flushing`.
322
+ flushing = run;
323
+ void run.finally(() => {
324
+ if (flushing === run) flushing = null;
325
+ });
326
+ return run;
327
+ }
328
+
329
+ // MARK: - Public API
330
+
331
+ // Each open must reach the app once, however native delivered it (initial
332
+ // notification, buffered replay, live event). Keyed by delivery + action.
333
+ const seenOpens = [];
334
+ function firstSighting(open) {
335
+ if (!open.deliveryId) return true;
336
+ const key = `${open.deliveryId}:${open.actionId ?? ""}`;
337
+ if (seenOpens.includes(key)) return false;
338
+ seenOpens.push(key);
339
+ if (seenOpens.length > 50) seenOpens.shift();
340
+ return true;
341
+ }
342
+ function normalizeOpen(raw) {
343
+ if (!raw) return null;
344
+ return {
345
+ ...(raw.messageId ? {
346
+ messageId: raw.messageId
347
+ } : {}),
348
+ ...(raw.deliveryId ? {
349
+ deliveryId: raw.deliveryId
350
+ } : {}),
351
+ ...(raw.link ? {
352
+ link: raw.link
353
+ } : {}),
354
+ ...(raw.actionId ? {
355
+ actionId: raw.actionId
356
+ } : {}),
357
+ data: raw.data ?? {}
358
+ };
359
+ }
360
+ const Notifications = exports.Notifications = {
361
+ /**
362
+ * Ask the user for notification permission (native mode). On iOS,
363
+ * `provisional` delivers quietly with no prompt; Android ignores it
364
+ * (API 33+ shows the POST_NOTIFICATIONS dialog).
365
+ */
366
+ async requestPermission(options = {}) {
367
+ const raw = await (0, _module.getNativeModule)().pushRequestPermission(options.provisional === true);
368
+ return normalizePermissionStatus(raw);
369
+ },
370
+ async getPermissionStatus() {
371
+ return normalizePermissionStatus(await (0, _module.getNativeModule)().pushPermissionStatus());
372
+ },
373
+ /**
374
+ * Native mode. iOS: `registerForRemoteNotifications` (token captured
375
+ * natively). Android: fetches the FCM token through the native SDK. The
376
+ * device is upserted automatically once a token arrives.
377
+ */
378
+ async registerForPushNotifications() {
379
+ await (0, _module.getNativeModule)().pushRegister();
380
+ },
381
+ /**
382
+ * Manual mode: register a token you obtained elsewhere
383
+ * (`expo-notifications`' `getDevicePushTokenAsync()`, RNFirebase's
384
+ * `messaging().getToken()`). Idempotent — an identical registration in this
385
+ * session is not re-sent; call again after login/logout to relink the user.
386
+ *
387
+ * @returns the server's device id, or null when nothing needed sending.
388
+ */
389
+ async registerDeviceToken(token, provider, options = {}) {
390
+ if (!token) throw new Error("registerDeviceToken requires a non-empty token");
391
+ const body = await buildDeviceBody(token, provider, options);
392
+ // `null` vs omitted must not collapse into the same fingerprint, or an
393
+ // unlink right after a linked registration would be skipped.
394
+ const fingerprint = JSON.stringify(body, (_k, v) => v === null ? "\u0000null" : v);
395
+ if (fingerprint === lastSentFingerprint) return null;
396
+ const res = asRecord(await post("/api/sdk/push/devices", body));
397
+ lastSentFingerprint = fingerprint;
398
+ manualRegistered = true;
399
+ lastManual = {
400
+ token,
401
+ provider,
402
+ options
403
+ };
404
+ if (body.user_id !== undefined) unlinkPending = false; // the server was told (link or unlink)
405
+ return str(res?.device_id) ?? null;
406
+ },
407
+ /**
408
+ * Stop pushes to this install: marks the device unregistered on the server
409
+ * (token = null) and, in native mode, drops the OS registration. Call on
410
+ * sign-out if the next user should not receive this user's notifications —
411
+ * or simply call `Identity.logOut()`, which relinks the device.
412
+ */
413
+ async unregister() {
414
+ if (manualRegistered) {
415
+ try {
416
+ const body = await buildDeviceBody(null, (0, _module.getPlatformOS)() === "ios" ? "apns" : "fcm", {});
417
+ await post("/api/sdk/push/devices", body);
418
+ manualRegistered = false;
419
+ lastSentFingerprint = null;
420
+ } catch (e) {
421
+ console.warn("[SwissKnife Notifications] unregister failed:", e);
422
+ }
423
+ }
424
+ try {
425
+ await (0, _module.getNativeModule)().pushUnregister();
426
+ } catch {
427
+ // Native module absent/older: nothing to drop.
428
+ }
429
+ },
430
+ /**
431
+ * Record that the user opened a notification. Pass the notification `data`
432
+ * (or the whole expo-notifications response / RNFirebase message); foreign
433
+ * notifications are ignored. Returns true when an event was queued.
434
+ * Not needed in native mode, where opens are tracked automatically.
435
+ */
436
+ trackOpened(input, options = {}) {
437
+ const payload = extractPayload(input);
438
+ if (!payload) return false;
439
+ enqueue(payload, options.actionId ? "action" : "opened", options.actionId);
440
+ return true;
441
+ },
442
+ /** Record that a notification was delivered (foreground handler / background task). */
443
+ trackReceived(input) {
444
+ const payload = extractPayload(input);
445
+ if (!payload) return false;
446
+ enqueue(payload, "received");
447
+ return true;
448
+ },
449
+ extractPayload,
450
+ flushEvents,
451
+ /**
452
+ * Native mode: subscribe to tapped notifications (and action buttons).
453
+ * Returns a subscription; call `.remove()` to unsubscribe.
454
+ */
455
+ addNotificationOpenedListener(callback) {
456
+ const sub = (0, _module.getEventEmitter)().addListener(_spec.PUSH_OPENED_EVENT, event => {
457
+ const open = normalizeOpen(event);
458
+ if (open && firstSighting(open)) callback(open);
459
+ });
460
+ return {
461
+ remove: () => sub.remove()
462
+ };
463
+ },
464
+ /**
465
+ * Native mode: the notification that cold-started the app, once.
466
+ * On iOS this needs native auto-integration to be enabled before the
467
+ * launch finishes (see README, "Push notifications").
468
+ */
469
+ async getInitialNotification() {
470
+ const open = normalizeOpen(await (0, _module.getNativeModule)().pushGetInitialNotification());
471
+ return open && firstSighting(open) ? open : null;
472
+ }
473
+ };
474
+
475
+ /**
476
+ * @internal Called by `Identity.logOut/reset/wipe`: the one transition that
477
+ * unlinks the user. Re-upserts the manually registered device with
478
+ * `user_id: null`; a failure leaves the flag set so the next registration
479
+ * retries it.
480
+ */
481
+ function notifyExplicitLogout() {
482
+ unlinkPending = true;
483
+ const last = lastManual;
484
+ if (!manualRegistered || !last) return;
485
+ void Notifications.registerDeviceToken(last.token, last.provider, last.options).catch(() => {});
486
+ }
487
+
488
+ /** @internal Test seam. */
489
+ function __resetNotificationsForTests() {
490
+ lastSentFingerprint = null;
491
+ manualRegistered = false;
492
+ lastManual = null;
493
+ unlinkPending = false;
494
+ eventQueue = [];
495
+ seenOpens.length = 0;
496
+ flushing = null;
497
+ if (flushTimer) clearTimeout(flushTimer);
498
+ flushTimer = null;
499
+ }
500
+ //# sourceMappingURL=notifications.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["_module","require","_spec","_config","DEFAULT_SERVER_URL","asRecord","v","Array","isArray","str","length","undefined","fromRecord","data","sk","JSON","parse","skRec","messageId","m","deliveryId","d","link","img","imageUrl","sk_m","sk_d","sk_link","sk_img","extractPayload","input","root","notification","candidates","request","flatMap","req","trigger","content","type","payload","remoteMessage","c","rec","found","normalizePermissionStatus","raw","toLowerCase","baseUrl","serverURL","replace","PushHttpError","Error","constructor","status","path","isPermanentFailure","e","post","body","cfg","getServerConfig","res","fetch","method","headers","apiKey","stringify","ok","json","lastSentFingerprint","manualRegistered","lastManual","unlinkPending","nativeOrNull","read","buildDeviceBody","token","provider","options","platform","getPlatformOS","native","getNativeModule","installId","getDeviceId","identity","identityCurrent","info","pushDeviceInfo","bundleId","permission","permissionStatus","pushPermissionStatus","resolved","Intl","DateTimeFormat","resolvedOptions","environment","install_id","bundle_id","permission_status","userId","user_id","anonymousId","anonymous_id","appVersion","app_version","sdkVersion","sdk_version","osVersion","os_version","locale","timeZone","timezone","MAX_QUEUED_EVENTS","BATCH_SIZE","eventQueue","flushing","flushTimer","enqueue","actionId","dupe","some","delivery_id","action_id","push","message_id","occurred_at","Date","toISOString","slice","setTimeout","flushEvents","Promise","resolve","run","batch","events","finally","seenOpens","firstSighting","open","key","includes","shift","normalizeOpen","Notifications","exports","requestPermission","pushRequestPermission","provisional","getPermissionStatus","registerForPushNotifications","pushRegister","registerDeviceToken","fingerprint","_k","device_id","unregister","console","warn","pushUnregister","trackOpened","trackReceived","addNotificationOpenedListener","callback","sub","getEventEmitter","addListener","PUSH_OPENED_EVENT","event","remove","getInitialNotification","pushGetInitialNotification","notifyExplicitLogout","last","catch","__resetNotificationsForTests","clearTimeout"],"sourceRoot":"../../../src","sources":["modules/notifications.ts"],"mappings":";;;;;;;;;;;AAqBA,IAAAA,OAAA,GAAAC,OAAA;AACA,IAAAC,KAAA,GAAAD,OAAA;AAEA,IAAAE,OAAA,GAAAF,OAAA;AAxBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAOA,MAAMG,kBAAkB,GAAG,6BAA6B;;AAExD;;AAWA;;AAQA;;AAuBA;;AAEA,SAASC,QAAQA,CAACC,CAAU,EAAkC;EAC5D,OAAOA,CAAC,IAAI,OAAOA,CAAC,KAAK,QAAQ,IAAI,CAACC,KAAK,CAACC,OAAO,CAACF,CAAC,CAAC,GACjDA,CAAC,GACF,IAAI;AACV;AAEA,SAASG,GAAGA,CAACH,CAAU,EAAsB;EAC3C,OAAO,OAAOA,CAAC,KAAK,QAAQ,IAAIA,CAAC,CAACI,MAAM,GAA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AACqB,IAAI,CAACnG,KAAK,EAAEmG,IAAI,CAAClG,QAAQ,EAAEkG,IAAI,CAACjG,OAAO,CAAC,CAACkG,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;AACjG;;AAEA;AACO,SAASC,4BAA4BA,CAAA,EAAS;EACnD5G,mBAAmB,GAAG,IAAI;EAC1BC,gBAAgB,GAAG,KAAK;EACxBC,UAAU,GAAG,IAAI;EACjBC,aAAa,GAAG,KAAK;EACrB4C,UAAU,GAAG,EAAE;EACfuB,SAAS,CAAClI,MAAM,GAAG,CAAC;EACpB4G,QAAQ,GAAG,IAAI;EACf,IAAIC,UAAU,EAAE4D,YAAY,CAAC5D,UAAU,CAAC;EACxCA,UAAU,GAAG,IAAI;AACnB","ignoreList":[]}
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Performance = void 0;
7
+ var _telemetryContext = require("../internal/telemetry-context.js");
7
8
  var _ids = require("./ids.js");
8
9
  var _crashReporting = require("./crash-reporting.js");
9
10
  // packages/react-native-sdk/src/modules/performance.ts
@@ -129,6 +130,13 @@ class SpanImpl {
129
130
  // MARK: - Transaction Implementation
130
131
 
131
132
  class TransactionImpl {
133
+ correlation = (0, _telemetryContext.captureTelemetryContext)();
134
+ delivery = _config ? {
135
+ ..._config
136
+ } : null;
137
+ capturedBuild = _config?.buildNumber;
138
+ capturedRelease = _config?.release;
139
+ capturedEnvironment = _config?.environment ?? "production";
132
140
  endTime = null;
133
141
  status = "ok";
134
142
  tags = {};
@@ -139,12 +147,12 @@ class TransactionImpl {
139
147
  stallTotalMs: 0,
140
148
  stallLongestMs: 0
141
149
  };
142
- constructor(name, op) {
150
+ constructor(name, op, startedAt) {
143
151
  this.traceId = (0, _ids.generateTraceId)();
144
152
  this.spanId = (0, _ids.generateSpanId)();
145
153
  this.name = name;
146
154
  this.op = op;
147
- this.startTime = new Date();
155
+ this.startTime = startedAt ?? new Date();
148
156
  // Stall tracking runs for every real (non-sampled-out) transaction,
149
157
  // including the navigation-tracker ones constructed directly.
150
158
  registerOpenTransaction(this);
@@ -196,14 +204,16 @@ class TransactionImpl {
196
204
  const childPayloads = this._allChildSpans().map(s => s._toPayload());
197
205
  const payload = {
198
206
  traceId: this.traceId,
207
+ spanId: this.spanId,
199
208
  name: this.name,
200
209
  op: this.op,
201
210
  startTimestamp: this.startTime.toISOString(),
202
211
  endTimestamp: end.toISOString(),
203
212
  status: this.status,
204
213
  spans: childPayloads,
205
- release: _config?.release,
206
- environment: _config?.environment ?? "production",
214
+ release: this.capturedRelease,
215
+ buildNumber: this.capturedBuild,
216
+ environment: this.capturedEnvironment,
207
217
  measurements: {
208
218
  ...this.stalls
209
219
  },
@@ -255,6 +265,7 @@ const noopTransaction = {
255
265
  let _config = null;
256
266
  let _originalFetch = null;
257
267
  let _activeTransaction = null;
268
+ (0, _telemetryContext.setTelemetryTraceReader)(() => _activeTransaction?.traceId);
258
269
  let _txQueue = [];
259
270
  let _txFlushTimer = null;
260
271
 
@@ -303,19 +314,24 @@ async function flushTransactions() {
303
314
  if (!_config || _txQueue.length === 0) return;
304
315
  const batch = _txQueue;
305
316
  _txQueue = [];
306
- const baseURL = _config.serverURL || "https://api.swiss-knife.dev";
307
- const url = `${baseURL}/api/sdk/errors/transaction`;
317
+
308
318
  // Use original fetch if we've patched it
309
319
  const fetchFn = _originalFetch ?? fetch;
310
320
  for (const transaction of batch) {
321
+ const config = transaction.delivery;
322
+ if (!config) continue;
323
+ const url = `${config.serverURL || "https://api.swiss-knife.dev"}/api/sdk/errors/transaction`;
311
324
  try {
312
325
  const res = await fetchFn(url, {
313
326
  method: "POST",
314
327
  headers: {
315
328
  "Content-Type": "application/json",
316
- "X-API-Key": _config.apiKey
329
+ "X-API-Key": config.apiKey
317
330
  },
318
- body: JSON.stringify(transaction._toPayload())
331
+ body: JSON.stringify({
332
+ ...transaction._toPayload(),
333
+ ...(await transaction.correlation)
334
+ })
319
335
  });
320
336
  if (!res.ok) {
321
337
  console.warn(`[SwissKnife Performance] send failed: HTTP ${res.status}`);
@@ -417,6 +433,22 @@ function createNavigationTracker() {
417
433
  };
418
434
  }
419
435
 
436
+ // MARK: - App Start
437
+
438
+ /** When this module was evaluated: the best JS-side stand-in for process start. */
439
+ const MODULE_LOADED_AT = new Date();
440
+ let _appStart = null;
441
+ let _appStartDone = false;
442
+ function beginAppStart() {
443
+ if (_appStartDone || _appStart) return;
444
+ const rate = resolveSampleRate("app.start", "app.start");
445
+ if (rate <= 0 || rate < 1.0 && Math.random() > rate) {
446
+ _appStartDone = true;
447
+ return;
448
+ }
449
+ _appStart = new TransactionImpl("app.start", "app.start", MODULE_LOADED_AT);
450
+ }
451
+
420
452
  // MARK: - Main Export
421
453
 
422
454
  const Performance = exports.Performance = {
@@ -429,6 +461,21 @@ const Performance = exports.Performance = {
429
461
  if (_config.enableAutoHTTP) {
430
462
  installFetchInstrumentation();
431
463
  }
464
+ if (_config.trackAppStart) {
465
+ beginAppStart();
466
+ }
467
+ },
468
+ /**
469
+ * Ends the `app.start` transaction begun by `trackAppStart: true`. Call it
470
+ * when the first screen is interactive. Once per launch; a no-op when
471
+ * app-start tracking is off, sampled out, or already finished.
472
+ */
473
+ finishAppStart(status = "ok") {
474
+ if (!_appStart) return;
475
+ const tx = _appStart;
476
+ _appStart = null;
477
+ _appStartDone = true;
478
+ tx.finish(status);
432
479
  },
433
480
  startTransaction(name, op) {
434
481
  const rate = resolveSampleRate(name, op);
@@ -464,6 +511,8 @@ const Performance = exports.Performance = {
464
511
 
465
512
  _reset() {
466
513
  _config = null;
514
+ _appStart = null;
515
+ _appStartDone = false;
467
516
  _activeTransaction = null;
468
517
  _txQueue = [];
469
518
  if (_txFlushTimer !== null) {