forked from mjmlio/gulp-mjml
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
79 lines (64 loc) · 1.83 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
var through = require ('through2')
var mjmlDefaultEngine = require ('mjml')
var gutil = require ('gulp-util')
var GulpError = gutil.PluginError
var NAME = 'MJML'
function error (file) {
return function (message) {
return new GulpError(
NAME,
'Error in file ' + file + ': ' + message
)
}
}
function html2cshtml (s) {
return newLineAfterModel(replaceCssDirectives(s))
}
function replaceCssDirectives (s) {
var regex = /<style[^>]*>([^<]*)<\/style>/g
return s.replace(regex, function (match) {
return match.replace(/@/g, '@@')
})
}
function newLineAfterModel (s) {
var regex = /@model [a-zA-Z\.]*/g
return s.replace(regex, function (match) {
return match + "\n"
})
}
module.exports = function mjml (mjmlEngine, options) {
if(!mjmlEngine) {
mjmlEngine = mjmlDefaultEngine
}
if (options === undefined) {
options = {}
}
return through.obj(function (file, enc, callback) {
// Not a big fan of this deep copy methods
// But it will work regardless of Node version
var localOptions = JSON.parse(JSON.stringify(options))
if (localOptions.filePath === undefined) {
localOptions.filePath = file.path.toString()
}
const raise = error(localOptions.filePath)
if (file.isStream()) {
this.emit('error', raise('Streams are not supported!'))
return callback()
}
if (file.isBuffer()) {
var output = file.clone()
var render
try {
render = mjmlEngine.mjml2html(file.contents.toString(), localOptions)
render.cshtml = html2cshtml(render.html)
} catch (e) {
this.emit('error', raise(e.message))
return callback()
}
output.contents = new Buffer(render.cshtml)
output.path = gutil.replaceExtension(file.path.toString(), '.cshtml')
this.push(output)
}
return callback()
})
}