@ohos-ports/babel-plugin-rewire-ts 0.0.0-stage → 1.4.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.babelrc +4 -0
- package/README.md +563 -3
- package/lib/RewireHelpers.js +38 -0
- package/lib/RewireState.js +276 -0
- package/lib/Templates.js +27 -0
- package/lib/babel-plugin-rewire.js +257 -0
- package/package.json +81 -4
package/.babelrc
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,563 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
This
|
|
1
|
+
# babel-plugin-rewire-ts
|
|
2
|
+
|
|
3
|
+
This is a fork of https://github.com/speedskater/babel-plugin-rewire which adds TypeScript compatibility. I will happily accept any contributions which further improve the support.
|
|
4
|
+
|
|
5
|
+
A Babel plugin that adds the ability to rewire module dependencies.
|
|
6
|
+
|
|
7
|
+
[](https://travis-ci.org/rosswarren/babel-plugin-rewire-ts)
|
|
8
|
+
|
|
9
|
+
It is inspired by [rewire.js](https://github.com/jhnns/rewire) and transfers its concepts to es6 using babel.
|
|
10
|
+
|
|
11
|
+
It is useful for writing tests, specifically to mock the dependencies of the module under test.
|
|
12
|
+
|
|
13
|
+
Therefore for each module it adds and exports the methods `__GetDependency__`, `__Rewire__`, and `__ResetDependency__`.
|
|
14
|
+
For compatibility reasons with rewire.js, the methods `__get__` and `__set__` are exported as well.
|
|
15
|
+
From version 1.0.0-rc-7 on calls to `__set__` will return a revert function like rewire.js.
|
|
16
|
+
|
|
17
|
+
These methods allow you to rewire the module under test.
|
|
18
|
+
Furthermore in case of a default export these methods are assigned to the existing default export, except for default exports of primitive types (boolean, number, string, ...).
|
|
19
|
+
|
|
20
|
+
An additional object named `__RewireAPI__` is exported as named export as well as a property of the default export. This object itself contains all the functions mentioned above as fields. This enables one to rewire members of the imported module itself without explicitly importing the module (see [Handling of default exports](#handling-of-default-exports) below).
|
|
21
|
+
|
|
22
|
+
## ES6 Imports and React
|
|
23
|
+
|
|
24
|
+
Dependencies from import statements can be rewired
|
|
25
|
+
|
|
26
|
+
### Example
|
|
27
|
+
|
|
28
|
+
```javascript
|
|
29
|
+
import ChildComponent from "child-component-module";
|
|
30
|
+
|
|
31
|
+
export default class MyFancyWrapperComponent extends React.Component {
|
|
32
|
+
render() {
|
|
33
|
+
return (
|
|
34
|
+
<div className="wrapper-style">
|
|
35
|
+
<ChildComponent {...this.props} />
|
|
36
|
+
</div>
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Test Code
|
|
43
|
+
|
|
44
|
+
```javascript
|
|
45
|
+
import ComponentToTest from 'my-fancy-wrapper-component-module';
|
|
46
|
+
|
|
47
|
+
ComponentToTest.__Rewire__('ChildComponent', React.createClass({
|
|
48
|
+
render: function() { return <div {...this.props}></div>; }
|
|
49
|
+
}));
|
|
50
|
+
....
|
|
51
|
+
|
|
52
|
+
ComponentToTest.__ResetDependency__('ChildComponent');
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Node/browserify require() and top-level var support
|
|
56
|
+
|
|
57
|
+
Variables declared and initialised at the top level, such as those from require() calls, can be rewired
|
|
58
|
+
|
|
59
|
+
### Example
|
|
60
|
+
|
|
61
|
+
```javascript
|
|
62
|
+
var Path = require("path");
|
|
63
|
+
|
|
64
|
+
var env = "production";
|
|
65
|
+
|
|
66
|
+
module.exports = function(name) {
|
|
67
|
+
return Path.normalise(name);
|
|
68
|
+
};
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
### Test Code
|
|
72
|
+
|
|
73
|
+
```javascript
|
|
74
|
+
var Normaliser = require('Normaliser');
|
|
75
|
+
|
|
76
|
+
Normaliser.__Rewire__('Path', {
|
|
77
|
+
normalise: (name) => name;
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
Normaliser.__Rewire__('env', 'testing');
|
|
81
|
+
....
|
|
82
|
+
|
|
83
|
+
Normaliser.__ResetDependency__('Path');
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Named and top level function rewiring
|
|
87
|
+
|
|
88
|
+
Besides top level variables also top level functions defined in the imported module can be rewired.
|
|
89
|
+
|
|
90
|
+
When exported functions of a module depend on each other it can be convenient to test them independently.
|
|
91
|
+
Hence, babel-plugin-rewire allows you to rewire the internal dependencies to exported named functions as shown in the example below.
|
|
92
|
+
|
|
93
|
+
Be aware, that rewiring a named export does not influence imports of that same export in other modules!
|
|
94
|
+
|
|
95
|
+
### Example
|
|
96
|
+
|
|
97
|
+
Asuming you have a module `TodoOperations.js` that internaly uses an asynchronous api to fetch some information
|
|
98
|
+
|
|
99
|
+
```js
|
|
100
|
+
function fetchToDos() {
|
|
101
|
+
...
|
|
102
|
+
return new Promise(...);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function filterToDos( filterString ) {
|
|
106
|
+
return fetchToDos().then( function( todos ) {
|
|
107
|
+
// Highly fashioned filter function code ...
|
|
108
|
+
return filteredToDos;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function filterAndSortToDos( filterString, sortOrder ) {
|
|
113
|
+
return fetchToDos( filterString ).then( function( filteredToDos ) {
|
|
114
|
+
// Higly fashioned sort function
|
|
115
|
+
return filteredAndSortedToDos;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Test Code
|
|
121
|
+
|
|
122
|
+
In your test you can mock your API-calls to simply return static dummy data like this
|
|
123
|
+
|
|
124
|
+
```js
|
|
125
|
+
import { filterToDos, filterAndSortToDos, __RewireAPI__ as ToDosRewireAPI } from "TodoOperations.js";
|
|
126
|
+
|
|
127
|
+
describe("api call mocking", function() {
|
|
128
|
+
it("should use the mocked api function", function(done) {
|
|
129
|
+
ToDosRewireAPI.__Rewire__("fetchToDos", function() {
|
|
130
|
+
return Promise.resolve(["Test more", "Refine your tests", "Tests first rocks"]);
|
|
131
|
+
});
|
|
132
|
+
filterToDos("Test")
|
|
133
|
+
.then(function(filteredTodos) {
|
|
134
|
+
//check results
|
|
135
|
+
done();
|
|
136
|
+
})
|
|
137
|
+
.catch(e => fail());
|
|
138
|
+
ToDosRewireAPI.__ResetDependency__("fetchToDos");
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("should use the mocked filter function", function(done) {
|
|
142
|
+
ToDosRewireAPI.__Rewire__("filterToDos", function() {
|
|
143
|
+
return Promise.resolve(["02 Test more", "01 Test even more"]);
|
|
144
|
+
});
|
|
145
|
+
filterAndSortToDos("Test", "asc")
|
|
146
|
+
.then(function(filteredAndSortedTodos) {
|
|
147
|
+
//check results
|
|
148
|
+
done();
|
|
149
|
+
})
|
|
150
|
+
.catch(e => fail());
|
|
151
|
+
ToDosRewireAPI.__ResetDependency__("filterToDos");
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## Handling of default exports
|
|
157
|
+
|
|
158
|
+
If a non primitive default export is present in the imported module, it is enriched with the API-Functions and the API-Object.
|
|
159
|
+
If no default export is present, the API-Object named `__RewireAPI__` becomes the default export of the module.
|
|
160
|
+
|
|
161
|
+
This object basically supports all the rewire API-Functions as described in the introduction above and allows one to rewire the module without explicitly importing the module itself.
|
|
162
|
+
|
|
163
|
+
### Example
|
|
164
|
+
|
|
165
|
+
Asuming your imported module does not have a default export specified like in this simple example
|
|
166
|
+
|
|
167
|
+
```js
|
|
168
|
+
function message() {
|
|
169
|
+
return "Hello world";
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function foo() {
|
|
173
|
+
return message();
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### Test Code
|
|
178
|
+
|
|
179
|
+
In your test you would use the default exported API-Object to rewire the function `message` of the imported module like this
|
|
180
|
+
|
|
181
|
+
```js
|
|
182
|
+
import FooModule from "foo.js";
|
|
183
|
+
import { foo, __RewireAPI__ as FooModuleRewireAPI } from "foo.js";
|
|
184
|
+
|
|
185
|
+
describe("module default export test", function() {
|
|
186
|
+
it("should demonstrate the default exported rewire api", function() {
|
|
187
|
+
expect(foo()).to.equal("Hello world");
|
|
188
|
+
FooModule.__Rewire__("message", function() {
|
|
189
|
+
return "my message";
|
|
190
|
+
});
|
|
191
|
+
expect(foo()).to.equal("my message");
|
|
192
|
+
FooModule.__ResetDependency__("message");
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it("should demonstrate the rewire apis named export", function() {
|
|
196
|
+
expect(foo()).to.equal("Hello world");
|
|
197
|
+
FooModuleRewireAPI.__Rewire__("message", function() {
|
|
198
|
+
return "my message";
|
|
199
|
+
});
|
|
200
|
+
expect(foo()).to.equal("my message");
|
|
201
|
+
FooModuleRewireAPI.__ResetDependency__("message");
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
## Handling of async functions
|
|
207
|
+
|
|
208
|
+
Rewiring of async functions works as one would expect using the same API as for other rewires for both default exports and named exports.
|
|
209
|
+
|
|
210
|
+
### Example
|
|
211
|
+
|
|
212
|
+
Assuming your imported module consists of the following.
|
|
213
|
+
|
|
214
|
+
```js
|
|
215
|
+
// api.js
|
|
216
|
+
export default async function asyncApiDefault() {
|
|
217
|
+
return await asyncApi();
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export async function asyncApi() {
|
|
221
|
+
return await api();
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function api() {
|
|
225
|
+
// Some async API call
|
|
226
|
+
return Promise.resolve("API Response");
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
### Test Code
|
|
231
|
+
|
|
232
|
+
In your test you would use the default exported API-Object to rewire the function `asyncApiDefault` and `asyncApi` of the imported module like this.
|
|
233
|
+
|
|
234
|
+
```js
|
|
235
|
+
import { default as asyncApiDefault, asyncApi, __RewireAPI__ as AsyncApiRewireAPI } from "api.js";
|
|
236
|
+
describe("async function export test", function() {
|
|
237
|
+
it("should be able to rewire default async function", function() {
|
|
238
|
+
return asyncApiDefault().then(response => {
|
|
239
|
+
expect(response).to.equal("API Response");
|
|
240
|
+
|
|
241
|
+
AsyncApiRewireAPI.__set__("asyncApi", function() {
|
|
242
|
+
return Promise.resolve("Mock API Response");
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
return asyncApiDefault().then(response => {
|
|
246
|
+
expect(response).to.equal("Mock API Response");
|
|
247
|
+
AsyncApiRewireAPI.__ResetDependency__("asyncApi");
|
|
248
|
+
});
|
|
249
|
+
});
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it("should be able to rewire non default async function", function() {
|
|
253
|
+
return asyncApi().then(response => {
|
|
254
|
+
expect(response).to.equal("API Response");
|
|
255
|
+
|
|
256
|
+
AsyncApiRewireAPI.__set__("api", function() {
|
|
257
|
+
return Promise.resolve("Mock API Response");
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
return asyncApi().then(response => {
|
|
261
|
+
expect(response).to.equal("Mock API Response");
|
|
262
|
+
AsyncApiRewireAPI.__ResetDependency__("api");
|
|
263
|
+
});
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
});
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
## Resetting all
|
|
270
|
+
|
|
271
|
+
When "babel-plugin-rewire" is used the global method `__rewire_reset_all__` is added.
|
|
272
|
+
Each time this method is called all rewired dependencies across all modules are reset.
|
|
273
|
+
|
|
274
|
+
### Example
|
|
275
|
+
|
|
276
|
+
Assuming you have two imported modules:
|
|
277
|
+
|
|
278
|
+
Module1:
|
|
279
|
+
|
|
280
|
+
```js
|
|
281
|
+
var value = "Module1-Original";
|
|
282
|
+
|
|
283
|
+
export default function getModule2Identifier() {
|
|
284
|
+
return value;
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
Module2:
|
|
289
|
+
|
|
290
|
+
```
|
|
291
|
+
var value = 'Module2-Original';
|
|
292
|
+
|
|
293
|
+
export default function getModule2Identifier() {
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
### Test Code
|
|
299
|
+
|
|
300
|
+
In your test by calling `__rewire_reset_all__` all dependencies are reset and you can ensure that no rewired data will harm subsequent tests.
|
|
301
|
+
|
|
302
|
+
```js
|
|
303
|
+
import getModule1Identifier from "./src/Module1.js";
|
|
304
|
+
import getModule2Identifier from "./src/Module2.js";
|
|
305
|
+
|
|
306
|
+
import expect from "expect.js";
|
|
307
|
+
|
|
308
|
+
describe("__rewire_reset_all__", function() {
|
|
309
|
+
it("should allow to reset all rewired dependencies", function() {
|
|
310
|
+
expect(getModule1Identifier()).to.be("Module1-Original");
|
|
311
|
+
expect(getModule2Identifier()).to.be("Module2-Original");
|
|
312
|
+
|
|
313
|
+
getModule1Identifier.__set__("value", "module1-rewired");
|
|
314
|
+
getModule2Identifier.__set__("value", "module2-rewired");
|
|
315
|
+
|
|
316
|
+
expect(getModule1Identifier()).to.be("module1-rewired");
|
|
317
|
+
expect(getModule2Identifier()).to.be("module2-rewired");
|
|
318
|
+
|
|
319
|
+
__rewire_reset_all__();
|
|
320
|
+
|
|
321
|
+
expect(getModule1Identifier()).to.be("Module1-Original");
|
|
322
|
+
expect(getModule2Identifier()).to.be("Module2-Original");
|
|
323
|
+
});
|
|
324
|
+
});
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
## Installation
|
|
328
|
+
|
|
329
|
+
```
|
|
330
|
+
$ npm install babel-core babel-plugin-rewire
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
## Usage
|
|
334
|
+
|
|
335
|
+
To use the plugin identify it by its long name "babel-plugin-rewire-ts" or by its abbreviation
|
|
336
|
+
"rewire-ts".
|
|
337
|
+
|
|
338
|
+
If you are using `@babel/plugin-tranform-typescript` and encounter these warnings:
|
|
339
|
+
```
|
|
340
|
+
The exported identifier "_get__" is not declared in Babel's scope tracker
|
|
341
|
+
as a JavaScript value binding, and "@babel/plugin-transform-typescript"
|
|
342
|
+
never encountered it as a TypeScript type declaration.
|
|
343
|
+
It will be treated as a JavaScript value.
|
|
344
|
+
...
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
We recommend you switch to `@babel/preset-typescript`, since it type-checks
|
|
348
|
+
your code while the plugin does not. Or use `@babel/preset-env` along with
|
|
349
|
+
the plugin to resolve those warnings. We already fixed the issue on our side
|
|
350
|
+
and reason behind those warning is unclear and they are harmless.
|
|
351
|
+
|
|
352
|
+
### Commandline
|
|
353
|
+
|
|
354
|
+
abbreviated:
|
|
355
|
+
|
|
356
|
+
```
|
|
357
|
+
$ babel --plugins rewire ..
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
full plugin name:
|
|
361
|
+
|
|
362
|
+
```
|
|
363
|
+
$ babel --plugins babel-plugin-rewire ..
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
### With babelrc
|
|
367
|
+
|
|
368
|
+
You can also specify plugins via the [babelrc](http://babeljs.io/docs/usage/babelrc/) file:
|
|
369
|
+
|
|
370
|
+
```json
|
|
371
|
+
{
|
|
372
|
+
"plugins": ["rewire"]
|
|
373
|
+
}
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
Whether you're using the command line, JS API, or require hook, this file is honored by babel.
|
|
377
|
+
|
|
378
|
+
### JavaScript API
|
|
379
|
+
|
|
380
|
+
abbreviated:
|
|
381
|
+
|
|
382
|
+
```javascript
|
|
383
|
+
require("babel-core").transform("code", { plugins: ["rewire"] });
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
full plugin name:
|
|
387
|
+
|
|
388
|
+
```javascript
|
|
389
|
+
require("babel-core").transform("code", { plugins: ["babel-plugin-rewire"] });
|
|
390
|
+
```
|
|
391
|
+
|
|
392
|
+
### Require Hook
|
|
393
|
+
|
|
394
|
+
```javascript
|
|
395
|
+
require("babel-register")({
|
|
396
|
+
plugins: ["babel-plugin-rewire"]
|
|
397
|
+
});
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
### Webpack
|
|
401
|
+
|
|
402
|
+
abbreviated:
|
|
403
|
+
|
|
404
|
+
```javascript
|
|
405
|
+
{test: /src\/js\/.+\.js$/, loader: 'babel-loader?plugins=rewire' }
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
full plugin name:
|
|
409
|
+
|
|
410
|
+
```javascript
|
|
411
|
+
{test: /src\/js\/.+\.js$/, loader: 'babel-loader?plugins=babel-plugin-rewire' }
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
### Browserify/Babelify
|
|
415
|
+
|
|
416
|
+
full plugin name:
|
|
417
|
+
|
|
418
|
+
```javascript
|
|
419
|
+
var appBundler = browserify({
|
|
420
|
+
entries: [test.src] // Only need initial file, browserify finds the rest
|
|
421
|
+
}).transform(
|
|
422
|
+
babelify.configure({
|
|
423
|
+
plugins: [require("babel-plugin-rewire")]
|
|
424
|
+
})
|
|
425
|
+
);
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
## Combining with other plugins/tools
|
|
429
|
+
|
|
430
|
+
### istanbul
|
|
431
|
+
|
|
432
|
+
To integrate babel-plugin-rewire with istanbul, it is recommended to use [babel-plugin-istanbul](https://github.com/istanbuljs/babel-plugin-istanbul).
|
|
433
|
+
This babel plugin instruments your code with Istanbul coverage.
|
|
434
|
+
|
|
435
|
+
It has been reported that the order of plugins are important. Therefore prefer the following order:
|
|
436
|
+
|
|
437
|
+
```json
|
|
438
|
+
{
|
|
439
|
+
"plugins": ["istanbul", "rewire"]
|
|
440
|
+
}
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
For a project integrating karma, babel, babel-plugin-rewire and istanbul please see [karma-rewire-istanbul-example](https://github.com/jseminck/karma-rewire-istanbul-example)
|
|
444
|
+
|
|
445
|
+
### [isparta](https://github.com/douglasduteil/isparta)
|
|
446
|
+
|
|
447
|
+
There are some things to consider when using babel-plugin-rewire together with isparta. Since isparta runs Babel itself it's important to remember to add the same configuration options to it as you would do with Babel. If you forget this you will in some cases see unexpected errors.
|
|
448
|
+
|
|
449
|
+
If you use _.babelrc_ it's advised that you run your tests with a specific ENV, for example "test", and add the following to your _.babelrc_.
|
|
450
|
+
Furthermore in case you use isparta only add the plugin once in the isparta loader and not in the babel loader as well.
|
|
451
|
+
|
|
452
|
+
```json
|
|
453
|
+
"env": {
|
|
454
|
+
"test": {
|
|
455
|
+
"plugins": ["rewire"]
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
```
|
|
459
|
+
|
|
460
|
+
If you are using isparta together with Webpack you could also do something like this.
|
|
461
|
+
|
|
462
|
+
```javascript
|
|
463
|
+
webpack: {
|
|
464
|
+
isparta: {
|
|
465
|
+
embedSource: true,
|
|
466
|
+
noAutoWrap: true,
|
|
467
|
+
babel: {
|
|
468
|
+
plugins: 'rewire'
|
|
469
|
+
}
|
|
470
|
+
},
|
|
471
|
+
preLoaders: [
|
|
472
|
+
...
|
|
473
|
+
{
|
|
474
|
+
test: /\.js$/,
|
|
475
|
+
include: path.resolve('src/'), //only source under test
|
|
476
|
+
loader: 'isparta'
|
|
477
|
+
},
|
|
478
|
+
]
|
|
479
|
+
...
|
|
480
|
+
}
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
## Examples projects
|
|
484
|
+
|
|
485
|
+
- [es6-library-boilerplate](https://github.com/CurtisHumphrey/es6-library-boilerplate)
|
|
486
|
+
|
|
487
|
+
## Release History
|
|
488
|
+
|
|
489
|
+
- 0.1.0 Initial release
|
|
490
|
+
- 0.1.1 Bugfix: moved to peer dependencies
|
|
491
|
+
- 0.1.2 Added \_\_set\_\_ and \_\_get\_\_ to provide compatibility with rewire.js
|
|
492
|
+
- 0.1.3 Added handling for the export of named declarations like classes or functions
|
|
493
|
+
- 0.1.4 Fixed variable handling and used renaming of scope variables. Further removed global identifiers to prevent memory leaks.
|
|
494
|
+
- 0.1.5 Fixed regression
|
|
495
|
+
- 0.1.6 Support for rewiring top level variables. Added module.exports for non-es6 modules.
|
|
496
|
+
- 0.1.7 Fixed regressions from 0.1.6.
|
|
497
|
+
- 0.1.8 Ignores destructuring assignments to prevent errors.
|
|
498
|
+
- 0.1.9 Removed issues with TDZ and es6.spec.blockScoping optional transformer.
|
|
499
|
+
- 0.1.10 Fixed tests.
|
|
500
|
+
- 0.1.11 Fixed issues with for-of loops.
|
|
501
|
+
- 0.1.12 Updated Plugin Format.
|
|
502
|
+
- 0.1.13 Changed rewire specific properties on default export to non-enumerable properties.
|
|
503
|
+
- 0.1.14 Added handling for non-enumerable properties to commonjs support. Support for mixed es6 and commonjs support. Handling for primitive types.
|
|
504
|
+
- 0.1.15 Added functionality to rewire functions.
|
|
505
|
+
- 0.1.16 Fixed variable scope for rewired functions.
|
|
506
|
+
- 0.1.17 Fixed variable scoping for var variable declarations.
|
|
507
|
+
- 0.1.18 Fixed function scope for rewired functions.
|
|
508
|
+
- 0.1.19 Removed debug statements.
|
|
509
|
+
- 0.1.20 Added rewiring named exported functions and variables.
|
|
510
|
+
- 0.1.21 Improved default export handling, fixed commonjs default exporting, fixed ast nodes resource leaks, improved README.
|
|
511
|
+
- 0.1.22 Added support for asynchronous functions
|
|
512
|
+
- 0.1.23-beta Improved flow compatibility, Added functionality to work with cyclic dependencies.
|
|
513
|
+
- 1.0.0-beta-1 Added support for babel 6, added support for rewiring classes, added support for flow types, added support for rewire.js compatible \_\_with\_\_
|
|
514
|
+
- 1.0.0-beta-2 Removed rewire of Object, require
|
|
515
|
+
- 1.0.0-beta-3 Removed support for rewiring of globals. Added support for rewiring in combination with assignment and update expressions.
|
|
516
|
+
- 1.0.0-beta-4 Updates jsx support in combination with babel 6 but has a regression
|
|
517
|
+
- 1.0.0-beta-5 Fixes rewiring of jsx elements. Readme improvements. Test for pass-through like modules.
|
|
518
|
+
- 1.0.0-rc-1 Fixes rewiring of switch statements. Readme improvements. Wildcard imports and tdz issues.
|
|
519
|
+
- 1.0.0-rc-2 Fixes issues with babelify, React stateless functions as well as flow declarations.
|
|
520
|
+
- 1.0.0-rc-3 Added support for ignoring identifiers and support for objects as parameter to \_\_set\_\_
|
|
521
|
+
- 1.0.0-rc-4 Support for rewiring to undefined, suppport for should.js and cleaned up package.json.
|
|
522
|
+
- 1.0.0-rc-5 Improved support for rewiring JSX-Components. Further improved for working in combination with other plugins.
|
|
523
|
+
- 1.0.0-rc-6 Fixed regression which can occur with variable declarators and function expressions. Fixed handling of default exports containing nested functions.
|
|
524
|
+
- 1.0.0-rc-7 Added revert function as a return of \_\_set\_\_ calls.
|
|
525
|
+
- 1.0.0 Fixed regression with object methods and improved istanbul documentation.
|
|
526
|
+
- 1.2.0-rc.1 Add support for babel 7, object spread and revert function from \_\_set\_\_ with object and fixes undefined variable error
|
|
527
|
+
|
|
528
|
+
## Contributors
|
|
529
|
+
|
|
530
|
+
- [speedskater](https://github.com/speedskater) - author and creator of initial release
|
|
531
|
+
- [Peet](https://github.com/peet) - module.exports and top-level var support
|
|
532
|
+
- [TheSavior](https://github.com/TheSavior) - support for non-enumerable rewire properties, support for ignored identifiers
|
|
533
|
+
- [Rene Saarsoo](https://github.com/nene) - support for using objects as parameter to \_\_set\_\_
|
|
534
|
+
- [PSpSynedra](https://github.com/PSpSynedra) - support for named export and function rewiring and improvements of default imports
|
|
535
|
+
- [Gustaf Dalemar](https://github.com/DLMR) - support for asynchronous functions
|
|
536
|
+
- [Spencre Leichty](https://github.com/spncrlkt) - support for named wildcard exports
|
|
537
|
+
- [Zhanzhan He](https://github.com/zh3) - support for wildcard imports
|
|
538
|
+
- [Kelly Selden](https://github.com/kellyselden) - fixed dependencies in package.json
|
|
539
|
+
- [Sasha Koss](https://github.com/kossnocorp) - support for rewiring to undefined
|
|
540
|
+
- [Kevin Canévet](https://github.com/StyMaar) - fixed incompatibility with should
|
|
541
|
+
- [Mike Sherov](https://github.com/mikesherov) - added support for for in loops
|
|
542
|
+
- [Thomas Levy](https://github.com/NilSet) - added support for babel 7
|
|
543
|
+
- [Malthe Jørgensen](https://github.com/malthejorgensen) - added support for object spread
|
|
544
|
+
- [Tim Whitbeck](https://github.com/twhitbeck) - added revert function from \_\_set\_\_ with object
|
|
545
|
+
- [Dennis E](https://github.com/destenson) - fixed undefined \_\_\$\$GLOBAL_REWIRE_REGISTRY\_\_ error
|
|
546
|
+
|
|
547
|
+
## License
|
|
548
|
+
|
|
549
|
+
The ISC License (ISC)
|
|
550
|
+
|
|
551
|
+
Copyright (c) 2015, Robert Binna <r.binna@synedra.com>
|
|
552
|
+
|
|
553
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
554
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
555
|
+
copyright notice and this permission notice appear in all copies.
|
|
556
|
+
|
|
557
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
558
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
559
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
560
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
561
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
562
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
563
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.wasProcessed = wasProcessed;
|
|
7
|
+
exports.noRewire = noRewire;
|
|
8
|
+
exports.contains = contains;
|
|
9
|
+
/*Copyright (c) 2015, Robert Binna <r.binna@synedra.com>
|
|
10
|
+
|
|
11
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
12
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
13
|
+
copyright notice and this permission notice appear in all copies.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
16
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
17
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
18
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
19
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
20
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
21
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.*/
|
|
22
|
+
|
|
23
|
+
function wasProcessed(path) {
|
|
24
|
+
return path.node.__noRewire === true;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function noRewire(identifier) {
|
|
28
|
+
identifier.__noRewire = true;
|
|
29
|
+
return identifier;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function contains(array, needle) {
|
|
33
|
+
var contains = false;
|
|
34
|
+
for (var i = 0; i < array.length; ++i) {
|
|
35
|
+
contains = contains || array[i] == needle;
|
|
36
|
+
}
|
|
37
|
+
return contains;
|
|
38
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
|
|
7
|
+
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); /*Copyright (c) 2015, Robert Binna <r.binna@synedra.com>
|
|
8
|
+
|
|
9
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
10
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
11
|
+
copyright notice and this permission notice appear in all copies.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED 'AS IS' AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
14
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
15
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
16
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
17
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
18
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
19
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.*/
|
|
20
|
+
|
|
21
|
+
var _Templates = require('./Templates.js');
|
|
22
|
+
|
|
23
|
+
var _Templates2 = _interopRequireDefault(_Templates);
|
|
24
|
+
|
|
25
|
+
var _RewireHelpers = require('./RewireHelpers.js');
|
|
26
|
+
|
|
27
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
28
|
+
|
|
29
|
+
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
|
|
30
|
+
|
|
31
|
+
var t;
|
|
32
|
+
var universalAccesorsTemplate;
|
|
33
|
+
var enrichExportTemplate;
|
|
34
|
+
var filterWildcardImportTemplate;
|
|
35
|
+
|
|
36
|
+
var RewireState = function () {
|
|
37
|
+
function RewireState(scope, types, template) {
|
|
38
|
+
_classCallCheck(this, RewireState);
|
|
39
|
+
|
|
40
|
+
t = types;
|
|
41
|
+
var templates = (0, _Templates2.default)(template);
|
|
42
|
+
universalAccesorsTemplate = templates.universalAccesorsTemplate;
|
|
43
|
+
enrichExportTemplate = templates.enrichExportTemplate;
|
|
44
|
+
filterWildcardImportTemplate = templates.filterWildcardImportTemplate;
|
|
45
|
+
this.isES6Module = false;
|
|
46
|
+
this.hasES6Export = false;
|
|
47
|
+
this.hasES6DefaultExport = false;
|
|
48
|
+
this.nodesToAppendToProgramBody = [];
|
|
49
|
+
this.hasCommonJSExport = false;
|
|
50
|
+
this.accessors = {};
|
|
51
|
+
this.trackedIdentfiers = {};
|
|
52
|
+
this.isWildcardImport = {};
|
|
53
|
+
this.ignoredIdentifiers = [];
|
|
54
|
+
this.updateableVariables = {};
|
|
55
|
+
this.syncInternalStateWithExports = true;
|
|
56
|
+
this.getGlobalVariableHandleIdentifier = scope.generateUidIdentifier('getGlobalObject');
|
|
57
|
+
this.getRewiredDataIdentifier = scope.generateUidIdentifier('__getRewiredData__');
|
|
58
|
+
this.getRewireRegistryIdentifier = scope.generateUidIdentifier('__getRewireRegistry__');
|
|
59
|
+
this.getUniqueGlobalModuleIdIdentifier = scope.generateUidIdentifier('__getRewireModuleId__');
|
|
60
|
+
this.uniqueModuleIdIdentifier = scope.generateUidIdentifier('__RewireModuleId__');
|
|
61
|
+
this.originalVariableAccessorIdentifier = scope.generateUidIdentifier('__get_original__');
|
|
62
|
+
this.originalVariableSetterIdentifier = scope.generateUidIdentifier('__set_original__');
|
|
63
|
+
this.updateOperationIdentifier = scope.generateUidIdentifier('__update_operation__');
|
|
64
|
+
this.assignmentOperationIdentifier = scope.generateUidIdentifier('__assign__');
|
|
65
|
+
this.typeofOriginalExportVariable = scope.generateUidIdentifier('typeOfOriginalExport');
|
|
66
|
+
this.exportsToResetIdentifier = scope.generateUidIdentifier('__exports_to_reset__');
|
|
67
|
+
this.recordExportToReset = scope.generateUidIdentifier('__record_export_to_reset__');
|
|
68
|
+
this.restoreExportsIdentifier = scope.generateUidIdentifier('__restore_exports__');
|
|
69
|
+
this.getRewireExportsRegistry = scope.generateUidIdentifier('__getRewireExportsRegistry__');
|
|
70
|
+
this.mayebeUpdateExportIdentifier = scope.generateUidIdentifier('__maybe_update_export__');
|
|
71
|
+
|
|
72
|
+
this.universalAccessors = {
|
|
73
|
+
__get__: (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__get__')),
|
|
74
|
+
__set__: (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__set__')),
|
|
75
|
+
__reset__: (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__reset__')),
|
|
76
|
+
__with__: (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__with__')),
|
|
77
|
+
__RewireAPI__: (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__RewireAPI__')),
|
|
78
|
+
__assignOperation: (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__assign__'))
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
_createClass(RewireState, [{
|
|
83
|
+
key: 'appendToProgramBody',
|
|
84
|
+
value: function appendToProgramBody(nodes) {
|
|
85
|
+
if (!Array.isArray(nodes)) {
|
|
86
|
+
nodes = [nodes];
|
|
87
|
+
}
|
|
88
|
+
this.nodesToAppendToProgramBody = this.nodesToAppendToProgramBody.concat(nodes);
|
|
89
|
+
}
|
|
90
|
+
}, {
|
|
91
|
+
key: 'prependToProgramBody',
|
|
92
|
+
value: function prependToProgramBody(nodes) {
|
|
93
|
+
if (!Array.isArray(nodes)) {
|
|
94
|
+
nodes = [nodes];
|
|
95
|
+
}
|
|
96
|
+
this.nodesToAppendToProgramBody = nodes.concat(this.nodesToAppendToProgramBody);
|
|
97
|
+
}
|
|
98
|
+
}, {
|
|
99
|
+
key: 'ensureAccessor',
|
|
100
|
+
value: function ensureAccessor(variableName) {
|
|
101
|
+
var isWildcardImport = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
|
102
|
+
|
|
103
|
+
if (!this.accessors[variableName]) {
|
|
104
|
+
this.accessors[variableName] = true;
|
|
105
|
+
this.addTrackedIdentifier(variableName, isWildcardImport);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return this.accessors[variableName];
|
|
109
|
+
}
|
|
110
|
+
}, {
|
|
111
|
+
key: 'addTrackedIdentifier',
|
|
112
|
+
value: function addTrackedIdentifier(variableName) {
|
|
113
|
+
var isWildcardImport = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
|
|
114
|
+
|
|
115
|
+
this.isWildcardImport[variableName] = isWildcardImport;
|
|
116
|
+
return this.trackedIdentfiers[variableName] = true;
|
|
117
|
+
}
|
|
118
|
+
}, {
|
|
119
|
+
key: 'hasTrackedIdentifier',
|
|
120
|
+
value: function hasTrackedIdentifier(variableName) {
|
|
121
|
+
return !!this.trackedIdentfiers[variableName];
|
|
122
|
+
}
|
|
123
|
+
}, {
|
|
124
|
+
key: 'addUpdateableVariable',
|
|
125
|
+
value: function addUpdateableVariable(variableName) {
|
|
126
|
+
this.updateableVariables[variableName] = true;
|
|
127
|
+
this.ensureAccessor(variableName);
|
|
128
|
+
}
|
|
129
|
+
}, {
|
|
130
|
+
key: 'setIgnoredIdentifiers',
|
|
131
|
+
value: function setIgnoredIdentifiers(ignoredIdentifiers) {
|
|
132
|
+
this.ignoredIdentifiers = ignoredIdentifiers || [];
|
|
133
|
+
}
|
|
134
|
+
}, {
|
|
135
|
+
key: 'prependUniversalAccessors',
|
|
136
|
+
value: function prependUniversalAccessors(scope) {
|
|
137
|
+
var hasWildcardImport = Object.keys(this.isWildcardImport).some(function (propertyName) {
|
|
138
|
+
return this.isWildcardImport[propertyName];
|
|
139
|
+
}.bind(this));
|
|
140
|
+
var filterWildcardImportIdentifier = hasWildcardImport && (0, _RewireHelpers.noRewire)(scope.generateUidIdentifier('__filterWildcardImport__')) || null;
|
|
141
|
+
|
|
142
|
+
var originalAccessor = t.functionDeclaration(this.originalVariableAccessorIdentifier, [t.identifier('variableName')], t.blockStatement([t.switchStatement(t.identifier('variableName'), Object.keys(this.accessors).map(function (identifierName) {
|
|
143
|
+
var accessOriginalVariable = (0, _RewireHelpers.noRewire)(t.identifier(identifierName));
|
|
144
|
+
|
|
145
|
+
if (this.isWildcardImport[identifierName]) {
|
|
146
|
+
accessOriginalVariable = t.callExpression(filterWildcardImportIdentifier, [accessOriginalVariable]);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return t.switchCase(t.stringLiteral(identifierName), [t.returnStatement(accessOriginalVariable)]);
|
|
150
|
+
}, this)), t.returnStatement((0, _RewireHelpers.noRewire)(t.identifier('undefined')))]));
|
|
151
|
+
|
|
152
|
+
var valueVariable = scope.generateUidIdentifier('value');
|
|
153
|
+
var originalSetter = t.functionDeclaration(this.originalVariableSetterIdentifier, [t.identifier('variableName'), valueVariable], t.blockStatement([t.switchStatement(t.identifier('variableName'), Object.keys(this.updateableVariables).map(function (identifierName) {
|
|
154
|
+
return t.switchCase(t.stringLiteral(identifierName), [t.returnStatement(t.assignmentExpression('=', (0, _RewireHelpers.noRewire)(t.identifier(identifierName)), valueVariable))]);
|
|
155
|
+
})), t.returnStatement((0, _RewireHelpers.noRewire)(t.identifier('undefined')))]));
|
|
156
|
+
|
|
157
|
+
var syncInternalStateWithExportsId = scope.generateUidIdentifier('__sync_internal_state_with_exports__');
|
|
158
|
+
|
|
159
|
+
var syncInternalStateWithExports = t.variableDeclaration("const", [t.variableDeclarator(syncInternalStateWithExportsId, t.booleanLiteral(this.syncInternalStateWithExports))]);
|
|
160
|
+
|
|
161
|
+
this.prependToProgramBody(universalAccesorsTemplate({
|
|
162
|
+
ORIGINAL_VARIABLE_ACCESSOR_IDENTIFIER: this.originalVariableAccessorIdentifier,
|
|
163
|
+
ORIGINAL_VARIABLE_SETTER_IDENTIFIER: this.originalVariableSetterIdentifier,
|
|
164
|
+
ASSIGNMENT_OPERATION_IDENTIFIER: this.assignmentOperationIdentifier,
|
|
165
|
+
UPDATE_OPERATION_IDENTIFIER: this.updateOperationIdentifier,
|
|
166
|
+
ORIGINAL_ACCESSOR: originalAccessor,
|
|
167
|
+
ORIGINAL_SETTER: originalSetter,
|
|
168
|
+
UNIVERSAL_GETTER_ID: this.getUniversalGetterID(),
|
|
169
|
+
UNIVERSAL_SETTER_ID: this.getUniversalSetterID(),
|
|
170
|
+
UNIVERSAL_RESETTER_ID: this.getUniversalResetterID(),
|
|
171
|
+
UNIVERSAL_WITH_ID: this.getUniversalWithID(),
|
|
172
|
+
API_OBJECT_ID: this.getAPIObjectID(),
|
|
173
|
+
GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER: this.getGlobalVariableHandleIdentifier,
|
|
174
|
+
GET_REWIRE_DATA_IDENTIFIER: this.getRewiredDataIdentifier,
|
|
175
|
+
GET_UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER: this.getUniqueGlobalModuleIdIdentifier,
|
|
176
|
+
GET_REWIRE_REGISTRY_IDENTIFIER: this.getRewireRegistryIdentifier,
|
|
177
|
+
UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER: this.uniqueModuleIdIdentifier,
|
|
178
|
+
EXPORTS_TO_RESET_IDENTIFIER: this.exportsToResetIdentifier,
|
|
179
|
+
RECORD_EXPORT_TO_RESET: this.recordExportToReset,
|
|
180
|
+
RESTORE_EXPORTS_IDENTIFIER: this.restoreExportsIdentifier,
|
|
181
|
+
GET_REWIRE_EXPORTS_REGISTRY: this.getRewireExportsRegistry,
|
|
182
|
+
MAYBE_UPDATE_EXPORT_IDENTIFIER: this.mayebeUpdateExportIdentifier,
|
|
183
|
+
SYNC_INTERNAL_STATE_WITH_EXPORTS_IDENTIFIER: syncInternalStateWithExportsId,
|
|
184
|
+
SYNC_INTERNAL_STATE_WITH_EXPORTS: syncInternalStateWithExports
|
|
185
|
+
}));
|
|
186
|
+
|
|
187
|
+
if (hasWildcardImport) {
|
|
188
|
+
this.appendToProgramBody(filterWildcardImportTemplate({
|
|
189
|
+
FILTER_WILDCARD_IMPORT_IDENTIFIER: filterWildcardImportIdentifier
|
|
190
|
+
}));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}, {
|
|
194
|
+
key: 'appendExports',
|
|
195
|
+
value: function appendExports() {
|
|
196
|
+
if (this.isES6Module && (!this.hasCommonJSExport || this.hasES6Export)) {
|
|
197
|
+
this.appendToProgramBody(this.generateNamedExports());
|
|
198
|
+
|
|
199
|
+
if (!this.hasES6DefaultExport) {
|
|
200
|
+
this.appendToProgramBody(t.exportDefaultDeclaration(this.getAPIObjectID()));
|
|
201
|
+
}
|
|
202
|
+
} else if (!this.isES6Module || !this.hasES6Export && this.hasCommonJSExport) {
|
|
203
|
+
var commonJSExport = t.memberExpression(t.identifier('module'), t.identifier('exports'), false);
|
|
204
|
+
this.enrichExport(commonJSExport);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}, {
|
|
208
|
+
key: 'enrichExport',
|
|
209
|
+
value: function enrichExport(exportValue) {
|
|
210
|
+
this.appendToProgramBody(enrichExportTemplate({
|
|
211
|
+
TYPEOFORIGINALEXPORTVARIABLE: this.getTypeOfOriginalExportVariable(),
|
|
212
|
+
UNIVERSAL_GETTER_ID: this.getUniversalGetterID(),
|
|
213
|
+
UNIVERSAL_SETTER_ID: this.getUniversalSetterID(),
|
|
214
|
+
UNIVERSAL_RESETTER_ID: this.getUniversalResetterID(),
|
|
215
|
+
UNIVERSAL_WITH_ID: this.getUniversalWithID(),
|
|
216
|
+
API_OBJECT_ID: this.getAPIObjectID(),
|
|
217
|
+
EXPORT_VALUE: exportValue
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
}, {
|
|
221
|
+
key: 'generateNamedExports',
|
|
222
|
+
value: function generateNamedExports() {
|
|
223
|
+
return t.exportNamedDeclaration(null, [t.exportSpecifier(this.getUniversalGetterID(), t.identifier('__get__')), t.exportSpecifier(this.getUniversalGetterID(), t.identifier('__GetDependency__')), t.exportSpecifier(this.getUniversalSetterID(), t.identifier('__Rewire__')), t.exportSpecifier(this.getUniversalSetterID(), t.identifier('__set__')), t.exportSpecifier(this.getUniversalResetterID(), t.identifier('__ResetDependency__')), t.exportSpecifier(this.getAPIObjectID(), t.identifier('__RewireAPI__'))]);
|
|
224
|
+
}
|
|
225
|
+
}, {
|
|
226
|
+
key: 'containsDependenciesToRewire',
|
|
227
|
+
value: function containsDependenciesToRewire() {
|
|
228
|
+
return Object.keys(this.accessors).length > 0 || Object.keys(this.updateableVariables).length > 0;
|
|
229
|
+
}
|
|
230
|
+
}, {
|
|
231
|
+
key: 'getUniversalGetterID',
|
|
232
|
+
value: function getUniversalGetterID() {
|
|
233
|
+
return this.universalAccessors['__get__'];
|
|
234
|
+
}
|
|
235
|
+
}, {
|
|
236
|
+
key: 'getUpdateOperationID',
|
|
237
|
+
value: function getUpdateOperationID() {
|
|
238
|
+
return this.updateOperationIdentifier;
|
|
239
|
+
}
|
|
240
|
+
}, {
|
|
241
|
+
key: 'getAssignmentOperationID',
|
|
242
|
+
value: function getAssignmentOperationID() {
|
|
243
|
+
return this.assignmentOperationIdentifier;
|
|
244
|
+
}
|
|
245
|
+
}, {
|
|
246
|
+
key: 'getUniversalSetterID',
|
|
247
|
+
value: function getUniversalSetterID() {
|
|
248
|
+
return this.universalAccessors['__set__'];
|
|
249
|
+
}
|
|
250
|
+
}, {
|
|
251
|
+
key: 'getUniversalResetterID',
|
|
252
|
+
value: function getUniversalResetterID() {
|
|
253
|
+
return this.universalAccessors['__reset__'];
|
|
254
|
+
}
|
|
255
|
+
}, {
|
|
256
|
+
key: 'getUniversalWithID',
|
|
257
|
+
value: function getUniversalWithID() {
|
|
258
|
+
return this.universalAccessors['__with__'];
|
|
259
|
+
}
|
|
260
|
+
}, {
|
|
261
|
+
key: 'getAPIObjectID',
|
|
262
|
+
value: function getAPIObjectID() {
|
|
263
|
+
return this.universalAccessors['__RewireAPI__'];
|
|
264
|
+
}
|
|
265
|
+
}, {
|
|
266
|
+
key: 'getTypeOfOriginalExportVariable',
|
|
267
|
+
value: function getTypeOfOriginalExportVariable() {
|
|
268
|
+
return this.typeofOriginalExportVariable;
|
|
269
|
+
}
|
|
270
|
+
}]);
|
|
271
|
+
|
|
272
|
+
return RewireState;
|
|
273
|
+
}();
|
|
274
|
+
|
|
275
|
+
exports.default = RewireState;
|
|
276
|
+
;
|
package/lib/Templates.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
|
|
7
|
+
exports.default = function (template) {
|
|
8
|
+
|
|
9
|
+
var compatTemplate = function compatTemplate(templateFn, code, opts) {
|
|
10
|
+
try {
|
|
11
|
+
return templateFn(code, opts);
|
|
12
|
+
} catch (err) {
|
|
13
|
+
var msg = String(err && err.message);
|
|
14
|
+
if (opts && opts.placeholderWhitelist && msg.indexOf('placeholderWhitelist') !== -1 && msg.indexOf('placeholderAllowlist') !== -1) {
|
|
15
|
+
return templateFn(code, { placeholderPattern: opts.placeholderPattern, placeholderAllowlist: opts.placeholderWhitelist });
|
|
16
|
+
}
|
|
17
|
+
throw err;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
var universalAccesorsTemplate = compatTemplate(template, "\nfunction GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER() {\n\ttry {\n\t\t\tif(!!global) {\n\t\t\t\t\treturn global;\n\t\t\t}\n\t} catch(e) {\n\t\t\ttry {\n\t\t\t\t\tif(!!window) {\n\t\t\t\t\t\t\treturn window;\n\t\t\t\t\t}\n\t\t\t} catch(e) {\n\t\t\t\t\treturn this;\n\t\t\t}\n\t}\n};\n\nvar UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER = null;\nfunction GET_UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER() {\n\tif(UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER === null) {\n\t\tlet globalVariable = GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER();\n\t\tif(!globalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__) {\n\t\t\tglobalVariable.__$$GLOBAL_REWIRE_NEXT_MODULE_ID__ = 0;\n\t\t}\n\t\tUNIQUE_GLOBAL_MODULE_ID_IDENTIFIER = __$$GLOBAL_REWIRE_NEXT_MODULE_ID__++;\n\t}\n\treturn UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER;\n}\n\nfunction GET_REWIRE_REGISTRY_IDENTIFIER() {\n\tlet theGlobalVariable = GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER();\n\tif(!theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__) {\n\t\ttheGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);\n\t}\n\treturn theGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__;\n}\n\nfunction GET_REWIRE_EXPORTS_REGISTRY() {\n\tlet theGlobalVariable = GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER();\n\tif(!theGlobalVariable.__$$GLOBAL_REWIRE_EXPORTS_REGISTRY__) {\n\t\ttheGlobalVariable.__$$GLOBAL_REWIRE_EXPORTS_REGISTRY__ = Object.create(null);\n\t}\n\treturn theGlobalVariable.__$$GLOBAL_REWIRE_EXPORTS_REGISTRY__;\n}\n\nSYNC_INTERNAL_STATE_WITH_EXPORTS\n\n/**\n * This map records the variable name to reset as a the key,\n * and reset value as it's key.\n */\nconst EXPORTS_TO_RESET_IDENTIFIER = new Map();\nfunction RECORD_EXPORT_TO_RESET(variableName, value) {\n\tif (!SYNC_INTERNAL_STATE_WITH_EXPORTS_IDENTIFIER) {\n\t\treturn;\n\t}\n\n\t// Defensively avoid storing non-exported variables.\n\t// We intend to use this in __reset__ where it could\n\t// be called on non-exported variable.\n\tif (!Object.prototype.hasOwnProperty.call(exports, variableName)) {\n\t\treturn;\n\t}\n\n\t// Only record the export if it is not added before,\n\t// so we don't record updates of previous __Rewire__ calls.\n\tif (!EXPORTS_TO_RESET_IDENTIFIER.has(variableName)) {\n\t\tEXPORTS_TO_RESET_IDENTIFIER.set(variableName, value);\n\t}\n}\n\nfunction RESTORE_EXPORTS_IDENTIFIER() {\n\tconst entries = EXPORTS_TO_RESET_IDENTIFIER.entries();\n\tfor (const [variableName, value] of entries) {\n\t\texports[variableName] = value;\n\t}\n\n\tEXPORTS_TO_RESET_IDENTIFIER.clear();\n}\n\nfunction MAYBE_UPDATE_EXPORT_IDENTIFIER(variableName, value) {\n\tif (!SYNC_INTERNAL_STATE_WITH_EXPORTS_IDENTIFIER) {\n\t\treturn;\n\t}\n\n\tif (!Object.prototype.hasOwnProperty.call(exports, variableName)) {\n\t\treturn;\n\t}\n\n\tRECORD_EXPORT_TO_RESET(variableName, exports[variableName]);\n\texports[variableName] = value;\n}\n\nfunction GET_REWIRE_DATA_IDENTIFIER() {\n\tlet moduleId = GET_UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER();\n\tlet registry = GET_REWIRE_REGISTRY_IDENTIFIER();\n\tlet rewireData = registry[moduleId];\n\tif (!rewireData) {\n\t\tregistry[moduleId] = Object.create(null);\n\t\trewireData = registry[moduleId];\n\t}\n\n\tlet exportsRegistry = GET_REWIRE_EXPORTS_REGISTRY();\n\tif (!exportsRegistry[moduleId]) {\n\t\texportsRegistry[moduleId] = RESTORE_EXPORTS_IDENTIFIER;\n\t}\n\n\treturn rewireData;\n}\n\n(function registerResetAll() {\n\tlet theGlobalVariable = GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER();\n\tif(!theGlobalVariable['__rewire_reset_all__']) {\n\t\ttheGlobalVariable['__rewire_reset_all__'] = function() {\n\t\t\ttheGlobalVariable.__$$GLOBAL_REWIRE_REGISTRY__ = Object.create(null);\n\n\t\t\tconst exportsRegistry = GET_REWIRE_EXPORTS_REGISTRY();\n\t\t\tfor (const restoreFunc of Object.values(exportsRegistry)) {\n\t\t\t\trestoreFunc();\n\t\t\t}\n\n\t\t\ttheGlobalVariable.__$$GLOBAL_REWIRE_EXPORTS_REGISTRY__ = Object.create(null);\n\t\t};\n\t}\n})();\n\nvar INTENTIONAL_UNDEFINED = '__INTENTIONAL_UNDEFINED__';\n\nlet API_OBJECT_ID = {};\n\n(function() {\n\tfunction addPropertyToAPIObject(name, value) {\n\t\tObject.defineProperty(API_OBJECT_ID, name, { value: value, enumerable: false, configurable: true });\n\t}\n\n\taddPropertyToAPIObject('__get__', UNIVERSAL_GETTER_ID);\n\taddPropertyToAPIObject('__GetDependency__', UNIVERSAL_GETTER_ID);\n\taddPropertyToAPIObject('__Rewire__', UNIVERSAL_SETTER_ID);\n\taddPropertyToAPIObject('__set__', UNIVERSAL_SETTER_ID);\n\taddPropertyToAPIObject('__reset__', UNIVERSAL_RESETTER_ID);\n\taddPropertyToAPIObject('__ResetDependency__', UNIVERSAL_RESETTER_ID);\n\taddPropertyToAPIObject('__with__', UNIVERSAL_WITH_ID);\n})();\n\nfunction UNIVERSAL_GETTER_ID(variableName) {\n\tlet rewireData = GET_REWIRE_DATA_IDENTIFIER();\n\tif (rewireData[variableName] === undefined) {\n\t\treturn ORIGINAL_VARIABLE_ACCESSOR_IDENTIFIER(variableName);\n\t} else {\n\t\tvar value = rewireData[variableName];\n\t\tif (value === INTENTIONAL_UNDEFINED) {\n\t\t\treturn undefined;\n\t\t} else {\n\t\t\treturn value;\n\t\t}\n\t}\n}\n\nORIGINAL_ACCESSOR\n\nfunction ASSIGNMENT_OPERATION_IDENTIFIER(variableName, value) {\n\tlet rewireData = GET_REWIRE_DATA_IDENTIFIER();\n\tif(rewireData[variableName] === undefined) {\n\t\treturn ORIGINAL_VARIABLE_SETTER_IDENTIFIER(variableName, value);\n\t} else {\n\t\tMAYBE_UPDATE_EXPORT_IDENTIFIER(variableName, value);\n\t\treturn rewireData[variableName] = value;\n\t}\n}\n\nORIGINAL_SETTER;\n\nfunction UPDATE_OPERATION_IDENTIFIER(operation, variableName, prefix) {\n\tvar oldValue = UNIVERSAL_GETTER_ID(variableName);\n\tvar newValue = (operation === '++') ? oldValue + 1 : oldValue - 1;\n\tASSIGNMENT_OPERATION_IDENTIFIER(variableName, newValue);\n\treturn (prefix) ? newValue : oldValue;\n}\n\nfunction UNIVERSAL_SETTER_ID(variableName, value) {\n\tlet rewireData = GET_REWIRE_DATA_IDENTIFIER();\n\tif(typeof variableName === 'object') {\n\t\tObject.keys(variableName).forEach(function(name) {\n\t\t\trewireData[name] = variableName[name];\n\t\t});\n\n\t\treturn function() {\n\t\t\tObject.keys(variableName).forEach(function(name) {\n\t\t\t\tUNIVERSAL_RESETTER_ID(variableName);\n\t\t\t});\n\t\t}\n\t} else {\n\t\tMAYBE_UPDATE_EXPORT_IDENTIFIER(variableName, value);\n\t\tif (value === undefined) {\n\t\t\trewireData[variableName] = INTENTIONAL_UNDEFINED\n\t\t} else {\n\t\t\trewireData[variableName] = value\n\t\t}\n\n\t\treturn function() {\n\t\t\tUNIVERSAL_RESETTER_ID(variableName);\n\t\t};\n\t}\n}\n\nfunction UNIVERSAL_RESETTER_ID(variableName) {\n\tlet rewireData = GET_REWIRE_DATA_IDENTIFIER();\n\tdelete rewireData[variableName];\n\tif (Object.keys(rewireData).length == 0) {\n\t\tdelete GET_REWIRE_REGISTRY_IDENTIFIER()[GET_UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER];\n\t}\n\n\tif (EXPORTS_TO_RESET_IDENTIFIER.has(variableName)) {\n\t\texports[variableName] = EXPORTS_TO_RESET_IDENTIFIER.get(variableName);\n\t\tEXPORTS_TO_RESET_IDENTIFIER.delete(variableName);\n\t}\n}\n\nfunction UNIVERSAL_WITH_ID(object) {\n\tlet rewireData = GET_REWIRE_DATA_IDENTIFIER();\n\tvar rewiredVariableNames = Object.keys(object);\n\tvar previousValues = {};\n\n\tfunction reset() {\n\t\trewiredVariableNames.forEach(function(variableName) {\n\t\t\trewireData[variableName] = previousValues[variableName];\n\t\t});\n\t}\n\n\treturn function(callback) {\n\t\trewiredVariableNames.forEach(function(variableName) {\n\t\t\tpreviousValues[variableName] = rewireData[variableName];\n\t\t\trewireData[variableName] = object[variableName];\n\t\t});\n\t\tlet result = callback();\n\t\tif(!!result && typeof result.then == 'function') {\n\t\t\tresult.then(reset).catch(reset);\n\t\t} else {\n\t\t\treset();\n\t\t}\n\t\treturn result;\n\t}\n}\n\n\n", { placeholderPattern: false, placeholderWhitelist: new Set(["ORIGINAL_VARIABLE_ACCESSOR_IDENTIFIER", "ORIGINAL_VARIABLE_SETTER_IDENTIFIER", "ASSIGNMENT_OPERATION_IDENTIFIER", "UPDATE_OPERATION_IDENTIFIER", "ORIGINAL_ACCESSOR", "ORIGINAL_SETTER", "UNIVERSAL_GETTER_ID", "UNIVERSAL_SETTER_ID", "UNIVERSAL_RESETTER_ID", "UNIVERSAL_WITH_ID", "API_OBJECT_ID", "GET_GLOBAL_VARIABLE_HANDLE_IDENTIFIER", "GET_REWIRE_DATA_IDENTIFIER", "GET_UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER", "GET_REWIRE_REGISTRY_IDENTIFIER", "UNIQUE_GLOBAL_MODULE_ID_IDENTIFIER", "EXPORTS_TO_RESET_IDENTIFIER", "RECORD_EXPORT_TO_RESET", "RESTORE_EXPORTS_IDENTIFIER", "GET_REWIRE_EXPORTS_REGISTRY", "MAYBE_UPDATE_EXPORT_IDENTIFIER", "SYNC_INTERNAL_STATE_WITH_EXPORTS", "SYNC_INTERNAL_STATE_WITH_EXPORTS_IDENTIFIER"]) });
|
|
22
|
+
|
|
23
|
+
var enrichExportTemplate = template("\nlet TYPEOFORIGINALEXPORTVARIABLE = typeof EXPORT_VALUE;\nfunction addNonEnumerableProperty(name, value) {\n\tObject.defineProperty(EXPORT_VALUE, name, { value: value, enumerable: false, configurable: true });\n}\n\nif((TYPEOFORIGINALEXPORTVARIABLE === 'object' || TYPEOFORIGINALEXPORTVARIABLE === 'function') && Object.isExtensible(EXPORT_VALUE)) {\n\taddNonEnumerableProperty('__get__', UNIVERSAL_GETTER_ID);\n\taddNonEnumerableProperty('__GetDependency__', UNIVERSAL_GETTER_ID);\n\taddNonEnumerableProperty('__Rewire__', UNIVERSAL_SETTER_ID);\n\taddNonEnumerableProperty('__set__', UNIVERSAL_SETTER_ID);\n\taddNonEnumerableProperty('__reset__', UNIVERSAL_RESETTER_ID);\n\taddNonEnumerableProperty('__ResetDependency__', UNIVERSAL_RESETTER_ID);\n\taddNonEnumerableProperty('__with__', UNIVERSAL_WITH_ID);\n\taddNonEnumerableProperty('__RewireAPI__', API_OBJECT_ID);\n}\n");
|
|
24
|
+
|
|
25
|
+
var filterWildcardImportTemplate = template("\nfunction FILTER_WILDCARD_IMPORT_IDENTIFIER(wildcardImport={}) {\n\tlet validPropertyNames = Object.keys(wildcardImport).filter(function(propertyName) {\n\t\treturn propertyName !== '__get__' &&\n\t\t\t\tpropertyName !== '__set__' &&\n\t\t\t\tpropertyName !== '__reset__' &&\n\t\t\t\tpropertyName !== '__with__' &&\n\n\t\t\t\tpropertyName !== '__GetDependency__' &&\n\t\t\t\tpropertyName !== '__Rewire__' &&\n\t\t\t\tpropertyName !== '__ResetDependency__' &&\n\n\t\t\t\tpropertyName !== '__RewireAPI__';\n\t});\n\n\treturn validPropertyNames.reduce(\n\t\tfunction(filteredWildcardImport, propertyName) {\n\t\t\tfilteredWildcardImport[propertyName] = wildcardImport[propertyName];\n\t\t\treturn filteredWildcardImport;\n\t\t}, {}\n\t);\n}\n");
|
|
26
|
+
return { universalAccesorsTemplate: universalAccesorsTemplate, enrichExportTemplate: enrichExportTemplate, filterWildcardImportTemplate: filterWildcardImportTemplate };
|
|
27
|
+
};
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var _RewireState = require('./RewireState.js');
|
|
4
|
+
|
|
5
|
+
var _RewireState2 = _interopRequireDefault(_RewireState);
|
|
6
|
+
|
|
7
|
+
var _RewireHelpers = require('./RewireHelpers.js');
|
|
8
|
+
|
|
9
|
+
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
|
|
10
|
+
|
|
11
|
+
/*Copyright (c) 2015, Robert Binna <r.binna@synedra.com>
|
|
12
|
+
|
|
13
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
14
|
+
purpose with or without fee is hereby granted, provided that the above
|
|
15
|
+
copyright notice and this permission notice appear in all copies.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
18
|
+
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
19
|
+
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
20
|
+
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
21
|
+
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
22
|
+
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
23
|
+
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.*/
|
|
24
|
+
|
|
25
|
+
module.exports = function (_ref) {
|
|
26
|
+
var t = _ref.types,
|
|
27
|
+
template = _ref.template;
|
|
28
|
+
|
|
29
|
+
function isRewireable(path, variableBinding) {
|
|
30
|
+
var node = path.node,
|
|
31
|
+
parent = path.parent;
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
return variableBinding.referencePaths !== null && !(parent.type === 'VariableDeclarator' && parent.id == node) && !(parent.type === 'ForInStatement' && parent.left == node) && !(parent.type === 'FunctionExpression' && parent.id === node) && !(parent.type === 'MemberExpression' && parent.property === node) && !(parent.type === 'ObjectProperty' && parent.key === node) && !(parent.type === 'RestProperty') && !(parent.type === 'ObjectMethod' && parent.key === node) && !(parent.type === 'ObjectProperty' && path.parentPath && path.parentPath.parent && path.parentPath.parent.type === 'ObjectPattern') && !(parent.type === 'ExportSpecifier') && !(parent.type === 'ImportSpecifier') && !(parent.type === 'ObjectTypeProperty') && !(parent.type === 'ClassMethod') && !(parent.type === 'TSDeclareFunction') && !(parent.type === 'TSExpressionWithTypeArguments') && !(parent.type === 'TSQualifiedName') && !(parent.type === 'TSTypeQuery') && !(parent.type === 'TSTypeReference') && !(parent.type === 'TSInterfaceDeclaration') && !(parent.type === 'TSTypeAliasDeclaration');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function doesIdentifierRepresentAValidReference(path, variableBinding, rewireInformation) {
|
|
38
|
+
var isIgnoredVariable = rewireInformation.ignoredIdentifiers.indexOf(path.node.name) !== -1;
|
|
39
|
+
return !isIgnoredVariable && variableBinding !== undefined && !(0, _RewireHelpers.wasProcessed)(path) && variableBinding.scope.block.type === 'Program';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function getVariableNameAndBinding(path) {
|
|
43
|
+
var node = path.node,
|
|
44
|
+
parent = path.parent,
|
|
45
|
+
scope = path.scope;
|
|
46
|
+
|
|
47
|
+
var variableName = node.name;
|
|
48
|
+
var variableBinding = !t.isFlow || !t.isFlow(node) && !t.isFlow(parent) ? scope.getBinding(variableName) : undefined;
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
variableName: variableName,
|
|
52
|
+
variableBinding: variableBinding
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
var BodyVisitor = {
|
|
57
|
+
Identifier: function Identifier(path, rewireInformation) {
|
|
58
|
+
var node = path.node,
|
|
59
|
+
parent = path.parent,
|
|
60
|
+
scope = path.scope;
|
|
61
|
+
|
|
62
|
+
var _getVariableNameAndBi = getVariableNameAndBinding(path),
|
|
63
|
+
variableName = _getVariableNameAndBi.variableName,
|
|
64
|
+
variableBinding = _getVariableNameAndBi.variableBinding;
|
|
65
|
+
|
|
66
|
+
//Matches for body
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if (doesIdentifierRepresentAValidReference(path, variableBinding, rewireInformation)) {
|
|
70
|
+
var isWildCardImport = variableBinding.path.type === 'ImportNamespaceSpecifier';
|
|
71
|
+
if (isRewireable(path, variableBinding) && (0, _RewireHelpers.contains)(variableBinding.referencePaths, path)) {
|
|
72
|
+
if (parent.type === 'UpdateExpression') {
|
|
73
|
+
rewireInformation.addUpdateableVariable(variableName);
|
|
74
|
+
replaceWith(path.parentPath, t.callExpression(rewireInformation.getUpdateOperationID(), [t.stringLiteral(parent.operator), t.stringLiteral(variableName), t.booleanLiteral(parent.prefix)]));
|
|
75
|
+
} else {
|
|
76
|
+
rewireInformation.ensureAccessor(variableName, isWildCardImport);
|
|
77
|
+
replaceWith(path, t.callExpression(rewireInformation.getUniversalGetterID(), [t.stringLiteral(variableName)]));
|
|
78
|
+
}
|
|
79
|
+
} else if (parent.type === 'AssignmentExpression' && parent.left == node) {
|
|
80
|
+
rewireInformation.addUpdateableVariable(variableName);
|
|
81
|
+
|
|
82
|
+
if (parent.operator === '=') {
|
|
83
|
+
replaceWith(path.parentPath, (0, _RewireHelpers.noRewire)(t.callExpression(rewireInformation.getAssignmentOperationID(), [t.stringLiteral(variableName), parent.right])));
|
|
84
|
+
} else {
|
|
85
|
+
var baseOperator = parent.operator.substring(0, parent.operator.length - 1);
|
|
86
|
+
replaceWith(path.parentPath, t.assignmentExpression('=', parent.left, t.binaryExpression(baseOperator, t.callExpression(rewireInformation.getUniversalGetterID(), [t.stringLiteral(variableName)]), parent.right)));
|
|
87
|
+
}
|
|
88
|
+
//TODO variable bindings add accessor for each variable declaration even if its unused. The reason is that any other plugin could potentially change the code otherwise
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
if (variableBinding.identifier === node) {
|
|
92
|
+
rewireInformation.addTrackedIdentifier(variableName, isWildCardImport);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
|
|
97
|
+
'ExportNamedDeclaration|ExportAllDeclaration': function ExportNamedDeclarationExportAllDeclaration(_ref2, rewireInformation) {
|
|
98
|
+
var _ref2$node$specifiers = _ref2.node.specifiers,
|
|
99
|
+
specifiers = _ref2$node$specifiers === undefined ? [] : _ref2$node$specifiers;
|
|
100
|
+
|
|
101
|
+
var hasDefaultExport = specifiers.some(function (specifier) {
|
|
102
|
+
return specifier.local && specifier.local.name === 'default' || specifier.exported && specifier.exported.name === 'default';
|
|
103
|
+
});
|
|
104
|
+
rewireInformation.hasES6DefaultExport = rewireInformation.hasES6DefaultExport || hasDefaultExport;
|
|
105
|
+
rewireInformation.isES6Module = true;
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
AssignmentExpression: function AssignmentExpression(_ref3, rewireInformation) {
|
|
109
|
+
var assignmentExpression = _ref3.node,
|
|
110
|
+
blockType = _ref3.scope.block.type;
|
|
111
|
+
|
|
112
|
+
rewireInformation.hasCommonJSExport = blockType === 'Program' && !!assignmentExpression.left.object && assignmentExpression.left.object.name === 'module' && !!assignmentExpression.left.property && assignmentExpression.left.property.name === 'exports';
|
|
113
|
+
},
|
|
114
|
+
|
|
115
|
+
ExportDefaultDeclaration: function ExportDefaultDeclaration(path, rewireInformation) {
|
|
116
|
+
if (!(0, _RewireHelpers.wasProcessed)(path)) {
|
|
117
|
+
var exportIdentifier = null;
|
|
118
|
+
rewireInformation.hasES6DefaultExport = true;
|
|
119
|
+
rewireInformation.hasES6Export = true;
|
|
120
|
+
rewireInformation.isES6Module = true;
|
|
121
|
+
|
|
122
|
+
var declarationVisitors = {
|
|
123
|
+
ClassDeclaration: function ClassDeclaration(path, rewireInformation) {
|
|
124
|
+
var existingClassDeclaration = path.node,
|
|
125
|
+
parent = path.parent,
|
|
126
|
+
scope = path.scope;
|
|
127
|
+
|
|
128
|
+
if (existingClassDeclaration.id === null && parent.type === 'ExportDefaultDeclaration') {
|
|
129
|
+
exportIdentifier = scope.generateUidIdentifier("DefaultExportValue");
|
|
130
|
+
replaceWith(path, t.classDeclaration(exportIdentifier, existingClassDeclaration.superClass, existingClassDeclaration.body, existingClassDeclaration.decorators || []));
|
|
131
|
+
} else {
|
|
132
|
+
exportIdentifier = existingClassDeclaration.id;
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
FunctionDeclaration: function FunctionDeclaration(path, rewireInformation) {
|
|
136
|
+
var existingFunctionDeclaration = path.node,
|
|
137
|
+
scope = path.scope;
|
|
138
|
+
|
|
139
|
+
if (existingFunctionDeclaration.id === null && path.parent.type === 'ExportDefaultDeclaration') {
|
|
140
|
+
exportIdentifier = scope.generateUidIdentifier("DefaultExportValue");
|
|
141
|
+
replaceWith(path, t.functionDeclaration(exportIdentifier, existingFunctionDeclaration.params, existingFunctionDeclaration.body, existingFunctionDeclaration.generator, existingFunctionDeclaration.async));
|
|
142
|
+
} else if (path.parent.type === 'ExportDefaultDeclaration') {
|
|
143
|
+
exportIdentifier = existingFunctionDeclaration.id;
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
Identifier: function Identifier(_ref4, rewireInformation) {
|
|
147
|
+
var parentType = _ref4.parent.type,
|
|
148
|
+
identifier = _ref4.node;
|
|
149
|
+
|
|
150
|
+
if (parentType === 'ExportDefaultDeclaration') {
|
|
151
|
+
exportIdentifier = identifier;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
path.traverse(declarationVisitors, rewireInformation);
|
|
157
|
+
if (exportIdentifier === null) {
|
|
158
|
+
exportIdentifier = (0, _RewireHelpers.noRewire)(path.scope.generateUidIdentifier("DefaultExportValue"));
|
|
159
|
+
replaceWithMultiple(path, [t.variableDeclaration('let', [t.variableDeclarator(exportIdentifier, path.node.declaration)]), (0, _RewireHelpers.noRewire)(t.exportDefaultDeclaration(exportIdentifier))]);
|
|
160
|
+
}
|
|
161
|
+
rewireInformation.enrichExport(exportIdentifier);
|
|
162
|
+
}
|
|
163
|
+
},
|
|
164
|
+
|
|
165
|
+
ImportDeclaration: function ImportDeclaration(path, rewireInformation) {
|
|
166
|
+
rewireInformation.isES6Module = true;
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
var BodySecondPassVisitor = {
|
|
171
|
+
Identifier: function Identifier(path, rewireInformation) {
|
|
172
|
+
var node = path.node,
|
|
173
|
+
parent = path.parent;
|
|
174
|
+
|
|
175
|
+
var _getVariableNameAndBi2 = getVariableNameAndBinding(path),
|
|
176
|
+
variableName = _getVariableNameAndBi2.variableName,
|
|
177
|
+
variableBinding = _getVariableNameAndBi2.variableBinding;
|
|
178
|
+
|
|
179
|
+
//Matches for body
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if (doesIdentifierRepresentAValidReference(path, variableBinding, rewireInformation) && isRewireable(path, variableBinding) && rewireInformation.hasTrackedIdentifier(variableName) && variableBinding.identifier !== node && parent.type !== 'UpdateExpression') {
|
|
183
|
+
var isWildCardImport = variableBinding.path.type === 'ImportNamespaceSpecifier';
|
|
184
|
+
rewireInformation.ensureAccessor(variableName, isWildCardImport);
|
|
185
|
+
replaceWith(path, t.callExpression(rewireInformation.getUniversalGetterID(), [t.stringLiteral(variableName)]));
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
var ProgramVisitor = {
|
|
191
|
+
Program: {
|
|
192
|
+
enter: function enter(path, state) {
|
|
193
|
+
if (!(0, _RewireHelpers.wasProcessed)(path)) {
|
|
194
|
+
var rewireState = new _RewireState2.default(path.scope, t, template);
|
|
195
|
+
rewireState.setIgnoredIdentifiers(state.opts.ignoredIdentifiers);
|
|
196
|
+
if (state.opts.syncInternalStateWithExports === false) {
|
|
197
|
+
rewireState.syncInternalStateWithExports = false;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
path.traverse(BodyVisitor, rewireState);
|
|
201
|
+
|
|
202
|
+
state.rewireState = rewireState;
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
exit: function exit(path, state) {
|
|
206
|
+
if (!(0, _RewireHelpers.wasProcessed)(path)) {
|
|
207
|
+
var scope = path.scope,
|
|
208
|
+
program = path.node;
|
|
209
|
+
|
|
210
|
+
var rewireState = state.rewireState;
|
|
211
|
+
path.traverse(BodySecondPassVisitor, rewireState);
|
|
212
|
+
if (rewireState.containsDependenciesToRewire()) {
|
|
213
|
+
rewireState.prependUniversalAccessors(scope);
|
|
214
|
+
rewireState.appendExports();
|
|
215
|
+
|
|
216
|
+
registerDeclarations(path.pushContainer("body", rewireState.nodesToAppendToProgramBody));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
visitor: ProgramVisitor
|
|
225
|
+
};
|
|
226
|
+
};
|
|
227
|
+
|
|
228
|
+
// Registers declarations return by calling path.replace or
|
|
229
|
+
// path.replaceWithMultiple in babel's scope tracker.
|
|
230
|
+
function registerDeclarations(path, declarations) {
|
|
231
|
+
// path.replace, path.replaceWithMultiple and path.pushContainer should
|
|
232
|
+
// return and array always. No idea why it is undefined sometimes :(
|
|
233
|
+
if (declarations === undefined) {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
declarations.forEach(function (declaration) {
|
|
237
|
+
path.scope.registerDeclaration(declaration);
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// The functions, replaceWith and replaceWithMultiple are meant
|
|
242
|
+
// to replace path.replaceWith and path.replaceWithMultiple for
|
|
243
|
+
// our uses. We need register new declaration to babel's scope
|
|
244
|
+
// tracker otherwise plugins like babel-plugin-transform-typescript
|
|
245
|
+
// throw warning stating DefaultExports, _set__, _get__ are not
|
|
246
|
+
// registred in babel scope tracker.
|
|
247
|
+
function replaceWith(path, node) {
|
|
248
|
+
var declarations = path.replaceWith(node);
|
|
249
|
+
registerDeclarations(path, declarations);
|
|
250
|
+
return declarations;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function replaceWithMultiple(path, nodes) {
|
|
254
|
+
var declarations = path.replaceWithMultiple(nodes);
|
|
255
|
+
registerDeclarations(path, declarations);
|
|
256
|
+
return declarations;
|
|
257
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,83 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ohos-ports/babel-plugin-rewire-ts",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.4.0-beta.1",
|
|
4
|
+
"description": "A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.",
|
|
5
|
+
"main": "lib/babel-plugin-rewire.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"test": "./node_modules/.bin/mocha && ./node_modules/.bin/mocha usage-tests",
|
|
8
|
+
"build": "./node_modules/.bin/babel src --out-dir lib",
|
|
9
|
+
"prepublish": "./node_modules/.bin/babel src --out-dir lib"
|
|
10
|
+
},
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "https://github.com/ohos-ports/ohos-ports.git",
|
|
14
|
+
"directory": "ports/babel-plugin-rewire-ts/1.4.0"
|
|
15
|
+
},
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/ohos-ports/ohos-ports/issues"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"babel",
|
|
21
|
+
"plugin",
|
|
22
|
+
"rewire",
|
|
23
|
+
"es6",
|
|
24
|
+
"modules"
|
|
25
|
+
],
|
|
26
|
+
"author": "r.binna@synedra.com",
|
|
27
|
+
"contributors": [
|
|
28
|
+
{
|
|
29
|
+
"name": "Robert Binna",
|
|
30
|
+
"email": "r.binna@synedra.com"
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"name": "Peet Goddard"
|
|
34
|
+
},
|
|
35
|
+
{
|
|
36
|
+
"name": "Eli White",
|
|
37
|
+
"email": "github@eli-white.com"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"name": "Philip Spitzlinger",
|
|
41
|
+
"email": "p.spitzlinger@synedra.com"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"name": "Gustaf Dalemar"
|
|
45
|
+
}
|
|
46
|
+
],
|
|
47
|
+
"license": "ISC",
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"babel-cli": "^6.10.1",
|
|
50
|
+
"babel-core": "^6.0.0",
|
|
51
|
+
"babel-plugin-syntax-async-functions": "^6.8.0",
|
|
52
|
+
"babel-plugin-syntax-flow": "^6.8.0",
|
|
53
|
+
"babel-plugin-syntax-jsx": "^6.8.0 ",
|
|
54
|
+
"babel-plugin-transform-async-to-generator": "^6.8.0",
|
|
55
|
+
"babel-plugin-transform-es2015-block-scoping": "^6.10.1 ",
|
|
56
|
+
"babel-plugin-transform-es2015-template-literals": "^6.8.0",
|
|
57
|
+
"babel-plugin-transform-es2015-typeof-symbol": "^6.8.0",
|
|
58
|
+
"babel-plugin-transform-export-extensions": "^6.8.0",
|
|
59
|
+
"babel-plugin-transform-flow-strip-types": "^6.18.0",
|
|
60
|
+
"babel-plugin-transform-object-rest-spread": "^6.8.0",
|
|
61
|
+
"babel-plugin-transform-react-jsx": "^6.8.0",
|
|
62
|
+
"babel-plugin-transform-regenerator": "^6.9.0",
|
|
63
|
+
"babel-plugin-transform-runtime": "^6.9.0",
|
|
64
|
+
"babel-polyfill": "^6.9.1",
|
|
65
|
+
"babel-preset-es2015": "^6.9.0",
|
|
66
|
+
"babel-preset-react": "^6.11.0",
|
|
67
|
+
"babel-preset-stage-0": "^6.16.0",
|
|
68
|
+
"babel-runtime": "^6.11.6",
|
|
69
|
+
"babel-template": "^6.2.0",
|
|
70
|
+
"babel-types": "^6.2.0",
|
|
71
|
+
"chai": "^3.5.0",
|
|
72
|
+
"core-js": "^1.0.0",
|
|
73
|
+
"expect.js": "^0.3.1",
|
|
74
|
+
"mocha": "^2.2.4",
|
|
75
|
+
"node-hook": "^0.1.0",
|
|
76
|
+
"react": "^15.1.0",
|
|
77
|
+
"react-dom": "^15.1.0",
|
|
78
|
+
"regenerator-runtime": "^0.9.5",
|
|
79
|
+
"should": "^9.0.2",
|
|
80
|
+
"sinon": "^1.17.4",
|
|
81
|
+
"yargs": "^15.4.1"
|
|
82
|
+
}
|
|
83
|
+
}
|