-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathunassert.js
More file actions
94 lines (81 loc) · 2.99 KB
/
Copy pathunassert.js
File metadata and controls
94 lines (81 loc) · 2.99 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import {createFilter} from '@rollup/pluginutils';
import acorn from 'acorn';
import escodegen from '@javascript-obfuscator/escodegen';
import {unassertAst} from 'unassert';
import convert from 'convert-source-map';
import {transfer} from 'multi-stage-sourcemap';
// Adapted from https://github.com/unassert-js/unassertify/blob/master/index.js
// by Takuto Wada (MIT-licensed)
function handleIncomingSourceMap(originalCode) {
const commented = convert.fromSource(originalCode);
if (commented) {
return commented.toObject();
}
return null;
}
function overwritePropertyIfExists(name, from, to) {
// eslint-disable-next-line no-prototype-builtins
if (from.hasOwnProperty(name)) {
to.setProperty(name, from[name]);
}
}
function reconnectSourceMap(inMap, outMap) {
const mergedRawMap = mergeSourceMap(inMap, outMap.toObject());
const reMap = convert.fromObject(mergedRawMap);
overwritePropertyIfExists('sources', inMap, reMap);
overwritePropertyIfExists('sourceRoot', inMap, reMap);
overwritePropertyIfExists('sourcesContent', inMap, reMap);
return reMap;
}
function mergeSourceMap(incomingSourceMap, outgoingSourceMap) {
if (typeof outgoingSourceMap === 'string' || outgoingSourceMap instanceof String) {
outgoingSourceMap = JSON.parse(outgoingSourceMap);
}
if (!incomingSourceMap) {
return outgoingSourceMap;
}
return JSON.parse(transfer({fromSourceMap: outgoingSourceMap, toSourceMap: incomingSourceMap}));
}
export default function unassert(options = {}) {
if (options.sourcemap === undefined) {
options.sourcemap = true;
}
const filter = createFilter(
options.include || ['*.js', '**/*.js'],
options.exclude
);
return {
name: 'unassert',
transform(code, id) {
if (!filter(id)) { return null; }
return new Promise((resolve) => {
const comments = [];
const tokens = [];
const ast = acorn.parse(code, {
sourceType: 'module',
ecmaVersion: 'latest',
locations: true,
ranges: true,
onComment: comments,
onToken: tokens,
});
escodegen.attachComments(ast, comments, tokens);
const unassertedAst = escodegen.generate(unassertAst(ast), {
sourceMap: id,
sourceContent: code,
sourceMapWithCode: true,
comment: true,
});
const inMap = options.sourcemap && handleIncomingSourceMap(code);
let outMap = convert.fromJSON(unassertedAst.map.toString());
if (inMap) {
outMap = reconnectSourceMap(inMap, outMap);
}
resolve({
code: unassertedAst.code,
map: outMap.toObject()
});
});
}
};
}