forked from simonbuchan/bindings-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
75 lines (62 loc) · 2.01 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
const path = require("path");
const vm = require("vm");
const { promisify } = require("util");
const { getOptions } = require("loader-utils");
const {
OriginalSource,
SourceMapSource,
ReplaceSource,
} = require("webpack-sources");
module.exports = function(source, map, meta) {
// Using exec() in parallel, so we need separate RegExp instances.
// That means don't "optimize" this by moving this to the global scope!
const pattern = /\brequire\((?:'bindings'|"bindings")\)\s*\(([^)]*)\)/g;
let match = pattern.exec(source);
if (!match) {
return this.callback(null, source, map, meta);
}
const options = getOptions(this) || {};
const resolve = promisify(this.resolve).bind(this, this.context);
const readFile = promisify(this.fs.readFile).bind(this.fs);
const callback = this.async();
(async () => {
const bindings = require(await resolve("bindings"));
const replaceSource = new ReplaceSource(
map
? new SourceMapSource(source, this.resourcePath, map)
: new OriginalSource(source, this.resourcePath),
);
do {
// Safer eval().
let arg = vm.runInNewContext(match[1]);
if (typeof arg === "string") {
arg = { bindings: arg };
}
const forPath = !!arg.path;
arg.path = true;
arg.module_root = arg.module_root
? await resolve(arg.module_root)
: bindings.getRoot(this.resourcePath);
const addonPath = bindings(arg);
const addonRequest = `./${path.basename(addonPath)}`;
const addonContent = await readFile(addonPath);
this.emitFile(addonRequest, addonContent);
replaceSource.replace(
match.index,
pattern.lastIndex,
forPath
? JSON.stringify(addonRequest)
: `require(${JSON.stringify(addonRequest)})`,
);
match = pattern.exec(source);
} while (match);
return replaceSource.sourceAndMap();
})().then(
result => {
callback(null, result.source, result.map);
},
err => {
callback(err);
},
);
};