@chipmobilesdk/rn-notification 0.1.1 → 0.2.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 (71) hide show
  1. package/CHANGELOG.md +80 -42
  2. package/README.md +399 -306
  3. package/package.json +2 -1
  4. package/skills/sdk-rn-notification/SKILL.md +68 -3
  5. package/src/channel/migrate.ts +86 -12
  6. package/src/channel/tone-map.ts +130 -90
  7. package/src/channel/validate-tone.ts +61 -0
  8. package/src/contract/channel.ts +188 -89
  9. package/src/contract/diagnostics.ts +102 -102
  10. package/src/contract/errors.ts +130 -123
  11. package/src/contract/index.ts +10 -10
  12. package/src/contract/interaction.ts +62 -62
  13. package/src/contract/notification.ts +118 -118
  14. package/src/contract/permission.ts +60 -60
  15. package/src/contract/reconcile.ts +88 -88
  16. package/src/contract/recurrence.ts +123 -123
  17. package/src/diagnostics/burst.ts +101 -101
  18. package/src/diagnostics/events.ts +72 -72
  19. package/src/diagnostics/redact.ts +72 -72
  20. package/src/diagnostics/snapshot.ts +64 -64
  21. package/src/engine/adapter.ts +172 -79
  22. package/src/engine/notify-kit-engine.ts +761 -535
  23. package/src/index.ts +35 -0
  24. package/src/initialize.ts +174 -174
  25. package/src/interaction/index.ts +146 -146
  26. package/src/maintenance/cycle.ts +147 -147
  27. package/src/maintenance/permission-refresh.ts +41 -41
  28. package/src/maintenance/reanchor.ts +95 -95
  29. package/src/maintenance/toggle.ts +60 -60
  30. package/src/maintenance/verify.ts +83 -83
  31. package/src/maintenance/window-refresh.ts +61 -61
  32. package/src/permission/index.ts +183 -183
  33. package/src/permission/state.ts +77 -77
  34. package/src/push/envelope.ts +165 -165
  35. package/src/push/fcm-provider.ts +146 -146
  36. package/src/push/gate.ts +190 -190
  37. package/src/push/instructions.ts +109 -109
  38. package/src/push/provider-adapter.ts +54 -54
  39. package/src/push/signout.ts +65 -65
  40. package/src/reconcile/chunk.ts +53 -53
  41. package/src/reconcile/diff.ts +145 -145
  42. package/src/reconcile/duplicates.ts +73 -73
  43. package/src/reconcile/index.ts +14 -1
  44. package/src/reconcile/truncate.ts +56 -56
  45. package/src/recurrence/clock-guard.ts +71 -71
  46. package/src/recurrence/expand.ts +292 -292
  47. package/src/repeat/expiry.ts +55 -0
  48. package/src/repeat/index.ts +54 -0
  49. package/src/repeat/marker.ts +72 -0
  50. package/src/repeat/place.ts +73 -0
  51. package/src/schedule/anchor.ts +267 -267
  52. package/src/schedule/index.ts +184 -173
  53. package/src/schedule/partition.ts +85 -85
  54. package/src/schedule/resolve-moment.ts +80 -80
  55. package/src/schedule/validate-content.ts +111 -111
  56. package/src/schedule/validate-identifier.ts +126 -114
  57. package/src/state/caps.ts +71 -71
  58. package/src/state/dedup-ledger.ts +35 -39
  59. package/src/state/interaction-buffer.ts +73 -73
  60. package/src/state/mmkv-store.ts +71 -71
  61. package/src/state/permission-history.ts +41 -41
  62. package/src/state/record.ts +258 -246
  63. package/src/state/reset.ts +41 -41
  64. package/src/state/series-ledger.ts +84 -84
  65. package/src/state/store.ts +40 -40
  66. package/src/testing/conformance/index.ts +248 -194
  67. package/src/testing/fake-engine.ts +469 -284
  68. package/src/testing/fake-provider.ts +129 -129
  69. package/src/testing/faults.ts +72 -72
  70. package/src/testing/index.ts +2 -0
  71. package/src/testing/measure.ts +337 -0
