@chipmobilesdk/rn-notification 0.5.0 → 0.6.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 (37) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +100 -10
  3. package/package.json +6 -1
  4. package/skills/sdk-rn-notification/SKILL.md +6 -5
  5. package/src/advanced.ts +35 -0
  6. package/src/channel/migrate.ts +176 -158
  7. package/src/channel/tone-map.ts +2 -10
  8. package/src/contract/errors.ts +7 -0
  9. package/src/contract/hash.ts +26 -0
  10. package/src/engine/adapter.ts +21 -1
  11. package/src/engine/notify-kit/events.ts +155 -0
  12. package/src/engine/notify-kit/module.ts +148 -0
  13. package/src/engine/notify-kit/platform/android.ts +172 -0
  14. package/src/engine/notify-kit/platform/index.ts +55 -0
  15. package/src/engine/notify-kit/platform/ios.ts +54 -0
  16. package/src/engine/notify-kit/platform/types.ts +40 -0
  17. package/src/engine/notify-kit-engine.ts +96 -477
  18. package/src/index.ts +9 -0
  19. package/src/notifications.ts +195 -0
  20. package/src/permission/index.ts +65 -4
  21. package/src/push/fcm-provider.ts +14 -4
  22. package/src/push/gate.ts +27 -5
  23. package/src/reconcile/diff.ts +38 -27
  24. package/src/reconcile/index.ts +13 -4
  25. package/src/recurrence/index.ts +2 -1
  26. package/src/repeat/expiry.ts +2 -6
  27. package/src/repeat/index.ts +45 -1
  28. package/src/repeat/marker.ts +1 -22
  29. package/src/repeat/place.ts +74 -35
  30. package/src/schedule/index.ts +10 -4
  31. package/src/schedule/partition.ts +0 -19
  32. package/src/schedule/validate-identifier.ts +8 -6
  33. package/src/schedule/writer.ts +13 -4
  34. package/src/state/caps.ts +28 -3
  35. package/src/state/permission-history.ts +25 -0
  36. package/src/state/record.ts +110 -20
  37. package/src/testing/fake-engine.ts +17 -1
@@ -1,112 +1,49 @@
1
1
  /**
2
2
  * The `react-native-notify-kit` engine implementation.
3
3
  *
4
- * Every import of the engine is confined to this file. Nothing above it knows
5
- * which engine is in use — which is what allowed the original Notifee choice to
6
- * be swapped for its maintained fork without touching a requirement, a test, or
7
- * a line of consumer code.
4
+ * Nothing above this adapter knows which engine is in use — which is what
5
+ * allowed the original Notifee choice to be swapped for its maintained fork
6
+ * without touching a requirement, a test, or a line of consumer code.
8
7
  *
9
- * The module is required lazily so the package loads in Jest and in any
10
- * environment without the native module. An absent engine is reported through
11
- * the normal diagnostic path rather than crashing at import time.
8
+ * This file is what both platforms share: scheduling, cancelling, reading the
9
+ * pending set, and routing events. The engine module and its constants live in
10
+ * `notify-kit/module.ts`, decoding in `notify-kit/events.ts`, and everything
11
+ * that differs between Android and iOS in `notify-kit/platform/` — chosen once
12
+ * when the engine is created (NOT-18, IOS-08).
12
13
  */
13
14
 
14
- import { lazyPeer } from '@chipmobilesdk/rn-core';
15
-
16
- import { Platform } from 'react-native';
17
15
  import type {
18
16
  NotificationEngineAdapter,
19
17
  DeliveryEvent,
20
- EngineCapabilities,
21
18
  EngineScheduleRequest,
22
19
  RepeatStop,
23
- ToneDeclarationOutcome,
24
20
  } from './adapter';
25
21
  import { isRepeatStopId } from '../repeat/marker';
26
- import { packData, unpackData } from './codec';
22
+ import { packData } from './codec';
27
23
  import type { PendingEntry } from '../contract/notification';
28
- import type { PermissionKind, PermissionState, RestrictionReport } from '../contract/permission';
29
- import type { ResolvedTone, ChannelGroup } from '../contract/channel';
24
+ import type { PermissionKind, PermissionState } from '../contract/permission';
30
25
  import type { InteractionEvent, Unsubscribe } from '../contract/interaction';
