@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,557 @@
1
+ // src/modules/notifications.ts
2
+ //
3
+ // Push notifications (swiss-push v1). Two integration modes share one API:
4
+ //
5
+ // 1. NATIVE mode — the Swiss Knife native SDK owns permission, the OS token
6
+ // (APNs on iOS, FCM on Android), upserts the device and tracks opens.
7
+ // await Notifications.requestPermission();
8
+ // await Notifications.registerForPushNotifications();
9
+ // Notifications.addNotificationOpenedListener(open => router.push(open.link));
10
+ //
11
+ // 2. MANUAL mode — the app already owns push through `expo-notifications`
12
+ // (`getDevicePushTokenAsync()`) or `@react-native-firebase/messaging`.
13
+ // It hands us the token and forwards open/receive payloads; everything
14
+ // here is pure JS and talks to the backend with `fetch`.
15
+ // const { data, type } = await Notifications2.getDevicePushTokenAsync();
16
+ // await Notifications.registerDeviceToken(data, type === "ios" ? "apns" : "fcm");
17
+ // Notifications.trackOpened(response);
18
+ //
19
+ // Wire contract: see the push contract (endpoints /api/sdk/push/devices and
20
+ // /api/sdk/push/events; payload keys `sk` on iOS, `sk_*` on Android).
21
+
22
+ import { getEventEmitter, getNativeModule, getPlatformOS } from "../native/module";
23
+ import { PUSH_OPENED_EVENT } from "../native/spec";
24
+ import type { NativePushOpen } from "../native/spec";
25
+ import { getServerConfig } from "../internal/config";
26
+
27
+ const DEFAULT_SERVER_URL = "https://api.swiss-knife.dev";
28
+
29
+ // MARK: - Types
30
+
31
+ export type PushProvider = "apns" | "fcm";
32
+
33
+ export type PermissionStatus =
34
+ | "authorized"
35
+ | "provisional"
36
+ | "denied"
37
+ | "not_determined"
38
+ | "ephemeral";
39
+
40
+ /** Swiss Knife metadata extracted from a notification's data. */
41
+ export interface PushPayload {
42
+ messageId: string;
43
+ deliveryId: string;
44
+ link?: string;
45
+ imageUrl?: string;
46
+ }
47
+
48
+ /** A tapped notification (or action button), as delivered by native mode. */
49
+ export interface NotificationOpen {
50
+ messageId?: string;
51
+ deliveryId?: string;
52
+ link?: string;
53
+ actionId?: string;
54
+ data: Record<string, unknown>;
55
+ }
56
+
57
+ export interface RegisterDeviceTokenOptions {
58
+ /** iOS only. Defaults to native detection (provisioning profile), else "production". */
59
+ environment?: "production" | "sandbox";
60
+ /** Defaults to the native permission status, else "authorized". Accepts expo-notifications' values too. */
61
+ permissionStatus?: string;
62
+ /** Override when the native module cannot supply it. */
63
+ bundleId?: string;
64
+ }
65
+
66
+ export interface TrackOptions {
67
+ /** Set when a custom action button was pressed; the event becomes `action`. */
68
+ actionId?: string;
69
+ }
70
+
71
+ // MARK: - Payload extraction
72
+
73
+ function asRecord(v: unknown): Record<string, unknown> | null {
74
+ return v && typeof v === "object" && !Array.isArray(v)
75
+ ? (v as Record<string, unknown>)
76
+ : null;
77
+ }
78
+
79
+ function str(v: unknown): string | undefined {
80
+ return typeof v === "string" && v.length > 0 ? v : undefined;
81
+ }
82
+
83
+ function fromRecord(data: Record<string, unknown>): PushPayload | null {
84
+ // iOS: reserved `sk` dictionary (an object, or a JSON string when a
85
+ // library stringified nested data).
86
+ let sk = data.sk;
87
+ if (typeof sk === "string") {
88
+ try {
89
+ sk = JSON.parse(sk);
90
+ } catch {
91
+ sk = undefined;
92
+ }
93
+ }
94
+ const skRec = asRecord(sk);
95
+ if (skRec) {
96
+ const messageId = str(skRec.m);
97
+ const deliveryId = str(skRec.d);
98
+ if (messageId && deliveryId) {
99
+ return {
100
+ messageId,
101
+ deliveryId,
102
+ ...(str(skRec.link) ? { link: str(skRec.link) } : {}),
103
+ ...(str(skRec.img) ? { imageUrl: str(skRec.img) } : {}),
104
+ };
105
+ }
106
+ }
107
+ // Android: flat string map, `sk_*` keys.
108
+ const messageId = str(data.sk_m);
109
+ const deliveryId = str(data.sk_d);
110
+ if (messageId && deliveryId) {
111
+ return {
112
+ messageId,
113
+ deliveryId,
114
+ ...(str(data.sk_link) ? { link: str(data.sk_link) } : {}),
115
+ ...(str(data.sk_img) ? { imageUrl: str(data.sk_img) } : {}),
116
+ };
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * Pull the Swiss Knife payload out of whatever a push library hands you.
123
+ * Accepts the bare `data` object (iOS `sk` or Android `sk_*` shapes), and the
124
+ * common wrappers: expo-notifications' `response` / `notification` and
125
+ * RNFirebase's `remoteMessage`. Returns null for foreign notifications.
126
+ */
127
+ export function extractPayload(input: unknown): PushPayload | null {
128
+ const root = asRecord(input);
129
+ if (!root) return null;
130
+ const notification = asRecord(root.notification);
131
+ const candidates: unknown[] = [
132
+ root,
133
+ root.data,
134
+ ...[root.request, notification?.request].flatMap(request => {
135
+ const req = asRecord(request);
136
+ const trigger = asRecord(req?.trigger);
137
+ return [asRecord(req?.content)?.data, ...(trigger?.type === "push"
138
+ ? [trigger.payload, asRecord(trigger.remoteMessage)?.data] : [])];
139
+ }),
140
+ notification?.data,
141
+ ];
142
+ for (const c of candidates) {
143
+ const rec = asRecord(c);
144
+ if (!rec) continue;
145
+ const found = fromRecord(rec);
146
+ if (found) return found;
147
+ }
148
+ return null;
149
+ }
150
+
151
+ // MARK: - Permission mapping
152
+
153
+ /**
154
+ * Normalize a permission status from any source (our native modules, or
155
+ * expo-notifications' `granted`/`denied`/`undetermined`) to the wire enum.
156
+ */
157
+ export function normalizePermissionStatus(raw: unknown): PermissionStatus {
158
+ switch (typeof raw === "string" ? raw.toLowerCase() : "") {
159
+ case "authorized":
160
+ case "granted":
161
+ return "authorized";
162
+ case "provisional":
163
+ return "provisional";
164
+ case "ephemeral":
165
+ return "ephemeral";
166
+ case "denied":
167
+ case "blocked":
168
+ return "denied";
169
+ default:
170
+ return "not_determined";
171
+ }
172
+ }
173
+
174
+ // MARK: - HTTP
175
+
176
+ function baseUrl(serverURL: string): string {
177
+ return (serverURL || DEFAULT_SERVER_URL).replace(/\/+$/, "");
178
+ }
179
+
180
+ class PushHttpError extends Error {
181
+ constructor(readonly status: number, path: string) {
182
+ super(`Swiss Knife push request ${path} failed: HTTP ${status}`);
183
+ }
184
+ }
185
+
186
+ /** 4xx other than 408/429 will never succeed on retry. */
187
+ function isPermanentFailure(e: unknown): boolean {
188
+ return e instanceof PushHttpError && e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 429;
189
+ }
190
+
191
+ async function post(path: string, body: unknown): Promise<unknown> {
192
+ const cfg = getServerConfig();
193
+ if (!cfg) {
194
+ throw new Error(
195
+ "Swiss Knife is not configured. Call SwissKnife.configure(), SwissKnife.configureCore() or Analytics.init() before using Notifications."
196
+ );
197
+ }
198
+ const res = await fetch(`${baseUrl(cfg.serverURL)}${path}`, {
199
+ method: "POST",
200
+ headers: { "Content-Type": "application/json", "X-API-Key": cfg.apiKey },
201
+ body: JSON.stringify(body),
202
+ });
203
+ if (!res.ok) {
204
+ throw new PushHttpError(res.status, path);
205
+ }
206
+ try {
207
+ return await res.json();
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ // MARK: - Manual registration
214
+
215
+ let lastSentFingerprint: string | null = null;
216
+ let manualRegistered = false;
217
+ /** Last manual registration, so a logout can relink the device. */
218
+ let lastManual: { token: string; provider: PushProvider; options: RegisterDeviceTokenOptions } | null = null;
219
+ /**
220
+ * True only after an EXPLICIT logout/reset/wipe. Identity is in-memory in the
221
+ * native SDKs, so after a relaunch it is "unknown", not "logged out": then
222
+ * `user_id` is omitted (the server keeps the link). Only this flag turns
223
+ * "no user" into an explicit `user_id: null` (server unlinks).
224
+ */
225
+ let unlinkPending = false;
226
+
227
+ interface DeviceBody {
228
+ install_id: string;
229
+ platform: "ios" | "android";
230
+ provider: PushProvider;
231
+ token: string | null;
232
+ environment?: "production" | "sandbox";
233
+ bundle_id: string;
234
+ permission_status: PermissionStatus;
235
+ /** null = explicitly logged out (server unlinks); absent = keep the existing link. */
236
+ user_id?: string | null;
237
+ anonymous_id?: string;
238
+ app_version?: string;
239
+ sdk_version?: string;
240
+ os_version?: string;
241
+ locale?: string;
242
+ timezone?: string;
243
+ }
244
+
245
+ async function nativeOrNull<T>(read: () => Promise<T>): Promise<T | null> {
246
+ try {
247
+ return await read();
248
+ } catch {
249
+ return null;
250
+ }
251
+ }
252
+
253
+ async function buildDeviceBody(
254
+ token: string | null,
255
+ provider: PushProvider,
256
+ options: RegisterDeviceTokenOptions
257
+ ): Promise<DeviceBody> {
258
+ const platform = getPlatformOS();
259
+ if (platform === "ios" && provider !== "apns") {
260
+ throw new Error('iOS devices register with provider "apns" (FCM on iOS is not supported in v1).');
261
+ }
262
+ if (platform === "android" && provider !== "fcm") {
263
+ throw new Error('Android devices register with provider "fcm".');
264
+ }
265
+ const native = getNativeModule();
266
+ const installId = await native.getDeviceId();
267
+ const identity = await nativeOrNull(() => native.identityCurrent());
268
+ const info = await nativeOrNull(() => native.pushDeviceInfo());
269
+ const bundleId = options.bundleId ?? info?.bundleId;
270
+ if (!bundleId) {
271
+ throw new Error("Could not determine the bundle id / package name; pass options.bundleId.");
272
+ }
273
+ const permission =
274
+ options.permissionStatus !== undefined
275
+ ? normalizePermissionStatus(options.permissionStatus)
276
+ : normalizePermissionStatus(
277
+ await nativeOrNull(() => native.pushPermissionStatus()) ?? "authorized"
278
+ );
279
+ const resolved = (() => {
280
+ try {
281
+ return Intl.DateTimeFormat().resolvedOptions();
282
+ } catch {
283
+ return null;
284
+ }
285
+ })();
286
+ const environment =
287
+ platform === "ios"
288
+ ? options.environment ?? (info?.environment === "sandbox" ? "sandbox" : "production")
289
+ : undefined;
290
+ return {
291
+ install_id: installId,
292
+ platform,
293
+ provider,
294
+ token,
295
+ ...(environment ? { environment } : {}),
296
+ bundle_id: bundleId,
297
+ permission_status: permission,
298
+ ...(identity?.userId
299
+ ? { user_id: identity.userId }
300
+ : unlinkPending
301
+ ? { user_id: null }
302
+ : {}),
303
+ ...(identity?.anonymousId ? { anonymous_id: identity.anonymousId } : {}),
304
+ ...(info?.appVersion ? { app_version: info.appVersion } : {}),
305
+ ...(info?.sdkVersion ? { sdk_version: info.sdkVersion } : {}),
306
+ ...(info?.osVersion ? { os_version: info.osVersion } : {}),
307
+ ...(resolved?.locale ? { locale: resolved.locale } : {}),
308
+ ...(resolved?.timeZone ? { timezone: resolved.timeZone } : {}),
309
+ };
310
+ }
311
+
312
+ // MARK: - Event queue (manual tracking)
313
+
314
+ interface PushEventWire {
315
+ delivery_id: string;
316
+ message_id: string;
317
+ type: "received" | "opened" | "action";
318
+ action_id?: string;
319
+ occurred_at: string;
320
+ }
321
+
322
+ const MAX_QUEUED_EVENTS = 200;
323
+ const BATCH_SIZE = 100;
324
+ let eventQueue: PushEventWire[] = [];
325
+ let flushing: Promise<void> | null = null;
326
+ let flushTimer: ReturnType<typeof setTimeout> | null = null;
327
+
328
+ function enqueue(payload: PushPayload, type: PushEventWire["type"], actionId?: string): void {
329
+ const dupe = eventQueue.some(
330
+ (e) =>
331
+ e.delivery_id === payload.deliveryId &&
332
+ e.type === type &&
333
+ (e.action_id ?? "") === (actionId ?? "")
334
+ );
335
+ if (dupe) return;
336
+ eventQueue.push({
337
+ delivery_id: payload.deliveryId,
338
+ message_id: payload.messageId,
339
+ type,
340
+ ...(actionId ? { action_id: actionId } : {}),
341
+ occurred_at: new Date().toISOString(),
342
+ });
343
+ if (eventQueue.length > MAX_QUEUED_EVENTS) {
344
+ eventQueue = eventQueue.slice(eventQueue.length - MAX_QUEUED_EVENTS);
345
+ }
346
+ // Coalesce a burst into one request.
347
+ if (!flushTimer) {
348
+ flushTimer = setTimeout(() => {
349
+ flushTimer = null;
350
+ void flushEvents();
351
+ }, 0);
352
+ }
353
+ }
354
+
355
+ /** Send queued `received`/`opened` events now. Failed batches stay queued. */
356
+ export function flushEvents(): Promise<void> {
357
+ if (flushing) return flushing;
358
+ if (eventQueue.length === 0) return Promise.resolve();
359
+ const run = (async () => {
360
+ {
361
+ while (eventQueue.length > 0) {
362
+ const batch = eventQueue.slice(0, BATCH_SIZE);
363
+ try {
364
+ await post("/api/sdk/push/events", { events: batch });
365
+ } catch (e) {
366
+ if (isPermanentFailure(e)) {
367
+ // Rejected for good (bad payload / key): drop the batch, keep going.
368
+ eventQueue = eventQueue.slice(batch.length);
369
+ continue;
370
+ }
371
+ return; // offline / 429 / 5xx / not configured: keep for the next flush
372
+ }
373
+ eventQueue = eventQueue.slice(batch.length);
374
+ }
375
+ }
376
+ })();
377
+ // Clear AFTER assignment: an async body that finishes synchronously must not
378
+ // leave a settled promise stuck in `flushing`.
379
+ flushing = run;
380
+ void run.finally(() => {
381
+ if (flushing === run) flushing = null;
382
+ });
383
+ return run;
384
+ }
385
+
386
+ // MARK: - Public API
387
+
388
+ // Each open must reach the app once, however native delivered it (initial
389
+ // notification, buffered replay, live event). Keyed by delivery + action.
390
+ const seenOpens: string[] = [];
391
+ function firstSighting(open: NotificationOpen): boolean {
392
+ if (!open.deliveryId) return true;
393
+ const key = `${open.deliveryId}:${open.actionId ?? ""}`;
394
+ if (seenOpens.includes(key)) return false;
395
+ seenOpens.push(key);
396
+ if (seenOpens.length > 50) seenOpens.shift();
397
+ return true;
398
+ }
399
+
400
+ function normalizeOpen(raw: NativePushOpen | null | undefined): NotificationOpen | null {
401
+ if (!raw) return null;
402
+ return {
403
+ ...(raw.messageId ? { messageId: raw.messageId } : {}),
404
+ ...(raw.deliveryId ? { deliveryId: raw.deliveryId } : {}),
405
+ ...(raw.link ? { link: raw.link } : {}),
406
+ ...(raw.actionId ? { actionId: raw.actionId } : {}),
407
+ data: raw.data ?? {},
408
+ };
409
+ }
410
+
411
+ export const Notifications = {
412
+ /**
413
+ * Ask the user for notification permission (native mode). On iOS,
414
+ * `provisional` delivers quietly with no prompt; Android ignores it
415
+ * (API 33+ shows the POST_NOTIFICATIONS dialog).
416
+ */
417
+ async requestPermission(options: { provisional?: boolean } = {}): Promise<PermissionStatus> {
418
+ const raw = await getNativeModule().pushRequestPermission(options.provisional === true);
419
+ return normalizePermissionStatus(raw);
420
+ },
421
+
422
+ async getPermissionStatus(): Promise<PermissionStatus> {
423
+ return normalizePermissionStatus(await getNativeModule().pushPermissionStatus());
424
+ },
425
+
426
+ /**
427
+ * Native mode. iOS: `registerForRemoteNotifications` (token captured
428
+ * natively). Android: fetches the FCM token through the native SDK. The
429
+ * device is upserted automatically once a token arrives.
430
+ */
431
+ async registerForPushNotifications(): Promise<void> {
432
+ await getNativeModule().pushRegister();
433
+ },
434
+
435
+ /**
436
+ * Manual mode: register a token you obtained elsewhere
437
+ * (`expo-notifications`' `getDevicePushTokenAsync()`, RNFirebase's
438
+ * `messaging().getToken()`). Idempotent — an identical registration in this
439
+ * session is not re-sent; call again after login/logout to relink the user.
440
+ *
441
+ * @returns the server's device id, or null when nothing needed sending.
442
+ */
443
+ async registerDeviceToken(
444
+ token: string,
445
+ provider: PushProvider,
446
+ options: RegisterDeviceTokenOptions = {}
447
+ ): Promise<string | null> {
448
+ if (!token) throw new Error("registerDeviceToken requires a non-empty token");
449
+ const body = await buildDeviceBody(token, provider, options);
450
+ // `null` vs omitted must not collapse into the same fingerprint, or an
451
+ // unlink right after a linked registration would be skipped.
452
+ const fingerprint = JSON.stringify(body, (_k, v) => (v === null ? "\u0000null" : v));
453
+ if (fingerprint === lastSentFingerprint) return null;
454
+ const res = asRecord(await post("/api/sdk/push/devices", body));
455
+ lastSentFingerprint = fingerprint;
456
+ manualRegistered = true;
457
+ lastManual = { token, provider, options };
458
+ if (body.user_id !== undefined) unlinkPending = false; // the server was told (link or unlink)
459
+ return str(res?.device_id) ?? null;
460
+ },
461
+
462
+ /**
463
+ * Stop pushes to this install: marks the device unregistered on the server
464
+ * (token = null) and, in native mode, drops the OS registration. Call on
465
+ * sign-out if the next user should not receive this user's notifications —
466
+ * or simply call `Identity.logOut()`, which relinks the device.
467
+ */
468
+ async unregister(): Promise<void> {
469
+ if (manualRegistered) {
470
+ try {
471
+ const body = await buildDeviceBody(null, getPlatformOS() === "ios" ? "apns" : "fcm", {});
472
+ await post("/api/sdk/push/devices", body);
473
+ manualRegistered = false;
474
+ lastSentFingerprint = null;
475
+ } catch (e) {
476
+ console.warn("[SwissKnife Notifications] unregister failed:", e);
477
+ }
478
+ }
479
+ try {
480
+ await getNativeModule().pushUnregister();
481
+ } catch {
482
+ // Native module absent/older: nothing to drop.
483
+ }
484
+ },
485
+
486
+ /**
487
+ * Record that the user opened a notification. Pass the notification `data`
488
+ * (or the whole expo-notifications response / RNFirebase message); foreign
489
+ * notifications are ignored. Returns true when an event was queued.
490
+ * Not needed in native mode, where opens are tracked automatically.
491
+ */
492
+ trackOpened(input: unknown, options: TrackOptions = {}): boolean {
493
+ const payload = extractPayload(input);
494
+ if (!payload) return false;
495
+ enqueue(payload, options.actionId ? "action" : "opened", options.actionId);
496
+ return true;
497
+ },
498
+
499
+ /** Record that a notification was delivered (foreground handler / background task). */
500
+ trackReceived(input: unknown): boolean {
501
+ const payload = extractPayload(input);
502
+ if (!payload) return false;
503
+ enqueue(payload, "received");
504
+ return true;
505
+ },
506
+
507
+ extractPayload,
508
+ flushEvents,
509
+
510
+ /**
511
+ * Native mode: subscribe to tapped notifications (and action buttons).
512
+ * Returns a subscription; call `.remove()` to unsubscribe.
513
+ */
514
+ addNotificationOpenedListener(callback: (open: NotificationOpen) => void): { remove(): void } {
515
+ const sub = getEventEmitter().addListener(PUSH_OPENED_EVENT, (event) => {
516
+ const open = normalizeOpen(event as NativePushOpen);
517
+ if (open && firstSighting(open)) callback(open);
518
+ });
519
+ return { remove: () => sub.remove() };
520
+ },
521
+
522
+ /**
523
+ * Native mode: the notification that cold-started the app, once.
524
+ * On iOS this needs native auto-integration to be enabled before the
525
+ * launch finishes (see README, "Push notifications").
526
+ */
527
+ async getInitialNotification(): Promise<NotificationOpen | null> {
528
+ const open = normalizeOpen(await getNativeModule().pushGetInitialNotification());
529
+ return open && firstSighting(open) ? open : null;
530
+ },
531
+ };
532
+
533
+ /**
534
+ * @internal Called by `Identity.logOut/reset/wipe`: the one transition that
535
+ * unlinks the user. Re-upserts the manually registered device with
536
+ * `user_id: null`; a failure leaves the flag set so the next registration
537
+ * retries it.
538
+ */
539
+ export function notifyExplicitLogout(): void {
540
+ unlinkPending = true;
541
+ const last = lastManual;
542
+ if (!manualRegistered || !last) return;
543
+ void Notifications.registerDeviceToken(last.token, last.provider, last.options).catch(() => {});
544
+ }
545
+
546
+ /** @internal Test seam. */
547
+ export function __resetNotificationsForTests(): void {
548
+ lastSentFingerprint = null;
549
+ manualRegistered = false;
550
+ lastManual = null;
551
+ unlinkPending = false;
552
+ eventQueue = [];
553
+ seenOpens.length = 0;
554
+ flushing = null;
555
+ if (flushTimer) clearTimeout(flushTimer);
556
+ flushTimer = null;
557
+ }