nightwatch-plugin-mailhog
Version:
A TypeScript based @nightwatchjs plugin for interacting with, and asserting on, data within a @mailhog instance.
360 lines (359 loc) • 20.5 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
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);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
// eslint-disable-next-line import/no-unassigned-import
require("@nightwatch/apitesting");
/**
* The mailhog command gives you a single entry point to all MailHog-related functions:
* browser.mailhog().<functionName>()
*/
var MailHogCommand = /** @class */ (function () {
function MailHogCommand() {
}
MailHogCommand.prototype.command = function () {
var api = this.api;
var mailhogUrl = api.globals.mailhog;
if (!mailhogUrl) {
throw new Error('globals.mailhog is empty; expected a URL to its API endpoint, e.g. http://localhost:4566/mailhog/api');
}
// Our MailHog methods
var methods = {
deleteAllEmails: function () {
var _this = this;
return api.perform(function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.supertest
.request(mailhogUrl)
.delete('/v1/messages')
.expect(200)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
},
deleteEmail: function (id) {
var _this = this;
return api.perform(function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.supertest
.request(mailhogUrl)
.delete("/v1/messages/".concat(encodeURIComponent(id)))
.expect(200)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); });
},
findEmails: function (queryOrOptions, callback) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, api.perform(function () { return __awaiter(_this, void 0, void 0, function () {
var options, _a, kind, _b, limit, query, _c, start, response, _i, _d, item, transferEncoding;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
options = typeof queryOrOptions === 'string'
? { query: queryOrOptions }
: queryOrOptions;
_a = options.kind, kind = _a === void 0 ? 'containing' : _a, _b = options.limit, limit = _b === void 0 ? 10 : _b, query = options.query, _c = options.start, start = _c === void 0 ? 0 : _c;
return [4 /*yield*/, api.supertest
.request(mailhogUrl)
.get("/v2/search?limit=".concat(limit, "&start=").concat(start, "&kind=").concat(kind, "&query=").concat(query))
.set('Accept', 'application/json')
.expect(200)];
case 1:
response = _e.sent();
// Decode quoted-printable encoding if present
for (_i = 0, _d = response.body.items; _i < _d.length; _i++) {
item = _d[_i];
transferEncoding = item.Content.Headers['Content-Transfer-Encoding'];
if (item.Content.Body && (transferEncoding === null || transferEncoding === void 0 ? void 0 : transferEncoding.includes('quoted-printable'))) {
item.Content.Body = methods.decodeQuotedPrintable(item.Content.Body);
}
}
return [4 /*yield*/, callback(response.body.items || [])];
case 2:
_e.sent();
return [2 /*return*/];
}
});
}); })];
});
});
},
findMostRecentEmail: function (queryOrOptions, callback) {
return __awaiter(this, void 0, void 0, function () {
var emails, sorted;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, methods.performFindEmails(queryOrOptions)];
case 1:
emails = _a.sent();
sorted = methods.toSortedByDate(emails);
return [4 /*yield*/, (sorted.length === 0 ? callback(undefined) : callback(sorted[0]))];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
},
getEmail: function (id, callback) {
var _this = this;
return api.perform(function () { return __awaiter(_this, void 0, void 0, function () {
var response, item, transferEncoding;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, api.supertest
.request(mailhogUrl)
.get("/v1/messages/".concat(encodeURIComponent(id)))
.set('Accept', 'text/json')
.expect(200)];
case 1:
response = _a.sent();
item = JSON.parse(response.text);
transferEncoding = item.Content.Headers['Content-Transfer-Encoding'];
if (item.Content.Body && (transferEncoding === null || transferEncoding === void 0 ? void 0 : transferEncoding.includes('quoted-printable'))) {
item.Content.Body = methods.decodeQuotedPrintable(item.Content.Body);
}
return [4 /*yield*/, callback(item)];
case 2:
_a.sent();
return [2 /*return*/];
}
});
}); });
},
getOneTimeCode: function (queryOrOptions, callback) {
var _this = this;
return api.perform(function () { return __awaiter(_this, void 0, void 0, function () {
var defaultOtpOptions, options, emails, mostRecentEmail, mostRecentCreated, _i, emails_1, email, created, emailId, body, matches, code;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
defaultOtpOptions = {
kind: 'to',
// There is no sort option, so we retrieve a
// batch and then sort it ourselves within
// the response logic. This ensures if multiple
// emails were sent, we get the latest one.
limit: 20,
start: 0,
};
options = typeof queryOrOptions === 'string'
? (__assign(__assign({}, defaultOtpOptions), { query: queryOrOptions })) : (__assign(__assign({}, defaultOtpOptions), queryOrOptions));
emails = [];
return [4 /*yield*/, methods.findEmails(options, function (found) {
emails = found;
})];
case 1:
_c.sent();
if (!(emails.length === 0)) return [3 /*break*/, 4];
return [4 /*yield*/, api.assert.fail('No emails found matching that query.')];
case 2:
_c.sent();
return [4 /*yield*/, callback('')];
case 3:
_c.sent();
return [2 /*return*/];
case 4:
mostRecentEmail = emails[0];
mostRecentCreated = new Date(((_a = mostRecentEmail.Content.Headers.Date) === null || _a === void 0 ? void 0 : _a.length)
? mostRecentEmail.Content.Headers.Date[0]
: mostRecentEmail.Created);
for (_i = 0, emails_1 = emails; _i < emails_1.length; _i++) {
email = emails_1[_i];
created = new Date(((_b = email.Content.Headers.Date) === null || _b === void 0 ? void 0 : _b.length)
? email.Content.Headers.Date[0]
: email.Created);
if (created.getTime() > mostRecentCreated.getTime()) {
mostRecentEmail = email;
mostRecentCreated = created;
}
}
emailId = mostRecentEmail.ID;
body = mostRecentEmail.Content.Body || '';
matches = /data-otp="one-time-code"\s*>(\d+)</.exec(body);
if (!(!matches || matches.length < 2)) return [3 /*break*/, 7];
return [4 /*yield*/, api.assert.fail('No code found in email (data-otp="one-time-code").')];
case 5:
_c.sent();
return [4 /*yield*/, callback('')];
case 6:
_c.sent();
return [2 /*return*/];
case 7:
code = matches[1];
// 3) Delete the email so it can't be reused
return [4 /*yield*/, methods.deleteEmail(emailId)];
case 8:
// 3) Delete the email so it can't be reused
_c.sent();
return [4 /*yield*/, callback(code)];
case 9:
_c.sent();
return [2 /*return*/];
}
});
}); });
},
performFindEmails: function (queryOrOptions) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
result = [];
return [4 /*yield*/, methods.findEmails(queryOrOptions, function (items) {
result = items;
})];
case 1:
_a.sent();
return [2 /*return*/, result];
}
});
});
},
performFindMostRecentEmail: function (queryOrOptions) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, methods.findMostRecentEmail(queryOrOptions, function (item) {
result = item;
})];
case 1:
_a.sent();
return [2 /*return*/, result];
}
});
});
},
performGetEmail: function (id) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, methods.getEmail(id, function (item) {
result = item;
})];
case 1:
_a.sent();
return [2 /*return*/, result];
}
});
});
},
performGetOneTimeCode: function (queryOrOptions) {
return __awaiter(this, void 0, void 0, function () {
var result;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, methods.getOneTimeCode(queryOrOptions, function (code) {
result = code;
})];
case 1:
_a.sent();
return [2 /*return*/, result];
}
});
});
},
decodeQuotedPrintable: function (content) {
// Based on https://www.npmjs.com/package/quoted-printable but
// without adding it as a full dependency.
return content
// https://tools.ietf.org/html/rfc2045#section-6.7, rule 3:
// “Therefore, when decoding a `Quoted-Printable` body, any trailing white
// space on a line must be deleted, as it will necessarily have been added
// by intermediate transport agents.”
.replaceAll(/[\t ]$/gm, '')
// Remove hard line breaks preceded by `=`. Proper `Quoted-Printable`-
// encoded data only contains CRLF line endings, but for compatibility
// reasons we support separate CR and LF too.
.replaceAll(/=(?:\r\n?|\n|$)/g, '')
// Decode escape sequences of the form `=XX` where `XX` is any
// combination of two hexidecimal digits. For optimal compatibility,
// lowercase hexadecimal digits are supported as well. See
// https://tools.ietf.org/html/rfc2045#section-6.7, note 1.
.replaceAll(/=([a-fA-F\d]{2})/g, function ($0, $1) {
var codePoint = Number.parseInt($1, 16);
return String.fromCodePoint(codePoint);
});
},
toSortedByDate: function (items) {
if (items.length === 0) {
return items;
}
return items.sort(function (a, b) {
var _a, _b;
var aDate = new Date(((_a = a.Content.Headers.Date) === null || _a === void 0 ? void 0 : _a.length)
? a.Content.Headers.Date[0]
: a.Created);
var bDate = new Date(((_b = b.Content.Headers.Date) === null || _b === void 0 ? void 0 : _b.length)
? b.Content.Headers.Date[0]
: b.Created);
return aDate.getTime() - bDate.getTime();
});
},
};
return methods;
};
MailHogCommand.autoInvoke = true;
return MailHogCommand;
}());
exports.default = MailHogCommand;