UNPKG

1.79 kBJavaScriptView Raw
1'use strict';
2
3var convert = require('convert-source-map')
4 , path = require('path')
5 , fs = require('fs')
6 , through = require('through2');
7
8function separate(src, file, root, url) {
9 var inlined = convert.fromSource(src);
10
11 if (!inlined) return null;
12
13 var json = inlined
14 .setProperty('sourceRoot', root || '')
15 .toJSON(2);
16
17 url = url || path.basename(file);
18
19 var newSrc = convert.removeComments(src);
20 var comment = '//# sourceMappingURL=' + url;
21
22 return { json: json, src: newSrc + '\n' + comment }
23}
24
25var go = module.exports =
26
27/**
28 * Transforms the incoming stream of code by removing the inlined source map and writing it to an external map file.
29 * Additionally it adds a source map url that points to the extracted map file.
30 *
31 * @name exorcist
32 * @function
33 * @param {String} file full path to the map file to which to write the extracted source map
34 * @param {String=} url allows overriding the url at which the map file is found (default: name of map file)
35 * @param {String=} root allows adjusting the source maps `sourceRoot` field (default: '')
36 * @return {TransformStream} transform stream into which to pipe the code containing the source map
37 */
38function exorcist(file, url, root) {
39 var src = '';
40
41 function ondata(d, _, cb) { src += d; cb(); }
42 function onend(cb) {
43 var self = this;
44 var separated = separate(src, file, root, url);
45 if (!separated) {
46 self.emit(
47 'missing-map'
48 , 'The code that you piped into exorcist contains no source map!\n'
49 + 'Therefore it was piped through as is and no external map file generated.'
50 );
51 self.push(src);
52 return cb();
53 }
54 self.push(separated.src);
55 fs.writeFile(file, separated.json, 'utf8', cb)
56 }
57
58 return through(ondata, onend);
59}