-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.js
99 lines (85 loc) · 2.63 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
const mjml2html = require('mjml');
const colors = require('colors');
const path = require('path');
const loaderUtils = require('loader-utils');
const fs = require('fs');
const crypto = require('crypto');
function getFileExtension(path) {
return path.split('.').pop();
}
module.exports = function(content) {
this.cacheable && this.cacheable();
this.value = content;
const config = loaderUtils.getOptions(this) || {
onlyHtml: false,
};
trackMjIncludeChanges.bind(this)(content);
let result = {};
try {
result = mjml2html(content, { level: 'soft', filePath: this.resourcePath });
} catch (e) {
result.html = displayErrors.bind(this)(e);
}
if (result.errors && result.errors.length) {
result.html = displayErrors.bind(this)(result.errors);
}
const mod = prepareSrc.bind(this)(result.html || '', config);
return `module.exports = ${JSON.stringify(mod)};`;
};
function displayErrors(errors) {
if (!Array.isArray(errors)) errors = [errors];
let htmlErr = [];
console.log(colors.red(`[mjml-with-images-loader] ERROR in ${this.resourcePath}:`));
htmlErr.push(`File: ${this.resourcePath}`);
errors.forEach(e => {
const msg = `- ${e.formattedMessage ? e.formattedMessage : e.message}`;
htmlErr.push(msg);
console.log(msg);
});
return htmlErr.join('<br />');
}
function prepareSrc(html, config) {
const images = {};
// find relative paths in src=""
const re = /(src="((?:\.|\.\.)\/.*?)")/gi;
let match;
while ((match = re.exec(html))) {
const imgPath = path.normalize(`${this.context}/${match[2]}`);
const imgExt = getFileExtension(imgPath);
this.addDependency(imgPath);
let imageBase64;
try {
imageBase64 = `data:image/${imgExt};base64,${fs.readFileSync(imgPath).toString('base64')}`;
} catch (e) {
html = displayErrors.bind(this)(e);
}
if (config.onlyHtml) {
html = html.replace(match[1], `src="${imageBase64}"`);
} else {
const cid = crypto.createHash('md5').update(imageBase64).digest('hex');
html = html.replace(match[1], `src="cid:${cid}"`);
images[cid] = {
filename: `${cid}.${imgExt}`,
path: imageBase64,
cid: cid,
};
}
}
if (config.onlyHtml) {
return html;
} else {
return {
html: html,
attachments: Object.keys(images).map(k => images[k]),
};
}
}
function trackMjIncludeChanges(html) {
// <mj-include path="./src/mailer/_shared/header.mjml" />
const re = /(mj-include path="((?:\.|\.\.)\/.*?)")/gi;
let match;
while ((match = re.exec(html))) {
const imgPath = path.normalize(`${this.context}/${match[2]}`);
this.addDependency(imgPath);
}
}