@terreno/comms 57.0.0-beta.1 → 57.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.
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { CommsApp, getCommsService } from "./commsApp";
4
4
  export { CommsService } from "./commsService";
5
5
  export { CommsMessage } from "./models/commsMessage";
6
6
  export { PushToken } from "./models/pushToken";
7
- export type { CommsMessageDocument, CommsMessageMethods, CommsMessageModel, CommsMessageSchema, CommsMessageStatics, LogSendParams, PushTokenDocument, PushTokenMethods, PushTokenModel, PushTokenPlatform, PushTokenSchema, PushTokenStatics, } from "./modelTypes";
7
+ export type { CommsMessageAttempt, CommsMessageDocument, CommsMessageMethods, CommsMessageModel, CommsMessageSchema, CommsMessageStatics, LogSendParams, PushTokenDocument, PushTokenMethods, PushTokenModel, PushTokenPlatform, PushTokenSchema, PushTokenStatics, } from "./modelTypes";
8
8
  export type { MessageTemplate, RenderTemplateOptions } from "./templates";
9
9
  export { renderTemplate } from "./templates";
10
- export type { CheckVerificationOptions, CommsChannel, CommsMessageStatus, CommsOptions, DeliveryEvent, MailMessage, MailProvider, PushMessage, PushProvider, SendPushToUserMessage, SendResult, SmsMessage, SmsProvider, StartVerificationOptions, VerificationProvider, VerificationResult, } from "./types";
10
+ export type { BeforeSendResult, CheckVerificationOptions, CommsChannel, CommsErrorClass, CommsHookContext, CommsHookMessage, CommsMessageStatus, CommsOptions, DeliveryEvent, MailMessage, MailProvider, OptOutEvent, PushMessage, PushProvider, SendPushToUserMessage, SendResult, SmsMessage, SmsProvider, StartVerificationOptions, VerificationProvider, VerificationResult, } from "./types";
@@ -1,33 +1,74 @@
1
1
  import type { FindExactlyOnePlugin, FindOneOrNonePlugin, HasUpsert } from "@terreno/api";
2
2
  import type mongoose from "mongoose";
3
- import type { CommsChannel, CommsMessageStatus } from "./types";
3
+ import type { CommsChannel, CommsErrorClass, CommsMessageStatus } from "./types";
4
4
  export type CommsMessageMethods = Record<never, never>;
5
+ export interface CommsMessageAttempt {
6
+ at: Date;
7
+ error?: string;
8
+ errorClass?: CommsErrorClass;
9
+ errorCode?: string;
10
+ provider: string;
11
+ providerMessageId?: string;
12
+ }
5
13
  export interface CommsMessageDocument extends mongoose.Document<mongoose.Types.ObjectId>, CommsMessageMethods {
14
+ attemptCount: number;
15
+ attempts: CommsMessageAttempt[];
6
16
  channel: CommsChannel;
7
17
  created: Date;
8
18
  deleted: boolean;
9
19
  error?: string;
20
+ errorClass?: CommsErrorClass;
21
+ errorCode?: string;
22
+ lastAttemptAt?: Date;
10
23
  metadata?: Record<string, unknown>;
24
+ payload?: unknown;
25
+ payloadExpiresAt?: Date;
11
26
  provider: string;
12
27
  providerMessageId?: string;
28
+ retriedById?: mongoose.Types.ObjectId;
29
+ retriedFromId?: mongoose.Types.ObjectId;
13
30
  status: CommsMessageStatus;
14
31
  subject?: string;
32
+ templateId?: string;
15
33
  to: string;
16
34
  updated: Date;
17
35
  userId?: mongoose.Types.ObjectId;
18
36
  }
19
37
  export interface LogSendParams {
38
+ attemptCount?: number;
39
+ attempts?: CommsMessageAttempt[];
20
40
  channel: CommsChannel;
21
41
  error?: string;
42
+ errorClass?: CommsErrorClass;
43
+ errorCode?: string;
44
+ lastAttemptAt?: Date;
22
45
  metadata?: Record<string, unknown>;
46
+ payload?: unknown;
47
+ payloadExpiresAt?: Date;
23
48
  provider: string;
24
49
  providerMessageId?: string;
50
+ retriedById?: mongoose.Types.ObjectId | string;
51
+ retriedFromId?: mongoose.Types.ObjectId | string;
25
52
  status: CommsMessageStatus;
26
53
  subject?: string;
54
+ templateId?: string;
27
55
  to: string;
28
56
  userId?: mongoose.Types.ObjectId | string;
29
57
  }
