This repository has been archived by the owner on Sep 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
start-dev-smtp-server.ts
207 lines (188 loc) · 5.46 KB
/
start-dev-smtp-server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
(function() {
const
ZarroError = requireModule<ZarroError>("zarro-error"),
{ log } = requireModule<GulpUtil>("gulp-util"),
{ redBright, yellowBright } = requireModule<AnsiColors>("ansi-colors"),
env = requireModule<Env>("env"),
debug = requireModule<DebugFactory>("debug")(__filename),
mailpitAllIps = "[::]",
gulp = requireModule<Gulp>("gulp");
env.associate([
env.DEV_SMTP_DETACHED,
env.DEV_SMTP_PORT,
env.DEV_SMTP_BIND_IP,
env.DEV_SMTP_INTERFACE_PORT,
env.DEV_SMTP_INTERFACE_BIND_IP,
env.DEV_SMTP_IGNORE_ERRORS,
env.DEV_SMTP_OPEN_INTERFACE
], "start-dev-smtp-server"
);
gulp.task("start-dev-smtp-server", async () => {
const
spawn = requireModule<Spawn>("spawn"),
mailpitBinary = await findOrDownloadMailpit(),
smtpPort = env.resolveNumber(env.DEV_SMTP_PORT),
smtpIp = env.resolveWithFallback(env.DEV_SMTP_BIND_IP, mailpitAllIps),
smtpInterfacePort = env.resolveNumber(env.DEV_SMTP_INTERFACE_PORT),
smtpInterfaceIp = env.resolveWithFallback(env.DEV_SMTP_INTERFACE_BIND_IP, mailpitAllIps),
raiseErrors = !env.resolveFlag(env.DEV_SMTP_IGNORE_ERRORS);
if (mailpitBinary === undefined) {
const downloadError = `Unable to download mailpit from GitHub`;
if (raiseErrors) {
throw new ZarroError(downloadError);
} else {
console.error(redBright(downloadError));
return;
}
}
const args = [] as string[];
pushSmtpBind(args, smtpIp, smtpPort);
pushSmtpInterfacePort(args, smtpInterfaceIp, smtpInterfacePort);
try {
await Promise.all([
spawn(
mailpitBinary,
args, {
detached: env.resolveFlag(env.DEV_SMTP_DETACHED)
}
),
openSmtpInterfaceIfRequired(
smtpInterfaceIp,
smtpInterfacePort
)
]);
} catch (e) {
const err = e as Error;
if (raiseErrors) {
console.error(`${ err.message } (if this service is not absolutely required, set the environment variable ${ env.DEV_SMTP_IGNORE_ERRORS }=1`);
throw e;
}
logError(err.message || `${ e }`)
}
});
async function openSmtpInterfaceIfRequired(
ip: string,
port: number
): Promise<void> {
if (!env.resolveFlag(env.DEV_SMTP_OPEN_INTERFACE)) {
return;
}
const
url = generateInterfaceUrlFor(ip, port),
{ open } = requireModule<Open>("open");
await waitForUrlToBecomeAvailable(url);
logInfo(`
Opening the dev smtp interface in your browser (${url})
To disable this behavior, set env variable ${env.DEV_SMTP_OPEN_INTERFACE}=0
`.trim());
await open(url);
}
async function waitForUrlToBecomeAvailable(url: string) {
const
sleep = requireModule<Sleep>("sleep"),
HttpClient = requireModule<HttpClientModule>("http-client"),
httpClient = HttpClient.create();
do {
await sleep(500);
} while (!(await httpClient.exists(url)));
}
const ipMap = {
"[::]": "localhost",
"127.0.0.1": "localhost"
} as Dictionary<string>;
function generateInterfaceUrlFor(
ip: string,
port: number
): string {
const
host = ipMap[ip] ?? ip;
return `http://${ host }:${ port }`;
}
function logError(err: string) {
log(
redBright(
err
)
);
}
function logInfo(info: string) {
log(
yellowBright(
info
)
)
}
function pushSmtpBind(
args: string[],
ip: string,
port: number
) {
args.push("--smtp");
args.push(`${ validateIp(ip) }:${ port }`);
}
function pushSmtpInterfacePort(
args: string[],
ip: string,
port: number
) {
args.push("--listen");
args.push(`${ validateIp(ip) }:${ port }`);
}
function validateIp(ip: string): string {
if (ip === mailpitAllIps) {
return ip;
}
if (ip.match(/^(\d{1,3}\.){3}\d{1,3}$/)) {
return ip;
}
throw new ZarroError(`provided value is not a valid IP: ${ ip }`);
}
async function tryFindMailpitUnder(folder: string): Promise<Optional<string>> {
const
{ ls } = require("yafs"),
os = require("os"),
path = require("path"),
contents = await ls(folder, { fullPaths: true });
const seek = os.platform() === "win32"
? "mailpit.exe"
: "mailpit";
for (const item of contents) {
const fn = path.basename(item);
if (fn.toLowerCase() === seek) {
debug(`will start smtp server at: ${ item }`);
return item;
}
}
}
async function findOrDownloadMailpit(): Promise<Optional<string>> {
const
{ ExecStepContext } = require("exec-step"),
ctx = new ExecStepContext(),
path = require("path"),
getToolsFolder = requireModule<GetToolsFolder>("get-tools-folder"),
target = path.join(getToolsFolder(), "mailpit"),
{ fetchLatestRelease } = require("./modules/fetch-github-release");
const existing = await tryFindMailpitUnder(target);
if (existing) {
return existing;
}
return ctx.exec(
"fetching mailpit",
async () => {
await fetchLatestRelease({
owner: "axllent",
repo: "mailpit",
destination: target,
shouldExtract: true
});
const downloaded = await tryFindMailpitUnder(target);
if (downloaded) {
return downloaded;
}
console.error(
redBright(`Unable to find mailpit binary under ${ target }`)
);
return undefined;
});
}
})();