@timshel_npm/maildev
Version:
SMTP Server with async API and Web Interface for viewing and testing emails during development
103 lines (102 loc) • 3.51 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MailBuffer = void 0;
class MailBuffer {
constructor(mailServer, subject, defaultTimeout) {
this.mails = [];
this.nexts = [];
this.defaultTimeout = defaultTimeout;
this._receive = (mail) => {
let consumed = false;
let index = -1;
do {
index = this.nexts.findIndex((n) => n.filter(mail));
if (index > -1) {
const n = this.nexts[index];
consumed = n.consume;
this.nexts.splice(index, 1);
n.resolve(mail);
if (n.timeout !== undefined) {
clearTimeout(n.timeout);
}
}
} while (index > -1 && !consumed);
if (!consumed) {
this.mails.push(mail);
}
};
this.close = () => {
mailServer.removeListener("close", this.close);
mailServer.removeListener(subject, this._receive);
const error = new Error("Closing buffer");
for (let _a of this.nexts) {
const { reject } = _a, _ = __rest(_a, ["reject"]);
reject(error);
}
};
mailServer.on(subject, this._receive);
mailServer.once("close", this.close);
}
find(filter, consume) {
const index = this.mails.findIndex(filter);
if (index > -1) {
const mail = this.mails[index];
if (consume) {
this.mails.splice(index, 1);
}
return mail;
}
}
next(filter, consume = true) {
return new Promise((resolve, reject) => {
const mail = this.find(filter, consume);
if (mail !== undefined) {
resolve(mail);
}
else {
this.nexts.push({
filter,
resolve,
reject,
consume,
});
}
});
}
expect(filter, consume = true, timeout) {
return new Promise((resolve, reject) => {
const mail = this.find(filter, consume);
if (mail !== undefined) {
resolve(mail);
}
else {
let next = {
filter,
resolve,
reject,
consume,
};
this.nexts.push(next);
next.timeout = setTimeout(() => {
let index = this.nexts.findIndex((n) => n === next);
if (index > -1) {
this.nexts.splice(index, 1);
reject(new Error("Timeout while waiting for Mail"));
}
}, timeout || this.defaultTimeout);
}
});
}
}
exports.MailBuffer = MailBuffer;