31
26
  import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
32
-
33
- /**
34
- * iOS keeps only the 64 soonest pending notifications and silently discards the
35
- * rest. This number is the entire reason truncation must be computed and
36
- * reported by the package rather than left to the platform.
37
- */
38
- const IOS_PENDING_CEILING = 64;
39
-
40
- /** Android has no comparable hard ceiling; this bound keeps behavior predictable. */
41
- const ANDROID_PENDING_BUDGET = 500;
42
-
43
- /** Both platforms bound background execution for a silent payload or background action. */
44
- const BACKGROUND_WINDOW_MS = 30_000;
45
-
46
- /**
47
- * The engine's own enum values, mirrored as literals.
48
- *
49
- * These are **numeric** enums in the engine's type definitions, and its native
50
- * validator rejects the string names — `importance: 'default'` fails with
51
- * "expected a valid Importance". Mirroring them here rather than importing the
52
- * enums keeps the engine out of the module graph, which is what lets the
53
- * package load without the native module present.
54
- *
55
- * The package's own `ResolvedTone` deliberately stays platform-neutral strings;
56
- * translating to the engine's representation is this adapter's job and nobody
57
- * else's.
58
- */
59
- const ANDROID_IMPORTANCE = {
60
- none: 0,
61
- min: 1,
62
- low: 2,
63
- default: 3,
64
- high: 4,
65
- } as const;
66
-
67
- /** `TriggerType.TIMESTAMP`. */
68
- const TRIGGER_TYPE_TIMESTAMP = 0;
69
-
70
- /** `AlarmType.SET_EXACT_AND_ALLOW_WHILE_IDLE` — exact delivery, survives Doze. */
71
- const ALARM_TYPE_EXACT_AND_ALLOW_WHILE_IDLE = 3;
72
-
73
- /** `AlarmType.SET_AND_ALLOW_WHILE_IDLE` — the approximate degradation of the above. */
74
- const ALARM_TYPE_INEXACT_AND_ALLOW_WHILE_IDLE = 1;
75
-
76
- /**
77
- * `EventType` values that represent a real user interaction.
78
- *
79
- * The engine emits far more than interactions on this channel — `DELIVERED`,
80
- * `TRIGGER_NOTIFICATION_CREATED`, `CHANNEL_BLOCKED` and others all arrive here.
81
- * Treating anything that is not a dismissal as a press would report a
82
- * notification *arriving* while the app is open as the user having tapped it,
83
- * and the interaction path cancels on tap — so the notification would vanish
84
- * from the tray in front of the user, unread.
85
- */
86
- const EVENT_TYPE_DISMISSED = 0;
87
- const EVENT_TYPE_PRESS = 1;
88
- const EVENT_TYPE_ACTION_PRESS = 2;
89
-
90
- /** `EventType.DELIVERED` — an arrival, which is emphatically not an interaction. */
91
- const EVENT_TYPE_DELIVERED = 3;
92
-
93
- /**
94
- * `AndroidCategory.ALARM`, the engine's marking for a time-sensitive alert.
95
- *
96
- * A per-notification property, not channel configuration — which is why
97
- * declaring `timeSensitive` on an existing tone never obliges a version bump.
98
- */
99
- const ANDROID_CATEGORY_ALARM = 'alarm';
100
-
101
- /**
102
- * The channel stop markers are posted on.
103
- *
104
- * A marker exists to be delivered and immediately removed, so it is given the
105
- * quietest configuration the platform offers: minimum importance, no sound, no
106
- * vibration. Its version is fixed because nothing about it is consumer-declared,
107
- * so it never migrates.
108
- */
109
- const MARKER_CHANNEL_ID = 'cms.internal.stop.v1';
27
+ import type { PlatformInfo } from '../permission/state';
28
+ import {
29
+ toDelivery,
30
+ toInteraction,
31
+ toPermissionState,
32
+ unpackEntry,
33
+ unpackRepeatStops,
34
+ } from './notify-kit/events';
35
+ import {
36
+ ALARM_TYPE_EXACT_AND_ALLOW_WHILE_IDLE,
37
+ ALARM_TYPE_INEXACT_AND_ALLOW_WHILE_IDLE,
38
+ ANDROID_CATEGORY_ALARM,
39
+ ANDROID_IMPORTANCE,
40
+ MARKER_CHANNEL_ID,
41
+ TRIGGER_TYPE_TIMESTAMP,
42
+ compact,
43
+ loadEngine,
44
+ type NotifyKitModule,
45
+ } from './notify-kit/module';
46
+ import { createNotifyKitPlatform } from './notify-kit/platform';
110
47
 
