1 | 'use strict';
|
2 | const path = require('path');
|
3 | const js = require('default-require-extensions/js');
|
4 |
|
5 | module.exports = appendTransform;
|
6 |
|
7 | let count = 0;
|
8 |
|
9 |
|
10 | function appendTransform(transform, ext = '.js', extensions = require.extensions) {
|
11 |
|
12 | const key = path.join(__dirname, count.toString());
|
13 | count++;
|
14 |
|
15 | let forwardGet;
|
16 | let forwardSet;
|
17 |
|
18 | const descriptor = Object.getOwnPropertyDescriptor(extensions, ext) || {value: js, configurable: true};
|
19 |
|
20 | if (
|
21 | ((descriptor.get || descriptor.set) && !(descriptor.get && descriptor.set)) ||
|
22 | !descriptor.configurable
|
23 | ) {
|
24 | throw new Error('Somebody did bad things to require.extensions["' + ext + '"]');
|
25 | }
|
26 |
|
27 | if (descriptor.get) {
|
28 |
|
29 | forwardGet = function () {
|
30 | return descriptor.get();
|
31 | };
|
32 |
|
33 | forwardSet = function (val) {
|
34 | descriptor.set(val);
|
35 | return forwardGet();
|
36 | };
|
37 | } else {
|
38 | forwardGet = function () {
|
39 | return descriptor.value;
|
40 | };
|
41 |
|
42 | forwardSet = function (val) {
|
43 | descriptor.value = val;
|
44 | return val;
|
45 | };
|
46 | }
|
47 |
|
48 | function wrapCustomHook(hook) {
|
49 | return function (module, filename) {
|
50 |
|
51 | if (!module[key]) {
|
52 | module[key] = true;
|
53 |
|
54 | const originalCompile = module._compile;
|
55 |
|
56 |
|
57 | module._compile = function replacementCompile(code, filename) {
|
58 | module._compile = originalCompile;
|
59 | code = transform(code, filename);
|
60 | module._compile(code, filename);
|
61 | };
|
62 | }
|
63 |
|
64 | hook(module, filename);
|
65 | };
|
66 | }
|
67 |
|
68 |
|
69 | forwardSet(wrapCustomHook(forwardGet()));
|
70 |
|
71 | const hooks = [forwardGet()];
|
72 |
|
73 | function setCurrentHook(hook) {
|
74 | const restoreIndex = hooks.indexOf(hook);
|
75 |
|
76 | if (restoreIndex === -1) {
|
77 | hooks.push(forwardSet(wrapCustomHook(hook)));
|
78 | } else {
|
79 |
|
80 | hooks.splice(restoreIndex + 1, hooks.length);
|
81 | forwardSet(hook);
|
82 | }
|
83 | }
|
84 |
|
85 | Object.defineProperty(extensions, ext, {
|
86 | configurable: true,
|
87 | enumerable: true,
|
88 | get: forwardGet,
|
89 | set: setCurrentHook
|
90 | });
|
91 | }
|