@terreno/comms 56.0.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/biome.jsonc +17 -0
  3. package/bunfig.toml +5 -0
  4. package/dist/adapters/console.d.ts +30 -0
  5. package/dist/adapters/console.js +122 -0
  6. package/dist/commsApp.d.ts +14 -0
  7. package/dist/commsApp.js +37 -0
  8. package/dist/commsService.d.ts +20 -0
  9. package/dist/commsService.js +386 -0
  10. package/dist/index.d.ts +10 -0
  11. package/dist/index.js +19 -0
  12. package/dist/modelTypes.d.ts +53 -0
  13. package/dist/modelTypes.js +2 -0
  14. package/dist/models/commsMessage.d.ts +2 -0
  15. package/dist/models/commsMessage.js +119 -0
  16. package/dist/models/pushToken.d.ts +2 -0
  17. package/dist/models/pushToken.js +56 -0
  18. package/dist/routes/commsExplorer.d.ts +7 -0
  19. package/dist/routes/commsExplorer.js +147 -0
  20. package/dist/routes/pushTokens.d.ts +7 -0
  21. package/dist/routes/pushTokens.js +292 -0
  22. package/dist/templates.d.ts +10 -0
  23. package/dist/templates.js +32 -0
  24. package/dist/types.d.ts +78 -0
  25. package/dist/types.js +2 -0
  26. package/package.json +55 -0
  27. package/src/adapters/console.test.ts +227 -0
  28. package/src/adapters/console.ts +87 -0
  29. package/src/commsApp.test.ts +448 -0
  30. package/src/commsApp.ts +48 -0
  31. package/src/commsService.test.ts +570 -0
  32. package/src/commsService.ts +293 -0
  33. package/src/index.ts +45 -0
  34. package/src/modelTypes.ts +78 -0
  35. package/src/models/commsMessage.test.ts +53 -0
  36. package/src/models/commsMessage.ts +97 -0
  37. package/src/models/pushToken.test.ts +45 -0
  38. package/src/models/pushToken.ts +69 -0
  39. package/src/routes/commsExplorer.ts +114 -0
  40. package/src/routes/pushTokens.ts +265 -0
  41. package/src/templates.test.ts +37 -0
  42. package/src/templates.ts +31 -0
  43. package/src/tests/bunSetup.ts +14 -0
  44. package/src/types.ts +93 -0
  45. package/tsconfig.json +32 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Flourish Health
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/biome.jsonc ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
+ "extends": ["../biome.jsonc"],
4
+ "files": {
5
+ "includes": [
6
+ "package.json",
7
+ "src/**/*.ts",
8
+ "!!**/node_modules",
9
+ "!!node_modules",
10
+ "!!**/dist",
11
+ "!!dist",
12
+ "!!**/coverage",
13
+ "!!coverage"
14
+ ]
15
+ },
16
+ "root": true
17
+ }
package/bunfig.toml ADDED
@@ -0,0 +1,5 @@
1
+ [test]
2
+ preload = ["./src/tests/bunSetup.ts"]
3
+ root = "./src"
4
+ coveragePathIgnorePatterns = ["**/dist/**", "**/*.test.ts", "**/tests/**", "**/node_modules/**", "../**"]
5
+ coverageThreshold = { line = 95, function = 95 }
@@ -0,0 +1,30 @@
1
+ import type { CheckVerificationOptions, MailMessage, MailProvider, PushMessage, PushProvider, SendResult, SmsMessage, SmsProvider, StartVerificationOptions, VerificationProvider, VerificationResult } from "../types";
2
+ interface ConsoleProviderOptions {
3
+ log?: (message: string) => void;
4
+ }
5
+ export declare class ConsoleMailProvider implements MailProvider {
6
+ readonly id = "console";
7
+ private readonly log;
8
+ constructor(options?: ConsoleProviderOptions);
9
+ sendMail(message: MailMessage): Promise<SendResult>;
10
+ }
11
+ export declare class ConsoleSmsProvider implements SmsProvider {
12
+ readonly id = "console";
13
+ private readonly log;
14
+ constructor(options?: ConsoleProviderOptions);
15
+ sendSms(message: SmsMessage): Promise<SendResult>;
16
+ }
17
+ export declare class ConsolePushProvider implements PushProvider {
18
+ readonly id = "console";
19
+ private readonly log;
20
+ constructor(options?: ConsoleProviderOptions);
21
+ sendPush(message: PushMessage): Promise<SendResult[]>;
22
+ }
23
+ export declare class ConsoleVerificationProvider implements VerificationProvider {
24
+ readonly id = "console";
25
+ private readonly log;
26
+ constructor(options?: ConsoleProviderOptions);
27
+ checkVerification(_options: CheckVerificationOptions): Promise<VerificationResult>;
28
+ startVerification(options: StartVerificationOptions): Promise<SendResult>;
29
+ }
30
+ export {};
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ 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);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ 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;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.ConsoleVerificationProvider = exports.ConsolePushProvider = exports.ConsoleSmsProvider = exports.ConsoleMailProvider = void 0;
40
+ var api_1 = require("@terreno/api");
41
+ var defaultLog = function (message) {
42
+ api_1.logger.info(message);
43
+ };
44
+ var acceptedResult = function () { return ({ accepted: true }); };
45
+ var ConsoleMailProvider = /** @class */ (function () {
46
+ function ConsoleMailProvider(options) {
47
+ var _a;
48
+ this.id = "console";
49
+ this.log = (_a = options === null || options === void 0 ? void 0 : options.log) !== null && _a !== void 0 ? _a : defaultLog;
50
+ }
51
+ ConsoleMailProvider.prototype.sendMail = function (message) {
52
+ return __awaiter(this, void 0, void 0, function () {
53
+ var recipientCount;
54
+ return __generator(this, function (_a) {
55
+ recipientCount = Array.isArray(message.to) ? message.to.length : 1;
56
+ this.log("[comms:mail] recipients=".concat(recipientCount, " subjectLength=").concat(message.subject.length));
57
+ return [2 /*return*/, acceptedResult()];
58
+ });
59
+ });
60
+ };
61
+ return ConsoleMailProvider;
62
+ }());
63
+ exports.ConsoleMailProvider = ConsoleMailProvider;
64
+ var ConsoleSmsProvider = /** @class */ (function () {
65
+ function ConsoleSmsProvider(options) {
66
+ var _a;
67
+ this.id = "console";
68
+ this.log = (_a = options === null || options === void 0 ? void 0 : options.log) !== null && _a !== void 0 ? _a : defaultLog;
69
+ }
70
+ ConsoleSmsProvider.prototype.sendSms = function (message) {
71
+ return __awaiter(this, void 0, void 0, function () {
72
+ return __generator(this, function (_a) {
73
+ this.log("[comms:sms] bodyLength=".concat(message.body.length));
74
+ return [2 /*return*/, acceptedResult()];
75
+ });
76
+ });
77
+ };
78
+ return ConsoleSmsProvider;
79
+ }());
80
+ exports.ConsoleSmsProvider = ConsoleSmsProvider;
81
+ var ConsolePushProvider = /** @class */ (function () {
82
+ function ConsolePushProvider(options) {
83
+ var _a;
84
+ this.id = "console";
85
+ this.log = (_a = options === null || options === void 0 ? void 0 : options.log) !== null && _a !== void 0 ? _a : defaultLog;
86
+ }
87
+ ConsolePushProvider.prototype.sendPush = function (message) {
88
+ return __awaiter(this, void 0, void 0, function () {
89
+ return __generator(this, function (_a) {
90
+ this.log("[comms:push] tokens=".concat(message.tokens.length, " titleLength=").concat(message.title.length));
91
+ return [2 /*return*/, message.tokens.map(acceptedResult)];
92
+ });
93
+ });
94
+ };
95
+ return ConsolePushProvider;
96
+ }());
97
+ exports.ConsolePushProvider = ConsolePushProvider;
98
+ var ConsoleVerificationProvider = /** @class */ (function () {
99
+ function ConsoleVerificationProvider(options) {
100
+ var _a;
101
+ this.id = "console";
102
+ this.log = (_a = options === null || options === void 0 ? void 0 : options.log) !== null && _a !== void 0 ? _a : defaultLog;
103
+ }
104
+ ConsoleVerificationProvider.prototype.checkVerification = function (_options) {
105
+ return __awaiter(this, void 0, void 0, function () {
106
+ return __generator(this, function (_a) {
107
+ this.log("[comms:verification:check]");
108
+ return [2 /*return*/, { valid: true }];
109
+ });
110
+ });
111
+ };
112
+ ConsoleVerificationProvider.prototype.startVerification = function (options) {
113
+ return __awaiter(this, void 0, void 0, function () {
114
+ return __generator(this, function (_a) {
115
+ this.log("[comms:verification:start] channel=".concat(options.channel));
116
+ return [2 /*return*/, acceptedResult()];
117
+ });
118
+ });
119
+ };
120
+ return ConsoleVerificationProvider;
121
+ }());
122
+ exports.ConsoleVerificationProvider = ConsoleVerificationProvider;
@@ -0,0 +1,14 @@
1
+ import { type TerrenoPlugin } from "@terreno/api";
2
+ import type express from "express";
3
+ import { CommsService } from "./commsService";
4
+ import type { CommsOptions } from "./types";
5
+ export interface CommsAppOptions extends CommsOptions {
6
+ basePath?: string;
7
+ }
8
+ export declare const getCommsService: () => CommsService;
9
+ export declare class CommsApp implements TerrenoPlugin {
10
+ readonly service: CommsService;
11
+ private readonly options;
12
+ constructor(options?: CommsAppOptions);
13
+ register(app: express.Application, openApi?: unknown): void;
14
+ }
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommsApp = exports.getCommsService = void 0;
4
+ var api_1 = require("@terreno/api");
5
+ var commsService_1 = require("./commsService");
6
+ var pushToken_1 = require("./models/pushToken");
7
+ var commsExplorer_1 = require("./routes/commsExplorer");
8
+ var pushTokens_1 = require("./routes/pushTokens");
9
+ var registeredCommsService;
10
+ var getCommsService = function () {
11
+ if (!registeredCommsService) {
12
+ throw new api_1.APIError({ status: 500, title: "CommsApp is not registered" });
13
+ }
14
+ return registeredCommsService;
15
+ };
16
+ exports.getCommsService = getCommsService;
17
+ var CommsApp = /** @class */ (function () {
18
+ function CommsApp(options) {
19
+ this.options = options !== null && options !== void 0 ? options : {};
20
+ this.service = new commsService_1.CommsService(this.options);
21
+ }
22
+ CommsApp.prototype.register = function (app, openApi) {
23
+ var _a;
24
+ var basePath = (_a = this.options.basePath) !== null && _a !== void 0 ? _a : "/comms";
25
+ registeredCommsService = this.service;
26
+ // Atomic push-token registration depends on the unique token index to reject concurrent
27
+ // claims, so build it explicitly instead of relying on Mongoose autoIndex being enabled.
28
+ void pushToken_1.PushToken.init().catch(function (error) {
29
+ api_1.logger.error("[comms] Failed to build PushToken indexes; concurrent token registration cannot be " +
30
+ "rejected safely until the unique token index exists: ".concat(String(error)));
31
+ });
32
+ (0, pushTokens_1.addPushTokenRoutes)(app, { basePath: "".concat(basePath, "/pushTokens"), openApi: openApi });
33
+ (0, commsExplorer_1.addCommsExplorerRoute)(app, { openApi: openApi, path: "".concat(basePath, "/messages") });
34
+ };
35
+ return CommsApp;
36
+ }());
37
+ exports.CommsApp = CommsApp;
@@ -0,0 +1,20 @@
1
+ import type { CheckVerificationOptions, CommsOptions, MailMessage, SendPushToUserMessage, SendResult, SmsMessage, StartVerificationOptions, VerificationResult } from "./types";
2
+ export declare class CommsService {
3
+ private readonly options;
4
+ private readonly consoleMail;
5
+ private readonly consolePush;
6
+ private readonly consoleSms;
7
+ private readonly consoleVerification;
8
+ constructor(options?: CommsOptions);
9
+ private recipientForLog;
10
+ private logResult;
11
+ private mailProvider;
12
+ private smsProvider;
13
+ private pushProvider;
14
+ private verificationProvider;
15
+ sendMail(message: MailMessage): Promise<SendResult>;
16
+ sendSms(message: SmsMessage): Promise<SendResult>;
17
+ sendPushToUser(message: SendPushToUserMessage): Promise<SendResult[]>;
18
+ startVerification(options: StartVerificationOptions): Promise<SendResult>;
19
+ checkVerification(options: CheckVerificationOptions): Promise<VerificationResult>;
20
+ }
@@ -0,0 +1,386 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.CommsService = void 0;
51
+ var api_1 = require("@terreno/api");
52
+ var console_1 = require("./adapters/console");
53
+ var commsMessage_1 = require("./models/commsMessage");
54
+ var pushToken_1 = require("./models/pushToken");
55
+ var CHANNEL_NOT_CONFIGURED_TITLE = "Comms channel not configured";
56
+ var REDACTED_RECIPIENT = "[redacted]";
57
+ var throwUnconfiguredChannel = function () {
58
+ throw new api_1.APIError({ status: 501, title: CHANNEL_NOT_CONFIGURED_TITLE });
59
+ };
60
+ var isProduction = function () { return process.env.NODE_ENV === "production"; };
61
+ var CommsService = /** @class */ (function () {
62
+ function CommsService(options) {
63
+ this.consoleMail = new console_1.ConsoleMailProvider();
64
+ this.consolePush = new console_1.ConsolePushProvider();
65
+ this.consoleSms = new console_1.ConsoleSmsProvider();
66
+ this.consoleVerification = new console_1.ConsoleVerificationProvider();
67
+ this.options = options !== null && options !== void 0 ? options : {};
68
+ }
69
+ CommsService.prototype.recipientForLog = function (recipient) {
70
+ if (this.options.redactRecipients !== false) {
71
+ return REDACTED_RECIPIENT;
72
+ }
73
+ return Array.isArray(recipient) ? recipient.join(",") : recipient;
74
+ };
75
+ CommsService.prototype.logResult = function (_a) {
76
+ return __awaiter(this, arguments, void 0, function (_b) {
77
+ var channel = _b.channel, metadata = _b.metadata, provider = _b.provider, result = _b.result, subject = _b.subject, to = _b.to, userId = _b.userId;
78
+ return __generator(this, function (_c) {
79
+ switch (_c.label) {
80
+ case 0:
81
+ if (this.options.logMessages === false) {
82
+ return [2 /*return*/];
83
+ }
84
+ return [4 /*yield*/, commsMessage_1.CommsMessage.logSend({
85
+ channel: channel,
86
+ error: result.error,
87
+ metadata: metadata,
88
+ provider: provider,
89
+ providerMessageId: result.providerMessageId,
90
+ status: result.accepted ? "sent" : "failed",
91
+ subject: subject,
92
+ to: this.recipientForLog(to),
93
+ userId: userId,
94
+ })];
95
+ case 1:
96
+ _c.sent();
97
+ return [2 /*return*/];
98
+ }
99
+ });
100
+ });
101
+ };
102
+ CommsService.prototype.mailProvider = function () {
103
+ if (this.options.mail) {
104
+ return this.options.mail;
105
+ }
106
+ if (isProduction()) {
107
+ return throwUnconfiguredChannel();
108
+ }
109
+ api_1.logger.warn("[comms] Mail provider not configured; using console provider");
110
+ return this.consoleMail;
111
+ };
112
+ CommsService.prototype.smsProvider = function () {
113
+ if (this.options.sms) {
114
+ return this.options.sms;
115
+ }
116
+ if (isProduction()) {
117
+ return throwUnconfiguredChannel();
118
+ }
119
+ api_1.logger.warn("[comms] SMS provider not configured; using console provider");
120
+ return this.consoleSms;
121
+ };
122
+ CommsService.prototype.pushProvider = function () {
123
+ if (this.options.push) {
124
+ return this.options.push;
125
+ }
126
+ if (isProduction()) {
127
+ return throwUnconfiguredChannel();
128
+ }
129
+ api_1.logger.warn("[comms] Push provider not configured; using console provider");
130
+ return this.consolePush;
131
+ };
132
+ CommsService.prototype.verificationProvider = function () {
133
+ if (this.options.verification) {
134
+ return this.options.verification;
135
+ }
136
+ if (isProduction()) {
137
+ return throwUnconfiguredChannel();
138
+ }
139
+ api_1.logger.warn("[comms] Verification provider not configured; using console provider");
140
+ return this.consoleVerification;
141
+ };
142
+ CommsService.prototype.sendMail = function (message) {
143
+ return __awaiter(this, void 0, void 0, function () {
144
+ var provider, resolvedMessage, result, error_1;
145
+ var _a;
146
+ return __generator(this, function (_b) {
147
+ switch (_b.label) {
148
+ case 0:
149
+ provider = this.mailProvider();
150
+ resolvedMessage = __assign(__assign({}, message), { from: (_a = message.from) !== null && _a !== void 0 ? _a : this.options.defaultFrom });
151
+ _b.label = 1;
152
+ case 1:
153
+ _b.trys.push([1, 4, , 6]);
154
+ return [4 /*yield*/, provider.sendMail(resolvedMessage)];
155
+ case 2:
156
+ result = _b.sent();
157
+ return [4 /*yield*/, this.logResult({
158
+ channel: "mail",
159
+ provider: provider.id,
160
+ result: result,
161
+ subject: message.subject,
162
+ to: message.to,
163
+ })];
164
+ case 3:
165
+ _b.sent();
166
+ return [2 /*return*/, result];
167
+ case 4:
168
+ error_1 = _b.sent();
169
+ return [4 /*yield*/, this.logResult({
170
+ channel: "mail",
171
+ provider: provider.id,
172
+ result: { accepted: false, error: "Provider send failed" },
173
+ subject: message.subject,
174
+ to: message.to,
175
+ })];
176
+ case 5:
177
+ _b.sent();
178
+ throw error_1;
179
+ case 6: return [2 /*return*/];
180
+ }
181
+ });
182
+ });
183
+ };
184
+ CommsService.prototype.sendSms = function (message) {
185
+ return __awaiter(this, void 0, void 0, function () {
186
+ var provider, result, error_2;
187
+ return __generator(this, function (_a) {
188
+ switch (_a.label) {
189
+ case 0:
190
+ provider = this.smsProvider();
191
+ _a.label = 1;
192
+ case 1:
193
+ _a.trys.push([1, 4, , 6]);
194
+ return [4 /*yield*/, provider.sendSms(message)];
195
+ case 2:
196
+ result = _a.sent();
197
+ return [4 /*yield*/, this.logResult({
198
+ channel: "sms",
199
+ provider: provider.id,
200
+ result: result,
201
+ to: message.to,
202
+ })];
203
+ case 3:
204
+ _a.sent();
205
+ return [2 /*return*/, result];
206
+ case 4:
207
+ error_2 = _a.sent();
208
+ return [4 /*yield*/, this.logResult({
209
+ channel: "sms",
210
+ provider: provider.id,
211
+ result: { accepted: false, error: "Provider send failed" },
212
+ to: message.to,
213
+ })];
214
+ case 5:
215
+ _a.sent();
216
+ throw error_2;
217
+ case 6: return [2 /*return*/];
218
+ }
219
+ });
220
+ });
221
+ };
222
+ CommsService.prototype.sendPushToUser = function (message) {
223
+ return __awaiter(this, void 0, void 0, function () {
224
+ var provider, tokens, providerMessage, results, error_3, normalizedResults;
225
+ var _this = this;
226
+ return __generator(this, function (_a) {
227
+ switch (_a.label) {
228
+ case 0:
229
+ provider = this.pushProvider();
230
+ return [4 /*yield*/, pushToken_1.PushToken.find({ active: true, userId: message.userId })];
231
+ case 1:
232
+ tokens = _a.sent();
233
+ if (tokens.length === 0) {
234
+ return [2 /*return*/, []];
235
+ }
236
+ providerMessage = {
237
+ badge: message.badge,
238
+ body: message.body,
239
+ data: message.data,
240
+ sound: message.sound,
241
+ title: message.title,
242
+ tokens: tokens.map(function (token) { return token.token; }),
243
+ };
244
+ _a.label = 2;
245
+ case 2:
246
+ _a.trys.push([2, 4, , 6]);
247
+ return [4 /*yield*/, provider.sendPush(providerMessage)];
248
+ case 3:
249
+ results = _a.sent();
250
+ return [3 /*break*/, 6];
251
+ case 4:
252
+ error_3 = _a.sent();
253
+ return [4 /*yield*/, Promise.all(tokens.map(function (token) {
254
+ return _this.logResult({
255
+ channel: "push",
256
+ provider: provider.id,
257
+ result: { accepted: false, error: "Provider send failed" },
258
+ to: token.token,
259
+ userId: String(message.userId),
260
+ });
261
+ }))];
262
+ case 5:
263
+ _a.sent();
264
+ throw error_3;
265
+ case 6:
266
+ normalizedResults = tokens.map(function (_token, index) {
267
+ var _a;
268
+ return (_a = results[index]) !== null && _a !== void 0 ? _a : {
269
+ accepted: false,
270
+ error: "Provider returned no result for token",
271
+ };
272
+ });
273
+ return [4 /*yield*/, Promise.all(tokens.map(function (token, index) { return __awaiter(_this, void 0, void 0, function () {
274
+ var result;
275
+ return __generator(this, function (_a) {
276
+ switch (_a.label) {
277
+ case 0:
278
+ result = normalizedResults[index];
279
+ return [4 /*yield*/, this.logResult({
280
+ channel: "push",
281
+ provider: provider.id,
282
+ result: result,
283
+ to: token.token,
284
+ userId: String(message.userId),
285
+ })];
286
+ case 1:
287
+ _a.sent();
288
+ if (!(!result.accepted && result.isPermanentFailure)) return [3 /*break*/, 3];
289
+ token.active = false;
290
+ return [4 /*yield*/, token.save()];
291
+ case 2:
292
+ _a.sent();
293
+ _a.label = 3;
294
+ case 3: return [2 /*return*/];
295
+ }
296
+ });
297
+ }); }))];
298
+ case 7:
299
+ _a.sent();
300
+ return [2 /*return*/, normalizedResults];
301
+ }
302
+ });
303
+ });
304
+ };
305
+ CommsService.prototype.startVerification = function (options) {
306
+ return __awaiter(this, void 0, void 0, function () {
307
+ var provider, result, error_4;
308
+ return __generator(this, function (_a) {
309
+ switch (_a.label) {
310
+ case 0:
311
+ provider = this.verificationProvider();
312
+ _a.label = 1;
313
+ case 1:
314
+ _a.trys.push([1, 4, , 6]);
315
+ return [4 /*yield*/, provider.startVerification(options)];
316
+ case 2:
317
+ result = _a.sent();
318
+ return [4 /*yield*/, this.logResult({
319
+ channel: "verification",
320
+ metadata: { verificationChannel: options.channel },
321
+ provider: provider.id,
322
+ result: result,
323
+ to: options.to,
324
+ })];
325
+ case 3:
326
+ _a.sent();
327
+ return [2 /*return*/, result];
328
+ case 4:
329
+ error_4 = _a.sent();
330
+ return [4 /*yield*/, this.logResult({
331
+ channel: "verification",
332
+ metadata: { verificationChannel: options.channel },
333
+ provider: provider.id,
334
+ result: { accepted: false, error: "Provider send failed" },
335
+ to: options.to,
336
+ })];
337
+ case 5:
338
+ _a.sent();
339
+ throw error_4;
340
+ case 6: return [2 /*return*/];
341
+ }
342
+ });
343
+ });
344
+ };
345
+ CommsService.prototype.checkVerification = function (options) {
346
+ return __awaiter(this, void 0, void 0, function () {
347
+ var provider, result, error_5;
348
+ var _a;
349
+ return __generator(this, function (_b) {
350
+ switch (_b.label) {
351
+ case 0:
352
+ provider = this.verificationProvider();
353
+ _b.label = 1;
354
+ case 1:
355
+ _b.trys.push([1, 4, , 6]);
356
+ return [4 /*yield*/, provider.checkVerification(options)];
357
+ case 2:
358
+ result = _b.sent();
359
+ return [4 /*yield*/, this.logResult({
360
+ channel: "verification",
361
+ provider: provider.id,
362
+ result: __assign({ accepted: result.valid }, (result.valid ? {} : { error: (_a = result.error) !== null && _a !== void 0 ? _a : "Verification check failed" })),
363
+ to: options.to,
364
+ })];
365
+ case 3:
366
+ _b.sent();
367
+ return [2 /*return*/, result];
368
+ case 4:
369
+ error_5 = _b.sent();
370
+ return [4 /*yield*/, this.logResult({
371
+ channel: "verification",
372
+ provider: provider.id,
373
+ result: { accepted: false, error: "Provider check failed" },
374
+ to: options.to,
375
+ })];
376
+ case 5:
377
+ _b.sent();
378
+ throw error_5;
379
+ case 6: return [2 /*return*/];
380
+ }
381
+ });
382
+ });
383
+ };
384
+ return CommsService;
385
+ }());
386
+ exports.CommsService = CommsService;