浏览代码

CLI tests and CLI class refactoring

sanex3339 9 年之前
父节点
当前提交
ef5c2c6de3
共有 3 个文件被更改,包括 86 次插入68 次删除
  1. 22 22
      dist/index.js
  2. 33 28
      src/cli/JavaScriptObfuscatorCLI.ts
  3. 31 18
      test/JavaScriptObfuscatorCLI.spec.ts

+ 22 - 22
dist/index.js

@@ -1061,7 +1061,7 @@ var _createClass = function () { function defineProperties(target, props) { for
 
 function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
-var commands = __webpack_require__(42);
+var commander_1 = __webpack_require__(42);
 var fs = __webpack_require__(43);
 var mkdirp = __webpack_require__(44);
 var path = __webpack_require__(45);
@@ -1083,20 +1083,36 @@ var JavaScriptObfuscatorCLI = function () {
         value: function run() {
             this.configureCommands();
             if (!this.arguments.length || this.arguments.indexOf('--help') >= 0) {
-                commands.outputHelp();
+                this.commands.outputHelp();
                 return;
             }
             this.inputPath = this.getInputPath();
             this.getData();
             this.processData();
         }
+    }, {
+        key: 'buildOptions',
+        value: function buildOptions() {
+            var options = {},
+                availableOptions = Object.keys(DefaultPreset_1.DEFAULT_PRESET);
+            for (var option in this.commands) {
+                if (!this.commands.hasOwnProperty(option)) {
+                    continue;
+                }
+                if (availableOptions.indexOf(option) === -1) {
+                    continue;
+                }
+                options[option] = this.commands[option];
+            }
+            return Object.assign({}, DefaultPreset_1.DEFAULT_PRESET, options);
+        }
     }, {
         key: 'configureCommands',
         value: function configureCommands() {
-            commands.version(JavaScriptObfuscatorCLI.getBuildVersion(), '-v, --version').usage('<inputPath> [options]').option('-o, --output <path>', 'Output path for obfuscated code').option('--compact <boolean>', 'Disable one line output code compacting', JavaScriptObfuscatorCLI.parseBoolean).option('--debugProtection <boolean>', 'Disable browser Debug panel (can cause DevTools enabled browser freeze)', JavaScriptObfuscatorCLI.parseBoolean).option('--debugProtectionInterval <boolean>', 'Disable browser Debug panel even after page was loaded (can cause DevTools enabled browser freeze)', JavaScriptObfuscatorCLI.parseBoolean).option('--disableConsoleOutput <boolean>', 'Allow console.log, console.info, console.error and console.warn messages output into browser console', JavaScriptObfuscatorCLI.parseBoolean).option('--encodeUnicodeLiterals <boolean>', 'All literals in Unicode array become encoded in Base64 (this option can slightly slow down your code speed)', JavaScriptObfuscatorCLI.parseBoolean).option('--reservedNames <list>', 'Disable obfuscation of variable names, function names and names of function parameters that match the passed RegExp patterns (comma separated)', function (val) {
+            this.commands = new commander_1.Command().version(JavaScriptObfuscatorCLI.getBuildVersion(), '-v, --version').usage('<inputPath> [options]').option('-o, --output <path>', 'Output path for obfuscated code').option('--compact <boolean>', 'Disable one line output code compacting', JavaScriptObfuscatorCLI.parseBoolean).option('--debugProtection <boolean>', 'Disable browser Debug panel (can cause DevTools enabled browser freeze)', JavaScriptObfuscatorCLI.parseBoolean).option('--debugProtectionInterval <boolean>', 'Disable browser Debug panel even after page was loaded (can cause DevTools enabled browser freeze)', JavaScriptObfuscatorCLI.parseBoolean).option('--disableConsoleOutput <boolean>', 'Allow console.log, console.info, console.error and console.warn messages output into browser console', JavaScriptObfuscatorCLI.parseBoolean).option('--encodeUnicodeLiterals <boolean>', 'All literals in Unicode array become encoded in Base64 (this option can slightly slow down your code speed)', JavaScriptObfuscatorCLI.parseBoolean).option('--reservedNames <list>', 'Disable obfuscation of variable names, function names and names of function parameters that match the passed RegExp patterns (comma separated)', function (val) {
                 return val.split(',');
             }).option('--rotateUnicodeArray <boolean>', 'Disable rotation of unicode array values during obfuscation', JavaScriptObfuscatorCLI.parseBoolean).option('--selfDefending <boolean>', 'Disables self-defending for obfuscated code', JavaScriptObfuscatorCLI.parseBoolean).option('--unicodeArray <boolean>', 'Disables gathering of all literal strings into an array and replacing every literal string with an array call', JavaScriptObfuscatorCLI.parseBoolean).option('--unicodeArrayThreshold <number>', 'The probability that the literal string will be inserted into unicodeArray (Default: 0.8, Min: 0, Max: 1)', parseFloat).option('--wrapUnicodeArrayCalls <boolean>', 'Disables usage of special access function instead of direct array call', JavaScriptObfuscatorCLI.parseBoolean).parse(this.rawArguments);
-            commands.on('--help', function () {
+            this.commands.on('--help', function () {
                 var isWindows = process.platform === 'win32',
                     commandName = isWindows ? 'type' : 'cat';
                 console.log('  Examples:\n');
@@ -1126,7 +1142,7 @@ var JavaScriptObfuscatorCLI = function () {
     }, {
         key: 'getOutputPath',
         value: function getOutputPath() {
-            var outputPath = commands.output;
+            var outputPath = this.commands.output;
             if (outputPath) {
                 return outputPath;
             }
@@ -1140,27 +1156,11 @@ var JavaScriptObfuscatorCLI = function () {
             var outputPath = this.getOutputPath(),
                 dirName = path.dirname(outputPath);
             mkdirp.sync(dirName);
-            fs.writeFileSync(this.getOutputPath(), JavaScriptObfuscator_1.JavaScriptObfuscator.obfuscate(this.data, JavaScriptObfuscatorCLI.buildOptions()), {
+            fs.writeFileSync(this.getOutputPath(), JavaScriptObfuscator_1.JavaScriptObfuscator.obfuscate(this.data, this.buildOptions()), {
                 encoding: JavaScriptObfuscatorCLI.encoding
             });
         }
     }], [{
-        key: 'buildOptions',
-        value: function buildOptions() {
-            var options = {},
-                availableOptions = Object.keys(DefaultPreset_1.DEFAULT_PRESET);
-            for (var option in commands) {
-                if (!commands.hasOwnProperty(option)) {
-                    continue;
-                }
-                if (availableOptions.indexOf(option) === -1) {
-                    continue;
-                }
-                options[option] = commands[option];
-            }
-            return Object.assign({}, DefaultPreset_1.DEFAULT_PRESET, options);
-        }
-    }, {
         key: 'getBuildVersion',
         value: function getBuildVersion() {
             return child_process_1.execSync('npm info ' + JavaScriptObfuscatorCLI.packageName + ' version', {

+ 33 - 28
src/cli/JavaScriptObfuscatorCLI.ts

@@ -1,4 +1,4 @@
-import * as commands from 'commander';
+import { Command } from 'commander';
 import * as fs from 'fs';
 import * as mkdirp from 'mkdirp';
 import * as path from 'path';
@@ -33,6 +33,11 @@ export class JavaScriptObfuscatorCLI {
      */
     private arguments: string[];
 
+    /**
+     * @type {commander.ICommand}
+     */
+    private commands: commander.ICommand;
+
     /**
      * @type {string[]}
      */
@@ -56,28 +61,6 @@ export class JavaScriptObfuscatorCLI {
         this.arguments = this.rawArguments.slice(2);
     }
 
-    /**
-     * @returns {IOptionsPreset}
-     */
-    private static buildOptions (): IOptionsPreset {
-        let options: IOptionsPreset = {},
-            availableOptions: string[] = Object.keys(DEFAULT_PRESET);
-
-        for (let option in commands) {
-            if (!commands.hasOwnProperty(option)) {
-                continue;
-            }
-
-            if (availableOptions.indexOf(option) === -1) {
-                continue;
-            }
-
-            options[option] = (<any>commands)[option];
-        }
-
-        return Object.assign({}, DEFAULT_PRESET, options);
-    }
-
     /**
      * @returns {string}
      */
@@ -110,7 +93,7 @@ export class JavaScriptObfuscatorCLI {
         this.configureCommands();
 
         if (!this.arguments.length || this.arguments.indexOf('--help') >= 0) {
-            commands.outputHelp();
+            this.commands.outputHelp();
 
             return;
         }
@@ -121,8 +104,30 @@ export class JavaScriptObfuscatorCLI {
         this.processData();
     }
 
+    /**
+     * @returns {IOptionsPreset}
+     */
+    private buildOptions (): IOptionsPreset {
+        let options: IOptionsPreset = {},
+            availableOptions: string[] = Object.keys(DEFAULT_PRESET);
+
+        for (let option in this.commands) {
+            if (!this.commands.hasOwnProperty(option)) {
+                continue;
+            }
+
+            if (availableOptions.indexOf(option) === -1) {
+                continue;
+            }
+
+            options[option] = (<any>this.commands)[option];
+        }
+
+        return Object.assign({}, DEFAULT_PRESET, options);
+    }
+
     private configureCommands (): void {
-        commands
+        this.commands = new Command()
             .version(JavaScriptObfuscatorCLI.getBuildVersion(), '-v, --version')
             .usage('<inputPath> [options]')
             .option('-o, --output <path>', 'Output path for obfuscated code')
@@ -139,7 +144,7 @@ export class JavaScriptObfuscatorCLI {
             .option('--wrapUnicodeArrayCalls <boolean>', 'Disables usage of special access function instead of direct array call', JavaScriptObfuscatorCLI.parseBoolean)
             .parse(this.rawArguments);
 
-        commands.on('--help', () => {
+        this.commands.on('--help', () => {
             let isWindows: boolean = process.platform === 'win32',
                 commandName: string = isWindows ? 'type' : 'cat';
 
@@ -177,7 +182,7 @@ export class JavaScriptObfuscatorCLI {
      * @returns {string}
      */
     private getOutputPath (): string {
-        let outputPath: string = (<any>commands).output;
+        let outputPath: string = (<any>this.commands).output;
 
         if (outputPath) {
             return outputPath;
@@ -199,7 +204,7 @@ export class JavaScriptObfuscatorCLI {
 
         fs.writeFileSync(
             this.getOutputPath(),
-            JavaScriptObfuscator.obfuscate(this.data, JavaScriptObfuscatorCLI.buildOptions()),
+            JavaScriptObfuscator.obfuscate(this.data, this.buildOptions()),
             {
                 encoding: JavaScriptObfuscatorCLI.encoding
             }

+ 31 - 18
test/JavaScriptObfuscatorCLI.spec.ts

@@ -10,30 +10,43 @@ describe('JavaScriptObfuscatorCLI', () => {
         fixtureFileName: string = 'sample.js',
         fixtureFilePath: string = `${fixturesDirName}/${fixtureFileName}`,
         outputFileName: string = 'sample-obfuscated.js',
+        outputFixturesFilePath: string = `${fixturesDirName}/${outputFileName}`,
         outputFilePath: string = `${tmpDirName}/${outputFileName}`;
 
     describe('run (): void', () => {
-        beforeEach(() => {
-            JavaScriptObfuscator.runCLI([
-                'node',
-                'javascript-obfuscator',
-                fixtureFilePath,
-                '--output',
-                outputFilePath,
-                '--compact',
-                'false',
-                '--selfDefending',
-                'false'
-            ]);
-        });
+        describe('--output option is set', () => {
+            it('should creates file with obfuscated JS code in --output directory', () => {
+                JavaScriptObfuscator.runCLI([
+                    'node',
+                    'javascript-obfuscator',
+                    fixtureFilePath,
+                    '--output',
+                    outputFilePath
+                ]);
+
+                assert.equal(fs.existsSync(outputFilePath), true);
+            });
 
-        it('should obfuscate file with JS code', () => {
-            assert.equal(1, 1);
+            afterEach(() => {
+                fs.unlinkSync(outputFilePath);
+                fs.rmdirSync(tmpDirName);
+            });
         });
 
-        afterEach(() => {
-            fs.unlinkSync(outputFilePath);
-            fs.rmdirSync(tmpDirName);
+        describe('—output option is not set', () => {
+            it(`should creates file called \`${outputFileName}\` with obfuscated JS code in \`${fixturesDirName}\` directory`, () => {
+                JavaScriptObfuscator.runCLI([
+                    'node',
+                    'javascript-obfuscator',
+                    fixtureFilePath
+                ]);
+
+                assert.equal(fs.existsSync(outputFixturesFilePath), true);
+            });
+
+            afterEach(() => {
+                fs.unlinkSync(outputFixturesFilePath);
+            });
         });
     });
 });