@chipmobilesdk/rn-notification 0.1.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 (66) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +306 -0
  3. package/package.json +73 -0
  4. package/src/channel/migrate.ts +211 -0
  5. package/src/channel/tone-map.ts +90 -0
  6. package/src/contract/channel.ts +89 -0
  7. package/src/contract/diagnostics.ts +102 -0
  8. package/src/contract/errors.ts +123 -0
  9. package/src/contract/index.ts +10 -0
  10. package/src/contract/interaction.ts +62 -0
  11. package/src/contract/notification.ts +118 -0
  12. package/src/contract/permission.ts +60 -0
  13. package/src/contract/reconcile.ts +88 -0
  14. package/src/contract/recurrence.ts +123 -0
  15. package/src/diagnostics/burst.ts +101 -0
  16. package/src/diagnostics/events.ts +72 -0
  17. package/src/diagnostics/redact.ts +72 -0
  18. package/src/diagnostics/snapshot.ts +64 -0
  19. package/src/engine/adapter.ts +79 -0
  20. package/src/engine/notify-kit-engine.ts +535 -0
  21. package/src/index.ts +173 -0
  22. package/src/initialize.ts +174 -0
  23. package/src/interaction/index.ts +146 -0
  24. package/src/maintenance/cycle.ts +147 -0
  25. package/src/maintenance/permission-refresh.ts +41 -0
  26. package/src/maintenance/reanchor.ts +95 -0
  27. package/src/maintenance/toggle.ts +60 -0
  28. package/src/maintenance/verify.ts +83 -0
  29. package/src/maintenance/window-refresh.ts +61 -0
  30. package/src/permission/index.ts +183 -0
  31. package/src/permission/state.ts +77 -0
  32. package/src/push/envelope.ts +165 -0
  33. package/src/push/fcm-provider.ts +146 -0
  34. package/src/push/gate.ts +190 -0
  35. package/src/push/index.ts +29 -0
  36. package/src/push/instructions.ts +109 -0
  37. package/src/push/provider-adapter.ts +54 -0
  38. package/src/push/signout.ts +65 -0
  39. package/src/reconcile/chunk.ts +53 -0
  40. package/src/reconcile/diff.ts +145 -0
  41. package/src/reconcile/duplicates.ts +73 -0
  42. package/src/reconcile/index.ts +175 -0
  43. package/src/reconcile/truncate.ts +56 -0
  44. package/src/recurrence/clock-guard.ts +71 -0
  45. package/src/recurrence/expand.ts +292 -0
  46. package/src/recurrence/index.ts +177 -0
  47. package/src/schedule/anchor.ts +267 -0
  48. package/src/schedule/index.ts +173 -0
  49. package/src/schedule/partition.ts +85 -0
  50. package/src/schedule/resolve-moment.ts +80 -0
  51. package/src/schedule/validate-content.ts +111 -0
  52. package/src/schedule/validate-identifier.ts +114 -0
  53. package/src/state/caps.ts +71 -0
  54. package/src/state/dedup-ledger.ts +39 -0
  55. package/src/state/interaction-buffer.ts +73 -0
  56. package/src/state/mmkv-store.ts +71 -0
  57. package/src/state/permission-history.ts +41 -0
  58. package/src/state/record.ts +246 -0
  59. package/src/state/reset.ts +41 -0
  60. package/src/state/series-ledger.ts +84 -0
  61. package/src/state/store.ts +40 -0
  62. package/src/testing/conformance/index.ts +194 -0
  63. package/src/testing/fake-engine.ts +284 -0
  64. package/src/testing/fake-provider.ts +129 -0
  65. package/src/testing/faults.ts +72 -0
  66. package/src/testing/index.ts +26 -0
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Desired-versus-device diffing.
3
+ *
4
+ * The package's central promise lives here: reconciling twice with unchanged
5
+ * input must produce **zero** platform operations on the second run. That is
6
+ * only true if "unchanged" is decided by comparing everything that would make
7
+ * the delivered notification different — miss a field and the second run
8
+ * rewrites entries needlessly; include a volatile one and it never settles.
9
+ *
10
+ * Anchoring mode is part of the comparison key deliberately. A mode change on
11
+ * the same identifier must force a replacement rather than read as unchanged,
12
+ * because the two modes resolve to different instants the moment a zone
13
+ * changes.
14
+ */
15
+
16
+ import type { NotificationRequest, PendingEntry } from '../contract/notification';
17
+
18
+ export type OperationKind = 'create' | 'replace' | 'cancel';
19
+
20
+ export interface DiffOperation {
21
+ readonly kind: OperationKind;
22
+ readonly id: string;
23
+ /** Present for create and replace. */
24
+ readonly request?: NotificationRequest;
25
+ /** The instant the entry should fire, after anchoring resolution. */
26
+ readonly resolvedAt?: number;
27
+ }
28
+
29
+ export interface DiffResult {
30
+ readonly operations: readonly DiffOperation[];
31
+ readonly unchanged: readonly string[];
32
+ }
33
+
34
+ /** Stable serialization of the fields that make a delivered notification different. */
35
+ function fingerprint(
36
+ request: NotificationRequest,
37
+ resolvedAt: number,
38
+ ): string {
39
+ return JSON.stringify([
40
+ resolvedAt,
41
+ request.moment.anchoring ?? 'wallClock',
42
+ request.content.title,
43
+ request.content.body,
44
+ request.content.subtitle ?? null,
45
+ request.tone,
46
+ request.ownerTag ?? null,
47
+ request.groupTag ?? null,
48
+ // Key order is not stable across constructions, so sort before comparing —
49
+ // otherwise two structurally identical payloads could compare unequal and
50
+ // the second pass would rewrite every entry carrying routing data.
51
+ request.routing === undefined ? null : stableStringify(request.routing),
52
+ request.actions === undefined
53
+ ? null
54
+ : request.actions.map(a => [a.id, a.title, a.mode, a.input?.placeholder ?? null]),
55
+ ]);
56
+ }
57
+
58
+ function entryFingerprint(entry: PendingEntry): string {
59
+ return JSON.stringify([
60
+ entry.resolvedAt,
61
+ entry.anchoring,
62
+ entry.content.title,
63
+ entry.content.body,
64
+ entry.content.subtitle ?? null,
65
+ entry.tone,
66
+ entry.ownerTag ?? null,
67
+ entry.groupTag ?? null,
68
+ entry.routing === undefined ? null : stableStringify(entry.routing),
69
+ entry.actions === undefined
70
+ ? null
71
+ : entry.actions.map(a => [a.id, a.title, a.mode, a.input?.placeholder ?? null]),
72
+ ]);
73
+ }
74
+
75
+ /** Key-order-independent JSON, so structurally equal payloads compare equal. */
76
+ function stableStringify(value: unknown): string {
77
+ if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';
78
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
79
+
80
+ const entries = Object.entries(value as Record<string, unknown>).sort(([a], [b]) =>
81
+ a < b ? -1 : a > b ? 1 : 0,
82
+ );
83
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(',')}}`;
84
+ }
85
+
86
+ export interface DiffInput {
87
+ readonly desired: readonly NotificationRequest[];
88
+ /** Resolved firing instant per desired identifier, after anchoring. */
89
+ readonly resolvedAt: ReadonlyMap<string, number>;
90
+ /** What the device currently holds, already narrowed to the caller's domain. */
91
+ readonly device: readonly PendingEntry[];
92
+ /**
93
+ * Identifiers that were rejected before diffing and must be left alone.
94
+ *
95
+ * Without this they would look like strays — present on the device, absent
96
+ * from the desired set — and be cancelled. But a rejection is not a
97
+ * cancellation: the package could not decide what the caller meant, so
98
+ * destroying the existing notification would be the worst available answer.
99
+ */
100
+ readonly protectedIds?: ReadonlySet<string>;
101
+ }
102
+
103
+ /**
104
+ * Computes the minimal operation set.
105
+ *
106
+ * Cancels are emitted before creates so an interrupted pass leaves a
107
+ * recoverable gap rather than a duplicate: a missing notification is fixed by
108
+ * the next reconcile, whereas two notifications for one subject is a defect the
109
+ * user sees.
110
+ */
111
+ export function diff(input: DiffInput): DiffResult {
112
+ const deviceById = new Map(input.device.map(entry => [entry.id, entry]));
113
+ const desiredIds = new Set(input.desired.map(request => request.id));
114
+
115
+ const cancels: DiffOperation[] = [];
116
+ const writes: DiffOperation[] = [];
117
+ const unchanged: string[] = [];
118
+
119
+ const protectedIds = input.protectedIds ?? new Set<string>();
120
+
121
+ for (const entry of input.device) {
122
+ if (!desiredIds.has(entry.id) && !protectedIds.has(entry.id)) {
123
+ cancels.push({ kind: 'cancel', id: entry.id });
124
+ }
125
+ }
126
+
127
+ for (const request of input.desired) {
128
+ const resolvedAt = input.resolvedAt.get(request.id) ?? request.moment.at;
129
+ const existing = deviceById.get(request.id);
130
+
131
+ if (existing === undefined) {
132
+ writes.push({ kind: 'create', id: request.id, request, resolvedAt });
133
+ continue;
134
+ }
135
+
136
+ if (fingerprint(request, resolvedAt) === entryFingerprint(existing)) {
137
+ unchanged.push(request.id);
138
+ continue;
139
+ }
140
+
141
+ writes.push({ kind: 'replace', id: request.id, request, resolvedAt });
142
+ }
143
+
144
+ return { operations: [...cancels, ...writes], unchanged };
145
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Duplicate identifier resolution.
3
+ *
4
+ * An identifier appearing twice in one desired set means the caller's key
5
+ * derivation produced two notifications for one identity. That is a bug, not a
6
+ * preference, so the package refuses rather than silently picking a winner.
7
+ *
8
+ * **Every** copy is rejected — no entry wins. Order-independence then follows
9
+ * for free rather than having to be engineered: there is no "first" or "last"
10
+ * to depend on.
11
+ *
12
+ * The rule applies even to byte-identical duplicates. Treating those as
13
+ * mergeable would require a deep-equality definition that becomes a contract of
14
+ * its own, and a repeated identifier is a key-derivation bug either way.
15
+ */
16
+
17
+ import type { NotificationRequest } from '../contract/notification';
18
+ import type { RejectedEntry } from '../contract/reconcile';
19
+ import { DIAGNOSTIC_CODES } from '../contract/errors';
20
+
21
+ export interface DuplicateSplit {
22
+ /** Entries whose identifier appeared exactly once. */
23
+ readonly unique: readonly NotificationRequest[];
24
+ /** One rejection record per repeated identifier, not per copy. */
25
+ readonly rejected: readonly RejectedEntry[];
26
+ }
27
+
28
+ /**
29
+ * Splits a desired set into applicable entries and rejections.
30
+ *
31
+ * `existingIds` lets the rejection state whether a notification already
32
+ * scheduled under that identifier was left in place — without it a caller could
33
+ * reasonably read "rejected" as "cancelled".
34
+ */
35
+ export function splitDuplicates(
36
+ desired: readonly NotificationRequest[],
37
+ existingIds: ReadonlySet<string> = new Set(),
38
+ ): DuplicateSplit {
39
+ const counts = new Map<string, number>();
40
+ for (const request of desired) {
41
+ counts.set(request.id, (counts.get(request.id) ?? 0) + 1);
42
+ }
43
+
44
+ const unique: NotificationRequest[] = [];
45
+ const rejected: RejectedEntry[] = [];
46
+
47
+ for (const request of desired) {
48
+ if ((counts.get(request.id) ?? 0) === 1) {
49
+ unique.push(request);
50
+ }
51
+ }
52
+
53
+ // Sorted so the report itself is order-independent, not merely its effect.
54
+ const repeated = [...counts.entries()]
55
+ .filter(([, count]) => count > 1)
56
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
57
+
58
+ for (const [id, occurrences] of repeated) {
59
+ rejected.push({
60
+ id,
61
+ code: DIAGNOSTIC_CODES.DUPLICATE_IDENTIFIER,
62
+ reason:
63
+ `Identifier appeared ${occurrences} times in one desired set. Every copy was rejected, because the package cannot know which was intended.` +
64
+ (existingIds.has(id)
65
+ ? ' Any notification already scheduled under it was left in place — this is a rejection, not a cancellation.'
66
+ : ''),
67
+ occurrences,
68
+ existingLeftInPlace: existingIds.has(id),
69
+ });
70
+ }
71
+
72
+ return { unique, rejected };
73
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The reconciliation operation.
3
+ *
4
+ * A caller hands over the complete set its data implies; the package works out
5
+ * what to add, replace, and remove. This is **never** run automatically — only
6
+ * the caller knows what its data implies, and a package that guessed a desired
7
+ * set would cancel notifications it does not understand.
8
+ *
9
+ * Overlapping calls are serialized rather than run concurrently, because two
10
+ * passes interleaving their cancels and creates is exactly how duplicates
11
+ * appear.
12
+ */
13
+
14
+ import type { NotificationRequest, PendingEntry } from '../contract/notification';
15
+ import type { ReconcileInput, ReconcileResult } from '../contract/reconcile';
16
+ import type { ResolvedTone } from '../contract/channel';
17
+ import type { NotificationEngineAdapter } from '../engine/adapter';
18
+ import { DIAGNOSTIC_CODES } from '../contract/errors';
19
+ import { anchorMoment, type TimeZoneReader } from '../schedule/anchor';
20
+ import { resolveMoment } from '../schedule/resolve-moment';
21
+ import { validateRequest } from '../schedule';
22
+ import { isNotificationError } from '../contract/errors';
23
+ import type { RejectedEntry } from '../contract/reconcile';
24
+ import { splitDuplicates } from './duplicates';
25
+ import { truncateToCeiling } from './truncate';
26
+ import { diff } from './diff';
27
+ import { applyInChunks } from './chunk';
28
+
29
+ export interface ReconcileDependencies {
30
+ readonly engine: NotificationEngineAdapter;
31
+ readonly resolveTone: (toneId: string) => ResolvedTone | undefined;
32
+ readonly timeZone: TimeZoneReader;
33
+ readonly now: () => number;
34
+ readonly canScheduleExactly: () => boolean;
35
+ readonly emit?: (code: string, message: string, context?: Record<string, unknown>) => void;
36
+ /** Overridable for tests that need to observe chunk boundaries. */
37
+ readonly chunkSize?: number;
38
+ }
39
+
40
+ /**
41
+ * Narrows the device set to the caller's declared domain.
42
+ *
43
+ * Everything outside it is invisible to this pass, which is what makes it safe
44
+ * to cancel strays: a notification from another domain or another library is
45
+ * never a stray, it simply is not ours.
46
+ */
47
+ function inDomain(entry: PendingEntry, input: ReconcileInput): boolean {
48
+ if (entry.pushCreated && input.includePushCreated !== true) return false;
49
+ return entry.groupTag === input.domain;
50
+ }
51
+
52
+ export function createReconciler(deps: ReconcileDependencies) {
53
+ const emit = deps.emit ?? (() => {});
54
+ let inFlight: Promise<ReconcileResult> = Promise.resolve() as unknown as Promise<ReconcileResult>;
55
+
56
+ const run = async (input: ReconcileInput): Promise<ReconcileResult> => {
57
+ const startedAt = deps.now();
58
+ const zone = deps.timeZone();
59
+
60
+ const device = (await deps.engine.getPending()).filter(entry => inDomain(entry, input));
61
+ const existingIds = new Set(device.map(entry => entry.id));
62
+
63
+ // Duplicates first: a repeated identifier is refused before anything else
64
+ // looks at it, so no later stage has to decide which copy it meant.
65
+ const { unique, rejected: duplicateRejections } = splitDuplicates(input.desired, existingIds);
66
+ const rejected: RejectedEntry[] = [...duplicateRejections];
67
+
68
+ // Validate and anchor. A rejection here removes one entry; it never fails
69
+ // the pass, because 499 valid entries should not be lost to one bad one.
70
+ const valid: NotificationRequest[] = [];
71
+ const resolvedAt = new Map<string, number>();
72
+
73
+ for (const request of unique) {
74
+ try {
75
+ validateRequest(request, deps.resolveTone);
76
+ const anchored = anchorMoment(request.moment, zone);
77
+ const resolution = resolveMoment(anchored.resolvedAt, deps.now());
78
+ resolvedAt.set(request.id, resolution.at);
79
+ valid.push(request);
80
+ } catch (error) {
81
+ rejected.push({
82
+ id: request.id,
83
+ code: isNotificationError(error) ? error.code : 'UNKNOWN',
84
+ reason: error instanceof Error ? error.message : String(error),
85
+ occurrences: 1,
86
+ existingLeftInPlace: existingIds.has(request.id),
87
+ });
88
+ }
89
+ }
90
+
91
+ const capabilities = await deps.engine.getCapabilities();
92
+ const { kept, report: truncation } = truncateToCeiling(
93
+ valid,
94
+ resolvedAt,
95
+ capabilities.pendingCeiling,
96
+ );
97
+
98
+ if (truncation !== undefined) {
99
+ emit(
100
+ DIAGNOSTIC_CODES.TRUNCATED_OVER_CEILING,
101
+ `Desired set exceeded the platform ceiling of ${truncation.ceiling}; ${truncation.droppedCount} furthest-out entries were not registered. They are re-evaluated at the next window refresh.`,
102
+ { ceiling: truncation.ceiling, dropped: truncation.droppedCount },
103
+ );
104
+ }
105
+
106
+ // Every rejected identifier is protected from cancellation. A rejection
107
+ // means the package could not tell what the caller intended, and
108
+ // destroying the existing notification on that basis would be the worst
109
+ // available answer (FR-028c).
110
+ const { operations, unchanged } = diff({
111
+ desired: kept,
112
+ resolvedAt,
113
+ device,
114
+ protectedIds: new Set(rejected.map(entry => entry.id)),
115
+ });
116
+
117
+ const created: string[] = [];
118
+ const replaced: string[] = [];
119
+ const cancelled: string[] = [];
120
+ const approximate = !deps.canScheduleExactly();
121
+
122
+ await applyInChunks(
123
+ operations,
124
+ async operation => {
125
+ if (operation.kind === 'cancel') {
126
+ await deps.engine.cancel(operation.id);
127
+ cancelled.push(operation.id);
128
+ return;
129
+ }
130
+
131
+ const request = operation.request!;
132
+ const tone = deps.resolveTone(request.tone)!;
133
+ await deps.engine.schedule({
134
+ request,
135
+ resolvedAt: operation.resolvedAt!,
136
+ tone,
137
+ anchoringGeneration:
138
+ (request.moment.anchoring ?? 'wallClock') === 'absolute' ? undefined : zone,
139
+ approximate,
140
+ });
141
+ (operation.kind === 'create' ? created : replaced).push(operation.id);
142
+ },
143
+ { size: deps.chunkSize },
144
+ );
145
+
146
+ return {
147
+ domain: input.domain,
148
+ created,
149
+ replaced,
150
+ cancelled,
151
+ unchanged,
152
+ rejected,
153
+ truncated: truncation,
154
+ operationCount: operations.length,
155
+ durationMs: deps.now() - startedAt,
156
+ };
157
+ };
158
+
159
+ return {
160
+ /**
161
+ * Serialized against itself: a second call waits for the first rather than
162
+ * interleaving with it.
163
+ */
164
+ async reconcile(input: ReconcileInput): Promise<ReconcileResult> {
165
+ const next = inFlight.then(
166
+ () => run(input),
167
+ () => run(input),
168
+ );
169
+ inFlight = next.catch(() => undefined) as Promise<ReconcileResult>;
170
+ return next;
171
+ },
172
+ };
173
+ }
174
+
175
+ export type Reconciler = ReturnType<typeof createReconciler>;
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Platform-ceiling truncation.
3
+ *
4
+ * iOS keeps only the 64 soonest pending notifications and silently discards the
5
+ * rest. The package computes the same cut deliberately, so the outcome is
6
+ * reported rather than discovered as missing notifications.
7
+ *
8
+ * Soonest-first is the only rule that degrades gracefully: dropped entries are
9
+ * not lost, they are simply not yet registered, and each window refresh
10
+ * registers those that have moved into range.
11
+ */
12
+
13
+ import type { NotificationRequest } from '../contract/notification';
14
+ import type { TruncationReport } from '../contract/reconcile';
15
+
16
+ export interface TruncationOutcome {
17
+ readonly kept: readonly NotificationRequest[];
18
+ readonly report?: TruncationReport;
19
+ }
20
+
21
+ /**
22
+ * Keeps the `ceiling` soonest entries.
23
+ *
24
+ * Ties on the delivery instant are broken by identifier so the cut is
25
+ * deterministic — otherwise two runs over the same data could drop different
26
+ * entries and the idempotence guarantee would not hold.
27
+ */
28
+ export function truncateToCeiling(
29
+ desired: readonly NotificationRequest[],
30
+ resolvedAt: ReadonlyMap<string, number>,
31
+ ceiling: number,
32
+ ): TruncationOutcome {
33
+ if (desired.length <= ceiling) {
34
+ return { kept: desired };
35
+ }
36
+
37
+ const ordered = [...desired].sort((a, b) => {
38
+ const aAt = resolvedAt.get(a.id) ?? a.moment.at;
39
+ const bAt = resolvedAt.get(b.id) ?? b.moment.at;
40
+ if (aAt !== bAt) return aAt - bAt;
41
+ return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
42
+ });
43
+
44
+ const kept = ordered.slice(0, ceiling);
45
+ const dropped = ordered.slice(ceiling);
46
+
47
+ return {
48
+ kept,
49
+ report: {
50
+ ceiling,
51
+ droppedCount: dropped.length,
52
+ droppedIds: dropped.map(entry => entry.id),
53
+ reEvaluatedOnNextRefresh: true,
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Clock-discontinuity bounding.
3
+ *
4
+ * A device clock moved backwards makes past occurrences look future again. Left
5
+ * alone, the next expansion would re-register every occurrence the user already
6
+ * received, and moving the clock forward again would fire them all at once.
7
+ *
8
+ * The guard is deliberately blunt: occurrences at or before the last horizon the
9
+ * series already expanded through are never re-emitted. The package would
10
+ * rather lose an occurrence after a manual clock change than deliver a burst of
11
+ * notifications for events that already happened.
12
+ */
13
+
14
+ import type { Occurrence } from './expand';
15
+
16
+ /** A jump larger than this is treated as a clock change rather than ordinary drift. */
17
+ export const CLOCK_DISCONTINUITY_THRESHOLD_MS = 60 * 60 * 1000;
18
+
19
+ export interface ClockGuardInput {
20
+ readonly occurrences: readonly Occurrence[];
21
+ /** Horizon this series had already expanded through before now. */
22
+ readonly previousHorizon: number | undefined;
23
+ readonly now: number;
24
+ /** The clock reading when the series was last expanded, if known. */
25
+ readonly previousNow: number | undefined;
26
+ }
27
+
28
+ export interface ClockGuardResult {
29
+ readonly occurrences: readonly Occurrence[];
30
+ readonly suppressed: number;
31
+ readonly discontinuity: 'none' | 'backwards' | 'forwards';
32
+ }
33
+
34
+ /**
35
+ * Drops occurrences that a clock discontinuity would otherwise resurrect.
36
+ *
37
+ * Forward jumps are detected and reported but not filtered: an occurrence that
38
+ * became due because time genuinely passed is legitimate, and the platform's
39
+ * own delivery is the right place for it to be resolved.
40
+ */
41
+ export function guardAgainstClockChange(input: ClockGuardInput): ClockGuardResult {
42
+ const { occurrences, previousHorizon, now, previousNow } = input;
43
+
44
+ let discontinuity: ClockGuardResult['discontinuity'] = 'none';
45
+ if (previousNow !== undefined) {
46
+ const delta = now - previousNow;
47
+ if (delta < -CLOCK_DISCONTINUITY_THRESHOLD_MS) {
48
+ discontinuity = 'backwards';
49
+ } else if (delta > CLOCK_DISCONTINUITY_THRESHOLD_MS * 24) {
50
+ discontinuity = 'forwards';
51
+ }
52
+ }
53
+
54
+ if (previousHorizon === undefined) {
55
+ return { occurrences, suppressed: 0, discontinuity };
56
+ }
57
+
58
+ // Anything at or before the previously-expanded horizon was already handled
59
+ // once. Re-emitting it would mean delivering a notification for an event the
60
+ // user has already seen.
61
+ const kept = occurrences.filter(occurrence => occurrence.at > previousHorizon || occurrence.at > now);
62
+ const alreadyHandled = occurrences.filter(
63
+ occurrence => occurrence.at <= previousHorizon && occurrence.at <= now,
64
+ );
65
+
66
+ return {
67
+ occurrences: kept,
68
+ suppressed: alreadyHandled.length,
69
+ discontinuity,
70
+ };
71
+ }