UNPKG

1.51 kBJavaScriptView Raw
1/*
2 MIT License http://www.opensource.org/licenses/mit-license.php
3 Author Tobias Koppers @sokra
4*/
5var baseRegex = "\\s*[@#]\\s*sourceMappingURL=data:[^;\n]+;base64,([^\\s]*)",
6 // Matches /* ... */ comments
7 regex1 = new RegExp("/\\*"+baseRegex+"\\s*\\*/$"),
8 // Matches // .... comments
9 regex2 = new RegExp("//"+baseRegex+".*$");
10module.exports = function(input) {
11 if(!this.query) throw new Error("Pass a module name as query to the transform-loader.");
12 var callback = this.async();
13 var resource = this.resource;
14 var loaderContext = this;
15 var q = this.query.substr(1);
16 if(/^[0-9]+$/.test(q)) {
17 next(this.options.transforms[+q]);
18 } else {
19 this.resolve(this.context, q, function(err, module) {
20 if(err) return callback(err);
21 next(require(module));
22 });
23 }
24 function next(transformFn) {
25 var stream = transformFn(resource);
26 var bufs = [];
27 var done = false;
28 stream.on("data", function(b) {
29 bufs.push(b);
30 });
31 stream.on("end", function() {
32 if(done) return;
33 var b = Buffer.concat(bufs).toString();
34 var match = b.match(regex1) || b.match(regex2);
35 try {
36 var map = match && JSON.parse((new Buffer(match[1], "base64")).toString());
37 } catch(e) {
38 var map = null;
39 }
40 done = true;
41 callback(null, map ? b.replace(match[0], "") : b, map);
42 });
43 stream.on("error", function(err) {
44 if(done) return;
45 done = true;
46 callback(err);
47 });
48 stream.write(input);
49 stream.end();
50 }
51};
52module.exports.raw = true;