-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathindex.js
243 lines (222 loc) · 7.07 KB
/
index.js
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const childProcess = require('child_process');
const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const process = require('process');
const util = require('util');
const { Buffer } = require('buffer');
const displayNotification = require('display-notification');
const getPort = require('get-port');
const nodemailer = require('nodemailer');
const open = require('open');
const pEvent = require('p-event');
const pWaitFor = require('p-wait-for');
const pug = require('pug');
const uuid = require('uuid');
const { isCI } = require('ci-info');
const { simpleParser } = require('mailparser');
const debug = util.debuglog('preview-email');
const isMacOS = os.platform() === 'darwin';
const writeFile = util.promisify(fs.writeFile);
const transport = nodemailer.createTransport({
streamTransport: true,
buffer: true
});
const templateFilePath = path.join(__dirname, 'template.pug');
const renderFilePromise = util.promisify(pug.renderFile);
const previewEmail = async (message, options) => {
options = {
dir: os.tmpdir(),
id: uuid.v4(),
open: { wait: false },
template: templateFilePath,
urlTransform: (path) => `file://${path}`,
openSimulator: process.env.NODE_ENV !== 'test',
returnHTML: false,
// <https://nodemailer.com/extras/mailparser/#options>
simpleParser: {},
hasDownloadOriginalButton: true,
...options
};
debug('message', message, 'options', options);
let raw;
let base64;
if (Buffer.isBuffer(message)) {
raw = message;
if (options.hasDownloadOriginalButton) base64 = message.toString('base64');
} else if (typeof message === 'string') {
raw = message;
if (options.hasDownloadOriginalButton)
base64 = Buffer.from(message).toString('base64');
} else if (typeof message === 'object') {
const response = await transport.sendMail(message);
raw = response.message;
if (options.hasDownloadOriginalButton)
base64 = Buffer.from(response.message).toString('base64');
} else {
throw new TypeError('Message argument is required');
}
const parsed = await simpleParser(raw, options.simpleParser);
if (options.hasDownloadOriginalButton) parsed.base64 = base64;
const html = await renderFilePromise(
options.template,
Object.assign(parsed, {
cache: true,
pretty: true
})
);
const filePath = `${options.dir}/${options.id}.html`;
const url = options.urlTransform(filePath);
if (!options.returnHTML) {
await writeFile(filePath, html);
if (options.open) await open(url, options.open);
}
//
// if on macOS then send a toast notification about XCode and Simulator for iOS
// App Store: <https://apps.apple.com/us/app/xcode/id497799835?mt=12>
// Developer Website: <https://developer.apple.com/download/all/?q=xcode>
// open -a Simulator
// `xcrun simctl openurl booted ${url}`
//
if (isMacOS && !isCI && options.openSimulator) {
try {
// <https://github.com/sindresorhus/open/blob/05ba9e150cc1a2629e518a9cc19b586c6ca3f269/index.js#L205-L222>
const simulator = childProcess.spawn('open', ['-a', 'Simulator']);
await new Promise((resolve, reject) => {
simulator.once('error', reject);
simulator.once('close', (exitCode) => {
if (exitCode !== 0)
return reject(
new Error(
'Install XCode from the macOS App Store or Apple Developer Website to continue.'
)
);
resolve(simulator);
});
});
// wait for the simulator to have been booted
// xcrun simctl list devices booted -j
await pWaitFor(async () => {
const devices = childProcess.spawn('xcrun', [
'simctl',
'list',
'devices',
'booted',
'-j'
]);
let stdout = '';
devices.stdout.on('data', (data) => {
stdout += data;
});
await new Promise((resolve, reject) => {
devices.once('error', reject);
devices.once('close', () => {
resolve();
});
});
let booted = false;
try {
const json = JSON.parse(stdout);
for (const device of Object.keys(json.devices)) {
for (const output of json.devices[device]) {
if (output.state === 'Booted') {
booted = true;
break;
}
}
}
} catch (err) {
debug(err);
}
return booted;
});
// let done = false;
const server = http.createServer((req, res) => {
pEvent(res, 'close').then(() => {
debug('end');
// done = true;
});
debug('request made');
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(html);
res.end();
});
const port = await getPort();
await new Promise((resolve, reject) => {
server.listen(port, (err) => {
if (err) return reject(err);
debug('server started');
resolve();
});
});
const emlFilePath = `${options.dir}/${options.id}.eml`;
await writeFile(emlFilePath, raw);
debug('emlFilePath', emlFilePath);
const xcrun = childProcess.spawn('xcrun', [
'simctl',
'openurl',
'booted',
emlFilePath
]);
await new Promise((resolve, reject) => {
xcrun.once('error', reject);
xcrun.once('close', (exitCode) => {
if (exitCode === 72)
return reject(
new Error(
`Could not open URL in booted Simulator; make sure Simulator is running.`
)
);
resolve(xcrun);
});
});
/*
const v = await cryptoRandomString({ length: 10, type: 'alphanumeric' });
const xcrun = childProcess.spawn('xcrun', [
'simctl',
'openurl',
'booted',
`http://127.0.0.1:${port}/?v=${v}#html`
]);
await new Promise((resolve, reject) => {
xcrun.once('error', reject);
xcrun.once('close', (exitCode) => {
if (exitCode === 72)
return reject(
new Error(
`Could not open URL in booted Simulator; make sure Simulator is running.`
)
);
resolve(xcrun);
});
});
await pWaitFor(() => done);
*/
// display notification
await displayNotification({
title: 'iOS Simulator Preview',
subtitle: 'Preview is ready!',
text: 'Open Simulator to preview and Safari Web Inspector to inspect.',
sound: 'Bottle'
});
await new Promise((resolve, reject) => {
server.close((err) => {
if (err) return reject(err);
resolve();
});
});
} catch (err) {
debug(err);
// display notification
await displayNotification({
title: 'iOS Simulator Preview',
subtitle: 'Preview emails on iOS',
text: err.message,
sound: 'Bottle'
});
}
}
return options.returnHTML ? html : url;
};
module.exports = previewEmail;