111
48
  /**
112
49
  * Whether this *process* has a background delivery handler.
@@ -118,104 +55,20 @@ const MARKER_CHANNEL_ID = 'cms.internal.stop.v1';
118
55
  * because the warning tells the consumer to fix something that is not broken.
119
56
  */
120
57
  let backgroundHandlerRegistered = false;
121
-
122
- /** Minimal shape used from the engine, so its full surface never leaks into typing. */
123
- interface NotifyKitModule {
124
- createChannel(channel: Record<string, unknown>): Promise<string>;
125
- deleteChannel(channelId: string): Promise<void>;
126
- /**
127
- * Labels come back with the id. That is what makes a label refresh decidable
128
- * against the device rather than against a ledger of our own — and a ledger
129
- * drifts after a restore, a reinstall, or a change the user made themselves.
130
- */
131
- getChannels(): Promise<{ id: string; name?: string; description?: string }[]>;
132
- createChannelGroup(group: Record<string, unknown>): Promise<string>;
133
- createTriggerNotification(
134
- notification: Record<string, unknown>,
135
- trigger: Record<string, unknown>,
136
- ): Promise<string>;
137
- displayNotification(notification: Record<string, unknown>): Promise<string>;
138
- getDisplayedNotifications(): Promise<Record<string, unknown>[]>;
139
- cancelNotification(id: string): Promise<void>;
140
- cancelAllNotifications(): Promise<void>;
141
- getTriggerNotifications(): Promise<Record<string, unknown>[]>;
142
- onBackgroundEvent(handler: (event: Record<string, unknown>) => Promise<void>): void;
143
- requestPermission(options?: Record<string, unknown>): Promise<Record<string, unknown>>;
144
- getNotificationSettings(): Promise<Record<string, unknown>>;
145
- openNotificationSettings(): Promise<void>;
146
- openAlarmPermissionSettings(): Promise<void>;
147
- isBatteryOptimizationEnabled(): Promise<boolean>;
148
- onForegroundEvent(handler: (event: Record<string, unknown>) => void): () => void;
149
- getInitialNotification(): Promise<Record<string, unknown> | null>;
150
- }
151
-
152
- /**
153
- * Drops keys whose value is `undefined`.
154
- *
155
- * The engine validates its arguments by key presence, not by value: passing
156
- * `{ groupId: undefined }` fails with "expected a string value", while omitting
157
- * the key entirely is accepted. JavaScript treats the two as interchangeable
158
- * almost everywhere, which is exactly why this is easy to get wrong — and why
159
- * it only surfaces on a real device, where the native validator runs.
160
- */
161
- function compact<T extends Record<string, unknown>>(value: T): Partial<T> {
162
- const output: Record<string, unknown> = {};
163
- for (const [key, entry] of Object.entries(value)) {
164
- if (entry !== undefined) output[key] = entry;
165
- }
166
- return output as Partial<T>;
167
- }
168
-
169
- const notifyKit = lazyPeer('react-native-notify-kit', () => {
170
- // Inside `try`, so Metro bundles an app that leaves this optional peer out.
171
- try {
172
- return require('react-native-notify-kit') as { default: NotifyKitModule };
173
- } catch (cause) {
174
- throw cause;
175
- }
176
- });
177
-
178
- function loadEngine(): NotifyKitModule {
179
- return notifyKit.require(
180
- (_peer, cause) =>
181
- new NotificationError(
182
- DIAGNOSTIC_CODES.PUSH_UNAVAILABLE,
183
- 'react-native-notify-kit is not installed or its native module is not linked. Install it as a peer dependency and rebuild the app.',
184
- { reason: cause instanceof Error ? cause.name : 'unknown' },
185
- ),
186
- ).default;
187
- }
188
-
189
58
  /**
190
- * Maps engine authorization values onto our six-state model.
191
- *
192
- * `notAsked` and `denied` must stay distinguishable — being able to read state
193
- * without prompting is worthless if the two collapse. `provisional` is its own
194
- * state on both edges, never folded into granted or denied.
59
+ * Interaction subscribers alive in this process, across engine instances: the
60
+ * one registered at module scope in `index.js` and the one the app's runtime
61
+ * uses are different instances, and a background interaction has to reach the
62
+ * runtime's subscribers when there are any (NOT-10).
195
63
  */