30
58
  export interface CommsMessageStatics extends FindExactlyOnePlugin<CommsMessageDocument>, FindOneOrNonePlugin<CommsMessageDocument> {
59
+ appendAttempt(params: {
60
+ error?: string;
61
+ errorClass?: CommsErrorClass;
62
+ errorCode?: string;
63
+ id: mongoose.Types.ObjectId | string;
64
+ metadata?: Record<string, unknown>;
65
+ payload?: unknown;
66
+ payloadExpiresAt?: Date;
67
+ providerMessageId?: string;
68
+ status: CommsMessageStatus;
69
+ attempt: CommsMessageAttempt;
70
+ }): Promise<CommsMessageDocument | null>;
71
+ clearExpiredPayloads(): Promise<number>;
31
72
  logSend(params: LogSendParams): Promise<CommsMessageDocument | null>;
32
73
  }
33
74
  export interface CommsMessageModel extends mongoose.Model<CommsMessageDocument>, CommsMessageStatics {
@@ -1,4 +1,15 @@
1
1
  "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -35,14 +46,81 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
46
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
47
  }
37
48
  };
49
+ var __read = (this && this.__read) || function (o, n) {
50
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
51
+ if (!m) return o;
52
+ var i = m.call(o), r, ar = [], e;
53
+ try {
54
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
55
+ }
56
+ catch (error) { e = { error: error }; }
57
+ finally {
58
+ try {
59
+ if (r && !r.done && (m = i["return"])) m.call(i);
60
+ }
61
+ finally { if (e) throw e.error; }
62
+ }
63
+ return ar;
64
+ };
65
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
66
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
67
+ if (ar || !(i in from)) {
68
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
69
+ ar[i] = from[i];
70
+ }
71
+ }
72
+ return to.concat(ar || Array.prototype.slice.call(from));
73
+ };
38
74
  var __importDefault = (this && this.__importDefault) || function (mod) {
39
75
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
76
  };
41
77
  Object.defineProperty(exports, "__esModule", { value: true });
42
78
  exports.CommsMessage = void 0;
43
79
  var api_1 = require("@terreno/api");
80
+ var luxon_1 = require("luxon");
44
81
  var mongoose_1 = __importDefault(require("mongoose"));
