appsonair-react-native-apppush 0.0.1-alpha

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +540 -0
  3. package/android/build.gradle +177 -0
  4. package/android/gradle.properties +15 -0
  5. package/android/src/main/AndroidManifest.xml +2 -0
  6. package/android/src/main/AndroidManifestNew.xml +2 -0
  7. package/android/src/main/java/com/appsonairreactnativeapppush/AppsonairReactNativeApppushModuleImpl.kt +767 -0
  8. package/android/src/main/java/com/appsonairreactnativeapppush/AppsonairReactNativeApppushPackage.kt +43 -0
  9. package/android/src/newarch/java/com/appsonairreactnativeapppush/AppsonairReactNativeApppushModule.kt +199 -0
  10. package/android/src/oldarch/java/com/appsonairreactnativeapppush/AppsonairReactNativeApppushModule.kt +249 -0
  11. package/appsonair-react-native-apppush.podspec +77 -0
  12. package/ios/AppsonairReactNativeApppush-Bridging-Header.h +12 -0
  13. package/ios/AppsonairReactNativeApppush.h +28 -0
  14. package/ios/AppsonairReactNativeApppush.mm +494 -0
  15. package/ios/AppsonairReactNativeApppushImpl.swift +594 -0
  16. package/lib/commonjs/NativeAppsonairApppush.js +48 -0
  17. package/lib/commonjs/NativeAppsonairApppush.js.map +1 -0
  18. package/lib/commonjs/index.js +686 -0
  19. package/lib/commonjs/index.js.map +1 -0
  20. package/lib/commonjs/types.js +2 -0
  21. package/lib/commonjs/types.js.map +1 -0
  22. package/lib/module/NativeAppsonairApppush.js +47 -0
  23. package/lib/module/NativeAppsonairApppush.js.map +1 -0
  24. package/lib/module/index.js +612 -0
  25. package/lib/module/index.js.map +1 -0
  26. package/lib/module/types.js +2 -0
  27. package/lib/module/types.js.map +1 -0
  28. package/lib/typescript/commonjs/package.json +1 -0
  29. package/lib/typescript/commonjs/src/NativeAppsonairApppush.d.ts +134 -0
  30. package/lib/typescript/commonjs/src/NativeAppsonairApppush.d.ts.map +1 -0
  31. package/lib/typescript/commonjs/src/index.d.ts +392 -0
  32. package/lib/typescript/commonjs/src/index.d.ts.map +1 -0
  33. package/lib/typescript/commonjs/src/types.d.ts +221 -0
  34. package/lib/typescript/commonjs/src/types.d.ts.map +1 -0
  35. package/lib/typescript/module/package.json +1 -0
  36. package/lib/typescript/module/src/NativeAppsonairApppush.d.ts +134 -0
  37. package/lib/typescript/module/src/NativeAppsonairApppush.d.ts.map +1 -0
  38. package/lib/typescript/module/src/index.d.ts +392 -0
  39. package/lib/typescript/module/src/index.d.ts.map +1 -0
  40. package/lib/typescript/module/src/types.d.ts +221 -0
  41. package/lib/typescript/module/src/types.d.ts.map +1 -0
  42. package/package.json +119 -0
  43. package/react-native.config.js +14 -0
  44. package/src/NativeAppsonairApppush.ts +188 -0
  45. package/src/index.tsx +745 -0
  46. package/src/types.ts +284 -0
