@terreno/comms 57.4.0 → 57.6.1

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.
@@ -1,294 +1,146 @@
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
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
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
- };
74
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
75
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
76
4
  };
77
5
  Object.defineProperty(exports, "__esModule", { value: true });
78
6
  exports.CommsService = void 0;
79
- var api_1 = require("@terreno/api");
80
- var luxon_1 = require("luxon");
81
- var mongoose_1 = __importDefault(require("mongoose"));
82
- var console_1 = require("./adapters/console");
83
- var commsRetry_1 = require("./commsRetry");
84
- var commsMessage_1 = require("./models/commsMessage");
85
- var pushToken_1 = require("./models/pushToken");
86
- var CHANNEL_NOT_CONFIGURED_TITLE = "Comms channel not configured";
87
- var REDACTED_RECIPIENT = "[redacted]";
88
- var DEFAULT_RETAIN_PAYLOAD_DAYS = 30;
89
- var CANCELLED_ERROR = "Cancelled by beforeSend";
90
- var HOOK_THREW = "hook-threw";
91
- var throwUnconfiguredChannel = function () {
7
+ const api_1 = require("@terreno/api");
8
+ const luxon_1 = require("luxon");
9
+ const mongoose_1 = __importDefault(require("mongoose"));
10
+ const console_1 = require("./adapters/console");
11
+ const commsRetry_1 = require("./commsRetry");
12
+ const commsMessage_1 = require("./models/commsMessage");
13
+ const pushToken_1 = require("./models/pushToken");
14
+ const CHANNEL_NOT_CONFIGURED_TITLE = "Comms channel not configured";
15
+ const REDACTED_RECIPIENT = "[redacted]";
16
+ const DEFAULT_RETAIN_PAYLOAD_DAYS = 30;
17
+ const CANCELLED_ERROR = "Cancelled by beforeSend";
18
+ const HOOK_THREW = "hook-threw";
19
+ const throwUnconfiguredChannel = () => {
92
20
  throw new api_1.APIError({ status: 501, title: CHANNEL_NOT_CONFIGURED_TITLE });
93
21
  };
94
- var isProduction = function () { return process.env.NODE_ENV === "production"; };
95
- var providerThrowResult = function (error) { return ({
22
+ const isProduction = () => process.env.NODE_ENV === "production";
23
+ const providerThrowResult = (error) => ({
96
24
  accepted: false,
97
25
  error: error instanceof Error ? error.message : "Provider send failed",
98
26
  errorClass: "transient",
99
27
  errorCode: "provider-throw",
100
- }); };
101
- var isTransientFailure = function (result) {
102
- return !result.accepted && result.errorClass === "transient";
103
- };
104
- var isPermanentPushFailure = function (result) {
105
- return result.isPermanentFailure === true || result.errorClass === "permanent";
106
- };
107
- var CommsService = /** @class */ (function () {
108
- function CommsService(options) {
109
- this.consoleMail = new console_1.ConsoleMailProvider();
110
- this.consolePush = new console_1.ConsolePushProvider();
111
- this.consoleSms = new console_1.ConsoleSmsProvider();
112
- this.consoleVerification = new console_1.ConsoleVerificationProvider();
113
- this.options = options !== null && options !== void 0 ? options : {};
28
+ });
29
+ const isTransientFailure = (result) => !result.accepted && result.errorClass === "transient";
30
+ const isPermanentPushFailure = (result) => result.isPermanentFailure === true || result.errorClass === "permanent";
31
+ class CommsService {
32
+ options;
33
+ consoleMail = new console_1.ConsoleMailProvider();
34
+ consolePush = new console_1.ConsolePushProvider();
35
+ consoleSms = new console_1.ConsoleSmsProvider();
36
+ consoleVerification = new console_1.ConsoleVerificationProvider();
37
+ constructor(options) {
38
+ this.options = options ?? {};
114
39
  }
115
- CommsService.prototype.recordDeliveryEvent = function (event) {
116
- return __awaiter(this, void 0, void 0, function () {
117
- var onDeliveryEvent, row, error_1;
118
- return __generator(this, function (_a) {
119
- switch (_a.label) {
120
- case 0:
121
- onDeliveryEvent = this.options.onDeliveryEvent;
122
- return [4 /*yield*/, this.invokeHook(onDeliveryEvent ? function () { return onDeliveryEvent(event); } : undefined, "onDeliveryEvent")];
123
- case 1:
124
- _a.sent();
125
- if (this.options.logMessages === false || !event.providerMessageId) {
126
- return [2 /*return*/];
127
- }
128
- _a.label = 2;
129
- case 2:
130
- _a.trys.push([2, 5, , 6]);
131
- return [4 /*yield*/, commsMessage_1.CommsMessage.findOneOrNone({ providerMessageId: event.providerMessageId })];
132
- case 3:
133
- row = _a.sent();
134
- if (!row) {
135
- api_1.logger.warn("[comms] No CommsMessage for delivery event ".concat(event.providerMessageId));
136
- return [2 /*return*/];
137
- }
138
- if (event.status === "opened") {
139
- return [2 /*return*/];
140
- }
141
- row.status = event.status;
142
- if (event.errorClass) {
143
- row.errorClass = event.errorClass;
144
- }
145
- if (event.errorCode) {
146
- row.errorCode = event.errorCode;
147
- }
148
- return [4 /*yield*/, row.save()];
149
- case 4:
150
- _a.sent();
151
- return [3 /*break*/, 6];
152
- case 5:
153
- error_1 = _a.sent();
154
- api_1.logger.warn("[comms] Failed to apply delivery event: ".concat(String(error_1)));
155
- throw error_1;
156
- case 6: return [2 /*return*/];
157
- }
158
- });
159
- });
160
- };
161
- CommsService.prototype.recordOptOut = function (event) {
162
- return __awaiter(this, void 0, void 0, function () {
163
- var onOptOut;
164
- return __generator(this, function (_a) {
165
- switch (_a.label) {
166
- case 0:
167
- onOptOut = this.options.onOptOut;
168
- return [4 /*yield*/, this.invokeHook(onOptOut ? function () { return onOptOut(event); } : undefined, "onOptOut")];
169
- case 1:
170
- _a.sent();
171
- return [2 /*return*/];
172
- }
173
- });
174
- });
175
- };
176
- CommsService.prototype.deactivatePushToken = function (token) {
177
- return __awaiter(this, void 0, void 0, function () {
178
- var tokenDoc, error_2;
179
- return __generator(this, function (_a) {
180
- switch (_a.label) {
181
- case 0:
182
- _a.trys.push([0, 3, , 4]);
183
- return [4 /*yield*/, pushToken_1.PushToken.findOneOrNone({ token: token })];
184
- case 1:
185
- tokenDoc = _a.sent();
186
- if (!tokenDoc || tokenDoc.active === false) {
187
- return [2 /*return*/];
188
- }
189
- tokenDoc.active = false;
190
- return [4 /*yield*/, tokenDoc.save()];
191
- case 2:
192
- _a.sent();
193
- return [3 /*break*/, 4];
194
- case 3:
195
- error_2 = _a.sent();
196
- api_1.logger.warn("[comms] Failed to deactivate push token: ".concat(String(error_2)));
197
- return [3 /*break*/, 4];
198
- case 4: return [2 /*return*/];
199
- }
200
- });
201
- });
202
- };
203
- CommsService.prototype.clearExpiredPayloads = function () {
204
- return __awaiter(this, void 0, void 0, function () {
205
- return __generator(this, function (_a) {
206
- return [2 /*return*/, commsMessage_1.CommsMessage.clearExpiredPayloads()];
207
- });
208
- });
209
- };
210
- CommsService.prototype.recipientForLog = function (recipient) {
40
+ async recordDeliveryEvent(event) {
41
+ const onDeliveryEvent = this.options.onDeliveryEvent;
42
+ await this.invokeHook(onDeliveryEvent ? () => onDeliveryEvent(event) : undefined, "onDeliveryEvent");
43
+ if (this.options.logMessages === false || !event.providerMessageId) {
44
+ return;
45
+ }
46
+ try {
47
+ const row = await commsMessage_1.CommsMessage.findOneOrNone({ providerMessageId: event.providerMessageId });
48
+ if (!row) {
49
+ api_1.logger.warn(`[comms] No CommsMessage for delivery event ${event.providerMessageId}`);
50
+ return;
51
+ }
52
+ if (event.status === "opened") {
53
+ return;
54
+ }
55
+ row.status = event.status;
56
+ if (event.errorClass) {
57
+ row.errorClass = event.errorClass;
58
+ }
59
+ if (event.errorCode) {
60
+ row.errorCode = event.errorCode;
61
+ }
62
+ await row.save();
63
+ }
64
+ catch (error) {
65
+ api_1.logger.warn(`[comms] Failed to apply delivery event: ${String(error)}`);
66
+ throw error;
67
+ }
68
+ }
69
+ async recordOptOut(event) {
70
+ const onOptOut = this.options.onOptOut;
71
+ await this.invokeHook(onOptOut ? () => onOptOut(event) : undefined, "onOptOut");
72
+ }
73
+ async deactivatePushToken(token) {
74
+ try {
75
+ const tokenDoc = await pushToken_1.PushToken.findOneOrNone({ token });
76
+ if (!tokenDoc || tokenDoc.active === false) {
77
+ return;
78
+ }
79
+ tokenDoc.active = false;
80
+ await tokenDoc.save();
81
+ }
82
+ catch (error) {
83
+ api_1.logger.warn(`[comms] Failed to deactivate push token: ${String(error)}`);
84
+ }
85
+ }
86
+ async clearExpiredPayloads() {
87
+ return commsMessage_1.CommsMessage.clearExpiredPayloads();
88
+ }
89
+ recipientForLog(recipient) {
211
90
  if (this.options.redactRecipients !== false) {
212
91
  return REDACTED_RECIPIENT;
213
92
  }
214
93
  return Array.isArray(recipient) ? recipient.join(",") : recipient;
215
- };
216
- CommsService.prototype.retainPayloadDays = function () {
217
- var _a;
218
- return (_a = this.options.retainPayloadDays) !== null && _a !== void 0 ? _a : DEFAULT_RETAIN_PAYLOAD_DAYS;
219
- };
220
- CommsService.prototype.invokeHook = function (hook, label) {
221
- return __awaiter(this, void 0, void 0, function () {
222
- var error_3, message;
223
- return __generator(this, function (_a) {
224
- switch (_a.label) {
225
- case 0:
226
- if (!hook) {
227
- return [2 /*return*/, undefined];
228
- }
229
- _a.label = 1;
230
- case 1:
231
- _a.trys.push([1, 3, , 4]);
232
- return [4 /*yield*/, hook()];
233
- case 2:
234
- _a.sent();
235
- return [2 /*return*/, undefined];
236
- case 3:
237
- error_3 = _a.sent();
238
- message = "[comms] ".concat(label, " hook failed: ").concat(String(error_3));
239
- api_1.logger.error(message);
240
- return [2 /*return*/, HOOK_THREW];
241
- case 4: return [2 /*return*/];
242
- }
243
- });
244
- });
245
- };
246
- CommsService.prototype.appendHookError = function (hookErrors, label, error) {
247
- var _a;
94
+ }
95
+ retainPayloadDays() {
96
+ return this.options.retainPayloadDays ?? DEFAULT_RETAIN_PAYLOAD_DAYS;
97
+ }
98
+ async invokeHook(hook, label) {
99
+ if (!hook) {
100
+ return undefined;
101
+ }
102
+ try {
103
+ await hook();
104
+ return undefined;
105
+ }
106
+ catch (error) {
107
+ const message = `[comms] ${label} hook failed: ${String(error)}`;
108
+ api_1.logger.error(message);
109
+ return HOOK_THREW;
110
+ }
111
+ }
112
+ appendHookError(hookErrors, label, error) {
248
113
  if (!error) {
249
114
  return;
250
115
  }
251
- var existing = (_a = hookErrors[label]) !== null && _a !== void 0 ? _a : [];
116
+ const existing = hookErrors[label] ?? [];
252
117
  existing.push(error);
253
118
  hookErrors[label] = existing;
254
- };
255
- CommsService.prototype.applyBeforeSend = function (context, hookErrors) {
256
- return __awaiter(this, void 0, void 0, function () {
257
- var beforeSend, result, error_4;
258
- var _a;
259
- return __generator(this, function (_b) {
260
- switch (_b.label) {
261
- case 0:
262
- beforeSend = this.options.beforeSend;
263
- if (!beforeSend) {
264
- return [2 /*return*/, { cancel: false, message: context.message }];
265
- }
266
- _b.label = 1;
267
- case 1:
268
- _b.trys.push([1, 3, , 4]);
269
- return [4 /*yield*/, beforeSend(context)];
270
- case 2:
271
- result = _b.sent();
272
- if (!result) {
273
- return [2 /*return*/, { cancel: false, message: context.message }];
274
- }
275
- return [2 /*return*/, {
276
- cancel: result.cancel === true,
277
- message: (_a = result.message) !== null && _a !== void 0 ? _a : context.message,
278
- }];
279
- case 3:
280
- error_4 = _b.sent();
281
- this.appendHookError(hookErrors, "beforeSend", HOOK_THREW);
282
- api_1.logger.error("[comms] beforeSend hook failed: ".concat(String(error_4)));
283
- return [2 /*return*/, { cancel: false, message: context.message }];
284
- case 4: return [2 /*return*/];
285
- }
286
- });
287
- });
288
- };
289
- CommsService.prototype.defaultPayload = function (message, channel) {
119
+ }
120
+ async applyBeforeSend(context, hookErrors) {
121
+ const beforeSend = this.options.beforeSend;
122
+ if (!beforeSend) {
123
+ return { cancel: false, message: context.message };
124
+ }
125
+ try {
126
+ const result = await beforeSend(context);
127
+ if (!result) {
128
+ return { cancel: false, message: context.message };
129
+ }
130
+ return {
131
+ cancel: result.cancel === true,
132
+ message: result.message ?? context.message,
133
+ };
134
+ }
135
+ catch (error) {
136
+ this.appendHookError(hookErrors, "beforeSend", HOOK_THREW);
137
+ api_1.logger.error(`[comms] beforeSend hook failed: ${String(error)}`);
138
+ return { cancel: false, message: context.message };
139
+ }
140
+ }
141
+ defaultPayload(message, channel) {
290
142
  if (channel === "mail") {
291
- var mail = message;
143
+ const mail = message;
292
144
  return {
293
145
  dynamicTemplateData: mail.dynamicTemplateData,
294
146
  from: mail.from,
@@ -301,11 +153,11 @@ var CommsService = /** @class */ (function () {
301
153
  };
302
154
  }
303
155
  if (channel === "sms") {
304
- var sms = message;
156
+ const sms = message;
305
157
  return { body: sms.body, to: sms.to };
306
158
  }
307
159
  if (channel === "push") {
308
- var push = message;
160
+ const push = message;
309
161
  return {
310
162
  badge: push.badge,
311
163
  body: push.body,
@@ -315,13 +167,13 @@ var CommsService = /** @class */ (function () {
315
167
  };
316
168
  }
317
169
  return { channel: message.channel };
318
- };
319
- CommsService.prototype.resolvePayload = function (context, hookErrors) {
170
+ }
171
+ resolvePayload(context, hookErrors) {
320
172
  if (this.retainPayloadDays() <= 0) {
321
173
  return undefined;
322
174
  }
323
- var payload = this.defaultPayload(context.message, context.channel);
324
- var redactPayload = this.options.redactPayload;
175
+ const payload = this.defaultPayload(context.message, context.channel);
176
+ const redactPayload = this.options.redactPayload;
325
177
  if (!redactPayload) {
326
178
  return payload;
327
179
  }
@@ -330,325 +182,210 @@ var CommsService = /** @class */ (function () {
330
182
  }
331
183
  catch (error) {
332
184
  this.appendHookError(hookErrors, "redactPayload", HOOK_THREW);
333
- api_1.logger.error("[comms] redactPayload hook failed: ".concat(String(error)));
185
+ api_1.logger.error(`[comms] redactPayload hook failed: ${String(error)}`);
334
186
  return undefined;
335
187
  }
336
- };
337
- CommsService.prototype.payloadExpiresAt = function () {
338
- var days = this.retainPayloadDays();
188
+ }
189
+ payloadExpiresAt() {
190
+ const days = this.retainPayloadDays();
339
191
  if (days <= 0) {
340
192
  return undefined;
341
193
  }
342
- return luxon_1.DateTime.utc().plus({ days: days }).toJSDate();
343
- };
344
- CommsService.prototype.cloneHookErrors = function (hookErrors) {
345
- return Object.fromEntries(Object.entries(hookErrors).map(function (_a) {
346
- var _b = __read(_a, 2), key = _b[0], values = _b[1];
347
- return [key, __spreadArray([], __read(values), false)];
348
- }));
349
- };
350
- CommsService.prototype.cloneContext = function (context, overrides) {
351
- if (overrides === void 0) { overrides = {}; }
352
- return __assign(__assign({}, context), overrides);
353
- };
354
- CommsService.prototype.resultsByToken = function (tokens, results) {
355
- var missingResult = {
194
+ return luxon_1.DateTime.utc().plus({ days }).toJSDate();
195
+ }
196
+ cloneHookErrors(hookErrors) {
197
+ return Object.fromEntries(Object.entries(hookErrors).map(([key, values]) => [key, [...values]]));
198
+ }
199
+ cloneContext(context, overrides = {}) {
200
+ return { ...context, ...overrides };
201
+ }
202
+ resultsByToken(tokens, results) {
203
+ const missingResult = {
356
204
  accepted: false,
357
205
  error: "Provider returned no result for token",
358
206
  };
359
- return new Map(tokens.map(function (token, index) { var _a; return [token, (_a = results[index]) !== null && _a !== void 0 ? _a : missingResult]; }));
360
- };
361
- CommsService.prototype.attemptFromResult = function (provider, result) {
207
+ return new Map(tokens.map((token, index) => [token, results[index] ?? missingResult]));
208
+ }
209
+ attemptFromResult(provider, result) {
362
210
  return {
363
211
  at: luxon_1.DateTime.utc().toJSDate(),
364
212
  error: result.error,
365
213
  errorClass: result.errorClass,
366
214
  errorCode: result.errorCode,
367
- provider: provider,
215
+ provider,
368
216
  providerMessageId: result.providerMessageId,
369
217
  };
370
- };
371
- CommsService.prototype.logResult = function (_a) {
372
- return __awaiter(this, arguments, void 0, function (_b) {
373
- var payload, lastAttempt, mergedMetadata, logged;
374
- var attempts = _b.attempts, channel = _b.channel, context = _b.context, hookErrors = _b.hookErrors, metadata = _b.metadata, omitPayload = _b.omitPayload, provider = _b.provider, result = _b.result, retriedFromId = _b.retriedFromId, status = _b.status, subject = _b.subject, templateId = _b.templateId, to = _b.to, userId = _b.userId;
375
- return __generator(this, function (_c) {
376
- switch (_c.label) {
377
- case 0:
378
- if (this.options.logMessages === false) {
379
- return [2 /*return*/, null];
380
- }
381
- payload = omitPayload ? undefined : this.resolvePayload(context, hookErrors);
382
- lastAttempt = attempts[attempts.length - 1];
383
- mergedMetadata = __assign(__assign(__assign({}, result.metadata), metadata), (Object.keys(hookErrors).length > 0 ? { hookErrors: hookErrors } : {}));
384
- return [4 /*yield*/, commsMessage_1.CommsMessage.logSend({
385
- attemptCount: attempts.length,
386
- attempts: attempts,
387
- channel: channel,
388
- error: result.error,
389
- errorClass: result.errorClass,
390
- errorCode: result.errorCode,
391
- lastAttemptAt: lastAttempt === null || lastAttempt === void 0 ? void 0 : lastAttempt.at,
392
- metadata: mergedMetadata,
393
- payload: payload,
394
- payloadExpiresAt: payload === undefined ? undefined : this.payloadExpiresAt(),
395
- provider: provider,
396
- providerMessageId: result.providerMessageId,
397
- retriedFromId: retriedFromId,
398
- status: status,
399
- subject: subject,
400
- templateId: templateId,
401
- to: this.recipientForLog(to),
402
- userId: userId,
403
- })];
404
- case 1:
405
- logged = _c.sent();
406
- if (logged) {
407
- context.messageId = String(logged._id);
408
- }
409
- return [2 /*return*/, logged];
410
- }
411
- });
412
- });
413
- };
414
- CommsService.prototype.patchHookErrors = function (logged, hookErrors) {
415
- return __awaiter(this, void 0, void 0, function () {
416
- return __generator(this, function (_a) {
417
- switch (_a.label) {
418
- case 0:
419
- if (!logged || Object.keys(hookErrors).length === 0) {
420
- return [2 /*return*/];
421
- }
422
- logged.metadata = __assign(__assign({}, logged.metadata), { hookErrors: hookErrors });
423
- logged.markModified("metadata");
424
- return [4 /*yield*/, logged.save().catch(function (error) {
425
- api_1.logger.warn("[comms] Failed to record hook errors: ".concat(String(error)));
426
- })];
427
- case 1:
428
- _a.sent();
429
- return [2 /*return*/];
430
- }
431
- });
432
- });
433
- };
434
- CommsService.prototype.notifyOutcomeHooks = function (context, result, hookErrors) {
435
- return __awaiter(this, void 0, void 0, function () {
436
- var onSend_1, _a, _b, onError, _c, _d;
437
- return __generator(this, function (_e) {
438
- switch (_e.label) {
439
- case 0:
440
- if (!result.accepted) return [3 /*break*/, 2];
441
- onSend_1 = this.options.onSend;
442
- _a = this.appendHookError;
443
- _b = [hookErrors,
444
- "onSend"];
445
- return [4 /*yield*/, this.invokeHook(onSend_1 ? function () { return onSend_1(context, result); } : undefined, "onSend")];
446
- case 1:
447
- _a.apply(this, _b.concat([_e.sent()]));
448
- return [2 /*return*/];
449
- case 2:
450
- onError = this.options.onError;
451
- _c = this.appendHookError;
452
- _d = [hookErrors,
453
- "onError"];
454
- return [4 /*yield*/, this.invokeHook(onError ? function () { return onError(context, result); } : undefined, "onError")];
455
- case 3:
456
- _c.apply(this, _d.concat([_e.sent()]));
457
- return [2 /*return*/];
458
- }
459
- });
218
+ }
219
+ async logResult({ attempts, channel, context, hookErrors, metadata, omitPayload, provider, result, retriedFromId, status, subject, templateId, to, userId, }) {
220
+ if (this.options.logMessages === false) {
221
+ return null;
222
+ }
223
+ const payload = omitPayload ? undefined : this.resolvePayload(context, hookErrors);
224
+ const lastAttempt = attempts[attempts.length - 1];
225
+ const mergedMetadata = {
226
+ ...result.metadata,
227
+ ...metadata,
228
+ ...(Object.keys(hookErrors).length > 0 ? { hookErrors } : {}),
229
+ };
230
+ const logged = await commsMessage_1.CommsMessage.logSend({
231
+ attemptCount: attempts.length,
232
+ attempts,
233
+ channel,
234
+ error: result.error,
235
+ errorClass: result.errorClass,
236
+ errorCode: result.errorCode,
237
+ lastAttemptAt: lastAttempt?.at,
238
+ metadata: mergedMetadata,
239
+ payload,
240
+ payloadExpiresAt: payload === undefined ? undefined : this.payloadExpiresAt(),
241
+ provider,
242
+ providerMessageId: result.providerMessageId,
243
+ retriedFromId,
244
+ status,
245
+ subject,
246
+ templateId,
247
+ to: this.recipientForLog(to),
248
+ userId,
460
249
  });
461
- };
462
- CommsService.prototype.retryOnce = function (context, firstResult, retry, hookErrors) {
463
- return __awaiter(this, void 0, void 0, function () {
464
- var onRetry, _a, _b, secondResult;
465
- return __generator(this, function (_c) {
466
- switch (_c.label) {
467
- case 0:
468
- if (!isTransientFailure(firstResult)) {
469
- return [2 /*return*/, { attempts: [firstResult], result: firstResult }];
470
- }
471
- context.isRetry = true;
472
- context.attempt = 2;
473
- onRetry = this.options.onRetry;
474
- _a = this.appendHookError;
475
- _b = [hookErrors,
476
- "onRetry"];
477
- return [4 /*yield*/, this.invokeHook(onRetry ? function () { return onRetry(context, firstResult); } : undefined, "onRetry")];
478
- case 1:
479
- _a.apply(this, _b.concat([_c.sent()]));
480
- return [4 /*yield*/, retry()];
481
- case 2:
482
- secondResult = _c.sent();
483
- return [2 /*return*/, { attempts: [firstResult, secondResult], result: secondResult }];
484
- }
485
- });
250
+ if (logged) {
251
+ context.messageId = String(logged._id);
252
+ }
253
+ return logged;
254
+ }
255
+ async patchHookErrors(logged, hookErrors) {
256
+ if (!logged || Object.keys(hookErrors).length === 0) {
257
+ return;
258
+ }
259
+ logged.metadata = { ...logged.metadata, hookErrors };
260
+ logged.markModified("metadata");
261
+ await logged.save().catch((error) => {
262
+ api_1.logger.warn(`[comms] Failed to record hook errors: ${String(error)}`);
486
263
  });
487
- };
488
- CommsService.prototype.persistRetry = function (logged, context, hookErrors, provider, result) {
489
- return __awaiter(this, void 0, void 0, function () {
490
- var payload;
491
- return __generator(this, function (_a) {
492
- if (!logged) {
493
- return [2 /*return*/, null];
494
- }
495
- payload = this.resolvePayload(context, hookErrors);
496
- return [2 /*return*/, commsMessage_1.CommsMessage.appendAttempt({
497
- attempt: this.attemptFromResult(provider, result),
498
- error: result.error,
499
- errorClass: result.errorClass,
500
- errorCode: result.errorCode,
501
- id: logged._id,
502
- metadata: Object.keys(hookErrors).length > 0 ? { hookErrors: hookErrors } : undefined,
503
- payload: payload,
504
- payloadExpiresAt: payload === undefined ? undefined : this.payloadExpiresAt(),
505
- providerMessageId: result.providerMessageId,
506
- status: result.accepted ? "sent" : "failed",
507
- })];
508
- });
264
+ }
265
+ async notifyOutcomeHooks(context, result, hookErrors) {
266
+ if (result.accepted) {
267
+ const onSend = this.options.onSend;
268
+ this.appendHookError(hookErrors, "onSend", await this.invokeHook(onSend ? () => onSend(context, result) : undefined, "onSend"));
269
+ return;
270
+ }
271
+ const onError = this.options.onError;
272
+ this.appendHookError(hookErrors, "onError", await this.invokeHook(onError ? () => onError(context, result) : undefined, "onError"));
273
+ }
274
+ async retryOnce(context, firstResult, retry, hookErrors) {
275
+ if (!isTransientFailure(firstResult)) {
276
+ return { attempts: [firstResult], result: firstResult };
277
+ }
278
+ context.isRetry = true;
279
+ context.attempt = 2;
280
+ const onRetry = this.options.onRetry;
281
+ this.appendHookError(hookErrors, "onRetry", await this.invokeHook(onRetry ? () => onRetry(context, firstResult) : undefined, "onRetry"));
282
+ const secondResult = await retry();
283
+ return { attempts: [firstResult, secondResult], result: secondResult };
284
+ }
285
+ async persistRetry(logged, context, hookErrors, provider, result) {
286
+ if (!logged) {
287
+ return null;
288
+ }
289
+ const payload = this.resolvePayload(context, hookErrors);
290
+ return commsMessage_1.CommsMessage.appendAttempt({
291
+ attempt: this.attemptFromResult(provider, result),
292
+ error: result.error,
293
+ errorClass: result.errorClass,
294
+ errorCode: result.errorCode,
295
+ id: logged._id,
296
+ metadata: Object.keys(hookErrors).length > 0 ? { hookErrors } : undefined,
297
+ payload,
298
+ payloadExpiresAt: payload === undefined ? undefined : this.payloadExpiresAt(),
299
+ providerMessageId: result.providerMessageId,
300
+ status: result.accepted ? "sent" : "failed",
509
301
  });
510
- };
511
- CommsService.prototype.finalizeWithRetry = function (_a) {
512
- return __awaiter(this, arguments, void 0, function (_b) {
513
- var logged, retried, finalLogged;
514
- var _c;
515
- var context = _b.context, first = _b.first, hookErrors = _b.hookErrors, logFields = _b.logFields, provider = _b.provider, retry = _b.retry;
516
- return __generator(this, function (_d) {
517
- switch (_d.label) {
518
- case 0: return [4 /*yield*/, this.logResult({
519
- attempts: [this.attemptFromResult(provider, first)],
520
- channel: logFields.channel,
521
- context: context,
522
- hookErrors: hookErrors,
523
- metadata: logFields.metadata,
524
- provider: provider,
525
- result: first,
526
- retriedFromId: logFields.retriedFromId,
527
- status: first.accepted ? "sent" : "failed",
528
- subject: logFields.subject,
529
- templateId: logFields.templateId,
530
- to: logFields.to,
531
- userId: logFields.userId,
532
- })];
533
- case 1:
534
- logged = _d.sent();
535
- return [4 /*yield*/, this.retryOnce(context, first, retry, hookErrors)];
536
- case 2:
537
- retried = _d.sent();
538
- finalLogged = logged;
539
- if (!(retried.attempts.length > 1)) return [3 /*break*/, 4];
540
- return [4 /*yield*/, this.persistRetry(logged, context, hookErrors, provider, retried.result)];
541
- case 3:
542
- finalLogged =
543
- (_c = (_d.sent())) !== null && _c !== void 0 ? _c : logged;
544
- _d.label = 4;
545
- case 4: return [4 /*yield*/, this.notifyOutcomeHooks(context, retried.result, hookErrors)];
546
- case 5:
547
- _d.sent();
548
- return [4 /*yield*/, this.patchHookErrors(finalLogged, hookErrors)];
549
- case 6:
550
- _d.sent();
551
- return [2 /*return*/, this.withLoggedId(retried.result, finalLogged)];
552
- }
553
- });
302
+ }
303
+ async finalizeWithRetry({ context, first, hookErrors, logFields, provider, retry, }) {
304
+ const logged = await this.logResult({
305
+ attempts: [this.attemptFromResult(provider, first)],
306
+ channel: logFields.channel,
307
+ context,
308
+ hookErrors,
309
+ metadata: logFields.metadata,
310
+ provider,
311
+ result: first,
312
+ retriedFromId: logFields.retriedFromId,
313
+ status: first.accepted ? "sent" : "failed",
314
+ subject: logFields.subject,
315
+ templateId: logFields.templateId,
316
+ to: logFields.to,
317
+ userId: logFields.userId,
554
318
  });
555
- };
556
- CommsService.prototype.withLoggedId = function (result, logged) {
319
+ const retried = await this.retryOnce(context, first, retry, hookErrors);
320
+ let finalLogged = logged;
321
+ if (retried.attempts.length > 1) {
322
+ finalLogged =
323
+ (await this.persistRetry(logged, context, hookErrors, provider, retried.result)) ?? logged;
324
+ }
325
+ await this.notifyOutcomeHooks(context, retried.result, hookErrors);
326
+ await this.patchHookErrors(finalLogged, hookErrors);
327
+ return this.withLoggedId(retried.result, finalLogged);
328
+ }
329
+ withLoggedId(result, logged) {
557
330
  if (!logged) {
558
331
  return result;
559
332
  }
560
- return __assign(__assign({}, result), { loggedMessageId: String(logged._id) });
561
- };
562
- CommsService.prototype.loggedIdFromSend = function (result) {
333
+ return { ...result, loggedMessageId: String(logged._id) };
334
+ }
335
+ loggedIdFromSend(result) {
563
336
  if (Array.isArray(result)) {
564
- return result.map(function (row) { return row.loggedMessageId; }).find(function (id) { return Boolean(id); });
337
+ return result.map((row) => row.loggedMessageId).find((id) => Boolean(id));
565
338
  }
566
339
  return result.loggedMessageId;
567
- };
568
- CommsService.prototype.cancelledResult = function () {
340
+ }
341
+ cancelledResult() {
569
342
  return {
570
343
  accepted: false,
571
344
  error: CANCELLED_ERROR,
572
345
  errorClass: "permanent",
573
346
  errorCode: "before-send-cancel",
574
347
  };
575
- };
576
- CommsService.prototype.sendMailOnce = function (provider, message) {
577
- return __awaiter(this, void 0, void 0, function () {
578
- var error_5;
579
- return __generator(this, function (_a) {
580
- switch (_a.label) {
581
- case 0:
582
- _a.trys.push([0, 2, , 3]);
583
- return [4 /*yield*/, provider.sendMail(message)];
584
- case 1: return [2 /*return*/, _a.sent()];
585
- case 2:
586
- error_5 = _a.sent();
587
- return [2 /*return*/, providerThrowResult(error_5)];
588
- case 3: return [2 /*return*/];
589
- }
590
- });
591
- });
592
- };
593
- CommsService.prototype.sendSmsOnce = function (provider, message) {
594
- return __awaiter(this, void 0, void 0, function () {
595
- var error_6;
596
- return __generator(this, function (_a) {
597
- switch (_a.label) {
598
- case 0:
599
- _a.trys.push([0, 2, , 3]);
600
- return [4 /*yield*/, provider.sendSms(message)];
601
- case 1: return [2 /*return*/, _a.sent()];
602
- case 2:
603
- error_6 = _a.sent();
604
- return [2 /*return*/, providerThrowResult(error_6)];
605
- case 3: return [2 /*return*/];
606
- }
607
- });
608
- });
609
- };
610
- CommsService.prototype.sendPushOnce = function (provider, message) {
611
- return __awaiter(this, void 0, void 0, function () {
612
- var error_7;
613
- return __generator(this, function (_a) {
614
- switch (_a.label) {
615
- case 0:
616
- _a.trys.push([0, 2, , 3]);
617
- return [4 /*yield*/, provider.sendPush(message)];
618
- case 1: return [2 /*return*/, _a.sent()];
619
- case 2:
620
- error_7 = _a.sent();
621
- return [2 /*return*/, message.tokens.map(function () { return providerThrowResult(error_7); })];
622
- case 3: return [2 /*return*/];
623
- }
624
- });
625
- });
626
- };
627
- CommsService.prototype.startVerificationOnce = function (provider, options) {
628
- return __awaiter(this, void 0, void 0, function () {
629
- var error_8;
630
- return __generator(this, function (_a) {
631
- switch (_a.label) {
632
- case 0:
633
- _a.trys.push([0, 2, , 3]);
634
- return [4 /*yield*/, provider.startVerification(options)];
635
- case 1: return [2 /*return*/, _a.sent()];
636
- case 2:
637
- error_8 = _a.sent();
638
- return [2 /*return*/, providerThrowResult(error_8)];
639
- case 3: return [2 /*return*/];
640
- }
641
- });
642
- });
643
- };
644
- CommsService.prototype.mergeSendMetadata = function (result, sendOptions) {
645
- var extra = sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.extraMetadata;
348
+ }
349
+ async sendMailOnce(provider, message) {
350
+ try {
351
+ return await provider.sendMail(message);
352
+ }
353
+ catch (error) {
354
+ return providerThrowResult(error);
355
+ }
356
+ }
357
+ async sendSmsOnce(provider, message) {
358
+ try {
359
+ return await provider.sendSms(message);
360
+ }
361
+ catch (error) {
362
+ return providerThrowResult(error);
363
+ }
364
+ }
365
+ async sendPushOnce(provider, message) {
366
+ try {
367
+ return await provider.sendPush(message);
368
+ }
369
+ catch (error) {
370
+ return message.tokens.map(() => providerThrowResult(error));
371
+ }
372
+ }
373
+ async startVerificationOnce(provider, options) {
374
+ try {
375
+ return await provider.startVerification(options);
376
+ }
377
+ catch (error) {
378
+ return providerThrowResult(error);
379
+ }
380
+ }
381
+ mergeSendMetadata(result, sendOptions) {
382
+ const extra = sendOptions?.extraMetadata;
646
383
  if (!result.metadata && !extra) {
647
384
  return result.metadata;
648
385
  }
649
- return __assign(__assign({}, result.metadata), extra);
650
- };
651
- CommsService.prototype.mailProvider = function () {
386
+ return { ...result.metadata, ...extra };
387
+ }
388
+ mailProvider() {
652
389
  if (this.options.mail) {
653
390
  return this.options.mail;
654
391
  }
@@ -657,8 +394,8 @@ var CommsService = /** @class */ (function () {
657
394
  }
658
395
  api_1.logger.warn("[comms] Mail provider not configured; using console provider");
659
396
  return this.consoleMail;
660
- };
661
- CommsService.prototype.smsProvider = function () {
397
+ }
398
+ smsProvider() {
662
399
  if (this.options.sms) {
663
400
  return this.options.sms;
664
401
  }
@@ -667,8 +404,8 @@ var CommsService = /** @class */ (function () {
667
404
  }
668
405
  api_1.logger.warn("[comms] SMS provider not configured; using console provider");
669
406
  return this.consoleSms;
670
- };
671
- CommsService.prototype.pushProvider = function () {
407
+ }
408
+ pushProvider() {
672
409
  if (this.options.push) {
673
410
  return this.options.push;
674
411
  }
@@ -677,8 +414,8 @@ var CommsService = /** @class */ (function () {
677
414
  }
678
415
  api_1.logger.warn("[comms] Push provider not configured; using console provider");
679
416
  return this.consolePush;
680
- };
681
- CommsService.prototype.verificationProvider = function () {
417
+ }
418
+ verificationProvider() {
682
419
  if (this.options.verification) {
683
420
  return this.options.verification;
684
421
  }
@@ -687,12 +424,14 @@ var CommsService = /** @class */ (function () {
687
424
  }
688
425
  api_1.logger.warn("[comms] Verification provider not configured; using console provider");
689
426
  return this.consoleVerification;
690
- };
691
- CommsService.prototype.applyMailDefaults = function (message) {
692
- var _a;
693
- return __assign(__assign({}, message), { from: (_a = message.from) !== null && _a !== void 0 ? _a : this.options.defaultFrom });
694
- };
695
- CommsService.prototype.isChannelConfigured = function (channel) {
427
+ }
428
+ applyMailDefaults(message) {
429
+ return {
430
+ ...message,
431
+ from: message.from ?? this.options.defaultFrom,
432
+ };
433
+ }
434
+ isChannelConfigured(channel) {
696
435
  if (channel === "mail") {
697
436
  return Boolean(this.options.mail) || !isProduction();
698
437
  }
@@ -703,542 +442,379 @@ var CommsService = /** @class */ (function () {
703
442
  return Boolean(this.options.push) || !isProduction();
704
443
  }
705
444
  return Boolean(this.options.verification) || !isProduction();
706
- };
707
- CommsService.prototype.sendMail = function (message, sendOptions) {
708
- return __awaiter(this, void 0, void 0, function () {
709
- var provider, hookErrors, context, before, activeMessage, result, logged, first;
710
- var _this = this;
711
- return __generator(this, function (_a) {
712
- switch (_a.label) {
713
- case 0:
714
- provider = this.mailProvider();
715
- hookErrors = {};
716
- context = {
717
- attempt: 1,
718
- channel: "mail",
719
- isRetry: (sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.isRetry) === true,
720
- message: this.applyMailDefaults(message),
721
- provider: provider.id,
722
- userId: (sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.userId) ? String(sendOptions.userId) : undefined,
723
- };
724
- return [4 /*yield*/, this.applyBeforeSend(context, hookErrors)];
725
- case 1:
726
- before = _a.sent();
727
- activeMessage = this.applyMailDefaults(before.message);
728
- context.message = activeMessage;
729
- if (!before.cancel) return [3 /*break*/, 3];
730
- result = this.cancelledResult();
731
- return [4 /*yield*/, this.logResult({
732
- attempts: [this.attemptFromResult(provider.id, result)],
733
- channel: "mail",
734
- context: context,
735
- hookErrors: hookErrors,
736
- metadata: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.extraMetadata,
737
- provider: provider.id,
738
- result: result,
739
- retriedFromId: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.retriedFromId,
740
- status: "cancelled",
741
- subject: activeMessage.subject,
742
- templateId: activeMessage.templateId,
743
- to: activeMessage.to,
744
- userId: context.userId,
745
- })];
746
- case 2:
747
- logged = _a.sent();
748
- return [2 /*return*/, this.withLoggedId(result, logged)];
749
- case 3: return [4 /*yield*/, this.sendMailOnce(provider, activeMessage)];
750
- case 4:
751
- first = _a.sent();
752
- return [2 /*return*/, this.finalizeWithRetry({
753
- context: context,
754
- first: first,
755
- hookErrors: hookErrors,
756
- logFields: {
757
- channel: "mail",
758
- metadata: this.mergeSendMetadata(first, sendOptions),
759
- retriedFromId: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.retriedFromId,
760
- subject: activeMessage.subject,
761
- templateId: activeMessage.templateId,
762
- to: activeMessage.to,
763
- userId: context.userId,
764
- },
765
- provider: provider.id,
766
- retry: function () { return _this.sendMailOnce(provider, activeMessage); },
767
- })];
768
- }
445
+ }
446
+ async sendMail(message, sendOptions) {
447
+ const provider = this.mailProvider();
448
+ const hookErrors = {};
449
+ const context = {
450
+ attempt: 1,
451
+ channel: "mail",
452
+ isRetry: sendOptions?.isRetry === true,
453
+ message: this.applyMailDefaults(message),
454
+ provider: provider.id,
455
+ userId: sendOptions?.userId ? String(sendOptions.userId) : undefined,
456
+ };
457
+ const before = await this.applyBeforeSend(context, hookErrors);
458
+ const activeMessage = this.applyMailDefaults(before.message);
459
+ context.message = activeMessage;
460
+ if (before.cancel) {
461
+ const result = this.cancelledResult();
462
+ const logged = await this.logResult({
463
+ attempts: [this.attemptFromResult(provider.id, result)],
464
+ channel: "mail",
465
+ context,
466
+ hookErrors,
467
+ metadata: sendOptions?.extraMetadata,
468
+ provider: provider.id,
469
+ result,
470
+ retriedFromId: sendOptions?.retriedFromId,
471
+ status: "cancelled",
472
+ subject: activeMessage.subject,
473
+ templateId: activeMessage.templateId,
474
+ to: activeMessage.to,
475
+ userId: context.userId,
769
476
  });
477
+ return this.withLoggedId(result, logged);
478
+ }
479
+ const first = await this.sendMailOnce(provider, activeMessage);
480
+ return this.finalizeWithRetry({
481
+ context,
482
+ first,
483
+ hookErrors,
484
+ logFields: {
485
+ channel: "mail",
486
+ metadata: this.mergeSendMetadata(first, sendOptions),
487
+ retriedFromId: sendOptions?.retriedFromId,
488
+ subject: activeMessage.subject,
489
+ templateId: activeMessage.templateId,
490
+ to: activeMessage.to,
491
+ userId: context.userId,
492
+ },
493
+ provider: provider.id,
494
+ retry: () => this.sendMailOnce(provider, activeMessage),
770
495
  });
771
- };
772
- CommsService.prototype.sendSms = function (message, sendOptions) {
773
- return __awaiter(this, void 0, void 0, function () {
774
- var provider, hookErrors, context, before, activeMessage, result, logged, first;
775
- var _this = this;
776
- return __generator(this, function (_a) {
777
- switch (_a.label) {
778
- case 0:
779
- provider = this.smsProvider();
780
- hookErrors = {};
781
- context = {
782
- attempt: 1,
783
- channel: "sms",
784
- isRetry: (sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.isRetry) === true,
785
- message: message,
786
- provider: provider.id,
787
- userId: (sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.userId) ? String(sendOptions.userId) : undefined,
788
- };
789
- return [4 /*yield*/, this.applyBeforeSend(context, hookErrors)];
790
- case 1:
791
- before = _a.sent();
792
- activeMessage = before.message;
793
- context.message = activeMessage;
794
- if (!before.cancel) return [3 /*break*/, 3];
795
- result = this.cancelledResult();
796
- return [4 /*yield*/, this.logResult({
797
- attempts: [this.attemptFromResult(provider.id, result)],
798
- channel: "sms",
799
- context: context,
800
- hookErrors: hookErrors,
801
- metadata: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.extraMetadata,
802
- provider: provider.id,
803
- result: result,
804
- retriedFromId: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.retriedFromId,
805
- status: "cancelled",
806
- to: activeMessage.to,
807
- userId: context.userId,
808
- })];
809
- case 2:
810
- logged = _a.sent();
811
- return [2 /*return*/, this.withLoggedId(result, logged)];
812
- case 3: return [4 /*yield*/, this.sendSmsOnce(provider, activeMessage)];
813
- case 4:
814
- first = _a.sent();
815
- return [2 /*return*/, this.finalizeWithRetry({
816
- context: context,
817
- first: first,
818
- hookErrors: hookErrors,
819
- logFields: {
820
- channel: "sms",
821
- metadata: this.mergeSendMetadata(first, sendOptions),
822
- retriedFromId: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.retriedFromId,
823
- to: activeMessage.to,
824
- userId: context.userId,
825
- },
826
- provider: provider.id,
827
- retry: function () { return _this.sendSmsOnce(provider, activeMessage); },
828
- })];
829
- }
496
+ }
497
+ async sendSms(message, sendOptions) {
498
+ const provider = this.smsProvider();
499
+ const hookErrors = {};
500
+ const context = {
501
+ attempt: 1,
502
+ channel: "sms",
503
+ isRetry: sendOptions?.isRetry === true,
504
+ message,
505
+ provider: provider.id,
506
+ userId: sendOptions?.userId ? String(sendOptions.userId) : undefined,
507
+ };
508
+ const before = await this.applyBeforeSend(context, hookErrors);
509
+ const activeMessage = before.message;
510
+ context.message = activeMessage;
511
+ if (before.cancel) {
512
+ const result = this.cancelledResult();
513
+ const logged = await this.logResult({
514
+ attempts: [this.attemptFromResult(provider.id, result)],
515
+ channel: "sms",
516
+ context,
517
+ hookErrors,
518
+ metadata: sendOptions?.extraMetadata,
519
+ provider: provider.id,
520
+ result,
521
+ retriedFromId: sendOptions?.retriedFromId,
522
+ status: "cancelled",
523
+ to: activeMessage.to,
524
+ userId: context.userId,
830
525
  });
526
+ return this.withLoggedId(result, logged);
527
+ }
528
+ const first = await this.sendSmsOnce(provider, activeMessage);
529
+ return this.finalizeWithRetry({
530
+ context,
531
+ first,
532
+ hookErrors,
533
+ logFields: {
534
+ channel: "sms",
535
+ metadata: this.mergeSendMetadata(first, sendOptions),
536
+ retriedFromId: sendOptions?.retriedFromId,
537
+ to: activeMessage.to,
538
+ userId: context.userId,
539
+ },
540
+ provider: provider.id,
541
+ retry: () => this.sendSmsOnce(provider, activeMessage),
831
542
  });
832
- };
833
- CommsService.prototype.sendPushToUser = function (message, sendOptions) {
834
- return __awaiter(this, void 0, void 0, function () {
835
- var provider, hookErrors, tokens, providerMessage, context, before, activeMessage, result_1, loggedRows_1, sendTokens, firstByToken, _a, _b, loggedByToken, retryTokens, retryTokenSet, beforeRetryHookErrors, finalByToken, retryContext, onRetry_1, firstTransient_1, _c, _d, retryByToken_1, _e, _f;
836
- var _this = this;
837
- return __generator(this, function (_g) {
838
- switch (_g.label) {
839
- case 0:
840
- provider = this.pushProvider();
841
- hookErrors = {};
842
- return [4 /*yield*/, pushToken_1.PushToken.find({ active: true, userId: message.userId })];
843
- case 1:
844
- tokens = _g.sent();
845
- if (tokens.length === 0) {
846
- return [2 /*return*/, []];
847
- }
848
- providerMessage = {
849
- badge: message.badge,
850
- body: message.body,
851
- data: message.data,
852
- sound: message.sound,
853
- title: message.title,
854
- tokens: tokens.map(function (token) { return token.token; }),
855
- };
856
- context = {
857
- attempt: 1,
858
- channel: "push",
859
- isRetry: (sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.isRetry) === true,
860
- message: providerMessage,
861
- provider: provider.id,
862
- userId: String(message.userId),
863
- };
864
- return [4 /*yield*/, this.applyBeforeSend(context, hookErrors)];
865
- case 2:
866
- before = _g.sent();
867
- activeMessage = before.message;
868
- context.message = activeMessage;
869
- if (!before.cancel) return [3 /*break*/, 4];
870
- result_1 = this.cancelledResult();
871
- return [4 /*yield*/, Promise.all(tokens.map(function (token) {
872
- return _this.logResult({
873
- attempts: [_this.attemptFromResult(provider.id, result_1)],
874
- channel: "push",
875
- context: _this.cloneContext(context),
876
- hookErrors: hookErrors,
877
- metadata: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.extraMetadata,
878
- provider: provider.id,
879
- result: result_1,
880
- retriedFromId: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.retriedFromId,
881
- status: "cancelled",
882
- to: token.token,
883
- userId: String(message.userId),
884
- });
885
- }))];
886
- case 3:
887
- loggedRows_1 = _g.sent();
888
- return [2 /*return*/, tokens.map(function (_, index) { var _a; return _this.withLoggedId(result_1, (_a = loggedRows_1[index]) !== null && _a !== void 0 ? _a : null); })];
889
- case 4:
890
- sendTokens = activeMessage.tokens;
891
- if (sendTokens.length === 0) {
892
- return [2 /*return*/, []];
893
- }
894
- _a = this.resultsByToken;
895
- _b = [sendTokens];
896
- return [4 /*yield*/, this.sendPushOnce(provider, activeMessage)];
897
- case 5:
898
- firstByToken = _a.apply(this, _b.concat([_g.sent()]));
899
- loggedByToken = new Map();
900
- return [4 /*yield*/, Promise.all(sendTokens.map(function (tokenValue) { return __awaiter(_this, void 0, void 0, function () {
901
- var result, tokenContext, logged;
902
- return __generator(this, function (_a) {
903
- switch (_a.label) {
904
- case 0:
905
- result = firstByToken.get(tokenValue);
906
- tokenContext = this.cloneContext(context);
907
- return [4 /*yield*/, this.logResult({
908
- attempts: [this.attemptFromResult(provider.id, result)],
909
- channel: "push",
910
- context: tokenContext,
911
- hookErrors: hookErrors,
912
- metadata: this.mergeSendMetadata(result, sendOptions),
913
- provider: provider.id,
914
- result: result,
915
- retriedFromId: sendOptions === null || sendOptions === void 0 ? void 0 : sendOptions.retriedFromId,
916
- status: result.accepted ? "sent" : "failed",
917
- to: tokenValue,
918
- userId: String(message.userId),
919
- })];
920
- case 1:
921
- logged = _a.sent();
922
- loggedByToken.set(tokenValue, logged);
923
- return [2 /*return*/];
924
- }
925
- });
926
- }); }))];
927
- case 6:
928
- _g.sent();
929
- retryTokens = sendTokens.filter(function (tokenValue) {
930
- return isTransientFailure(firstByToken.get(tokenValue));
931
- });
932
- retryTokenSet = new Set(retryTokens);
933
- beforeRetryHookErrors = this.cloneHookErrors(hookErrors);
934
- finalByToken = new Map(firstByToken);
935
- retryContext = this.cloneContext(context, { attempt: 2, isRetry: true });
936
- if (!(retryTokens.length > 0)) return [3 /*break*/, 10];
937
- onRetry_1 = this.options.onRetry;
938
- firstTransient_1 = firstByToken.get(retryTokens[0]);
939
- _c = this.appendHookError;
940
- _d = [hookErrors,
941
- "onRetry"];
942
- return [4 /*yield*/, this.invokeHook(onRetry_1 ? function () { return onRetry_1(retryContext, firstTransient_1); } : undefined, "onRetry")];
943
- case 7:
944
- _c.apply(this, _d.concat([_g.sent()]));
945
- _e = this.resultsByToken;
946
- _f = [retryTokens];
947
- return [4 /*yield*/, this.sendPushOnce(provider, __assign(__assign({}, activeMessage), { tokens: retryTokens }))];
948
- case 8:
949
- retryByToken_1 = _e.apply(this, _f.concat([_g.sent()]));
950
- return [4 /*yield*/, Promise.all(retryTokens.map(function (tokenValue) { return __awaiter(_this, void 0, void 0, function () {
951
- var retryResult, tokenHookErrors, logged, appended;
952
- var _a;
953
- return __generator(this, function (_b) {
954
- switch (_b.label) {
955
- case 0:
956
- retryResult = retryByToken_1.get(tokenValue);
957
- finalByToken.set(tokenValue, retryResult);
958
- tokenHookErrors = this.cloneHookErrors(beforeRetryHookErrors);
959
- if (hookErrors.onRetry) {
960
- tokenHookErrors.onRetry = __spreadArray([], __read(hookErrors.onRetry), false);
961
- }
962
- logged = (_a = loggedByToken.get(tokenValue)) !== null && _a !== void 0 ? _a : null;
963
- return [4 /*yield*/, this.persistRetry(logged, this.cloneContext(retryContext, {
964
- messageId: logged ? String(logged._id) : undefined,
965
- }), tokenHookErrors, provider.id, retryResult)];
966
- case 1:
967
- appended = _b.sent();
968
- if (appended) {
969
- loggedByToken.set(tokenValue, appended);
970
- }
971
- return [2 /*return*/];
972
- }
973
- });
974
- }); }))];
975
- case 9:
976
- _g.sent();
977
- _g.label = 10;
978
- case 10: return [4 /*yield*/, Promise.all(sendTokens.map(function (tokenValue) { return __awaiter(_this, void 0, void 0, function () {
979
- var result, tokenHookErrors, logged, didRetry;
980
- var _a;
981
- return __generator(this, function (_b) {
982
- switch (_b.label) {
983
- case 0:
984
- result = finalByToken.get(tokenValue);
985
- tokenHookErrors = this.cloneHookErrors(beforeRetryHookErrors);
986
- if (retryTokenSet.has(tokenValue) && hookErrors.onRetry) {
987
- tokenHookErrors.onRetry = __spreadArray([], __read(hookErrors.onRetry), false);
988
- }
989
- logged = (_a = loggedByToken.get(tokenValue)) !== null && _a !== void 0 ? _a : null;
990
- didRetry = retryTokenSet.has(tokenValue);
991
- return [4 /*yield*/, this.notifyOutcomeHooks(this.cloneContext(context, {
992
- attempt: didRetry ? 2 : 1,
993
- isRetry: didRetry,
994
- messageId: logged ? String(logged._id) : undefined,
995
- }), result, tokenHookErrors)];
996
- case 1:
997
- _b.sent();
998
- return [4 /*yield*/, this.patchHookErrors(logged, tokenHookErrors)];
999
- case 2:
1000
- _b.sent();
1001
- if (!(!result.accepted && isPermanentPushFailure(result))) return [3 /*break*/, 4];
1002
- return [4 /*yield*/, this.deactivatePushToken(tokenValue)];
1003
- case 3:
1004
- _b.sent();
1005
- _b.label = 4;
1006
- case 4: return [2 /*return*/];
1007
- }
1008
- });
1009
- }); }))];
1010
- case 11:
1011
- _g.sent();
1012
- return [2 /*return*/, sendTokens.map(function (tokenValue) {
1013
- var _a;
1014
- return _this.withLoggedId(finalByToken.get(tokenValue), (_a = loggedByToken.get(tokenValue)) !== null && _a !== void 0 ? _a : null);
1015
- })];
1016
- }
543
+ }
544
+ async sendPushToUser(message, sendOptions) {
545
+ const provider = this.pushProvider();
546
+ const hookErrors = {};
547
+ const tokens = await pushToken_1.PushToken.find({ active: true, userId: message.userId });
548
+ if (tokens.length === 0) {
549
+ return [];
550
+ }
551
+ const providerMessage = {
552
+ badge: message.badge,
553
+ body: message.body,
554
+ data: message.data,
555
+ sound: message.sound,
556
+ title: message.title,
557
+ tokens: tokens.map((token) => token.token),
558
+ };
559
+ const context = {
560
+ attempt: 1,
561
+ channel: "push",
562
+ isRetry: sendOptions?.isRetry === true,
563
+ message: providerMessage,
564
+ provider: provider.id,
565
+ userId: String(message.userId),
566
+ };
567
+ const before = await this.applyBeforeSend(context, hookErrors);
568
+ const activeMessage = before.message;
569
+ context.message = activeMessage;
570
+ if (before.cancel) {
571
+ const result = this.cancelledResult();
572
+ const loggedRows = await Promise.all(tokens.map((token) => this.logResult({
573
+ attempts: [this.attemptFromResult(provider.id, result)],
574
+ channel: "push",
575
+ context: this.cloneContext(context),
576
+ hookErrors,
577
+ metadata: sendOptions?.extraMetadata,
578
+ provider: provider.id,
579
+ result,
580
+ retriedFromId: sendOptions?.retriedFromId,
581
+ status: "cancelled",
582
+ to: token.token,
583
+ userId: String(message.userId),
584
+ })));
585
+ return tokens.map((_, index) => this.withLoggedId(result, loggedRows[index] ?? null));
586
+ }
587
+ const sendTokens = activeMessage.tokens;
588
+ if (sendTokens.length === 0) {
589
+ return [];
590
+ }
591
+ const firstByToken = this.resultsByToken(sendTokens, await this.sendPushOnce(provider, activeMessage));
592
+ const loggedByToken = new Map();
593
+ await Promise.all(sendTokens.map(async (tokenValue) => {
594
+ const result = firstByToken.get(tokenValue);
595
+ const tokenContext = this.cloneContext(context);
596
+ const logged = await this.logResult({
597
+ attempts: [this.attemptFromResult(provider.id, result)],
598
+ channel: "push",
599
+ context: tokenContext,
600
+ hookErrors,
601
+ metadata: this.mergeSendMetadata(result, sendOptions),
602
+ provider: provider.id,
603
+ result,
604
+ retriedFromId: sendOptions?.retriedFromId,
605
+ status: result.accepted ? "sent" : "failed",
606
+ to: tokenValue,
607
+ userId: String(message.userId),
1017
608
  });
1018
- });
1019
- };
1020
- CommsService.prototype.startVerification = function (options) {
1021
- return __awaiter(this, void 0, void 0, function () {
1022
- var provider, hookErrors, context, before, activeOptions, result, first;
1023
- var _this = this;
1024
- return __generator(this, function (_a) {
1025
- switch (_a.label) {
1026
- case 0:
1027
- provider = this.verificationProvider();
1028
- hookErrors = {};
1029
- context = {
1030
- attempt: 1,
1031
- channel: "verification",
1032
- isRetry: false,
1033
- message: options,
1034
- provider: provider.id,
1035
- };
1036
- return [4 /*yield*/, this.applyBeforeSend(context, hookErrors)];
1037
- case 1:
1038
- before = _a.sent();
1039
- activeOptions = before.message;
1040
- context.message = activeOptions;
1041
- if (!before.cancel) return [3 /*break*/, 3];
1042
- result = this.cancelledResult();
1043
- return [4 /*yield*/, this.logResult({
1044
- attempts: [this.attemptFromResult(provider.id, result)],
1045
- channel: "verification",
1046
- context: context,
1047
- hookErrors: hookErrors,
1048
- metadata: { verificationChannel: activeOptions.channel },
1049
- provider: provider.id,
1050
- result: result,
1051
- status: "cancelled",
1052
- to: activeOptions.to,
1053
- })];
1054
- case 2:
1055
- _a.sent();
1056
- return [2 /*return*/, result];
1057
- case 3: return [4 /*yield*/, this.startVerificationOnce(provider, activeOptions)];
1058
- case 4:
1059
- first = _a.sent();
1060
- return [2 /*return*/, this.finalizeWithRetry({
1061
- context: context,
1062
- first: first,
1063
- hookErrors: hookErrors,
1064
- logFields: {
1065
- channel: "verification",
1066
- metadata: { verificationChannel: activeOptions.channel },
1067
- to: activeOptions.to,
1068
- },
1069
- provider: provider.id,
1070
- retry: function () { return _this.startVerificationOnce(provider, activeOptions); },
1071
- })];
609
+ loggedByToken.set(tokenValue, logged);
610
+ }));
611
+ const retryTokens = sendTokens.filter((tokenValue) => isTransientFailure(firstByToken.get(tokenValue)));
612
+ const retryTokenSet = new Set(retryTokens);
613
+ const beforeRetryHookErrors = this.cloneHookErrors(hookErrors);
614
+ const finalByToken = new Map(firstByToken);
615
+ const retryContext = this.cloneContext(context, { attempt: 2, isRetry: true });
616
+ if (retryTokens.length > 0) {
617
+ const onRetry = this.options.onRetry;
618
+ const firstTransient = firstByToken.get(retryTokens[0]);
619
+ this.appendHookError(hookErrors, "onRetry", await this.invokeHook(onRetry ? () => onRetry(retryContext, firstTransient) : undefined, "onRetry"));
620
+ const retryByToken = this.resultsByToken(retryTokens, await this.sendPushOnce(provider, { ...activeMessage, tokens: retryTokens }));
621
+ await Promise.all(retryTokens.map(async (tokenValue) => {
622
+ const retryResult = retryByToken.get(tokenValue);
623
+ finalByToken.set(tokenValue, retryResult);
624
+ const tokenHookErrors = this.cloneHookErrors(beforeRetryHookErrors);
625
+ if (hookErrors.onRetry) {
626
+ tokenHookErrors.onRetry = [...hookErrors.onRetry];
1072
627
  }
1073
- });
1074
- });
1075
- };
1076
- CommsService.prototype.checkVerification = function (options) {
1077
- return __awaiter(this, void 0, void 0, function () {
1078
- var provider, hookErrors, context, result, loggedResult, logged, error_9, loggedResult, logged;
1079
- var _a;
1080
- return __generator(this, function (_b) {
1081
- switch (_b.label) {
1082
- case 0:
1083
- provider = this.verificationProvider();
1084
- hookErrors = {};
1085
- context = {
1086
- attempt: 1,
1087
- channel: "verification",
1088
- isRetry: false,
1089
- message: { channel: "sms", to: options.to },
1090
- provider: provider.id,
1091
- };
1092
- _b.label = 1;
1093
- case 1:
1094
- _b.trys.push([1, 6, , 10]);
1095
- return [4 /*yield*/, provider.checkVerification(options)];
1096
- case 2:
1097
- result = _b.sent();
1098
- loggedResult = __assign({ accepted: result.valid }, (result.valid ? {} : { error: (_a = result.error) !== null && _a !== void 0 ? _a : "Verification check failed" }));
1099
- return [4 /*yield*/, this.logResult({
1100
- attempts: [this.attemptFromResult(provider.id, loggedResult)],
1101
- channel: "verification",
1102
- context: context,
1103
- hookErrors: hookErrors,
1104
- omitPayload: true,
1105
- provider: provider.id,
1106
- result: loggedResult,
1107
- status: loggedResult.accepted ? "sent" : "failed",
1108
- to: options.to,
1109
- })];
1110
- case 3:
1111
- logged = _b.sent();
1112
- return [4 /*yield*/, this.notifyOutcomeHooks(context, loggedResult, hookErrors)];
1113
- case 4:
1114
- _b.sent();
1115
- return [4 /*yield*/, this.patchHookErrors(logged, hookErrors)];
1116
- case 5:
1117
- _b.sent();
1118
- return [2 /*return*/, result];
1119
- case 6:
1120
- error_9 = _b.sent();
1121
- loggedResult = providerThrowResult(error_9);
1122
- return [4 /*yield*/, this.logResult({
1123
- attempts: [this.attemptFromResult(provider.id, loggedResult)],
1124
- channel: "verification",
1125
- context: context,
1126
- hookErrors: hookErrors,
1127
- omitPayload: true,
1128
- provider: provider.id,
1129
- result: loggedResult,
1130
- status: "failed",
1131
- to: options.to,
1132
- })];
1133
- case 7:
1134
- logged = _b.sent();
1135
- return [4 /*yield*/, this.notifyOutcomeHooks(context, loggedResult, hookErrors)];
1136
- case 8:
1137
- _b.sent();
1138
- return [4 /*yield*/, this.patchHookErrors(logged, hookErrors)];
1139
- case 9:
1140
- _b.sent();
1141
- return [2 /*return*/, { error: loggedResult.error, valid: false }];
1142
- case 10: return [2 /*return*/];
628
+ const logged = loggedByToken.get(tokenValue) ?? null;
629
+ const appended = await this.persistRetry(logged, this.cloneContext(retryContext, {
630
+ messageId: logged ? String(logged._id) : undefined,
631
+ }), tokenHookErrors, provider.id, retryResult);
632
+ if (appended) {
633
+ loggedByToken.set(tokenValue, appended);
1143
634
  }
635
+ }));
636
+ }
637
+ await Promise.all(sendTokens.map(async (tokenValue) => {
638
+ const result = finalByToken.get(tokenValue);
639
+ const tokenHookErrors = this.cloneHookErrors(beforeRetryHookErrors);
640
+ if (retryTokenSet.has(tokenValue) && hookErrors.onRetry) {
641
+ tokenHookErrors.onRetry = [...hookErrors.onRetry];
642
+ }
643
+ const logged = loggedByToken.get(tokenValue) ?? null;
644
+ const didRetry = retryTokenSet.has(tokenValue);
645
+ await this.notifyOutcomeHooks(this.cloneContext(context, {
646
+ attempt: didRetry ? 2 : 1,
647
+ isRetry: didRetry,
648
+ messageId: logged ? String(logged._id) : undefined,
649
+ }), result, tokenHookErrors);
650
+ await this.patchHookErrors(logged, tokenHookErrors);
651
+ if (!result.accepted && isPermanentPushFailure(result)) {
652
+ await this.deactivatePushToken(tokenValue);
653
+ }
654
+ }));
655
+ return sendTokens.map((tokenValue) => this.withLoggedId(finalByToken.get(tokenValue), loggedByToken.get(tokenValue) ?? null));
656
+ }
657
+ async startVerification(options) {
658
+ const provider = this.verificationProvider();
659
+ const hookErrors = {};
660
+ const context = {
661
+ attempt: 1,
662
+ channel: "verification",
663
+ isRetry: false,
664
+ message: options,
665
+ provider: provider.id,
666
+ };
667
+ const before = await this.applyBeforeSend(context, hookErrors);
668
+ const activeOptions = before.message;
669
+ context.message = activeOptions;
670
+ if (before.cancel) {
671
+ const result = this.cancelledResult();
672
+ await this.logResult({
673
+ attempts: [this.attemptFromResult(provider.id, result)],
674
+ channel: "verification",
675
+ context,
676
+ hookErrors,
677
+ metadata: { verificationChannel: activeOptions.channel },
678
+ provider: provider.id,
679
+ result,
680
+ status: "cancelled",
681
+ to: activeOptions.to,
1144
682
  });
683
+ return result;
684
+ }
685
+ const first = await this.startVerificationOnce(provider, activeOptions);
686
+ return this.finalizeWithRetry({
687
+ context,
688
+ first,
689
+ hookErrors,
690
+ logFields: {
691
+ channel: "verification",
692
+ metadata: { verificationChannel: activeOptions.channel },
693
+ to: activeOptions.to,
694
+ },
695
+ provider: provider.id,
696
+ retry: () => this.startVerificationOnce(provider, activeOptions),
1145
697
  });
1146
- };
1147
- CommsService.prototype.retryMessage = function (options) {
1148
- return __awaiter(this, void 0, void 0, function () {
1149
- var original, block, sendOptions, payload, sendResult, loggedId, retried;
1150
- var _this = this;
1151
- var _a, _b, _c, _d, _e, _f, _g, _h;
1152
- return __generator(this, function (_j) {
1153
- switch (_j.label) {
1154
- case 0:
1155
- if (!mongoose_1.default.isValidObjectId(options.messageId)) {
1156
- throw new api_1.APIError({ status: 404, title: "Comms message not found" });
1157
- }
1158
- return [4 /*yield*/, commsMessage_1.CommsMessage.findOneOrNone({ _id: options.messageId })];
1159
- case 1:
1160
- original = _j.sent();
1161
- if (!original) {
1162
- throw new api_1.APIError({ status: 404, title: "Comms message not found" });
1163
- }
1164
- block = (0, commsRetry_1.evaluateRetryBlock)({
1165
- isChannelConfigured: function (channel) { return _this.isChannelConfigured(channel); },
1166
- message: original,
1167
- });
1168
- if (block) {
1169
- (0, commsRetry_1.throwRetryBlock)(block);
1170
- }
1171
- sendOptions = {
1172
- extraMetadata: options.retriedByUserId
1173
- ? { retriedByUserId: options.retriedByUserId }
1174
- : undefined,
1175
- isRetry: true,
1176
- retriedFromId: String(original._id),
1177
- userId: original.userId,
1178
- };
1179
- payload = original.payload;
1180
- if (!(original.channel === "mail")) return [3 /*break*/, 3];
1181
- return [4 /*yield*/, this.sendMail({
1182
- dynamicTemplateData: payload.dynamicTemplateData,
1183
- from: payload.from,
1184
- html: payload.html,
1185
- replyTo: payload.replyTo,
1186
- subject: String((_b = (_a = payload.subject) !== null && _a !== void 0 ? _a : original.subject) !== null && _b !== void 0 ? _b : ""),
1187
- templateId: (_c = payload.templateId) !== null && _c !== void 0 ? _c : original.templateId,
1188
- text: payload.text,
1189
- to: (_d = payload.to) !== null && _d !== void 0 ? _d : original.to,
1190
- }, sendOptions)];
1191
- case 2:
1192
- sendResult = _j.sent();
1193
- return [3 /*break*/, 8];
1194
- case 3:
1195
- if (!(original.channel === "sms")) return [3 /*break*/, 5];
1196
- return [4 /*yield*/, this.sendSms({
1197
- body: String((_e = payload.body) !== null && _e !== void 0 ? _e : ""),
1198
- to: String((_f = payload.to) !== null && _f !== void 0 ? _f : original.to),
1199
- }, sendOptions)];
1200
- case 4:
1201
- sendResult = _j.sent();
1202
- return [3 /*break*/, 8];
1203
- case 5:
1204
- if (!original.userId) return [3 /*break*/, 7];
1205
- return [4 /*yield*/, this.sendPushToUser({
1206
- badge: payload.badge,
1207
- body: String((_g = payload.body) !== null && _g !== void 0 ? _g : ""),
1208
- data: payload.data,
1209
- sound: payload.sound,
1210
- title: String((_h = payload.title) !== null && _h !== void 0 ? _h : ""),
1211
- userId: original.userId,
1212
- }, sendOptions)];
1213
- case 6:
1214
- sendResult = _j.sent();
1215
- return [3 /*break*/, 8];
1216
- case 7:
1217
- (0, commsRetry_1.throwRetryBlock)({
1218
- code: "comms-retry-not-retryable",
1219
- title: "Push retries require a linked user",
1220
- });
1221
- _j.label = 8;
1222
- case 8:
1223
- loggedId = this.loggedIdFromSend(sendResult !== null && sendResult !== void 0 ? sendResult : []);
1224
- if (!loggedId) {
1225
- throw new api_1.APIError({ status: 500, title: "Retry did not create a communication log" });
1226
- }
1227
- return [4 /*yield*/, commsMessage_1.CommsMessage.findOneOrNone({ _id: loggedId })];
1228
- case 9:
1229
- retried = _j.sent();
1230
- if (!retried) {
1231
- throw new api_1.APIError({ status: 500, title: "Retry did not create a communication log" });
1232
- }
1233
- original.retriedById = retried._id;
1234
- return [4 /*yield*/, original.save()];
1235
- case 10:
1236
- _j.sent();
1237
- return [2 /*return*/, retried];
1238
- }
698
+ }
699
+ async checkVerification(options) {
700
+ const provider = this.verificationProvider();
701
+ const hookErrors = {};
702
+ const context = {
703
+ attempt: 1,
704
+ channel: "verification",
705
+ isRetry: false,
706
+ message: { channel: "sms", to: options.to },
707
+ provider: provider.id,
708
+ };
709
+ try {
710
+ const result = await provider.checkVerification(options);
711
+ const loggedResult = {
712
+ accepted: result.valid,
713
+ ...(result.valid ? {} : { error: result.error ?? "Verification check failed" }),
714
+ };
715
+ const logged = await this.logResult({
716
+ attempts: [this.attemptFromResult(provider.id, loggedResult)],
717
+ channel: "verification",
718
+ context,
719
+ hookErrors,
720
+ omitPayload: true,
721
+ provider: provider.id,
722
+ result: loggedResult,
723
+ status: loggedResult.accepted ? "sent" : "failed",
724
+ to: options.to,
725
+ });
726
+ await this.notifyOutcomeHooks(context, loggedResult, hookErrors);
727
+ await this.patchHookErrors(logged, hookErrors);
728
+ return result;
729
+ }
730
+ catch (error) {
731
+ const loggedResult = providerThrowResult(error);
732
+ const logged = await this.logResult({
733
+ attempts: [this.attemptFromResult(provider.id, loggedResult)],
734
+ channel: "verification",
735
+ context,
736
+ hookErrors,
737
+ omitPayload: true,
738
+ provider: provider.id,
739
+ result: loggedResult,
740
+ status: "failed",
741
+ to: options.to,
1239
742
  });
743
+ await this.notifyOutcomeHooks(context, loggedResult, hookErrors);
744
+ await this.patchHookErrors(logged, hookErrors);
745
+ return { error: loggedResult.error, valid: false };
746
+ }
747
+ }
748
+ async retryMessage(options) {
749
+ if (!mongoose_1.default.isValidObjectId(options.messageId)) {
750
+ throw new api_1.APIError({ status: 404, title: "Comms message not found" });
751
+ }
752
+ const original = await commsMessage_1.CommsMessage.findOneOrNone({ _id: options.messageId });
753
+ if (!original) {
754
+ throw new api_1.APIError({ status: 404, title: "Comms message not found" });
755
+ }
756
+ const block = (0, commsRetry_1.evaluateRetryBlock)({
757
+ isChannelConfigured: (channel) => this.isChannelConfigured(channel),
758
+ message: original,
1240
759
  });
1241
- };
1242
- return CommsService;
1243
- }());
760
+ if (block) {
761
+ (0, commsRetry_1.throwRetryBlock)(block);
762
+ }
763
+ const sendOptions = {
764
+ extraMetadata: options.retriedByUserId
765
+ ? { retriedByUserId: options.retriedByUserId }
766
+ : undefined,
767
+ isRetry: true,
768
+ retriedFromId: String(original._id),
769
+ userId: original.userId,
770
+ };
771
+ const payload = original.payload;
772
+ let sendResult;
773
+ if (original.channel === "mail") {
774
+ sendResult = await this.sendMail({
775
+ dynamicTemplateData: payload.dynamicTemplateData,
776
+ from: payload.from,
777
+ html: payload.html,
778
+ replyTo: payload.replyTo,
779
+ subject: String(payload.subject ?? original.subject ?? ""),
780
+ templateId: payload.templateId ?? original.templateId,
781
+ text: payload.text,
782
+ to: payload.to ?? original.to,
783
+ }, sendOptions);
784
+ }
785
+ else if (original.channel === "sms") {
786
+ sendResult = await this.sendSms({
787
+ body: String(payload.body ?? ""),
788
+ to: String(payload.to ?? original.to),
789
+ }, sendOptions);
790
+ }
791
+ else if (original.userId) {
792
+ sendResult = await this.sendPushToUser({
793
+ badge: payload.badge,
794
+ body: String(payload.body ?? ""),
795
+ data: payload.data,
796
+ sound: payload.sound,
797
+ title: String(payload.title ?? ""),
798
+ userId: original.userId,
799
+ }, sendOptions);
800
+ }
801
+ else {
802
+ (0, commsRetry_1.throwRetryBlock)({
803
+ code: "comms-retry-not-retryable",
804
+ title: "Push retries require a linked user",
805
+ });
806
+ }
807
+ const loggedId = this.loggedIdFromSend(sendResult ?? []);
808
+ if (!loggedId) {
809
+ throw new api_1.APIError({ status: 500, title: "Retry did not create a communication log" });
810
+ }
811
+ const retried = await commsMessage_1.CommsMessage.findOneOrNone({ _id: loggedId });
812
+ if (!retried) {
813
+ throw new api_1.APIError({ status: 500, title: "Retry did not create a communication log" });
814
+ }
815
+ original.retriedById = retried._id;
816
+ await original.save();
817
+ return retried;
818
+ }
819
+ }
1244
820
  exports.CommsService = CommsService;