196
- function toPermissionState(raw: unknown): PermissionState {
197
- switch (raw) {
198
- case 1:
199
- case 'authorized':
200
- return 'granted';
201
- case 2:
202
- case 'provisional':
203
- return 'provisional';
204
- case 0:
205
- case 'denied':
206
- return 'denied';
207
- case -1:
208
- case 'notDetermined':
209
- return 'notAsked';
210
- default:
211
- return 'notAsked';
212
- }
213
- }
64
+ const liveInteractionListeners = new Set<(event: InteractionEvent) => void>();
214
65
 
215
66
  export interface NotifyKitEngineOptions {
216
67
  /** Injected in tests; production resolves the real module. */
217
68
  readonly module?: NotifyKitModule;
218
69
  readonly now?: () => number;
70
+ /** Defaults to the running platform. Injected to test one platform's behaviour. */
71
+ readonly platform?: PlatformInfo;
219
72
  }
220
73
 
221
74
  export function createNotifyKitEngine(
@@ -224,154 +77,29 @@ export function createNotifyKitEngine(
224
77
  let cached: NotifyKitModule | undefined = options.module;
225
78
  const engine = (): NotifyKitModule => (cached ??= loadEngine());
226
79
  const now = options.now ?? (() => Date.now());
80
+ const platform = createNotifyKitPlatform(engine, options.platform);
227
81
 
228
- /** Reads a stop marker back out of a pending entry's data bag, if it is one. */
229
- const unpackRepeatStop = (id: string, data: Record<string, string>): RepeatStop | undefined => {
230
- if (!isRepeatStopId(id)) return undefined;
231
- const targetId = data.__cms_stop_target;
232
- const dueAt = Number.parseInt(data.__cms_stop_due ?? '', 10);
233
- if (typeof targetId !== 'string' || !Number.isFinite(dueAt)) return undefined;
234
- return { markerId: id, targetId, dueAt };
235
- };
236
-
237
- const unpackEntry = (raw: Record<string, unknown>): PendingEntry | undefined => {
238
- const notification = (raw.notification ?? {}) as Record<string, unknown>;
239
- const trigger = (raw.trigger ?? {}) as Record<string, unknown>;
240
- const data = (notification.data ?? {}) as Record<string, string>;
241
- const id = notification.id;
242
-
243
- if (typeof id !== 'string') return undefined;
244
-
245
- return {
246
- id,
247
- resolvedAt: typeof trigger.timestamp === 'number' ? trigger.timestamp : now(),
248
- content: {
249
- title: typeof notification.title === 'string' ? notification.title : '',
250
- body: typeof notification.body === 'string' ? notification.body : '',
251
- subtitle: typeof notification.subtitle === 'string' ? notification.subtitle : undefined,
252
- },
253
- ...unpackData(data),
254
- };
255
- };
256
-
257
- const toInteraction = (raw: Record<string, unknown>): InteractionEvent | undefined => {
258
- const eventType = raw.type;
259
-
260
- // Only a dismissal or a press is an interaction. Everything else the
261
- // engine emits on this channel — delivery, trigger creation, channel
262
- // blocking — is not, and must not be reported as one.
263
- if (
264
- eventType !== EVENT_TYPE_DISMISSED &&
265
- eventType !== EVENT_TYPE_PRESS &&
266
- eventType !== EVENT_TYPE_ACTION_PRESS
267
- ) {
268
- return undefined;
269
- }
270
-
271
- const detail = (raw.detail ?? {}) as Record<string, unknown>;
272
- const notification = (detail.notification ?? {}) as Record<string, unknown>;
273
- const pressAction = (detail.pressAction ?? {}) as Record<string, unknown>;
274
- const id = notification.id;
275
-
276
- if (typeof id !== 'string') return undefined;
277
-
278
- const data = (notification.data ?? {}) as Record<string, string>;
279
- let routing: Record<string, unknown> | undefined;
280
- if (typeof data.__cms_routing === 'string') {
281
- try {
282
- routing = JSON.parse(data.__cms_routing) as Record<string, unknown>;
283
- } catch {
284
- routing = undefined;
285
- }
286
- }
287
-
288
- const actionId = typeof pressAction.id === 'string' ? pressAction.id : undefined;
289
- // `default` is the engine's own press-action id for tapping the body, so
290
- // it is a tap rather than a named action.
291
- const isNamedAction = actionId !== undefined && actionId !== 'default';
292
- let kind: InteractionEvent['kind'];
293
- if (eventType === EVENT_TYPE_DISMISSED) {
294
- kind = 'dismiss';
295
- } else if (isNamedAction) {
296
- kind = 'action';
297
- } else {
298
- kind = 'tap';
299
- }
300
-
301
- return {
302
- kind,
303
- notificationId: id,
304
- actionId: actionId !== 'default' ? actionId : undefined,
305
- inputText: typeof detail.input === 'string' ? detail.input : undefined,
306
- routing,
307
- ownerTag: data.__cms_owner,
308
- occurredAt: now(),
309
- appState: 'foreground',
310
- wasBuffered: false,
311
- };
312
- };
313
-
314
- /**
315
- * Creates the marker channel the first time one is needed.
316
- *
317
- * Lazily rather than at initialization, so an app that never declares a
318
- * repeating tone never grows an extra entry in the user's notification
319
- * settings for a feature it does not use.
320
- */
321
- let markerChannelReady = false;
322
- const ensureMarkerChannel = async (): Promise<void> => {
323
- if (Platform.OS !== 'android' || markerChannelReady) return;
324
-
325
- await engine().createChannel({
326
- id: MARKER_CHANNEL_ID,
327
- name: 'Background maintenance',
328
- description:
329
- 'Used briefly to end a repeating alert. Notifications here are removed immediately.',
330
- importance: ANDROID_IMPORTANCE.min,
331
- vibration: false,
332
- badge: false,
333
- });
334
- markerChannelReady = true;
335
- };
336
-
337
- let deliveryListeners: ((event: DeliveryEvent) => void)[] = [];
338
-
339
- /** A delivery, or undefined for anything that is not one. */
340
- const toDelivery = (raw: Record<string, unknown>): DeliveryEvent | undefined => {
341
- if (raw.type !== EVENT_TYPE_DELIVERED) return undefined;
342
-
343
- const detail = (raw.detail ?? {}) as Record<string, unknown>;
344
- const notification = (detail.notification ?? {}) as Record<string, unknown>;
345
- const id = notification.id;
346
- if (typeof id !== 'string') return undefined;
347
-
348
- const data = (notification.data ?? {}) as Record<string, string>;
349
- return {
350
- notificationId: id,
351
- occurredAt: now(),
352
- repeatStop: unpackRepeatStop(id, data),
353
- };
354
- };
82
+ const getPermission = async (kind: PermissionKind): Promise<PermissionState> =>
83
+ platform.permissionFrom(kind, await engine().getNotificationSettings());
355
84
 
356
85
  return {
357
86
  name: 'react-native-notify-kit',
358
87
 
359
- async getCapabilities(): Promise<EngineCapabilities> {
360
- return {
361
- pendingCeiling: Platform.OS === 'ios' ? IOS_PENDING_CEILING : ANDROID_PENDING_BUDGET,
362
- supportsExactAlarms: Platform.OS === 'android',
363
- supportsChannels: Platform.OS === 'android',
364
- supportsTextInputActions: true,
365
- supportsDoNotDisturbBypass: Platform.OS === 'android',
366
- // iOS exposes no looping-sound API. The one alert level that
367
- // overrides the mute switch is entitlement-gated by Apple, and does
368
- // not loop either — so there is nothing to partially support, and a
369
- // partial emulation would be worse than an honest refusal.
370
- supportsRepeatingAlert: Platform.OS === 'android',
371
- backgroundWindowMs: BACKGROUND_WINDOW_MS,
372
- };
88
+ withChannelSnapshot: work => platform.withChannelSnapshot(work),
89
+
90
+ async pendingIds(): Promise<readonly string[]> {
91
+ const module = engine();
92
+ if (module.getTriggerNotificationIds) {
93
+ return module.getTriggerNotificationIds();
94
+ }
95
+ return (await module.getTriggerNotifications()).flatMap(raw => {
96
+ const id = (raw as { notification?: { id?: unknown } }).notification?.id;
97
+ return typeof id === 'string' ? [id] : [];
98
+ });
373
99
  },
374
100
 
101
+ getCapabilities: async () => platform.capabilities(),
102
+
375
103
  async schedule(request: EngineScheduleRequest): Promise<void> {
376
104
  const actions = request.request.actions?.map(action =>
377
105
  compact({
@@ -389,7 +117,7 @@ export function createNotifyKitEngine(
389
117
 
390
118
  const isMarker = request.repeatStop !== undefined;
391
119
  if (isMarker) {
392
- await ensureMarkerChannel();
120
+ await platform.ensureMarkerChannel();
393
121
  }
394
122
 
395
123
  await engine().createTriggerNotification(
@@ -461,7 +189,7 @@ export function createNotifyKitEngine(
461
189
  const raw = await engine().getTriggerNotifications();
462
190
  return (
463
191
  raw
464
- .map(unpackEntry)
192
+ .map(entry => unpackEntry(entry, now))
465
193
  .filter((entry): entry is PendingEntry => entry !== undefined)
466
194
  // Stop markers are package-owned artifacts. A consumer diffing the
467
195
  // device against its own intent would otherwise see a notification it
@@ -471,120 +199,33 @@ export function createNotifyKitEngine(
471
199
  );
472
200
  },
473
201
 
474
- async declareTone(tone: ResolvedTone): Promise<ToneDeclarationOutcome> {
475
- if (Platform.OS !== 'android') {
476
- // iOS categories are declared at request time rather than up front.
477
- return 'unchanged';
478
- }
479
-
480
- const existing = await engine().getChannels();
481
- const held = existing.find(channel => channel.id === tone.android.channelId);
482
-
483
- const payload = compact({
484
- id: tone.android.channelId,
485
- // The consumer's declared label, not the tone identifier. Passing the
486
- // identifier here is what put a technical string in front of users on
487
- // the one screen these labels exist to serve.
488
- name: tone.android.name,
489
- description: tone.android.description,
490
- importance: ANDROID_IMPORTANCE[tone.android.importance],
491
- sound: tone.android.sound,
492
- vibration: tone.android.vibration,
493
- badge: tone.android.badge,
494
- bypassDnd: tone.android.bypassDnd,
495
- groupId: tone.android.groupId,
496
- });
497
-
498
- if (held === undefined) {
499
- await engine().createChannel(payload);
500
- return 'created';
501
- }
502
-
503
- if (held.name === tone.android.name && held.description === tone.android.description) {
504
- // Nothing to say to the platform. Skipping the call is what keeps an
505
- // unchanged configuration genuinely free, which reconciliation
506
- // idempotence depends on.
507
- return 'unchanged';
508
- }
509
-
510
- // Android accepts a re-declaration of an existing channel and applies
511
- // only the name and description, ignoring importance, sound, vibration
512
- // and DND — because those belong to the user once the channel exists.
513
- // That refusal is the guarantee: we do not have to protect the user's
514
- // settings here, the platform declines to overwrite them.
515
- await engine().createChannel(payload);
516
- return 'labelsRefreshed';
517
- },
518
-
519
- async retireTone(channelId: string): Promise<boolean> {
520
- if (Platform.OS !== 'android') return false;
521
-
522
- const existing = await engine().getChannels();
523
- if (!existing.some(channel => channel.id === channelId)) return false;
524
-
525
- await engine().deleteChannel(channelId);
526
- return true;
527
- },
528
-
529
- async declareGroups(groups: readonly ChannelGroup[]): Promise<void> {
530
- if (Platform.OS !== 'android') return;
531
-
532
- for (const group of groups) {
533
- await engine().createChannelGroup(
534
- compact({ id: group.id, name: group.name, description: group.description }),
535
- );
536
- }
537
- },
538
-
539
- async listDeclaredChannels(): Promise<readonly string[]> {
540
- if (Platform.OS !== 'android') return [];
541
- const channels = await engine().getChannels();
542
- return channels.map(channel => channel.id);
543
- },
544
-
545
- async getPermission(kind: PermissionKind): Promise<PermissionState> {
546
- const settings = await engine().getNotificationSettings();
547
-
548
- if (kind === 'display') {
549
- // Android below 13 has no runtime display permission at all.
550
- if (Platform.OS === 'android' && (Platform.Version as number) < 33) {
551
- return 'notRequired';
552
- }
553
- return toPermissionState(settings.authorizationStatus);
554
- }
555
-
556
- // Exact alarms exist only on Android 12+; elsewhere the concept does not
557
- // apply, which is "not required" rather than "denied".
558
- if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
559
- return 'notRequired';
560
- }
202
+ declareTone: tone => platform.declareTone(tone),
203
+ retireTone: channelId => platform.retireTone(channelId),
204
+ declareGroups: groups => platform.declareGroups(groups),
205
+ listDeclaredChannels: () => platform.listDeclaredChannels(),
561
206
 
562
- const android = (settings.android ?? {}) as Record<string, unknown>;
563
- return android.alarm === 1 ? 'granted' : 'denied';
564
- },
207
+ getPermission,
565
208
 
566
209
  async requestPermission(kind: PermissionKind): Promise<PermissionState> {
567
210
  if (kind === 'display') {
568
211
  const result = await engine().requestPermission();
569
212
  return toPermissionState(result.authorizationStatus);
570
213
  }
571
-
572
214
  // Exact-alarm capability is granted only through system settings on the
573
215
  // versions that gate it — there is no in-app dialog to present.
574
- if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
216
+ if (!platform.gatesExactAlarms()) {
575
217
  return 'notRequired';
576
218
  }
577
219
  await engine().openAlarmPermissionSettings();
578
- return this.getPermission('exactAlarm');
220
+ return getPermission('exactAlarm');
579
221
  },
580
222
 
581
223
  async openSettings(kind: PermissionKind): Promise<void> {
582
224
  if (kind === 'exactAlarm') {
583
- if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
225
+ if (!platform.gatesExactAlarms()) {
584
226
  throw new NotificationError(
585
227
  DIAGNOSTIC_CODES.SETTINGS_UNAVAILABLE,
586
228
  'No exact-alarm settings screen exists on this platform version.',
587
- { platform: Platform.OS, version: Platform.Version },
588
229
  );
589
230
  }
590
231
  await engine().openAlarmPermissionSettings();
@@ -593,45 +234,25 @@ export function createNotifyKitEngine(
593
234
  await engine().openNotificationSettings();
594
235
  },
595
236
 
596
- async getRestrictions(): Promise<RestrictionReport> {
597
- if (Platform.OS !== 'android') {
598
- return {
599
- batteryOptimization: 'unrestricted',
600
- autoStart: 'unrestricted',
601
- readAt: now(),
602
- };
603
- }
604
-
605
- let batteryOptimization: RestrictionReport['batteryOptimization'] = 'unknown';
606
- try {
607
- batteryOptimization = (await engine().isBatteryOptimizationEnabled())
608
- ? 'restricted'
609
- : 'unrestricted';
610
- } catch {
611
- batteryOptimization = 'unknown';
612
- }
613
-
614
- return {
615
- batteryOptimization,
616
- // No standard API exposes vendor auto-start policy, and guessing would
617
- // be worse than admitting it. `unknown` is a first-class answer here.
618
- autoStart: 'unknown',
619
- readAt: now(),
620
- };
621
- },
237
+ getRestrictions: () => platform.restrictions(now),
622
238
 
623
239
  subscribeToInteractions(handler: (event: InteractionEvent) => void): Unsubscribe {
624
- return engine().onForegroundEvent(raw => {
625
- const event = toInteraction(raw);
240
+ liveInteractionListeners.add(handler);
241
+ const unsubscribe = engine().onForegroundEvent(raw => {
242
+ const event = toInteraction(raw, now);
626
243
  if (event !== undefined) handler(event);
627
244
  });
245
+ return () => {
246
+ liveInteractionListeners.delete(handler);
247
+ unsubscribe();
248
+ };
628
249
  },
629
250
 
630
251
  async takeInitialInteraction(): Promise<InteractionEvent | undefined> {
631
252
  const raw = await engine().getInitialNotification();
632
253
  if (raw === null) return undefined;
633
254
 
634
- const event = toInteraction(raw);
255
+ const event = toInteraction(raw, now);
635
256
  // A cold-start tap arrives before any handler exists, so it is reported
636
257
  // with the state that actually produced it.
637
258
  return event === undefined ? undefined : { ...event, appState: 'coldStart' };
@@ -670,40 +291,38 @@ export function createNotifyKitEngine(
670
291
  },
671
292
 
672
293
  async listRepeatStops(): Promise<readonly RepeatStop[]> {
673
- const raw = await engine().getTriggerNotifications();
674
- const stops: RepeatStop[] = [];
675
-
676
- for (const entry of raw) {
677
- const notification = (entry.notification ?? {}) as Record<string, unknown>;
678
- const id = notification.id;
679
- if (typeof id !== 'string') continue;
680
-
681
- const data = (notification.data ?? {}) as Record<string, string>;
682
- const stop = unpackRepeatStop(id, data);
683
- if (stop !== undefined) stops.push(stop);
684
- }
685
-
686
- return stops;
294
+ return unpackRepeatStops(await engine().getTriggerNotifications());
687
295
  },
688
296
 
689
297
  subscribeToDeliveries(handler: (event: DeliveryEvent) => void): Unsubscribe {
690
- deliveryListeners.push(handler);
691
-
692
- const unsubscribe = engine().onForegroundEvent(raw => {
693
- const event = toDelivery(raw);
298
+ return engine().onForegroundEvent(raw => {
299
+ const event = toDelivery(raw, now);
694
300
  if (event !== undefined) handler(event);
695
301
  });
696
-
697
- return () => {
698
- deliveryListeners = deliveryListeners.filter(l => l !== handler);
699
- unsubscribe();
700
- };
701
302
  },
702
303
 
703
- registerBackgroundDeliveryHandler(handler: (event: DeliveryEvent) => Promise<void>): void {
304
+ registerBackgroundDeliveryHandler(
305
+ handler: (event: DeliveryEvent) => Promise<void>,
306
+ onInteraction?: (event: InteractionEvent) => Promise<void>,
307
+ ): void {
704
308
  engine().onBackgroundEvent(async raw => {
705
- const event = toDelivery(raw);
706
- if (event !== undefined) await handler(event);
309
+ const delivery = toDelivery(raw, now);
310
+ if (delivery !== undefined) {
311
+ await handler(delivery);
312
+ return;
313
+ }
314
+ // A tap, an action or a dismissal while the app was not in front. Until
315
+ // 0.6.0 only deliveries were looked at here, so a background action
316
+ // ("Taken", "Snooze", an inline reply) never reached the app (NOT-10).
317
+ const interaction = toInteraction(raw, now);
318
+ if (interaction === undefined) return;
319
+ const event: InteractionEvent = { ...interaction, appState: 'background' };
320
+ if (liveInteractionListeners.size > 0) {
321
+ // The app's runtime is alive: its handlers get it, as in the foreground.
322
+ for (const listener of [...liveInteractionListeners]) listener(event);
323
+ } else {
324
+ await onInteraction?.(event);
325
+ }
707
326
  });
708
327
  backgroundHandlerRegistered = true;
709
328
  },