@idoall/dsh-notify 0.2.2

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.
package/dist/buffer.js ADDED
@@ -0,0 +1,109 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
+
4
+ /**
5
+ * Live delivery, and nothing else.
6
+ *
7
+ * The plugin keeps no history. A record lives here until newer ones push it out, and a page that was
8
+ * not connected when the event happened never learns about it. That is the deliberate trade: the
9
+ * toast IS the notification, so there is no read state to reconcile, no ack, no epoch, no cursor, no
10
+ * queue that survives a restart — and nothing to validate, recover or evict by policy.
11
+ *
12
+ * What a page needs is one number. It asks for everything after the sequence it already has, which
13
+ * makes a poll idempotent and lets a lagging tab catch up on its own.
14
+ */
15
+ export const BUFFER_LIMIT = 50;
16
+
17
+ const clone = (value) => (value === undefined ? undefined : structuredClone(value));
18
+
19
+ export function createBuffer({ limit = BUFFER_LIMIT } = {}) {
20
+ const cap = Number.isSafeInteger(limit) && limit > 0 ? limit : BUFFER_LIMIT;
21
+ let seq = 0;
22
+ const entries = [];
23
+ const index = new Map(); // mergeKey -> the sequence of its newest copy
24
+ return {
25
+ get seq() { return seq; },
26
+ get size() { return entries.length; },
27
+ /**
28
+ * Keep the newest copy of a record, at the end of the buffer. The reducer merges in place, so the
29
+ * same record legitimately arrives twice (an approval asked, then decided): a page following the
30
+ * sequence has to see the update, and nobody needs the superseded copy.
31
+ */
32
+ push(record) {
33
+ if (!record || typeof record.mergeKey !== 'string') return null;
34
+ const dropAt = (at) => {
35
+ if (at === -1) return;
36
+ const dropped = entries.splice(at, 1)[0];
37
+ if (index.get(dropped.record.mergeKey) === dropped.seq) index.delete(dropped.record.mergeKey);
38
+ };
39
+ dropAt(entries.findIndex((entry) => entry.seq === index.get(record.mergeKey)));
40
+ // A complementary merge rekeys `unlinked:…` onto the real callId but keeps the eventId, so the
41
+ // toast can update in place. The old merge identity is not news and must not sit beside it.
42
+ if (typeof record.eventId === 'string' && record.eventId !== '') {
43
+ dropAt(entries.findIndex((entry) => entry.record.eventId === record.eventId));
44
+ }
45
+ seq += 1;
46
+ entries.push({ seq, record: clone(record) });
47
+ index.set(record.mergeKey, seq);
48
+ while (entries.length > cap) {
49
+ const dropped = entries.shift();
50
+ if (index.get(dropped.record.mergeKey) === dropped.seq) index.delete(dropped.record.mergeKey);
51
+ }
52
+ return seq;
53
+ },
54
+ /**
55
+ * Everything after `since`. A client that has never polled (or that asks with a sequence from a
56
+ * previous host process) gets what the buffer holds; the caller decides what counts as news.
57
+ */
58
+ pull({ since = 0 } = {}) {
59
+ const boundary = Number.isSafeInteger(since) && since > 0 ? Math.min(since, seq) : 0;
60
+ return { seq, items: entries.filter((entry) => entry.seq > boundary).map((entry) => clone(entry.record)) };
61
+ },
62
+ };
63
+ }
64
+
65
+ /**
66
+ * Preferences are the one thing worth keeping on disk: they are the user's own choices (sound, toast
67
+ * position, subtask noise) and losing them on every restart would be a regression, not a
68
+ * simplification. No schema, no recovery machinery — a malformed file is simply replaced, and a file
69
+ * written by the store this replaced is unwrapped rather than allowed to shadow what the user chose.
70
+ */
71
+ export const SETTINGS_VERSION = 1;
72
+ /**
73
+ * @param options.dataDir — profile-owned directory; without an absolute one, preferences are per process.
74
+ * @param options.keys — the settings this version knows. A file from an older one is filtered through
75
+ * it, so a key that no longer exists cannot be carried forward forever; omitting it keeps every key.
76
+ */
77
+ export function createSettings({ dataDir, keys } = {}) {
78
+ const file = typeof dataDir === 'string' && isAbsolute(dataDir) ? join(dataDir, 'settings.json') : null;
79
+ const allowed = Array.isArray(keys) ? new Set(keys) : null;
80
+ const clean = (input) => (allowed ? Object.fromEntries(Object.entries(input ?? {}).filter(([key]) => allowed.has(key))) : { ...(input ?? {}) });
81
+ let value = {};
82
+ if (file) {
83
+ try {
84
+ const parsed = JSON.parse(readFileSync(file, 'utf8'));
85
+ const document = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
86
+ // The deleted store kept preferences as a `{version, value}` document. Leaving that wrapper in
87
+ // place would shadow every setting already chosen, and it would be written back forever; the
88
+ // next `set` rewrites the file flat.
89
+ const legacy = document?.version === SETTINGS_VERSION && document.value && typeof document.value === 'object' && !Array.isArray(document.value);
90
+ value = clean(legacy ? document.value : document);
91
+ } catch { /* first run, or a file we are about to overwrite */ }
92
+ }
93
+ return {
94
+ get: () => ({ ...value }),
95
+ set(next = {}) {
96
+ value = { ...value, ...clean(next) };
97
+ if (!file) return { ...value };
98
+ try {
99
+ mkdirSync(dirname(file), { recursive: true });
100
+ const temporary = `${file}.tmp`;
101
+ writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
102
+ renameSync(temporary, file);
103
+ } catch { /* a read-only profile still gets the setting for this process */ }
104
+ return { ...value };
105
+ },
106
+ /** What `/config` reports about durability: records never persist, preferences usually do. */
107
+ get status() { return { records: 'memory', preferences: file ? 'file' : 'session' }; },
108
+ };
109
+ }