45
82
  var commsMessageSchema = new mongoose_1.default.Schema({
83
+ attemptCount: {
84
+ default: 0,
85
+ description: "Number of facade send attempts recorded on this row",
86
+ type: Number,
87
+ },
88
+ attempts: {
89
+ default: [],
90
+ description: "Per-attempt provider results including the inline retry",
91
+ type: [
92
+ {
93
+ _id: false,
94
+ at: {
95
+ description: "When this send attempt ran",
96
+ required: true,
97
+ type: Date,
98
+ },
99
+ error: {
100
+ description: "Provider error message for this attempt",
101
+ type: String,
102
+ },
103
+ errorClass: {
104
+ description: "Classified failure category for this attempt",
105
+ enum: ["config", "permanent", "transient"],
106
+ type: String,
107
+ },
108
+ errorCode: {
109
+ description: "Provider-native error code for this attempt",
110
+ type: String,
111
+ },
112
+ provider: {
113
+ description: "Provider identifier used for this attempt",
114
+ required: true,
115
+ type: String,
116
+ },
117
+ providerMessageId: {
118
+ description: "Provider-assigned identifier returned by this attempt",
119
+ type: String,
120
+ },
121
+ },
122
+ ],
123
+ },
46
124
  channel: {
47
125
  description: "Communication channel used for the send attempt",
48
126
  enum: ["mail", "push", "sms", "verification"],
@@ -53,10 +131,33 @@ var commsMessageSchema = new mongoose_1.default.Schema({
53
131
  description: "Provider error returned for a failed send attempt",
54
132
  type: String,
55
133
  },
134
+ errorClass: {
135
+ description: "Classified failure category used for retry eligibility",
136
+ enum: ["config", "permanent", "transient"],
137
+ type: String,
138
+ },
139
+ errorCode: {
140
+ description: "Provider-native error code for a failed send attempt",
141
+ index: true,
142
+ type: String,
143
+ },
144
+ lastAttemptAt: {
145
+ description: "Timestamp of the most recent send attempt",
146
+ type: Date,
147
+ },
56
148
  metadata: {
57
149
  description: "Additional metadata associated with the send attempt",
58
150
  type: mongoose_1.default.Schema.Types.Mixed,
59
151
  },
152
+ payload: {
153
+ description: "Redacted rendered message retained for admin retry",
154
+ type: mongoose_1.default.Schema.Types.Mixed,
155
+ },
156
+ payloadExpiresAt: {
157
+ description: "When the retained payload should be cleared",
158
+ index: true,
159
+ type: Date,
160
+ },
60
161
  provider: {
61
162
  description: "Identifier of the provider handling the send attempt",
62
163
  minlength: 1,
@@ -68,9 +169,19 @@ var commsMessageSchema = new mongoose_1.default.Schema({
68
169
  index: true,
69
170
  type: String,
70
171
  },
172
+ retriedById: {
173
+ description: "Admin-dashboard retry that was created from this row",
174
+ ref: "CommsMessage",
175
+ type: mongoose_1.default.Schema.Types.ObjectId,
176
+ },
177
+ retriedFromId: {
178
+ description: "Original CommsMessage this admin retry was created from",
179
+ ref: "CommsMessage",
180
+ type: mongoose_1.default.Schema.Types.ObjectId,
181
+ },
71
182
  status: {
72
183
  description: "Current delivery status of the communication",
73
- enum: ["bounced", "delivered", "failed", "sent"],
184
+ enum: ["bounced", "cancelled", "delivered", "failed", "sent"],
74
185
  required: true,
75
186
  type: String,
76
187
  },
@@ -78,6 +189,10 @@ var commsMessageSchema = new mongoose_1.default.Schema({
78
189
  description: "Mail subject when the communication channel is mail",
79
190
  type: String,
80
191
  },
192
+ templateId: {
193
+ description: "Provider or app template identifier used to render the message",
194
+ type: String,
195
+ },
81
196
  to: {
82
197
  description: "Recipient identifier for the communication",
83
198
  required: true,
@@ -90,20 +205,101 @@ var commsMessageSchema = new mongoose_1.default.Schema({
90
205
  },
91
206
  }, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
92
207
  commsMessageSchema.statics = {
208
+ appendAttempt: function (params) {
209
+ return __awaiter(this, void 0, void 0, function () {
210
+ var document, _a;
211
+ return __generator(this, function (_b) {
212
+ switch (_b.label) {
213
+ case 0:
214
+ _b.trys.push([0, 3, , 4]);
215
+ return [4 /*yield*/, this.findOneOrNone({ _id: params.id })];
216
+ case 1:
217
+ document = _b.sent();
218
+ if (!document) {
219
+ return [2 /*return*/, null];
220
+ }
221
+ document.attempts = __spreadArray(__spreadArray([], __read(document.attempts), false), [params.attempt], false);
222
+ document.attemptCount = document.attempts.length;
223
+ document.error = params.error;
224
+ document.errorClass = params.errorClass;
225
+ document.errorCode = params.errorCode;
226
+ document.lastAttemptAt = params.attempt.at;
227
+ document.providerMessageId = params.providerMessageId;
228
+ document.status = params.status;
229
+ if (params.metadata) {
230
+ document.metadata = __assign(__assign({}, document.metadata), params.metadata);
231
+ document.markModified("metadata");
232
+ }
233
+ if (params.payload !== undefined) {
234
+ document.payload = params.payload;
235
+ document.payloadExpiresAt = params.payloadExpiresAt;
236
+ }
237
+ return [4 /*yield*/, document.save()];
238
+ case 2:
239
+ _b.sent();
240
+ return [3 /*break*/, 4];
241
+ case 3:
242
+ _a = _b.sent();
243
+ api_1.logger.warn("[comms] Failed to append communication attempt");
244
+ return [2 /*return*/, null];
245
+ case 4: return [4 /*yield*/, this.clearExpiredPayloads()];
246
+ case 5:
247
+ _b.sent();
248
+ return [2 /*return*/, document];
249
+ }
250
+ });
251
+ });
252
+ },
253
+ clearExpiredPayloads: function () {
254
+ return __awaiter(this, void 0, void 0, function () {
255
+ var expired, result, error_1;
256
+ return __generator(this, function (_a) {
257
+ switch (_a.label) {
258
+ case 0:
259
+ _a.trys.push([0, 3, , 4]);
260
+ return [4 /*yield*/, this.find({
261
+ payload: { $exists: true },
262
+ payloadExpiresAt: { $lte: luxon_1.DateTime.utc().toJSDate() },
263
+ })
264
+ .select("_id")
265
+ .limit(50)];
266
+ case 1:
267
+ expired = _a.sent();
268
+ if (expired.length === 0) {
269
+ return [2 /*return*/, 0];
270
+ }
271
+ return [4 /*yield*/, this.updateMany({ _id: { $in: expired.map(function (row) { return row._id; }) } }, { $unset: { payload: 1, payloadExpiresAt: 1 } })];
272
+ case 2:
273
+ result = _a.sent();
274
+ return [2 /*return*/, result.modifiedCount];
275
+ case 3:
276
+ error_1 = _a.sent();
277
+ api_1.logger.warn("[comms] Failed to clear expired payloads: ".concat(String(error_1)));
278
+ return [2 /*return*/, 0];
279
+ case 4: return [2 /*return*/];
280
+ }
281
+ });
282
+ });
283
+ },
93
284
  logSend: function (params) {
94
285
  return __awaiter(this, void 0, void 0, function () {
95
- var _a;
286
+ var created, _a;
96
287
  return __generator(this, function (_b) {
97
288
  switch (_b.label) {
98
289
  case 0:
99
290
  _b.trys.push([0, 2, , 3]);
100
291
  return [4 /*yield*/, this.create(params)];
101
- case 1: return [2 /*return*/, _b.sent()];
292
+ case 1:
293
+ created = _b.sent();
294
+ return [3 /*break*/, 3];
102
295
  case 2:
103
296
  _a = _b.sent();
104
297
  api_1.logger.warn("[comms] Failed to record communication send");
105
298
  return [2 /*return*/, null];
106
- case 3: return [2 /*return*/];
299
+ case 3: return [4 /*yield*/, this.clearExpiredPayloads()];
300
+ case 4:
301
+ _b.sent();
302
+ return [2 /*return*/, created];
107
303
  }
108
304
  });
109
305
  });
package/dist/types.d.ts CHANGED
@@ -1,31 +1,31 @@
1
1
  import type mongoose from "mongoose";
2
+ export type CommsErrorClass = "config" | "permanent" | "transient";
2
3
  export interface SendResult {
3
4
  accepted: boolean;
4
5
  error?: string;
6
+ errorClass?: CommsErrorClass;
7
+ errorCode?: string;
5
8
  isPermanentFailure?: boolean;
9
+ metadata?: Record<string, unknown>;
6
10
  providerMessageId?: string;
7
11
  }
8
12
  export interface MailMessage {
13
+ dynamicTemplateData?: Record<string, unknown>;
9
14
  from?: string;
10
15
  html?: string;
11
16
  metadata?: Record<string, string>;
12
17
  replyTo?: string;
13
18
  subject: string;
19
+ templateId?: string;
14
20
  text?: string;
15
21
  to: string | string[];
16
22
  }
17
- export interface MailProvider {
18
- readonly id: string;
19
- sendMail(message: MailMessage): Promise<SendResult>;
20
- }
23
+ export type CommsChannel = "mail" | "push" | "sms" | "verification";
24
+ export type CommsMessageStatus = "bounced" | "cancelled" | "delivered" | "failed" | "sent";
21
25
  export interface SmsMessage {
22
26
  body: string;
23
27
  to: string;
24
28
  }
25
- export interface SmsProvider {
26
- readonly id: string;
27
- sendSms(message: SmsMessage): Promise<SendResult>;
28
- }
29
29
  export interface PushMessage {
30
30
  badge?: number;
31
31
  body: string;
@@ -34,14 +34,36 @@ export interface PushMessage {
34
34
  title: string;
35
35
  tokens: string[];
36
36
  }
37
- export interface PushProvider {
38
- readonly id: string;
39
- sendPush(message: PushMessage): Promise<SendResult[]>;
40
- }
41
37
  export interface StartVerificationOptions {
42
38
  channel: "email" | "sms";
43
39
  to: string;
44
40
  }
41
+ export type CommsHookMessage = MailMessage | PushMessage | SmsMessage | StartVerificationOptions;
42
+ export interface CommsHookContext {
43
+ attempt: number;
44
+ channel: CommsChannel;
45
+ isRetry: boolean;
46
+ message: CommsHookMessage;
47
+ messageId?: string;
48
+ provider: string;
49
+ userId?: string;
50
+ }
51
+ export interface BeforeSendResult {
52
+ cancel?: boolean;
53
+ message?: CommsHookMessage;
54
+ }
55
+ export interface MailProvider {
56
+ readonly id: string;
57
+ sendMail(message: MailMessage): Promise<SendResult>;
58
+ }
59
+ export interface SmsProvider {
60
+ readonly id: string;
61
+ sendSms(message: SmsMessage): Promise<SendResult>;
62
+ }
63
+ export interface PushProvider {
64
+ readonly id: string;
65
+ sendPush(message: PushMessage): Promise<SendResult[]>;
66
+ }
45
67
  export interface CheckVerificationOptions {
46
68
  code: string;
47
69
  to: string;
@@ -57,19 +79,33 @@ export interface VerificationProvider {
57
79
  }
58
80
  export interface DeliveryEvent {
59
81
  channel: "mail" | "push" | "sms";
82
+ errorClass?: CommsErrorClass;
83
+ errorCode?: string;
60
84
  providerMessageId: string;
61
85
  raw?: unknown;
62
86
  status: "bounced" | "delivered" | "failed" | "opened";
63
87
  }
64
- export type CommsChannel = "mail" | "push" | "sms" | "verification";
65
- export type CommsMessageStatus = "bounced" | "delivered" | "failed" | "sent";
88
+ export interface OptOutEvent {
89
+ channel: "mail" | "sms";
90
+ provider: string;
91
+ raw?: unknown;
92
+ reason: string;
93
+ to: string;
94
+ }
66
95
  export interface CommsOptions {
96
+ beforeSend?: (context: CommsHookContext) => Promise<BeforeSendResult | undefined>;
67
97
  defaultFrom?: string;
68
98
  logMessages?: boolean;
69
99
  mail?: MailProvider;
70
100
  onDeliveryEvent?: (event: DeliveryEvent) => Promise<void>;
101
+ onError?: (context: CommsHookContext, result: SendResult) => Promise<void>;
102
+ onOptOut?: (event: OptOutEvent) => Promise<void>;
103
+ onRetry?: (context: CommsHookContext, result: SendResult) => Promise<void>;
104
+ onSend?: (context: CommsHookContext, result: SendResult) => Promise<void>;
71
105
  push?: PushProvider;
106
+ redactPayload?: (context: CommsHookContext, payload: unknown) => unknown;
72
107
  redactRecipients?: boolean;
108
+ retainPayloadDays?: number;
73
109
  sms?: SmsProvider;
74
110
  verification?: VerificationProvider;
75
111
  }
package/package.json CHANGED
@@ -4,13 +4,13 @@
4
4
  "url": "https://github.com/FlourishHealth/terreno/issues"
5
5
  },
6
6
  "dependencies": {
7
- "@terreno/api": "57.0.0-beta.1",
7
+ "@terreno/api": "57.1.0",
8
8
  "luxon": "^3.7.2"
9
9
  },
10
10
  "description": "Pluggable communications providers for Terreno backends",
11
11
  "devDependencies": {
12
12
  "@biomejs/biome": "^2.3.6",
13
- "@terreno/test": "57.0.0-beta.1",
13
+ "@terreno/test": "57.1.0",
14
14
  "@types/bun": "^1.3.8",
15
15
  "@types/express": "^5.0.6",
16
16
  "@types/luxon": "^3.7.1",
@@ -19,6 +19,16 @@
19
19
  "supertest": "^7.2.2",
20
20
  "typescript": "~6.0.3"
21
21
  },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ },
27
+ "./adapters/sendgrid": {
28
+ "types": "./dist/adapters/sendgrid.d.ts",
29
+ "default": "./dist/adapters/sendgrid.js"
30
+ }
31
+ },
22
32
  "homepage": "https://github.com/FlourishHealth/terreno#readme",
23
33
  "keywords": [
24
34
  "communications",
@@ -31,8 +41,14 @@
31
41
  "main": "dist/index.js",
32
42
  "name": "@terreno/comms",
33
43
  "peerDependencies": {
44
+ "@sendgrid/mail": "^8.0.0",
34
45
  "mongoose": "^8.0.0 || ^9.0.0"
35
46
  },
47
+ "peerDependenciesMeta": {
48
+ "@sendgrid/mail": {
49
+ "optional": true
50
+ }
51
+ },
36
52
  "publishConfig": {
37
53
  "access": "public"
38
54
  },
@@ -47,9 +63,10 @@
47
63
  "lint": "biome check ./src",
48
64
  "lint:fix": "biome check --write ./src",
49
65
  "test": "bun test",
66
+ "test:agent": "AGENT=1 bun test --only-failures",
50
67
  "test:ci": "bun test",
51
68
  "test:coverage": "bun run ../scripts/check-coverage.ts"
52
69
  },
53
70
  "types": "dist/index.d.ts",
54
- "version": "57.0.0-beta.1"
71
+ "version": "57.1.0"
55
72
  }