Browse Source

Refactoring of `unicodeEscapeSequence` logic

sanex 4 years ago
parent
commit
34b1619ee6

File diff suppressed because it is too large
+ 0 - 0
dist/index.browser.js


File diff suppressed because it is too large
+ 0 - 0
dist/index.cli.js


File diff suppressed because it is too large
+ 0 - 0
dist/index.js


+ 2 - 1
package.json

@@ -34,7 +34,7 @@
     "eventemitter3": "4.0.7",
     "fast-deep-equal": "3.1.3",
     "inversify": "5.0.1",
-    "js-string-escape": "1.0.1",
+    "js-string-escape": "^1.0.1",
     "md5": "2.3.0",
     "mkdirp": "1.0.4",
     "multimatch": "4.0.0",
@@ -50,6 +50,7 @@
     "@types/eslint-scope": "3.7.0",
     "@types/estraverse": "5.1.0",
     "@types/estree": "0.0.45",
+    "@types/js-string-escape": "^1.0.0",
     "@types/md5": "2.2.0",
     "@types/mkdirp": "1.0.1",
     "@types/mocha": "8.0.3",

+ 17 - 1
src/custom-code-helpers/string-array/StringArrayCodeHelper.ts

@@ -9,6 +9,7 @@ import { ICustomCodeHelperObfuscator } from '../../interfaces/custom-code-helper
 import { IOptions } from '../../interfaces/options/IOptions';
 import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
 import { IStringArrayStorage } from '../../interfaces/storages/string-array-transformers/IStringArrayStorage';
+import { IStringArrayStorageItemData } from '../../interfaces/storages/string-array-transformers/IStringArrayStorageItem';
 
 import { initializable } from '../../decorators/Initializable';
 
@@ -16,6 +17,7 @@ import { StringArrayTemplate } from './templates/string-array/StringArrayTemplat
 
 import { AbstractCustomCodeHelper } from '../AbstractCustomCodeHelper';
 import { NodeUtils } from '../../node/NodeUtils';