@@ -1,535 +1,761 @@
1
- /**
2
- * The `react-native-notify-kit` engine implementation.
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.
8
- *
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.
12
- */
13
-
14
- import { Platform } from 'react-native';
15
- import type {
16
- NotificationEngineAdapter,
17
- EngineCapabilities,
18
- EngineScheduleRequest,
19
- } from './adapter';
20
- import type { PendingEntry } from '../contract/notification';
21
- import type { PermissionKind, PermissionState, RestrictionReport } from '../contract/permission';
22
- import type { ResolvedTone, ChannelGroup } from '../contract/channel';
23
- import type { InteractionEvent, Unsubscribe } from '../contract/interaction';
24
- import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
25
-
26
- /**
27
- * iOS keeps only the 64 soonest pending notifications and silently discards the
28
- * rest. This number is the entire reason truncation must be computed and
29
- * reported by the package rather than left to the platform.
30
- */
31
- const IOS_PENDING_CEILING = 64;
32
-
33
- /** Android has no comparable hard ceiling; this bound keeps behavior predictable. */
34
- const ANDROID_PENDING_BUDGET = 500;
35
-
36
- /** Both platforms bound background execution for a silent payload or background action. */
37
- const BACKGROUND_WINDOW_MS = 30_000;
38
-
39
- /**
40
- * The engine's own enum values, mirrored as literals.
41
- *
42
- * These are **numeric** enums in the engine's type definitions, and its native
43
- * validator rejects the string names — `importance: 'default'` fails with
44
- * "expected a valid Importance". Mirroring them here rather than importing the
45
- * enums keeps the engine out of the module graph, which is what lets the
46
- * package load without the native module present.
47
- *
48
- * The package's own `ResolvedTone` deliberately stays platform-neutral strings;
49
- * translating to the engine's representation is this adapter's job and nobody
50
- * else's.
51
- */
52
- const ANDROID_IMPORTANCE = {
53
- none: 0,
54
- min: 1,
55
- low: 2,
56
- default: 3,
57
- high: 4,
58
- } as const;
59
-
60
- /** `TriggerType.TIMESTAMP`. */
61
- const TRIGGER_TYPE_TIMESTAMP = 0;
62
-
63
- /** `AlarmType.SET_EXACT_AND_ALLOW_WHILE_IDLE` — exact delivery, survives Doze. */
64
- const ALARM_TYPE_EXACT_AND_ALLOW_WHILE_IDLE = 3;
65
-
66
- /** `AlarmType.SET_AND_ALLOW_WHILE_IDLE` — the approximate degradation of the above. */
67
- const ALARM_TYPE_INEXACT_AND_ALLOW_WHILE_IDLE = 1;
68
-
69
- /**
70
- * `EventType` values that represent a real user interaction.
71
- *
72
- * The engine emits far more than interactions on this channel — `DELIVERED`,
73
- * `TRIGGER_NOTIFICATION_CREATED`, `CHANNEL_BLOCKED` and others all arrive here.
74
- * Treating anything that is not a dismissal as a press would report a
75
- * notification *arriving* while the app is open as the user having tapped it,
76
- * and the interaction path cancels on tap — so the notification would vanish
77
- * from the tray in front of the user, unread.
78
- */
79
- const EVENT_TYPE_DISMISSED = 0;
80
- const EVENT_TYPE_PRESS = 1;
81
- const EVENT_TYPE_ACTION_PRESS = 2;
82
-
83
- /** Minimal shape used from the engine, so its full surface never leaks into typing. */
84
- interface NotifyKitModule {
85
- createChannel(channel: Record<string, unknown>): Promise<string>;
86
- deleteChannel(channelId: string): Promise<void>;
87
- getChannels(): Promise<{ id: string }[]>;
88
- createChannelGroup(group: Record<string, unknown>): Promise<string>;
89
- createTriggerNotification(
90
- notification: Record<string, unknown>,
91
- trigger: Record<string, unknown>,
92
- ): Promise<string>;
93
- cancelNotification(id: string): Promise<void>;
94
- cancelAllNotifications(): Promise<void>;
95
- getTriggerNotifications(): Promise<Record<string, unknown>[]>;
96
- requestPermission(options?: Record<string, unknown>): Promise<Record<string, unknown>>;
97
- getNotificationSettings(): Promise<Record<string, unknown>>;
98
- openNotificationSettings(): Promise<void>;
99
- openAlarmPermissionSettings(): Promise<void>;
100
- isBatteryOptimizationEnabled(): Promise<boolean>;
101
- onForegroundEvent(handler: (event: Record<string, unknown>) => void): () => void;
102
- getInitialNotification(): Promise<Record<string, unknown> | null>;
103
- }
104
-
105
- /**
106
- * Drops keys whose value is `undefined`.
107
- *
108
- * The engine validates its arguments by key presence, not by value: passing
109
- * `{ groupId: undefined }` fails with "expected a string value", while omitting
110
- * the key entirely is accepted. JavaScript treats the two as interchangeable
111
- * almost everywhere, which is exactly why this is easy to get wrong — and why
112
- * it only surfaces on a real device, where the native validator runs.
113
- */
114
- function compact<T extends Record<string, unknown>>(value: T): Partial<T> {
115
- const output: Record<string, unknown> = {};
116
- for (const [key, entry] of Object.entries(value)) {
117
- if (entry !== undefined) output[key] = entry;
118
- }
119
- return output as Partial<T>;
120
- }
121
-
122
- function loadEngine(): NotifyKitModule {
123
- try {
124
- const module = require('react-native-notify-kit') as { default: NotifyKitModule };
125
- return module.default;
126
- } catch (error) {
127
- throw new NotificationError(
128
- DIAGNOSTIC_CODES.PUSH_UNAVAILABLE,
129
- 'react-native-notify-kit is not installed or its native module is not linked. Install it as a peer dependency and rebuild the app.',
130
- { reason: error instanceof Error ? error.name : 'unknown' },
131
- );
132
- }
133
- }
134
-
135
- /**
136
- * Maps engine authorization values onto our six-state model.
137
- *
138
- * `notAsked` and `denied` must stay distinguishable — being able to read state
139
- * without prompting is worthless if the two collapse. `provisional` is its own
140
- * state on both edges, never folded into granted or denied.
141
- */
142
- function toPermissionState(raw: unknown): PermissionState {
143
- switch (raw) {
144
- case 1:
145
- case 'authorized':
146
- return 'granted';
147
- case 2:
148
- case 'provisional':
149
- return 'provisional';
150
- case 0:
151
- case 'denied':
152
- return 'denied';
153
- case -1:
154
- case 'notDetermined':
155
- return 'notAsked';
156
- default:
157
- return 'notAsked';
158
- }
159
- }
160
-
161
- export interface NotifyKitEngineOptions {
162
- /** Injected in tests; production resolves the real module. */
163
- readonly module?: NotifyKitModule;
164
- readonly now?: () => number;
165
- }
166
-
167
- export function createNotifyKitEngine(
168
- options: NotifyKitEngineOptions = {},
169
- ): NotificationEngineAdapter {
170
- let cached: NotifyKitModule | undefined = options.module;
171
- const engine = (): NotifyKitModule => (cached ??= loadEngine());
172
- const now = options.now ?? (() => Date.now());
173
-
174
- /**
175
- * Round-trips our own metadata through the engine's free-form data bag.
176
- *
177
- * Anchoring mode, generation, and series origin have no engine equivalent,
178
- * and `getPending` must return them (FR-010) or a consumer cannot diff
179
- * against intent. Values are stringified because the platform data bag
180
- * carries strings on both platforms.
181
- */
182
- const packData = (request: EngineScheduleRequest): Record<string, string> => ({
183
- __cms_anchoring: request.request.moment.anchoring ?? 'wallClock',
184
- // The IANA zone, not the tone. Storing the wrong value here does not merely
185
- // mislabel an entry: the re-anchoring pass feeds it straight to
186
- // Intl.DateTimeFormat, which throws a hard Hermes error on an invalid zone.
187
- ...(request.anchoringGeneration !== undefined
188
- ? { __cms_generation: request.anchoringGeneration }
189
- : {}),
190
- __cms_tone: request.request.tone,
191
- __cms_approximate: String(request.approximate),
192
- __cms_pushCreated: String(request.pushCreated ?? false),
193
- ...(request.seriesId !== undefined ? { __cms_series: request.seriesId } : {}),
194
- ...(request.request.ownerTag !== undefined ? { __cms_owner: request.request.ownerTag } : {}),
195
- ...(request.request.groupTag !== undefined ? { __cms_group: request.request.groupTag } : {}),
196
- ...(request.request.routing !== undefined
197
- ? { __cms_routing: JSON.stringify(request.request.routing) }
198
- : {}),
199
- });
200
-
201
- const unpackEntry = (raw: Record<string, unknown>): PendingEntry | undefined => {
202
- const notification = (raw.notification ?? {}) as Record<string, unknown>;
203
- const trigger = (raw.trigger ?? {}) as Record<string, unknown>;
204
- const data = (notification.data ?? {}) as Record<string, string>;
205
- const id = notification.id;
206
-
207
- if (typeof id !== 'string') return undefined;
208
-
209
- let routing: Record<string, unknown> | undefined;
210
- if (typeof data.__cms_routing === 'string') {
211
- try {
212
- routing = JSON.parse(data.__cms_routing) as Record<string, unknown>;
213
- } catch {
214
- // A payload we cannot parse is reported as absent rather than as a
215
- // crash: the notification is still valid, only its routing is lost.
216
- routing = undefined;
217
- }
218
- }
219
-
220
- return {
221
- id,
222
- resolvedAt: typeof trigger.timestamp === 'number' ? trigger.timestamp : now(),
223
- anchoring: data.__cms_anchoring === 'absolute' ? 'absolute' : 'wallClock',
224
- anchoringGeneration:
225
- data.__cms_anchoring === 'absolute' ? undefined : data.__cms_generation,
226
- content: {
227
- title: typeof notification.title === 'string' ? notification.title : '',
228
- body: typeof notification.body === 'string' ? notification.body : '',
229
- subtitle: typeof notification.subtitle === 'string' ? notification.subtitle : undefined,
230
- },
231
- tone: data.__cms_tone ?? '',
232
- routing,
233
- ownerTag: data.__cms_owner,
234
- groupTag: data.__cms_group,
235
- seriesId: data.__cms_series,
236
- mayBeDelayed: data.__cms_approximate === 'true',
237
- pushCreated: data.__cms_pushCreated === 'true',
238
- };
239
- };
240
-
241
- const toInteraction = (raw: Record<string, unknown>): InteractionEvent | undefined => {
242
- const eventType = raw.type;
243
-
244
- // Only a dismissal or a press is an interaction. Everything else the
245
- // engine emits on this channel — delivery, trigger creation, channel
246
- // blocking — is not, and must not be reported as one.
247
- if (
248
- eventType !== EVENT_TYPE_DISMISSED &&
249
- eventType !== EVENT_TYPE_PRESS &&
250
- eventType !== EVENT_TYPE_ACTION_PRESS
251
- ) {
252
- return undefined;
253
- }
254
-
255
- const detail = (raw.detail ?? {}) as Record<string, unknown>;
256
- const notification = (detail.notification ?? {}) as Record<string, unknown>;
257
- const pressAction = (detail.pressAction ?? {}) as Record<string, unknown>;
258
- const id = notification.id;
259
-
260
- if (typeof id !== 'string') return undefined;
261
-
262
- const data = (notification.data ?? {}) as Record<string, string>;
263
- let routing: Record<string, unknown> | undefined;
264
- if (typeof data.__cms_routing === 'string') {
265
- try {
266
- routing = JSON.parse(data.__cms_routing) as Record<string, unknown>;
267
- } catch {
268
- routing = undefined;
269
- }
270
- }
271
-
272
- const actionId = typeof pressAction.id === 'string' ? pressAction.id : undefined;
273
- // `default` is the engine's own press-action id for tapping the body, so
274
- // it is a tap rather than a named action.
275
- const isNamedAction = actionId !== undefined && actionId !== 'default';
276
- let kind: InteractionEvent['kind'];
277
- if (eventType === EVENT_TYPE_DISMISSED) {
278
- kind = 'dismiss';
279
- } else if (isNamedAction) {
280
- kind = 'action';
281
- } else {
282
- kind = 'tap';
283
- }
284
-
285
- return {
286
- kind,
287
- notificationId: id,
288
- actionId: actionId !== 'default' ? actionId : undefined,
289
- inputText: typeof detail.input === 'string' ? detail.input : undefined,
290
- routing,
291
- ownerTag: data.__cms_owner,
292
- occurredAt: now(),
293
- appState: 'foreground',
294
- wasBuffered: false,
295
- };
296
- };
297
-
298
- return {
299
- name: 'react-native-notify-kit',
300
-
301
- async getCapabilities(): Promise<EngineCapabilities> {
302
- return {
303
- pendingCeiling: Platform.OS === 'ios' ? IOS_PENDING_CEILING : ANDROID_PENDING_BUDGET,
304
- supportsExactAlarms: Platform.OS === 'android',
305
- supportsChannels: Platform.OS === 'android',
306
- supportsTextInputActions: true,
307
- supportsDoNotDisturbBypass: Platform.OS === 'android',
308
- backgroundWindowMs: BACKGROUND_WINDOW_MS,
309
- };
310
- },
311
-
312
- async schedule(request: EngineScheduleRequest): Promise<void> {
313
- const actions = request.request.actions?.map(action =>
314
- compact({
315
- title: action.title,
316
- pressAction: compact({
317
- id: action.id,
318
- launchActivity: action.mode === 'foreground' ? 'default' : undefined,
319
- }),
320
- input: action.input === undefined ? undefined : compact({ placeholder: action.input.placeholder }),
321
- }),
322
- );
323
-
324
- await engine().createTriggerNotification(
325
- compact({
326
- id: request.request.id,
327
- title: request.request.content.title,
328
- body: request.request.content.body,
329
- subtitle: request.request.content.subtitle,
330
- data: packData(request),
331
- android: compact({
332
- channelId: request.tone.android.channelId,
333
- // Numeric enum, not the string name — see ANDROID_IMPORTANCE.
334
- importance: ANDROID_IMPORTANCE[request.tone.android.importance],
335
- sound: request.tone.android.sound,
336
- groupId: request.tone.android.groupId,
337
- actions,
338
- }),
339
- ios: compact({
340
- categoryId: request.tone.ios.categoryId,
341
- // This one genuinely is a string union in the engine's types.
342
- interruptionLevel: request.tone.ios.interruptionLevel,
343
- sound: request.tone.ios.sound,
344
- }),
345
- }),
346
- {
347
- type: TRIGGER_TYPE_TIMESTAMP,
348
- timestamp: request.resolvedAt,
349
- // Approximate mode is a degradation, not a failure: the notification
350
- // is still scheduled and the caller is told it may arrive late.
351
- alarmManager: {
352
- allowWhileIdle: true,
353
- type: request.approximate
354
- ? ALARM_TYPE_INEXACT_AND_ALLOW_WHILE_IDLE
355
- : ALARM_TYPE_EXACT_AND_ALLOW_WHILE_IDLE,
356
- },
357
- },
358
- );
359
- },
360
-
361
- async cancel(id: string): Promise<void> {
362
- await engine().cancelNotification(id);
363
- },
364
-
365
- async cancelMany(ids: readonly string[]): Promise<void> {
366
- // Sequential rather than parallel: the engine bridges each call to
367
- // native, and a burst of concurrent cancels is where duplicate-delivery
368
- // races have historically appeared.
369
- for (const id of ids) {
370
- await engine().cancelNotification(id);
371
- }
372
- },
373
-
374
- async cancelAll(): Promise<void> {
375
- await engine().cancelAllNotifications();
376
- },
377
-
378
- async getPending(): Promise<readonly PendingEntry[]> {
379
- const raw = await engine().getTriggerNotifications();
380
- return raw
381
- .map(unpackEntry)
382
- .filter((entry): entry is PendingEntry => entry !== undefined)
383
- .sort((a, b) => a.resolvedAt - b.resolvedAt);
384
- },
385
-
386
- async declareTone(tone: ResolvedTone): Promise<boolean> {
387
- if (Platform.OS !== 'android') {
388
- // iOS categories are declared at request time rather than up front.
389
- return false;
390
- }
391
-
392
- const existing = await engine().getChannels();
393
- if (existing.some(channel => channel.id === tone.android.channelId)) {
394
- // Android silently ignores re-declaration, which is exactly why the
395
- // package keeps its own migration ledger rather than asking here.
396
- return false;
397
- }
398
-
399
- await engine().createChannel(
400
- compact({
401
- id: tone.android.channelId,
402
- name: tone.toneId,
403
- importance: ANDROID_IMPORTANCE[tone.android.importance],
404
- sound: tone.android.sound,
405
- vibration: tone.android.vibration,
406
- badge: tone.android.badge,
407
- bypassDnd: tone.android.bypassDnd,
408
- groupId: tone.android.groupId,
409
- }),
410
- );
411
- return true;
412
- },
413
-
414
- async retireTone(channelId: string): Promise<boolean> {
415
- if (Platform.OS !== 'android') return false;
416
-
417
- const existing = await engine().getChannels();
418
- if (!existing.some(channel => channel.id === channelId)) return false;
419
-
420
- await engine().deleteChannel(channelId);
421
- return true;
422
- },
423
-
424
- async declareGroups(groups: readonly ChannelGroup[]): Promise<void> {
425
- if (Platform.OS !== 'android') return;
426
-
427
- for (const group of groups) {
428
- await engine().createChannelGroup(
429
- compact({ id: group.id, name: group.name, description: group.description }),
430
- );
431
- }
432
- },
433
-
434
- async listDeclaredChannels(): Promise<readonly string[]> {
435
- if (Platform.OS !== 'android') return [];
436
- const channels = await engine().getChannels();
437
- return channels.map(channel => channel.id);
438
- },
439
-
440
- async getPermission(kind: PermissionKind): Promise<PermissionState> {
441
- const settings = await engine().getNotificationSettings();
442
-
443
- if (kind === 'display') {
444
- // Android below 13 has no runtime display permission at all.
445
- if (Platform.OS === 'android' && (Platform.Version as number) < 33) {
446
- return 'notRequired';
447
- }
448
- return toPermissionState(settings.authorizationStatus);
449
- }
450
-
451
- // Exact alarms exist only on Android 12+; elsewhere the concept does not
452
- // apply, which is "not required" rather than "denied".
453
- if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
454
- return 'notRequired';
455
- }
456
-
457
- const android = (settings.android ?? {}) as Record<string, unknown>;
458
- return android.alarm === 1 ? 'granted' : 'denied';
459
- },
460
-
461
- async requestPermission(kind: PermissionKind): Promise<PermissionState> {
462
- if (kind === 'display') {
463
- const result = await engine().requestPermission();
464
- return toPermissionState(result.authorizationStatus);
465
- }
466
-
467
- // Exact-alarm capability is granted only through system settings on the
468
- // versions that gate it — there is no in-app dialog to present.
469
- if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
470
- return 'notRequired';
471
- }
472
- await engine().openAlarmPermissionSettings();
473
- return this.getPermission('exactAlarm');
474
- },
475
-
476
- async openSettings(kind: PermissionKind): Promise<void> {
477
- if (kind === 'exactAlarm') {
478
- if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
479
- throw new NotificationError(
480
- DIAGNOSTIC_CODES.SETTINGS_UNAVAILABLE,
481
- 'No exact-alarm settings screen exists on this platform version.',
482
- { platform: Platform.OS, version: Platform.Version },
483
- );
484
- }
485
- await engine().openAlarmPermissionSettings();
486
- return;
487
- }
488
- await engine().openNotificationSettings();
489
- },
490
-
491
- async getRestrictions(): Promise<RestrictionReport> {
492
- if (Platform.OS !== 'android') {
493
- return {
494
- batteryOptimization: 'unrestricted',
495
- autoStart: 'unrestricted',
496
- readAt: now(),
497
- };
498
- }
499
-
500
- let batteryOptimization: RestrictionReport['batteryOptimization'] = 'unknown';
501
- try {
502
- batteryOptimization = (await engine().isBatteryOptimizationEnabled())
503
- ? 'restricted'
504
- : 'unrestricted';
505
- } catch {
506
- batteryOptimization = 'unknown';
507
- }
508
-
509
- return {
510
- batteryOptimization,
511
- // No standard API exposes vendor auto-start policy, and guessing would
512
- // be worse than admitting it. `unknown` is a first-class answer here.
513
- autoStart: 'unknown',
514
- readAt: now(),
515
- };
516
- },
517
-
518
- subscribeToInteractions(handler: (event: InteractionEvent) => void): Unsubscribe {
519
- return engine().onForegroundEvent(raw => {
520
- const event = toInteraction(raw);
521
- if (event !== undefined) handler(event);
522
- });
523
- },
524
-
525
- async takeInitialInteraction(): Promise<InteractionEvent | undefined> {
526
- const raw = await engine().getInitialNotification();
527
- if (raw === null) return undefined;
528
-
529
- const event = toInteraction(raw);
530
- // A cold-start tap arrives before any handler exists, so it is reported
531
- // with the state that actually produced it.
532
- return event === undefined ? undefined : { ...event, appState: 'coldStart' };
533
- },
534
- };
535
- }
1
+ /**
2
+ * The `react-native-notify-kit` engine implementation.
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.
8
+ *
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.
12
+ */
13
+
14
+ import { Platform } from 'react-native';
15
+ import type {
16
+ NotificationEngineAdapter,
17
+ DeliveryEvent,
18
+ EngineCapabilities,
19
+ EngineScheduleRequest,
20
+ RepeatStop,
21
+ ToneDeclarationOutcome,
22
+ } from './adapter';
23
+ import { isRepeatStopId } from '../repeat/marker';
24
+ import type { PendingEntry } from '../contract/notification';
25
+ import type { PermissionKind, PermissionState, RestrictionReport } from '../contract/permission';
26
+ import type { ResolvedTone, ChannelGroup } from '../contract/channel';
27
+ import type { InteractionEvent, Unsubscribe } from '../contract/interaction';
28
+ import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
29
+
30
+ /**
31
+ * iOS keeps only the 64 soonest pending notifications and silently discards the
32
+ * rest. This number is the entire reason truncation must be computed and
33
+ * reported by the package rather than left to the platform.
34
+ */
35
+ const IOS_PENDING_CEILING = 64;
36
+
37
+ /** Android has no comparable hard ceiling; this bound keeps behavior predictable. */
38
+ const ANDROID_PENDING_BUDGET = 500;
39
+
40
+ /** Both platforms bound background execution for a silent payload or background action. */
41
+ const BACKGROUND_WINDOW_MS = 30_000;
42
+
43
+ /**
44
+ * The engine's own enum values, mirrored as literals.
45
+ *
46
+ * These are **numeric** enums in the engine's type definitions, and its native
47
+ * validator rejects the string names — `importance: 'default'` fails with
48
+ * "expected a valid Importance". Mirroring them here rather than importing the
49
+ * enums keeps the engine out of the module graph, which is what lets the
50
+ * package load without the native module present.
51
+ *
52
+ * The package's own `ResolvedTone` deliberately stays platform-neutral strings;
53
+ * translating to the engine's representation is this adapter's job and nobody
54
+ * else's.
55
+ */
56
+ const ANDROID_IMPORTANCE = {
57
+ none: 0,
58
+ min: 1,
59
+ low: 2,
60
+ default: 3,
61
+ high: 4,
62
+ } as const;
63
+
64
+ /** `TriggerType.TIMESTAMP`. */
65
+ const TRIGGER_TYPE_TIMESTAMP = 0;
66
+
67
+ /** `AlarmType.SET_EXACT_AND_ALLOW_WHILE_IDLE` — exact delivery, survives Doze. */
68
+ const ALARM_TYPE_EXACT_AND_ALLOW_WHILE_IDLE = 3;
69
+
70
+ /** `AlarmType.SET_AND_ALLOW_WHILE_IDLE` — the approximate degradation of the above. */
71
+ const ALARM_TYPE_INEXACT_AND_ALLOW_WHILE_IDLE = 1;
72
+
73
+ /**
74
+ * `EventType` values that represent a real user interaction.
75
+ *
76
+ * The engine emits far more than interactions on this channel — `DELIVERED`,
77
+ * `TRIGGER_NOTIFICATION_CREATED`, `CHANNEL_BLOCKED` and others all arrive here.
78
+ * Treating anything that is not a dismissal as a press would report a
79
+ * notification *arriving* while the app is open as the user having tapped it,
80
+ * and the interaction path cancels on tap — so the notification would vanish
81
+ * from the tray in front of the user, unread.
82
+ */
83
+ const EVENT_TYPE_DISMISSED = 0;
84
+ const EVENT_TYPE_PRESS = 1;
85
+ const EVENT_TYPE_ACTION_PRESS = 2;
86
+
87
+ /** `EventType.DELIVERED` — an arrival, which is emphatically not an interaction. */
88
+ const EVENT_TYPE_DELIVERED = 3;
89
+
90
+ /**
91
+ * `AndroidCategory.ALARM`, the engine's marking for a time-sensitive alert.
92
+ *
93
+ * A per-notification property, not channel configuration — which is why
94
+ * declaring `timeSensitive` on an existing tone never obliges a version bump.
95
+ */
96
+ const ANDROID_CATEGORY_ALARM = 'alarm';
97
+
98
+ /**
99
+ * The channel stop markers are posted on.
100
+ *
101
+ * A marker exists to be delivered and immediately removed, so it is given the
102
+ * quietest configuration the platform offers: minimum importance, no sound, no
103
+ * vibration. Its version is fixed because nothing about it is consumer-declared,
104
+ * so it never migrates.
105
+ */
106
+ const MARKER_CHANNEL_ID = 'cms.internal.stop.v1';
107
+
108
+ /**
109
+ * Whether this *process* has a background delivery handler.
110
+ *
111
+ * Module scope, not adapter instance state. The engine registers one headless
112
+ * task per process, so registering through any adapter registers it for all of
113
+ * them. Keeping the flag per instance made an app that had wired the handler up
114
+ * correctly report that it had not — which is worse than not reporting at all,
115
+ * because the warning tells the consumer to fix something that is not broken.
116
+ */
117
+ let backgroundHandlerRegistered = false;
118
+
119
+ /** Minimal shape used from the engine, so its full surface never leaks into typing. */
120
+ interface NotifyKitModule {
121
+ createChannel(channel: Record<string, unknown>): Promise<string>;
122
+ deleteChannel(channelId: string): Promise<void>;
123
+ /**
124
+ * Labels come back with the id. That is what makes a label refresh decidable
125
+ * against the device rather than against a ledger of our own — and a ledger
126
+ * drifts after a restore, a reinstall, or a change the user made themselves.
127
+ */
128
+ getChannels(): Promise<{ id: string; name?: string; description?: string }[]>;
129
+ createChannelGroup(group: Record<string, unknown>): Promise<string>;
130
+ createTriggerNotification(
131
+ notification: Record<string, unknown>,
132
+ trigger: Record<string, unknown>,
133
+ ): Promise<string>;
134
+ displayNotification(notification: Record<string, unknown>): Promise<string>;
135
+ getDisplayedNotifications(): Promise<Record<string, unknown>[]>;
136
+ cancelNotification(id: string): Promise<void>;
137
+ cancelAllNotifications(): Promise<void>;
138
+ getTriggerNotifications(): Promise<Record<string, unknown>[]>;
139
+ onBackgroundEvent(handler: (event: Record<string, unknown>) => Promise<void>): void;
140
+ requestPermission(options?: Record<string, unknown>): Promise<Record<string, unknown>>;
141
+ getNotificationSettings(): Promise<Record<string, unknown>>;
142
+ openNotificationSettings(): Promise<void>;
143
+ openAlarmPermissionSettings(): Promise<void>;
144
+ isBatteryOptimizationEnabled(): Promise<boolean>;
145
+ onForegroundEvent(handler: (event: Record<string, unknown>) => void): () => void;
146
+ getInitialNotification(): Promise<Record<string, unknown> | null>;
147
+ }
148
+
149
+ /**
150
+ * Drops keys whose value is `undefined`.
151
+ *
152
+ * The engine validates its arguments by key presence, not by value: passing
153
+ * `{ groupId: undefined }` fails with "expected a string value", while omitting
154
+ * the key entirely is accepted. JavaScript treats the two as interchangeable
155
+ * almost everywhere, which is exactly why this is easy to get wrong — and why
156
+ * it only surfaces on a real device, where the native validator runs.
157
+ */
158
+ function compact<T extends Record<string, unknown>>(value: T): Partial<T> {
159
+ const output: Record<string, unknown> = {};
160
+ for (const [key, entry] of Object.entries(value)) {
161
+ if (entry !== undefined) output[key] = entry;
162
+ }
163
+ return output as Partial<T>;
164
+ }
165
+
166
+ function loadEngine(): NotifyKitModule {
167
+ try {
168
+ const module = require('react-native-notify-kit') as { default: NotifyKitModule };
169
+ return module.default;
170
+ } catch (error) {
171
+ throw new NotificationError(
172
+ DIAGNOSTIC_CODES.PUSH_UNAVAILABLE,
173
+ 'react-native-notify-kit is not installed or its native module is not linked. Install it as a peer dependency and rebuild the app.',
174
+ { reason: error instanceof Error ? error.name : 'unknown' },
175
+ );
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Maps engine authorization values onto our six-state model.
181
+ *
182
+ * `notAsked` and `denied` must stay distinguishable — being able to read state
183
+ * without prompting is worthless if the two collapse. `provisional` is its own
184
+ * state on both edges, never folded into granted or denied.
185
+ */
186
+ function toPermissionState(raw: unknown): PermissionState {
187
+ switch (raw) {
188
+ case 1:
189
+ case 'authorized':
190
+ return 'granted';
191
+ case 2:
192
+ case 'provisional':
193
+ return 'provisional';
194
+ case 0:
195
+ case 'denied':
196
+ return 'denied';
197
+ case -1:
198
+ case 'notDetermined':
199
+ return 'notAsked';
200
+ default:
201
+ return 'notAsked';
202
+ }
203
+ }
204
+
205
+ export interface NotifyKitEngineOptions {
206
+ /** Injected in tests; production resolves the real module. */
207
+ readonly module?: NotifyKitModule;
208
+ readonly now?: () => number;
209
+ }
210
+
211
+ export function createNotifyKitEngine(
212
+ options: NotifyKitEngineOptions = {},
213
+ ): NotificationEngineAdapter {
214
+ let cached: NotifyKitModule | undefined = options.module;
215
+ const engine = (): NotifyKitModule => (cached ??= loadEngine());
216
+ const now = options.now ?? (() => Date.now());
217
+
218
+ /**
219
+ * Round-trips our own metadata through the engine's free-form data bag.
220
+ *
221
+ * Anchoring mode, generation, and series origin have no engine equivalent,
222
+ * and `getPending` must return them (FR-010) or a consumer cannot diff
223
+ * against intent. Values are stringified because the platform data bag
224
+ * carries strings on both platforms.
225
+ */
226
+ const packData = (request: EngineScheduleRequest): Record<string, string> => ({
227
+ __cms_anchoring: request.request.moment.anchoring ?? 'wallClock',
228
+ // The IANA zone, not the tone. Storing the wrong value here does not merely
229
+ // mislabel an entry: the re-anchoring pass feeds it straight to
230
+ // Intl.DateTimeFormat, which throws a hard Hermes error on an invalid zone.
231
+ ...(request.anchoringGeneration !== undefined
232
+ ? { __cms_generation: request.anchoringGeneration }
233
+ : {}),
234
+ __cms_tone: request.request.tone,
235
+ __cms_approximate: String(request.approximate),
236
+ __cms_pushCreated: String(request.pushCreated ?? false),
237
+ ...(request.seriesId !== undefined ? { __cms_series: request.seriesId } : {}),
238
+ ...(request.request.ownerTag !== undefined ? { __cms_owner: request.request.ownerTag } : {}),
239
+ ...(request.request.groupTag !== undefined ? { __cms_group: request.request.groupTag } : {}),
240
+ ...(request.request.routing !== undefined
241
+ ? { __cms_routing: JSON.stringify(request.request.routing) }
242
+ : {}),
243
+ // A stop marker's whole payload. It travels here rather than in `ownerTag`
244
+ // or `routing` so it can never collide with a value a consumer owns.
245
+ ...(request.repeatStop !== undefined
246
+ ? {
247
+ __cms_stop_target: request.repeatStop.targetId,
248
+ __cms_stop_due: String(request.repeatStop.dueAt),
249
+ }
250
+ : {}),
251
+ });
252
+
253
+ /** Reads a stop marker back out of a pending entry's data bag, if it is one. */
254
+ const unpackRepeatStop = (
255
+ id: string,
256
+ data: Record<string, string>,
257
+ ): RepeatStop | undefined => {
258
+ if (!isRepeatStopId(id)) return undefined;
259
+ const targetId = data.__cms_stop_target;
260
+ const dueAt = Number.parseInt(data.__cms_stop_due ?? '', 10);
261
+ if (typeof targetId !== 'string' || !Number.isFinite(dueAt)) return undefined;
262
+ return { markerId: id, targetId, dueAt };
263
+ };
264
+
265
+ const unpackEntry = (raw: Record<string, unknown>): PendingEntry | undefined => {
266
+ const notification = (raw.notification ?? {}) as Record<string, unknown>;
267
+ const trigger = (raw.trigger ?? {}) as Record<string, unknown>;
268
+ const data = (notification.data ?? {}) as Record<string, string>;
269
+ const id = notification.id;
270
+
271
+ if (typeof id !== 'string') return undefined;
272
+
273
+ let routing: Record<string, unknown> | undefined;
274
+ if (typeof data.__cms_routing === 'string') {
275
+ try {
276
+ routing = JSON.parse(data.__cms_routing) as Record<string, unknown>;
277
+ } catch {
278
+ // A payload we cannot parse is reported as absent rather than as a
279
+ // crash: the notification is still valid, only its routing is lost.
280
+ routing = undefined;
281
+ }
282
+ }
283
+
284
+ return {
285
+ id,
286
+ resolvedAt: typeof trigger.timestamp === 'number' ? trigger.timestamp : now(),
287
+ anchoring: data.__cms_anchoring === 'absolute' ? 'absolute' : 'wallClock',
288
+ anchoringGeneration:
289
+ data.__cms_anchoring === 'absolute' ? undefined : data.__cms_generation,
290
+ content: {
291
+ title: typeof notification.title === 'string' ? notification.title : '',
292
+ body: typeof notification.body === 'string' ? notification.body : '',
293
+ subtitle: typeof notification.subtitle === 'string' ? notification.subtitle : undefined,
294
+ },
295
+ tone: data.__cms_tone ?? '',
296
+ routing,
297
+ ownerTag: data.__cms_owner,
298
+ groupTag: data.__cms_group,
299
+ seriesId: data.__cms_series,
300
+ mayBeDelayed: data.__cms_approximate === 'true',
301
+ pushCreated: data.__cms_pushCreated === 'true',
302
+ };
303
+ };
304
+
305
+ const toInteraction = (raw: Record<string, unknown>): InteractionEvent | undefined => {
306
+ const eventType = raw.type;
307
+
308
+ // Only a dismissal or a press is an interaction. Everything else the
309
+ // engine emits on this channel — delivery, trigger creation, channel
310
+ // blocking — is not, and must not be reported as one.
311
+ if (
312
+ eventType !== EVENT_TYPE_DISMISSED &&
313
+ eventType !== EVENT_TYPE_PRESS &&
314
+ eventType !== EVENT_TYPE_ACTION_PRESS
315
+ ) {
316
+ return undefined;
317
+ }
318
+
319
+ const detail = (raw.detail ?? {}) as Record<string, unknown>;
320
+ const notification = (detail.notification ?? {}) as Record<string, unknown>;
321
+ const pressAction = (detail.pressAction ?? {}) as Record<string, unknown>;
322
+ const id = notification.id;
323
+
324
+ if (typeof id !== 'string') return undefined;
325
+
326
+ const data = (notification.data ?? {}) as Record<string, string>;
327
+ let routing: Record<string, unknown> | undefined;
328
+ if (typeof data.__cms_routing === 'string') {
329
+ try {
330
+ routing = JSON.parse(data.__cms_routing) as Record<string, unknown>;
331
+ } catch {
332
+ routing = undefined;
333
+ }
334
+ }
335
+
336
+ const actionId = typeof pressAction.id === 'string' ? pressAction.id : undefined;
337
+ // `default` is the engine's own press-action id for tapping the body, so
338
+ // it is a tap rather than a named action.
339
+ const isNamedAction = actionId !== undefined && actionId !== 'default';
340
+ let kind: InteractionEvent['kind'];
341
+ if (eventType === EVENT_TYPE_DISMISSED) {
342
+ kind = 'dismiss';
343
+ } else if (isNamedAction) {
344
+ kind = 'action';
345
+ } else {
346
+ kind = 'tap';
347
+ }
348
+
349
+ return {
350
+ kind,
351
+ notificationId: id,
352
+ actionId: actionId !== 'default' ? actionId : undefined,
353
+ inputText: typeof detail.input === 'string' ? detail.input : undefined,
354
+ routing,
355
+ ownerTag: data.__cms_owner,
356
+ occurredAt: now(),
357
+ appState: 'foreground',
358
+ wasBuffered: false,
359
+ };
360
+ };
361
+
362
+ /**
363
+ * Creates the marker channel the first time one is needed.
364
+ *
365
+ * Lazily rather than at initialization, so an app that never declares a
366
+ * repeating tone never grows an extra entry in the user's notification
367
+ * settings for a feature it does not use.
368
+ */
369
+ let markerChannelReady = false;
370
+ const ensureMarkerChannel = async (): Promise<void> => {
371
+ if (Platform.OS !== 'android' || markerChannelReady) return;
372
+
373
+ await engine().createChannel({
374
+ id: MARKER_CHANNEL_ID,
375
+ name: 'Background maintenance',
376
+ description: 'Used briefly to end a repeating alert. Notifications here are removed immediately.',
377
+ importance: ANDROID_IMPORTANCE.min,
378
+ vibration: false,
379
+ badge: false,
380
+ });
381
+ markerChannelReady = true;
382
+ };
383
+
384
+ let deliveryListeners: ((event: DeliveryEvent) => void)[] = [];
385
+
386
+ /** A delivery, or undefined for anything that is not one. */
387
+ const toDelivery = (raw: Record<string, unknown>): DeliveryEvent | undefined => {
388
+ if (raw.type !== EVENT_TYPE_DELIVERED) return undefined;
389
+
390
+ const detail = (raw.detail ?? {}) as Record<string, unknown>;
391
+ const notification = (detail.notification ?? {}) as Record<string, unknown>;
392
+ const id = notification.id;
393
+ if (typeof id !== 'string') return undefined;
394
+
395
+ const data = (notification.data ?? {}) as Record<string, string>;
396
+ return {
397
+ notificationId: id,
398
+ occurredAt: now(),
399
+ repeatStop: unpackRepeatStop(id, data),
400
+ };
401
+ };
402
+
403
+ return {
404
+ name: 'react-native-notify-kit',
405
+
406
+ async getCapabilities(): Promise<EngineCapabilities> {
407
+ return {
408
+ pendingCeiling: Platform.OS === 'ios' ? IOS_PENDING_CEILING : ANDROID_PENDING_BUDGET,
409
+ supportsExactAlarms: Platform.OS === 'android',
410
+ supportsChannels: Platform.OS === 'android',
411
+ supportsTextInputActions: true,
412
+ supportsDoNotDisturbBypass: Platform.OS === 'android',
413
+ // iOS exposes no looping-sound API. The one alert level that
414
+ // overrides the mute switch is entitlement-gated by Apple, and does
415
+ // not loop either — so there is nothing to partially support, and a
416
+ // partial emulation would be worse than an honest refusal.
417
+ supportsRepeatingAlert: Platform.OS === 'android',
418
+ backgroundWindowMs: BACKGROUND_WINDOW_MS,
419
+ };
420
+ },
421
+
422
+ async schedule(request: EngineScheduleRequest): Promise<void> {
423
+ const actions = request.request.actions?.map(action =>
424
+ compact({
425
+ title: action.title,
426
+ pressAction: compact({
427
+ id: action.id,
428
+ launchActivity: action.mode === 'foreground' ? 'default' : undefined,
429
+ }),
430
+ input: action.input === undefined ? undefined : compact({ placeholder: action.input.placeholder }),
431
+ }),
432
+ );
433
+
434
+ const isMarker = request.repeatStop !== undefined;
435
+ if (isMarker) {
436
+ await ensureMarkerChannel();
437
+ }
438
+
439
+ await engine().createTriggerNotification(
440
+ compact({
441
+ id: request.request.id,
442
+ title: request.request.content.title,
443
+ body: request.request.content.body,
444
+ subtitle: request.request.content.subtitle,
445
+ data: packData(request),
446
+ android: compact({
447
+ // A marker gets the quietest channel the package owns rather than
448
+ // the consumer's tone. It exists to be delivered and removed, and
449
+ // borrowing the alarm's own channel would make it alarm too.
450
+ channelId: isMarker ? MARKER_CHANNEL_ID : request.tone.android.channelId,
451
+ // Numeric enum, not the string name — see ANDROID_IMPORTANCE.
452
+ importance: isMarker
453
+ ? ANDROID_IMPORTANCE.min
454
+ : ANDROID_IMPORTANCE[request.tone.android.importance],
455
+ sound: isMarker ? undefined : request.tone.android.sound,
456
+ groupId: isMarker ? undefined : request.tone.android.groupId,
457
+ // Per-notification, not channel configuration. That is what lets
458
+ // a consumer add a repeating alert to an existing tone without
459
+ // bumping its version and costing the user their settings.
460
+ loopSound: !isMarker && request.tone.android.loopSound ? true : undefined,
461
+ category:
462
+ !isMarker && request.tone.android.alarmCategory
463
+ ? ANDROID_CATEGORY_ALARM
464
+ : undefined,
465
+ actions: isMarker ? undefined : actions,
466
+ }),
467
+ ios: compact({
468
+ categoryId: request.tone.ios.categoryId,
469
+ // This one genuinely is a string union in the engine's types.
470
+ interruptionLevel: request.tone.ios.interruptionLevel,
471
+ sound: request.tone.ios.sound,
472
+ }),
473
+ }),
474
+ {
475
+ type: TRIGGER_TYPE_TIMESTAMP,
476
+ timestamp: request.resolvedAt,
477
+ // Approximate mode is a degradation, not a failure: the notification
478
+ // is still scheduled and the caller is told it may arrive late.
479
+ alarmManager: {
480
+ allowWhileIdle: true,
481
+ type: request.approximate
482
+ ? ALARM_TYPE_INEXACT_AND_ALLOW_WHILE_IDLE
483
+ : ALARM_TYPE_EXACT_AND_ALLOW_WHILE_IDLE,
484
+ },
485
+ },
486
+ );
487
+ },
488
+
489
+ async cancel(id: string): Promise<void> {
490
+ await engine().cancelNotification(id);
491
+ },
492
+
493
+ async cancelMany(ids: readonly string[]): Promise<void> {
494
+ // Sequential rather than parallel: the engine bridges each call to
495
+ // native, and a burst of concurrent cancels is where duplicate-delivery
496
+ // races have historically appeared.
497
+ for (const id of ids) {
498
+ await engine().cancelNotification(id);
499
+ }
500
+ },
501
+
502
+ async cancelAll(): Promise<void> {
503
+ await engine().cancelAllNotifications();
504
+ },
505
+
506
+ async getPending(): Promise<readonly PendingEntry[]> {
507
+ const raw = await engine().getTriggerNotifications();
508
+ return raw
509
+ .map(unpackEntry)
510
+ .filter((entry): entry is PendingEntry => entry !== undefined)
511
+ // Stop markers are package-owned artifacts. A consumer diffing the
512
+ // device against its own intent would otherwise see a notification it
513
+ // never scheduled and, quite reasonably, cancel it.
514
+ .filter(entry => !isRepeatStopId(entry.id))
515
+ .sort((a, b) => a.resolvedAt - b.resolvedAt);
516
+ },
517
+
518
+ async declareTone(tone: ResolvedTone): Promise<ToneDeclarationOutcome> {
519
+ if (Platform.OS !== 'android') {
520
+ // iOS categories are declared at request time rather than up front.
521
+ return 'unchanged';
522
+ }
523
+
524
+ const existing = await engine().getChannels();
525
+ const held = existing.find(channel => channel.id === tone.android.channelId);
526
+
527
+ const payload = compact({
528
+ id: tone.android.channelId,
529
+ // The consumer's declared label, not the tone identifier. Passing the
530
+ // identifier here is what put a technical string in front of users on
531
+ // the one screen these labels exist to serve.
532
+ name: tone.android.name,
533
+ description: tone.android.description,
534
+ importance: ANDROID_IMPORTANCE[tone.android.importance],
535
+ sound: tone.android.sound,
536
+ vibration: tone.android.vibration,
537
+ badge: tone.android.badge,
538
+ bypassDnd: tone.android.bypassDnd,
539
+ groupId: tone.android.groupId,
540
+ });
541
+
542
+ if (held === undefined) {
543
+ await engine().createChannel(payload);
544
+ return 'created';
545
+ }
546
+
547
+ if (held.name === tone.android.name && held.description === tone.android.description) {
548
+ // Nothing to say to the platform. Skipping the call is what keeps an
549
+ // unchanged configuration genuinely free, which reconciliation
550
+ // idempotence depends on.
551
+ return 'unchanged';
552
+ }
553
+
554
+ // Android accepts a re-declaration of an existing channel and applies
555
+ // only the name and description, ignoring importance, sound, vibration
556
+ // and DND — because those belong to the user once the channel exists.
557
+ // That refusal is the guarantee: we do not have to protect the user's
558
+ // settings here, the platform declines to overwrite them.
559
+ await engine().createChannel(payload);
560
+ return 'labelsRefreshed';
561
+ },
562
+
563
+ async retireTone(channelId: string): Promise<boolean> {
564
+ if (Platform.OS !== 'android') return false;
565
+
566
+ const existing = await engine().getChannels();
567
+ if (!existing.some(channel => channel.id === channelId)) return false;
568
+
569
+ await engine().deleteChannel(channelId);
570
+ return true;
571
+ },
572
+
573
+ async declareGroups(groups: readonly ChannelGroup[]): Promise<void> {
574
+ if (Platform.OS !== 'android') return;
575
+
576
+ for (const group of groups) {
577
+ await engine().createChannelGroup(
578
+ compact({ id: group.id, name: group.name, description: group.description }),
579
+ );
580
+ }
581
+ },
582
+
583
+ async listDeclaredChannels(): Promise<readonly string[]> {
584
+ if (Platform.OS !== 'android') return [];
585
+ const channels = await engine().getChannels();
586
+ return channels.map(channel => channel.id);
587
+ },
588
+
589
+ async getPermission(kind: PermissionKind): Promise<PermissionState> {
590
+ const settings = await engine().getNotificationSettings();
591
+
592
+ if (kind === 'display') {
593
+ // Android below 13 has no runtime display permission at all.
594
+ if (Platform.OS === 'android' && (Platform.Version as number) < 33) {
595
+ return 'notRequired';
596
+ }
597
+ return toPermissionState(settings.authorizationStatus);
598
+ }
599
+
600
+ // Exact alarms exist only on Android 12+; elsewhere the concept does not
601
+ // apply, which is "not required" rather than "denied".
602
+ if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
603
+ return 'notRequired';
604
+ }
605
+
606
+ const android = (settings.android ?? {}) as Record<string, unknown>;
607
+ return android.alarm === 1 ? 'granted' : 'denied';
608
+ },
609
+
610
+ async requestPermission(kind: PermissionKind): Promise<PermissionState> {
611
+ if (kind === 'display') {
612
+ const result = await engine().requestPermission();
613
+ return toPermissionState(result.authorizationStatus);
614
+ }
615
+
616
+ // Exact-alarm capability is granted only through system settings on the
617
+ // versions that gate it — there is no in-app dialog to present.
618
+ if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
619
+ return 'notRequired';
620
+ }
621
+ await engine().openAlarmPermissionSettings();
622
+ return this.getPermission('exactAlarm');
623
+ },
624
+
625
+ async openSettings(kind: PermissionKind): Promise<void> {
626
+ if (kind === 'exactAlarm') {
627
+ if (Platform.OS !== 'android' || (Platform.Version as number) < 31) {
628
+ throw new NotificationError(
629
+ DIAGNOSTIC_CODES.SETTINGS_UNAVAILABLE,
630
+ 'No exact-alarm settings screen exists on this platform version.',
631
+ { platform: Platform.OS, version: Platform.Version },
632
+ );
633
+ }
634
+ await engine().openAlarmPermissionSettings();
635
+ return;
636
+ }
637
+ await engine().openNotificationSettings();
638
+ },
639
+
640
+ async getRestrictions(): Promise<RestrictionReport> {
641
+ if (Platform.OS !== 'android') {
642
+ return {
643
+ batteryOptimization: 'unrestricted',
644
+ autoStart: 'unrestricted',
645
+ readAt: now(),
646
+ };
647
+ }
648
+
649
+ let batteryOptimization: RestrictionReport['batteryOptimization'] = 'unknown';
650
+ try {
651
+ batteryOptimization = (await engine().isBatteryOptimizationEnabled())
652
+ ? 'restricted'
653
+ : 'unrestricted';
654
+ } catch {
655
+ batteryOptimization = 'unknown';
656
+ }
657
+
658
+ return {
659
+ batteryOptimization,
660
+ // No standard API exposes vendor auto-start policy, and guessing would
661
+ // be worse than admitting it. `unknown` is a first-class answer here.
662
+ autoStart: 'unknown',
663
+ readAt: now(),
664
+ };
665
+ },
666
+
667
+ subscribeToInteractions(handler: (event: InteractionEvent) => void): Unsubscribe {
668
+ return engine().onForegroundEvent(raw => {
669
+ const event = toInteraction(raw);
670
+ if (event !== undefined) handler(event);
671
+ });
672
+ },
673
+
674
+ async takeInitialInteraction(): Promise<InteractionEvent | undefined> {
675
+ const raw = await engine().getInitialNotification();
676
+ if (raw === null) return undefined;
677
+
678
+ const event = toInteraction(raw);
679
+ // A cold-start tap arrives before any handler exists, so it is reported
680
+ // with the state that actually produced it.
681
+ return event === undefined ? undefined : { ...event, appState: 'coldStart' };
682
+ },
683
+
684
+ async silenceDelivered(id: string): Promise<boolean> {
685
+ const displayed = await engine().getDisplayedNotifications();
686
+ const match = displayed.find(entry => {
687
+ const notification = (entry.notification ?? entry) as Record<string, unknown>;
688
+ return notification.id === id;
689
+ });
690
+
691
+ // Not displayed is the ordinary outcome, not a failure: the user handled
692
+ // it before the window ran out.
693
+ if (match === undefined) return false;
694
+
695
+ const notification = (match.notification ?? match) as Record<string, unknown>;
696
+ const android = (notification.android ?? {}) as Record<string, unknown>;
697
+
698
+ // Re-posted under the *same* identifier, so it lands on the same tray
699
+ // slot and replaces in place. Cancelling instead would remove it, and a
700
+ // notification that vanished is worse than one that never sounded — the
701
+ // user comes home to a silent phone and no idea what they missed.
702
+ await engine().displayNotification({
703
+ ...notification,
704
+ android: {
705
+ ...android,
706
+ loopSound: false,
707
+ // Without this the replacement re-alerts once on its way to going
708
+ // quiet, which is a strange thing to do to someone who has already
709
+ // heard it for fifteen minutes.
710
+ onlyAlertOnce: true,
711
+ },
712
+ });
713
+ return true;
714
+ },
715
+
716
+ async listRepeatStops(): Promise<readonly RepeatStop[]> {
717
+ const raw = await engine().getTriggerNotifications();
718
+ const stops: RepeatStop[] = [];
719
+
720
+ for (const entry of raw) {
721
+ const notification = (entry.notification ?? {}) as Record<string, unknown>;
722
+ const id = notification.id;
723
+ if (typeof id !== 'string') continue;
724
+
725
+ const data = (notification.data ?? {}) as Record<string, string>;
726
+ const stop = unpackRepeatStop(id, data);
727
+ if (stop !== undefined) stops.push(stop);
728
+ }
729
+
730
+ return stops;
731
+ },
732
+
733
+ subscribeToDeliveries(handler: (event: DeliveryEvent) => void): Unsubscribe {
734
+ deliveryListeners.push(handler);
735
+
736
+ const unsubscribe = engine().onForegroundEvent(raw => {
737
+ const event = toDelivery(raw);
738
+ if (event !== undefined) handler(event);
739
+ });
740
+
741
+ return () => {
742
+ deliveryListeners = deliveryListeners.filter(l => l !== handler);
743
+ unsubscribe();
744
+ };
745
+ },
746
+
747
+ registerBackgroundDeliveryHandler(
748
+ handler: (event: DeliveryEvent) => Promise<void>,
749
+ ): void {
750
+ engine().onBackgroundEvent(async raw => {
751
+ const event = toDelivery(raw);
752
+ if (event !== undefined) await handler(event);
753
+ });
754
+ backgroundHandlerRegistered = true;
755
+ },
756
+
757
+ hasBackgroundDeliveryHandler(): boolean {
758
+ return backgroundHandlerRegistered;
759
+ },
760
+ };
761
+ }