@voltro/plugin-notifications 0.85.0 → 0.86.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.
@@ -0,0 +1,42 @@
1
+ import { Schema as e } from "effect";
2
+ //#region src/sendNotification.ts
3
+ var t = (e) => {
4
+ if (typeof e == "object" && e) {
5
+ let t = e;
6
+ if (typeof t.userId == "string") return [t.userId];
7
+ if (Array.isArray(t.userIds)) return t.userIds.filter((e) => typeof e == "string");
8
+ }
9
+ throw Error("sendNotification: pass `recipients` — the audience has neither `userId` nor `userIds`");
10
+ }, n = async (n, i, a) => {
11
+ let o = e.decodeUnknownSync(i.audience)(a.audience), s = e.decodeUnknownSync(i.payload)(a.payload), c = a.recipients ? await a.recipients(o) : t(o), l = [];
12
+ for (let e of c) {
13
+ let t = (a.localeFor ? await a.localeFor(e) : null) ?? a.defaultLocale ?? "en", o = await n.send(r(i, s, e, t, a.tenantId));
14
+ l.push({
15
+ recipientId: e,
16
+ locale: t,
17
+ result: o
18
+ });
19
+ }
20
+ return l;
21
+ }, r = (e, t, n, r, i) => {
22
+ let a = e.render(t, {
23
+ locale: r,
24
+ recipientId: n
25
+ });
26
+ return {
27
+ to: n,
28
+ category: e.category,
29
+ title: a.title,
30
+ body: a.body,
31
+ data: {
32
+ ...a.data,
33
+ notification: e.name,
34
+ ...a.image === void 0 ? {} : { image: a.image },
35
+ ...a.actions === void 0 ? {} : { actions: a.actions }
36
+ },
37
+ ...e.channels === void 0 ? {} : { channels: e.channels },
38
+ ...i === void 0 ? {} : { tenantId: i }
39
+ };
40
+ };
41
+ //#endregion
42
+ export { t as defaultRecipients, r as sendInputFor, n as sendNotification };
@@ -0,0 +1,212 @@
1
+ import { resolveChannels as e } from "./channels.js";
2
+ import { randomUUID as t } from "node:crypto";
3
+ //#region src/service.ts
4
+ var n = (e) => ({
5
+ id: "inApp",
6
+ deliver: async (n) => {
7
+ await e.addInbox({
8
+ id: t(),
9
+ subjectId: n.to,
10
+ category: n.category,
11
+ title: n.title,
12
+ body: n.body,
13
+ data: n.data ?? {},
14
+ tenantId: n.tenantId ?? null,
15
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
16
+ });
17
+ }
18
+ }), r = (e, t) => {
19
+ try {
20
+ let n = new Intl.DateTimeFormat("en-US", {
21
+ timeZone: t,
22
+ hour: "2-digit",
23
+ minute: "2-digit",
24
+ hour12: !1
25
+ }).formatToParts(e), r = Number(n.find((e) => e.type === "hour")?.value ?? "0") % 24, i = Number(n.find((e) => e.type === "minute")?.value ?? "0");
26
+ return r * 60 + i;
27
+ } catch {
28
+ return e.getUTCHours() * 60 + e.getUTCMinutes();
29
+ }
30
+ }, i = (e, t) => {
31
+ if (e.startMinute === e.endMinute) return !1;
32
+ let n = r(t, e.tz ?? "UTC");
33
+ return e.startMinute < e.endMinute ? n >= e.startMinute && n < e.endMinute : n >= e.startMinute || n < e.endMinute;
34
+ }, a = (e, t) => {
35
+ let n = r(t, e.tz ?? "UTC"), i = e.endMinute - n;
36
+ return i <= 0 && (i += 1440), new Date(t.getTime() + i * 6e4);
37
+ }, o = (n) => {
38
+ let r = new Map(n.channels.map((e) => [e.id, e])), o = n.channels.map((e) => e.id), c = n.now ?? (() => (/* @__PURE__ */ new Date()).toISOString()), l = n.digestWindowMs ?? 0, u = async (i) => {
39
+ let a = await n.store.getPreferences(i.to), s = e(o, i.category, i.channels, a, i.to), l = o.filter((e) => !s.includes(e)), u = [], d = [], f = {
40
+ to: i.to,
41
+ category: i.category,
42
+ title: i.title,
43
+ body: i.body,
44
+ ...i.data ? { data: i.data } : {},
45
+ tenantId: i.tenantId ?? null
46
+ };
47
+ for (let e of s) {
48
+ let a = r.get(e);
49
+ if (!a) continue;
50
+ if (a.deliverDetailed !== void 0) {
51
+ try {
52
+ let r = await a.deliverDetailed(f);
53
+ for (let a of r) await n.store.recordDelivery({
54
+ id: t(),
55
+ to: i.to,
56
+ category: i.category,
57
+ channel: e,
58
+ at: c(),
59
+ status: a.status,
60
+ endpoint: a.endpoint,
61
+ ...a.error === void 0 ? {} : { error: a.error },
62
+ ...a.clickToken === void 0 ? {} : { clickToken: a.clickToken }
63
+ });
64
+ let o = r.filter((e) => e.status === "failed");
65
+ r.length === 0 || o.length < r.length ? u.push(e) : d.push({
66
+ channel: e,
67
+ error: o[0]?.error ?? "all endpoints failed"
68
+ });
69
+ } catch (r) {
70
+ let a = r instanceof Error ? r.message : String(r);
71
+ d.push({
72
+ channel: e,
73
+ error: a
74
+ }), await n.store.recordDelivery({
75
+ id: t(),
76
+ to: i.to,
77
+ category: i.category,
78
+ channel: e,
79
+ at: c(),
80
+ status: "failed",
81
+ error: a
82
+ });
83
+ }
84
+ continue;
85
+ }
86
+ let o = {
87
+ id: t(),
88
+ to: i.to,
89
+ category: i.category,
90
+ channel: e,
91
+ at: c()
92
+ };
93
+ try {
94
+ await a.deliver(f), u.push(e), await n.store.recordDelivery({
95
+ ...o,
96
+ status: "sent"
97
+ });
98
+ } catch (t) {
99
+ let r = t instanceof Error ? t.message : String(t);
100
+ d.push({
101
+ channel: e,
102
+ error: r
103
+ }), await n.store.recordDelivery({
104
+ ...o,
105
+ status: "failed",
106
+ error: r
107
+ });
108
+ }
109
+ }
110
+ return {
111
+ delivered: u,
112
+ failed: d,
113
+ skipped: l
114
+ };
115
+ }, d = async (e) => {
116
+ let r = await n.store.getQuietHours(e.to), o = new Date(c());
117
+ if (r && i(r, o)) return (r.policy ?? "hold") === "drop" ? {
118
+ delivered: [],
119
+ failed: [],
120
+ skipped: [],
121
+ held: "quiet-drop"
122
+ } : (await n.store.enqueueHeld({
123
+ id: t(),
124
+ kind: "quiet",
125
+ subjectId: e.to,
126
+ send: e,
127
+ flushAt: a(r, o).toISOString()
128
+ }), {
129
+ delivered: [],
130
+ failed: [],
131
+ skipped: [],
132
+ held: "quiet-held"
133
+ });
134
+ if (l > 0 && !e.channels) {
135
+ let r = (await n.store.pendingDigest(e.to))[0]?.flushAt ?? new Date(o.getTime() + l).toISOString();
136
+ return await n.store.enqueueHeld({
137
+ id: t(),
138
+ kind: "digest",
139
+ subjectId: e.to,
140
+ send: e,
141
+ flushAt: r
142
+ }), {
143
+ delivered: [],
144
+ failed: [],
145
+ skipped: [],
146
+ held: "digest"
147
+ };
148
+ }
149
+ return u(e);
150
+ };
151
+ return {
152
+ send: d,
153
+ inbox: (e, t) => n.store.listInbox(e, t),
154
+ unreadCount: (e) => n.store.unreadCount(e),
155
+ markRead: (e, t) => n.store.markRead(e, t),
156
+ markUnread: (e, t) => n.store.markUnread(e, t),
157
+ markAllRead: (e) => n.store.markAllRead(e),
158
+ setArchived: (e, t, r) => n.store.setArchived(e, t, r),
159
+ getPreferences: (e) => n.store.getPreferences(e),
160
+ setPreference: (e) => n.store.setPreference(e),
161
+ subscribe: (e, t, r) => n.store.subscribeTopic({
162
+ topic: e,
163
+ subjectId: t,
164
+ tenantId: r ?? null
165
+ }),
166
+ unsubscribe: (e, t) => n.store.unsubscribeTopic(e, t),
167
+ broadcast: async (e, t) => {
168
+ let r = await n.store.listTopicSubscribers(e), i = [];
169
+ for (let e of r) i.push(await d({
170
+ ...t,
171
+ to: e.subjectId,
172
+ tenantId: t.tenantId ?? e.tenantId ?? null
173
+ }));
174
+ return {
175
+ recipients: r.length,
176
+ results: i
177
+ };
178
+ },
179
+ setQuietHours: (e) => n.store.setQuietHours(e),
180
+ clearQuietHours: (e) => n.store.clearQuietHours(e),
181
+ getQuietHours: (e) => n.store.getQuietHours(e),
182
+ flushDue: async (e = new Date(c())) => {
183
+ let t = await n.store.dueHeld(e.toISOString());
184
+ if (t.length === 0) return 0;
185
+ for (let e of t.filter((e) => e.kind === "quiet")) await u(e.send);
186
+ let r = /* @__PURE__ */ new Map();
187
+ for (let e of t.filter((e) => e.kind === "digest")) {
188
+ let t = r.get(e.subjectId) ?? [];
189
+ t.push(e), r.set(e.subjectId, t);
190
+ }
191
+ for (let [e, t] of r) await u(s(e, t));
192
+ return await n.store.clearHeld(t.map((e) => e.id)), t.length;
193
+ }
194
+ };
195
+ }, s = (e, t) => {
196
+ if (t.length === 1) return t[0].send;
197
+ let n = t.map((e) => ({
198
+ category: e.send.category,
199
+ title: e.send.title,
200
+ body: e.send.body
201
+ }));
202
+ return {
203
+ to: e,
204
+ category: "digest",
205
+ title: `${t.length} new notifications`,
206
+ body: n.map((e) => `• ${e.title}`).join("\n"),
207
+ data: { items: n },
208
+ tenantId: t[0].send.tenantId ?? null
209
+ };
210
+ };
211
+ //#endregion
212
+ export { o as buildNotificationService, n as inAppChannel, i as inQuietHours, r as minuteOfDayInZone, a as quietHoursEnd };
package/dist/store.js ADDED
@@ -0,0 +1,303 @@
1
+ import { and as e, eq as t, generateId as n, isNull as r, lte as i } from "@voltro/database";
2
+ //#region src/store.ts
3
+ var a = () => {
4
+ let e = [], t = /* @__PURE__ */ new Map(), n = [], r = /* @__PURE__ */ new Map(), i = /* @__PURE__ */ new Map(), a = [], o = (e) => `${e.subjectId}|${e.category}|${e.channel}`, s = (e, t) => `${e}|${t}`;
5
+ return {
6
+ addInbox: async (t) => {
7
+ e.unshift({
8
+ ...t,
9
+ readAt: null,
10
+ archivedAt: null,
11
+ data: t.data ?? {},
12
+ tenantId: t.tenantId ?? null
13
+ });
14
+ },
15
+ listInbox: async (t, n) => {
16
+ let r = e.filter((e) => e.subjectId === t);
17
+ return n?.unreadOnly && (r = r.filter((e) => e.readAt === null)), n?.limit === void 0 ? r : r.slice(0, n.limit);
18
+ },
19
+ markRead: async (t, n) => {
20
+ let r = e.findIndex((e) => e.id === t && e.subjectId === n);
21
+ return r !== -1 && (e[r] = {
22
+ ...e[r],
23
+ readAt: (/* @__PURE__ */ new Date(0)).toISOString()
24
+ }, !0);
25
+ },
26
+ markUnread: async (t, n) => {
27
+ let r = e.findIndex((e) => e.id === t && e.subjectId === n);
28
+ return r !== -1 && (e[r] = {
29
+ ...e[r],
30
+ readAt: null
31
+ }, !0);
32
+ },
33
+ markAllRead: async (t) => {
34
+ let n = 0;
35
+ for (let r = 0; r < e.length; r++) {
36
+ let i = e[r];
37
+ i.subjectId === t && i.readAt === null && (e[r] = {
38
+ ...i,
39
+ readAt: (/* @__PURE__ */ new Date(0)).toISOString()
40
+ }, n++);
41
+ }
42
+ return n;
43
+ },
44
+ setArchived: async (t, n, r) => {
45
+ let i = e.findIndex((e) => e.id === t && e.subjectId === n);
46
+ return i !== -1 && (e[i] = {
47
+ ...e[i],
48
+ archivedAt: r ? (/* @__PURE__ */ new Date(0)).toISOString() : null
49
+ }, !0);
50
+ },
51
+ unreadCount: async (t) => e.filter((e) => e.subjectId === t && e.readAt === null).length,
52
+ getPreferences: async (e) => [...t.values()].filter((t) => t.subjectId === e),
53
+ setPreference: async (e) => {
54
+ t.set(o(e), e);
55
+ },
56
+ recordDelivery: async (e) => {
57
+ n.unshift(e);
58
+ },
59
+ listDeliveries: async (e) => e?.limit === void 0 ? [...n] : n.slice(0, e.limit),
60
+ markClicked: async (e) => {
61
+ let t = n.findIndex((t) => t.clickToken === e);
62
+ return t !== -1 && (n[t] = {
63
+ ...n[t],
64
+ clickedAt: (/* @__PURE__ */ new Date()).toISOString()
65
+ }, !0);
66
+ },
67
+ subscribeTopic: async (e) => {
68
+ r.set(s(e.topic, e.subjectId), e);
69
+ },
70
+ unsubscribeTopic: async (e, t) => {
71
+ r.delete(s(e, t));
72
+ },
73
+ listTopicSubscribers: async (e) => [...r.values()].filter((t) => t.topic === e),
74
+ getQuietHours: async (e) => i.get(e) ?? null,
75
+ setQuietHours: async (e) => {
76
+ i.set(e.subjectId, e);
77
+ },
78
+ clearQuietHours: async (e) => {
79
+ i.delete(e);
80
+ },
81
+ enqueueHeld: async (e) => {
82
+ a.push(e);
83
+ },
84
+ pendingDigest: async (e) => a.filter((t) => t.kind === "digest" && t.subjectId === e),
85
+ dueHeld: async (e) => a.filter((t) => t.flushAt <= e).sort((e, t) => e.flushAt < t.flushAt ? -1 : 1),
86
+ clearHeld: async (e) => {
87
+ let t = new Set(e);
88
+ for (let e = a.length - 1; e >= 0; e--) t.has(a[e].id) && a.splice(e, 1);
89
+ }
90
+ };
91
+ }, o = (e) => e instanceof Date ? e.toISOString() : typeof e == "string" ? e : "", s = (a) => {
92
+ let s = async (e, t, n, r) => await a.query({
93
+ table: e,
94
+ predicate: t,
95
+ order: n,
96
+ take: r,
97
+ skip: void 0,
98
+ projection: void 0
99
+ }), c = (e) => ({
100
+ id: String(e.id),
101
+ subjectId: String(e.subjectId),
102
+ category: String(e.category),
103
+ title: String(e.title),
104
+ body: String(e.body),
105
+ data: e.data ?? {},
106
+ readAt: e.readAt == null ? null : o(e.readAt),
107
+ archivedAt: e.archivedAt == null ? null : o(e.archivedAt),
108
+ createdAt: o(e.createdAt),
109
+ tenantId: e.tenantId ?? null
110
+ }), l = (e) => ({
111
+ subjectId: String(e.subjectId),
112
+ category: String(e.category),
113
+ channel: String(e.channel),
114
+ enabled: !!e.enabled
115
+ }), u = (e) => ({
116
+ id: String(e.id),
117
+ to: String(e.recipient),
118
+ category: String(e.category),
119
+ channel: String(e.channel),
120
+ status: e.status,
121
+ at: o(e.at),
122
+ ...e.error == null ? {} : { error: String(e.error) },
123
+ ...e.endpoint == null ? {} : { endpoint: String(e.endpoint) },
124
+ ...e.clickToken == null ? {} : { clickToken: String(e.clickToken) },
125
+ ...e.clickedAt == null ? {} : { clickedAt: o(e.clickedAt) }
126
+ }), d = (e) => ({
127
+ topic: String(e.topic),
128
+ subjectId: String(e.subjectId),
129
+ tenantId: e.tenantId ?? null
130
+ }), f = (e) => ({
131
+ subjectId: String(e.subjectId),
132
+ startMinute: Number(e.startMinute),
133
+ endMinute: Number(e.endMinute),
134
+ tz: String(e.tz ?? "UTC"),
135
+ policy: e.policy === "drop" ? "drop" : "hold"
136
+ }), p = (e) => ({
137
+ id: String(e.id),
138
+ kind: e.kind === "quiet" ? "quiet" : "digest",
139
+ subjectId: String(e.subjectId),
140
+ send: e.send ?? {},
141
+ flushAt: o(e.flushAt)
142
+ });
143
+ return {
144
+ addInbox: async (e) => {
145
+ await a.insert("_voltro_notification_inbox", {
146
+ id: e.id,
147
+ subjectId: e.subjectId,
148
+ category: e.category,
149
+ title: e.title,
150
+ body: e.body,
151
+ data: e.data ?? {},
152
+ readAt: null,
153
+ archivedAt: null,
154
+ createdAt: e.createdAt,
155
+ tenantId: e.tenantId ?? null
156
+ });
157
+ },
158
+ listInbox: async (n, i) => {
159
+ let a = i?.unreadOnly ? e(t("subjectId", n), r("readAt")) : t("subjectId", n);
160
+ return (await s("_voltro_notification_inbox", a, [{
161
+ column: "createdAt",
162
+ direction: "desc"
163
+ }], i?.limit)).map(c);
164
+ },
165
+ markRead: async (n, r) => (await s("_voltro_notification_inbox", e(t("id", n), t("subjectId", r)), [], 1))[0] ? (await a.update("_voltro_notification_inbox", n, { readAt: (/* @__PURE__ */ new Date()).toISOString() }), !0) : !1,
166
+ markUnread: async (n, r) => (await s("_voltro_notification_inbox", e(t("id", n), t("subjectId", r)), [], 1))[0] ? (await a.update("_voltro_notification_inbox", n, { readAt: null }), !0) : !1,
167
+ markAllRead: async (n) => {
168
+ let i = /* @__PURE__ */ new Date();
169
+ return a.updateMany("_voltro_notification_inbox", { readAt: i }, { where: e(t("subjectId", n), r("readAt")) });
170
+ },
171
+ setArchived: async (n, r, i) => (await s("_voltro_notification_inbox", e(t("id", n), t("subjectId", r)), [], 1))[0] ? (await a.update("_voltro_notification_inbox", n, { archivedAt: i ? (/* @__PURE__ */ new Date()).toISOString() : null }), !0) : !1,
172
+ unreadCount: async (n) => {
173
+ let i = await a.query({
174
+ table: "_voltro_notification_inbox",
175
+ predicate: e(t("subjectId", n), r("readAt")),
176
+ order: [],
177
+ take: void 0,
178
+ skip: void 0,
179
+ projection: void 0,
180
+ aggregations: [{
181
+ op: "count",
182
+ alias: "count"
183
+ }]
184
+ });
185
+ return Number(i[0]?.count ?? 0);
186
+ },
187
+ getPreferences: async (e) => (await s("_voltro_notification_preferences", t("subjectId", e), [], void 0)).map(l),
188
+ setPreference: async (e) => {
189
+ let t = n({
190
+ kind: "typeid",
191
+ prefix: "notifpref"
192
+ }, "_voltro_notification_preferences");
193
+ await a.upsert("_voltro_notification_preferences", {
194
+ id: t,
195
+ subjectId: e.subjectId,
196
+ category: e.category,
197
+ channel: e.channel,
198
+ enabled: e.enabled
199
+ }, {
200
+ conflictColumns: [
201
+ "subjectId",
202
+ "category",
203
+ "channel"
204
+ ],
205
+ update: ["enabled"]
206
+ });
207
+ },
208
+ recordDelivery: async (e) => {
209
+ await a.insert("_voltro_notification_deliveries", {
210
+ id: e.id,
211
+ recipient: e.to,
212
+ category: e.category,
213
+ channel: e.channel,
214
+ status: e.status,
215
+ error: e.error ?? null,
216
+ at: e.at,
217
+ endpoint: e.endpoint ?? null,
218
+ clickToken: e.clickToken ?? null,
219
+ clickedAt: e.clickedAt ?? null
220
+ });
221
+ },
222
+ markClicked: async (e) => {
223
+ let n = await s("_voltro_notification_deliveries", t("clickToken", e), [], 1);
224
+ return n[0] ? (await a.update("_voltro_notification_deliveries", String(n[0].id), { clickedAt: (/* @__PURE__ */ new Date()).toISOString() }), !0) : !1;
225
+ },
226
+ listDeliveries: async (e) => (await s("_voltro_notification_deliveries", void 0, [{
227
+ column: "at",
228
+ direction: "desc"
229
+ }], e?.limit)).map(u),
230
+ subscribeTopic: async (e) => {
231
+ let t = n({
232
+ kind: "typeid",
233
+ prefix: "notiftsub"
234
+ }, "_voltro_notification_topic_subscriptions");
235
+ await a.upsert("_voltro_notification_topic_subscriptions", {
236
+ id: t,
237
+ topic: e.topic,
238
+ subjectId: e.subjectId,
239
+ tenantId: e.tenantId ?? null
240
+ }, {
241
+ conflictColumns: ["topic", "subjectId"],
242
+ update: ["tenantId"]
243
+ });
244
+ },
245
+ unsubscribeTopic: async (n, r) => {
246
+ let i = await s("_voltro_notification_topic_subscriptions", e(t("topic", n), t("subjectId", r)), [], 1);
247
+ i[0] && await a.delete("_voltro_notification_topic_subscriptions", String(i[0].id));
248
+ },
249
+ listTopicSubscribers: async (e) => (await s("_voltro_notification_topic_subscriptions", t("topic", e), [], void 0)).map(d),
250
+ getQuietHours: async (e) => {
251
+ let n = await s("_voltro_notification_quiet_hours", t("subjectId", e), [], 1);
252
+ return n[0] ? f(n[0]) : null;
253
+ },
254
+ setQuietHours: async (e) => {
255
+ let t = n({
256
+ kind: "typeid",
257
+ prefix: "notifqh"
258
+ }, "_voltro_notification_quiet_hours");
259
+ await a.upsert("_voltro_notification_quiet_hours", {
260
+ id: t,
261
+ subjectId: e.subjectId,
262
+ startMinute: e.startMinute,
263
+ endMinute: e.endMinute,
264
+ tz: e.tz ?? "UTC",
265
+ policy: e.policy ?? "hold"
266
+ }, {
267
+ conflictColumns: ["subjectId"],
268
+ update: [
269
+ "startMinute",
270
+ "endMinute",
271
+ "tz",
272
+ "policy"
273
+ ]
274
+ });
275
+ },
276
+ clearQuietHours: async (e) => {
277
+ let n = await s("_voltro_notification_quiet_hours", t("subjectId", e), [], 1);
278
+ n[0] && await a.delete("_voltro_notification_quiet_hours", String(n[0].id));
279
+ },
280
+ enqueueHeld: async (e) => {
281
+ await a.insert("_voltro_notification_held", {
282
+ id: e.id,
283
+ kind: e.kind,
284
+ subjectId: e.subjectId,
285
+ send: e.send,
286
+ flushAt: e.flushAt
287
+ });
288
+ },
289
+ pendingDigest: async (n) => (await s("_voltro_notification_held", e(t("kind", "digest"), t("subjectId", n)), [{
290
+ column: "flushAt",
291
+ direction: "asc"
292
+ }], void 0)).map(p),
293
+ dueHeld: async (e) => (await s("_voltro_notification_held", i("flushAt", e), [{
294
+ column: "flushAt",
295
+ direction: "asc"
296
+ }], void 0)).map(p),
297
+ clearHeld: async (e) => {
298
+ for (let t of e) await a.delete("_voltro_notification_held", t);
299
+ }
300
+ };
301
+ };
302
+ //#endregion
303
+ export { s as dataStoreNotificationStore, a as memoryNotificationStore };