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