forked from alexsaves/gulp-jsonp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
105 lines (90 loc) · 2.65 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
'use strict';
var through = require('through2');
var rs = require('replacestream');
var istextorbinary = require('istextorbinary');
var btoa = require('btoa'),
Path = require('path');
/**
* Extract path information
* @param path
* @returns {{dirname: *, basename: *, extname: *}}
*/
function parsePath(path) {
var extname = Path.extname(path);
return {
dirname: Path.dirname(path),
basename: Path.basename(path, extname),
extname: extname
};
}
/**
* Find the last index of a regex within a string
* @param str
* @param regex
* @param startpos
* @returns {number}
*/
var regexLastIndexOf = function (str, regex, startpos) {
regex = (regex.global) ? regex : new RegExp(regex.source, "g" + (regex.ignoreCase ? "i" : "") + (regex.multiLine ? "m" : ""));
if (typeof (startpos) == "undefined") {
startpos = str.length;
} else if (startpos < 0) {
startpos = 0;
}
var stringToWorkWith = str.substring(0, startpos + 1);
var lastIndexOf = -1;
var nextStop = 0;
var result;
while ((result = regex.exec(stringToWorkWith)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
};
module.exports = function (config) {
config.skipBinary = true;
var doReplace = function (file, enc, callback) {
if (file.isNull()) {
return callback(null, file);
}
function doReplace() {
if (file.isStream()) {
file.contents = file.contents.pipe(rs(search, replacement));
return callback(null, file);
}
if (file.isBuffer()) {
var pchar = '/';
if (file.path.toString().indexOf('\\') > -1) {
pchar = '\\';
}
var parsedPath = parsePath(file.relative),
cnts = String(file.contents),
fname = file.path.substr(file.path.lastIndexOf(pchar) + 1);
var resobj = {
filename: (config.key ? config.key : "" ) + fname,
contents: btoa(cnts)
};
var path = file.path.substr(0, file.path.lastIndexOf(pchar) + 1) + Path.join(parsedPath.dirname, parsedPath.basename + parsedPath.extname.replace(/\./gi, '___') + '.js');
file.path = path;
file.contents = new Buffer(config.callback + '(' + JSON.stringify(resobj) + ');');
return callback(null, file);
}
callback(null, file);
}
if (config && config.skipBinary) {
istextorbinary.isText('', file.contents, function (err, result) {
if (err) {
return callback(err, file);
}
if (!result) {
callback(null, file);
} else {
doReplace();
}
});
return;
}
doReplace();
};
return through.obj(doReplace);
};