package/src/index.tsx ADDED
@@ -0,0 +1,745 @@
1
+ import {
2
+ NativeEventEmitter,
3
+ NativeModules,
4
+ Platform,
5
+ TurboModuleRegistry,
6
+ type EmitterSubscription,
7
+ } from 'react-native';
8
+
9
+ import type { Spec } from './NativeAppsonairApppush';
10
+ import type {
11
+ InstallationIdEvent,
12
+ LogLevel,
13
+ NotificationOpenedEvent,
14
+ NotificationReceivedEvent,
15
+ NotificationWillDisplayEvent,
16
+ PermissionChangedEvent,
17
+ PermissionStatus,
18
+ PushConfig,
19
+ PushErrorEvent,
20
+ PushNotification,
21
+ PushSubscriptionChangedEvent,
22
+ PushSubscriptionState,
23
+ RequestPermissionOptions,
24
+ SilentNotificationEvent,
25
+ Subscription,
26
+ TokenUpdatedEvent,
27
+ UserStateChangedEvent,
28
+ } from './types';
29
+
30
+ export * from './types';
31
+
32
+ const LINKING_ERROR =
33
+ `The package 'appsonair-react-native-apppush' doesn't seem to be linked. Make sure: \n\n` +
34
+ Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
35
+ '- You rebuilt the app after installing the package\n' +
36
+ '- You are not using Expo Go\n';
37
+
38
+ /**
39
+ * Resolves the native module on both architectures.
40
+ *
41
+ * `TurboModuleRegistry.get` returns the TurboModule when the New Architecture is
42
+ * on and falls back to the legacy `NativeModules` entry when it is off, so one
43
+ * lookup covers both. The `NativeModules` read is the belt-and-braces path for
44
+ * hosts where the registry is unavailable; the Proxy then turns a missing module
45
+ * into an actionable message instead of `undefined is not an object`.
46
+ */
47
+ const NativePush: Spec =
48
+ TurboModuleRegistry.get<Spec>('AppsonairReactNativeApppush') ??
49
+ (NativeModules.AppsonairReactNativeApppush as Spec | undefined) ??
50
+ (new Proxy(
51
+ {},
52
+ {
53
+ get() {
54
+ throw new Error(LINKING_ERROR);
55
+ },
56
+ }
57
+ ) as Spec);
58
+
59
+ const emitter = new NativeEventEmitter(
60
+ // The legacy bridge needs the module instance to route `addListener`;
61
+ // the New Architecture ignores this argument entirely.
62
+ NativeModules.AppsonairReactNativeApppush ?? undefined
63
+ );
64
+
65
+ // MARK: - Event names
66
+ // Kept in one place because the native bridges hardcode these same strings — a
67
+ // rename has to happen in four files at once: here,
68
+ // AppsonairReactNativeApppushModuleImpl.kt, AppsonairReactNativeApppushImpl.swift and
69
+ // the supportedEvents list in AppsonairReactNativeApppush.mm.
70
+
71
+ const EVENT = {
72
+ notificationReceived: 'AppsonairPush:onNotificationReceived',
73
+ notificationOpened: 'AppsonairPush:onNotificationOpened',
74
+ notificationWillDisplay: 'AppsonairPush:onNotificationWillDisplay',
75
+ permissionChanged: 'AppsonairPush:onPermissionChanged',
76
+ subscriptionChanged: 'AppsonairPush:onSubscriptionChanged',
77
+ userStateChanged: 'AppsonairPush:onUserStateChanged',
78
+ tokenUpdated: 'AppsonairPush:onTokenUpdated',
79
+ silentNotification: 'AppsonairPush:onSilentNotification',
80
+ installationIdUpdated: 'AppsonairPush:onInstallationIdUpdated',
81
+ error: 'AppsonairPush:onError',
82
+ } as const;
83
+
84
+ // MARK: - Initialization guard
85
+ //
86
+ // Parity I1: calling before `initialize()` emits a catchable error on iOS but
87
+ // throws `IllegalStateException` on Android — a hard crash. The wrapper tracks
88
+ // initialisation itself so the same misuse produces the same rejected promise
89
+ // on both platforms and the Android `check()` never reaches the app.
90
+
91
+ let initialized = false;
92
+
93
+ class PushNotInitializedError extends Error {
94
+ readonly code = 'notInitialized';
95
+ constructor(method: string) {
96
+ super(
97
+ `AppPushService.${method}() was called before initialize(). ` +
98
+ 'Await initialize() once at app start before using the SDK.'
99
+ );
100
+ this.name = 'PushNotInitializedError';
101
+ }
102
+ }
103
+
104
+ class PushArgumentError extends Error {
105
+ readonly code = 'invalidArgument';
106
+ constructor(message: string) {
107
+ super(message);
108
+ this.name = 'PushArgumentError';
109
+ }
110
+ }
111
+
112
+ function guard<T>(method: string, call: () => Promise<T>): Promise<T> {
113
+ if (!initialized) {
114
+ return Promise.reject(new PushNotInitializedError(method));
115
+ }
116
+ return call();
117
+ }
118
+
119
+ /**
120
+ * Parity I2: `login("")` logs and returns on iOS but throws
121
+ * `IllegalArgumentException` on Android. Validated here so neither happens.
122
+ */
123
+ function requireNonEmpty(value: string, label: string): void {
124
+ if (typeof value !== 'string' || value.trim().length === 0) {
125
+ throw new PushArgumentError(`${label} must be a non-empty string.`);
126
+ }
127
+ }
128
+
129
+ // MARK: - Lifecycle
130
+
131
+ /**
132
+ * Starts the SDK. Await this once, before any other call.
133
+ *
134
+ * On Android the wrapper supplies the `Context` itself; on iOS it resolves the
135
+ * App Group and enables AppDelegate swizzling. Neither detail is exposed here.
136
+ */
137
+ export async function initialize(config: PushConfig = {}): Promise<void> {
138
+ await NativePush.initialize({ debug: config.debug ?? false });
139
+ initialized = true;
140
+ }
141
+
142
+ /** Whether {@link initialize} has completed in this JS context. */
143
+ export function isInitialized(): boolean {
144
+ return initialized;
145
+ }
146
+
147
+ // MARK: - Identity
148
+
149
+ /** The AppsOnAir-assigned device id. */
150
+ export function getDeviceId(): Promise<string> {
151
+ return guard('getDeviceId', () => NativePush.getDeviceId());
152
+ }
153
+
154
+ /** The backend-assigned subscription id. `null` until the device registers. */
155
+ export function getSubscriptionId(): Promise<string | null> {
156
+ return guard('getSubscriptionId', () => NativePush.getSubscriptionId());
157
+ }
158
+
159
+ /** The external id linked via {@link login}. `null` while anonymous. */
160
+ export function getExternalId(): Promise<string | null> {
161
+ return guard('getExternalId', () => NativePush.getExternalId());
162
+ }
163
+
164
+ /** Associates this device with your own user id. */
165
+ export function login(externalId: string): Promise<void> {
166
+ requireNonEmpty(externalId, 'externalId');
167
+ return guard('login', () => NativePush.login(externalId));
168
+ }
169
+
170
+ /** Unlinks the external id, returning the device to an anonymous subscription. */
171
+ export function logout(): Promise<void> {
172
+ return guard('logout', () => NativePush.logout());
173
+ }
174
+
175
+ /** Alias of {@link login}, for teams that prefer the noun. */
176
+ export const setUserId = login;
177
+
178
+ // MARK: - Token
179
+
180
+ /** APNs hex token on iOS, FCM token on Android. `null` before registration. */
181
+ export function getToken(): Promise<string | null> {
182
+ return guard('getToken', () => NativePush.getToken());
183
+ }
184
+
185
+ /** Alias of {@link getToken}. */
186
+ export const getDeviceToken = getToken;
187
+
188
+ // MARK: - Permissions
189
+
190
+ /**
191
+ * Prompts for notification permission and resolves the resulting grant state.
192
+ *
193
+ * Parity E1: Android needs a live Activity. The bridge resolves the current one
194
+ * and rejects if none is attached rather than crashing.
195
+ */
196
+ export function requestPermission(
197
+ options: RequestPermissionOptions = {}
198
+ ): Promise<boolean> {
199
+ return guard('requestPermission', () =>
200
+ NativePush.requestPermission(options.fallbackToSettings ?? false)
201
+ );
202
+ }
203
+
204
+ /**
205
+ * Whether notifications are currently permitted.
206
+ *
207
+ * Parity E3/E4/E6: iOS reads a cache and Android reads live, so the iOS bridge
208
+ * refreshes first. The two native shapes (`async` vs sync, `permission` vs
209
+ * `isPermissionGranted`) are collapsed into this one promise.
210
+ */
211
+ export function getPermission(): Promise<boolean> {
212
+ return guard('getPermission', () => NativePush.getPermission());
213
+ }
214
+
215
+ /**
216
+ * The granular permission state.
217
+ *
218
+ * Parity C7: iOS reports all five values. **Android reports only `authorized`
219
+ * or `denied`** — it never returns `notDetermined`, so do not gate a
220
+ * cross-platform pre-prompt on that value.
221
+ */
222
+ export function getPermissionStatus(): Promise<PermissionStatus> {
223
+ return guard('getPermissionStatus', () =>
224
+ NativePush.getPermissionStatus()
225
+ ) as Promise<PermissionStatus>;
226
+ }
227
+
228
+ /**
229
+ * Whether a permission prompt can still be shown.
230
+ *
231
+ * Parity E2 — **known divergence, not yet fixed in the native SDKs.** iOS
232
+ * returns `true` only before the user has ever been asked. Android returns
233
+ * `true` whenever permission is not granted, *including after a permanent
234
+ * denial*. Treat a `true` on Android as "not granted", not as "never asked".
235
+ */
236
+ export function canRequestPermission(): Promise<boolean> {
237
+ return guard('canRequestPermission', () => NativePush.canRequestPermission());
238
+ }
239
+
240
+ /** Quiet iOS 12+ provisional authorization. **iOS only** — a no-op on Android. */
241
+ export function registerForProvisionalAuthorization(): Promise<void> {
242
+ return guard('registerForProvisionalAuthorization', () =>
243
+ NativePush.registerForProvisionalAuthorization()
244
+ );
245
+ }
246
+
247
+ // MARK: - Notifications namespace
248
+
249
+ export const notifications = {
250
+ /** Dismisses every notification this app has posted. */
251
+ clearAll(): Promise<void> {
252
+ return guard('notifications.clearAll', () =>
253
+ NativePush.clearAllNotifications()
254
+ );
255
+ },
256
+
257
+ /**
258
+ * Dismisses one notification by its payload `notification_id`.
259
+ *
260
+ * Parity F2: on Android the id is hashed to find the posted notification, so
261
+ * two ids that hash alike could collide. iOS matches the request identifier
262
+ * exactly.
263
+ */
264
+ remove(notificationId: string): Promise<void> {
265
+ requireNonEmpty(notificationId, 'notificationId');
266
+ return guard('notifications.remove', () =>
267
+ NativePush.removeNotification(notificationId)
268
+ );
269
+ },
270
+
271
+ /** Dismisses several notifications. Android loops; iOS removes them in one call. */
272
+ removeMany(notificationIds: string[]): Promise<void> {
273
+ if (!Array.isArray(notificationIds)) {
274
+ throw new PushArgumentError(
275
+ 'notificationIds must be an array of strings.'
276
+ );
277
+ }
278
+ return guard('notifications.removeMany', () =>
279
+ NativePush.removeNotifications(notificationIds)
280
+ );
281
+ },
282
+
283
+ /** Dismisses a notification group. **Android only** — a no-op on iOS. */
284
+ removeGroup(groupKey: string): Promise<void> {
285
+ requireNonEmpty(groupKey, 'groupKey');
286
+ return guard('notifications.removeGroup', () =>
287
+ NativePush.removeNotificationGroup(groupKey)
288
+ );
289
+ },
290
+ };
291
+
292
+ // MARK: - Badges
293
+
294
+ export const badge = {
295
+ /**
296
+ * The SDK's badge count.
297
+ *
298
+ * Parity G1/G3: iOS reads the OS badge. Android has no OS read API, so this
299
+ * returns the SDK's own persisted value, which can drift from what the
300
+ * launcher actually shows.
301
+ */
302
+ get(): Promise<number> {
303
+ return guard('badge.get', () => NativePush.getBadgeCount());
304
+ },
305
+
306
+ /**
307
+ * Sets the badge count.
308
+ *
309
+ * Parity G3: reliable on iOS. On Android this is a best-effort launcher
310
+ * broadcast that silently does nothing outside Samsung / MIUI / ASUS — which
311
+ * is why nothing here reports success.
312
+ */
313
+ set(count: number): Promise<void> {
314
+ if (!Number.isFinite(count) || count < 0) {
315
+ throw new PushArgumentError('badge count must be a non-negative number.');
316
+ }
317
+ return guard('badge.set', () => NativePush.setBadgeCount(count));
318
+ },
319
+
320
+ /** Adds `delta` to the badge and resolves the new value, clamped at 0. */
321
+ increment(delta = 1): Promise<number> {
322
+ if (!Number.isFinite(delta)) {
323
+ throw new PushArgumentError('badge delta must be a number.');
324
+ }
325
+ return guard('badge.increment', () =>
326
+ NativePush.incrementBadgeCount(delta)
327
+ );
328
+ },
329
+
330
+ /** Clears the badge. */
331
+ clear(): Promise<void> {
332
+ return guard('badge.clear', () => NativePush.clearBadgeCount());
333
+ },
334
+
335
+ /** Clears the badge whenever the app foregrounds. **iOS only.** */
336
+ setAutoClearOnForeground(enabled: boolean): Promise<void> {
337
+ return guard('badge.setAutoClearOnForeground', () =>
338
+ NativePush.setAutoClearBadgeOnForeground(enabled)
339
+ );
340
+ },
341
+ };
342
+
343
+ // MARK: - User namespace
344
+
345
+ export const user = {
346
+ /** The AppsOnAir device id. */
347
+ getAppsOnAirId(): Promise<string> {
348
+ return guard('user.getAppsOnAirId', () => NativePush.getDeviceId());
349
+ },
350
+
351
+ getExternalId,
352
+
353
+ addTag(key: string, value: string): Promise<void> {
354
+ requireNonEmpty(key, 'tag key');
355
+ return guard('user.addTag', () => NativePush.addTag(key, value));
356
+ },
357
+
358
+ addTags(tags: Record<string, string>): Promise<void> {
359
+ return guard('user.addTags', () => NativePush.addTags(tags));
360
+ },
361
+
362
+ removeTag(key: string): Promise<void> {
363
+ requireNonEmpty(key, 'tag key');
364
+ return guard('user.removeTag', () => NativePush.removeTag(key));
365
+ },
366
+
367
+ removeTags(keys: string[]): Promise<void> {
368
+ return guard('user.removeTags', () => NativePush.removeTags(keys));
369
+ },
370
+
371
+ /**
372
+ * The user's tags.
373
+ *
374
+ * **Android round-trips to the backend** once the device has a
375
+ * `subscriptionId`, replacing its local cache with the result; before
376
+ * registration it resolves the local cache without a network call. **iOS reads
377
+ * its local cache only.** So a tag set on another device shows up on Android
378
+ * and not on iOS, and the Android call can reject on a network failure where
379
+ * iOS cannot.
380
+ */
381
+ getTags(): Promise<Record<string, string>> {
382
+ return guard('user.getTags', () => NativePush.getTags()) as Promise<
383
+ Record<string, string>
384
+ >;
385
+ },
386
+
387
+ addAlias(label: string, id: string): Promise<void> {
388
+ requireNonEmpty(label, 'alias label');
389
+ requireNonEmpty(id, 'alias id');
390
+ return guard('user.addAlias', () => NativePush.addAlias(label, id));
391
+ },
392
+
393
+ addAliases(aliases: Record<string, string>): Promise<void> {
394
+ return guard('user.addAliases', () => NativePush.addAliases(aliases));
395
+ },
396
+
397
+ removeAlias(label: string): Promise<void> {
398
+ requireNonEmpty(label, 'alias label');
399
+ return guard('user.removeAlias', () => NativePush.removeAlias(label));
400
+ },
401
+
402
+ removeAliases(labels: string[]): Promise<void> {
403
+ return guard('user.removeAliases', () => NativePush.removeAliases(labels));
404
+ },
405
+
406
+ /**
407
+ * Adds an email identifier.
408
+ *
409
+ * Parity A5 — **known Android bug.** Android persists emails but never reads
410
+ * them back on restart, so an email added here silently vanishes when the app
411
+ * relaunches. The wrapper cannot work around it; it needs an SDK fix.
412
+ */
413
+ addEmail(address: string): Promise<void> {
414
+ requireNonEmpty(address, 'email address');
415
+ return guard('user.addEmail', () => NativePush.addEmail(address));
416
+ },
417
+
418
+ removeEmail(address: string): Promise<void> {
419
+ requireNonEmpty(address, 'email address');
420
+ return guard('user.removeEmail', () => NativePush.removeEmail(address));
421
+ },
422
+
423
+ setLanguage(languageCode: string): Promise<void> {
424
+ requireNonEmpty(languageCode, 'languageCode');
425
+ return guard('user.setLanguage', () =>
426
+ NativePush.setLanguage(languageCode)
427
+ );
428
+ },
429
+
430
+ /**
431
+ * The device language.
432
+ *
433
+ * Parity 1.5 — Android reads this live; iOS snapshots it once at init and
434
+ * never refreshes, so a mid-session language change is stale on iOS.
435
+ */
436
+ getLanguage(): Promise<string> {
437
+ return guard('user.getLanguage', () => NativePush.getLanguage());
438
+ },
439
+
440
+ /** The current push subscription: `{ id, token, optedIn }`. */
441
+ getPushSubscription(): Promise<PushSubscriptionState> {
442
+ return guard('user.getPushSubscription', () =>
443
+ NativePush.getPushSubscription()
444
+ ) as Promise<PushSubscriptionState>;
445
+ },
446
+
447
+ /** Opts this device back in to push delivery. */
448
+ optIn(): Promise<void> {
449
+ return guard('user.optIn', () => NativePush.optIn());
450
+ },
451
+
452
+ /** Opts this device out of push delivery without unregistering the token. */
453
+ optOut(): Promise<void> {
454
+ return guard('user.optOut', () => NativePush.optOut());
455
+ },
456
+
457
+ /**
458
+ * The subscription's enabled state as the backend sees it.
459
+ *
460
+ * Distinct from `getPushSubscription().optedIn`, which is the purely local
461
+ * `!optedOut` flag on both platforms. The two derive it differently and
462
+ * converge only in steady state:
463
+ *
464
+ * - **Android** reads it back from `/subscriptions`, so it reflects what the
465
+ * server actually stored. Before the device registers it falls back to the
466
+ * local value without a network call.
467
+ * - **iOS** computes the same flag it would send: an APNs token exists, the
468
+ * user has not opted out, *and* the OS currently grants permission. So
469
+ * revoking permission in Settings flips this to `false` on iOS while
470
+ * Android keeps reporting the server's stored value.
471
+ */
472
+ getOptedIn(): Promise<boolean> {
473
+ return guard('user.getOptedIn', () => NativePush.getOptedIn());
474
+ },
475
+ };
476
+
477
+ // MARK: - Consent
478
+ //
479
+ // Parity I5: both SDKs store these flags but neither enforces them. They are
480
+ // exposed because they round-trip, but they are not a compliance control yet —
481
+ // setting `consentGiven` to false does not currently gate anything.
482
+
483
+ export const consent = {
484
+ setRequired(required: boolean): Promise<void> {
485
+ return guard('consent.setRequired', () =>
486
+ NativePush.setConsentRequired(required)
487
+ );
488
+ },
489
+ getRequired(): Promise<boolean> {
490
+ return guard('consent.getRequired', () => NativePush.getConsentRequired());
491
+ },
492
+ setGiven(given: boolean): Promise<void> {
493
+ return guard('consent.setGiven', () => NativePush.setConsentGiven(given));
494
+ },
495
+ getGiven(): Promise<boolean> {
496
+ return guard('consent.getGiven', () => NativePush.getConsentGiven());
497
+ },
498
+ };
499
+
500
+ // MARK: - Debug
501
+
502
+ export const debug = {
503
+ /** Sets SDK log verbosity. Safe to call before {@link initialize}. */
504
+ setLogLevel(level: LogLevel): Promise<void> {
505
+ return NativePush.setLogLevel(level);
506
+ },
507
+ };
508
+
509
+ // MARK: - Events
510
+
511
+ function subscribe<T>(
512
+ eventName: string,
513
+ callback: (event: T) => void
514
+ ): Subscription {
515
+ const sub: EmitterSubscription = emitter.addListener(eventName, callback);
516
+ return { remove: () => sub.remove() };
517
+ }
518
+
519
+ /** Fires when a notification arrives while the app is in the foreground. */
520
+ export function onNotificationReceived(
521
+ callback: (event: NotificationReceivedEvent) => void
522
+ ): Subscription {
523
+ return subscribe(EVENT.notificationReceived, callback);
524
+ }
525
+
526
+ /** Fires when the user taps a notification or one of its action buttons. */
527
+ export function onNotificationOpened(
528
+ callback: (event: NotificationOpenedEvent) => void
529
+ ): Subscription {
530
+ return subscribe(EVENT.notificationOpened, callback);
531
+ }
532
+
533
+ /**
534
+ * Fires in the foreground *before* the notification is displayed, giving you a
535
+ * chance to suppress it.
536
+ *
537
+ * `preventDefault()` must be called synchronously inside the handler — the
538
+ * native side is holding the notification until this returns, and releases it
539
+ * anyway after a short timeout so a throwing handler cannot wedge delivery.
540
+ *
541
+ * All registered handlers run; the notification is suppressed if *any* of them
542
+ * calls `preventDefault()`.
543
+ *
544
+ * **`preventDefault()` is honoured on Android only.** iOS decides presentation
545
+ * synchronously and cannot wait for a JS answer — see
546
+ * {@link NotificationWillDisplayEvent.preventDefault}. The event itself fires on
547
+ * both platforms.
548
+ */
549
+ export function onNotificationWillDisplay(
550
+ callback: (event: NotificationWillDisplayEvent) => void
551
+ ): Subscription {
552
+ willDisplayHandlers.add(callback);
553
+ ensureWillDisplayBridge();
554
+ return {
555
+ remove: () => {
556
+ willDisplayHandlers.delete(callback);
557
+ if (willDisplayHandlers.size === 0) {
558
+ willDisplayBridge?.remove();
559
+ willDisplayBridge = null;
560
+ }
561
+ },
562
+ };
563
+ }
564
+
565
+ type WillDisplayHandler = (event: NotificationWillDisplayEvent) => void;
566
+
567
+ const willDisplayHandlers = new Set<WillDisplayHandler>();
568
+ let willDisplayBridge: EmitterSubscription | null = null;
569
+
570
+ /**
571
+ * One emitter subscription fans out to every handler, so
572
+ * `completeNotificationWillDisplay` is called exactly once per notification no
573
+ * matter how many handlers are registered. Completing twice would release the
574
+ * same held notification twice on the native side.
575
+ */
576
+ function ensureWillDisplayBridge(): void {
577
+ if (willDisplayBridge) return;
578
+
579
+ willDisplayBridge = emitter.addListener(
580
+ EVENT.notificationWillDisplay,
581
+ (payload: { notification: PushNotification }) => {
582
+ let prevented = false;
583
+ const event: NotificationWillDisplayEvent = {
584
+ notification: payload.notification,
585
+ preventDefault: () => {
586
+ prevented = true;
587
+ },
588
+ };
589
+
590
+ for (const handler of willDisplayHandlers) {
591
+ try {
592
+ handler(event);
593
+ } catch (error) {
594
+ // A throwing handler must not stop the remaining handlers, and must
595
+ // not prevent the completion call below — otherwise the native side
596
+ // holds the notification until its timeout for no reason.
597
+ console.error(
598
+ '[AppPushService] onNotificationWillDisplay handler threw',
599
+ error
600
+ );
601
+ }
602
+ }
603
+
604
+ const id = payload.notification?.id;
605
+ if (id != null) {
606
+ NativePush.completeNotificationWillDisplay(id, !prevented).catch(() => {
607
+ // The native side falls back to displaying the notification when the
608
+ // completion never lands, so there is nothing to recover here.
609
+ });
610
+ }
611
+ }
612
+ );
613
+ }
614
+
615
+ /** Fires when the OS notification permission changes. */
616
+ export function onPermissionChanged(
617
+ callback: (event: PermissionChangedEvent) => void
618
+ ): Subscription {
619
+ return subscribe(EVENT.permissionChanged, callback);
620
+ }
621
+
622
+ /** Fires when the push subscription's token or opt-in state changes. */
623
+ export function onSubscriptionChanged(
624
+ callback: (event: PushSubscriptionChangedEvent) => void
625
+ ): Subscription {
626
+ return subscribe(EVENT.subscriptionChanged, callback);
627
+ }
628
+
629
+ /** Fires on {@link login} / {@link logout}. */
630
+ export function onUserStateChanged(
631
+ callback: (event: UserStateChangedEvent) => void
632
+ ): Subscription {
633
+ return subscribe(EVENT.userStateChanged, callback);
634
+ }
635
+
636
+ /**
637
+ * Fires when the device registration token is issued or refreshed.
638
+ *
639
+ * This is the push-side counterpart to {@link getToken}: the getter answers
640
+ * "what is the token now", this answers "the token just changed" — which is when
641
+ * your backend needs to hear about it. A token can rotate at any point in a
642
+ * session, so a one-shot `getToken()` at startup will eventually go stale.
643
+ *
644
+ * `environment` is the APNs endpoint the backend must send to. It is
645
+ * `'sandbox'` or `'production'` on iOS and always `null` on Android, where FCM
646
+ * routes for you.
647
+ *
648
+ * Events raised before the first subscriber exists are dropped rather than
649
+ * queued on both platforms, so read {@link getToken} once after subscribing if
650
+ * you need the current value too.
651
+ */
652
+ export function onTokenUpdated(
653
+ callback: (event: TokenUpdatedEvent) => void
654
+ ): Subscription {
655
+ return subscribe(EVENT.tokenUpdated, callback);
656
+ }
657
+
658
+ /**
659
+ * Fires on an SDK-level failure — token registration, a denied permission, a
660
+ * missing Firebase config.
661
+ *
662
+ * These are conditions the SDK hits on its own schedule, outside any call you
663
+ * made, so they surface here rather than as a rejected promise. A promise
664
+ * rejection from a method you called carries the same `code` values.
665
+ *
666
+ * Without a subscriber these failures are silent, which is why this is worth
667
+ * wiring even if it only ever logs.
668
+ */
669
+ export function onError(
670
+ callback: (event: PushErrorEvent) => void
671
+ ): Subscription {
672
+ return subscribe(EVENT.error, callback);
673
+ }
674
+
675
+ /**
676
+ * Fires for a data-only push that is delivered without being displayed.
677
+ *
678
+ * Supported on both platforms, but they are triggered differently and your
679
+ * backend has to send for both: iOS uses the APNs `content-available` flag,
680
+ * while Android keys off a `silent: "true"` data entry, since FCM has no
681
+ * transport-level equivalent. See {@link SilentNotificationEvent}.
682
+ *
683
+ * iOS invokes the OS completion handler as soon as this event is emitted, so
684
+ * the handler cannot extend the app's background execution window: treat it as
685
+ * a notification that the payload arrived, not as a place to await work.
686
+ */
687
+ export function onSilentNotification(
688
+ callback: (event: SilentNotificationEvent) => void
689
+ ): Subscription {
690
+ return subscribe(EVENT.silentNotification, callback);
691
+ }
692
+
693
+ /**
694
+ * Fires when the Firebase Installation ID becomes available.
695
+ *
696
+ * **Android only** — the event name is registered on iOS so the two bridges
697
+ * stay diffable, but nothing ever emits it there.
698
+ */
699
+ export function onInstallationIdUpdated(
700
+ callback: (event: InstallationIdEvent) => void
701
+ ): Subscription {
702
+ return subscribe(EVENT.installationIdUpdated, callback);
703
+ }
704
+
705
+ // MARK: - Default export
706
+
707
+ const AppPushService = {
708
+ initialize,
709
+ isInitialized,
710
+
711
+ getDeviceId,
712
+ getSubscriptionId,
713
+ getExternalId,
714
+ login,
715
+ logout,
716
+ setUserId,
717
+
718
+ getToken,
719
+ getDeviceToken,
720
+
721
+ requestPermission,
722
+ getPermission,
723
+ getPermissionStatus,
724
+ canRequestPermission,
725
+ registerForProvisionalAuthorization,
726
+
727
+ notifications,
728
+ badge,
729
+ user,
730
+ consent,
731
+ debug,
732
+
733
+ onNotificationReceived,
734
+ onNotificationOpened,
735
+ onNotificationWillDisplay,
736
+ onPermissionChanged,
737
+ onSubscriptionChanged,
738
+ onUserStateChanged,
739
+ onTokenUpdated,
740
+ onError,
741
+ onSilentNotification,
742
+ onInstallationIdUpdated,
743
+ };
744
+
745
+ export default AppPushService;