-
Notifications
You must be signed in to change notification settings - Fork 0
/
esbuild-plugin-obfuscator.js
68 lines (55 loc) · 2.12 KB
/
esbuild-plugin-obfuscator.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
import JavaScriptObfuscator from 'javascript-obfuscator';
import micromatch from 'micromatch';
import { promises as fs } from 'fs';
import { transform } from 'esbuild';
export function ObfuscatorPlugin({ filter = [], shouldObfuscateOutput = false, ignoreRequireImports = true, ...options } = {}) {
return {
name: 'obfuscator',
async setup(build) {
options = {
ignoreRequireImports,
...options,
};
if (shouldObfuscateOutput) {
build.initialOptions.write = false;
build.onEnd(async (result) => {
let tasks = [];
for (const output of result.outputFiles) {
const filePath = output.path;
const originalCode = output.text;
// Obfuscate the code using javascript-obfuscator
const obfuscatedCode = JavaScriptObfuscator.obfuscate(originalCode, options).getObfuscatedCode();
// Write the obfuscated code to the file
tasks.push(fs.writeFile(filePath, obfuscatedCode));
}
await Promise.all(tasks);
});
} else {
build.onLoad({ filter: /\.(js|ts)$/ }, async (args) => {
const isTs = args.path.endsWith('.ts');
let loader = isTs ? 'ts' : 'js';
// Read the file contents
let source = await fs.readFile(args.path, 'utf8');
// Use micromatch to check if the input file matches any patterns in the filter array
const shouldObfuscate = micromatch.isMatch(args.path, filter);
// If the input file does not match the filter, skip obfuscation
if (shouldObfuscate) {
// If it's a TypeScript file, transpile it to JavaScript using esbuild
if (isTs) {
const result = await transform(await fs.readFile(args.path, 'utf8'), {
loader: 'ts',
sourcemap: false,
});
source = result.code;
}
source = JavaScriptObfuscator.obfuscate(source, options).getObfuscatedCode();
}
return {
contents: source,
loader
};
});
}
},
};
}