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