+import { StringUtils } from '../../utils/StringUtils';
 
 @injectable()
 export class StringArrayCodeHelper extends AbstractCustomCodeHelper {
@@ -81,7 +83,21 @@ export class StringArrayCodeHelper extends AbstractCustomCodeHelper {
     protected getCodeHelperTemplate (): string {
         return this.customCodeHelperFormatter.formatTemplate(StringArrayTemplate(), {
             stringArrayName: this.stringArrayName,
-            stringArray: this.stringArrayStorage.toString()
+            stringArrayStorageItems: this.getEncodedStringArrayStorageItems()
         });
     }
+
+    /**
+     * @returns {string}
+     */
+    private getEncodedStringArrayStorageItems (): string {
+        return Array
+            .from(this.stringArrayStorage.getStorage().values())
+            .map((stringArrayStorageItemData: IStringArrayStorageItemData): string => {
+                const escapedEncodedValue: string = StringUtils.escapeJsString(stringArrayStorageItemData.encodedValue);
+
+                return `'${escapedEncodedValue}'`;
+            })
+            .toString();
+    }
 }

+ 1 - 1
src/custom-code-helpers/string-array/templates/string-array/StringArrayTemplate.ts

@@ -3,6 +3,6 @@
  */
 export function StringArrayTemplate (): string {
     return `
-        const {stringArrayName} = [{stringArray}];
+        const {stringArrayName} = [{stringArrayStorageItems}];
     `;
 }

+ 12 - 5
src/node-transformers/finalizing-transformers/EscapeSequenceTransformer.ts

@@ -9,6 +9,7 @@ import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
 import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
 
 import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage';
+import { NodeTransformer } from '../../enums/node-transformers/NodeTransformer';
 
 import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
 import { NodeGuards } from '../../node/NodeGuards';
@@ -18,6 +19,13 @@ import { NodeUtils } from '../../node/NodeUtils';
 
 @injectable()
 export class EscapeSequenceTransformer extends AbstractNodeTransformer {
+    /**
+     * @type {NodeTransformer[]}
+     */
+    public readonly runAfter: NodeTransformer[] = [
+        NodeTransformer.CustomCodeHelpersTransformer
+    ];
+
     /**
      * @type {IEscapeSequenceEncoder}
      */
@@ -68,12 +76,11 @@ export class EscapeSequenceTransformer extends AbstractNodeTransformer {
             return literalNode;
         }
 
-        const newLiteralNode: ESTree.Literal = NodeFactory.literalNode(
-            this.escapeSequenceEncoder.encode(
-                literalNode.value,
-                this.options.unicodeEscapeSequence
-            )
+        const encodedValue: string = this.escapeSequenceEncoder.encode(
+            literalNode.value,
+            this.options.unicodeEscapeSequence
         );
+        const newLiteralNode: ESTree.Literal = NodeFactory.literalNode(encodedValue);
 
         NodeUtils.parentizeNode(newLiteralNode, parentNode);
 

+ 1 - 0
src/node-transformers/preparing-transformers/EvalCallExpressionTransformer.ts

@@ -22,6 +22,7 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer {
      * @type {NodeTransformer.ParentificationTransformer[]}
      */
     public readonly runAfter: NodeTransformer[] = [
+        NodeTransformer.EscapeSequenceTransformer,
         NodeTransformer.ParentificationTransformer,
         NodeTransformer.VariablePreserveTransformer
     ];

+ 1 - 25
src/storages/string-array-transformers/StringArrayStorage.ts

@@ -7,7 +7,6 @@ import { TStringArrayEncoding } from '../../types/options/TStringArrayEncoding';
 import { IArrayUtils } from '../../interfaces/utils/IArrayUtils';
 import { ICryptUtilsSwappedAlphabet } from '../../interfaces/utils/ICryptUtilsSwappedAlphabet';
 import { IEncodedValue } from '../../interfaces/IEncodedValue';
-import { IEscapeSequenceEncoder } from '../../interfaces/utils/IEscapeSequenceEncoder';
 import { IIdentifierNamesGenerator } from '../../interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator';
 import { IOptions } from '../../interfaces/options/IOptions';
 import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
@@ -55,11 +54,6 @@ export class StringArrayStorage extends MapStorage <string, IStringArrayStorageI
      */
     private readonly cryptUtilsSwappedAlphabet: ICryptUtilsSwappedAlphabet;
 
-    /**
-     * @type {IEscapeSequenceEncoder}
-     */
-    private readonly escapeSequenceEncoder: IEscapeSequenceEncoder;
-
     /**
      * @type {IIdentifierNamesGenerator}
      */
@@ -96,7 +90,6 @@ export class StringArrayStorage extends MapStorage <string, IStringArrayStorageI
      * @param {IRandomGenerator} randomGenerator
      * @param {IOptions} options
      * @param {ICryptUtilsSwappedAlphabet} cryptUtilsSwappedAlphabet
-     * @param {IEscapeSequenceEncoder} escapeSequenceEncoder
      */
     public constructor (
         @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator)
@@ -104,15 +97,13 @@ export class StringArrayStorage extends MapStorage <string, IStringArrayStorageI
         @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils,
         @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
         @inject(ServiceIdentifiers.IOptions) options: IOptions,
-        @inject(ServiceIdentifiers.ICryptUtilsSwappedAlphabet) cryptUtilsSwappedAlphabet: ICryptUtilsSwappedAlphabet,
-        @inject(ServiceIdentifiers.IEscapeSequenceEncoder) escapeSequenceEncoder: IEscapeSequenceEncoder
+        @inject(ServiceIdentifiers.ICryptUtilsSwappedAlphabet) cryptUtilsSwappedAlphabet: ICryptUtilsSwappedAlphabet
     ) {
         super(randomGenerator, options);
 
         this.identifierNamesGenerator = identifierNamesGeneratorFactory(options);
         this.arrayUtils = arrayUtils;
         this.cryptUtilsSwappedAlphabet = cryptUtilsSwappedAlphabet;
-        this.escapeSequenceEncoder = escapeSequenceEncoder;
 
         this.rc4Keys = this.randomGenerator.getRandomGenerator()
             .n(
@@ -225,21 +216,6 @@ export class StringArrayStorage extends MapStorage <string, IStringArrayStorageI
         );
     }
 
-    /**
-     * @returns {string}
-     */
-    public toString (): string {
-        return Array
-            .from(this.storage.values())
-            .map((stringArrayStorageItemData: IStringArrayStorageItemData) => {
-                // we have to encode here, because of possible errors during `parse` of StringArrayCustomNode
-                return `'${this.escapeSequenceEncoder.encode(
-                    stringArrayStorageItemData.encodedValue,
-                    this.options.unicodeEscapeSequence
-                )}'`;
-            }).toString();
-    }
-
     /**
      * @param {string} value
      * @returns {IStringArrayStorageItemData}

+ 11 - 0
src/utils/StringUtils.ts

@@ -0,0 +1,11 @@
+import jsStringEscape from 'js-string-escape';
+
+export class StringUtils {
+    /**
+     * @param {string} string
+     * @returns {string}
+     */
+    public static escapeJsString (string: string): string {
+        return jsStringEscape(string);
+    }
+}

+ 3 - 5
test/dev/dev.ts

@@ -8,11 +8,9 @@ import { IdentifierNamesGenerator } from '../../src/enums/generators/identifier-
 
     let obfuscatedCode: string = JavaScriptObfuscator.obfuscate(
         `
-            const foo = 'foo test';
-
-            function test () {
-                const bar = 'bar';
-            }
+           var test = '\\nreturn \\n//# sourceURL= there can only be \\'^\\' and \\'!\\' markers in a subscription marble diagram.';
+           
+           console.log(test);
         `,
         {
             ...NO_ADDITIONAL_NODES_PRESET,

+ 1 - 0
test/index.spec.ts

@@ -45,6 +45,7 @@ import './unit-tests/utils/CryptUtilsSwappedAlphabet.spec';
 import './unit-tests/utils/EscapeSequenceEncoder.spec';
 import './unit-tests/utils/LevelledTopologicalSorter.spec';
 import './unit-tests/utils/NumberUtils.spec';
+import './unit-tests/utils/StringUtils.spec';
 import './unit-tests/utils/Utils.spec';
 
 /**

+ 37 - 0
test/unit-tests/utils/StringUtils.spec.ts

@@ -0,0 +1,37 @@
+import { assert } from 'chai';
+
+import { StringUtils } from '../../../src/utils/StringUtils';
+
+describe('StringUtils', function () {
+    this.timeout(30000);
+
+    describe('escapeJsString', () => {
+        describe('Variant #1: single quotes', () => {
+            const expectedEscapedJsString: string = 'const foo = \\\'Hello World!\\\'';
+
+            let escapedJsString: string;
+
+            before(() => {
+                escapedJsString = StringUtils.escapeJsString('const foo = \'Hello World!\'');
+            });
+
+            it('should escape js string', () => {
+                assert.equal(escapedJsString, expectedEscapedJsString);
+            });
+        });
+
+        describe('Variant #2: double quotes', () => {
+            const expectedEscapedJsString: string = 'const foo = \\"Hello World!\\"';
+
+            let escapedJsString: string;
+
+            before(() => {
+                escapedJsString = StringUtils.escapeJsString('const foo = "Hello World!"');
+            });
+
+            it('should escape js string', () => {
+                assert.equal(escapedJsString, expectedEscapedJsString);
+            });
+        });
+    });
+});

+ 6 - 1
yarn.lock

@@ -455,6 +455,11 @@
     "@types/minimatch" "*"
     "@types/node" "*"
 
+"@types/js-string-escape@^1.0.0":
+  version "1.0.0"
+  resolved "https://registry.yarnpkg.com/@types/js-string-escape/-/js-string-escape-1.0.0.tgz#96738a64ea912f7d4b87ee097231d68fd1813332"
+  integrity sha512-UANTN9S09hivqbeR4unjVS7DrtgjYUFNK4UCmHGPuwMrHyMFeU3z9KMg0wja/fTflXo7fVl0BsAohlgRO4QowQ==
+
 "@types/json-schema@*", "@types/json-schema@^7.0.3":
   version "7.0.4"
   resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.4.tgz#38fd73ddfd9b55abb1e1b2ed578cb55bd7b7d339"
@@ -3416,7 +3421,7 @@ iterate-value@^1.0.0:
     es-get-iterator "^1.0.2"
     iterate-iterator "^1.0.1"
 
[email protected]:
+js-string-escape@^1.0.1:
   version "1.0.1"
   resolved "https://registry.yarnpkg.com/js-string-escape/-/js-string-escape-1.0.1.tgz#e2625badbc0d67c7533e9edc1068c587ae4137ef"
   integrity sha1-4mJbrbwNZ8dTPp7cEGjFh65BN+8=

Some files were not shown because too many files changed in this diff