diff --git a/.eslintrc.js b/.eslintrc.js index 19606656..a18e32d6 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,336 +1,292 @@ module.exports = { - "env": { - "browser": true, - "es6": true, - "node": true + env: { + browser: true, + es6: true, + node: true }, - "parser": "@typescript-eslint/parser", - "parserOptions": { - "project": "src/tsconfig.node.json", - "sourceType": "module" + parser: '@typescript-eslint/parser', + parserOptions: { + project: 'src/tsconfig.node.json', + sourceType: 'module' }, - "plugins": [ - "@typescript-eslint", - "import", - "jsdoc", - "prefer-arrow", - "unicorn" - ], - "rules": { - "@typescript-eslint/adjacent-overload-signatures": "error", - "@typescript-eslint/array-type": [ - "error", + plugins: ['@typescript-eslint', 'import', 'jsdoc', 'prefer-arrow', 'unicorn', 'prettier'], + extends: ['prettier'], + rules: { + '@typescript-eslint/adjacent-overload-signatures': 'error', + '@typescript-eslint/array-type': [ + 'error', { - "default": "array" + default: 'array' } ], - "@typescript-eslint/await-thenable": "error", - "@typescript-eslint/ban-ts-comment": "error", - "@typescript-eslint/ban-types": "off", - "@typescript-eslint/brace-style": [ - "error", - "1tbs", + '@typescript-eslint/await-thenable': 'error', + '@typescript-eslint/ban-ts-comment': 'error', + '@typescript-eslint/ban-types': 'off', + '@typescript-eslint/brace-style': 'off', + '@typescript-eslint/camelcase': 'off', + '@typescript-eslint/comma-spacing': 'error', + '@typescript-eslint/consistent-type-assertions': [ + 'error', { - "allowSingleLine": true + assertionStyle: 'angle-bracket' } ], - "@typescript-eslint/camelcase": "off", - "@typescript-eslint/comma-spacing": "error", - "@typescript-eslint/consistent-type-assertions": [ - "error", + '@typescript-eslint/consistent-type-definitions': 'error', + '@typescript-eslint/default-param-last': 'error', + '@typescript-eslint/explicit-function-return-type': 'error', + '@typescript-eslint/explicit-member-accessibility': [ + 'error', { - "assertionStyle": "angle-bracket" + accessibility: 'explicit' } ], - "@typescript-eslint/consistent-type-definitions": "error", - "@typescript-eslint/default-param-last": "error", - "@typescript-eslint/explicit-function-return-type": "error", - "@typescript-eslint/explicit-member-accessibility": [ - "error", + '@typescript-eslint/explicit-module-boundary-types': 'error', + '@typescript-eslint/func-call-spacing': 'error', + '@typescript-eslint/indent': ['off', 4], + '@typescript-eslint/member-delimiter-style': [ + 'error', { - "accessibility": "explicit" - } - ], - "@typescript-eslint/explicit-module-boundary-types": "error", - "@typescript-eslint/func-call-spacing": "error", - "@typescript-eslint/indent": [ - "off", - 4 - ], - "@typescript-eslint/member-delimiter-style": [ - "error", - { - "multiline": { - "delimiter": "semi", - "requireLast": true + multiline: { + delimiter: 'semi', + requireLast: true }, - "singleline": { - "delimiter": "semi", - "requireLast": false + singleline: { + delimiter: 'semi', + requireLast: false } } ], - "@typescript-eslint/member-ordering": "error", - "@typescript-eslint/naming-convention": [ - "error", + '@typescript-eslint/member-ordering': 'error', + '@typescript-eslint/naming-convention': [ + 'error', { - "selector": "default", - "format": ["camelCase", "PascalCase"] + selector: 'default', + format: ['camelCase', 'PascalCase'] }, { - "selector": "variable", - "format": ["camelCase", "PascalCase", "UPPER_CASE"] + selector: 'variable', + format: ['camelCase', 'PascalCase', 'UPPER_CASE'] }, { - "selector": "function", - "format": ["camelCase", "PascalCase"] + selector: 'function', + format: ['camelCase', 'PascalCase'] }, { - "selector": "class", - "format": ["PascalCase"] + selector: 'class', + format: ['PascalCase'] }, { - "selector": "interface", - "format": ["PascalCase"], - "prefix": ["I"] + selector: 'interface', + format: ['PascalCase'], + prefix: ['I'] }, { - "selector": "typeAlias", - "format": ["PascalCase"], - "prefix": ["T"] + selector: 'typeAlias', + format: ['PascalCase'], + prefix: ['T'] }, { - "selector": "typeParameter", - "format": ["PascalCase"] + selector: 'typeParameter', + format: ['PascalCase'] }, { - "selector": "enum", - "format": ["PascalCase"] + selector: 'enum', + format: ['PascalCase'] }, { - "selector": "enumMember", - "format": null + selector: 'enumMember', + format: null }, { - "selector": "property", - "format": ["camelCase", "PascalCase", "snake_case"] + selector: 'property', + format: ['camelCase', 'PascalCase', 'snake_case'] } ], - "@typescript-eslint/no-empty-function": "off", - "@typescript-eslint/no-empty-interface": "error", - "@typescript-eslint/no-explicit-any": "off", - "@typescript-eslint/no-extra-parens": "off", - "@typescript-eslint/no-floating-promises": "error", - "@typescript-eslint/no-for-in-array": "error", - "@typescript-eslint/no-inferrable-types": "off", - "@typescript-eslint/no-magic-numbers": "off", - "@typescript-eslint/no-misused-new": "error", - "@typescript-eslint/no-namespace": "error", - "@typescript-eslint/no-non-null-asserted-optional-chain": "error", - "@typescript-eslint/no-non-null-assertion": "error", - "@typescript-eslint/no-param-reassign": "off", - "@typescript-eslint/parameter-properties": "error", - "@typescript-eslint/no-require-imports": "off", - "@typescript-eslint/no-shadow": "error", - "@typescript-eslint/no-this-alias": "error", - "@typescript-eslint/no-unnecessary-qualifier": "error", - "@typescript-eslint/no-unnecessary-type-arguments": "error", - "@typescript-eslint/no-unnecessary-type-assertion": "error", - "@typescript-eslint/no-unused-expressions": "error", - "@typescript-eslint/no-use-before-define": "off", - "@typescript-eslint/no-var-requires": "error", - "@typescript-eslint/prefer-for-of": "error", - "@typescript-eslint/prefer-function-type": "error", - "@typescript-eslint/prefer-namespace-keyword": "error", - "@typescript-eslint/prefer-nullish-coalescing": "error", - "@typescript-eslint/prefer-optional-chain": "error", - "@typescript-eslint/prefer-readonly": "error", - "@typescript-eslint/promise-function-async": "error", - "@typescript-eslint/quotes": [ - "error", - "single" - ], - "@typescript-eslint/require-array-sort-compare": "error", - "@typescript-eslint/restrict-plus-operands": "error", - "@typescript-eslint/semi": [ - "error", - "always" - ], - "@typescript-eslint/space-before-function-paren": "error", - "@typescript-eslint/strict-boolean-expressions": "off", - "@typescript-eslint/triple-slash-reference": "error", - "@typescript-eslint/type-annotation-spacing": "error", - "@typescript-eslint/typedef": "error", - "@typescript-eslint/unified-signatures": "error", - "arrow-body-style": "off", - "arrow-parens": [ - "off", - "as-needed" - ], - "brace-style": "off", - "capitalized-comments": "off", - "comma-dangle": "off", - "comma-spacing": "off", - "complexity": [ - "error", + '@typescript-eslint/no-empty-function': 'off', + '@typescript-eslint/no-empty-interface': 'error', + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-extra-parens': 'off', + '@typescript-eslint/no-floating-promises': 'error', + '@typescript-eslint/no-for-in-array': 'error', + '@typescript-eslint/no-inferrable-types': 'off', + '@typescript-eslint/no-magic-numbers': 'off', + '@typescript-eslint/no-misused-new': 'error', + '@typescript-eslint/no-namespace': 'error', + '@typescript-eslint/no-non-null-asserted-optional-chain': 'error', + '@typescript-eslint/no-non-null-assertion': 'off', + '@typescript-eslint/no-param-reassign': 'off', + '@typescript-eslint/parameter-properties': 'error', + '@typescript-eslint/no-require-imports': 'off', + '@typescript-eslint/no-shadow': 'error', + '@typescript-eslint/no-this-alias': 'error', + '@typescript-eslint/no-unnecessary-qualifier': 'error', + '@typescript-eslint/no-unnecessary-type-arguments': 'error', + '@typescript-eslint/no-unnecessary-type-assertion': 'error', + '@typescript-eslint/no-unused-expressions': 'error', + '@typescript-eslint/no-use-before-define': 'off', + '@typescript-eslint/no-var-requires': 'error', + '@typescript-eslint/prefer-for-of': 'error', + '@typescript-eslint/prefer-function-type': 'error', + '@typescript-eslint/prefer-namespace-keyword': 'error', + '@typescript-eslint/prefer-nullish-coalescing': 'error', + '@typescript-eslint/prefer-optional-chain': 'error', + '@typescript-eslint/prefer-readonly': 'error', + '@typescript-eslint/promise-function-async': 'error', + '@typescript-eslint/quotes': ['error', 'single', { avoidEscape: true }], + '@typescript-eslint/require-array-sort-compare': 'error', + '@typescript-eslint/restrict-plus-operands': 'error', + '@typescript-eslint/semi': ['error', 'always'], + '@typescript-eslint/space-before-function-paren': 'off', + '@typescript-eslint/strict-boolean-expressions': 'off', + '@typescript-eslint/triple-slash-reference': 'error', + '@typescript-eslint/type-annotation-spacing': 'error', + '@typescript-eslint/typedef': 'error', + '@typescript-eslint/unified-signatures': 'error', + 'arrow-body-style': 'off', + 'arrow-parens': ['off', 'as-needed'], + 'brace-style': 'off', + 'capitalized-comments': 'off', + 'comma-dangle': 'off', + 'comma-spacing': 'off', + 'complexity': [ + 'error', { - "max": 10 + max: 10 } ], - "constructor-super": "error", - "curly": "error", - "default-case": "off", - "dot-notation": "error", - "eol-last": "error", - "eqeqeq": [ - "error", - "smart" - ], - "func-call-spacing": "off", - "guard-for-in": "error", - "id-blacklist": "off", - "id-match": "off", - "import/export": "error", - "import/first": "error", - "import/newline-after-import": "error", - "import/no-absolute-path": "error", - "import/no-cycle": "error", - "import/no-default-export": "error", - "import/no-deprecated": "error", - "import/no-extraneous-dependencies": "error", - "import/no-internal-modules": "error", - "import/no-mutable-exports": "error", - "import/no-unassigned-import": "off", - "import/no-useless-path-segments": "error", - "import/order": "off", - "indent": "off", - "jsdoc/no-types": "off", - "linebreak-style": "off", - "max-classes-per-file": [ - "error", - 1 - ], - "max-len": "off", - "max-lines": [ - "error", - 500 - ], - "new-parens": "error", - "newline-per-chained-call": "off", - "no-bitwise": "off", - "no-caller": "error", - "no-cond-assign": "error", - "no-console": [ - "error", + 'constructor-super': 'error', + 'curly': 'error', + 'default-case': 'off', + 'dot-notation': 'error', + 'eol-last': 'error', + 'eqeqeq': ['error', 'smart'], + 'func-call-spacing': 'off', + 'guard-for-in': 'error', + 'id-blacklist': 'off', + 'id-match': 'off', + 'import/export': 'error', + 'import/first': 'error', + 'import/newline-after-import': 'error', + 'import/no-absolute-path': 'error', + 'import/no-cycle': 'error', + 'import/no-default-export': 'error', + 'import/no-deprecated': 'error', + 'import/no-extraneous-dependencies': 'error', + 'import/no-internal-modules': 'error', + 'import/no-mutable-exports': 'error', + 'import/no-unassigned-import': 'off', + 'import/no-useless-path-segments': 'error', + 'import/order': 'off', + 'indent': 'off', + 'jsdoc/no-types': 'off', + 'linebreak-style': 'off', + 'max-classes-per-file': ['error', 1], + 'max-len': 'off', + 'max-lines': ['error', { max: 500, skipComments: true }], + 'new-parens': 'error', + 'newline-per-chained-call': 'off', + 'no-bitwise': 'off', + 'no-caller': 'error', + 'no-cond-assign': 'error', + 'no-console': [ + 'error', { - "allow": [ - "log", - "warn", - "dir", - "timeLog", - "assert", - "clear", - "count", - "countReset", - "group", - "groupEnd", - "table", - "dirxml", - "error", - "groupCollapsed", - "Console", - "profile", - "profileEnd", - "timeStamp", - "context" + allow: [ + 'log', + 'warn', + 'dir', + 'timeLog', + 'assert', + 'clear', + 'count', + 'countReset', + 'group', + 'groupEnd', + 'table', + 'dirxml', + 'error', + 'groupCollapsed', + 'Console', + 'profile', + 'profileEnd', + 'timeStamp', + 'context' ] } ], - "no-constant-condition": "error", - "no-control-regex": "off", - "no-debugger": "error", - "no-duplicate-case": "error", - "no-duplicate-imports": "error", - "no-empty": "off", - "no-eval": "off", - "no-extra-bind": "error", - "no-extra-parens": "off", - "no-extra-semi": "error", - "no-fallthrough": "error", - "no-invalid-regexp": "error", - "no-invalid-this": "off", - "no-irregular-whitespace": "error", - "no-magic-numbers": "off", - "no-multi-str": "error", - "no-multiple-empty-lines": "error", - "no-new-wrappers": "error", - "no-null/no-null": "off", - "no-octal": "error", - "no-octal-escape": "error", - "no-redeclare": "error", - "no-regex-spaces": "error", - "no-restricted-syntax": [ - "error", - "ForInStatement" - ], - "no-return-await": "error", - "no-sequences": "error", - "no-shadow": "off", - "no-sparse-arrays": "error", - "no-template-curly-in-string": "error", - "no-throw-literal": "error", - "no-trailing-spaces": [ - "error", + 'no-constant-condition': 'error', + 'no-control-regex': 'off', + 'no-debugger': 'error', + 'no-duplicate-case': 'error', + 'no-duplicate-imports': 'error', + 'no-empty': 'off', + 'no-eval': 'off', + 'no-extra-bind': 'error', + 'no-extra-parens': 'off', + 'no-extra-semi': 'error', + 'no-fallthrough': 'error', + 'no-invalid-regexp': 'error', + 'no-invalid-this': 'off', + 'no-irregular-whitespace': 'error', + 'no-magic-numbers': 'off', + 'no-multi-str': 'error', + 'no-multiple-empty-lines': 'error', + 'no-new-wrappers': 'error', + 'no-null/no-null': 'off', + 'no-octal': 'error', + 'no-octal-escape': 'error', + 'no-redeclare': 'error', + 'no-regex-spaces': 'error', + 'no-restricted-syntax': ['error', 'ForInStatement'], + 'no-return-await': 'error', + 'no-sequences': 'error', + 'no-shadow': 'off', + 'no-sparse-arrays': 'error', + 'no-template-curly-in-string': 'error', + 'no-throw-literal': 'error', + 'no-trailing-spaces': [ + 'error', { - "skipBlankLines": true + skipBlankLines: true } ], - "no-undef-init": "error", - "no-underscore-dangle": "off", - "no-unsafe-finally": "error", - "no-unused-expressions": "off", - "no-unused-labels": "error", - "no-var": "error", - "no-void": "error", - "object-shorthand": "off", - "one-var": [ - "error", - "never" - ], - "padding-line-between-statements": [ - "error", + 'no-undef-init': 'error', + 'no-underscore-dangle': 'off', + 'no-unsafe-finally': 'error', + 'no-unused-expressions': 'off', + 'no-unused-labels': 'error', + 'no-var': 'error', + 'no-void': 'error', + 'object-shorthand': 'off', + 'one-var': ['error', 'never'], + 'padding-line-between-statements': [ + 'error', { - "blankLine": "always", - "prev": "*", - "next": "return" + blankLine: 'always', + prev: '*', + next: 'return' } ], - "prefer-arrow/prefer-arrow-functions": "off", - "prefer-const": "error", - "prefer-object-spread": "error", - "prefer-template": "error", - "quote-props": [ - "error", - "as-needed" - ], - "quotes": "off", - "radix": "error", - "space-before-function-paren": "off", - "spaced-comment": "error", - "space-in-parens": [ - "error", - "never" - ], - "unicorn/catch-error-name": [ - "error", + 'prefer-arrow/prefer-arrow-functions': 'off', + 'prefer-const': 'error', + 'prefer-object-spread': 'error', + 'prefer-template': 'error', + 'quote-props': ['error', 'as-needed'], + 'quotes': 'off', + 'radix': 'error', + 'space-before-function-paren': 'off', + 'spaced-comment': 'error', + 'space-in-parens': ['error', 'never'], + 'unicorn/catch-error-name': [ + 'error', { - "name": "error" + name: 'error' } ], - "unicorn/no-nested-ternary": "error", - "unicorn/no-unreadable-array-destructuring": "error", - "unicorn/numeric-separators-style": [ - "error", + 'unicorn/no-nested-ternary': 'off', + 'unicorn/no-unreadable-array-destructuring': 'error', + 'unicorn/numeric-separators-style': [ + 'error', { number: { minimumDigits: 7, @@ -338,15 +294,15 @@ module.exports = { } } ], - "unicorn/prefer-array-find": "error", - "unicorn/prefer-includes": "error", - "unicorn/prefer-optional-catch-binding": "error", - "unicorn/prefer-starts-ends-with": "error", - "unicorn/prefer-set-has": "error", - "unicorn/prefer-string-slice": "error", - "unicorn/prefer-string-trim-start-end": "error", - "use-isnan": "error", - "valid-typeof": "error", - "yoda": "error" + 'unicorn/prefer-array-find': 'error', + 'unicorn/prefer-includes': 'error', + 'unicorn/prefer-optional-catch-binding': 'error', + 'unicorn/prefer-starts-ends-with': 'error', + 'unicorn/prefer-set-has': 'error', + 'unicorn/prefer-string-slice': 'error', + 'unicorn/prefer-string-trim-start-end': 'error', + 'use-isnan': 'error', + 'valid-typeof': 'error', + 'yoda': 'error' } }; diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 00000000..859bd06b --- /dev/null +++ b/.prettierignore @@ -0,0 +1,34 @@ +# Dependencies +node_modules + +# Build output +dist +*.browser.js + +# Coverage +coverage +.nyc_output + +# Type definitions +typings + +# Webpack bundles +webpack + +# Lock files +package-lock.json +yarn.lock + +# Logs +*.log + +# Temporary files +*.tmp +.DS_Store + +# Test fixtures and expected output +test/**/*.expected.js +test/**/*.fixture.js + +# Templates (custom code helpers - these are code templates, not regular code) +src/custom-code-helpers/**/templates/*.ts diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 00000000..09aeed30 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,50 @@ +module.exports = { + // Basic formatting + printWidth: 120, + tabWidth: 4, + useTabs: false, + semi: true, + singleQuote: true, + quoteProps: 'consistent', + trailingComma: 'none', + + // Spacing + bracketSpacing: true, + arrowParens: 'always', + + // Line breaks + endOfLine: 'lf', + + // TypeScript + parser: 'typescript', + + // Override for specific file types + overrides: [ + { + files: '*.ts', + options: { + parser: 'typescript' + } + }, + { + files: '*.js', + options: { + parser: 'babel' + } + }, + { + files: '*.json', + options: { + parser: 'json', + tabWidth: 2 + } + }, + { + files: '*.md', + options: { + parser: 'markdown', + proseWrap: 'preserve' + } + } + ] +}; diff --git a/package.json b/package.json index e6f51f02..dfc99ba1 100644 --- a/package.json +++ b/package.json @@ -71,10 +71,12 @@ "chai-exclude": "3.0.1", "cross-env": "10.1.0", "eslint": "8.57.1", + "eslint-config-prettier": "10.1.8", "eslint-plugin-import": "2.32.0", "eslint-plugin-jsdoc": "50.6.3", "eslint-plugin-no-null": "1.0.2", "eslint-plugin-prefer-arrow": "1.2.3", + "eslint-plugin-prettier": "5.5.4", "eslint-plugin-unicorn": "56.0.1", "eslint-webpack-plugin": "4.2.0", "fork-ts-checker-notifier-webpack-plugin": "9.0.0", @@ -84,6 +86,7 @@ "mocha": "11.7.4", "nyc": "17.1.0", "pjson": "1.0.9", + "prettier": "3.6.2", "rimraf": "6.0.1", "sinon": "19.0.2", "source-map-resolve": "0.6.0", @@ -117,6 +120,9 @@ "test:mocha-memory-performance": "cross-env NODE_OPTIONS=--max-old-space-size=280 mocha --require ts-node/register test/performance-tests/JavaScriptObfuscatorMemory.spec.ts", "test": "yarn run test:full", "eslint": "eslint src/**/*.ts", + "prettier": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", + "prettier:check": "prettier --check \"src/**/*.ts\" \"test/**/*.ts\"", + "format": "yarn run prettier && yarn run eslint --fix", "git:addFiles": "git add .", "postinstall": "opencollective-postinstall", "precommit": "npm run build", diff --git a/src/ASTParserFacade.ts b/src/ASTParserFacade.ts index 565a3df9..796f2ad8 100644 --- a/src/ASTParserFacade.ts +++ b/src/ASTParserFacade.ts @@ -19,17 +19,14 @@ export class ASTParserFacade { /** * @type {acorn.Options['sourceType'][]} */ - private static readonly sourceTypes: acorn.Options['sourceType'][] = [ - 'script', - 'module' - ]; + private static readonly sourceTypes: acorn.Options['sourceType'][] = ['script', 'module']; /** * @param {string} sourceCode * @param {Options} config * @returns {Program} */ - public static parse (sourceCode: string, config: acorn.Options): ESTree.Program | never { + public static parse(sourceCode: string, config: acorn.Options): ESTree.Program | never { const sourceTypeLength: number = ASTParserFacade.sourceTypes.length; for (let i: number = 0; i < sourceTypeLength; i++) { @@ -40,11 +37,7 @@ export class ASTParserFacade { continue; } - throw new Error(ASTParserFacade.processParsingError( - sourceCode, - error.message, - error.loc - )); + throw new Error(ASTParserFacade.processParsingError(sourceCode, error.message, error.loc)); } } @@ -57,7 +50,7 @@ export class ASTParserFacade { * @param {acorn.Options["sourceType"]} sourceType * @returns {Program} */ - private static parseType ( + private static parseType( sourceCode: string, inputConfig: acorn.Options, sourceType: acorn.Options['sourceType'] @@ -70,8 +63,7 @@ export class ASTParserFacade { sourceType }; - const program: acorn.Node & ESTree.Program = acorn - .parse(sourceCode, config); + const program: acorn.Node & ESTree.Program = acorn.parse(sourceCode, config); if (comments.length) { program.comments = comments; @@ -86,7 +78,7 @@ export class ASTParserFacade { * @param {Position | null} position * @returns {never} */ - private static processParsingError ( + private static processParsingError( sourceCode: string, errorMessage: string, position: ESTree.Position | null @@ -108,12 +100,10 @@ export class ASTParserFacade { const endErrorIndex: number = Math.min(errorLine.length, position.column + ASTParserFacade.nearestSymbolsCount); const formattedPointer: string = ASTParserFacade.colorError('>'); - const formattedCodeSlice: string = `...${ - errorLine.slice(startErrorIndex, endErrorIndex).replace(/^\s+/, '') - }...`; + const formattedCodeSlice: string = `...${errorLine + .slice(startErrorIndex, endErrorIndex) + .replace(/^\s+/, '')}...`; - throw new Error( - `ERROR at line ${position.line}: ${errorMessage}\n${formattedPointer} ${formattedCodeSlice}` - ); + throw new Error(`ERROR at line ${position.line}: ${errorMessage}\n${formattedPointer} ${formattedCodeSlice}`); } } diff --git a/src/JavaScriptObfuscator.ts b/src/JavaScriptObfuscator.ts index 4728c05a..f6f91a5d 100644 --- a/src/JavaScriptObfuscator.ts +++ b/src/JavaScriptObfuscator.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from './container/ServiceIdentifiers'; import * as acorn from 'acorn'; @@ -55,9 +55,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { /** * @type {CodeTransformer[]} */ - private static readonly codeTransformersList: CodeTransformer[] = [ - CodeTransformer.HashbangOperatorTransformer - ]; + private static readonly codeTransformersList: CodeTransformer[] = [CodeTransformer.HashbangOperatorTransformer]; /** * @type {NodeTransformer[]} @@ -138,7 +136,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {ILogger} logger * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.ICodeTransformersRunner) codeTransformersRunner: ICodeTransformersRunner, @inject(ServiceIdentifiers.INodeTransformersRunner) nodeTransformersRunner: INodeTransformersRunner, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -158,13 +156,16 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {string} sourceCode * @returns {IObfuscationResult} */ - public obfuscate (sourceCode: string): IObfuscationResult { + public obfuscate(sourceCode: string): IObfuscationResult { if (typeof sourceCode !== 'string') { sourceCode = ''; } const timeStart: number = Date.now(); - this.logger.info(LoggingMessage.Version, Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP)); + this.logger.info( + LoggingMessage.Version, + Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP) + ); this.logger.info(LoggingMessage.ObfuscationStarted); this.logger.info(LoggingMessage.RandomGeneratorSeed, this.randomGenerator.getInputSeed()); @@ -181,7 +182,10 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { const generatorOutput: IGeneratorOutput = this.generateCode(sourceCode, obfuscatedAstTree); // finalizing code transformations - generatorOutput.code = this.runCodeTransformationStage(generatorOutput.code, CodeTransformationStage.FinalizingTransformers); + generatorOutput.code = this.runCodeTransformationStage( + generatorOutput.code, + CodeTransformationStage.FinalizingTransformers + ); const obfuscationTime: number = (Date.now() - timeStart) / 1000; this.logger.success(LoggingMessage.ObfuscationCompleted, obfuscationTime); @@ -193,7 +197,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {string} sourceCode * @returns {Program} */ - private parseCode (sourceCode: string): ESTree.Program { + private parseCode(sourceCode: string): ESTree.Program { return ASTParserFacade.parse(sourceCode, JavaScriptObfuscator.parseOptions); } @@ -201,13 +205,14 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {Program} astTree * @returns {Program} */ - private transformAstTree (astTree: ESTree.Program): ESTree.Program { + private transformAstTree(astTree: ESTree.Program): ESTree.Program { astTree = this.runNodeTransformationStage(astTree, NodeTransformationStage.Initializing); - const isEmptyAstTree: boolean = NodeGuards.isProgramNode(astTree) - && !astTree.body.length - && !astTree.leadingComments - && !astTree.trailingComments; + const isEmptyAstTree: boolean = + NodeGuards.isProgramNode(astTree) && + !astTree.body.length && + !astTree.leadingComments && + !astTree.trailingComments; if (isEmptyAstTree) { this.logger.warn(LoggingMessage.EmptySourceCode); @@ -245,22 +250,22 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {Program} astTree * @returns {IGeneratorOutput} */ - private generateCode (sourceCode: string, astTree: ESTree.Program): IGeneratorOutput { + private generateCode(sourceCode: string, astTree: ESTree.Program): IGeneratorOutput { const escodegenParams: escodegen.GenerateOptions = { ...JavaScriptObfuscator.escodegenParams, format: { compact: this.options.compact }, - ...this.options.sourceMap && { - ...this.options.sourceMapSourcesMode === SourceMapSourcesMode.SourcesContent + ...(this.options.sourceMap && { + ...(this.options.sourceMapSourcesMode === SourceMapSourcesMode.SourcesContent ? { - sourceMap: 'sourceMap', - sourceContent: sourceCode - } + sourceMap: 'sourceMap', + sourceContent: sourceCode + } : { - sourceMap: this.options.inputFileName || 'sourceMap' - } - } + sourceMap: this.options.inputFileName || 'sourceMap' + }) + }) }; const generatorOutput: IGeneratorOutput = escodegen.generate(astTree, escodegenParams); @@ -274,7 +279,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {IGeneratorOutput} generatorOutput * @returns {IObfuscationResult} */ - private getObfuscationResult (generatorOutput: IGeneratorOutput): IObfuscationResult { + private getObfuscationResult(generatorOutput: IGeneratorOutput): IObfuscationResult { return this.obfuscationResultFactory(generatorOutput.code, generatorOutput.map); } @@ -283,7 +288,7 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - private runCodeTransformationStage (code: string, codeTransformationStage: CodeTransformationStage): string { + private runCodeTransformationStage(code: string, codeTransformationStage: CodeTransformationStage): string { this.logger.info(LoggingMessage.CodeTransformationStage, codeTransformationStage); return this.codeTransformersRunner.transform( @@ -298,7 +303,10 @@ export class JavaScriptObfuscator implements IJavaScriptObfuscator { * @param {NodeTransformationStage} nodeTransformationStage * @returns {Program} */ - private runNodeTransformationStage (astTree: ESTree.Program, nodeTransformationStage: NodeTransformationStage): ESTree.Program { + private runNodeTransformationStage( + astTree: ESTree.Program, + nodeTransformationStage: NodeTransformationStage + ): ESTree.Program { this.logger.info(LoggingMessage.NodeTransformationStage, nodeTransformationStage); return this.nodeTransformersRunner.transform( diff --git a/src/JavaScriptObfuscatorCLIFacade.ts b/src/JavaScriptObfuscatorCLIFacade.ts index eb3f632c..09a66604 100644 --- a/src/JavaScriptObfuscatorCLIFacade.ts +++ b/src/JavaScriptObfuscatorCLIFacade.ts @@ -6,7 +6,7 @@ class JavaScriptObfuscatorCLIFacade { /** * @param {string[]} argv */ - public static obfuscate (argv: string[]): void { + public static obfuscate(argv: string[]): void { const javaScriptObfuscatorCLI: JavaScriptObfuscatorCLI = new JavaScriptObfuscatorCLI(argv); javaScriptObfuscatorCLI.initialize(); diff --git a/src/JavaScriptObfuscatorFacade.ts b/src/JavaScriptObfuscatorFacade.ts index 2489c40b..abc6e260 100644 --- a/src/JavaScriptObfuscatorFacade.ts +++ b/src/JavaScriptObfuscatorFacade.ts @@ -26,13 +26,14 @@ class JavaScriptObfuscatorFacade { * @param {TInputOptions} inputOptions * @returns {IObfuscationResult} */ - public static obfuscate (sourceCode: string, inputOptions: TInputOptions = {}): IObfuscationResult { + public static obfuscate(sourceCode: string, inputOptions: TInputOptions = {}): IObfuscationResult { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load(sourceCode, '', inputOptions); - const javaScriptObfuscator: IJavaScriptObfuscator = inversifyContainerFacade - .get(ServiceIdentifiers.IJavaScriptObfuscator); + const javaScriptObfuscator: IJavaScriptObfuscator = inversifyContainerFacade.get( + ServiceIdentifiers.IJavaScriptObfuscator + ); const obfuscationResult: IObfuscationResult = javaScriptObfuscator.obfuscate(sourceCode); inversifyContainerFacade.unload(); @@ -45,7 +46,7 @@ class JavaScriptObfuscatorFacade { * @param {TInputOptions} inputOptions * @returns {TObfuscationResultsObject} */ - public static obfuscateMultiple > ( + public static obfuscateMultiple>( sourceCodesObject: TSourceCodesObject, inputOptions: TInputOptions = {} ): TObfuscationResultsObject { @@ -53,39 +54,37 @@ class JavaScriptObfuscatorFacade { throw new Error('Source codes object should be a plain object'); } - return Object - .keys(sourceCodesObject) - .reduce( - ( - acc: TObfuscationResultsObject, - sourceCodeIdentifier: keyof TSourceCodesObject, - index: number - ) => { - const identifiersPrefix: string = Utils.getIdentifiersPrefixForMultipleSources( - inputOptions.identifiersPrefix, - index - ); + return Object.keys(sourceCodesObject).reduce( + ( + acc: TObfuscationResultsObject, + sourceCodeIdentifier: keyof TSourceCodesObject, + index: number + ) => { + const identifiersPrefix: string = Utils.getIdentifiersPrefixForMultipleSources( + inputOptions.identifiersPrefix, + index + ); - const sourceCode: string = sourceCodesObject[sourceCodeIdentifier]; - const sourceCodeOptions: TInputOptions = { - ...inputOptions, - identifiersPrefix - }; + const sourceCode: string = sourceCodesObject[sourceCodeIdentifier]; + const sourceCodeOptions: TInputOptions = { + ...inputOptions, + identifiersPrefix + }; - return { - ...acc, - [sourceCodeIdentifier]: JavaScriptObfuscatorFacade.obfuscate(sourceCode, sourceCodeOptions) - }; - }, - >{} - ); + return { + ...acc, + [sourceCodeIdentifier]: JavaScriptObfuscatorFacade.obfuscate(sourceCode, sourceCodeOptions) + }; + }, + >{} + ); } /** * @param {TOptionsPreset} optionsPreset * @returns {TInputOptions} */ - public static getOptionsByPreset (optionsPreset: TOptionsPreset): TInputOptions { + public static getOptionsByPreset(optionsPreset: TOptionsPreset): TInputOptions { return Options.getOptionsByPreset(optionsPreset); } } diff --git a/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts b/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts index 99c9b1db..7e5d8096 100644 --- a/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts +++ b/src/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -72,8 +72,9 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { */ private readonly calleeDataExtractorFactory: TCalleeDataExtractorFactory; - public constructor ( - @inject(ServiceIdentifiers.Factory__ICalleeDataExtractor) calleeDataExtractorFactory: TCalleeDataExtractorFactory + public constructor( + @inject(ServiceIdentifiers.Factory__ICalleeDataExtractor) + calleeDataExtractorFactory: TCalleeDataExtractorFactory ) { this.calleeDataExtractorFactory = calleeDataExtractorFactory; } @@ -82,16 +83,14 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {number} blockScopeBodyLength * @returns {number} */ - public static getLimitIndex (blockScopeBodyLength: number): number { + public static getLimitIndex(blockScopeBodyLength: number): number { const lastIndex: number = blockScopeBodyLength - 1; const limitThresholdActivationIndex: number = CallsGraphAnalyzer.limitThresholdActivationLength - 1; let limitIndex: number = lastIndex; if (lastIndex > limitThresholdActivationIndex) { - limitIndex = Math.round( - limitThresholdActivationIndex + (lastIndex * CallsGraphAnalyzer.limitThreshold) - ); + limitIndex = Math.round(limitThresholdActivationIndex + lastIndex * CallsGraphAnalyzer.limitThreshold); if (limitIndex > lastIndex) { limitIndex = lastIndex; @@ -105,7 +104,7 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {Program} astTree * @returns {ICallsGraphData[]} */ - public analyze (astTree: ESTree.Program): ICallsGraphData[] { + public analyze(astTree: ESTree.Program): ICallsGraphData[] { return this.analyzeRecursive(astTree.body); } @@ -113,7 +112,7 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {NodeGuards[]} blockScopeBody * @returns {ICallsGraphData[]} */ - private analyzeRecursive (blockScopeBody: ESTree.Node[]): ICallsGraphData[] { + private analyzeRecursive(blockScopeBody: ESTree.Node[]): ICallsGraphData[] { const limitIndex: number = CallsGraphAnalyzer.getLimitIndex(blockScopeBody.length); const callsGraphData: ICallsGraphData[] = []; const blockScopeBodyLength: number = blockScopeBody.length; @@ -148,14 +147,16 @@ export class CallsGraphAnalyzer implements ICallsGraphAnalyzer { * @param {NodeGuards[]} blockScopeBody * @param {CallExpression} callExpressionNode */ - private analyzeCallExpressionNode ( + private analyzeCallExpressionNode( callsGraphData: ICallsGraphData[], blockScopeBody: ESTree.Node[], callExpressionNode: ESTree.CallExpression ): void { CallsGraphAnalyzer.calleeDataExtractorsList.forEach((calleeDataExtractorName: CalleeDataExtractor) => { - const calleeData: ICalleeData | null = this.calleeDataExtractorFactory(calleeDataExtractorName) - .extract(blockScopeBody, callExpressionNode.callee); + const calleeData: ICalleeData | null = this.calleeDataExtractorFactory(calleeDataExtractorName).extract( + blockScopeBody, + callExpressionNode.callee + ); if (!calleeData) { return; diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts index 34381f6f..444701c9 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/AbstractCalleeDataExtractor.ts @@ -12,5 +12,5 @@ export abstract class AbstractCalleeDataExtractor implements ICalleeDataExtracto * @param {Node} callee * @returns {ICalleeData} */ - public abstract extract (blockScopeBody: ESTree.Node[], callee: ESTree.Node): ICalleeData | null; + public abstract extract(blockScopeBody: ESTree.Node[], callee: ESTree.Node): ICalleeData | null; } diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts index 8d781646..2a366715 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionDeclarationCalleeDataExtractor.ts @@ -16,7 +16,7 @@ export class FunctionDeclarationCalleeDataExtractor extends AbstractCalleeDataEx * @param {Identifier} callee * @returns {ICalleeData} */ - public extract (blockScopeBody: ESTree.Node[], callee: ESTree.Identifier): ICalleeData | null { + public extract(blockScopeBody: ESTree.Node[], callee: ESTree.Identifier): ICalleeData | null { if (!NodeGuards.isIdentifierNode(callee)) { return null; } @@ -41,7 +41,7 @@ export class FunctionDeclarationCalleeDataExtractor extends AbstractCalleeDataEx * @param {string} name * @returns {BlockStatement} */ - private getCalleeBlockStatement (targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { + private getCalleeBlockStatement(targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { let calleeBlockStatement: ESTree.BlockStatement | null = null; estraverse.traverse(targetNode, { diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts index 606ca238..a24cb5c0 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/FunctionExpressionCalleeDataExtractor.ts @@ -16,7 +16,10 @@ export class FunctionExpressionCalleeDataExtractor extends AbstractCalleeDataExt * @param {Identifier} callee * @returns {ICalleeData} */ - public extract (blockScopeBody: ESTree.Node[], callee: ESTree.Identifier | ESTree.FunctionExpression): ICalleeData | null { + public extract( + blockScopeBody: ESTree.Node[], + callee: ESTree.Identifier | ESTree.FunctionExpression + ): ICalleeData | null { let calleeName: string | null = null; let calleeBlockStatement: ESTree.BlockStatement | null = null; @@ -46,7 +49,7 @@ export class FunctionExpressionCalleeDataExtractor extends AbstractCalleeDataExt * @param {string} name * @returns {BlockStatement} */ - private getCalleeBlockStatement (targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { + private getCalleeBlockStatement(targetNode: ESTree.Node, name: string): ESTree.BlockStatement | null { let calleeBlockStatement: ESTree.BlockStatement | null = null; estraverse.traverse(targetNode, { diff --git a/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts b/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts index 1fabd1da..57e22783 100644 --- a/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts +++ b/src/analyzers/calls-graph-analyzer/callee-data-extractors/ObjectExpressionCalleeDataExtractor.ts @@ -18,7 +18,10 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {string | number} nextItemInCallsChain * @returns {boolean} */ - private static isValidTargetPropertyNode (propertyNode: ESTree.Property, nextItemInCallsChain: string | number): boolean { + private static isValidTargetPropertyNode( + propertyNode: ESTree.Property, + nextItemInCallsChain: string | number + ): boolean { if (!propertyNode.key) { return false; } @@ -38,7 +41,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {MemberExpression} callee * @returns {ICalleeData} */ - public extract (blockScopeBody: ESTree.Node[], callee: ESTree.MemberExpression): ICalleeData | null { + public extract(blockScopeBody: ESTree.Node[], callee: ESTree.MemberExpression): ICalleeData | null { if (!NodeGuards.isMemberExpressionNode(callee)) { return null; } @@ -49,7 +52,8 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra return null; } - const functionExpressionName: string | number | null = objectMembersCallsChain[objectMembersCallsChain.length - 1]; + const functionExpressionName: string | number | null = + objectMembersCallsChain[objectMembersCallsChain.length - 1]; const calleeBlockStatement: ESTree.BlockStatement | null = this.getCalleeBlockStatement( NodeStatementUtils.getParentNodeWithStatements(blockScopeBody[0]), objectMembersCallsChain @@ -74,7 +78,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {MemberExpression} memberExpression * @returns {TObjectMembersCallsChain} */ - private createObjectMembersCallsChain ( + private createObjectMembersCallsChain( currentChain: TObjectMembersCallsChain, memberExpression: ESTree.MemberExpression ): TObjectMembersCallsChain { @@ -83,10 +87,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra currentChain.unshift(memberExpression.property.name); } else if ( NodeGuards.isLiteralNode(memberExpression.property) && - ( - typeof memberExpression.property.value === 'string' || - typeof memberExpression.property.value === 'number' - ) + (typeof memberExpression.property.value === 'string' || typeof memberExpression.property.value === 'number') ) { currentChain.unshift(memberExpression.property.value); } else { @@ -108,7 +109,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {TObjectMembersCallsChain} objectMembersCallsChain * @returns {BlockStatement} */ - private getCalleeBlockStatement ( + private getCalleeBlockStatement( targetNode: ESTree.Node, objectMembersCallsChain: TObjectMembersCallsChain ): ESTree.BlockStatement | null { @@ -144,7 +145,7 @@ export class ObjectExpressionCalleeDataExtractor extends AbstractCalleeDataExtra * @param {TObjectMembersCallsChain} objectMembersCallsChain * @returns {BlockStatement} */ - private findCalleeBlockStatement ( + private findCalleeBlockStatement( objectExpressionProperties: (ESTree.Property | ESTree.SpreadElement)[], objectMembersCallsChain: TObjectMembersCallsChain ): ESTree.BlockStatement | null { diff --git a/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts b/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts index 79efad5c..557e3bed 100644 --- a/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts +++ b/src/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.ts @@ -37,9 +37,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres /** * @param {IRandomGenerator} randomGenerator */ - public constructor ( - @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator - ) { + public constructor(@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator) { this.randomGenerator = randomGenerator; } @@ -48,10 +46,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres * @param {number} additionalPartsCount * @returns {TNumberNumericalExpressionData} */ - public analyze ( - number: number, - additionalPartsCount: number - ): TNumberNumericalExpressionData { + public analyze(number: number, additionalPartsCount: number): TNumberNumericalExpressionData { if (isNaN(number)) { throw new Error('Given value is NaN'); } @@ -70,7 +65,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres * @param {number} additionalPartsCount * @returns {number[]} */ - private generateAdditionParts (number: number, additionalPartsCount: number): number[] { + private generateAdditionParts(number: number, additionalPartsCount: number): number[] { const additionParts = []; const upperNumberLimit: number = Math.min(Math.abs(number * 2), Number.MAX_SAFE_INTEGER); @@ -115,7 +110,7 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres * @param {number} number * @returns {number | number[]} */ - private mixWithMultiplyParts (number: number): number | number[] { + private mixWithMultiplyParts(number: number): number | number[] { const shouldMixWithMultiplyParts: boolean = this.randomGenerator.getMathRandom() > 0.5; if (!shouldMixWithMultiplyParts || number === 0) { @@ -125,8 +120,8 @@ export class NumberNumericalExpressionAnalyzer implements INumberNumericalExpres let factors: number[] | null = this.numberFactorsMap.get(number) ?? null; if (!factors) { - factors = NumberUtils.getFactors(number); - this.numberFactorsMap.set(number, factors); + factors = NumberUtils.getFactors(number); + this.numberFactorsMap.set(number, factors); } if (!factors.length) { diff --git a/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts b/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts index c3e2fa62..cbfb43f5 100644 --- a/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts +++ b/src/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -24,18 +24,17 @@ export class PrevailingKindOfVariablesAnalyzer implements IPrevailingKindOfVaria /** * @type {ESTree.VariableDeclaration['kind']} */ - private prevailingKindOfVariables: ESTree.VariableDeclaration['kind'] = PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; + private prevailingKindOfVariables: ESTree.VariableDeclaration['kind'] = + PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; - public constructor ( - @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils - ) { + public constructor(@inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils) { this.arrayUtils = arrayUtils; } /** * @param {Program} astTree */ - public analyze (astTree: ESTree.Program): void { + public analyze(astTree: ESTree.Program): void { const variableKinds: ESTree.VariableDeclaration['kind'][] = []; estraverse.traverse(astTree, { @@ -48,14 +47,15 @@ export class PrevailingKindOfVariablesAnalyzer implements IPrevailingKindOfVaria } }); - this.prevailingKindOfVariables = this.arrayUtils.findMostOccurringElement(variableKinds) - ?? PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; + this.prevailingKindOfVariables = + this.arrayUtils.findMostOccurringElement(variableKinds) ?? + PrevailingKindOfVariablesAnalyzer.defaultKindOfVariables; } /** * @returns {VariableDeclaration["kind"]} */ - public getPrevailingKind (): ESTree.VariableDeclaration['kind'] { + public getPrevailingKind(): ESTree.VariableDeclaration['kind'] { return this.prevailingKindOfVariables; } } diff --git a/src/analyzers/scope-analyzer/ScopeAnalyzer.ts b/src/analyzers/scope-analyzer/ScopeAnalyzer.ts index f4ea1f2c..169e3339 100644 --- a/src/analyzers/scope-analyzer/ScopeAnalyzer.ts +++ b/src/analyzers/scope-analyzer/ScopeAnalyzer.ts @@ -1,4 +1,4 @@ -import { injectable, } from 'inversify'; +import { injectable } from 'inversify'; import * as acorn from 'acorn'; import * as eslintScope from 'eslint-scope'; @@ -28,10 +28,7 @@ export class ScopeAnalyzer implements IScopeAnalyzer { /** * @type {acorn.Options['sourceType'][]} */ - private static readonly sourceTypes: acorn.Options['sourceType'][] = [ - 'script', - 'module' - ]; + private static readonly sourceTypes: acorn.Options['sourceType'][] = ['script', 'module']; /** * @type {number} @@ -49,7 +46,7 @@ export class ScopeAnalyzer implements IScopeAnalyzer { * * @param {Node} astTree */ - private static attachMissingRanges (astTree: ESTree.Node): void { + private static attachMissingRanges(astTree: ESTree.Node): void { estraverse.replace(astTree, { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node => { if (!node.range) { @@ -68,14 +65,14 @@ export class ScopeAnalyzer implements IScopeAnalyzer { * @param {Node} node * @returns {boolean} */ - private static isRootNode (node: ESTree.Node): boolean { + private static isRootNode(node: ESTree.Node): boolean { return NodeGuards.isProgramNode(node) || node.parentNode === node; } /** * @param {Program} astTree */ - public analyze (astTree: ESTree.Node): void { + public analyze(astTree: ESTree.Node): void { const sourceTypeLength: number = ScopeAnalyzer.sourceTypes.length; ScopeAnalyzer.attachMissingRanges(astTree); @@ -104,15 +101,12 @@ export class ScopeAnalyzer implements IScopeAnalyzer { * @param {Node} node * @returns {Scope} */ - public acquireScope (node: ESTree.Node): eslintScope.Scope { + public acquireScope(node: ESTree.Node): eslintScope.Scope { if (!this.scopeManager) { throw new Error('Scope manager is not defined'); } - const scope: eslintScope.Scope | null = this.scopeManager.acquire( - node, - ScopeAnalyzer.isRootNode(node) - ); + const scope: eslintScope.Scope | null = this.scopeManager.acquire(node, ScopeAnalyzer.isRootNode(node)); if (!scope) { throw new Error('Cannot acquire scope for node'); @@ -126,7 +120,7 @@ export class ScopeAnalyzer implements IScopeAnalyzer { /** * @param {Scope} scope */ - private sanitizeScopes (scope: eslintScope.Scope): void { + private sanitizeScopes(scope: eslintScope.Scope): void { scope.childScopes.forEach((childScope: eslintScope.Scope) => { // fix of class scopes // trying to move class scope references to the parent scope @@ -138,13 +132,15 @@ export class ScopeAnalyzer implements IScopeAnalyzer { // class name variable is always first const classNameVariable: eslintScope.Variable = childScope.variables[0]; - const upperVariable: eslintScope.Variable | undefined = childScope.upper.variables - .find((variable: eslintScope.Variable) => { - const isValidClassNameVariable: boolean = classNameVariable.defs - .some((definition: eslintScope.Definition) => definition.type === 'ClassName'); + const upperVariable: eslintScope.Variable | undefined = childScope.upper.variables.find( + (variable: eslintScope.Variable) => { + const isValidClassNameVariable: boolean = classNameVariable.defs.some( + (definition: eslintScope.Definition) => definition.type === 'ClassName' + ); return isValidClassNameVariable && variable.name === classNameVariable.name; - }); + } + ); upperVariable?.references.push(...childScope.variables[0].references); } diff --git a/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts b/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts index f10acb78..c6cce7c3 100644 --- a/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts +++ b/src/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -51,10 +51,10 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, - @inject(ServiceIdentifiers.IOptions) options: IOptions, + @inject(ServiceIdentifiers.IOptions) options: IOptions ) { this.stringArrayStorage = stringArrayStorage; this.randomGenerator = randomGenerator; @@ -64,7 +64,7 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { /** * @param {Program} astTree */ - public analyze (astTree: ESTree.Program): void { + public analyze(astTree: ESTree.Program): void { if (!this.options.stringArray) { return; } @@ -92,7 +92,7 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { * @param {Literal} literalNode * @param {Node} parentNode */ - public analyzeLiteralNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): void { + public analyzeLiteralNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): void { if (!NodeLiteralUtils.isStringLiteralNode(literalNode)) { return; } @@ -111,18 +111,15 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { /** * @param {TStringLiteralNode} literalNode */ - public addItemDataForLiteralNode (literalNode: TStringLiteralNode): void { - this.stringArrayStorageData.set( - literalNode, - this.stringArrayStorage.getOrThrow(literalNode.value) - ); + public addItemDataForLiteralNode(literalNode: TStringLiteralNode): void { + this.stringArrayStorageData.set(literalNode, this.stringArrayStorage.getOrThrow(literalNode.value)); } /** * @param {Literal} literalNode * @returns {IStringArrayStorageItemData | undefined} */ - public getItemDataForLiteralNode (literalNode: ESTree.Literal): IStringArrayStorageItemData | undefined { + public getItemDataForLiteralNode(literalNode: ESTree.Literal): IStringArrayStorageItemData | undefined { return this.stringArrayStorageData.get(literalNode); } @@ -130,15 +127,17 @@ export class StringArrayStorageAnalyzer implements IStringArrayStorageAnalyzer { * @param {TStringLiteralNode} literalNode * @returns {boolean} */ - private shouldAddValueToStringArray (literalNode: TStringLiteralNode): boolean { + private shouldAddValueToStringArray(literalNode: TStringLiteralNode): boolean { const isForceTransformNode: boolean = NodeMetadata.isForceTransformNode(literalNode); if (isForceTransformNode) { return true; } - return literalNode.value.length >= StringArrayStorageAnalyzer.minimumLengthForStringArray - && !!this.options.stringArrayThreshold - && this.randomGenerator.getMathRandom() <= this.options.stringArrayThreshold; + return ( + literalNode.value.length >= StringArrayStorageAnalyzer.minimumLengthForStringArray && + !!this.options.stringArrayThreshold && + this.randomGenerator.getMathRandom() <= this.options.stringArrayThreshold + ); } } diff --git a/src/cli/JavaScriptObfuscatorCLI.ts b/src/cli/JavaScriptObfuscatorCLI.ts index 8a7621d4..9d905acc 100644 --- a/src/cli/JavaScriptObfuscatorCLI.ts +++ b/src/cli/JavaScriptObfuscatorCLI.ts @@ -39,11 +39,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { /** * @type {string[]} */ - public static readonly availableInputExtensions: string[] = [ - '.js', - '.mjs', - '.cjs' - ]; + public static readonly availableInputExtensions: string[] = ['.js', '.mjs', '.cjs']; /** * @type {BufferEncoding} @@ -104,7 +100,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { /** * @param {string[]} argv */ - public constructor (argv: string[]) { + public constructor(argv: string[]) { this.rawArguments = argv; this.arguments = argv.slice(2); } @@ -113,7 +109,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { * @param {TInputCLIOptions} inputOptions * @returns {TInputOptions} */ - private static buildOptions (inputOptions: TInputCLIOptions): TInputOptions { + private static buildOptions(inputOptions: TInputCLIOptions): TInputOptions { const inputCLIOptions: TInputOptions = JavaScriptObfuscatorCLI.filterOptions(inputOptions); const configFilePath: string | undefined = inputOptions.config; const configFileLocation: string = configFilePath ? path.resolve(configFilePath, '.') : ''; @@ -130,23 +126,21 @@ export class JavaScriptObfuscatorCLI implements IInitializable { * @param {TObject} options * @returns {TInputOptions} */ - private static filterOptions (options: TInputCLIOptions): TInputOptions { + private static filterOptions(options: TInputCLIOptions): TInputOptions { const filteredOptions: TInputOptions = {}; - Object - .keys(options) - .forEach((option: keyof TInputCLIOptions) => { - if (options[option] === undefined) { - return; - } + Object.keys(options).forEach((option: keyof TInputCLIOptions) => { + if (options[option] === undefined) { + return; + } - filteredOptions[option] = options[option]; - }); + filteredOptions[option] = options[option]; + }); return filteredOptions; } - public initialize (): void { + public initialize(): void { this.commands = new commander.Command(); this.configureCommands(); @@ -154,18 +148,14 @@ export class JavaScriptObfuscatorCLI implements IInitializable { this.inputPath = path.normalize(this.commands.args[0] || ''); this.inputCLIOptions = JavaScriptObfuscatorCLI.buildOptions(this.commands.opts()); - this.sourceCodeFileUtils = new SourceCodeFileUtils( - this.inputPath, - this.inputCLIOptions + this.sourceCodeFileUtils = new SourceCodeFileUtils(this.inputPath, this.inputCLIOptions); + this.obfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(this.inputPath, this.inputCLIOptions); + this.identifierNamesCacheFileUtils = new IdentifierNamesCacheFileUtils( + this.inputCLIOptions.identifierNamesCachePath ); - this.obfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - this.inputPath, - this.inputCLIOptions - ); - this.identifierNamesCacheFileUtils = new IdentifierNamesCacheFileUtils(this.inputCLIOptions.identifierNamesCachePath); } - public run (): void { + public run(): void { const canShowHelp: boolean = !this.arguments.length || this.arguments.includes('--help'); if (canShowHelp) { @@ -179,41 +169,20 @@ export class JavaScriptObfuscatorCLI implements IInitializable { this.processSourceCodeData(sourceCodeData); } - private configureCommands (): void { + private configureCommands(): void { this.commands .usage(' [options]') - .version( - Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP), - '-v, --version' - ) - .option( - '-o, --output ', - 'Output path for obfuscated code' - ) - .option( - '--compact ', - 'Disable one line output code compacting', - BooleanSanitizer - ) - .option( - '--config ', - 'Name of js / json config file' - ) - .option( - '--control-flow-flattening ', - 'Enables control flow flattening', - BooleanSanitizer - ) + .version(Utils.buildVersionMessage(process.env.VERSION, process.env.BUILD_TIMESTAMP), '-v, --version') + .option('-o, --output ', 'Output path for obfuscated code') + .option('--compact ', 'Disable one line output code compacting', BooleanSanitizer) + .option('--config ', 'Name of js / json config file') + .option('--control-flow-flattening ', 'Enables control flow flattening', BooleanSanitizer) .option( '--control-flow-flattening-threshold ', 'The probability that the control flow flattening transformation will be applied to the node', parseFloat ) - .option( - '--dead-code-injection ', - 'Enables dead code injection', - BooleanSanitizer - ) + .option('--dead-code-injection ', 'Enables dead code injection', BooleanSanitizer) .option( '--dead-code-injection-threshold ', 'The probability that the dead code injection transformation will be applied to the node', @@ -241,7 +210,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { ) .option( '--domain-lock-redirect-url ', - 'Allows the browser to be redirected to a passed URL if the source code isn\'t run on the domains specified by --domain-lock', + 'Allows the browser to be redirected to a passed URL if the source code isn\'t run on the domains specified by --domain-lock' ) .option( '--exclude (comma separated, without whitespaces)', @@ -253,42 +222,31 @@ export class JavaScriptObfuscatorCLI implements IInitializable { 'Enables force transformation of string literals, which being matched by passed RegExp patterns (comma separated)', ArraySanitizer ) - .option( - '--identifier-names-cache-path ', - 'Sets path for identifier names cache' - ) + .option('--identifier-names-cache-path ', 'Sets path for identifier names cache') .option( '--identifier-names-generator ', 'Sets identifier names generator. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(IdentifierNamesGenerator)}. ` + - `Default: ${IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator}` - ) - .option( - '--identifiers-prefix ', - 'Sets prefix for all global identifiers' + `Values: ${CLIUtils.stringifyOptionAvailableValues(IdentifierNamesGenerator)}. ` + + `Default: ${IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator}` ) + .option('--identifiers-prefix ', 'Sets prefix for all global identifiers') .option( '--identifiers-dictionary (comma separated, without whitespaces)', 'Identifiers dictionary (comma separated) for `--identifier-names-generator dictionary` option', ArraySanitizer ) .option( - '--ignore-imports ', 'Prevents obfuscation of `require` and `dynamic` imports', - BooleanSanitizer - ) - .option( - '--log ', 'Enables logging of the information to the console', - BooleanSanitizer - ) - .option( - '--numbers-to-expressions ', 'Enables numbers conversion to expressions', + '--ignore-imports ', + 'Prevents obfuscation of `require` and `dynamic` imports', BooleanSanitizer ) + .option('--log ', 'Enables logging of the information to the console', BooleanSanitizer) + .option('--numbers-to-expressions ', 'Enables numbers conversion to expressions', BooleanSanitizer) .option( '--options-preset ', 'Allows to set options preset. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(OptionsPreset)}. ` + - `Default: ${OptionsPreset.Default}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(OptionsPreset)}. ` + + `Default: ${OptionsPreset.Default}` ) .option( '--reserved-names (comma separated, without whitespaces)', @@ -301,38 +259,33 @@ export class JavaScriptObfuscatorCLI implements IInitializable { ArraySanitizer ) .option( - '--rename-globals ', 'Allows to enable obfuscation of global variable and function names with declaration', + '--rename-globals ', + 'Allows to enable obfuscation of global variable and function names with declaration', BooleanSanitizer ) .option( - '--rename-properties ', 'UNSAFE: Enables renaming of property names. This probably MAY break your code', + '--rename-properties ', + 'UNSAFE: Enables renaming of property names. This probably MAY break your code', BooleanSanitizer ) .option( '--rename-properties-mode ', 'Specify `--rename-properties` option mode. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(RenamePropertiesMode)}. ` + - `Default: ${RenamePropertiesMode.Safe}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(RenamePropertiesMode)}. ` + + `Default: ${RenamePropertiesMode.Safe}` ) .option( '--seed ', 'Sets seed for random generator. This is useful for creating repeatable results.', parseFloat ) + .option('--self-defending ', 'Disables self-defending for obfuscated code', BooleanSanitizer) .option( - '--self-defending ', - 'Disables self-defending for obfuscated code', - BooleanSanitizer - ) - .option( - '--simplify ', 'Enables additional code obfuscation through simplification', - BooleanSanitizer - ) - .option( - '--source-map ', - 'Enables source map generation', + '--simplify ', + 'Enables additional code obfuscation through simplification', BooleanSanitizer ) + .option('--source-map ', 'Enables source map generation', BooleanSanitizer) .option( '--source-map-base-url ', 'Sets base url to the source map import url when `--source-map-mode=separate`' @@ -344,25 +297,21 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--source-map-mode ', 'Specify source map output mode. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapMode)}. ` + - `Default: ${SourceMapMode.Separate}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapMode)}. ` + + `Default: ${SourceMapMode.Separate}` ) .option( '--source-map-sources-mode ', 'Specify source map sources mode. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapSourcesMode)}. ` + - `Default: ${SourceMapSourcesMode.SourcesContent}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(SourceMapSourcesMode)}. ` + + `Default: ${SourceMapSourcesMode.SourcesContent}` ) .option( '--split-strings ', 'Splits literal strings into chunks with length of `splitStringsChunkLength` option value', BooleanSanitizer ) - .option( - '--split-strings-chunk-length ', - 'Sets chunk length of `splitStrings` option', - parseFloat - ) + .option('--split-strings-chunk-length ', 'Sets chunk length of `splitStrings` option', parseFloat) .option( '--string-array ', 'Enables gathering of all literal strings into an array and replacing every literal string with an array call', @@ -381,15 +330,15 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--string-array-encoding (comma separated, without whitespaces)', 'Encodes each string in strings array using base64 or rc4 (this option can slow down your code speed). ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayEncoding)}. ` + - `Default: ${StringArrayEncoding.None}`, + `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayEncoding)}. ` + + `Default: ${StringArrayEncoding.None}`, ArraySanitizer ) .option( '--string-array-indexes-type (comma separated, without whitespaces)', 'Encodes each string in strings array using base64 or rc4 (this option can slow down your code speed). ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayIndexesType)}. ` + - `Default: ${StringArrayIndexesType.HexadecimalNumber}`, + `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayIndexesType)}. ` + + `Default: ${StringArrayIndexesType.HexadecimalNumber}`, ArraySanitizer ) .option( @@ -398,13 +347,11 @@ export class JavaScriptObfuscatorCLI implements IInitializable { BooleanSanitizer ) .option( - '--string-array-rotate ', 'Enable rotation of string array values during obfuscation', - BooleanSanitizer - ) - .option( - '--string-array-shuffle ', 'Randomly shuffles string array items', + '--string-array-rotate ', + 'Enable rotation of string array values during obfuscation', BooleanSanitizer ) + .option('--string-array-shuffle ', 'Randomly shuffles string array items', BooleanSanitizer) .option( '--string-array-wrappers-count ', 'Sets the count of wrappers for the string array inside each root or function scope', @@ -423,8 +370,8 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--string-array-wrappers-type ', 'Allows to select a type of the wrappers that are appending by the `--string-array-wrappers-count` option. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayWrappersType)}. ` + - `Default: ${StringArrayWrappersType.Variable}` + `Values: ${CLIUtils.stringifyOptionAvailableValues(StringArrayWrappersType)}. ` + + `Default: ${StringArrayWrappersType.Variable}` ) .option( '--string-array-threshold ', @@ -434,14 +381,10 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .option( '--target ', 'Allows to set target environment for obfuscated code. ' + - `Values: ${CLIUtils.stringifyOptionAvailableValues(ObfuscationTarget)}. ` + - `Default: ${ObfuscationTarget.Browser}` - ) - .option( - '--transform-object-keys ', - 'Enables transformation of object keys', - BooleanSanitizer + `Values: ${CLIUtils.stringifyOptionAvailableValues(ObfuscationTarget)}. ` + + `Default: ${ObfuscationTarget.Browser}` ) + .option('--transform-object-keys ', 'Enables transformation of object keys', BooleanSanitizer) .option( '--unicode-escape-sequence ', 'Allows to enable/disable string conversion to unicode escape sequence', @@ -450,11 +393,13 @@ export class JavaScriptObfuscatorCLI implements IInitializable { .parse(this.rawArguments); } - private configureHelp (): void { + private configureHelp(): void { this.commands.on('--help', () => { console.log(' Examples:\n'); console.log(' %> javascript-obfuscator input_file_name.js --compact true --self-defending false'); - console.log(' %> javascript-obfuscator input_file_name.js --output output_file_name.js --compact true --self-defending false'); + console.log( + ' %> javascript-obfuscator input_file_name.js --output output_file_name.js --compact true --self-defending false' + ); console.log(' %> javascript-obfuscator input_directory_name --compact true --self-defending false'); console.log(''); }); @@ -463,24 +408,16 @@ export class JavaScriptObfuscatorCLI implements IInitializable { /** * @param {IFileData[]} sourceCodeData */ - private processSourceCodeData (sourceCodeData: IFileData[]): void { + private processSourceCodeData(sourceCodeData: IFileData[]): void { sourceCodeData.forEach(({ filePath, content }: IFileData, index: number) => { const outputCodePath: string = this.obfuscatedCodeFileUtils.getOutputCodePath(filePath); try { - Logger.log( - Logger.colorInfo, - LoggingPrefix.CLI, - `Obfuscating file: ${filePath}...` - ); + Logger.log(Logger.colorInfo, LoggingPrefix.CLI, `Obfuscating file: ${filePath}...`); this.processSourceCode(content, filePath, outputCodePath, index); } catch (error) { - Logger.log( - Logger.colorInfo, - LoggingPrefix.CLI, - `Error in file: ${filePath}...` - ); + Logger.log(Logger.colorInfo, LoggingPrefix.CLI, `Error in file: ${filePath}...`); throw error; } @@ -493,7 +430,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { * @param {string} outputCodePath * @param {number | null} sourceCodeIndex */ - private processSourceCode ( + private processSourceCode( sourceCode: string, inputCodePath: string, outputCodePath: string, @@ -503,12 +440,12 @@ export class JavaScriptObfuscatorCLI implements IInitializable { ...this.inputCLIOptions, identifierNamesCache: this.identifierNamesCacheFileUtils.readFile(), inputFileName: path.basename(inputCodePath), - ...sourceCodeIndex !== null && { + ...(sourceCodeIndex !== null && { identifiersPrefix: Utils.getIdentifiersPrefixForMultipleSources( this.inputCLIOptions.identifiersPrefix, sourceCodeIndex ) - } + }) }; if (options.sourceMap) { @@ -523,7 +460,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { * @param {string} outputCodePath * @param {TInputOptions} options */ - private processSourceCodeWithoutSourceMap ( + private processSourceCodeWithoutSourceMap( sourceCode: string, outputCodePath: string, options: TInputOptions @@ -539,11 +476,7 @@ export class JavaScriptObfuscatorCLI implements IInitializable { * @param {string} outputCodePath * @param {TInputOptions} options */ - private processSourceCodeWithSourceMap ( - sourceCode: string, - outputCodePath: string, - options: TInputOptions - ): void { + private processSourceCodeWithSourceMap(sourceCode: string, outputCodePath: string, options: TInputOptions): void { const outputSourceMapPath: string = this.obfuscatedCodeFileUtils.getOutputSourceMapPath( outputCodePath, options.sourceMapFileName ?? '' diff --git a/src/cli/sanitizers/ArraySanitizer.ts b/src/cli/sanitizers/ArraySanitizer.ts index c52ff71a..07b2e563 100644 --- a/src/cli/sanitizers/ArraySanitizer.ts +++ b/src/cli/sanitizers/ArraySanitizer.ts @@ -4,9 +4,11 @@ import { TCLISanitizer } from '../../types/cli/TCLISanitizer'; * @param {string} value * @returns {string[]} */ -export const ArraySanitizer: TCLISanitizer = (value: string): string[] => { +export const ArraySanitizer: TCLISanitizer = (value: string): string[] => { if (value.endsWith(',')) { - throw new SyntaxError('Multiple values should be wrapped inside quotes: --option-name \'value1\',\'value2\''); + throw new SyntaxError( + "Multiple values should be wrapped inside quotes: --option-name 'value1','value2'" + ); } return value.split(',').map((string: string) => string.trim()); diff --git a/src/cli/sanitizers/BooleanSanitizer.ts b/src/cli/sanitizers/BooleanSanitizer.ts index 2bbfb222..2e58866a 100644 --- a/src/cli/sanitizers/BooleanSanitizer.ts +++ b/src/cli/sanitizers/BooleanSanitizer.ts @@ -4,6 +4,6 @@ import { TCLISanitizer } from '../../types/cli/TCLISanitizer'; * @param {string} value * @returns {boolean} */ -export const BooleanSanitizer: TCLISanitizer = (value: string): boolean => { +export const BooleanSanitizer: TCLISanitizer = (value: string): boolean => { return value === 'true' || value === '1'; }; diff --git a/src/cli/utils/CLIUtils.ts b/src/cli/utils/CLIUtils.ts index 50ce3186..4dcc4a86 100644 --- a/src/cli/utils/CLIUtils.ts +++ b/src/cli/utils/CLIUtils.ts @@ -8,17 +8,13 @@ export class CLIUtils { /** * @type {string[]} */ - public static readonly allowedConfigFileExtensions: string[] = [ - '.js', - '.json', - '.cjs' - ]; + public static readonly allowedConfigFileExtensions: string[] = ['.js', '.json', '.cjs']; /** * @param {string} configPath * @returns {TDictionary} */ - public static getUserConfig (configPath: string): TDictionary { + public static getUserConfig(configPath: string): TDictionary { let config: TDictionary; const configFileExtension: string = path.extname(configPath); @@ -45,7 +41,7 @@ export class CLIUtils { * @param {TDictionary} optionEnum * @returns {string} */ - public static stringifyOptionAvailableValues (optionEnum: TDictionary): string { + public static stringifyOptionAvailableValues(optionEnum: TDictionary): string { return Object.values(optionEnum).join(`${StringSeparator.Comma} `); } } diff --git a/src/cli/utils/IdentifierNamesCacheFileUtils.ts b/src/cli/utils/IdentifierNamesCacheFileUtils.ts index f7f76808..47170dea 100644 --- a/src/cli/utils/IdentifierNamesCacheFileUtils.ts +++ b/src/cli/utils/IdentifierNamesCacheFileUtils.ts @@ -24,7 +24,7 @@ export class IdentifierNamesCacheFileUtils { /** * @param {string} identifierNamesCachePath */ - public constructor (identifierNamesCachePath: string | undefined) { + public constructor(identifierNamesCachePath: string | undefined) { this.identifierNamesCachePath = identifierNamesCachePath; } @@ -32,10 +32,12 @@ export class IdentifierNamesCacheFileUtils { * @param {string} filePath * @returns {boolean} */ - private static isValidFilePath (filePath: string): boolean { + private static isValidFilePath(filePath: string): boolean { try { - return fs.statSync(filePath).isFile() - && path.extname(filePath) === IdentifierNamesCacheFileUtils.identifierNamesCacheExtension; + return ( + fs.statSync(filePath).isFile() && + path.extname(filePath) === IdentifierNamesCacheFileUtils.identifierNamesCacheExtension + ); } catch { return false; } @@ -45,7 +47,7 @@ export class IdentifierNamesCacheFileUtils { * @param {string} filePath * @returns {IFileData} */ - private static readFile (filePath: string): IFileData { + private static readFile(filePath: string): IFileData { return { filePath: path.normalize(filePath), content: fs.readFileSync(filePath, JavaScriptObfuscatorCLI.encoding) @@ -55,15 +57,17 @@ export class IdentifierNamesCacheFileUtils { /** * @returns {TIdentifierNamesCache | null} */ - public readFile (): TIdentifierNamesCache | null { + public readFile(): TIdentifierNamesCache | null { if (!this.identifierNamesCachePath) { return null; } if (!IdentifierNamesCacheFileUtils.isValidFilePath(this.identifierNamesCachePath)) { - throw new ReferenceError(`Given identifier names cache path must be a valid ${ - IdentifierNamesCacheFileUtils.identifierNamesCacheExtension - } file path`); + throw new ReferenceError( + `Given identifier names cache path must be a valid ${ + IdentifierNamesCacheFileUtils.identifierNamesCacheExtension + } file path` + ); } const fileData: IFileData = IdentifierNamesCacheFileUtils.readFile(this.identifierNamesCachePath); @@ -77,14 +81,16 @@ export class IdentifierNamesCacheFileUtils { // Already written identifier names cache file return JSON.parse(fileData.content); } catch { - throw new ReferenceError('Identifier names cache file must contains a json dictionary with identifier names'); + throw new ReferenceError( + 'Identifier names cache file must contains a json dictionary with identifier names' + ); } } /** * @param {TIdentifierNamesCache} identifierNamesCache */ - public writeFile (identifierNamesCache: TIdentifierNamesCache): void { + public writeFile(identifierNamesCache: TIdentifierNamesCache): void { if (!this.identifierNamesCachePath) { return; } diff --git a/src/cli/utils/ObfuscatedCodeFileUtils.ts b/src/cli/utils/ObfuscatedCodeFileUtils.ts index de7824f2..da157c6a 100644 --- a/src/cli/utils/ObfuscatedCodeFileUtils.ts +++ b/src/cli/utils/ObfuscatedCodeFileUtils.ts @@ -23,10 +23,7 @@ export class ObfuscatedCodeFileUtils { * @param {string} inputPath * @param {TInputCLIOptions} options */ - public constructor ( - inputPath: string, - options: TInputCLIOptions - ) { + public constructor(inputPath: string, options: TInputCLIOptions) { this.inputPath = path.normalize(inputPath); this.options = options; } @@ -35,11 +32,9 @@ export class ObfuscatedCodeFileUtils { * @param {string} filePath * @returns {string} */ - public getOutputCodePath (filePath: string): string { + public getOutputCodePath(filePath: string): string { const normalizedFilePath: string = path.normalize(filePath); - const normalizedRawOutputPath: string | null = this.options.output - ? path.normalize(this.options.output) - : null; + const normalizedRawOutputPath: string | null = this.options.output ? path.normalize(this.options.output) : null; if (!normalizedRawOutputPath) { return normalizedFilePath @@ -54,9 +49,8 @@ export class ObfuscatedCodeFileUtils { const outputPathExtName: string = path.extname(normalizedRawOutputPath); const isDirectoryRawInputPath: boolean = rawInputPathStats.isDirectory(); - const isDirectoryRawOutputPath: boolean = !JavaScriptObfuscatorCLI - .availableInputExtensions - .includes(outputPathExtName); + const isDirectoryRawOutputPath: boolean = + !JavaScriptObfuscatorCLI.availableInputExtensions.includes(outputPathExtName); if (isDirectoryRawInputPath) { if (isDirectoryRawOutputPath) { @@ -90,7 +84,7 @@ export class ObfuscatedCodeFileUtils { * @param {string} sourceMapFileName * @returns {string} */ - public getOutputSourceMapPath (outputCodePath: string, sourceMapFileName: string = ''): string { + public getOutputSourceMapPath(outputCodePath: string, sourceMapFileName: string = ''): string { if (!outputCodePath) { throw new Error('Output code path is empty'); } @@ -110,9 +104,7 @@ export class ObfuscatedCodeFileUtils { // File path with directory, like: `foo/bar.js`, or without, like: `bar.js` const isFilePathWithDirectory: boolean = indexOfLastSeparator > 0; - sourceMapPath = isFilePathWithDirectory - ? normalizedOutputCodePath.slice(0, indexOfLastSeparator) - : ''; + sourceMapPath = isFilePathWithDirectory ? normalizedOutputCodePath.slice(0, indexOfLastSeparator) : ''; } else { sourceMapPath = normalizedOutputCodePath; } @@ -125,7 +117,10 @@ export class ObfuscatedCodeFileUtils { if (!/\.js\.map$/.test(normalizedOutputCodePath)) { parsedOutputCodePath = path.parse(normalizedOutputCodePath); - const outputCodePathWithoutExtension: string = path.join(parsedOutputCodePath.dir, parsedOutputCodePath.name); + const outputCodePathWithoutExtension: string = path.join( + parsedOutputCodePath.dir, + parsedOutputCodePath.name + ); normalizedOutputCodePath = `${outputCodePathWithoutExtension}.js.map`; } else if (/\.js$/.test(normalizedOutputCodePath)) { @@ -139,7 +134,7 @@ export class ObfuscatedCodeFileUtils { * @param {string} outputPath * @param {string} data */ - public writeFile (outputPath: string, data: string): void { + public writeFile(outputPath: string, data: string): void { mkdirp.sync(path.dirname(outputPath)); fs.writeFileSync(outputPath, data, { diff --git a/src/cli/utils/SourceCodeFileUtils.ts b/src/cli/utils/SourceCodeFileUtils.ts index f89610c6..5d979e36 100644 --- a/src/cli/utils/SourceCodeFileUtils.ts +++ b/src/cli/utils/SourceCodeFileUtils.ts @@ -23,10 +23,7 @@ export class SourceCodeFileUtils { * @param {string} inputPath * @param {TInputCLIOptions} options */ - public constructor ( - inputPath: string, - options: TInputCLIOptions - ) { + public constructor(inputPath: string, options: TInputCLIOptions) { this.inputPath = inputPath; this.options = options; } @@ -36,15 +33,15 @@ export class SourceCodeFileUtils { * @param {string[]} excludePatterns * @returns {boolean} */ - private static isExcludedPath (filePath: string, excludePatterns: string[] = []): boolean { + private static isExcludedPath(filePath: string, excludePatterns: string[] = []): boolean { if (!excludePatterns.length) { return false; } const fileName: string = path.basename(filePath); const isExcludedFilePathByGlobPattern: boolean = !!multimatch([filePath], excludePatterns).length; - const isExcludedFilePathByInclusion: boolean = excludePatterns.some((excludePattern: string) => - filePath.includes(excludePattern) || fileName.includes(excludePattern) + const isExcludedFilePathByInclusion: boolean = excludePatterns.some( + (excludePattern: string) => filePath.includes(excludePattern) || fileName.includes(excludePattern) ); return isExcludedFilePathByInclusion || isExcludedFilePathByGlobPattern; @@ -54,7 +51,7 @@ export class SourceCodeFileUtils { * @param {string} filePath * @returns {boolean} */ - private static isDirectoryPath (filePath: string): boolean { + private static isDirectoryPath(filePath: string): boolean { try { return fs.statSync(filePath).isDirectory(); } catch { @@ -66,7 +63,7 @@ export class SourceCodeFileUtils { * @param {string} filePath * @returns {boolean} */ - private static isFilePath (filePath: string): boolean { + private static isFilePath(filePath: string): boolean { try { return fs.statSync(filePath).isFile(); } catch { @@ -79,7 +76,7 @@ export class SourceCodeFileUtils { * @param {string[]} excludePatterns * @returns {boolean} */ - private static isValidDirectory (directoryPath: string, excludePatterns: string[] = []): boolean { + private static isValidDirectory(directoryPath: string, excludePatterns: string[] = []): boolean { return !SourceCodeFileUtils.isExcludedPath(directoryPath, excludePatterns); } @@ -88,17 +85,19 @@ export class SourceCodeFileUtils { * @param {string[]} excludePatterns * @returns {boolean} */ - private static isValidFile (filePath: string, excludePatterns: string[] = []): boolean { - return JavaScriptObfuscatorCLI.availableInputExtensions.includes(path.extname(filePath)) - && !filePath.includes(JavaScriptObfuscatorCLI.obfuscatedFilePrefix) - && !SourceCodeFileUtils.isExcludedPath(filePath, excludePatterns); + private static isValidFile(filePath: string, excludePatterns: string[] = []): boolean { + return ( + JavaScriptObfuscatorCLI.availableInputExtensions.includes(path.extname(filePath)) && + !filePath.includes(JavaScriptObfuscatorCLI.obfuscatedFilePrefix) && + !SourceCodeFileUtils.isExcludedPath(filePath, excludePatterns) + ); } /** * @param {string} filePath * @returns {string} */ - private static readFile (filePath: string): IFileData { + private static readFile(filePath: string): IFileData { return { filePath: path.normalize(filePath), content: fs.readFileSync(filePath, JavaScriptObfuscatorCLI.encoding) @@ -108,23 +107,22 @@ export class SourceCodeFileUtils { /** * @returns {IFileData[]} */ - public readSourceCode (): IFileData[] { + public readSourceCode(): IFileData[] { if ( - SourceCodeFileUtils.isFilePath(this.inputPath) - && SourceCodeFileUtils.isValidFile(this.inputPath, this.options.exclude) + SourceCodeFileUtils.isFilePath(this.inputPath) && + SourceCodeFileUtils.isValidFile(this.inputPath, this.options.exclude) ) { return [SourceCodeFileUtils.readFile(this.inputPath)]; } if ( - SourceCodeFileUtils.isDirectoryPath(this.inputPath) - && SourceCodeFileUtils.isValidDirectory(this.inputPath, this.options.exclude) + SourceCodeFileUtils.isDirectoryPath(this.inputPath) && + SourceCodeFileUtils.isValidDirectory(this.inputPath, this.options.exclude) ) { return this.readDirectoryRecursive(this.inputPath); } - const availableFilePaths: string = JavaScriptObfuscatorCLI - .availableInputExtensions + const availableFilePaths: string = JavaScriptObfuscatorCLI.availableInputExtensions .map((extension: string) => `\`${extension}\``) .join(', '); @@ -136,31 +134,30 @@ export class SourceCodeFileUtils { * @param {IFileData[]} filesData * @returns {IFileData[]} */ - private readDirectoryRecursive (directoryPath: string, filesData: IFileData[] = []): IFileData[] { - fs.readdirSync(directoryPath, JavaScriptObfuscatorCLI.encoding) - .forEach((fileName: string) => { - const filePath: string = path.join(directoryPath, fileName); + private readDirectoryRecursive(directoryPath: string, filesData: IFileData[] = []): IFileData[] { + fs.readdirSync(directoryPath, JavaScriptObfuscatorCLI.encoding).forEach((fileName: string) => { + const filePath: string = path.join(directoryPath, fileName); - if ( - SourceCodeFileUtils.isDirectoryPath(filePath) - && SourceCodeFileUtils.isValidDirectory(filePath, this.options.exclude) - ) { - filesData.push(...this.readDirectoryRecursive(filePath)); + if ( + SourceCodeFileUtils.isDirectoryPath(filePath) && + SourceCodeFileUtils.isValidDirectory(filePath, this.options.exclude) + ) { + filesData.push(...this.readDirectoryRecursive(filePath)); - return; - } + return; + } - if ( - SourceCodeFileUtils.isFilePath(filePath) - && SourceCodeFileUtils.isValidFile(filePath, this.options.exclude) - ) { - const fileData: IFileData = SourceCodeFileUtils.readFile(filePath); + if ( + SourceCodeFileUtils.isFilePath(filePath) && + SourceCodeFileUtils.isValidFile(filePath, this.options.exclude) + ) { + const fileData: IFileData = SourceCodeFileUtils.readFile(filePath); - filesData.push(fileData); + filesData.push(fileData); - return; - } - }); + return; + } + }); return filesData; } diff --git a/src/code-transformers/AbstractCodeTransformer.ts b/src/code-transformers/AbstractCodeTransformer.ts index 10fde172..513a8171 100644 --- a/src/code-transformers/AbstractCodeTransformer.ts +++ b/src/code-transformers/AbstractCodeTransformer.ts @@ -29,7 +29,7 @@ export abstract class AbstractCodeTransformer implements ICodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -42,5 +42,5 @@ export abstract class AbstractCodeTransformer implements ICodeTransformer { * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - public abstract transformCode (code: string, codeTransformationStage: CodeTransformationStage): string; + public abstract transformCode(code: string, codeTransformationStage: CodeTransformationStage): string; } diff --git a/src/code-transformers/CodeTransformersRunner.ts b/src/code-transformers/CodeTransformersRunner.ts index 35c1b996..0998e2f6 100644 --- a/src/code-transformers/CodeTransformersRunner.ts +++ b/src/code-transformers/CodeTransformersRunner.ts @@ -31,14 +31,11 @@ export class CodeTransformersRunner implements ICodeTransformersRunner { * @param {TNodeTransformerFactory} codeTransformerFactory * @param {ITransformerNamesGroupsBuilder} codeTransformerNamesGroupsBuilder */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__ICodeTransformer) - codeTransformerFactory: TCodeTransformerFactory, + codeTransformerFactory: TCodeTransformerFactory, @inject(ServiceIdentifiers.ICodeTransformerNamesGroupsBuilder) - codeTransformerNamesGroupsBuilder: ITransformerNamesGroupsBuilder< - CodeTransformer, - ICodeTransformer - >, + codeTransformerNamesGroupsBuilder: ITransformerNamesGroupsBuilder ) { this.codeTransformerFactory = codeTransformerFactory; this.codeTransformerNamesGroupsBuilder = codeTransformerNamesGroupsBuilder; @@ -50,7 +47,7 @@ export class CodeTransformersRunner implements ICodeTransformersRunner { * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - public transform ( + public transform( code: string, codeTransformerNames: CodeTransformer[], codeTransformationStage: CodeTransformationStage @@ -59,8 +56,10 @@ export class CodeTransformersRunner implements ICodeTransformersRunner { return code; } - const normalizedCodeTransformers: TDictionary = - this.buildNormalizedCodeTransformers(codeTransformerNames, codeTransformationStage); + const normalizedCodeTransformers: TDictionary = this.buildNormalizedCodeTransformers( + codeTransformerNames, + codeTransformationStage + ); const codeTransformerNamesGroups: CodeTransformer[][] = this.codeTransformerNamesGroupsBuilder.build(normalizedCodeTransformers); @@ -80,21 +79,20 @@ export class CodeTransformersRunner implements ICodeTransformersRunner { * @param {NodeTransformationStage} codeTransformationStage * @returns {TDictionary} */ - private buildNormalizedCodeTransformers ( + private buildNormalizedCodeTransformers( codeTransformerNames: CodeTransformer[], codeTransformationStage: CodeTransformationStage ): TDictionary { - return codeTransformerNames - .reduce>( - (acc: TDictionary, codeTransformerName: CodeTransformer) => { - const codeTransformer: ICodeTransformer = this.codeTransformerFactory(codeTransformerName); + return codeTransformerNames.reduce>( + (acc: TDictionary, codeTransformerName: CodeTransformer) => { + const codeTransformer: ICodeTransformer = this.codeTransformerFactory(codeTransformerName); - return { - ...acc, - [codeTransformerName]: codeTransformer - }; - }, - {} - ); + return { + ...acc, + [codeTransformerName]: codeTransformer + }; + }, + {} + ); } } diff --git a/src/code-transformers/preparing-transformers/HashbangOperatorTransformer.ts b/src/code-transformers/preparing-transformers/HashbangOperatorTransformer.ts index 08b3e452..02cdbd4b 100644 --- a/src/code-transformers/preparing-transformers/HashbangOperatorTransformer.ts +++ b/src/code-transformers/preparing-transformers/HashbangOperatorTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { IOptions } from '../../interfaces/options/IOptions'; @@ -19,7 +19,7 @@ export class HashbangOperatorTransformer extends AbstractCodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -33,7 +33,7 @@ export class HashbangOperatorTransformer extends AbstractCodeTransformer { * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - public transformCode (code: string, codeTransformationStage: CodeTransformationStage): string { + public transformCode(code: string, codeTransformationStage: CodeTransformationStage): string { switch (codeTransformationStage) { case CodeTransformationStage.PreparingTransformers: return this.removeAndSaveHashbangOperatorLine(code); @@ -50,7 +50,7 @@ export class HashbangOperatorTransformer extends AbstractCodeTransformer { * @param {string} code * @returns {string} */ - private removeAndSaveHashbangOperatorLine (code: string): string { + private removeAndSaveHashbangOperatorLine(code: string): string { return code .replace(/^#!.*$(\r?\n)*/m, (substring: string) => { if (substring) { @@ -66,7 +66,7 @@ export class HashbangOperatorTransformer extends AbstractCodeTransformer { * @param {string} code * @returns {string} */ - private appendSavedHashbangOperatorLine (code: string): string { + private appendSavedHashbangOperatorLine(code: string): string { return `${this.hashbangOperatorLine ?? ''}${code}`; } } diff --git a/src/constants/ReservedIdentifierNames.ts b/src/constants/ReservedIdentifierNames.ts index 9ba8e37d..e5c10424 100644 --- a/src/constants/ReservedIdentifierNames.ts +++ b/src/constants/ReservedIdentifierNames.ts @@ -1,11 +1,51 @@ export const reservedIdentifierNames = [ // reserved identifiers - 'byte', 'case', 'char', 'do', 'else', 'enum', 'eval', 'for', 'goto', - 'if', 'in', 'int', 'let', 'long', 'new', 'null', 'this', 'true', 'try', - 'var', 'void', 'with', + 'byte', + 'case', + 'char', + 'do', + 'else', + 'enum', + 'eval', + 'for', + 'goto', + 'if', + 'in', + 'int', + 'let', + 'long', + 'new', + 'null', + 'this', + 'true', + 'try', + 'var', + 'void', + 'with', // reserved global object identifiers - 'Array', 'Attr', 'Audio', 'Blob', 'Cache', 'Date', 'Error', 'Event', - 'Feed', 'File', 'Hz', 'Image', 'Intl', 'Lock', 'Map', 'Math', 'Node', - 'Proxy', 'Range', 'Rect', 'Set', 'Table', 'Text', 'Touch' + 'Array', + 'Attr', + 'Audio', + 'Blob', + 'Cache', + 'Date', + 'Error', + 'Event', + 'Feed', + 'File', + 'Hz', + 'Image', + 'Intl', + 'Lock', + 'Map', + 'Math', + 'Node', + 'Proxy', + 'Range', + 'Rect', + 'Set', + 'Table', + 'Text', + 'Touch' ]; diff --git a/src/container/InversifyContainerFacade.ts b/src/container/InversifyContainerFacade.ts index bacf2713..21eac245 100644 --- a/src/container/InversifyContainerFacade.ts +++ b/src/container/InversifyContainerFacade.ts @@ -46,7 +46,7 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { */ private readonly container: interfaces.Container; - public constructor () { + public constructor() { this.container = new Container(); } @@ -54,10 +54,10 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { * @param {interfaces.ServiceIdentifier} serviceIdentifier * @returns {U} */ - public static getFactory ( + public static getFactory( serviceIdentifier: interfaces.ServiceIdentifier ): (context: interfaces.Context) => (bindingName: T) => U { - return (context: interfaces.Context): (bindingName: T) => U => { + return (context: interfaces.Context): ((bindingName: T) => U) => { return (bindingName: T): U => { return context.container.getNamed(serviceIdentifier, bindingName); }; @@ -68,11 +68,11 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { * @param {interfaces.ServiceIdentifier} serviceIdentifier * @returns {U} */ - public static getCacheFactory ( + public static getCacheFactory( serviceIdentifier: interfaces.ServiceIdentifier ): (context: interfaces.Context) => (bindingName: T) => U { - return (context: interfaces.Context): (bindingName: T) => U => { - const cache: Map = new Map(); + return (context: interfaces.Context): ((bindingName: T) => U) => { + const cache: Map = new Map(); return (bindingName: T): U => { if (cache.has(bindingName)) { @@ -93,33 +93,34 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { * @param {interfaces.ServiceIdentifier[], U>>} dependencies * @returns {(context: interfaces.Context) => (bindingName: T) => U} */ - public static getConstructorFactory ( + public static getConstructorFactory( serviceIdentifier: interfaces.ServiceIdentifier[], U>>, ...dependencies: interfaces.ServiceIdentifier[], U>>[] ): (context: interfaces.Context) => (bindingName: T) => U { - return (context: interfaces.Context): (bindingName: T) => U => { + return (context: interfaces.Context): ((bindingName: T) => U) => { const cache: Map[], U>> = new Map(); const cachedDependencies: Record[] = []; return (bindingName: T): U => { - dependencies.forEach(( - dependency: interfaces.ServiceIdentifier[], U>>, - index: number - ) => { - if (!cachedDependencies[index]) { - cachedDependencies[index] = context.container.get(dependency); + dependencies.forEach( + ( + dependency: interfaces.ServiceIdentifier[], U>>, + index: number + ) => { + if (!cachedDependencies[index]) { + cachedDependencies[index] = context.container.get(dependency); + } } - }); + ); if (cache.has(bindingName)) { return new ([], U>>cache.get(bindingName))(...cachedDependencies); } - const constructor = context.container - .getNamed[], U>>( - serviceIdentifier, - bindingName - ); + const constructor = context.container.getNamed[], U>>( + serviceIdentifier, + bindingName + ); cache.set(bindingName, constructor); @@ -132,7 +133,7 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { * @param {interfaces.ServiceIdentifier} serviceIdentifier * @returns {T} */ - public get (serviceIdentifier: interfaces.ServiceIdentifier): T { + public get(serviceIdentifier: interfaces.ServiceIdentifier): T { return this.container.get(serviceIdentifier); } @@ -141,7 +142,7 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { * @param {string | number | symbol} named * @returns {T} */ - public getNamed (serviceIdentifier: interfaces.ServiceIdentifier, named: string | number | symbol): T { + public getNamed(serviceIdentifier: interfaces.ServiceIdentifier, named: string | number | symbol): T { return this.container.getNamed(serviceIdentifier, named); } @@ -150,7 +151,7 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { * @param {string} sourceMap * @param {TInputOptions} options */ - public load (sourceCode: string, sourceMap: string, options: TInputOptions): void { + public load(sourceCode: string, sourceMap: string, options: TInputOptions): void { this.container .bind(ServiceIdentifiers.ISourceCode) .toDynamicValue(() => new SourceCode(sourceCode, sourceMap)) @@ -161,10 +162,7 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { .toDynamicValue(() => options) .inSingletonScope(); - this.container - .bind(ServiceIdentifiers.ILogger) - .to(Logger) - .inSingletonScope(); + this.container.bind(ServiceIdentifiers.ILogger).to(Logger).inSingletonScope(); this.container .bind(ServiceIdentifiers.IJavaScriptObfuscator) @@ -181,16 +179,15 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { .to(NodeTransformersRunner) .inSingletonScope(); - this.container - .bind(ServiceIdentifiers.IObfuscationResult) - .to(ObfuscationResult); + this.container.bind(ServiceIdentifiers.IObfuscationResult).to(ObfuscationResult); this.container .bind(ServiceIdentifiers.Factory__IObfuscationResult) .toFactory((context: interfaces.Context) => { return (obfuscatedCodeAsString: string, sourceMapAsString: string): IObfuscationResult => { - const obfuscationResult: IObfuscationResult = context.container - .get(ServiceIdentifiers.IObfuscationResult); + const obfuscationResult: IObfuscationResult = context.container.get( + ServiceIdentifiers.IObfuscationResult + ); obfuscationResult.initialize(obfuscatedCodeAsString, sourceMapAsString); @@ -221,7 +218,7 @@ export class InversifyContainerFacade implements IInversifyContainerFacade { this.container.load(utilsModule); } - public unload (): void { + public unload(): void { this.container.unbindAll(); } } diff --git a/src/container/modules/analyzers/AnalyzersModule.ts b/src/container/modules/analyzers/AnalyzersModule.ts index ce76b198..ae327cc2 100644 --- a/src/container/modules/analyzers/AnalyzersModule.ts +++ b/src/container/modules/analyzers/AnalyzersModule.ts @@ -21,9 +21,7 @@ import { StringArrayStorageAnalyzer } from '../../../analyzers/string-array-stor export const analyzersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { // calls graph analyzer - bind(ServiceIdentifiers.ICallsGraphAnalyzer) - .to(CallsGraphAnalyzer) - .inSingletonScope(); + bind(ServiceIdentifiers.ICallsGraphAnalyzer).to(CallsGraphAnalyzer).inSingletonScope(); // number numerical expression analyzer bind(ServiceIdentifiers.INumberNumericalExpressionAnalyzer) @@ -36,9 +34,7 @@ export const analyzersModule: interfaces.ContainerModule = new ContainerModule(( .inSingletonScope(); // scope analyzer - bind(ServiceIdentifiers.IScopeAnalyzer) - .to(ScopeAnalyzer) - .inSingletonScope(); + bind(ServiceIdentifiers.IScopeAnalyzer).to(ScopeAnalyzer).inSingletonScope(); // string array storage analyzer bind(ServiceIdentifiers.IStringArrayStorageAnalyzer) @@ -59,9 +55,12 @@ export const analyzersModule: interfaces.ContainerModule = new ContainerModule(( .whenTargetNamed(CalleeDataExtractor.ObjectExpressionCalleeDataExtractor); // callee data extractor factory - bind(ServiceIdentifiers.Factory__ICalleeDataExtractor) - .toFactory(InversifyContainerFacade - .getCacheFactory( - ServiceIdentifiers.ICalleeDataExtractor - )); + bind(ServiceIdentifiers.Factory__ICalleeDataExtractor).toFactory< + ICalleeDataExtractor, + [CalleeDataExtractor] + >( + InversifyContainerFacade.getCacheFactory( + ServiceIdentifiers.ICalleeDataExtractor + ) + ); }); diff --git a/src/container/modules/code-transformers/CodeTransformersModule.ts b/src/container/modules/code-transformers/CodeTransformersModule.ts index 7c2fb3d6..ad8af23e 100644 --- a/src/container/modules/code-transformers/CodeTransformersModule.ts +++ b/src/container/modules/code-transformers/CodeTransformersModule.ts @@ -12,12 +12,14 @@ import { HashbangOperatorTransformer } from '../../../code-transformers/preparin export const codeTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { // code transformers factory - bind(ServiceIdentifiers.Factory__ICodeTransformer) - .toFactory(InversifyContainerFacade - .getCacheFactory(ServiceIdentifiers.ICodeTransformer)); + bind(ServiceIdentifiers.Factory__ICodeTransformer).toFactory( + InversifyContainerFacade.getCacheFactory(ServiceIdentifiers.ICodeTransformer) + ); // code transformer names groups builder - bind>(ServiceIdentifiers.ICodeTransformerNamesGroupsBuilder) + bind>( + ServiceIdentifiers.ICodeTransformerNamesGroupsBuilder + ) .to(CodeTransformerNamesGroupsBuilder) .inSingletonScope(); diff --git a/src/container/modules/custom-code-helpers/CustomCodeHelpersModule.ts b/src/container/modules/custom-code-helpers/CustomCodeHelpersModule.ts index de96a08d..6ddca83d 100644 --- a/src/container/modules/custom-code-helpers/CustomCodeHelpersModule.ts +++ b/src/container/modules/custom-code-helpers/CustomCodeHelpersModule.ts @@ -103,14 +103,20 @@ export const customCodeHelpersModule: interfaces.ContainerModule = new Container .whenTargetNamed(CustomCodeHelperGroup.StringArray); // customCodeHelper factory - bind(ServiceIdentifiers.Factory__ICustomCodeHelper) - .toFactory(InversifyContainerFacade - .getFactory(ServiceIdentifiers.ICustomCodeHelper)); + bind(ServiceIdentifiers.Factory__ICustomCodeHelper).toFactory< + ICustomCodeHelper, + [CustomCodeHelper] + >(InversifyContainerFacade.getFactory(ServiceIdentifiers.ICustomCodeHelper)); // customCodeHelperGroup factory - bind(ServiceIdentifiers.Factory__ICustomCodeHelperGroup) - .toFactory(InversifyContainerFacade - .getFactory(ServiceIdentifiers.ICustomCodeHelperGroup)); + bind(ServiceIdentifiers.Factory__ICustomCodeHelperGroup).toFactory< + ICustomCodeHelperGroup, + [CustomCodeHelperGroup] + >( + InversifyContainerFacade.getFactory( + ServiceIdentifiers.ICustomCodeHelperGroup + ) + ); // custom code helper formatter bind(ServiceIdentifiers.ICustomCodeHelperFormatter) diff --git a/src/container/modules/custom-nodes/CustomNodesModule.ts b/src/container/modules/custom-nodes/CustomNodesModule.ts index b73aa8b8..2d813f0c 100644 --- a/src/container/modules/custom-nodes/CustomNodesModule.ts +++ b/src/container/modules/custom-nodes/CustomNodesModule.ts @@ -101,54 +101,71 @@ export const customNodesModule: interfaces.ContainerModule = new ContainerModule .whenTargetNamed(StringArrayIndexNode.StringArrayHexadecimalNumericStringIndexNode); // control flow customNode constructor factory - bind(ServiceIdentifiers.Factory__IControlFlowCustomNode) - .toFactory(InversifyContainerFacade - .getConstructorFactory( - ServiceIdentifiers.Newable__ICustomNode, - ServiceIdentifiers.Factory__IIdentifierNamesGenerator, - ServiceIdentifiers.ICustomCodeHelperFormatter, - ServiceIdentifiers.IRandomGenerator, - ServiceIdentifiers.IOptions - )); + bind(ServiceIdentifiers.Factory__IControlFlowCustomNode).toFactory< + ICustomNode, + [ControlFlowCustomNode] + >( + InversifyContainerFacade.getConstructorFactory( + ServiceIdentifiers.Newable__ICustomNode, + ServiceIdentifiers.Factory__IIdentifierNamesGenerator, + ServiceIdentifiers.ICustomCodeHelperFormatter, + ServiceIdentifiers.IRandomGenerator, + ServiceIdentifiers.IOptions + ) + ); // dead code injection customNode constructor factory - bind(ServiceIdentifiers.Factory__IDeadCodeInjectionCustomNode) - .toFactory(InversifyContainerFacade - .getConstructorFactory( - ServiceIdentifiers.Newable__ICustomNode, - ServiceIdentifiers.Factory__IIdentifierNamesGenerator, - ServiceIdentifiers.ICustomCodeHelperFormatter, - ServiceIdentifiers.IRandomGenerator, - ServiceIdentifiers.IOptions - )); + bind(ServiceIdentifiers.Factory__IDeadCodeInjectionCustomNode).toFactory< + ICustomNode, + [DeadCodeInjectionCustomNode] + >( + InversifyContainerFacade.getConstructorFactory( + ServiceIdentifiers.Newable__ICustomNode, + ServiceIdentifiers.Factory__IIdentifierNamesGenerator, + ServiceIdentifiers.ICustomCodeHelperFormatter, + ServiceIdentifiers.IRandomGenerator, + ServiceIdentifiers.IOptions + ) + ); // object expression keys transformer customNode constructor factory - bind(ServiceIdentifiers.Factory__IObjectExpressionKeysTransformerCustomNode) - .toFactory(InversifyContainerFacade - .getConstructorFactory( - ServiceIdentifiers.Newable__ICustomNode, - ServiceIdentifiers.Factory__IIdentifierNamesGenerator, - ServiceIdentifiers.ICustomCodeHelperFormatter, - ServiceIdentifiers.IRandomGenerator, - ServiceIdentifiers.IOptions - )); + bind(ServiceIdentifiers.Factory__IObjectExpressionKeysTransformerCustomNode).toFactory< + ICustomNode, + [ObjectExpressionKeysTransformerCustomNode] + >( + InversifyContainerFacade.getConstructorFactory( + ServiceIdentifiers.Newable__ICustomNode, + ServiceIdentifiers.Factory__IIdentifierNamesGenerator, + ServiceIdentifiers.ICustomCodeHelperFormatter, + ServiceIdentifiers.IRandomGenerator, + ServiceIdentifiers.IOptions + ) + ); // string array customNode constructor factory - bind(ServiceIdentifiers.Factory__IStringArrayCustomNode) - .toFactory(InversifyContainerFacade - .getConstructorFactory( - ServiceIdentifiers.Newable__ICustomNode, - ServiceIdentifiers.Factory__IIdentifierNamesGenerator, - ServiceIdentifiers.Factory__IStringArrayIndexNode, - ServiceIdentifiers.ICustomCodeHelperFormatter, - ServiceIdentifiers.IStringArrayStorage, - ServiceIdentifiers.IArrayUtils, - ServiceIdentifiers.IRandomGenerator, - ServiceIdentifiers.IOptions - )); + bind(ServiceIdentifiers.Factory__IStringArrayCustomNode).toFactory< + ICustomNode, + [StringArrayCustomNode] + >( + InversifyContainerFacade.getConstructorFactory( + ServiceIdentifiers.Newable__ICustomNode, + ServiceIdentifiers.Factory__IIdentifierNamesGenerator, + ServiceIdentifiers.Factory__IStringArrayIndexNode, + ServiceIdentifiers.ICustomCodeHelperFormatter, + ServiceIdentifiers.IStringArrayStorage, + ServiceIdentifiers.IArrayUtils, + ServiceIdentifiers.IRandomGenerator, + ServiceIdentifiers.IOptions + ) + ); // string array index node factory - bind(ServiceIdentifiers.Factory__IStringArrayIndexNode) - .toFactory(InversifyContainerFacade - .getCacheFactory(ServiceIdentifiers.IStringArrayIndexNode)); + bind(ServiceIdentifiers.Factory__IStringArrayIndexNode).toFactory< + IStringArrayIndexNode, + [StringArrayIndexNode] + >( + InversifyContainerFacade.getCacheFactory( + ServiceIdentifiers.IStringArrayIndexNode + ) + ); }); diff --git a/src/container/modules/generators/GeneratorsModule.ts b/src/container/modules/generators/GeneratorsModule.ts index f65bd616..c1ff48e3 100644 --- a/src/container/modules/generators/GeneratorsModule.ts +++ b/src/container/modules/generators/GeneratorsModule.ts @@ -34,54 +34,59 @@ export const generatorsModule: interfaces.ContainerModule = new ContainerModule( .whenTargetNamed(IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator); // identifier name generator factory - function identifierNameGeneratorFactory (): (context: interfaces.Context) => (options: IOptions) => IIdentifierNamesGenerator { + function identifierNameGeneratorFactory(): ( + context: interfaces.Context + ) => (options: IOptions) => IIdentifierNamesGenerator { let cachedIdentifierNamesGenerator: IIdentifierNamesGenerator | null = null; - return (context: interfaces.Context): (options: IOptions) => IIdentifierNamesGenerator => (options: IOptions): IIdentifierNamesGenerator => { - if (cachedIdentifierNamesGenerator) { - return cachedIdentifierNamesGenerator; - } + return (context: interfaces.Context): ((options: IOptions) => IIdentifierNamesGenerator) => + (options: IOptions): IIdentifierNamesGenerator => { + if (cachedIdentifierNamesGenerator) { + return cachedIdentifierNamesGenerator; + } - let identifierNamesGenerator: IIdentifierNamesGenerator; + let identifierNamesGenerator: IIdentifierNamesGenerator; - switch (options.identifierNamesGenerator) { - case IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator: - identifierNamesGenerator = context.container.getNamed( - ServiceIdentifiers.IIdentifierNamesGenerator, - IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator - ); + switch (options.identifierNamesGenerator) { + case IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator: + identifierNamesGenerator = context.container.getNamed( + ServiceIdentifiers.IIdentifierNamesGenerator, + IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator + ); - break; + break; - case IdentifierNamesGenerator.MangledIdentifierNamesGenerator: - identifierNamesGenerator = context.container.getNamed( - ServiceIdentifiers.IIdentifierNamesGenerator, - IdentifierNamesGenerator.MangledIdentifierNamesGenerator - ); + case IdentifierNamesGenerator.MangledIdentifierNamesGenerator: + identifierNamesGenerator = context.container.getNamed( + ServiceIdentifiers.IIdentifierNamesGenerator, + IdentifierNamesGenerator.MangledIdentifierNamesGenerator + ); - break; + break; - case IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator: - identifierNamesGenerator = context.container.getNamed( - ServiceIdentifiers.IIdentifierNamesGenerator, - IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator - ); + case IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator: + identifierNamesGenerator = context.container.getNamed( + ServiceIdentifiers.IIdentifierNamesGenerator, + IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator + ); - break; + break; - case IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator: - default: - identifierNamesGenerator = context.container.getNamed( - ServiceIdentifiers.IIdentifierNamesGenerator, - IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator - ); - } + case IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator: + default: + identifierNamesGenerator = context.container.getNamed( + ServiceIdentifiers.IIdentifierNamesGenerator, + IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + ); + } - cachedIdentifierNamesGenerator = identifierNamesGenerator; + cachedIdentifierNamesGenerator = identifierNamesGenerator; - return identifierNamesGenerator; - }; + return identifierNamesGenerator; + }; } - bind(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - .toFactory(identifierNameGeneratorFactory()); + bind(ServiceIdentifiers.Factory__IIdentifierNamesGenerator).toFactory< + IIdentifierNamesGenerator, + [IOptions] + >(identifierNameGeneratorFactory()); }); diff --git a/src/container/modules/node-transformers/ControlFlowTransformersModule.ts b/src/container/modules/node-transformers/ControlFlowTransformersModule.ts index a2406c1b..02a458e5 100644 --- a/src/container/modules/node-transformers/ControlFlowTransformersModule.ts +++ b/src/container/modules/node-transformers/ControlFlowTransformersModule.ts @@ -17,43 +17,50 @@ import { StringArrayCallControlFlowReplacer } from '../../../node-transformers/c import { StringArrayControlFlowTransformer } from '../../../node-transformers/control-flow-transformers/StringArrayControlFlowTransformer'; import { StringLiteralControlFlowReplacer } from '../../../node-transformers/control-flow-transformers/control-flow-replacers/StringLiteralControlFlowReplacer'; -export const controlFlowTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // control flow transformers - bind(ServiceIdentifiers.INodeTransformer) - .to(BlockStatementControlFlowTransformer) - .whenTargetNamed(NodeTransformer.BlockStatementControlFlowTransformer); +export const controlFlowTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // control flow transformers + bind(ServiceIdentifiers.INodeTransformer) + .to(BlockStatementControlFlowTransformer) + .whenTargetNamed(NodeTransformer.BlockStatementControlFlowTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(FunctionControlFlowTransformer) - .whenTargetNamed(NodeTransformer.FunctionControlFlowTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(FunctionControlFlowTransformer) + .whenTargetNamed(NodeTransformer.FunctionControlFlowTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(StringArrayControlFlowTransformer) - .whenTargetNamed(NodeTransformer.StringArrayControlFlowTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(StringArrayControlFlowTransformer) + .whenTargetNamed(NodeTransformer.StringArrayControlFlowTransformer); - // control flow replacers - bind(ServiceIdentifiers.IControlFlowReplacer) - .to(BinaryExpressionControlFlowReplacer) - .whenTargetNamed(ControlFlowReplacer.BinaryExpressionControlFlowReplacer); + // control flow replacers + bind(ServiceIdentifiers.IControlFlowReplacer) + .to(BinaryExpressionControlFlowReplacer) + .whenTargetNamed(ControlFlowReplacer.BinaryExpressionControlFlowReplacer); - bind(ServiceIdentifiers.IControlFlowReplacer) - .to(CallExpressionControlFlowReplacer) - .whenTargetNamed(ControlFlowReplacer.CallExpressionControlFlowReplacer); + bind(ServiceIdentifiers.IControlFlowReplacer) + .to(CallExpressionControlFlowReplacer) + .whenTargetNamed(ControlFlowReplacer.CallExpressionControlFlowReplacer); - bind(ServiceIdentifiers.IControlFlowReplacer) - .to(LogicalExpressionControlFlowReplacer) - .whenTargetNamed(ControlFlowReplacer.LogicalExpressionControlFlowReplacer); + bind(ServiceIdentifiers.IControlFlowReplacer) + .to(LogicalExpressionControlFlowReplacer) + .whenTargetNamed(ControlFlowReplacer.LogicalExpressionControlFlowReplacer); - bind(ServiceIdentifiers.IControlFlowReplacer) - .to(StringArrayCallControlFlowReplacer) - .whenTargetNamed(ControlFlowReplacer.StringArrayCallControlFlowReplacer); + bind(ServiceIdentifiers.IControlFlowReplacer) + .to(StringArrayCallControlFlowReplacer) + .whenTargetNamed(ControlFlowReplacer.StringArrayCallControlFlowReplacer); - bind(ServiceIdentifiers.IControlFlowReplacer) - .to(StringLiteralControlFlowReplacer) - .whenTargetNamed(ControlFlowReplacer.StringLiteralControlFlowReplacer); + bind(ServiceIdentifiers.IControlFlowReplacer) + .to(StringLiteralControlFlowReplacer) + .whenTargetNamed(ControlFlowReplacer.StringLiteralControlFlowReplacer); - // control flow replacer factory - bind(ServiceIdentifiers.Factory__IControlFlowReplacer) - .toFactory(InversifyContainerFacade - .getCacheFactory(ServiceIdentifiers.IControlFlowReplacer)); -}); + // control flow replacer factory + bind(ServiceIdentifiers.Factory__IControlFlowReplacer).toFactory< + IControlFlowReplacer, + [ControlFlowReplacer] + >( + InversifyContainerFacade.getCacheFactory( + ServiceIdentifiers.IControlFlowReplacer + ) + ); + } +); diff --git a/src/container/modules/node-transformers/ConvertingTransformersModule.ts b/src/container/modules/node-transformers/ConvertingTransformersModule.ts index cf9874df..682550e0 100644 --- a/src/container/modules/node-transformers/ConvertingTransformersModule.ts +++ b/src/container/modules/node-transformers/ConvertingTransformersModule.ts @@ -78,9 +78,12 @@ export const convertingTransformersModule: interfaces.ContainerModule = new Cont .whenTargetNamed(ObjectExpressionExtractor.BasePropertiesExtractor); // object expression extractor factory - bind(ServiceIdentifiers.Factory__IObjectExpressionExtractor) - .toFactory(InversifyContainerFacade - .getCacheFactory( - ServiceIdentifiers.IObjectExpressionExtractor - )); + bind(ServiceIdentifiers.Factory__IObjectExpressionExtractor).toFactory< + IObjectExpressionExtractor, + [ObjectExpressionExtractor] + >( + InversifyContainerFacade.getCacheFactory( + ServiceIdentifiers.IObjectExpressionExtractor + ) + ); }); diff --git a/src/container/modules/node-transformers/DeadCodeInjectionTransformersModule.ts b/src/container/modules/node-transformers/DeadCodeInjectionTransformersModule.ts index cbb869cb..211d510b 100644 --- a/src/container/modules/node-transformers/DeadCodeInjectionTransformersModule.ts +++ b/src/container/modules/node-transformers/DeadCodeInjectionTransformersModule.ts @@ -7,9 +7,11 @@ import { NodeTransformer } from '../../../enums/node-transformers/NodeTransforme import { DeadCodeInjectionTransformer } from '../../../node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer'; -export const deadCodeInjectionTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // dead code injection - bind(ServiceIdentifiers.INodeTransformer) - .to(DeadCodeInjectionTransformer) - .whenTargetNamed(NodeTransformer.DeadCodeInjectionTransformer); -}); +export const deadCodeInjectionTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // dead code injection + bind(ServiceIdentifiers.INodeTransformer) + .to(DeadCodeInjectionTransformer) + .whenTargetNamed(NodeTransformer.DeadCodeInjectionTransformer); + } +); diff --git a/src/container/modules/node-transformers/InitializingTransformersModule.ts b/src/container/modules/node-transformers/InitializingTransformersModule.ts index a64d0381..b7753ba5 100644 --- a/src/container/modules/node-transformers/InitializingTransformersModule.ts +++ b/src/container/modules/node-transformers/InitializingTransformersModule.ts @@ -7,9 +7,11 @@ import { NodeTransformer } from '../../../enums/node-transformers/NodeTransforme import { CommentsTransformer } from '../../../node-transformers/initializing-transformers/CommentsTransformer'; -export const initializingTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // preparing transformers - bind(ServiceIdentifiers.INodeTransformer) - .to(CommentsTransformer) - .whenTargetNamed(NodeTransformer.CommentsTransformer); -}); +export const initializingTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // preparing transformers + bind(ServiceIdentifiers.INodeTransformer) + .to(CommentsTransformer) + .whenTargetNamed(NodeTransformer.CommentsTransformer); + } +); diff --git a/src/container/modules/node-transformers/NodeTransformersModule.ts b/src/container/modules/node-transformers/NodeTransformersModule.ts index 05fb8020..a637ce34 100644 --- a/src/container/modules/node-transformers/NodeTransformersModule.ts +++ b/src/container/modules/node-transformers/NodeTransformersModule.ts @@ -11,12 +11,14 @@ import { NodeTransformerNamesGroupsBuilder } from '../../../node-transformers/No export const nodeTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { // node transformers factory - bind(ServiceIdentifiers.Factory__INodeTransformer) - .toFactory(InversifyContainerFacade - .getCacheFactory(ServiceIdentifiers.INodeTransformer)); + bind(ServiceIdentifiers.Factory__INodeTransformer).toFactory( + InversifyContainerFacade.getCacheFactory(ServiceIdentifiers.INodeTransformer) + ); // node transformer names groups builder - bind>(ServiceIdentifiers.INodeTransformerNamesGroupsBuilder) + bind>( + ServiceIdentifiers.INodeTransformerNamesGroupsBuilder + ) .to(NodeTransformerNamesGroupsBuilder) .inSingletonScope(); }); diff --git a/src/container/modules/node-transformers/PreparingTransformersModule.ts b/src/container/modules/node-transformers/PreparingTransformersModule.ts index f7309b4a..da19c7a6 100644 --- a/src/container/modules/node-transformers/PreparingTransformersModule.ts +++ b/src/container/modules/node-transformers/PreparingTransformersModule.ts @@ -14,9 +14,7 @@ import { CustomCodeHelpersTransformer } from '../../../node-transformers/prepari import { EvalCallExpressionTransformer } from '../../../node-transformers/preparing-transformers/EvalCallExpressionTransformer'; import { ForceTransformStringObfuscatingGuard } from '../../../node-transformers/preparing-transformers/obfuscating-guards/ForceTransformStringObfuscatingGuard'; import { IgnoredImportObfuscatingGuard } from '../../../node-transformers/preparing-transformers/obfuscating-guards/IgnoredImportObfuscatingGuard'; -import { - ImportMetaObfuscationGuard -} from '../../../node-transformers/preparing-transformers/obfuscating-guards/ImportMetaObfuscationGuard'; +import { ImportMetaObfuscationGuard } from '../../../node-transformers/preparing-transformers/obfuscating-guards/ImportMetaObfuscationGuard'; import { MetadataTransformer } from '../../../node-transformers/preparing-transformers/MetadataTransformer'; import { ObfuscatingGuardsTransformer } from '../../../node-transformers/preparing-transformers/ObfuscatingGuardsTransformer'; import { ParentificationTransformer } from '../../../node-transformers/preparing-transformers/ParentificationTransformer'; @@ -81,9 +79,7 @@ export const preparingTransformersModule: interfaces.ContainerModule = new Conta .whenTargetNamed(ObfuscatingGuard.ReservedStringObfuscatingGuard); // obfuscating guards factory - bind(ServiceIdentifiers.Factory__INodeGuard) - .toFactory(InversifyContainerFacade - .getCacheFactory( - ServiceIdentifiers.INodeGuard - )); + bind(ServiceIdentifiers.Factory__INodeGuard).toFactory( + InversifyContainerFacade.getCacheFactory(ServiceIdentifiers.INodeGuard) + ); }); diff --git a/src/container/modules/node-transformers/RenameIdentifiersTransformersModule.ts b/src/container/modules/node-transformers/RenameIdentifiersTransformersModule.ts index 63d0777c..00fcaf83 100644 --- a/src/container/modules/node-transformers/RenameIdentifiersTransformersModule.ts +++ b/src/container/modules/node-transformers/RenameIdentifiersTransformersModule.ts @@ -14,30 +14,30 @@ import { ScopeThroughIdentifiersTransformer } from '../../../node-transformers/r import { ThroughIdentifierReplacer } from '../../../node-transformers/rename-identifiers-transformers/through-replacer/ThroughIdentifierReplacer'; import { IThroughIdentifierReplacer } from '../../../interfaces/node-transformers/rename-identifiers-transformers/replacer/IThroughIdentifierReplacer'; -export const renameIdentifiersTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // rename identifiers transformers - bind(ServiceIdentifiers.INodeTransformer) - .to(DeadCodeInjectionIdentifiersTransformer) - .whenTargetNamed(NodeTransformer.DeadCodeInjectionIdentifiersTransformer); +export const renameIdentifiersTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // rename identifiers transformers + bind(ServiceIdentifiers.INodeTransformer) + .to(DeadCodeInjectionIdentifiersTransformer) + .whenTargetNamed(NodeTransformer.DeadCodeInjectionIdentifiersTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(LabeledStatementTransformer) - .whenTargetNamed(NodeTransformer.LabeledStatementTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(LabeledStatementTransformer) + .whenTargetNamed(NodeTransformer.LabeledStatementTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(ScopeIdentifiersTransformer) - .whenTargetNamed(NodeTransformer.ScopeIdentifiersTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(ScopeIdentifiersTransformer) + .whenTargetNamed(NodeTransformer.ScopeIdentifiersTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(ScopeThroughIdentifiersTransformer) - .whenTargetNamed(NodeTransformer.ScopeThroughIdentifiersTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(ScopeThroughIdentifiersTransformer) + .whenTargetNamed(NodeTransformer.ScopeThroughIdentifiersTransformer); - // identifier replacer - bind(ServiceIdentifiers.IIdentifierReplacer) - .to(IdentifierReplacer) - .inSingletonScope(); + // identifier replacer + bind(ServiceIdentifiers.IIdentifierReplacer).to(IdentifierReplacer).inSingletonScope(); - bind(ServiceIdentifiers.IThroughIdentifierReplacer) - .to(ThroughIdentifierReplacer) - .inSingletonScope(); -}); + bind(ServiceIdentifiers.IThroughIdentifierReplacer) + .to(ThroughIdentifierReplacer) + .inSingletonScope(); + } +); diff --git a/src/container/modules/node-transformers/RenamePropertiesTransformersModule.ts b/src/container/modules/node-transformers/RenamePropertiesTransformersModule.ts index 6812e786..2d1c79c0 100644 --- a/src/container/modules/node-transformers/RenamePropertiesTransformersModule.ts +++ b/src/container/modules/node-transformers/RenamePropertiesTransformersModule.ts @@ -9,13 +9,14 @@ import { NodeTransformer } from '../../../enums/node-transformers/NodeTransforme import { RenamePropertiesReplacer } from '../../../node-transformers/rename-properties-transformers/replacer/RenamePropertiesReplacer'; import { RenamePropertiesTransformer } from '../../../node-transformers/rename-properties-transformers/RenamePropertiesTransformer'; -export const renamePropertiesTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // rename properties transformers - bind(ServiceIdentifiers.INodeTransformer) - .to(RenamePropertiesTransformer) - .whenTargetNamed(NodeTransformer.RenamePropertiesTransformer); +export const renamePropertiesTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // rename properties transformers + bind(ServiceIdentifiers.INodeTransformer) + .to(RenamePropertiesTransformer) + .whenTargetNamed(NodeTransformer.RenamePropertiesTransformer); - // rename properties obfuscating replacer - bind(ServiceIdentifiers.IRenamePropertiesReplacer) - .to(RenamePropertiesReplacer); -}); + // rename properties obfuscating replacer + bind(ServiceIdentifiers.IRenamePropertiesReplacer).to(RenamePropertiesReplacer); + } +); diff --git a/src/container/modules/node-transformers/SimplifyingTransformersModule.ts b/src/container/modules/node-transformers/SimplifyingTransformersModule.ts index 145d15f1..ea1c8163 100644 --- a/src/container/modules/node-transformers/SimplifyingTransformersModule.ts +++ b/src/container/modules/node-transformers/SimplifyingTransformersModule.ts @@ -10,21 +10,23 @@ import { ExpressionStatementsMergeTransformer } from '../../../node-transformers import { IfStatementSimplifyTransformer } from '../../../node-transformers/simplifying-transformers/IfStatementSimplifyTransformer'; import { VariableDeclarationsMergeTransformer } from '../../../node-transformers/simplifying-transformers/VariableDeclarationsMergeTransformer'; -export const simplifyingTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // simplifying transformers - bind(ServiceIdentifiers.INodeTransformer) - .to(BlockStatementSimplifyTransformer) - .whenTargetNamed(NodeTransformer.BlockStatementSimplifyTransformer); +export const simplifyingTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // simplifying transformers + bind(ServiceIdentifiers.INodeTransformer) + .to(BlockStatementSimplifyTransformer) + .whenTargetNamed(NodeTransformer.BlockStatementSimplifyTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(ExpressionStatementsMergeTransformer) - .whenTargetNamed(NodeTransformer.ExpressionStatementsMergeTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(ExpressionStatementsMergeTransformer) + .whenTargetNamed(NodeTransformer.ExpressionStatementsMergeTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(IfStatementSimplifyTransformer) - .whenTargetNamed(NodeTransformer.IfStatementSimplifyTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(IfStatementSimplifyTransformer) + .whenTargetNamed(NodeTransformer.IfStatementSimplifyTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(VariableDeclarationsMergeTransformer) - .whenTargetNamed(NodeTransformer.VariableDeclarationsMergeTransformer); -}); + bind(ServiceIdentifiers.INodeTransformer) + .to(VariableDeclarationsMergeTransformer) + .whenTargetNamed(NodeTransformer.VariableDeclarationsMergeTransformer); + } +); diff --git a/src/container/modules/node-transformers/StringArrayTransformersModule.ts b/src/container/modules/node-transformers/StringArrayTransformersModule.ts index 2ab43e48..1c5d1c4a 100644 --- a/src/container/modules/node-transformers/StringArrayTransformersModule.ts +++ b/src/container/modules/node-transformers/StringArrayTransformersModule.ts @@ -9,17 +9,19 @@ import { StringArrayRotateFunctionTransformer } from '../../../node-transformers import { StringArrayScopeCallsWrapperTransformer } from '../../../node-transformers/string-array-transformers/StringArrayScopeCallsWrapperTransformer'; import { StringArrayTransformer } from '../../../node-transformers/string-array-transformers/StringArrayTransformer'; -export const stringArrayTransformersModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - // strings transformers - bind(ServiceIdentifiers.INodeTransformer) - .to(StringArrayRotateFunctionTransformer) - .whenTargetNamed(NodeTransformer.StringArrayRotateFunctionTransformer); +export const stringArrayTransformersModule: interfaces.ContainerModule = new ContainerModule( + (bind: interfaces.Bind) => { + // strings transformers + bind(ServiceIdentifiers.INodeTransformer) + .to(StringArrayRotateFunctionTransformer) + .whenTargetNamed(NodeTransformer.StringArrayRotateFunctionTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(StringArrayScopeCallsWrapperTransformer) - .whenTargetNamed(NodeTransformer.StringArrayScopeCallsWrapperTransformer); + bind(ServiceIdentifiers.INodeTransformer) + .to(StringArrayScopeCallsWrapperTransformer) + .whenTargetNamed(NodeTransformer.StringArrayScopeCallsWrapperTransformer); - bind(ServiceIdentifiers.INodeTransformer) - .to(StringArrayTransformer) - .whenTargetNamed(NodeTransformer.StringArrayTransformer); -}); + bind(ServiceIdentifiers.INodeTransformer) + .to(StringArrayTransformer) + .whenTargetNamed(NodeTransformer.StringArrayTransformer); + } +); diff --git a/src/container/modules/options/OptionsModule.ts b/src/container/modules/options/OptionsModule.ts index 5e464416..1e6fc150 100644 --- a/src/container/modules/options/OptionsModule.ts +++ b/src/container/modules/options/OptionsModule.ts @@ -8,11 +8,7 @@ import { Options } from '../../../options/Options'; import { OptionsNormalizer } from '../../../options/OptionsNormalizer'; export const optionsModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { - bind(ServiceIdentifiers.IOptions) - .to(Options) - .inSingletonScope(); + bind(ServiceIdentifiers.IOptions).to(Options).inSingletonScope(); - bind(ServiceIdentifiers.IOptionsNormalizer) - .to(OptionsNormalizer) - .inSingletonScope(); + bind(ServiceIdentifiers.IOptionsNormalizer).to(OptionsNormalizer).inSingletonScope(); }); diff --git a/src/container/modules/storages/StoragesModule.ts b/src/container/modules/storages/StoragesModule.ts index 52bc6505..ead8cdc4 100644 --- a/src/container/modules/storages/StoragesModule.ts +++ b/src/container/modules/storages/StoragesModule.ts @@ -2,9 +2,7 @@ import { ContainerModule, interfaces } from 'inversify'; import { ServiceIdentifiers } from '../../ServiceIdentifiers'; import { TControlFlowStorageFactory } from '../../../types/container/node-transformers/TControlFlowStorageFactory'; -import { - TControlFlowStorageFactoryCreator -} from '../../../types/container/node-transformers/TControlFlowStorageFactoryCreator'; +import { TControlFlowStorageFactoryCreator } from '../../../types/container/node-transformers/TControlFlowStorageFactoryCreator'; import { TCustomCodeHelperGroupStorage } from '../../../types/storages/TCustomCodeHelperGroupStorage'; import { IControlFlowStorage } from '../../../interfaces/storages/control-flow-transformers/IControlFlowStorage'; @@ -23,9 +21,7 @@ import { GlobalIdentifierNamesCacheStorage } from '../../../storages/identifier- import { LiteralNodesCacheStorage } from '../../../storages/string-array-transformers/LiteralNodesCacheStorage'; import { PropertyIdentifierNamesCacheStorage } from '../../../storages/identifier-names-cache/PropertyIdentifierNamesCacheStorage'; import { StringArrayScopeCallsWrappersDataStorage } from '../../../storages/string-array-transformers/StringArrayScopeCallsWrappersDataStorage'; -import { - StringControlFlowStorage -} from '../../../storages/control-flow-transformers/StringControlFlowStorage'; +import { StringControlFlowStorage } from '../../../storages/control-flow-transformers/StringControlFlowStorage'; import { StringArrayStorage } from '../../../storages/string-array-transformers/StringArrayStorage'; import { VisitedLexicalScopeNodesStackStorage } from '../../../storages/string-array-transformers/VisitedLexicalScopeNodesStackStorage'; @@ -51,9 +47,7 @@ export const storagesModule: interfaces.ContainerModule = new ContainerModule((b .to(PropertyIdentifierNamesCacheStorage) .inSingletonScope(); - bind(ServiceIdentifiers.IStringArrayStorage) - .to(StringArrayStorage) - .inSingletonScope(); + bind(ServiceIdentifiers.IStringArrayStorage).to(StringArrayStorage).inSingletonScope(); bind(ServiceIdentifiers.IStringArrayScopeCallsWrappersDataStorage) .to(StringArrayScopeCallsWrappersDataStorage) @@ -68,12 +62,13 @@ export const storagesModule: interfaces.ContainerModule = new ContainerModule((b .inSingletonScope(); // controlFlowStorage factory - bind(ServiceIdentifiers.Factory__TControlFlowStorage) - .toFactory((context: interfaces.Context): TControlFlowStorageFactoryCreator => - (controlFlowStorageName: ControlFlowStorage): TControlFlowStorageFactory => (): IControlFlowStorage => + bind(ServiceIdentifiers.Factory__TControlFlowStorage).toFactory( + (context: interfaces.Context): TControlFlowStorageFactoryCreator => + (controlFlowStorageName: ControlFlowStorage): TControlFlowStorageFactory => + (): IControlFlowStorage => context.container.getNamed( - ServiceIdentifiers.IControlFlowStorage, - controlFlowStorageName + ServiceIdentifiers.IControlFlowStorage, + controlFlowStorageName ) - ); + ); }); diff --git a/src/container/modules/utils/UtilsModule.ts b/src/container/modules/utils/UtilsModule.ts index 8ec11832..5b31f33a 100644 --- a/src/container/modules/utils/UtilsModule.ts +++ b/src/container/modules/utils/UtilsModule.ts @@ -19,19 +19,13 @@ import { SetUtils } from '../../../utils/SetUtils'; export const utilsModule: interfaces.ContainerModule = new ContainerModule((bind: interfaces.Bind) => { // array utils - bind(ServiceIdentifiers.IArrayUtils) - .to(ArrayUtils) - .inSingletonScope(); + bind(ServiceIdentifiers.IArrayUtils).to(ArrayUtils).inSingletonScope(); // random generator - bind(ServiceIdentifiers.IRandomGenerator) - .to(RandomGenerator) - .inSingletonScope(); + bind(ServiceIdentifiers.IRandomGenerator).to(RandomGenerator).inSingletonScope(); // crypt utils - bind(ServiceIdentifiers.ICryptUtils) - .to(CryptUtils) - .inSingletonScope(); + bind(ServiceIdentifiers.ICryptUtils).to(CryptUtils).inSingletonScope(); // crypt utils for string array bind(ServiceIdentifiers.ICryptUtilsStringArray) @@ -44,11 +38,8 @@ export const utilsModule: interfaces.ContainerModule = new ContainerModule((bind .inSingletonScope(); // levelled topological sorter - bind(ServiceIdentifiers.ILevelledTopologicalSorter) - .to(LevelledTopologicalSorter); + bind(ServiceIdentifiers.ILevelledTopologicalSorter).to(LevelledTopologicalSorter); // set utils - bind(ServiceIdentifiers.ISetUtils) - .to(SetUtils) - .inSingletonScope(); + bind(ServiceIdentifiers.ISetUtils).to(SetUtils).inSingletonScope(); }); diff --git a/src/custom-code-helpers/AbstractCustomCodeHelper.ts b/src/custom-code-helpers/AbstractCustomCodeHelper.ts index a6c55013..e9669f83 100644 --- a/src/custom-code-helpers/AbstractCustomCodeHelper.ts +++ b/src/custom-code-helpers/AbstractCustomCodeHelper.ts @@ -18,9 +18,9 @@ import { GlobalVariableNoEvalTemplate } from './common/templates/GlobalVariableN import { GlobalVariableServiceWorkerTemplate } from './common/templates/GlobalVariableServiceWorkerTemplate'; @injectable() -export abstract class AbstractCustomCodeHelper < - TInitialData extends unknown[] = unknown[] -> implements ICustomCodeHelper { +export abstract class AbstractCustomCodeHelper + implements ICustomCodeHelper +{ /** * @type {string[]} */ @@ -66,9 +66,9 @@ export abstract class AbstractCustomCodeHelper < * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -84,13 +84,11 @@ export abstract class AbstractCustomCodeHelper < /** * @returns {TStatement[]} */ - public getNode (): TStatement[] { + public getNode(): TStatement[] { if (!this.cachedNode) { const codeHelperTemplate: string = this.getCodeHelperTemplate(); - this.cachedNode = this.customCodeHelperFormatter.formatStructure( - this.getNodeStructure(codeHelperTemplate) - ); + this.cachedNode = this.customCodeHelperFormatter.formatStructure(this.getNodeStructure(codeHelperTemplate)); } return this.cachedNode; @@ -99,7 +97,7 @@ export abstract class AbstractCustomCodeHelper < /** * @returns {string} */ - protected getGlobalVariableTemplate (): string { + protected getGlobalVariableTemplate(): string { switch (this.options.target) { case ObfuscationTarget.BrowserNoEval: return GlobalVariableNoEvalTemplate(); @@ -115,17 +113,17 @@ export abstract class AbstractCustomCodeHelper < /** * @returns {string} */ - protected getCodeHelperTemplate (): string { + protected getCodeHelperTemplate(): string { return ''; } /** * @param {TInitialData} args */ - public abstract initialize (...args: TInitialData): void; + public abstract initialize(...args: TInitialData): void; /** * @returns {TStatement[]} */ - protected abstract getNodeStructure (codeHelperTemplate: string): TStatement[]; + protected abstract getNodeStructure(codeHelperTemplate: string): TStatement[]; } diff --git a/src/custom-code-helpers/AbstractCustomCodeHelperGroup.ts b/src/custom-code-helpers/AbstractCustomCodeHelperGroup.ts index 5b6e8682..267a09db 100644 --- a/src/custom-code-helpers/AbstractCustomCodeHelperGroup.ts +++ b/src/custom-code-helpers/AbstractCustomCodeHelperGroup.ts @@ -31,16 +31,16 @@ export abstract class AbstractCustomCodeHelperGroup implements ICustomCodeHelper /** * @type {Map} */ - protected abstract customCodeHelpers: Map ; + protected abstract customCodeHelpers: Map; /** * @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -52,7 +52,7 @@ export abstract class AbstractCustomCodeHelperGroup implements ICustomCodeHelper /** * @returns {Map} */ - public getCustomCodeHelpers (): Map { + public getCustomCodeHelpers(): Map { return this.customCodeHelpers; } @@ -60,7 +60,10 @@ export abstract class AbstractCustomCodeHelperGroup implements ICustomCodeHelper * @param {CustomCodeHelper} customCodeHelperName * @param {callback} callback */ - protected appendCustomNodeIfExist (customCodeHelperName: CustomCodeHelper, callback: (customCodeHelper: ICustomCodeHelper) => void): void { + protected appendCustomNodeIfExist( + customCodeHelperName: CustomCodeHelper, + callback: (customCodeHelper: ICustomCodeHelper) => void + ): void { const customCodeHelper: ICustomCodeHelper | undefined = this.customCodeHelpers.get(customCodeHelperName); if (!customCodeHelper) { @@ -75,9 +78,9 @@ export abstract class AbstractCustomCodeHelperGroup implements ICustomCodeHelper * @returns {number} */ - protected getRandomCallsGraphIndex (callsGraphLength: number): number { + protected getRandomCallsGraphIndex(callsGraphLength: number): number { return this.randomGenerator.getRandomInteger(0, Math.max(0, Math.round(callsGraphLength - 1))); } - public abstract initialize (): void; + public abstract initialize(): void; } diff --git a/src/custom-code-helpers/CustomCodeHelperFormatter.ts b/src/custom-code-helpers/CustomCodeHelperFormatter.ts index b24464a0..a62be6b7 100644 --- a/src/custom-code-helpers/CustomCodeHelperFormatter.ts +++ b/src/custom-code-helpers/CustomCodeHelperFormatter.ts @@ -20,9 +20,9 @@ export class CustomCodeHelperFormatter implements ICustomCodeHelperFormatter { */ private readonly prevailingKindOfVariables: ESTree.VariableDeclaration['kind']; - public constructor ( + public constructor( @inject(ServiceIdentifiers.IPrevailingKindOfVariablesAnalyzer) - prevailingKindOfVariablesAnalyzer: IPrevailingKindOfVariablesAnalyzer + prevailingKindOfVariablesAnalyzer: IPrevailingKindOfVariablesAnalyzer ) { this.prevailingKindOfVariables = prevailingKindOfVariablesAnalyzer.getPrevailingKind(); } @@ -32,10 +32,7 @@ export class CustomCodeHelperFormatter implements ICustomCodeHelperFormatter { * @param {TMapping} mapping * @returns {string} */ - public formatTemplate ( - template: string, - mapping: TMapping - ): string { + public formatTemplate(template: string, mapping: TMapping): string { return format(template, mapping); } @@ -43,7 +40,7 @@ export class CustomCodeHelperFormatter implements ICustomCodeHelperFormatter { * @param {TStatement[]} statements * @returns {TStatement[]} */ - public formatStructure (statements: TStatement[]): TStatement[] { + public formatStructure(statements: TStatement[]): TStatement[] { for (const statement of statements) { estraverse.replace(statement, { enter: (node: ESTree.Node): ESTree.Node | void => { diff --git a/src/custom-code-helpers/CustomCodeHelperObfuscator.ts b/src/custom-code-helpers/CustomCodeHelperObfuscator.ts index f33bc251..76cc9a36 100644 --- a/src/custom-code-helpers/CustomCodeHelperObfuscator.ts +++ b/src/custom-code-helpers/CustomCodeHelperObfuscator.ts @@ -27,7 +27,7 @@ export class CustomCodeHelperObfuscator implements ICustomCodeHelperObfuscator { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -40,18 +40,15 @@ export class CustomCodeHelperObfuscator implements ICustomCodeHelperObfuscator { * @param {TInputOptions} additionalOptions * @returns {string} */ - public obfuscateTemplate (template: string, additionalOptions: TInputOptions = {}): string { - return JavaScriptObfuscator.obfuscate( - template, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: this.options.identifierNamesGenerator, - identifiersDictionary: this.options.identifiersDictionary, - numbersToExpressions: this.options.numbersToExpressions, - simplify: this.options.simplify, - seed: this.randomGenerator.getRawSeed(), - ...additionalOptions - } - ).getObfuscatedCode(); + public obfuscateTemplate(template: string, additionalOptions: TInputOptions = {}): string { + return JavaScriptObfuscator.obfuscate(template, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: this.options.identifierNamesGenerator, + identifiersDictionary: this.options.identifiersDictionary, + numbersToExpressions: this.options.numbersToExpressions, + simplify: this.options.simplify, + seed: this.randomGenerator.getRawSeed(), + ...additionalOptions + }).getObfuscatedCode(); } } diff --git a/src/custom-code-helpers/calls-controller/CallsControllerFunctionCodeHelper.ts b/src/custom-code-helpers/calls-controller/CallsControllerFunctionCodeHelper.ts index c9d21121..4f6758ef 100644 --- a/src/custom-code-helpers/calls-controller/CallsControllerFunctionCodeHelper.ts +++ b/src/custom-code-helpers/calls-controller/CallsControllerFunctionCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -39,9 +39,9 @@ export class CallsControllerFunctionCodeHelper extends AbstractCustomCodeHelper * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -60,7 +60,7 @@ export class CallsControllerFunctionCodeHelper extends AbstractCustomCodeHelper * @param {NodeTransformationStage} nodeTransformationStage * @param {string} callsControllerFunctionName */ - public initialize (nodeTransformationStage: NodeTransformationStage, callsControllerFunctionName: string): void { + public initialize(nodeTransformationStage: NodeTransformationStage, callsControllerFunctionName: string): void { this.nodeTransformationStage = nodeTransformationStage; this.callsControllerFunctionName = callsControllerFunctionName; } @@ -69,14 +69,14 @@ export class CallsControllerFunctionCodeHelper extends AbstractCustomCodeHelper * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { if (this.nodeTransformationStage === NodeTransformationStage.Finalizing) { return this.customCodeHelperObfuscator.obfuscateTemplate( this.customCodeHelperFormatter.formatTemplate(SingleCallControllerTemplate(), { diff --git a/src/custom-code-helpers/console-output/ConsoleOutputDisableCodeHelper.ts b/src/custom-code-helpers/console-output/ConsoleOutputDisableCodeHelper.ts index 8f34a5bc..f342aedf 100644 --- a/src/custom-code-helpers/console-output/ConsoleOutputDisableCodeHelper.ts +++ b/src/custom-code-helpers/console-output/ConsoleOutputDisableCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -9,7 +9,6 @@ import { ICustomCodeHelperObfuscator } from '../../interfaces/custom-code-helper import { IOptions } from '../../interfaces/options/IOptions'; import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator'; - import { ConsoleOutputDisableTemplate } from './templates/ConsoleOutputDisableTemplate'; import { initializable } from '../../decorators/Initializable'; @@ -38,9 +37,9 @@ export class ConsoleOutputDisableCodeHelper extends AbstractCustomCodeHelper { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -59,7 +58,7 @@ export class ConsoleOutputDisableCodeHelper extends AbstractCustomCodeHelper { * @param {string} callsControllerFunctionName * @param {StaticRange} consoleOutputDisableFunctionName */ - public initialize (callsControllerFunctionName: string, consoleOutputDisableFunctionName: string): void { + public initialize(callsControllerFunctionName: string, consoleOutputDisableFunctionName: string): void { this.callsControllerFunctionName = callsControllerFunctionName; this.consoleOutputDisableFunctionName = consoleOutputDisableFunctionName; } @@ -68,18 +67,18 @@ export class ConsoleOutputDisableCodeHelper extends AbstractCustomCodeHelper { * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { return this.customCodeHelperFormatter.formatTemplate(ConsoleOutputDisableTemplate(), { callControllerFunctionName: this.callsControllerFunctionName, consoleLogDisableFunctionName: this.consoleOutputDisableFunctionName, - globalVariableTemplate: this.getGlobalVariableTemplate(), + globalVariableTemplate: this.getGlobalVariableTemplate() }); } } diff --git a/src/custom-code-helpers/console-output/group/ConsoleOutputCodeHelperGroup.ts b/src/custom-code-helpers/console-output/group/ConsoleOutputCodeHelperGroup.ts index 4ffae2bb..75f584ea 100644 --- a/src/custom-code-helpers/console-output/group/ConsoleOutputCodeHelperGroup.ts +++ b/src/custom-code-helpers/console-output/group/ConsoleOutputCodeHelperGroup.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import { TCustomCodeHelperFactory } from '../../../types/container/custom-code-helpers/TCustomCodeHelperFactory'; @@ -29,7 +29,7 @@ export class ConsoleOutputCodeHelperGroup extends AbstractCustomCodeHelperGroup * @type {Map} */ @initializable() - protected customCodeHelpers!: Map ; + protected customCodeHelpers!: Map; /** * @type {TCustomCodeHelperFactory} @@ -42,10 +42,10 @@ export class ConsoleOutputCodeHelperGroup extends AbstractCustomCodeHelperGroup * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__ICustomCodeHelper) customCodeHelperFactory: TCustomCodeHelperFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -58,7 +58,7 @@ export class ConsoleOutputCodeHelperGroup extends AbstractCustomCodeHelperGroup * @param {TNodeWithStatements} nodeWithStatements * @param {ICallsGraphData[]} callsGraphData */ - public appendOnPreparingStage (nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { + public appendOnPreparingStage(nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { if (!this.options.disableConsoleOutput) { return; } @@ -72,8 +72,8 @@ export class ConsoleOutputCodeHelperGroup extends AbstractCustomCodeHelperGroup ? NodeAppender.getOptimalBlockScope(callsGraphData, randomCallsGraphIndex, 1) : nodeWithStatements; - const consoleOutputDisableLexicalScopeNode: TNodeWithLexicalScope | null = NodeLexicalScopeUtils - .getLexicalScope(consoleOutputDisableHostNode) ?? null; + const consoleOutputDisableLexicalScopeNode: TNodeWithLexicalScope | null = + NodeLexicalScopeUtils.getLexicalScope(consoleOutputDisableHostNode) ?? null; const consoleOutputDisableFunctionName: string = consoleOutputDisableLexicalScopeNode ? this.identifierNamesGenerator.generate(consoleOutputDisableLexicalScopeNode) @@ -103,15 +103,16 @@ export class ConsoleOutputCodeHelperGroup extends AbstractCustomCodeHelperGroup ); } - public initialize (): void { - this.customCodeHelpers = new Map (); + public initialize(): void { + this.customCodeHelpers = new Map(); if (!this.options.disableConsoleOutput) { return; } - const consoleOutputDisableExpressionCodeHelper: ICustomCodeHelper> = - this.customCodeHelperFactory(CustomCodeHelper.ConsoleOutputDisable); + const consoleOutputDisableExpressionCodeHelper: ICustomCodeHelper< + TInitialData + > = this.customCodeHelperFactory(CustomCodeHelper.ConsoleOutputDisable); const callsControllerFunctionCodeHelper: ICustomCodeHelper> = this.customCodeHelperFactory(CustomCodeHelper.CallsControllerFunction); diff --git a/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCallCodeHelper.ts b/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCallCodeHelper.ts index 48b170a6..c00476ec 100644 --- a/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCallCodeHelper.ts +++ b/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCallCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -37,9 +37,9 @@ export class DebugProtectionFunctionCallCodeHelper extends AbstractCustomCodeHel * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -58,7 +58,7 @@ export class DebugProtectionFunctionCallCodeHelper extends AbstractCustomCodeHel * @param {string} debugProtectionFunctionName * @param {string} callsControllerFunctionName */ - public initialize (debugProtectionFunctionName: string, callsControllerFunctionName: string): void { + public initialize(debugProtectionFunctionName: string, callsControllerFunctionName: string): void { this.debugProtectionFunctionName = debugProtectionFunctionName; this.callsControllerFunctionName = callsControllerFunctionName; } @@ -67,14 +67,14 @@ export class DebugProtectionFunctionCallCodeHelper extends AbstractCustomCodeHel * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { return this.customCodeHelperFormatter.formatTemplate(DebugProtectionFunctionCallTemplate(), { debugProtectionFunctionName: this.debugProtectionFunctionName, callControllerFunctionName: this.callsControllerFunctionName diff --git a/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCodeHelper.ts b/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCodeHelper.ts index 13b5a1de..381521de 100644 --- a/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCodeHelper.ts +++ b/src/custom-code-helpers/debug-protection/DebugProtectionFunctionCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -35,9 +35,9 @@ export class DebugProtectionFunctionCodeHelper extends AbstractCustomCodeHelper * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -55,7 +55,7 @@ export class DebugProtectionFunctionCodeHelper extends AbstractCustomCodeHelper /** * @param {string} debugProtectionFunctionName */ - public initialize (debugProtectionFunctionName: string): void { + public initialize(debugProtectionFunctionName: string): void { this.debugProtectionFunctionName = debugProtectionFunctionName; } @@ -63,17 +63,16 @@ export class DebugProtectionFunctionCodeHelper extends AbstractCustomCodeHelper * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { - const debuggerTemplate: string = this.options.target !== ObfuscationTarget.BrowserNoEval - ? DebuggerTemplate() - : DebuggerTemplateNoEval(); + protected override getCodeHelperTemplate(): string { + const debuggerTemplate: string = + this.options.target !== ObfuscationTarget.BrowserNoEval ? DebuggerTemplate() : DebuggerTemplateNoEval(); return this.customCodeHelperFormatter.formatTemplate(DebugProtectionFunctionTemplate(), { debuggerTemplate, diff --git a/src/custom-code-helpers/debug-protection/DebugProtectionFunctionIntervalCodeHelper.ts b/src/custom-code-helpers/debug-protection/DebugProtectionFunctionIntervalCodeHelper.ts index 686d32e5..78e8dc18 100644 --- a/src/custom-code-helpers/debug-protection/DebugProtectionFunctionIntervalCodeHelper.ts +++ b/src/custom-code-helpers/debug-protection/DebugProtectionFunctionIntervalCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -40,9 +40,9 @@ export class DebugProtectionFunctionIntervalCodeHelper extends AbstractCustomCod * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -61,7 +61,7 @@ export class DebugProtectionFunctionIntervalCodeHelper extends AbstractCustomCod * @param {string} debugProtectionFunctionName * @param {number} debugProtectionInterval */ - public initialize (debugProtectionFunctionName: string, debugProtectionInterval: number): void { + public initialize(debugProtectionFunctionName: string, debugProtectionInterval: number): void { this.debugProtectionFunctionName = debugProtectionFunctionName; this.debugProtectionInterval = debugProtectionInterval; } @@ -70,17 +70,18 @@ export class DebugProtectionFunctionIntervalCodeHelper extends AbstractCustomCod * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { - const globalVariableTemplate: string = this.options.target !== ObfuscationTarget.BrowserNoEval - ? this.getGlobalVariableTemplate() - : GlobalVariableNoEvalTemplate(); + protected override getCodeHelperTemplate(): string { + const globalVariableTemplate: string = + this.options.target !== ObfuscationTarget.BrowserNoEval + ? this.getGlobalVariableTemplate() + : GlobalVariableNoEvalTemplate(); return this.customCodeHelperFormatter.formatTemplate(DebugProtectionFunctionIntervalTemplate(), { debugProtectionFunctionName: this.debugProtectionFunctionName, diff --git a/src/custom-code-helpers/debug-protection/group/DebugProtectionCodeHelperGroup.ts b/src/custom-code-helpers/debug-protection/group/DebugProtectionCodeHelperGroup.ts index cfe5e984..14ad7cfd 100644 --- a/src/custom-code-helpers/debug-protection/group/DebugProtectionCodeHelperGroup.ts +++ b/src/custom-code-helpers/debug-protection/group/DebugProtectionCodeHelperGroup.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import { TCustomCodeHelperFactory } from '../../../types/container/custom-code-helpers/TCustomCodeHelperFactory'; @@ -32,7 +32,7 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou * @type {Map} */ @initializable() - protected customCodeHelpers!: Map ; + protected customCodeHelpers!: Map; /** * @type {TCustomCodeHelperFactory} @@ -45,10 +45,10 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__ICustomCodeHelper) customCodeHelperFactory: TCustomCodeHelperFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -61,7 +61,7 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou * @param {TNodeWithStatements} nodeWithStatements * @param {ICallsGraphData[]} callsGraphData */ - public appendOnPreparingStage (nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { + public appendOnPreparingStage(nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { if (!this.options.debugProtection) { return; } @@ -75,8 +75,8 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou ? NodeAppender.getOptimalBlockScope(callsGraphData, randomCallsGraphIndex, 1) : nodeWithStatements; - const debugProtectionFunctionCallScopeNode: TNodeWithLexicalScope | null = NodeLexicalScopeUtils - .getLexicalScope(debugProtectionFunctionCallHostNode) ?? null; + const debugProtectionFunctionCallScopeNode: TNodeWithLexicalScope | null = + NodeLexicalScopeUtils.getLexicalScope(debugProtectionFunctionCallHostNode) ?? null; const debugProtectionFunctionName: string = debugProtectionFunctionCallScopeNode ? this.identifierNamesGenerator.generate(debugProtectionFunctionCallScopeNode) @@ -108,7 +108,7 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou // debugProtectionFunction helper nodes append this.appendCustomNodeIfExist( CustomCodeHelper.DebugProtectionFunction, - (customCodeHelper: ICustomCodeHelper>) => { + (customCodeHelper: ICustomCodeHelper>) => { customCodeHelper.initialize(debugProtectionFunctionName); NodeAppender.append(nodeWithStatements, customCodeHelper.getNode()); @@ -131,8 +131,8 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou ); } - public initialize (): void { - this.customCodeHelpers = new Map (); + public initialize(): void { + this.customCodeHelpers = new Map(); if (!this.options.debugProtection) { return; @@ -140,10 +140,12 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou const debugProtectionFunctionCodeHelper: ICustomCodeHelper> = this.customCodeHelperFactory(CustomCodeHelper.DebugProtectionFunction); - const debugProtectionFunctionCallCodeHelper: ICustomCodeHelper> = - this.customCodeHelperFactory(CustomCodeHelper.DebugProtectionFunctionCall); - const debugProtectionFunctionIntervalCodeHelper: ICustomCodeHelper> = - this.customCodeHelperFactory(CustomCodeHelper.DebugProtectionFunctionInterval); + const debugProtectionFunctionCallCodeHelper: ICustomCodeHelper< + TInitialData + > = this.customCodeHelperFactory(CustomCodeHelper.DebugProtectionFunctionCall); + const debugProtectionFunctionIntervalCodeHelper: ICustomCodeHelper< + TInitialData + > = this.customCodeHelperFactory(CustomCodeHelper.DebugProtectionFunctionInterval); const callsControllerFunctionCodeHelper: ICustomCodeHelper> = this.customCodeHelperFactory(CustomCodeHelper.CallsControllerFunction); @@ -151,7 +153,10 @@ export class DebugProtectionCodeHelperGroup extends AbstractCustomCodeHelperGrou this.customCodeHelpers.set(CustomCodeHelper.DebugProtectionFunctionCall, debugProtectionFunctionCallCodeHelper); if (this.options.debugProtectionInterval) { - this.customCodeHelpers.set(CustomCodeHelper.DebugProtectionFunctionInterval, debugProtectionFunctionIntervalCodeHelper); + this.customCodeHelpers.set( + CustomCodeHelper.DebugProtectionFunctionInterval, + debugProtectionFunctionIntervalCodeHelper + ); } this.customCodeHelpers.set(CustomCodeHelper.CallsControllerFunction, callsControllerFunctionCodeHelper); diff --git a/src/custom-code-helpers/debug-protection/templates/debug-protection-function-call/DebugProtectionFunctionCallTemplate.ts b/src/custom-code-helpers/debug-protection/templates/debug-protection-function-call/DebugProtectionFunctionCallTemplate.ts index 2382da79..162b65d4 100644 --- a/src/custom-code-helpers/debug-protection/templates/debug-protection-function-call/DebugProtectionFunctionCallTemplate.ts +++ b/src/custom-code-helpers/debug-protection/templates/debug-protection-function-call/DebugProtectionFunctionCallTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function DebugProtectionFunctionCallTemplate (): string { +export function DebugProtectionFunctionCallTemplate(): string { return ` (function () { {callControllerFunctionName}( diff --git a/src/custom-code-helpers/debug-protection/templates/debug-protection-function-interval/DebugProtectionFunctionIntervalTemplate.ts b/src/custom-code-helpers/debug-protection/templates/debug-protection-function-interval/DebugProtectionFunctionIntervalTemplate.ts index fca700e5..3137f5e6 100644 --- a/src/custom-code-helpers/debug-protection/templates/debug-protection-function-interval/DebugProtectionFunctionIntervalTemplate.ts +++ b/src/custom-code-helpers/debug-protection/templates/debug-protection-function-interval/DebugProtectionFunctionIntervalTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function DebugProtectionFunctionIntervalTemplate (): string { +export function DebugProtectionFunctionIntervalTemplate(): string { return ` (function () { {globalVariableTemplate} diff --git a/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebugProtectionFunctionTemplate.ts b/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebugProtectionFunctionTemplate.ts index ef61656f..dae4007e 100644 --- a/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebugProtectionFunctionTemplate.ts +++ b/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebugProtectionFunctionTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function DebugProtectionFunctionTemplate (): string { +export function DebugProtectionFunctionTemplate(): string { return ` function {debugProtectionFunctionName} (ret) { function debuggerProtection (counter) { diff --git a/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplate.ts b/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplate.ts index eeb93b38..8740e592 100644 --- a/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplate.ts +++ b/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function DebuggerTemplate (): string { +export function DebuggerTemplate(): string { return ` if (typeof counter === 'string') { return (function (arg) {}.constructor('while (true) {}').apply('counter')); diff --git a/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplateNoEval.ts b/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplateNoEval.ts index fe52b6ba..62f841b0 100644 --- a/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplateNoEval.ts +++ b/src/custom-code-helpers/debug-protection/templates/debug-protection-function/DebuggerTemplateNoEval.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function DebuggerTemplateNoEval (): string { +export function DebuggerTemplateNoEval(): string { return ` if (typeof counter === 'string') { const func = function () { diff --git a/src/custom-code-helpers/domain-lock/DomainLockCodeHelper.ts b/src/custom-code-helpers/domain-lock/DomainLockCodeHelper.ts index 9a92b15c..eb683161 100644 --- a/src/custom-code-helpers/domain-lock/DomainLockCodeHelper.ts +++ b/src/custom-code-helpers/domain-lock/DomainLockCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -47,9 +47,9 @@ export class DomainLockCodeHelper extends AbstractCustomCodeHelper { * @param {IOptions} options * @param {ICryptUtils} cryptUtils */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -71,7 +71,7 @@ export class DomainLockCodeHelper extends AbstractCustomCodeHelper { * @param {string} callsControllerFunctionName * @param {string} domainLockFunctionName */ - public initialize (callsControllerFunctionName: string, domainLockFunctionName: string): void { + public initialize(callsControllerFunctionName: string, domainLockFunctionName: string): void { this.callsControllerFunctionName = callsControllerFunctionName; this.domainLockFunctionName = domainLockFunctionName; } @@ -80,14 +80,14 @@ export class DomainLockCodeHelper extends AbstractCustomCodeHelper { * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { const domainsString: string = this.options.domainLock.join(';'); const domainsLockRedirectUrl: string = this.options.domainLockRedirectUrl; const [hiddenDomainsString, domainsStringDiff]: string[] = this.cryptUtils.hideString( @@ -98,9 +98,10 @@ export class DomainLockCodeHelper extends AbstractCustomCodeHelper { domainsLockRedirectUrl, domainsLockRedirectUrl.length * 3 ); - const globalVariableTemplate: string = this.options.target !== ObfuscationTarget.BrowserNoEval - ? this.getGlobalVariableTemplate() - : GlobalVariableNoEvalTemplate(); + const globalVariableTemplate: string = + this.options.target !== ObfuscationTarget.BrowserNoEval + ? this.getGlobalVariableTemplate() + : GlobalVariableNoEvalTemplate(); return this.customCodeHelperFormatter.formatTemplate(DomainLockTemplate(), { callControllerFunctionName: this.callsControllerFunctionName, diff --git a/src/custom-code-helpers/domain-lock/group/DomainLockCustomCodeHelperGroup.ts b/src/custom-code-helpers/domain-lock/group/DomainLockCustomCodeHelperGroup.ts index 48ed8326..e768d03f 100644 --- a/src/custom-code-helpers/domain-lock/group/DomainLockCustomCodeHelperGroup.ts +++ b/src/custom-code-helpers/domain-lock/group/DomainLockCustomCodeHelperGroup.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import { TCustomCodeHelperFactory } from '../../../types/container/custom-code-helpers/TCustomCodeHelperFactory'; @@ -29,7 +29,7 @@ export class DomainLockCustomCodeHelperGroup extends AbstractCustomCodeHelperGro * @type {Map} */ @initializable() - protected customCodeHelpers!: Map ; + protected customCodeHelpers!: Map; /** * @type {TCustomCodeHelperFactory} @@ -42,10 +42,10 @@ export class DomainLockCustomCodeHelperGroup extends AbstractCustomCodeHelperGro * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__ICustomCodeHelper) customCodeHelperFactory: TCustomCodeHelperFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -58,7 +58,7 @@ export class DomainLockCustomCodeHelperGroup extends AbstractCustomCodeHelperGro * @param {TNodeWithStatements} nodeWithStatements * @param {ICallsGraphData[]} callsGraphData */ - public appendOnPreparingStage (nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { + public appendOnPreparingStage(nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { if (!this.options.domainLock.length) { return; } @@ -72,8 +72,8 @@ export class DomainLockCustomCodeHelperGroup extends AbstractCustomCodeHelperGro ? NodeAppender.getOptimalBlockScope(callsGraphData, randomCallsGraphIndex, 1) : nodeWithStatements; - const domainLockFunctionLexicalScopeNode: TNodeWithLexicalScope | null = NodeLexicalScopeUtils - .getLexicalScope(domainLockFunctionHostNode) ?? null; + const domainLockFunctionLexicalScopeNode: TNodeWithLexicalScope | null = + NodeLexicalScopeUtils.getLexicalScope(domainLockFunctionHostNode) ?? null; const domainLockFunctionName: string = domainLockFunctionLexicalScopeNode ? this.identifierNamesGenerator.generate(domainLockFunctionLexicalScopeNode) @@ -103,8 +103,8 @@ export class DomainLockCustomCodeHelperGroup extends AbstractCustomCodeHelperGro ); } - public initialize (): void { - this.customCodeHelpers = new Map (); + public initialize(): void { + this.customCodeHelpers = new Map(); if (!this.options.domainLock.length) { return; diff --git a/src/custom-code-helpers/self-defending/SelfDefendingCodeHelper.ts b/src/custom-code-helpers/self-defending/SelfDefendingCodeHelper.ts index 86d02a2e..b03a052c 100644 --- a/src/custom-code-helpers/self-defending/SelfDefendingCodeHelper.ts +++ b/src/custom-code-helpers/self-defending/SelfDefendingCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -37,9 +37,9 @@ export class SelfDefendingCodeHelper extends AbstractCustomCodeHelper { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -58,7 +58,7 @@ export class SelfDefendingCodeHelper extends AbstractCustomCodeHelper { * @param {string} callsControllerFunctionName * @param {string} selfDefendingFunctionName */ - public initialize (callsControllerFunctionName: string, selfDefendingFunctionName: string): void { + public initialize(callsControllerFunctionName: string, selfDefendingFunctionName: string): void { this.callsControllerFunctionName = callsControllerFunctionName; this.selfDefendingFunctionName = selfDefendingFunctionName; } @@ -67,14 +67,14 @@ export class SelfDefendingCodeHelper extends AbstractCustomCodeHelper { * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { return this.customCodeHelperFormatter.formatTemplate(SelfDefendingTemplate(), { callControllerFunctionName: this.callsControllerFunctionName, selfDefendingFunctionName: this.selfDefendingFunctionName diff --git a/src/custom-code-helpers/self-defending/group/SelfDefendingCodeHelperGroup.ts b/src/custom-code-helpers/self-defending/group/SelfDefendingCodeHelperGroup.ts index b747c682..ebb46590 100644 --- a/src/custom-code-helpers/self-defending/group/SelfDefendingCodeHelperGroup.ts +++ b/src/custom-code-helpers/self-defending/group/SelfDefendingCodeHelperGroup.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import { TCustomCodeHelperFactory } from '../../../types/container/custom-code-helpers/TCustomCodeHelperFactory'; @@ -29,7 +29,7 @@ export class SelfDefendingCodeHelperGroup extends AbstractCustomCodeHelperGroup * @type {Map} */ @initializable() - protected customCodeHelpers!: Map ; + protected customCodeHelpers!: Map; /** * @type {TCustomCodeHelperFactory} @@ -42,10 +42,10 @@ export class SelfDefendingCodeHelperGroup extends AbstractCustomCodeHelperGroup * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__ICustomCodeHelper) customCodeHelperFactory: TCustomCodeHelperFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -58,7 +58,7 @@ export class SelfDefendingCodeHelperGroup extends AbstractCustomCodeHelperGroup * @param {TNodeWithStatements} nodeWithStatements * @param {ICallsGraphData[]} callsGraphData */ - public appendOnPreparingStage (nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { + public appendOnPreparingStage(nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { if (!this.options.selfDefending) { return; } @@ -72,8 +72,8 @@ export class SelfDefendingCodeHelperGroup extends AbstractCustomCodeHelperGroup ? NodeAppender.getOptimalBlockScope(callsGraphData, randomCallsGraphIndex, 1) : nodeWithStatements; - const selfDefendingFunctionLexicalScopeNode: TNodeWithLexicalScope | null = NodeLexicalScopeUtils - .getLexicalScope(selfDefendingFunctionHostNode) ?? null; + const selfDefendingFunctionLexicalScopeNode: TNodeWithLexicalScope | null = + NodeLexicalScopeUtils.getLexicalScope(selfDefendingFunctionHostNode) ?? null; const selfDefendingFunctionName: string = selfDefendingFunctionLexicalScopeNode ? this.identifierNamesGenerator.generate(selfDefendingFunctionLexicalScopeNode) @@ -103,8 +103,8 @@ export class SelfDefendingCodeHelperGroup extends AbstractCustomCodeHelperGroup ); } - public initialize (): void { - this.customCodeHelpers = new Map (); + public initialize(): void { + this.customCodeHelpers = new Map(); if (!this.options.selfDefending) { return; diff --git a/src/custom-code-helpers/string-array/StringArrayCallsWrapperBase64CodeHelper.ts b/src/custom-code-helpers/string-array/StringArrayCallsWrapperBase64CodeHelper.ts index 43f60033..61cf1113 100644 --- a/src/custom-code-helpers/string-array/StringArrayCallsWrapperBase64CodeHelper.ts +++ b/src/custom-code-helpers/string-array/StringArrayCallsWrapperBase64CodeHelper.ts @@ -1,4 +1,4 @@ -import { injectable, } from 'inversify'; +import { injectable } from 'inversify'; import { AtobTemplate } from './templates/string-array-calls-wrapper/AtobTemplate'; import { StringArrayBase64DecodeTemplate } from './templates/string-array-calls-wrapper/StringArrayBase64DecodeTemplate'; @@ -10,7 +10,7 @@ export class StringArrayCallsWrapperBase64CodeHelper extends StringArrayCallsWra /** * @returns {string} */ - protected override getDecodeStringArrayTemplate (): string { + protected override getDecodeStringArrayTemplate(): string { const atobFunctionName: string = this.randomGenerator.getRandomString(6); const atobPolyfill: string = this.customCodeHelperFormatter.formatTemplate( @@ -22,15 +22,12 @@ export class StringArrayCallsWrapperBase64CodeHelper extends StringArrayCallsWra const selfDefendingCode: string = this.getSelfDefendingTemplate(); - return this.customCodeHelperFormatter.formatTemplate( - StringArrayBase64DecodeTemplate(this.randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode, - stringArrayCallsWrapperName: this.stringArrayCallsWrapperName, - stringArrayFunctionName: this.stringArrayFunctionName - } - ); + return this.customCodeHelperFormatter.formatTemplate(StringArrayBase64DecodeTemplate(this.randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode, + stringArrayCallsWrapperName: this.stringArrayCallsWrapperName, + stringArrayFunctionName: this.stringArrayFunctionName + }); } } diff --git a/src/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.ts b/src/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.ts index e599643d..ac4e3005 100644 --- a/src/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.ts +++ b/src/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -57,9 +57,9 @@ export class StringArrayCallsWrapperCodeHelper extends AbstractCustomCodeHelper * @param {IOptions} options * @param {IEscapeSequenceEncoder} escapeSequenceEncoder */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -82,7 +82,7 @@ export class StringArrayCallsWrapperCodeHelper extends AbstractCustomCodeHelper * @param {string} stringArrayCallsWrapperName * @param {number} indexShiftAmount */ - public initialize ( + public initialize( stringArrayFunctionName: string, stringArrayCallsWrapperName: string, indexShiftAmount: number @@ -98,14 +98,14 @@ export class StringArrayCallsWrapperCodeHelper extends AbstractCustomCodeHelper * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { const decodeCodeHelperTemplate: string = this.getDecodeStringArrayTemplate(); const preservedNames: string[] = [`^${this.stringArrayFunctionName}$`]; @@ -126,23 +126,20 @@ export class StringArrayCallsWrapperCodeHelper extends AbstractCustomCodeHelper /** * @returns {string} */ - protected getDecodeStringArrayTemplate (): string { + protected getDecodeStringArrayTemplate(): string { return ''; } /** * @returns {string} */ - protected getSelfDefendingTemplate (): string { + protected getSelfDefendingTemplate(): string { if (!this.options.selfDefending) { return ''; } return this.customCodeHelperFormatter.formatTemplate( - SelfDefendingTemplate( - this.randomGenerator, - this.escapeSequenceEncoder - ), + SelfDefendingTemplate(this.randomGenerator, this.escapeSequenceEncoder), { stringArrayCallsWrapperName: this.stringArrayCallsWrapperName } diff --git a/src/custom-code-helpers/string-array/StringArrayCallsWrapperRc4CodeHelper.ts b/src/custom-code-helpers/string-array/StringArrayCallsWrapperRc4CodeHelper.ts index 48074fc0..2f830cbd 100644 --- a/src/custom-code-helpers/string-array/StringArrayCallsWrapperRc4CodeHelper.ts +++ b/src/custom-code-helpers/string-array/StringArrayCallsWrapperRc4CodeHelper.ts @@ -1,4 +1,4 @@ -import { injectable, } from 'inversify'; +import { injectable } from 'inversify'; import { AtobTemplate } from './templates/string-array-calls-wrapper/AtobTemplate'; import { Rc4Template } from './templates/string-array-calls-wrapper/Rc4Template'; @@ -11,7 +11,7 @@ export class StringArrayCallsWrapperRc4CodeHelper extends StringArrayCallsWrappe /** * @returns {string} */ - protected override getDecodeStringArrayTemplate (): string { + protected override getDecodeStringArrayTemplate(): string { const atobFunctionName: string = this.randomGenerator.getRandomString(6); const rc4FunctionName: string = this.randomGenerator.getRandomString(6); @@ -21,26 +21,20 @@ export class StringArrayCallsWrapperRc4CodeHelper extends StringArrayCallsWrappe atobFunctionName } ); - const rc4Polyfill: string = this.customCodeHelperFormatter.formatTemplate( - Rc4Template(), - { - atobFunctionName, - rc4FunctionName - } - ); + const rc4Polyfill: string = this.customCodeHelperFormatter.formatTemplate(Rc4Template(), { + atobFunctionName, + rc4FunctionName + }); const selfDefendingCode: string = this.getSelfDefendingTemplate(); - return this.customCodeHelperFormatter.formatTemplate( - StringArrayRC4DecodeTemplate(this.randomGenerator), - { - atobPolyfill, - rc4FunctionName, - rc4Polyfill, - selfDefendingCode, - stringArrayCallsWrapperName: this.stringArrayCallsWrapperName, - stringArrayFunctionName: this.stringArrayFunctionName - } - ); + return this.customCodeHelperFormatter.formatTemplate(StringArrayRC4DecodeTemplate(this.randomGenerator), { + atobPolyfill, + rc4FunctionName, + rc4Polyfill, + selfDefendingCode, + stringArrayCallsWrapperName: this.stringArrayCallsWrapperName, + stringArrayFunctionName: this.stringArrayFunctionName + }); } } diff --git a/src/custom-code-helpers/string-array/StringArrayCodeHelper.ts b/src/custom-code-helpers/string-array/StringArrayCodeHelper.ts index e1c97f75..47ce8613 100644 --- a/src/custom-code-helpers/string-array/StringArrayCodeHelper.ts +++ b/src/custom-code-helpers/string-array/StringArrayCodeHelper.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -40,9 +40,9 @@ export class StringArrayCodeHelper extends AbstractCustomCodeHelper { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -61,10 +61,7 @@ export class StringArrayCodeHelper extends AbstractCustomCodeHelper { * @param {IStringArrayStorage} stringArrayStorage * @param {string} stringArrayFunctionName */ - public initialize ( - stringArrayStorage: IStringArrayStorage, - stringArrayFunctionName: string - ): void { + public initialize(stringArrayStorage: IStringArrayStorage, stringArrayFunctionName: string): void { this.stringArrayStorage = stringArrayStorage; this.stringArrayFunctionName = stringArrayFunctionName; } @@ -73,14 +70,14 @@ export class StringArrayCodeHelper extends AbstractCustomCodeHelper { * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { const stringArrayName: string = this.identifierNamesGenerator.generateNext(); return this.customCodeHelperFormatter.formatTemplate(StringArrayTemplate(), { @@ -93,9 +90,8 @@ export class StringArrayCodeHelper extends AbstractCustomCodeHelper { /** * @returns {string} */ - private getEncodedStringArrayStorageItems (): string { - return Array - .from(this.stringArrayStorage.getStorage().values()) + private getEncodedStringArrayStorageItems(): string { + return Array.from(this.stringArrayStorage.getStorage().values()) .map((stringArrayStorageItemData: IStringArrayStorageItemData): string => { const escapedEncodedValue: string = StringUtils.escapeJsString(stringArrayStorageItemData.encodedValue); diff --git a/src/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.ts b/src/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.ts index 776b2643..563c8749 100644 --- a/src/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.ts +++ b/src/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.ts @@ -1,5 +1,5 @@ import type { Expression } from 'estree'; -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -44,9 +44,9 @@ export class StringArrayRotateFunctionCodeHelper extends AbstractCustomCodeHelpe * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.ICustomCodeHelperObfuscator) customCodeHelperObfuscator: ICustomCodeHelperObfuscator, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -66,7 +66,7 @@ export class StringArrayRotateFunctionCodeHelper extends AbstractCustomCodeHelpe * @param {number} comparisonValue * @param {Expression} comparisonExpressionNode */ - public initialize ( + public initialize( stringArrayFunctionName: string, comparisonValue: number, comparisonExpressionNode: Expression @@ -80,23 +80,20 @@ export class StringArrayRotateFunctionCodeHelper extends AbstractCustomCodeHelpe * @param {string} codeHelperTemplate * @returns {TStatement[]} */ - protected getNodeStructure (codeHelperTemplate: string): TStatement[] { + protected getNodeStructure(codeHelperTemplate: string): TStatement[] { return NodeUtils.convertCodeToStructure(codeHelperTemplate); } /** * @returns {string} */ - protected override getCodeHelperTemplate (): string { + protected override getCodeHelperTemplate(): string { const comparisonExpressionCode: string = NodeUtils.convertStructureToCode([this.comparisonExpressionNode]); - return this.customCodeHelperFormatter.formatTemplate( - StringArrayRotateFunctionTemplate(), - { - comparisonExpressionCode, - comparisonValue: this.comparisonValue, - stringArrayFunctionName: this.stringArrayFunctionName - } - ); + return this.customCodeHelperFormatter.formatTemplate(StringArrayRotateFunctionTemplate(), { + comparisonExpressionCode, + comparisonValue: this.comparisonValue, + stringArrayFunctionName: this.stringArrayFunctionName + }); } } diff --git a/src/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.ts b/src/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.ts index 90a667b4..242dd8e3 100644 --- a/src/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.ts +++ b/src/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import { TCustomCodeHelperFactory } from '../../../types/container/custom-code-helpers/TCustomCodeHelperFactory'; @@ -29,17 +29,19 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { /** * @type {Map} */ - private static readonly stringArrayCallsWrapperCodeHelperMap: Map = new Map([ - [StringArrayEncoding.None, CustomCodeHelper.StringArrayCallsWrapper], - [StringArrayEncoding.Base64, CustomCodeHelper.StringArrayCallsWrapperBase64], - [StringArrayEncoding.Rc4, CustomCodeHelper.StringArrayCallsWrapperRc4] - ]); + private static readonly stringArrayCallsWrapperCodeHelperMap: Map = new Map( + [ + [StringArrayEncoding.None, CustomCodeHelper.StringArrayCallsWrapper], + [StringArrayEncoding.Base64, CustomCodeHelper.StringArrayCallsWrapperBase64], + [StringArrayEncoding.Rc4, CustomCodeHelper.StringArrayCallsWrapperRc4] + ] + ); /** * @type {Map} */ @initializable() - protected customCodeHelpers!: Map ; + protected customCodeHelpers!: Map; /** * @type {TCustomCodeHelperFactory} @@ -58,11 +60,11 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__ICustomCodeHelper) customCodeHelperFactory: TCustomCodeHelperFactory, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -76,7 +78,7 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { * @param {TNodeWithStatements} nodeWithStatements * @param {ICallsGraphData[]} callsGraphData */ - public appendOnFinalizingStage (nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { + public appendOnFinalizingStage(nodeWithStatements: TNodeWithStatements, callsGraphData: ICallsGraphData[]): void { if (!this.stringArrayStorage.getLength()) { return; } @@ -97,7 +99,8 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { // stringArrayCallsWrapper helper nodes append for (const stringArrayEncoding of this.options.stringArrayEncoding) { - const stringArrayCallsWrapperCodeHelperName: CustomCodeHelper = this.getStringArrayCallsWrapperCodeHelperName(stringArrayEncoding); + const stringArrayCallsWrapperCodeHelperName: CustomCodeHelper = + this.getStringArrayCallsWrapperCodeHelperName(stringArrayEncoding); this.appendCustomNodeIfExist( stringArrayCallsWrapperCodeHelperName, @@ -112,8 +115,8 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { } } - public initialize (): void { - this.customCodeHelpers = new Map (); + public initialize(): void { + this.customCodeHelpers = new Map(); if (!this.options.stringArray) { return; @@ -125,18 +128,18 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { const stringArrayCodeHelper: ICustomCodeHelper> = this.customCodeHelperFactory(CustomCodeHelper.StringArray); - stringArrayCodeHelper.initialize( - this.stringArrayStorage, - stringArrayFunctionName - ); + stringArrayCodeHelper.initialize(this.stringArrayStorage, stringArrayFunctionName); this.customCodeHelpers.set(CustomCodeHelper.StringArray, stringArrayCodeHelper); // stringArrayCallsWrapper helper initialize for (const stringArrayEncoding of this.options.stringArrayEncoding) { - const stringArrayCallsWrapperCodeHelperName: CustomCodeHelper = this.getStringArrayCallsWrapperCodeHelperName(stringArrayEncoding); - const stringArrayCallsWrapperCodeHelper: ICustomCodeHelper> = - this.customCodeHelperFactory(stringArrayCallsWrapperCodeHelperName); - const stringArrayCallsWrapperName: string = this.stringArrayStorage.getStorageCallsWrapperName(stringArrayEncoding); + const stringArrayCallsWrapperCodeHelperName: CustomCodeHelper = + this.getStringArrayCallsWrapperCodeHelperName(stringArrayEncoding); + const stringArrayCallsWrapperCodeHelper: ICustomCodeHelper< + TInitialData + > = this.customCodeHelperFactory(stringArrayCallsWrapperCodeHelperName); + const stringArrayCallsWrapperName: string = + this.stringArrayStorage.getStorageCallsWrapperName(stringArrayEncoding); stringArrayCallsWrapperCodeHelper.initialize( stringArrayFunctionName, @@ -152,20 +155,18 @@ export class StringArrayCodeHelperGroup extends AbstractCustomCodeHelperGroup { * @param {TStringArrayEncoding} stringArrayEncoding * @returns {CustomCodeHelper} */ - private getStringArrayCallsWrapperCodeHelperName (stringArrayEncoding: TStringArrayEncoding): CustomCodeHelper { - return StringArrayCodeHelperGroup - .stringArrayCallsWrapperCodeHelperMap.get(stringArrayEncoding) - ?? CustomCodeHelper.StringArrayCallsWrapper; + private getStringArrayCallsWrapperCodeHelperName(stringArrayEncoding: TStringArrayEncoding): CustomCodeHelper { + return ( + StringArrayCodeHelperGroup.stringArrayCallsWrapperCodeHelperMap.get(stringArrayEncoding) ?? + CustomCodeHelper.StringArrayCallsWrapper + ); } /** * @param {TStatement[]} scopeStatements * @returns {number} */ - private getScopeStatementRandomIndex (scopeStatements: TStatement[]): number { - return this.randomGenerator.getRandomInteger( - 0, - Math.max(0, scopeStatements.length) - ); + private getScopeStatementRandomIndex(scopeStatements: TStatement[]): number { + return this.randomGenerator.getRandomInteger(0, Math.max(0, scopeStatements.length)); } } diff --git a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/AtobTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/AtobTemplate.ts index bedeec5f..340d7b42 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/AtobTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/AtobTemplate.ts @@ -5,7 +5,7 @@ import { base64alphabetSwapped } from '../../../../constants/Base64AlphabetSwapp * * @returns {string} */ -export function AtobTemplate (selfDefending: boolean): string { +export function AtobTemplate(selfDefending: boolean): string { return ` var {atobFunctionName} = function (input) { const chars = '${base64alphabetSwapped}'; @@ -20,10 +20,8 @@ export function AtobTemplate (selfDefending: boolean): string { ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += ${((): string => { const basePart: string = 'String.fromCharCode(255 & bs >> (-2 * bc & 6))'; - - return selfDefending - ? `((func.charCodeAt(idx + 10) - 10 !== 0) ? ${basePart} : bc)` - : basePart; + + return selfDefending ? `((func.charCodeAt(idx + 10) - 10 !== 0) ? ${basePart} : bc)` : basePart; })()} : 0 ) { diff --git a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/Rc4Template.ts b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/Rc4Template.ts index 15f72ad2..cab18adb 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/Rc4Template.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/Rc4Template.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function Rc4Template (): string { +export function Rc4Template(): string { return ` const {rc4FunctionName} = function (str, key) { let s = [], j = 0, x, output = ''; diff --git a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/SelfDefendingTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/SelfDefendingTemplate.ts index bf08c200..def5c29e 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/SelfDefendingTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/SelfDefendingTemplate.ts @@ -7,7 +7,7 @@ import { IRandomGenerator } from '../../../../interfaces/utils/IRandomGenerator' * @returns {string} * @constructor */ -export function SelfDefendingTemplate ( +export function SelfDefendingTemplate( randomGenerator: IRandomGenerator, escapeSequenceEncoder: IEscapeSequenceEncoder ): string { @@ -21,18 +21,14 @@ export function SelfDefendingTemplate ( const runStateIdentifier: string = randomGenerator.getRandomString(identifierLength); const getStateIdentifier: string = randomGenerator.getRandomString(identifierLength); const stateResultIdentifier: string = randomGenerator.getRandomString(identifierLength); - + return ` const StatesClass = function (${rc4BytesIdentifier}) { this.${rc4BytesIdentifier} = ${rc4BytesIdentifier}; this.${statesIdentifier} = [1, 0, 0]; this.${newStateIdentifier} = function(){return 'newState';}; - this.${firstStateIdentifier} = '${ - escapeSequenceEncoder.encode('\\w+ *\\(\\) *{\\w+ *', true) - }'; - this.${secondStateIdentifier} = '${ - escapeSequenceEncoder.encode('[\'|"].+[\'|"];? *}', true) - }'; + this.${firstStateIdentifier} = '${escapeSequenceEncoder.encode('\\w+ *\\(\\) *{\\w+ *', true)}'; + this.${secondStateIdentifier} = '${escapeSequenceEncoder.encode('[\'|"].+[\'|"];? *}', true)}'; }; StatesClass.prototype.${checkStateIdentifier} = function () { diff --git a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayBase64DecodeTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayBase64DecodeTemplate.ts index b1b0a4f8..9bda4bf2 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayBase64DecodeTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayBase64DecodeTemplate.ts @@ -5,9 +5,7 @@ import { IRandomGenerator } from '../../../../interfaces/utils/IRandomGenerator' * @returns {string} * @constructor */ -export function StringArrayBase64DecodeTemplate ( - randomGenerator: IRandomGenerator -): string { +export function StringArrayBase64DecodeTemplate(randomGenerator: IRandomGenerator): string { const identifierLength: number = 6; const initializedIdentifier: string = randomGenerator.getRandomString(identifierLength); const base64Identifier: string = randomGenerator.getRandomString(identifierLength); diff --git a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayCallsWrapperTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayCallsWrapperTemplate.ts index c7dcaca9..072b6b89 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayCallsWrapperTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayCallsWrapperTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function StringArrayCallsWrapperTemplate (): string { +export function StringArrayCallsWrapperTemplate(): string { return ` function {stringArrayCallsWrapperName} (index, key) { index = index - {indexShiftAmount}; diff --git a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayRC4DecodeTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayRC4DecodeTemplate.ts index 4a8bcbf6..69e4fc8b 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayRC4DecodeTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-calls-wrapper/StringArrayRC4DecodeTemplate.ts @@ -5,9 +5,7 @@ import { IRandomGenerator } from '../../../../interfaces/utils/IRandomGenerator' * @returns {string} * @constructor */ -export function StringArrayRC4DecodeTemplate ( - randomGenerator: IRandomGenerator -): string { +export function StringArrayRC4DecodeTemplate(randomGenerator: IRandomGenerator): string { const identifierLength: number = 6; const initializedIdentifier: string = randomGenerator.getRandomString(identifierLength); const rc4Identifier: string = randomGenerator.getRandomString(identifierLength); diff --git a/src/custom-code-helpers/string-array/templates/string-array-rotate-function/StringArrayRotateFunctionTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array-rotate-function/StringArrayRotateFunctionTemplate.ts index 4a8e1203..bc300c89 100644 --- a/src/custom-code-helpers/string-array/templates/string-array-rotate-function/StringArrayRotateFunctionTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array-rotate-function/StringArrayRotateFunctionTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function StringArrayRotateFunctionTemplate (): string { +export function StringArrayRotateFunctionTemplate(): string { return ` (function (stringArrayFunction, comparisonValue) { const stringArray = stringArrayFunction(); diff --git a/src/custom-code-helpers/string-array/templates/string-array/StringArrayTemplate.ts b/src/custom-code-helpers/string-array/templates/string-array/StringArrayTemplate.ts index a9689e70..a0e05ca0 100644 --- a/src/custom-code-helpers/string-array/templates/string-array/StringArrayTemplate.ts +++ b/src/custom-code-helpers/string-array/templates/string-array/StringArrayTemplate.ts @@ -1,7 +1,7 @@ /** * @returns {string} */ -export function StringArrayTemplate (): string { +export function StringArrayTemplate(): string { return ` function {stringArrayFunctionName} () { const {stringArrayName} = [{stringArrayStorageItems}]; diff --git a/src/custom-nodes/AbstractCustomNode.ts b/src/custom-nodes/AbstractCustomNode.ts index 99622731..63584218 100644 --- a/src/custom-nodes/AbstractCustomNode.ts +++ b/src/custom-nodes/AbstractCustomNode.ts @@ -11,9 +11,9 @@ import { IOptions } from '../interfaces/options/IOptions'; import { IRandomGenerator } from '../interfaces/utils/IRandomGenerator'; @injectable() -export abstract class AbstractCustomNode < - TInitialData extends unknown[] = unknown[] -> implements ICustomNode { +export abstract class AbstractCustomNode + implements ICustomNode +{ /** * @type {TStatement[] | null} */ @@ -45,9 +45,9 @@ export abstract class AbstractCustomNode < * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -61,11 +61,9 @@ export abstract class AbstractCustomNode < /** * @returns {TStatement[]} */ - public getNode (): TStatement[] { + public getNode(): TStatement[] { if (!this.cachedNode) { - this.cachedNode = this.customCodeHelperFormatter.formatStructure( - this.getNodeStructure() - ); + this.cachedNode = this.customCodeHelperFormatter.formatStructure(this.getNodeStructure()); } return this.cachedNode; @@ -74,10 +72,10 @@ export abstract class AbstractCustomNode < /** * @param {TInitialData} args */ - public abstract initialize (...args: TInitialData): void; + public abstract initialize(...args: TInitialData): void; /** * @returns {TStatement[]} */ - protected abstract getNodeStructure (): TStatement[]; + protected abstract getNodeStructure(): TStatement[]; } diff --git a/src/custom-nodes/control-flow-flattening-nodes/BinaryExpressionFunctionNode.ts b/src/custom-nodes/control-flow-flattening-nodes/BinaryExpressionFunctionNode.ts index d74718f2..55c02da8 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/BinaryExpressionFunctionNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/BinaryExpressionFunctionNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import type { BinaryOperator } from 'estree'; @@ -27,38 +27,30 @@ export class BinaryExpressionFunctionNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {BinaryOperator} operator */ - public initialize (operator: BinaryOperator): void { + public initialize(operator: BinaryOperator): void { this.operator = operator; } /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.expressionStatementNode( NodeFactory.functionExpressionNode( - [ - NodeFactory.identifierNode('x'), - NodeFactory.identifierNode('y') - ], + [NodeFactory.identifierNode('x'), NodeFactory.identifierNode('y')], NodeFactory.blockStatementNode([ NodeFactory.returnStatementNode( NodeFactory.binaryExpressionNode( diff --git a/src/custom-nodes/control-flow-flattening-nodes/BlockStatementControlFlowFlatteningNode.ts b/src/custom-nodes/control-flow-flattening-nodes/BlockStatementControlFlowFlatteningNode.ts index d774a9c6..84f64b93 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/BlockStatementControlFlowFlatteningNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/BlockStatementControlFlowFlatteningNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -45,19 +45,14 @@ export class BlockStatementControlFlowFlatteningNode extends AbstractCustomNode * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** @@ -65,7 +60,7 @@ export class BlockStatementControlFlowFlatteningNode extends AbstractCustomNode * @param {number[]} shuffledKeys * @param {number[]} originalKeysIndexesInShuffledArray */ - public initialize ( + public initialize( blockStatementBody: ESTree.Statement[], shuffledKeys: number[], originalKeysIndexesInShuffledArray: number[] @@ -78,7 +73,7 @@ export class BlockStatementControlFlowFlatteningNode extends AbstractCustomNode /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const controllerIdentifierName: string = this.randomGenerator.getRandomString(6); const indexIdentifierName: string = this.randomGenerator.getRandomString(6); @@ -94,9 +89,7 @@ export class BlockStatementControlFlowFlatteningNode extends AbstractCustomNode ), NodeFactory.identifierNode('split') ), - [ - NodeFactory.literalNode(StringSeparator.VerticalLine) - ] + [NodeFactory.literalNode(StringSeparator.VerticalLine)] ) ) ], @@ -117,10 +110,7 @@ export class BlockStatementControlFlowFlatteningNode extends AbstractCustomNode NodeFactory.switchStatementNode( NodeFactory.memberExpressionNode( NodeFactory.identifierNode(controllerIdentifierName), - NodeFactory.updateExpressionNode( - '++', - NodeFactory.identifierNode(indexIdentifierName) - ), + NodeFactory.updateExpressionNode('++', NodeFactory.identifierNode(indexIdentifierName)), true ), this.shuffledKeys.map((key: number, index: number) => { @@ -135,10 +125,7 @@ export class BlockStatementControlFlowFlatteningNode extends AbstractCustomNode consequent.push(NodeFactory.continueStatement()); } - return NodeFactory.switchCaseNode( - NodeFactory.literalNode(String(index)), - consequent - ); + return NodeFactory.switchCaseNode(NodeFactory.literalNode(String(index)), consequent); }) ), NodeFactory.breakStatement() diff --git a/src/custom-nodes/control-flow-flattening-nodes/CallExpressionFunctionNode.ts b/src/custom-nodes/control-flow-flattening-nodes/CallExpressionFunctionNode.ts index 88f34b03..8202db77 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/CallExpressionFunctionNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/CallExpressionFunctionNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -38,26 +38,24 @@ export class CallExpressionFunctionNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {(Expression | SpreadElement)[]} expressionArguments * @param {boolean} isChainExpressionParent */ - public initialize (expressionArguments: (ESTree.Expression | ESTree.SpreadElement)[], isChainExpressionParent: boolean): void { + public initialize( + expressionArguments: (ESTree.Expression | ESTree.SpreadElement)[], + isChainExpressionParent: boolean + ): void { this.expressionArguments = expressionArguments; this.isChainExpressionParent = isChainExpressionParent; } @@ -65,7 +63,7 @@ export class CallExpressionFunctionNode extends AbstractCustomNode { /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const calleeIdentifier: ESTree.Identifier = NodeFactory.identifierNode('callee'); const params: (ESTree.Identifier | ESTree.RestElement)[] = []; const callArguments: (ESTree.Identifier | ESTree.SpreadElement)[] = []; @@ -92,22 +90,19 @@ export class CallExpressionFunctionNode extends AbstractCustomNode { } const callExpression = NodeFactory.callExpressionNode( - calleeIdentifier, - callArguments, - this.isChainExpressionParent + calleeIdentifier, + callArguments, + this.isChainExpressionParent ); - + const structure: TStatement = NodeFactory.expressionStatementNode( NodeFactory.functionExpressionNode( - [ - calleeIdentifier, - ...params - ], + [calleeIdentifier, ...params], NodeFactory.blockStatementNode([ NodeFactory.returnStatementNode( this.isChainExpressionParent - ? NodeFactory.chainExpressionNode(callExpression) - : callExpression + ? NodeFactory.chainExpressionNode(callExpression) + : callExpression ) ]) ) diff --git a/src/custom-nodes/control-flow-flattening-nodes/LiteralNode.ts b/src/custom-nodes/control-flow-flattening-nodes/LiteralNode.ts index 1e418d11..29097ceb 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/LiteralNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/LiteralNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import type * as ESTree from 'estree'; @@ -29,32 +29,27 @@ export class LiteralNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {ESTree.Literal} literalNode */ - public initialize (literalNode: ESTree.Literal): void { + public initialize(literalNode: ESTree.Literal): void { this.literalNode = literalNode; } /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.expressionStatementNode(this.literalNode); return [structure]; diff --git a/src/custom-nodes/control-flow-flattening-nodes/LogicalExpressionFunctionNode.ts b/src/custom-nodes/control-flow-flattening-nodes/LogicalExpressionFunctionNode.ts index a10f1425..65da3d95 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/LogicalExpressionFunctionNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/LogicalExpressionFunctionNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import type { LogicalOperator } from 'estree'; @@ -27,38 +27,30 @@ export class LogicalExpressionFunctionNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {LogicalOperator} operator */ - public initialize (operator: LogicalOperator): void { + public initialize(operator: LogicalOperator): void { this.operator = operator; } /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.expressionStatementNode( NodeFactory.functionExpressionNode( - [ - NodeFactory.identifierNode('x'), - NodeFactory.identifierNode('y') - ], + [NodeFactory.identifierNode('x'), NodeFactory.identifierNode('y')], NodeFactory.blockStatementNode([ NodeFactory.returnStatementNode( NodeFactory.logicalExpressionNode( diff --git a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/CallExpressionControlFlowStorageCallNode.ts b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/CallExpressionControlFlowStorageCallNode.ts index eba9f6ac..a024ec1a 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/CallExpressionControlFlowStorageCallNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/CallExpressionControlFlowStorageCallNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import type * as ESTree from 'estree'; @@ -48,19 +48,14 @@ export class CallExpressionControlFlowStorageCallNode extends AbstractCustomNode * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** @@ -69,7 +64,7 @@ export class CallExpressionControlFlowStorageCallNode extends AbstractCustomNode * @param {Expression} callee * @param {(Expression | SpreadElement)[]} expressionArguments */ - public initialize ( + public initialize( controlFlowStorageName: string, controlFlowStorageKey: string, callee: ESTree.Expression, @@ -84,17 +79,14 @@ export class CallExpressionControlFlowStorageCallNode extends AbstractCustomNode /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.expressionStatementNode( NodeFactory.callExpressionNode( NodeFactory.memberExpressionNode( NodeFactory.identifierNode(this.controlFlowStorageName), NodeFactory.identifierNode(this.controlFlowStorageKey) ), - [ - this.callee, - ...this.expressionArguments - ] + [this.callee, ...this.expressionArguments] ) ); diff --git a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ControlFlowStorageNode.ts b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ControlFlowStorageNode.ts index 8db3102d..463f6a16 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ControlFlowStorageNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ControlFlowStorageNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -32,32 +32,27 @@ export class ControlFlowStorageNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {IControlFlowStorage} controlFlowStorage */ - public initialize (controlFlowStorage: IControlFlowStorage): void { + public initialize(controlFlowStorage: IControlFlowStorage): void { this.controlFlowStorage = controlFlowStorage; } /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const propertyNodes: ESTree.Property[] = []; const controlFlowStorageMap: Map = this.controlFlowStorage.getStorage(); @@ -65,15 +60,12 @@ export class ControlFlowStorageNode extends AbstractCustomNode { const node: ESTree.Node = value.getNode()[0]; if (!NodeGuards.isExpressionStatementNode(node)) { - throw new Error('Function node for control flow storage object should be passed inside the `ExpressionStatement` node!'); + throw new Error( + 'Function node for control flow storage object should be passed inside the `ExpressionStatement` node!' + ); } - propertyNodes.push( - NodeFactory.propertyNode( - NodeFactory.identifierNode(key), - node.expression - ) - ); + propertyNodes.push(NodeFactory.propertyNode(NodeFactory.identifierNode(key), node.expression)); } const structure: ESTree.Node = NodeFactory.variableDeclarationNode( diff --git a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ExpressionWithOperatorControlFlowStorageCallNode.ts b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ExpressionWithOperatorControlFlowStorageCallNode.ts index f0ce1218..a5cc0eec 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ExpressionWithOperatorControlFlowStorageCallNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ExpressionWithOperatorControlFlowStorageCallNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import type { Expression } from 'estree'; @@ -46,19 +46,14 @@ export class ExpressionWithOperatorControlFlowStorageCallNode extends AbstractCu * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** @@ -67,11 +62,11 @@ export class ExpressionWithOperatorControlFlowStorageCallNode extends AbstractCu * @param {Expression} leftValue * @param {Expression} rightValue */ - public initialize ( + public initialize( controlFlowStorageName: string, controlFlowStorageKey: string, leftValue: Expression, - rightValue: Expression, + rightValue: Expression ): void { this.controlFlowStorageName = controlFlowStorageName; this.controlFlowStorageKey = controlFlowStorageKey; @@ -82,17 +77,14 @@ export class ExpressionWithOperatorControlFlowStorageCallNode extends AbstractCu /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.expressionStatementNode( NodeFactory.callExpressionNode( NodeFactory.memberExpressionNode( NodeFactory.identifierNode(this.controlFlowStorageName), NodeFactory.identifierNode(this.controlFlowStorageKey) ), - [ - this.leftValue, - this.rightValue - ] + [this.leftValue, this.rightValue] ) ); diff --git a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/StringLiteralControlFlowStorageCallNode.ts b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/StringLiteralControlFlowStorageCallNode.ts index cb18049b..a597e016 100644 --- a/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/StringLiteralControlFlowStorageCallNode.ts +++ b/src/custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/StringLiteralControlFlowStorageCallNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -34,29 +34,21 @@ export class StringLiteralControlFlowStorageCallNode extends AbstractCustomNode * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {string} controlFlowStorageName * @param {string} controlFlowStorageKey */ - public initialize ( - controlFlowStorageName: string, - controlFlowStorageKey: string - ): void { + public initialize(controlFlowStorageName: string, controlFlowStorageKey: string): void { this.controlFlowStorageName = controlFlowStorageName; this.controlFlowStorageKey = controlFlowStorageKey; } @@ -64,7 +56,7 @@ export class StringLiteralControlFlowStorageCallNode extends AbstractCustomNode /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.expressionStatementNode( NodeFactory.memberExpressionNode( NodeFactory.identifierNode(this.controlFlowStorageName), diff --git a/src/custom-nodes/dead-code-injection-nodes/BlockStatementDeadCodeInjectionNode.ts b/src/custom-nodes/dead-code-injection-nodes/BlockStatementDeadCodeInjectionNode.ts index 9d66be34..c711d152 100644 --- a/src/custom-nodes/dead-code-injection-nodes/BlockStatementDeadCodeInjectionNode.ts +++ b/src/custom-nodes/dead-code-injection-nodes/BlockStatementDeadCodeInjectionNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import type { BinaryOperator, BlockStatement } from 'estree'; @@ -32,29 +32,21 @@ export class BlockStatementDeadCodeInjectionNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {BlockStatement} blockStatementNode * @param {BlockStatement} deadCodeInjectionRootAstHostNode */ - public initialize ( - blockStatementNode: BlockStatement, - deadCodeInjectionRootAstHostNode: BlockStatement - ): void { + public initialize(blockStatementNode: BlockStatement, deadCodeInjectionRootAstHostNode: BlockStatement): void { this.blockStatementNode = blockStatementNode; this.deadCodeInjectionRootAstHostNode = deadCodeInjectionRootAstHostNode; } @@ -64,14 +56,14 @@ export class BlockStatementDeadCodeInjectionNode extends AbstractCustomNode { * * @returns {TStatement[]} */ - public override getNode (): TStatement[] { + public override getNode(): TStatement[] { return this.getNodeStructure(); } /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const random1: boolean = this.randomGenerator.getMathRandom() > 0.5; const random2: boolean = this.randomGenerator.getMathRandom() > 0.5; @@ -79,9 +71,10 @@ export class BlockStatementDeadCodeInjectionNode extends AbstractCustomNode { const leftString: string = this.randomGenerator.getRandomString(5); const rightString: string = random2 ? leftString : this.randomGenerator.getRandomString(5); - const [consequent, alternate]: [BlockStatement, BlockStatement] = random1 === random2 - ? [this.blockStatementNode, this.deadCodeInjectionRootAstHostNode] - : [this.deadCodeInjectionRootAstHostNode, this.blockStatementNode]; + const [consequent, alternate]: [BlockStatement, BlockStatement] = + random1 === random2 + ? [this.blockStatementNode, this.deadCodeInjectionRootAstHostNode] + : [this.deadCodeInjectionRootAstHostNode, this.blockStatementNode]; const structure: BlockStatement = NodeFactory.blockStatementNode([ NodeFactory.ifStatementNode( diff --git a/src/custom-nodes/object-expression-keys-transformer-nodes/ObjectExpressionVariableDeclarationHostNode.ts b/src/custom-nodes/object-expression-keys-transformer-nodes/ObjectExpressionVariableDeclarationHostNode.ts index 2e942615..3bb223c9 100644 --- a/src/custom-nodes/object-expression-keys-transformer-nodes/ObjectExpressionVariableDeclarationHostNode.ts +++ b/src/custom-nodes/object-expression-keys-transformer-nodes/ObjectExpressionVariableDeclarationHostNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -32,26 +32,24 @@ export class ObjectExpressionVariableDeclarationHostNode extends AbstractCustomN * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); } /** * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {(ESTree.Property | ESTree.SpreadElement)[]} properties */ - public initialize (lexicalScopeNode: TNodeWithLexicalScope, properties: (ESTree.Property | ESTree.SpreadElement)[]): void { + public initialize( + lexicalScopeNode: TNodeWithLexicalScope, + properties: (ESTree.Property | ESTree.SpreadElement)[] + ): void { this.lexicalScopeNode = lexicalScopeNode; this.properties = properties; } @@ -59,7 +57,7 @@ export class ObjectExpressionVariableDeclarationHostNode extends AbstractCustomN /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const variableDeclarationName: string = NodeGuards.isProgramNode(this.lexicalScopeNode) ? this.identifierNamesGenerator.generateForGlobalScope() : this.identifierNamesGenerator.generateForLexicalScope(this.lexicalScopeNode); diff --git a/src/custom-nodes/string-array-nodes/AbstractStringArrayCallNode.ts b/src/custom-nodes/string-array-nodes/AbstractStringArrayCallNode.ts index a9583390..296d4f7c 100644 --- a/src/custom-nodes/string-array-nodes/AbstractStringArrayCallNode.ts +++ b/src/custom-nodes/string-array-nodes/AbstractStringArrayCallNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -35,7 +35,10 @@ export abstract class AbstractStringArrayCallNode extends AbstractCustomNode { */ private static readonly stringArrayIndexNodesMap: Map = new Map([ [StringArrayIndexesType.HexadecimalNumber, StringArrayIndexNode.StringArrayHexadecimalNumberIndexNode], - [StringArrayIndexesType.HexadecimalNumericString, StringArrayIndexNode.StringArrayHexadecimalNumericStringIndexNode] + [ + StringArrayIndexesType.HexadecimalNumericString, + StringArrayIndexNode.StringArrayHexadecimalNumericStringIndexNode + ] ]); /** @@ -62,23 +65,18 @@ export abstract class AbstractStringArrayCallNode extends AbstractCustomNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.Factory__IStringArrayIndexNode) - stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, + stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - identifierNamesGeneratorFactory, - customCodeHelperFormatter, - randomGenerator, - options - ); + super(identifierNamesGeneratorFactory, customCodeHelperFormatter, randomGenerator, options); this.stringArrayIndexNodeFactory = stringArrayIndexNodeFactory; this.stringArrayStorage = stringArrayStorage; @@ -89,33 +87,31 @@ export abstract class AbstractStringArrayCallNode extends AbstractCustomNode { * @param {number} index * @returns {Expression} */ - protected getStringArrayIndexNode (index: number): ESTree.Expression { + protected getStringArrayIndexNode(index: number): ESTree.Expression { const isPositive: boolean = index >= 0; const normalizedIndex: number = Math.abs(index); const stringArrayCallsIndexType: TStringArrayIndexesType = this.randomGenerator .getRandomGenerator() .pickone(this.options.stringArrayIndexesType); - const stringArrayIndexNodeName: StringArrayIndexNode | null = AbstractStringArrayCallNode.stringArrayIndexNodesMap.get(stringArrayCallsIndexType) ?? null; + const stringArrayIndexNodeName: StringArrayIndexNode | null = + AbstractStringArrayCallNode.stringArrayIndexNodesMap.get(stringArrayCallsIndexType) ?? null; if (!stringArrayIndexNodeName) { throw new Error('Invalid string array index node name'); } - const stringArrayCallIndexNode: ESTree.Expression = this.stringArrayIndexNodeFactory(stringArrayIndexNodeName) - .getNode(normalizedIndex); + const stringArrayCallIndexNode: ESTree.Expression = + this.stringArrayIndexNodeFactory(stringArrayIndexNodeName).getNode(normalizedIndex); NodeMetadata.set(stringArrayCallIndexNode, { stringArrayCallLiteralNode: true }); const hexadecimalNode: ESTree.Expression = isPositive ? stringArrayCallIndexNode - : NodeFactory.unaryExpressionNode( - '-', - stringArrayCallIndexNode - ); + : NodeFactory.unaryExpressionNode('-', stringArrayCallIndexNode); NodeUtils.parentizeAst(hexadecimalNode); - + return hexadecimalNode; } @@ -123,7 +119,7 @@ export abstract class AbstractStringArrayCallNode extends AbstractCustomNode { * @param {string} decodeKey * @returns {Literal} */ - protected getRc4KeyLiteralNode (decodeKey: string): ESTree.Literal { + protected getRc4KeyLiteralNode(decodeKey: string): ESTree.Literal { const rc4KeyLiteralNode: ESTree.Literal = NodeFactory.literalNode(decodeKey); NodeMetadata.set(rc4KeyLiteralNode, { stringArrayCallLiteralNode: true }); diff --git a/src/custom-nodes/string-array-nodes/StringArrayCallNode.ts b/src/custom-nodes/string-array-nodes/StringArrayCallNode.ts index 8f159ced..d330eecd 100644 --- a/src/custom-nodes/string-array-nodes/StringArrayCallNode.ts +++ b/src/custom-nodes/string-array-nodes/StringArrayCallNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -55,11 +55,11 @@ export class StringArrayCallNode extends AbstractStringArrayCallNode { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.Factory__IStringArrayIndexNode) - stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, + stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @@ -83,7 +83,7 @@ export class StringArrayCallNode extends AbstractStringArrayCallNode { * @param {IStringArrayScopeCallsWrapperData} stringArrayCallsWrapperData * @param {string | null} decodeKey */ - public initialize ( + public initialize( index: number, indexShiftAmount: number, stringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData, @@ -98,7 +98,7 @@ export class StringArrayCallNode extends AbstractStringArrayCallNode { /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const resultIndex: number = this.indexShiftAmount + this.stringArrayCallsWrapperData.index + this.index; const indexNode: ESTree.Expression = this.getStringArrayIndexNode(resultIndex); @@ -109,10 +109,10 @@ export class StringArrayCallNode extends AbstractStringArrayCallNode { // filling call expression arguments with a fake arguments first const callExpressionArgs: ESTree.Expression[] = this.arrayUtils.fillWithRange( !this.stringArrayCallsWrapperData.parameterIndexesData - // root string array calls wrapper - ? AbstractStringArrayCallNode.stringArrayRootCallsWrapperParametersCount - // scope string array calls wrapper - : this.options.stringArrayWrappersParametersMaxCount, + ? // root string array calls wrapper + AbstractStringArrayCallNode.stringArrayRootCallsWrapperParametersCount + : // scope string array calls wrapper + this.options.stringArrayWrappersParametersMaxCount, () => this.getFakeStringArrayIndexNode(resultIndex) ); @@ -152,7 +152,7 @@ export class StringArrayCallNode extends AbstractStringArrayCallNode { * @param {number} actualIndex * @returns {Expression} */ - private getFakeStringArrayIndexNode (actualIndex: number): ESTree.Expression { + private getFakeStringArrayIndexNode(actualIndex: number): ESTree.Expression { return this.getStringArrayIndexNode(this.getFakeStringArrayIndex(actualIndex)); } @@ -160,7 +160,7 @@ export class StringArrayCallNode extends AbstractStringArrayCallNode { * @param {number} actualIndex * @returns {number} */ - private getFakeStringArrayIndex (actualIndex: number): number { + private getFakeStringArrayIndex(actualIndex: number): number { const stringArrayStorageLength: number = this.stringArrayStorage.getLength(); const fakeIndexOffset: number = stringArrayStorageLength / 2; diff --git a/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperFunctionNode.ts b/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperFunctionNode.ts index 10d8cda6..7ebf4e70 100644 --- a/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperFunctionNode.ts +++ b/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperFunctionNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -43,11 +43,11 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.Factory__IStringArrayIndexNode) - stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, + stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @@ -69,9 +69,9 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra * @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData * @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData */ - public initialize ( + public initialize( stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData, - upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData, + upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData ): void { this.stringArrayScopeCallsWrapperData = stringArrayScopeCallsWrapperData; this.upperStringArrayCallsWrapperData = upperStringArrayCallsWrapperData; @@ -80,17 +80,20 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { // identifiers of function expression parameters // as a temporary names use random strings - const stringArrayCallIdentifierNode: ESTree.Identifier = NodeFactory.identifierNode(this.randomGenerator.getRandomString(6)); - const decodeKeyIdentifierNode: ESTree.Identifier = NodeFactory.identifierNode(this.randomGenerator.getRandomString(6)); + const stringArrayCallIdentifierNode: ESTree.Identifier = NodeFactory.identifierNode( + this.randomGenerator.getRandomString(6) + ); + const decodeKeyIdentifierNode: ESTree.Identifier = NodeFactory.identifierNode( + this.randomGenerator.getRandomString(6) + ); const stringArrayCallNode: ESTree.Expression = this.getUpperStringArrayCallNode( stringArrayCallIdentifierNode, this.getStringArrayIndexNode( - this.stringArrayScopeCallsWrapperData.index - - this.upperStringArrayCallsWrapperData.index + this.stringArrayScopeCallsWrapperData.index - this.upperStringArrayCallsWrapperData.index ) ); @@ -98,10 +101,10 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra // filling all parameters with a fake parameters first const parameters: ESTree.Identifier[] = this.arrayUtils.fillWithRange( !this.stringArrayScopeCallsWrapperData.parameterIndexesData - // root string array calls wrapper - ? AbstractStringArrayCallNode.stringArrayRootCallsWrapperParametersCount - // scope string array calls wrapper - : this.options.stringArrayWrappersParametersMaxCount, + ? // root string array calls wrapper + AbstractStringArrayCallNode.stringArrayRootCallsWrapperParametersCount + : // scope string array calls wrapper + this.options.stringArrayWrappersParametersMaxCount, () => this.getFakeParameterNode() ); parameters.splice( @@ -119,14 +122,12 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra // filling all call expression arguments with a fake string array calls const callExpressionArgs: ESTree.Expression[] = this.arrayUtils.fillWithRange( !this.upperStringArrayCallsWrapperData.parameterIndexesData - // root string array calls wrapper - ? AbstractStringArrayCallNode.stringArrayRootCallsWrapperParametersCount - // scope string array calls wrapper - : this.options.stringArrayWrappersParametersMaxCount, - (index: number) => this.getUpperStringArrayCallNode( - parameters[index], - this.getFakeUpperStringArrayIndexNode() - ) + ? // root string array calls wrapper + AbstractStringArrayCallNode.stringArrayRootCallsWrapperParametersCount + : // scope string array calls wrapper + this.options.stringArrayWrappersParametersMaxCount, + (index: number) => + this.getUpperStringArrayCallNode(parameters[index], this.getFakeUpperStringArrayIndexNode()) ); callExpressionArgs.splice( @@ -141,7 +142,7 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra ); // stage 3: function declaration node - const functionDeclarationNode: ESTree.FunctionDeclaration = NodeFactory.functionDeclarationNode( + const functionDeclarationNode: ESTree.FunctionDeclaration = NodeFactory.functionDeclarationNode( this.stringArrayScopeCallsWrapperData.name, parameters, NodeFactory.blockStatementNode([ @@ -172,28 +173,24 @@ export class StringArrayScopeCallsWrapperFunctionNode extends AbstractStringArra * @param {Expression} indexShiftNode * @returns {Expression} */ - private getUpperStringArrayCallNode ( + private getUpperStringArrayCallNode( indexParameterIdentifierNode: ESTree.Identifier, indexShiftNode: ESTree.Expression ): ESTree.Expression { - return NodeFactory.binaryExpressionNode( - '-', - indexParameterIdentifierNode, - indexShiftNode - ); + return NodeFactory.binaryExpressionNode('-', indexParameterIdentifierNode, indexShiftNode); } /** * @returns {Identifier} */ - private getFakeParameterNode (): ESTree.Identifier { + private getFakeParameterNode(): ESTree.Identifier { return NodeFactory.identifierNode(this.randomGenerator.getRandomString(6)); } /** * @returns {Expression} */ - private getFakeUpperStringArrayIndexNode (): ESTree.Expression { + private getFakeUpperStringArrayIndexNode(): ESTree.Expression { return this.getStringArrayIndexNode(this.randomGenerator.getRandomInteger(0, 500)); } } diff --git a/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperVariableNode.ts b/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperVariableNode.ts index c9206c83..2a19f05b 100644 --- a/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperVariableNode.ts +++ b/src/custom-nodes/string-array-nodes/StringArrayScopeCallsWrapperVariableNode.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import { TIdentifierNamesGeneratorFactory } from '../../types/container/generators/TIdentifierNamesGeneratorFactory'; @@ -32,7 +32,6 @@ export class StringArrayScopeCallsWrapperVariableNode extends AbstractStringArra @initializable() private stringArrayScopeCallsWrapperData!: IStringArrayScopeCallsWrapperData; - /** * @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory * @param {TStringArrayIndexNodeFactory} stringArrayIndexNodeFactory @@ -42,16 +41,16 @@ export class StringArrayScopeCallsWrapperVariableNode extends AbstractStringArra * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.Factory__IStringArrayIndexNode) - stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, + stringArrayIndexNodeFactory: TStringArrayIndexNodeFactory, @inject(ServiceIdentifiers.ICustomCodeHelperFormatter) customCodeHelperFormatter: ICustomCodeHelperFormatter, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, - @inject(ServiceIdentifiers.IOptions) options: IOptions, + @inject(ServiceIdentifiers.IOptions) options: IOptions ) { super( identifierNamesGeneratorFactory, @@ -68,7 +67,7 @@ export class StringArrayScopeCallsWrapperVariableNode extends AbstractStringArra * @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData * @param {IStringArrayScopeCallsWrapperData} stringArrayCallsWrapperData */ - public initialize ( + public initialize( stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData, stringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData ): void { @@ -79,7 +78,7 @@ export class StringArrayScopeCallsWrapperVariableNode extends AbstractStringArra /** * @returns {TStatement[]} */ - protected getNodeStructure (): TStatement[] { + protected getNodeStructure(): TStatement[] { const structure: TStatement = NodeFactory.variableDeclarationNode( [ NodeFactory.variableDeclaratorNode( @@ -87,7 +86,7 @@ export class StringArrayScopeCallsWrapperVariableNode extends AbstractStringArra NodeFactory.identifierNode(this.stringArrayCallsWrapperData.name) ) ], - 'const', + 'const' ); NodeUtils.parentizeAst(structure); diff --git a/src/custom-nodes/string-array-nodes/string-array-index-nodes/AbstractStringArrayIndexNode.ts b/src/custom-nodes/string-array-nodes/string-array-index-nodes/AbstractStringArrayIndexNode.ts index 29734769..00e8366d 100644 --- a/src/custom-nodes/string-array-nodes/string-array-index-nodes/AbstractStringArrayIndexNode.ts +++ b/src/custom-nodes/string-array-nodes/string-array-index-nodes/AbstractStringArrayIndexNode.ts @@ -24,7 +24,7 @@ export abstract class AbstractStringArrayIndexNode implements IStringArrayIndexN * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -36,5 +36,5 @@ export abstract class AbstractStringArrayIndexNode implements IStringArrayIndexN * @param {number} index * @returns {Expression} */ - public abstract getNode (index: number): ESTree.Expression; + public abstract getNode(index: number): ESTree.Expression; } diff --git a/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumberIndexNode.ts b/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumberIndexNode.ts index 3889659e..ed3fb3e3 100644 --- a/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumberIndexNode.ts +++ b/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumberIndexNode.ts @@ -17,7 +17,7 @@ export class StringArrayHexadecimalNumberIndexNode extends AbstractStringArrayIn * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -28,7 +28,7 @@ export class StringArrayHexadecimalNumberIndexNode extends AbstractStringArrayIn * @param {number} index * @returns {Expression} */ - public getNode (index: number): ESTree.Expression { + public getNode(index: number): ESTree.Expression { const hexadecimalIndex: string = NumberUtils.toHex(index); return NodeFactory.literalNode(index, hexadecimalIndex); diff --git a/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumericStringIndexNode.ts b/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumericStringIndexNode.ts index c014e161..afaa3d2e 100644 --- a/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumericStringIndexNode.ts +++ b/src/custom-nodes/string-array-nodes/string-array-index-nodes/StringArrayHexadecimalNumericStringIndexNode.ts @@ -17,7 +17,7 @@ export class StringArrayHexadecimalNumericStringIndexNode extends AbstractString * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -28,7 +28,7 @@ export class StringArrayHexadecimalNumericStringIndexNode extends AbstractString * @param {number} index * @returns {Expression} */ - public getNode (index: number): ESTree.Expression { + public getNode(index: number): ESTree.Expression { const hexadecimalIndex: string = NumberUtils.toHex(index); return NodeFactory.literalNode(hexadecimalIndex); diff --git a/src/declarations/ESTree.d.ts b/src/declarations/ESTree.d.ts index 2b4bed81..f598ecd8 100644 --- a/src/declarations/ESTree.d.ts +++ b/src/declarations/ESTree.d.ts @@ -18,12 +18,12 @@ declare module 'estree' { } export interface IdentifierNodeMetadata extends BaseNodeMetadata { - propertyKeyToRenameNode?: boolean + propertyKeyToRenameNode?: boolean; } export interface LiteralNodeMetadata extends BaseNodeMetadata { stringArrayCallLiteralNode?: boolean; - propertyKeyToRenameNode?: boolean + propertyKeyToRenameNode?: boolean; } /** @@ -57,17 +57,17 @@ declare module 'estree' { } interface BigIntLiteral extends BaseNode { - metadata?: LiteralNodeMetadata; + 'metadata'?: LiteralNodeMetadata; 'x-verbatim-property'?: escodegen.XVerbatimProperty; } interface RegExpLiteral extends BaseNode { - metadata?: LiteralNodeMetadata; + 'metadata'?: LiteralNodeMetadata; 'x-verbatim-property'?: escodegen.XVerbatimProperty; } interface SimpleLiteral extends BaseNode { - metadata?: LiteralNodeMetadata; + 'metadata'?: LiteralNodeMetadata; 'x-verbatim-property'?: escodegen.XVerbatimProperty; } } diff --git a/src/declarations/acorn-import-meta.d.ts b/src/declarations/acorn-import-meta.d.ts index dcdf0fc6..5e2d804e 100644 --- a/src/declarations/acorn-import-meta.d.ts +++ b/src/declarations/acorn-import-meta.d.ts @@ -1,7 +1,7 @@ declare module 'acorn-import-meta' { import * as acorn from 'acorn'; - function acornImportMeta (BaseParser: typeof acorn.Parser): typeof acorn.Parser; + function acornImportMeta(BaseParser: typeof acorn.Parser): typeof acorn.Parser; export = acornImportMeta; } diff --git a/src/declarations/environment.d.ts b/src/declarations/environment.d.ts index 15f603b8..1e0025a5 100644 --- a/src/declarations/environment.d.ts +++ b/src/declarations/environment.d.ts @@ -5,4 +5,4 @@ declare namespace NodeJS { VERSION?: string; BUILD_TIMESTAMP?: string; } -} \ No newline at end of file +} diff --git a/src/declarations/escodegen.d.ts b/src/declarations/escodegen.d.ts index 300b4590..cc98a28b 100644 --- a/src/declarations/escodegen.d.ts +++ b/src/declarations/escodegen.d.ts @@ -20,5 +20,5 @@ declare module '@javascript-obfuscator/escodegen' { * @param options * @returns IGeneratorOutput */ - export function generate (ast: ESTree.Node, options?: escodegen.GenerateOptions): IGeneratorOutput; + export function generate(ast: ESTree.Node, options?: escodegen.GenerateOptions): IGeneratorOutput; } diff --git a/src/decorators/Initializable.ts b/src/decorators/Initializable.ts index a968a5aa..f445127a 100644 --- a/src/decorators/Initializable.ts +++ b/src/decorators/Initializable.ts @@ -15,14 +15,16 @@ const initializeMethodName: 'initialize' = 'initialize'; * @param {string} initializeMethodName * @returns {(target: IInitializable, propertyKey: (string | symbol)) => any} */ -export function initializable (): (target: IInitializable, propertyKey: string | symbol) => any { +export function initializable(): (target: IInitializable, propertyKey: string | symbol) => any { return (target: IInitializable, propertyKey: string | symbol): PropertyDescriptor => { const initializeMethod: Function = target[initializeMethodName]; const isInvalidInitializeMethod = !initializeMethod || typeof initializeMethod !== 'function'; if (isInvalidInitializeMethod) { - throw new Error(`\`${initializeMethodName}\` method with initialization logic not ` + - `found. \`@${decoratorName}\` decorator requires \`${initializeMethodName}\` method`); + throw new Error( + `\`${initializeMethodName}\` method with initialization logic not ` + + `found. \`@${decoratorName}\` decorator requires \`${initializeMethodName}\` method` + ); } /** @@ -50,7 +52,7 @@ export function initializable (): (target: IInitializable, propertyKey: string | * @param metadataValue * @param {IInitializable} target */ -function initializeTargetMetadata (metadataKey: string, metadataValue: any, target: IInitializable): void { +function initializeTargetMetadata(metadataKey: string, metadataValue: any, target: IInitializable): void { const hasInitializedMetadata: boolean = Reflect.hasMetadata(metadataKey, target); if (!hasInitializedMetadata) { @@ -63,19 +65,21 @@ function initializeTargetMetadata (metadataKey: string, metadataValue: any, targ * * @param {IInitializable} target */ -function wrapTargetMethodsInInitializedCheck (target: IInitializable): void { +function wrapTargetMethodsInInitializedCheck(target: IInitializable): void { const ownPropertyNames: string[] = Object.getOwnPropertyNames(target); const prohibitedPropertyNames: Set = new Set([initializeMethodName, constructorMethodName]); ownPropertyNames.forEach((propertyName: string) => { - const initializablePropertiesSet: Set = Reflect - .getMetadata(initializablePropertiesSetMetadataKey, target); - const wrappedMethodsSet: Set = Reflect - .getMetadata(wrappedMethodsSetMetadataKey, target); + const initializablePropertiesSet: Set = Reflect.getMetadata( + initializablePropertiesSetMetadataKey, + target + ); + const wrappedMethodsSet: Set = Reflect.getMetadata(wrappedMethodsSetMetadataKey, target); - const isProhibitedPropertyName: boolean = prohibitedPropertyNames.has(propertyName) - || initializablePropertiesSet.has(propertyName) - || wrappedMethodsSet.has(propertyName); + const isProhibitedPropertyName: boolean = + prohibitedPropertyNames.has(propertyName) || + initializablePropertiesSet.has(propertyName) || + wrappedMethodsSet.has(propertyName); if (isProhibitedPropertyName) { return; @@ -87,13 +91,13 @@ function wrapTargetMethodsInInitializedCheck (target: IInitializable): void { return; } - const methodDescriptor: PropertyDescriptor = Object - .getOwnPropertyDescriptor(target, propertyName) ?? defaultDescriptor; + const methodDescriptor: PropertyDescriptor = + Object.getOwnPropertyDescriptor(target, propertyName) ?? defaultDescriptor; const originalMethod: Function = methodDescriptor.value; Object.defineProperty(target, propertyName, { ...methodDescriptor, - value (): void { + value(): void { if (!Reflect.getMetadata(initializedTargetMetadataKey, this)) { throw new Error(`Class should be initialized with \`${initializeMethodName}()\` method`); } @@ -112,12 +116,9 @@ function wrapTargetMethodsInInitializedCheck (target: IInitializable): void { * @param {IInitializable} target * @param {string | symbol} propertyKey */ -function wrapInitializeMethodInInitializeCheck ( - target: IInitializable, - propertyKey: string | symbol -): void { - const methodDescriptor: PropertyDescriptor = Object - .getOwnPropertyDescriptor(target, initializeMethodName) ?? defaultDescriptor; +function wrapInitializeMethodInInitializeCheck(target: IInitializable, propertyKey: string | symbol): void { + const methodDescriptor: PropertyDescriptor = + Object.getOwnPropertyDescriptor(target, initializeMethodName) ?? defaultDescriptor; const originalMethod: Function = methodDescriptor.value; Object.defineProperty(target, initializeMethodName, { @@ -131,7 +132,8 @@ function wrapInitializeMethodInInitializeCheck ( const result: typeof originalMethod = originalMethod.apply(this, arguments); - if (this[propertyKey]) {} + if (this[propertyKey]) { + } return result; } @@ -145,15 +147,17 @@ function wrapInitializeMethodInInitializeCheck ( * @param {string | symbol} propertyKey * @returns {PropertyDescriptor} */ -function wrapInitializableProperty (target: IInitializable, propertyKey: string | symbol): PropertyDescriptor { - const initializablePropertiesSet: Set = Reflect - .getMetadata(initializablePropertiesSetMetadataKey, target); +function wrapInitializableProperty(target: IInitializable, propertyKey: string | symbol): PropertyDescriptor { + const initializablePropertiesSet: Set = Reflect.getMetadata( + initializablePropertiesSetMetadataKey, + target + ); initializablePropertiesSet.add(propertyKey); const initializablePropertyMetadataKey: string = `_${propertyKey.toString()}`; - const propertyDescriptor: PropertyDescriptor = Object - .getOwnPropertyDescriptor(target, initializablePropertyMetadataKey) ?? defaultDescriptor; + const propertyDescriptor: PropertyDescriptor = + Object.getOwnPropertyDescriptor(target, initializablePropertyMetadataKey) ?? defaultDescriptor; Object.defineProperty(target, propertyKey, { ...propertyDescriptor, diff --git a/src/enums/ObfuscationTarget.ts b/src/enums/ObfuscationTarget.ts index 7fb67763..55235dbf 100644 --- a/src/enums/ObfuscationTarget.ts +++ b/src/enums/ObfuscationTarget.ts @@ -9,5 +9,5 @@ export const ObfuscationTarget: Readonly<{ Browser: 'browser', BrowserNoEval: 'browser-no-eval', Node: 'node', - ServiceWorker: 'service-worker', + ServiceWorker: 'service-worker' }); diff --git a/src/enums/analyzers/calls-graph-analyzer/CalleeDataExtractor.ts b/src/enums/analyzers/calls-graph-analyzer/CalleeDataExtractor.ts index 2652e419..df3a3a74 100644 --- a/src/enums/analyzers/calls-graph-analyzer/CalleeDataExtractor.ts +++ b/src/enums/analyzers/calls-graph-analyzer/CalleeDataExtractor.ts @@ -1,5 +1,5 @@ export enum CalleeDataExtractor { FunctionDeclarationCalleeDataExtractor = 'FunctionDeclarationCalleeDataExtractor', FunctionExpressionCalleeDataExtractor = 'FunctionExpressionCalleeDataExtractor', - ObjectExpressionCalleeDataExtractor = 'ObjectExpressionCalleeDataExtractor', + ObjectExpressionCalleeDataExtractor = 'ObjectExpressionCalleeDataExtractor' } diff --git a/src/enums/code-transformers/CodeTransformationStage.ts b/src/enums/code-transformers/CodeTransformationStage.ts index 93261246..aea3a4d9 100644 --- a/src/enums/code-transformers/CodeTransformationStage.ts +++ b/src/enums/code-transformers/CodeTransformationStage.ts @@ -1,4 +1,4 @@ export enum CodeTransformationStage { PreparingTransformers = 'PreparingTransformers', - FinalizingTransformers = 'FinalizingTransformers', + FinalizingTransformers = 'FinalizingTransformers' } diff --git a/src/enums/custom-nodes/ObjectExpressionKeysTransformerCustomNode.ts b/src/enums/custom-nodes/ObjectExpressionKeysTransformerCustomNode.ts index 98daa538..40968aed 100644 --- a/src/enums/custom-nodes/ObjectExpressionKeysTransformerCustomNode.ts +++ b/src/enums/custom-nodes/ObjectExpressionKeysTransformerCustomNode.ts @@ -1,4 +1,3 @@ export enum ObjectExpressionKeysTransformerCustomNode { - ObjectExpressionVariableDeclarationHostNode = - 'ObjectExpressionVariableDeclarationHostNode' + ObjectExpressionVariableDeclarationHostNode = 'ObjectExpressionVariableDeclarationHostNode' } diff --git a/src/enums/node-transformers/string-array-transformers/StringArrayWrappersType.ts b/src/enums/node-transformers/string-array-transformers/StringArrayWrappersType.ts index 8e49b589..67c0542f 100644 --- a/src/enums/node-transformers/string-array-transformers/StringArrayWrappersType.ts +++ b/src/enums/node-transformers/string-array-transformers/StringArrayWrappersType.ts @@ -5,5 +5,5 @@ export const StringArrayWrappersType: Readonly<{ Function: 'function'; }> = Utils.makeEnum({ Variable: 'variable', - Function: 'function', + Function: 'function' }); diff --git a/src/generators/identifier-names-generators/AbstractIdentifierNamesGenerator.ts b/src/generators/identifier-names-generators/AbstractIdentifierNamesGenerator.ts index f9ab69fe..9779d6af 100644 --- a/src/generators/identifier-names-generators/AbstractIdentifierNamesGenerator.ts +++ b/src/generators/identifier-names-generators/AbstractIdentifierNamesGenerator.ts @@ -35,7 +35,7 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -48,7 +48,7 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam * @param {number} nameLength * @returns {string} */ - public generate (lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string { + public generate(lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string { return NodeGuards.isProgramNode(lexicalScopeNode) ? this.generateForGlobalScope() : this.generateForLexicalScope(lexicalScopeNode); @@ -57,7 +57,7 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam /** * @param {string} name */ - public preserveName (name: string): void { + public preserveName(name: string): void { this.preservedNamesSet.add(name); } @@ -65,7 +65,7 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam * @param {string} name * @param {TNodeWithLexicalScope} lexicalScopeNode */ - public preserveNameForLexicalScope (name: string, lexicalScopeNode: TNodeWithLexicalScope): void { + public preserveNameForLexicalScope(name: string, lexicalScopeNode: TNodeWithLexicalScope): void { const preservedNamesForLexicalScopeSet: Set = this.lexicalScopesPreservedNamesMap.get(lexicalScopeNode) ?? new Set(); @@ -78,9 +78,8 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam * @param {string} name * @returns {boolean} */ - public isValidIdentifierName (name: string): boolean { - return !this.isReservedName(name) - && !this.preservedNamesSet.has(name); + public isValidIdentifierName(name: string): boolean { + return !this.isReservedName(name) && !this.preservedNamesSet.has(name); } /** @@ -88,7 +87,7 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam * @param {TNodeWithLexicalScope[]} lexicalScopeNodes * @returns {boolean} */ - public isValidIdentifierNameInLexicalScopes (name: string, lexicalScopeNodes: TNodeWithLexicalScope[]): boolean { + public isValidIdentifierNameInLexicalScopes(name: string, lexicalScopeNodes: TNodeWithLexicalScope[]): boolean { if (!this.isValidIdentifierName(name)) { return false; } @@ -113,38 +112,37 @@ export abstract class AbstractIdentifierNamesGenerator implements IIdentifierNam * @param {string} name * @returns {boolean} */ - private isReservedName (name: string): boolean { + private isReservedName(name: string): boolean { return this.options.reservedNames.length - ? this.options.reservedNames.some((reservedName: string) => - new RegExp(reservedName, 'g').exec(name) !== null - ) + ? this.options.reservedNames.some( + (reservedName: string) => new RegExp(reservedName, 'g').exec(name) !== null + ) : false; - } /** * @param {number} nameLength * @returns {string} */ - public abstract generateForGlobalScope (nameLength?: number): string; + public abstract generateForGlobalScope(nameLength?: number): string; /** * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {number} nameLength * @returns {string} */ - public abstract generateForLexicalScope (lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string; + public abstract generateForLexicalScope(lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string; /** * @param {string} label * @param {number} nameLength * @returns {string} */ - public abstract generateForLabel (label: string, nameLength?: number): string; + public abstract generateForLabel(label: string, nameLength?: number): string; /** * @param {number} nameLength * @returns {string} */ - public abstract generateNext (nameLength?: number): string; + public abstract generateNext(nameLength?: number): string; } diff --git a/src/generators/identifier-names-generators/DictionaryIdentifierNamesGenerator.ts b/src/generators/identifier-names-generators/DictionaryIdentifierNamesGenerator.ts index 448a251b..da6195a5 100644 --- a/src/generators/identifier-names-generators/DictionaryIdentifierNamesGenerator.ts +++ b/src/generators/identifier-names-generators/DictionaryIdentifierNamesGenerator.ts @@ -20,7 +20,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @type {Set} */ private identifierNamesSet: Set; - + /** * @type {IterableIterator} */ @@ -31,10 +31,10 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {IOptions} options * @param {IArrayUtils} arrayUtils */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, - @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, + @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils ) { super(randomGenerator, options); @@ -47,7 +47,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {string} identifierName * @returns {string | null} */ - private static incrementIdentifierName (identifierName: string): string | null { + private static incrementIdentifierName(identifierName: string): string | null { let newIdentifierName: string = ''; let isSuccess: boolean = false; @@ -69,7 +69,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG return null; } - public generateNext (): string { + public generateNext(): string { const identifierName: string = this.generateNewDictionaryName(); this.preserveName(identifierName); @@ -80,10 +80,8 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG /** * @returns {string} */ - public generateForGlobalScope (): string { - const prefix: string = this.options.identifiersPrefix ? - `${this.options.identifiersPrefix}` - : ''; + public generateForGlobalScope(): string { + const prefix: string = this.options.identifiersPrefix ? `${this.options.identifiersPrefix}` : ''; const identifierName: string = this.generateNewDictionaryName((newIdentifierName: string) => { const identifierNameWithPrefix: string = `${prefix}${newIdentifierName}`; @@ -101,7 +99,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {TNodeWithLexicalScope} lexicalScopeNode * @returns {string} */ - public generateForLexicalScope (lexicalScopeNode: TNodeWithLexicalScope): string { + public generateForLexicalScope(lexicalScopeNode: TNodeWithLexicalScope): string { const lexicalScopes: TNodeWithLexicalScope[] = [ lexicalScopeNode, ...NodeLexicalScopeUtils.getLexicalScopes(lexicalScopeNode) @@ -119,7 +117,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {string} label * @returns {string} */ - public generateForLabel (label: string): string { + public generateForLabel(label: string): string { return this.generateNewDictionaryName(); } @@ -127,7 +125,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {(newIdentifierName: string) => boolean} validationFunction * @returns {string} */ - private generateNewDictionaryName (validationFunction?: (newIdentifierName: string) => boolean): string { + private generateNewDictionaryName(validationFunction?: (newIdentifierName: string) => boolean): string { const generateNewDictionaryName = (): string => { if (!this.identifierNamesSet.size) { throw new Error('Too many identifiers in the code, add more words to identifiers dictionary'); @@ -138,8 +136,8 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG if (!iteratorResult.done) { const identifierName: string = iteratorResult.value; - const isValidIdentifierName = validationFunction?.(identifierName) - ?? this.isValidIdentifierName(identifierName); + const isValidIdentifierName = + validationFunction?.(identifierName) ?? this.isValidIdentifierName(identifierName); if (!isValidIdentifierName) { return generateNewDictionaryName(); @@ -161,7 +159,7 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {string[]} identifierNames * @returns {string[]} */ - private getInitialIdentifierNames (identifierNames: string[]): string[] { + private getInitialIdentifierNames(identifierNames: string[]): string[] { const formattedIdentifierNames: string[] = identifierNames .filter(Boolean) .map((identifierName: string) => identifierName.toLowerCase()); @@ -173,12 +171,12 @@ export class DictionaryIdentifierNamesGenerator extends AbstractIdentifierNamesG * @param {string[]} identifierNames * @returns {string[]} */ - private getIncrementedIdentifierNames (identifierNames: string[]): string[] { + private getIncrementedIdentifierNames(identifierNames: string[]): string[] { const formattedIdentifierNames: string[] = []; for (const identifierName of identifierNames) { - const newIdentifierName: string | null = DictionaryIdentifierNamesGenerator - .incrementIdentifierName(identifierName); + const newIdentifierName: string | null = + DictionaryIdentifierNamesGenerator.incrementIdentifierName(identifierName); if (newIdentifierName) { formattedIdentifierNames.push(newIdentifierName); diff --git a/src/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.ts b/src/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.ts index c5f0e2c1..b4762901 100644 --- a/src/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.ts +++ b/src/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.ts @@ -21,7 +21,7 @@ export class HexadecimalIdentifierNamesGenerator extends AbstractIdentifierNames * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -32,14 +32,14 @@ export class HexadecimalIdentifierNamesGenerator extends AbstractIdentifierNames * @param {number} nameLength * @returns {string} */ - public generateNext (nameLength?: number): string { + public generateNext(nameLength?: number): string { const rangeMinInteger: number = 10000; const rangeMaxInteger: number = 99_999_999; const randomInteger: number = this.randomGenerator.getRandomInteger(rangeMinInteger, rangeMaxInteger); const hexadecimalNumber: string = NumberUtils.toHex(randomInteger); const prefixLength: number = Utils.hexadecimalPrefix.length; - const baseNameLength: number = (nameLength ?? HexadecimalIdentifierNamesGenerator.baseIdentifierNameLength) - + prefixLength; + const baseNameLength: number = + (nameLength ?? HexadecimalIdentifierNamesGenerator.baseIdentifierNameLength) + prefixLength; const baseIdentifierName: string = hexadecimalNumber.slice(0, baseNameLength); const identifierName: string = `_${baseIdentifierName}`; @@ -56,7 +56,7 @@ export class HexadecimalIdentifierNamesGenerator extends AbstractIdentifierNames * @param {number} nameLength * @returns {string} */ - public generateForGlobalScope (nameLength?: number): string { + public generateForGlobalScope(nameLength?: number): string { const identifierName: string = this.generateNext(nameLength); return `${this.options.identifiersPrefix}${identifierName}`.replace('__', '_'); @@ -67,7 +67,7 @@ export class HexadecimalIdentifierNamesGenerator extends AbstractIdentifierNames * @param {number} nameLength * @returns {string} */ - public generateForLexicalScope (lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string { + public generateForLexicalScope(lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string { return this.generateNext(nameLength); } @@ -76,7 +76,7 @@ export class HexadecimalIdentifierNamesGenerator extends AbstractIdentifierNames * @param {number} nameLength * @returns {string} */ - public generateForLabel (label: string, nameLength?: number): string { + public generateForLabel(label: string, nameLength?: number): string { return this.generateNext(nameLength); } } diff --git a/src/generators/identifier-names-generators/MangledIdentifierNamesGenerator.ts b/src/generators/identifier-names-generators/MangledIdentifierNamesGenerator.ts index 0528e895..1c011bda 100644 --- a/src/generators/identifier-names-generators/MangledIdentifierNamesGenerator.ts +++ b/src/generators/identifier-names-generators/MangledIdentifierNamesGenerator.ts @@ -30,9 +30,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene /** * @type {string[]} */ - private static readonly nameSequence: string[] = [ - ...`${numbersString}${alphabetString}${alphabetStringUppercase}` - ]; + private static readonly nameSequence: string[] = [...`${numbersString}${alphabetString}${alphabetStringUppercase}`]; /** * Reserved JS words with length of 2-4 symbols that can be possible generated with this replacer @@ -50,12 +48,12 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene /** * @type {WeakMap} */ - private readonly lastMangledNameForScopeMap: WeakMap = new WeakMap(); + private readonly lastMangledNameForScopeMap: WeakMap = new WeakMap(); /** * @type {WeakMap} */ - private readonly lastMangledNameForLabelMap: Map = new Map(); + private readonly lastMangledNameForLabelMap: Map = new Map(); /** * @type {ISetUtils} @@ -67,10 +65,10 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {IOptions} options * @param {ISetUtils} setUtils */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, - @inject(ServiceIdentifiers.ISetUtils) setUtils: ISetUtils, + @inject(ServiceIdentifiers.ISetUtils) setUtils: ISetUtils ) { super(randomGenerator, options); @@ -84,7 +82,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {number} nameLength * @returns {string} */ - public generateNext (nameLength?: number): string { + public generateNext(nameLength?: number): string { const identifierName: string = this.generateNewMangledName(this.lastMangledName); this.updatePreviousMangledName(identifierName); @@ -97,10 +95,8 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {number} nameLength * @returns {string} */ - public generateForGlobalScope (nameLength?: number): string { - const prefix: string = this.options.identifiersPrefix ? - `${this.options.identifiersPrefix}` - : ''; + public generateForGlobalScope(nameLength?: number): string { + const prefix: string = this.options.identifiersPrefix ? `${this.options.identifiersPrefix}` : ''; const identifierName: string = this.generateNewMangledName( this.lastMangledName, @@ -123,7 +119,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {number} nameLength * @returns {string} */ - public generateForLexicalScope (lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string { + public generateForLexicalScope(lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string { const lexicalScopes: TNodeWithLexicalScope[] = [ lexicalScopeNode, ...NodeLexicalScopeUtils.getLexicalScopes(lexicalScopeNode) @@ -132,8 +128,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene const lastMangledNameForScope: string = this.getLastMangledNameForScopes(lexicalScopes); const identifierName: string = this.generateNewMangledName( lastMangledNameForScope, - (newIdentifierName: string) => - this.isValidIdentifierNameInLexicalScopes(newIdentifierName, lexicalScopes) + (newIdentifierName: string) => this.isValidIdentifierNameInLexicalScopes(newIdentifierName, lexicalScopes) ); this.lastMangledNameForScopeMap.set(lexicalScopeNode, identifierName); @@ -149,7 +144,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {number} nameLength * @returns {string} */ - public generateForLabel (label: string, nameLength?: number): string { + public generateForLabel(label: string, nameLength?: number): string { const lastMangledNameForLabel: string = this.getLastMangledNameForLabel(label); const identifierName: string = this.generateNewMangledName(lastMangledNameForLabel); @@ -165,7 +160,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @returns {boolean} */ // eslint-disable-next-line complexity - public isIncrementedMangledName (nextName: string, prevName: string): boolean { + public isIncrementedMangledName(nextName: string, prevName: string): boolean { if (nextName === prevName) { return false; } @@ -200,22 +195,24 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {string} mangledName * @returns {boolean} */ - public override isValidIdentifierName (mangledName: string): boolean { - return super.isValidIdentifierName(mangledName) - && !MangledIdentifierNamesGenerator.reservedNamesSet.has(mangledName); + public override isValidIdentifierName(mangledName: string): boolean { + return ( + super.isValidIdentifierName(mangledName) && + !MangledIdentifierNamesGenerator.reservedNamesSet.has(mangledName) + ); } /** * @returns {string[]} */ - protected getNameSequence (): string[] { + protected getNameSequence(): string[] { return MangledIdentifierNamesGenerator.nameSequence; } /** * @param {string} name */ - protected updatePreviousMangledName (name: string): void { + protected updatePreviousMangledName(name: string): void { if (!this.isIncrementedMangledName(name, this.lastMangledName)) { return; } @@ -228,7 +225,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {string} label * @param {string} lastMangledNameForLabel */ - protected updatePreviousMangledNameForLabel (name: string, label: string, lastMangledNameForLabel: string): void { + protected updatePreviousMangledNameForLabel(name: string, label: string, lastMangledNameForLabel: string): void { if (!this.isIncrementedMangledName(name, lastMangledNameForLabel)) { return; } @@ -241,7 +238,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {(newIdentifierName: string) => boolean} validationFunction * @returns {string} */ - protected generateNewMangledName ( + protected generateNewMangledName( previousMangledName: string, validationFunction?: (newIdentifierName: string) => boolean ): string { @@ -296,8 +293,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene do { identifierName = generateNewMangledName(identifierName); - isValidIdentifierName = validationFunction?.(identifierName) - ?? this.isValidIdentifierName(identifierName); + isValidIdentifierName = validationFunction?.(identifierName) ?? this.isValidIdentifierName(identifierName); } while (!isValidIdentifierName); return identifierName; @@ -307,7 +303,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {TNodeWithLexicalScope[]} lexicalScopeNodes * @returns {string} */ - private getLastMangledNameForScopes (lexicalScopeNodes: TNodeWithLexicalScope[]): string { + private getLastMangledNameForScopes(lexicalScopeNodes: TNodeWithLexicalScope[]): string { for (const lexicalScope of lexicalScopeNodes) { const lastMangledName: string | null = this.lastMangledNameForScopeMap.get(lexicalScope) ?? null; @@ -325,7 +321,7 @@ export class MangledIdentifierNamesGenerator extends AbstractIdentifierNamesGene * @param {string} label * @returns {string} */ - private getLastMangledNameForLabel (label: string): string { + private getLastMangledNameForLabel(label: string): string { const lastMangledName: string | null = this.lastMangledNameForLabelMap.get(label) ?? null; return lastMangledName ?? MangledIdentifierNamesGenerator.initMangledNameCharacter; diff --git a/src/generators/identifier-names-generators/MangledShuffledIdentifierNamesGenerator.ts b/src/generators/identifier-names-generators/MangledShuffledIdentifierNamesGenerator.ts index aeeaf592..e4705ae3 100644 --- a/src/generators/identifier-names-generators/MangledShuffledIdentifierNamesGenerator.ts +++ b/src/generators/identifier-names-generators/MangledShuffledIdentifierNamesGenerator.ts @@ -30,7 +30,7 @@ export class MangledShuffledIdentifierNamesGenerator extends MangledIdentifierNa * @param {IOptions} options * @param {ISetUtils} setUtils */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @@ -42,7 +42,7 @@ export class MangledShuffledIdentifierNamesGenerator extends MangledIdentifierNa } @postConstruct() - public initialize (): void { + public initialize(): void { this.initializeNameSequence([ ...`${numbersString}`, ...this.arrayUtils.shuffle([...`${alphabetString}${alphabetStringUppercase}`]) @@ -52,7 +52,7 @@ export class MangledShuffledIdentifierNamesGenerator extends MangledIdentifierNa /** * @param {string[]} nameSequence */ - protected initializeNameSequence (nameSequence: string[]): void { + protected initializeNameSequence(nameSequence: string[]): void { if (!this.getNameSequence()) { MangledShuffledIdentifierNamesGenerator.shuffledNameSequence = nameSequence; } @@ -61,7 +61,7 @@ export class MangledShuffledIdentifierNamesGenerator extends MangledIdentifierNa /** * @returns {string[]} */ - protected override getNameSequence (): string[] { + protected override getNameSequence(): string[] { return MangledShuffledIdentifierNamesGenerator.shuffledNameSequence; } } diff --git a/src/interfaces/IInitializable.ts b/src/interfaces/IInitializable.ts index df1746e6..21731f02 100644 --- a/src/interfaces/IInitializable.ts +++ b/src/interfaces/IInitializable.ts @@ -1,8 +1,8 @@ -export interface IInitializable { +export interface IInitializable { [key: string]: any; /** * @param args */ - initialize (...args: T): void; + initialize(...args: T): void; } diff --git a/src/interfaces/IJavaScriptObfsucator.ts b/src/interfaces/IJavaScriptObfsucator.ts index bdb82122..31b3dc9a 100644 --- a/src/interfaces/IJavaScriptObfsucator.ts +++ b/src/interfaces/IJavaScriptObfsucator.ts @@ -5,5 +5,5 @@ export interface IJavaScriptObfuscator { * @param sourceCode * @returns IObfuscationResult */ - obfuscate (sourceCode: string): IObfuscationResult; + obfuscate(sourceCode: string): IObfuscationResult; } diff --git a/src/interfaces/ITransformer.ts b/src/interfaces/ITransformer.ts index 118f5706..b63fb768 100644 --- a/src/interfaces/ITransformer.ts +++ b/src/interfaces/ITransformer.ts @@ -1,4 +1,4 @@ -export interface ITransformer { +export interface ITransformer { /** * @type {TTransformerName[] | undefined} */ diff --git a/src/interfaces/analyzers/IAnalyzer.ts b/src/interfaces/analyzers/IAnalyzer.ts index f718e31c..75ff6b15 100644 --- a/src/interfaces/analyzers/IAnalyzer.ts +++ b/src/interfaces/analyzers/IAnalyzer.ts @@ -1,7 +1,7 @@ -export interface IAnalyzer { +export interface IAnalyzer { /** * @param {TArgs} args * @returns {TData} */ - analyze (...args: TArgs): TData; + analyze(...args: TArgs): TData; } diff --git a/src/interfaces/analyzers/calls-graph-analyzer/ICalleeDataExtractor.ts b/src/interfaces/analyzers/calls-graph-analyzer/ICalleeDataExtractor.ts index 95324ba7..e4097ab0 100644 --- a/src/interfaces/analyzers/calls-graph-analyzer/ICalleeDataExtractor.ts +++ b/src/interfaces/analyzers/calls-graph-analyzer/ICalleeDataExtractor.ts @@ -8,5 +8,5 @@ export interface ICalleeDataExtractor { * @param callee * @returns ICalleeData|null */ - extract (blockScopeBody: ESTree.Node[], callee: ESTree.Node): ICalleeData | null; + extract(blockScopeBody: ESTree.Node[], callee: ESTree.Node): ICalleeData | null; } diff --git a/src/interfaces/analyzers/calls-graph-analyzer/ICallsGraphAnalyzer.ts b/src/interfaces/analyzers/calls-graph-analyzer/ICallsGraphAnalyzer.ts index e768bf18..948d3dec 100644 --- a/src/interfaces/analyzers/calls-graph-analyzer/ICallsGraphAnalyzer.ts +++ b/src/interfaces/analyzers/calls-graph-analyzer/ICallsGraphAnalyzer.ts @@ -8,5 +8,5 @@ export interface ICallsGraphAnalyzer extends IAnalyzer<[ESTree.Program], ICallsG * @param {Program} astTree * @returns {ICallsGraphData[]} */ - analyze (astTree: ESTree.Program): ICallsGraphData[]; + analyze(astTree: ESTree.Program): ICallsGraphData[]; } diff --git a/src/interfaces/analyzers/calls-graph-analyzer/IPrevailingKindOfVariablesAnalyzer.ts b/src/interfaces/analyzers/calls-graph-analyzer/IPrevailingKindOfVariablesAnalyzer.ts index b6cfb1f8..e4c974c6 100644 --- a/src/interfaces/analyzers/calls-graph-analyzer/IPrevailingKindOfVariablesAnalyzer.ts +++ b/src/interfaces/analyzers/calls-graph-analyzer/IPrevailingKindOfVariablesAnalyzer.ts @@ -6,10 +6,10 @@ export interface IPrevailingKindOfVariablesAnalyzer extends IAnalyzer<[ESTree.Pr /** * @param {Program} astTree */ - analyze (astTree: ESTree.Program): void; + analyze(astTree: ESTree.Program): void; /** * @returns {ESTree.VariableDeclaration['kind']} */ - getPrevailingKind (): ESTree.VariableDeclaration['kind']; + getPrevailingKind(): ESTree.VariableDeclaration['kind']; } diff --git a/src/interfaces/analyzers/number-numerical-expression-analyzer/INumberNumericalExpressionAnalyzer.ts b/src/interfaces/analyzers/number-numerical-expression-analyzer/INumberNumericalExpressionAnalyzer.ts index aff82287..948dded3 100644 --- a/src/interfaces/analyzers/number-numerical-expression-analyzer/INumberNumericalExpressionAnalyzer.ts +++ b/src/interfaces/analyzers/number-numerical-expression-analyzer/INumberNumericalExpressionAnalyzer.ts @@ -2,14 +2,12 @@ import { TNumberNumericalExpressionData } from '../../../types/analyzers/number- import { IAnalyzer } from '../IAnalyzer'; -export interface INumberNumericalExpressionAnalyzer extends IAnalyzer<[number, number], TNumberNumericalExpressionData> { +export interface INumberNumericalExpressionAnalyzer + extends IAnalyzer<[number, number], TNumberNumericalExpressionData> { /** * @param {number} number * @param {number} additionalPartsCount * @returns {TNumberNumericalExpressionData} */ - analyze ( - number: number, - additionalPartsCount: number - ): TNumberNumericalExpressionData; + analyze(number: number, additionalPartsCount: number): TNumberNumericalExpressionData; } diff --git a/src/interfaces/analyzers/scope-analyzer/IScopeAnalyzer.ts b/src/interfaces/analyzers/scope-analyzer/IScopeAnalyzer.ts index 6215a56f..a4d80b07 100644 --- a/src/interfaces/analyzers/scope-analyzer/IScopeAnalyzer.ts +++ b/src/interfaces/analyzers/scope-analyzer/IScopeAnalyzer.ts @@ -7,11 +7,11 @@ export interface IScopeAnalyzer extends IAnalyzer<[ESTree.Node], void> { /** * @param {Program} astTree */ - analyze (astTree: ESTree.Node): void; + analyze(astTree: ESTree.Node): void; /** * @param {Node} node * @returns {Scope} */ - acquireScope (node: ESTree.Node): eslintScope.Scope; + acquireScope(node: ESTree.Node): eslintScope.Scope; } diff --git a/src/interfaces/analyzers/string-array-storage-analyzer/IStringArrayStorageAnalyzer.ts b/src/interfaces/analyzers/string-array-storage-analyzer/IStringArrayStorageAnalyzer.ts index b635b355..cabb4725 100644 --- a/src/interfaces/analyzers/string-array-storage-analyzer/IStringArrayStorageAnalyzer.ts +++ b/src/interfaces/analyzers/string-array-storage-analyzer/IStringArrayStorageAnalyzer.ts @@ -9,22 +9,22 @@ export interface IStringArrayStorageAnalyzer extends IAnalyzer<[ESTree.Program], /** * @param {Program} astTree */ - analyze (astTree: ESTree.Program): void; + analyze(astTree: ESTree.Program): void; /** * @param {Literal} literalNode * @param {Node} parentNode */ - analyzeLiteralNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): void; + analyzeLiteralNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): void; /** * @param {TStringLiteralNode} stringLiteralNode */ - addItemDataForLiteralNode (stringLiteralNode: TStringLiteralNode): void; + addItemDataForLiteralNode(stringLiteralNode: TStringLiteralNode): void; /** * @param {Literal} literalNode * @returns {IStringArrayStorageItemData | undefined} */ - getItemDataForLiteralNode (literalNode: ESTree.Literal): IStringArrayStorageItemData | undefined; + getItemDataForLiteralNode(literalNode: ESTree.Literal): IStringArrayStorageItemData | undefined; } diff --git a/src/interfaces/code-transformers/ICodeTransformer.ts b/src/interfaces/code-transformers/ICodeTransformer.ts index 7b399252..276a09a9 100644 --- a/src/interfaces/code-transformers/ICodeTransformer.ts +++ b/src/interfaces/code-transformers/ICodeTransformer.ts @@ -3,11 +3,11 @@ import { ITransformer } from '../ITransformer'; import { CodeTransformer } from '../../enums/code-transformers/CodeTransformer'; import { CodeTransformationStage } from '../../enums/code-transformers/CodeTransformationStage'; -export interface ICodeTransformer extends ITransformer { +export interface ICodeTransformer extends ITransformer { /** * @param {string} code * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - transformCode (code: string, codeTransformationStage: CodeTransformationStage): string; + transformCode(code: string, codeTransformationStage: CodeTransformationStage): string; } diff --git a/src/interfaces/code-transformers/ICodeTransformersRunner.ts b/src/interfaces/code-transformers/ICodeTransformersRunner.ts index 0eab6f39..cde212fc 100644 --- a/src/interfaces/code-transformers/ICodeTransformersRunner.ts +++ b/src/interfaces/code-transformers/ICodeTransformersRunner.ts @@ -8,7 +8,7 @@ export interface ICodeTransformersRunner { * @param {CodeTransformationStage} codeTransformationStage * @returns {string} */ - transform ( + transform( code: string, codeTransformers: CodeTransformer[], codeTransformationStage: CodeTransformationStage diff --git a/src/interfaces/container/IInversifyContainerFacade.ts b/src/interfaces/container/IInversifyContainerFacade.ts index 3252ea83..ccd4bbe7 100644 --- a/src/interfaces/container/IInversifyContainerFacade.ts +++ b/src/interfaces/container/IInversifyContainerFacade.ts @@ -6,20 +6,20 @@ export interface IInversifyContainerFacade { /** * @param serviceIdentifier */ - get (serviceIdentifier: interfaces.ServiceIdentifier): T; + get(serviceIdentifier: interfaces.ServiceIdentifier): T; /** * @param serviceIdentifier * @param named */ - getNamed (serviceIdentifier: interfaces.ServiceIdentifier, named: string | number | symbol): T; + getNamed(serviceIdentifier: interfaces.ServiceIdentifier, named: string | number | symbol): T; /** * @param {string} sourceCode * @param {string} sourceMap * @param {TInputOptions} options */ - load (sourceCode: string, sourceMap: string, options: TInputOptions): void; + load(sourceCode: string, sourceMap: string, options: TInputOptions): void; - unload (): void; + unload(): void; } diff --git a/src/interfaces/custom-code-helpers/ICustomCodeHelper.ts b/src/interfaces/custom-code-helpers/ICustomCodeHelper.ts index e821b68f..148b3953 100644 --- a/src/interfaces/custom-code-helpers/ICustomCodeHelper.ts +++ b/src/interfaces/custom-code-helpers/ICustomCodeHelper.ts @@ -2,11 +2,9 @@ import { TStatement } from '../../types/node/TStatement'; import { IInitializable } from '../IInitializable'; -export interface ICustomCodeHelper < - TInitialData extends unknown[] = unknown[] -> extends IInitializable { +export interface ICustomCodeHelper extends IInitializable { /** * @returns ESTree.Node[] */ - getNode (): TStatement[]; + getNode(): TStatement[]; } diff --git a/src/interfaces/custom-code-helpers/ICustomCodeHelperFormatter.ts b/src/interfaces/custom-code-helpers/ICustomCodeHelperFormatter.ts index e6266ed8..d77a91b0 100644 --- a/src/interfaces/custom-code-helpers/ICustomCodeHelperFormatter.ts +++ b/src/interfaces/custom-code-helpers/ICustomCodeHelperFormatter.ts @@ -7,14 +7,11 @@ export interface ICustomCodeHelperFormatter { * @param {TMapping} mapping * @returns {string} */ - formatTemplate ( - template: string, - mapping: TMapping - ): string; + formatTemplate(template: string, mapping: TMapping): string; /** * @param {TStatement[]} structure * @returns {TStatement[]} */ - formatStructure (structure: TStatement[]): TStatement[]; + formatStructure(structure: TStatement[]): TStatement[]; } diff --git a/src/interfaces/custom-code-helpers/ICustomCodeHelperGroup.ts b/src/interfaces/custom-code-helpers/ICustomCodeHelperGroup.ts index 07df4266..cdae125d 100644 --- a/src/interfaces/custom-code-helpers/ICustomCodeHelperGroup.ts +++ b/src/interfaces/custom-code-helpers/ICustomCodeHelperGroup.ts @@ -9,7 +9,7 @@ export interface ICustomCodeHelperGroup extends IInitializable, TCustomCodeHelpe /** * @type {Map } */ - getCustomCodeHelpers (): Map ; + getCustomCodeHelpers(): Map; - initialize (): void; + initialize(): void; } diff --git a/src/interfaces/custom-code-helpers/ICustomCodeHelperObfuscator.ts b/src/interfaces/custom-code-helpers/ICustomCodeHelperObfuscator.ts index 0d9abdfa..9f209fd6 100644 --- a/src/interfaces/custom-code-helpers/ICustomCodeHelperObfuscator.ts +++ b/src/interfaces/custom-code-helpers/ICustomCodeHelperObfuscator.ts @@ -6,5 +6,5 @@ export interface ICustomCodeHelperObfuscator { * @param {TInputOptions} additionalOptions * @returns {string} */ - obfuscateTemplate (template: string, additionalOptions?: TInputOptions): string; + obfuscateTemplate(template: string, additionalOptions?: TInputOptions): string; } diff --git a/src/interfaces/custom-nodes/ICustomNode.ts b/src/interfaces/custom-nodes/ICustomNode.ts index 359db4be..1869485a 100644 --- a/src/interfaces/custom-nodes/ICustomNode.ts +++ b/src/interfaces/custom-nodes/ICustomNode.ts @@ -2,11 +2,9 @@ import { TStatement } from '../../types/node/TStatement'; import { IInitializable } from '../IInitializable'; -export interface ICustomNode < - TInitialData extends unknown[] = unknown[] -> extends IInitializable { +export interface ICustomNode extends IInitializable { /** * @returns ESTree.Node[] */ - getNode (): TStatement[]; + getNode(): TStatement[]; } diff --git a/src/interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator.ts b/src/interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator.ts index f0d2f897..a5164d74 100644 --- a/src/interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator.ts +++ b/src/interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator.ts @@ -6,55 +6,55 @@ export interface IIdentifierNamesGenerator { * @param {number} nameLength * @returns {string} */ - generate (lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string; + generate(lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string; /** * @param {number} nameLength * @returns {string} */ - generateForGlobalScope (nameLength?: number): string; + generateForGlobalScope(nameLength?: number): string; /** * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {number} nameLength * @returns {string} */ - generateForLexicalScope (lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string; + generateForLexicalScope(lexicalScopeNode: TNodeWithLexicalScope, nameLength?: number): string; /** * @param {string} label * @param {number} nameLength * @returns {string} */ - generateForLabel (label: string, nameLength?: number): string; + generateForLabel(label: string, nameLength?: number): string; /** * @param {number} nameLength * @returns {string} */ - generateNext (nameLength?: number): string; + generateNext(nameLength?: number): string; /** * @param {string} identifierName * @returns {boolean} */ - isValidIdentifierName (identifierName: string): boolean; + isValidIdentifierName(identifierName: string): boolean; /** * @param {string} identifierName * @param {TNodeWithLexicalScope[]} lexicalScopeNodes * @returns {boolean} */ - isValidIdentifierNameInLexicalScopes (identifierName: string, lexicalScopeNodes: TNodeWithLexicalScope[]): boolean; + isValidIdentifierNameInLexicalScopes(identifierName: string, lexicalScopeNodes: TNodeWithLexicalScope[]): boolean; /** * @param {string} identifierName */ - preserveName (identifierName: string): void; + preserveName(identifierName: string): void; /** * @param {string} identifierName * @param {TNodeWithLexicalScope} lexicalScope */ - preserveNameForLexicalScope (identifierName: string, lexicalScope: TNodeWithLexicalScope): void; + preserveNameForLexicalScope(identifierName: string, lexicalScope: TNodeWithLexicalScope): void; } diff --git a/src/interfaces/logger/ILogger.ts b/src/interfaces/logger/ILogger.ts index f0b4a704..f186f502 100644 --- a/src/interfaces/logger/ILogger.ts +++ b/src/interfaces/logger/ILogger.ts @@ -5,17 +5,17 @@ export interface ILogger { * @param {LoggingMessage} loggingMessage * @param {string | number} value */ - info (loggingMessage: LoggingMessage, value?: string | number): void; + info(loggingMessage: LoggingMessage, value?: string | number): void; /** * @param {LoggingMessage} loggingMessage * @param {string | number} value */ - success (loggingMessage: LoggingMessage, value?: string | number): void; + success(loggingMessage: LoggingMessage, value?: string | number): void; /** * @param {LoggingMessage} loggingMessage * @param {string | number} value */ - warn (loggingMessage: LoggingMessage, value?: string | number): void; + warn(loggingMessage: LoggingMessage, value?: string | number): void; } diff --git a/src/interfaces/node-transformers/INodeTransformer.ts b/src/interfaces/node-transformers/INodeTransformer.ts index 3798edbe..9d67274d 100644 --- a/src/interfaces/node-transformers/INodeTransformer.ts +++ b/src/interfaces/node-transformers/INodeTransformer.ts @@ -7,29 +7,29 @@ import { IVisitor } from './IVisitor'; import { NodeTransformer } from '../../enums/node-transformers/NodeTransformer'; import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage'; -export interface INodeTransformer extends ITransformer { +export interface INodeTransformer extends ITransformer { /** * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null; + getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null; /** * @param {Node} node * @param {Node | null} parentNode */ - prepareNode ? (node: ESTree.Node, parentNode: ESTree.Node | null): void; + prepareNode?(node: ESTree.Node, parentNode: ESTree.Node | null): void; /** * @param {Node} node * @param {Node | null} parentNode */ - restoreNode ? (node: ESTree.Node, parentNode: ESTree.Node | null): void; + restoreNode?(node: ESTree.Node, parentNode: ESTree.Node | null): void; /** * @param {Node} node * @param {Node | null} parentNode * @returns {Node | VisitorOption} */ - transformNode (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | estraverse.VisitorOption; + transformNode(node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | estraverse.VisitorOption; } diff --git a/src/interfaces/node-transformers/INodeTransformersRunner.ts b/src/interfaces/node-transformers/INodeTransformersRunner.ts index 568cb3fc..7369702c 100644 --- a/src/interfaces/node-transformers/INodeTransformersRunner.ts +++ b/src/interfaces/node-transformers/INodeTransformersRunner.ts @@ -10,7 +10,7 @@ export interface INodeTransformersRunner { * @param {NodeTransformationStage} nodeTransformationStage * @returns {T} */ - transform ( + transform( astTree: T, nodeTransformers: NodeTransformer[], nodeTransformationStage: NodeTransformationStage diff --git a/src/interfaces/node-transformers/IVisitor.ts b/src/interfaces/node-transformers/IVisitor.ts index 993f31f0..fc7db401 100644 --- a/src/interfaces/node-transformers/IVisitor.ts +++ b/src/interfaces/node-transformers/IVisitor.ts @@ -1,7 +1,7 @@ import * as estraverse from '@javascript-obfuscator/estraverse'; import * as ESTree from 'estree'; -export interface IVisitor { - enter? (node: T, parentNode: ESTree.Node | null): ESTree.Node | estraverse.VisitorOption | void; - leave? (node: T, parentNode: ESTree.Node | null): ESTree.Node | estraverse.VisitorOption | void; +export interface IVisitor { + enter?(node: T, parentNode: ESTree.Node | null): ESTree.Node | estraverse.VisitorOption | void; + leave?(node: T, parentNode: ESTree.Node | null): ESTree.Node | estraverse.VisitorOption | void; } diff --git a/src/interfaces/node-transformers/control-flow-transformers/IControlFlowReplacer.ts b/src/interfaces/node-transformers/control-flow-transformers/IControlFlowReplacer.ts index 67c183f8..d2f912fb 100644 --- a/src/interfaces/node-transformers/control-flow-transformers/IControlFlowReplacer.ts +++ b/src/interfaces/node-transformers/control-flow-transformers/IControlFlowReplacer.ts @@ -9,15 +9,11 @@ export interface IControlFlowReplacer { * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - replace ( - node: ESTree.Node, - parentNode: ESTree.Node, - controlFlowStorage: IControlFlowStorage - ): ESTree.Node; + replace(node: ESTree.Node, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage): ESTree.Node; /** * @param {TControlFlowStorage} controlFlowStorage * @returns {string} */ - generateStorageKey (controlFlowStorage: IControlFlowStorage): string; + generateStorageKey(controlFlowStorage: IControlFlowStorage): string; } diff --git a/src/interfaces/node-transformers/converting-transformers/object-expression-extractors/IObjectExpressionExtractor.ts b/src/interfaces/node-transformers/converting-transformers/object-expression-extractors/IObjectExpressionExtractor.ts index fb811e29..632129ec 100644 --- a/src/interfaces/node-transformers/converting-transformers/object-expression-extractors/IObjectExpressionExtractor.ts +++ b/src/interfaces/node-transformers/converting-transformers/object-expression-extractors/IObjectExpressionExtractor.ts @@ -8,7 +8,7 @@ export interface IObjectExpressionExtractor { * @param {Statement} hostStatement * @returns {IObjectExpressionExtractorResult} */ - extract ( + extract( objectExpressionNode: ESTree.ObjectExpression, hostStatement: ESTree.Statement ): IObjectExpressionExtractorResult; diff --git a/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IIdentifierReplacer.ts b/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IIdentifierReplacer.ts index b4c9e808..5e64b4ab 100644 --- a/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IIdentifierReplacer.ts +++ b/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IIdentifierReplacer.ts @@ -7,13 +7,13 @@ export interface IIdentifierReplacer { * @param {Identifier} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - storeGlobalName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void; + storeGlobalName(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void; /** * @param {Identifier} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - storeLocalName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void; + storeLocalName(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void; /** * @param {Node} node @@ -21,20 +21,16 @@ export interface IIdentifierReplacer { * @param {number} nodeIdentifier * @returns {ESTree.Identifier} */ - replace ( - node: ESTree.Node, - lexicalScopeNode?: TNodeWithLexicalScope, - nodeIdentifier?: number - ): ESTree.Identifier; + replace(node: ESTree.Node, lexicalScopeNode?: TNodeWithLexicalScope, nodeIdentifier?: number): ESTree.Identifier; /** * @param {Identifier} identifierNode */ - preserveName (identifierNode: ESTree.Identifier): void; + preserveName(identifierNode: ESTree.Identifier): void; /** * @param {Identifier} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - preserveNameForLexicalScope (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void; + preserveNameForLexicalScope(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void; } diff --git a/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IThroughIdentifierReplacer.ts b/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IThroughIdentifierReplacer.ts index 802c16a4..84914a3c 100644 --- a/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IThroughIdentifierReplacer.ts +++ b/src/interfaces/node-transformers/rename-identifiers-transformers/replacer/IThroughIdentifierReplacer.ts @@ -5,5 +5,5 @@ export interface IThroughIdentifierReplacer { * @param {Identifier} identifierNode * @returns {Identifier} */ - replace (identifierNode: ESTree.Identifier): ESTree.Identifier; + replace(identifierNode: ESTree.Identifier): ESTree.Identifier; } diff --git a/src/interfaces/node-transformers/rename-properties-transformers/replacer/IRenamePropertiesReplacer.ts b/src/interfaces/node-transformers/rename-properties-transformers/replacer/IRenamePropertiesReplacer.ts index ef9cbba6..18abe84c 100644 --- a/src/interfaces/node-transformers/rename-properties-transformers/replacer/IRenamePropertiesReplacer.ts +++ b/src/interfaces/node-transformers/rename-properties-transformers/replacer/IRenamePropertiesReplacer.ts @@ -4,11 +4,11 @@ export interface IRenamePropertiesReplacer { /** * @param {string} propertyName */ - excludePropertyName (propertyName: string): void; + excludePropertyName(propertyName: string): void; /** * @param {ESTree.Identifier | ESTree.Literal} node * @returns {ESTree.Identifier | ESTree.Literal} */ - replace (node: ESTree.Identifier | ESTree.Literal): ESTree.Identifier | ESTree.Literal; + replace(node: ESTree.Identifier | ESTree.Literal): ESTree.Identifier | ESTree.Literal; } diff --git a/src/interfaces/node/IScopeIdentifiersTraverser.ts b/src/interfaces/node/IScopeIdentifiersTraverser.ts index 4f5570f5..870b838e 100644 --- a/src/interfaces/node/IScopeIdentifiersTraverser.ts +++ b/src/interfaces/node/IScopeIdentifiersTraverser.ts @@ -10,7 +10,7 @@ export interface IScopeIdentifiersTraverser { * @param {Node | null} parentNode * @param {TScopeIdentifiersTraverserCallback} callback */ - traverseScopeIdentifiers ( + traverseScopeIdentifiers( programNode: ESTree.Program, parentNode: ESTree.Node | null, callback: TScopeIdentifiersTraverserCallback @@ -21,10 +21,9 @@ export interface IScopeIdentifiersTraverser { * @param {Node | null} parentNode * @param {TScopeIdentifiersTraverserCallback} callback */ - traverseScopeThroughIdentifiers ( + traverseScopeThroughIdentifiers( node: ESTree.Node, parentNode: ESTree.Node | null, callback: TScopeIdentifiersTraverserCallback ): void; - } diff --git a/src/interfaces/options/IOptionsNormalizer.ts b/src/interfaces/options/IOptionsNormalizer.ts index fe7f3961..d44cb749 100644 --- a/src/interfaces/options/IOptionsNormalizer.ts +++ b/src/interfaces/options/IOptionsNormalizer.ts @@ -5,5 +5,5 @@ export interface IOptionsNormalizer { * @param {IOptions} options * @returns {IOptions} */ - normalize (options: IOptions): IOptions; + normalize(options: IOptions): IOptions; } diff --git a/src/interfaces/source-code/IObfuscationResult.ts b/src/interfaces/source-code/IObfuscationResult.ts index 16c7301a..00e07974 100644 --- a/src/interfaces/source-code/IObfuscationResult.ts +++ b/src/interfaces/source-code/IObfuscationResult.ts @@ -3,24 +3,24 @@ import { TIdentifierNamesCache } from '../../types/TIdentifierNamesCache'; import { IInitializable } from '../IInitializable'; import { IOptions } from '../options/IOptions'; -export interface IObfuscationResult extends IInitializable <[string, string]> { +export interface IObfuscationResult extends IInitializable<[string, string]> { /** * @returns {TIdentifierNamesCache} */ - getIdentifierNamesCache (): TIdentifierNamesCache; + getIdentifierNamesCache(): TIdentifierNamesCache; /** * @return {string} */ - getObfuscatedCode (): string; + getObfuscatedCode(): string; /** * @return {IOptions} */ - getOptions (): IOptions; + getOptions(): IOptions; /** * @return {string} */ - getSourceMap (): string; + getSourceMap(): string; } diff --git a/src/interfaces/source-code/ISourceCode.ts b/src/interfaces/source-code/ISourceCode.ts index 5c9311b4..61c2b2bf 100644 --- a/src/interfaces/source-code/ISourceCode.ts +++ b/src/interfaces/source-code/ISourceCode.ts @@ -2,10 +2,10 @@ export interface ISourceCode { /** * @returns string */ - getSourceCode (): string; + getSourceCode(): string; /** * @returns string */ - getSourceMap (): string; + getSourceMap(): string; } diff --git a/src/interfaces/storages/IArrayStorage.ts b/src/interfaces/storages/IArrayStorage.ts index 771b21f8..47e917f9 100644 --- a/src/interfaces/storages/IArrayStorage.ts +++ b/src/interfaces/storages/IArrayStorage.ts @@ -1,59 +1,59 @@ import { IInitializable } from '../IInitializable'; -export interface IArrayStorage extends IInitializable { +export interface IArrayStorage extends IInitializable { /** * @param {number} key * @returns {V | undefined} */ - delete (key: number): V | undefined; + delete(key: number): V | undefined; /** * @param {number} key * @returns {V | undefined} */ - get (key: number): V | undefined; + get(key: number): V | undefined; /** * @param {number} key * @returns {V} */ - getOrThrow (key: number): V; + getOrThrow(key: number): V; /** * @param value * @returns number | null */ - getKeyOf (value: V): number | null; + getKeyOf(value: V): number | null; /** * @returns number */ - getLength (): number; + getLength(): number; /** * @returns {V[]} */ - getStorage (): V[]; + getStorage(): V[]; /** * @returns string */ - getStorageId (): string; + getStorageId(): string; /** * @param storage * @param mergeId */ - mergeWith (storage: this, mergeId: boolean): void; + mergeWith(storage: this, mergeId: boolean): void; /** * @param {number} key * @param {V} value */ - set (key: number, value: V): void; + set(key: number, value: V): void; /** * @returns string */ - toString (): string; + toString(): string; } diff --git a/src/interfaces/storages/IMapStorage.ts b/src/interfaces/storages/IMapStorage.ts index 50f004ca..f217f980 100644 --- a/src/interfaces/storages/IMapStorage.ts +++ b/src/interfaces/storages/IMapStorage.ts @@ -2,65 +2,65 @@ import { TDictionary } from '../../types/TDictionary'; import { IInitializable } from '../IInitializable'; -export interface IMapStorage extends IInitializable { +export interface IMapStorage extends IInitializable { /** * @param {K} key * @returns {V | undefined} */ - get (key: K): V | undefined; + get(key: K): V | undefined; /** * @param {K} key * @returns {V} */ - getOrThrow (key: K): V; + getOrThrow(key: K): V; /** * @param {V} value * @returns {K | null} */ - getKeyOf (value: V): K | null; + getKeyOf(value: V): K | null; /** * @returns number */ - getLength (): number; + getLength(): number; /** * @returns {Map} */ - getStorage (): Map ; + getStorage(): Map; /** * @returns {TDictionary} */ - getStorageAsDictionary (): TDictionary; + getStorageAsDictionary(): TDictionary; /** * @returns string */ - getStorageId (): string; + getStorageId(): string; /** * @param {K} key * @returns {boolean} */ - has (key: K): boolean; + has(key: K): boolean; /** * @param storage * @param mergeId */ - mergeWith (storage: this, mergeId: boolean): void; + mergeWith(storage: this, mergeId: boolean): void; /** * @param {K} key * @param {V} value */ - set (key: K, value: V): void; + set(key: K, value: V): void; /** * @returns string */ - toString (): string; + toString(): string; } diff --git a/src/interfaces/storages/IWeakMapStorage.ts b/src/interfaces/storages/IWeakMapStorage.ts index 82b91560..40c06434 100644 --- a/src/interfaces/storages/IWeakMapStorage.ts +++ b/src/interfaces/storages/IWeakMapStorage.ts @@ -1,37 +1,37 @@ import { IInitializable } from '../IInitializable'; -export interface IWeakMapStorage extends IInitializable { +export interface IWeakMapStorage extends IInitializable { /** * @param {K} key * @returns {V | undefined} */ - get (key: K): V | undefined; + get(key: K): V | undefined; /** * @param {K} key * @returns {V} */ - getOrThrow (key: K): V; + getOrThrow(key: K): V; /** * @returns {WeakMap} */ - getStorage (): WeakMap ; + getStorage(): WeakMap; /** * @returns string */ - getStorageId (): string; + getStorageId(): string; /** * @param {K} key * @returns {boolean} */ - has (key: K): boolean; + has(key: K): boolean; /** * @param {K} key * @param {V} value */ - set (key: K, value: V): void; + set(key: K, value: V): void; } diff --git a/src/interfaces/storages/control-flow-transformers/IControlFlowStorage.ts b/src/interfaces/storages/control-flow-transformers/IControlFlowStorage.ts index 7c59d6df..19171fc7 100644 --- a/src/interfaces/storages/control-flow-transformers/IControlFlowStorage.ts +++ b/src/interfaces/storages/control-flow-transformers/IControlFlowStorage.ts @@ -2,4 +2,4 @@ import { IMapStorage } from '../IMapStorage'; import { ICustomNode } from '../../custom-nodes/ICustomNode'; // eslint-disable-next-line -export interface IControlFlowStorage extends IMapStorage {} +export interface IControlFlowStorage extends IMapStorage {} diff --git a/src/interfaces/storages/identifier-names-cache/IGlobalIdentifierNamesCacheStorage.ts b/src/interfaces/storages/identifier-names-cache/IGlobalIdentifierNamesCacheStorage.ts index c1aa13be..dfdc4718 100644 --- a/src/interfaces/storages/identifier-names-cache/IGlobalIdentifierNamesCacheStorage.ts +++ b/src/interfaces/storages/identifier-names-cache/IGlobalIdentifierNamesCacheStorage.ts @@ -1,4 +1,4 @@ import { IMapStorage } from '../IMapStorage'; // eslint-disable-next-line -export interface IGlobalIdentifierNamesCacheStorage extends IMapStorage {} +export interface IGlobalIdentifierNamesCacheStorage extends IMapStorage {} diff --git a/src/interfaces/storages/identifier-names-cache/IPropertyIdentifierNamesCacheStorage.ts b/src/interfaces/storages/identifier-names-cache/IPropertyIdentifierNamesCacheStorage.ts index b4a6e157..5003d6c6 100644 --- a/src/interfaces/storages/identifier-names-cache/IPropertyIdentifierNamesCacheStorage.ts +++ b/src/interfaces/storages/identifier-names-cache/IPropertyIdentifierNamesCacheStorage.ts @@ -1,4 +1,4 @@ import { IMapStorage } from '../IMapStorage'; // eslint-disable-next-line -export interface IPropertyIdentifierNamesCacheStorage extends IMapStorage {} +export interface IPropertyIdentifierNamesCacheStorage extends IMapStorage {} diff --git a/src/interfaces/storages/string-array-transformers/ILiteralNodesCacheStorage.ts b/src/interfaces/storages/string-array-transformers/ILiteralNodesCacheStorage.ts index 149e0cc1..4c505cb2 100644 --- a/src/interfaces/storages/string-array-transformers/ILiteralNodesCacheStorage.ts +++ b/src/interfaces/storages/string-array-transformers/ILiteralNodesCacheStorage.ts @@ -3,24 +3,18 @@ import * as ESTree from 'estree'; import { IMapStorage } from '../IMapStorage'; import { IStringArrayStorageItemData } from './IStringArrayStorageItem'; -export interface ILiteralNodesCacheStorage extends IMapStorage { +export interface ILiteralNodesCacheStorage extends IMapStorage { /** * @param {string} literalValue * @param {IStringArrayStorageItemData | undefined} stringArrayStorageItemData * @returns {string} */ - buildKey ( - literalValue: string, - stringArrayStorageItemData: IStringArrayStorageItemData | undefined, - ): string; + buildKey(literalValue: string, stringArrayStorageItemData: IStringArrayStorageItemData | undefined): string; /** * @param {string} key * @param {IStringArrayStorageItemData | undefined} stringArrayStorageItemData * @returns {boolean} */ - shouldUseCachedValue ( - key: string, - stringArrayStorageItemData: IStringArrayStorageItemData | undefined - ): boolean; + shouldUseCachedValue(key: string, stringArrayStorageItemData: IStringArrayStorageItemData | undefined): boolean; } diff --git a/src/interfaces/storages/string-array-transformers/IStringArrayScopeCallsWrappersDataStorage.ts b/src/interfaces/storages/string-array-transformers/IStringArrayScopeCallsWrappersDataStorage.ts index ed9e7134..f88a899a 100644 --- a/src/interfaces/storages/string-array-transformers/IStringArrayScopeCallsWrappersDataStorage.ts +++ b/src/interfaces/storages/string-array-transformers/IStringArrayScopeCallsWrappersDataStorage.ts @@ -4,7 +4,5 @@ import { TStringArrayScopeCallsWrappersDataByEncoding } from '../../../types/nod import { IWeakMapStorage } from '../IWeakMapStorage'; // eslint-disable-next-line @typescript-eslint/no-empty-interface -export interface IStringArrayScopeCallsWrappersDataStorage extends IWeakMapStorage< - TNodeWithLexicalScopeStatements, - TStringArrayScopeCallsWrappersDataByEncoding -> {} +export interface IStringArrayScopeCallsWrappersDataStorage + extends IWeakMapStorage {} diff --git a/src/interfaces/storages/string-array-transformers/IStringArrayStorage.ts b/src/interfaces/storages/string-array-transformers/IStringArrayStorage.ts index a80d3d96..0e1cf6b4 100644 --- a/src/interfaces/storages/string-array-transformers/IStringArrayStorage.ts +++ b/src/interfaces/storages/string-array-transformers/IStringArrayStorage.ts @@ -3,29 +3,29 @@ import { TStringArrayEncoding } from '../../../types/options/TStringArrayEncodin import { IMapStorage } from '../IMapStorage'; import { IStringArrayStorageItemData } from './IStringArrayStorageItem'; -export interface IStringArrayStorage extends IMapStorage { +export interface IStringArrayStorage extends IMapStorage { /** * @returns {number} */ - getIndexShiftAmount (): number; + getIndexShiftAmount(): number; /** * @returns {number} */ - getRotationAmount (): number; + getRotationAmount(): number; /** * @returns {string} */ - getStorageName (): string; + getStorageName(): string; /** * @param {TStringArrayEncoding | null} stringArrayEncoding * @returns {string} */ - getStorageCallsWrapperName (stringArrayEncoding: TStringArrayEncoding | null): string; + getStorageCallsWrapperName(stringArrayEncoding: TStringArrayEncoding | null): string; - rotateStorage (): void; + rotateStorage(): void; - shuffleStorage (): void; + shuffleStorage(): void; } diff --git a/src/interfaces/storages/string-array-transformers/IVisitedLexicalScopeNodesStackStorage.ts b/src/interfaces/storages/string-array-transformers/IVisitedLexicalScopeNodesStackStorage.ts index 8d41654e..76f01e56 100644 --- a/src/interfaces/storages/string-array-transformers/IVisitedLexicalScopeNodesStackStorage.ts +++ b/src/interfaces/storages/string-array-transformers/IVisitedLexicalScopeNodesStackStorage.ts @@ -6,20 +6,20 @@ export interface IVisitedLexicalScopeNodesStackStorage extends IArrayStorage TValue} valueFunction * @returns {TValue[]} */ - fillWithRange (length: number, valueFunction: (index: number) => TValue): TValue[]; + fillWithRange(length: number, valueFunction: (index: number) => TValue): TValue[]; /** * @param {T[]} array * @returns {T | null} */ - findMostOccurringElement (array: T[]): T | null; + findMostOccurringElement(array: T[]): T | null; /** * @param {T[]} array * @returns {T | undefined} */ - getLastElement (array: T[]): T | undefined; + getLastElement(array: T[]): T | undefined; /** * @param {T[]} array * @param {number} index * @returns {T | undefined} */ - getLastElementByIndex (array: T[], index: number): T | undefined; + getLastElementByIndex(array: T[], index: number): T | undefined; /** * @param array * @param times * @returns {T[]} */ - rotate (array: T[], times: number): T[]; + rotate(array: T[], times: number): T[]; /** * @param array * @return {T[]} */ - shuffle (array: T[]): T[]; + shuffle(array: T[]): T[]; } diff --git a/src/interfaces/utils/ICryptUtils.ts b/src/interfaces/utils/ICryptUtils.ts index 49dae1a0..ea8b9047 100644 --- a/src/interfaces/utils/ICryptUtils.ts +++ b/src/interfaces/utils/ICryptUtils.ts @@ -3,19 +3,19 @@ export interface ICryptUtils { * @param {string} string * @returns {string} */ - btoa (string: string): string; + btoa(string: string): string; /** * @param str * @param length * @returns {[string, string]} */ - hideString (str: string, length: number): [string, string]; + hideString(str: string, length: number): [string, string]; /** * @param key * @param string * @returns {string} */ - rc4 (string: string, key: string): string; + rc4(string: string, key: string): string; } diff --git a/src/interfaces/utils/IEscapeSequenceEncoder.ts b/src/interfaces/utils/IEscapeSequenceEncoder.ts index 2394170c..e8cc0aec 100644 --- a/src/interfaces/utils/IEscapeSequenceEncoder.ts +++ b/src/interfaces/utils/IEscapeSequenceEncoder.ts @@ -4,5 +4,5 @@ export interface IEscapeSequenceEncoder { * @param {boolean} encodeAllSymbols * @returns {string} */ - encode (string: string, encodeAllSymbols: boolean): string; + encode(string: string, encodeAllSymbols: boolean): string; } diff --git a/src/interfaces/utils/ILevelledTopologicalSorter.ts b/src/interfaces/utils/ILevelledTopologicalSorter.ts index 137cfc29..6c97b4a8 100644 --- a/src/interfaces/utils/ILevelledTopologicalSorter.ts +++ b/src/interfaces/utils/ILevelledTopologicalSorter.ts @@ -1,21 +1,18 @@ -export interface ILevelledTopologicalSorter { +export interface ILevelledTopologicalSorter { /** * @param {TValue} precedent * @param {TValue | null} consequent * @returns {this} */ - add ( - precedent: TValue, - consequent?: TValue | null - ): this; + add(precedent: TValue, consequent?: TValue | null): this; /** * @returns {TValue[]} */ - sort (): TValue[]; + sort(): TValue[]; /** * @returns {TValue[][]} */ - sortByGroups (): TValue[][]; + sortByGroups(): TValue[][]; } diff --git a/src/interfaces/utils/IRandomGenerator.ts b/src/interfaces/utils/IRandomGenerator.ts index 65c5f4d2..d3091f48 100644 --- a/src/interfaces/utils/IRandomGenerator.ts +++ b/src/interfaces/utils/IRandomGenerator.ts @@ -6,19 +6,19 @@ export interface IRandomGenerator { /** * @returns {number} */ - getMathRandom (): number; + getMathRandom(): number; /** * @returns {Chance.Chance} */ - getRandomGenerator (): Chance.Chance; + getRandomGenerator(): Chance.Chance; /** * @param min * @param max * @returns {number} */ - getRandomInteger (min: number, max: number): number; + getRandomInteger(min: number, max: number): number; /** * @param {number} min @@ -26,22 +26,22 @@ export interface IRandomGenerator { * @param {number[]} valuesToExclude * @returns {number} */ - getRandomIntegerExcluding (min: number, max: number, valuesToExclude: number[]): number; + getRandomIntegerExcluding(min: number, max: number, valuesToExclude: number[]): number; /** * @param length * @param pool * @returns {string} */ - getRandomString (length: number, pool?: string): string; + getRandomString(length: number, pool?: string): string; /** * @returns {string} */ - getInputSeed (): string; + getInputSeed(): string; /** * @returns {string} */ - getRawSeed (): string; + getRawSeed(): string; } diff --git a/src/interfaces/utils/ISetUtils.ts b/src/interfaces/utils/ISetUtils.ts index 7a81941e..5b5c5c47 100644 --- a/src/interfaces/utils/ISetUtils.ts +++ b/src/interfaces/utils/ISetUtils.ts @@ -3,5 +3,5 @@ export interface ISetUtils { * @param {Set} set * @returns {T | undefined} */ - getLastElement (set: Set): T | undefined; + getLastElement(set: Set): T | undefined; } diff --git a/src/interfaces/utils/ITransformerNamesGroupsBuilder.ts b/src/interfaces/utils/ITransformerNamesGroupsBuilder.ts index 99f813c6..0dd4875c 100644 --- a/src/interfaces/utils/ITransformerNamesGroupsBuilder.ts +++ b/src/interfaces/utils/ITransformerNamesGroupsBuilder.ts @@ -1,12 +1,9 @@ import { TDictionary } from '../../types/TDictionary'; -export interface ITransformerNamesGroupsBuilder < - TTransformerName extends string, - TTransformer -> { +export interface ITransformerNamesGroupsBuilder { /** * @param {TDictionary} normalizedTransformers * @returns {TTransformerName[][]} */ - build (normalizedTransformers: TDictionary): TTransformerName[][]; + build(normalizedTransformers: TDictionary): TTransformerName[][]; } diff --git a/src/logger/Logger.ts b/src/logger/Logger.ts index 7a93c6c5..5b706cb1 100644 --- a/src/logger/Logger.ts +++ b/src/logger/Logger.ts @@ -34,9 +34,7 @@ export class Logger implements ILogger { /** * @param {IOptions} options */ - public constructor ( - @inject(ServiceIdentifiers.IOptions) options: IOptions - ) { + public constructor(@inject(ServiceIdentifiers.IOptions) options: IOptions) { this.options = options; } @@ -46,11 +44,11 @@ export class Logger implements ILogger { * @param {string} loggingMessage * @param {string | number} value */ - public static log ( + public static log( loggingLevelColor: Chalk, loggingPrefix: LoggingPrefix, loggingMessage: string, - value?: string | number, + value?: string | number ): void { const processedMessage: string = loggingLevelColor(`\n${loggingPrefix} ${loggingMessage}`); @@ -61,7 +59,7 @@ export class Logger implements ILogger { * @param {LoggingMessage} loggingMessage * @param {string | number} value */ - public info (loggingMessage: LoggingMessage, value?: string | number): void { + public info(loggingMessage: LoggingMessage, value?: string | number): void { if (!this.options.log) { return; } @@ -73,7 +71,7 @@ export class Logger implements ILogger { * @param {LoggingMessage} loggingMessage * @param {string | number} value */ - public success (loggingMessage: LoggingMessage, value?: string | number): void { + public success(loggingMessage: LoggingMessage, value?: string | number): void { if (!this.options.log) { return; } @@ -85,7 +83,7 @@ export class Logger implements ILogger { * @param {LoggingMessage} loggingMessage * @param {string | number} value */ - public warn (loggingMessage: LoggingMessage, value?: string | number): void { + public warn(loggingMessage: LoggingMessage, value?: string | number): void { if (!this.options.log) { return; } diff --git a/src/node-transformers/AbstractNodeTransformer.ts b/src/node-transformers/AbstractNodeTransformer.ts index 44232a2f..ebaa85e4 100644 --- a/src/node-transformers/AbstractNodeTransformer.ts +++ b/src/node-transformers/AbstractNodeTransformer.ts @@ -33,7 +33,7 @@ export abstract class AbstractNodeTransformer implements INodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -45,12 +45,12 @@ export abstract class AbstractNodeTransformer implements INodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public abstract getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null; + public abstract getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null; /** * @param {Node} node * @param {Node} parentNode * @returns {Node | VisitorOption} */ - public abstract transformNode (node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node | estraverse.VisitorOption; + public abstract transformNode(node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node | estraverse.VisitorOption; } diff --git a/src/node-transformers/NodeTransformersRunner.ts b/src/node-transformers/NodeTransformersRunner.ts index 8e423bae..360566ca 100644 --- a/src/node-transformers/NodeTransformersRunner.ts +++ b/src/node-transformers/NodeTransformersRunner.ts @@ -42,14 +42,11 @@ export class NodeTransformersRunner implements INodeTransformersRunner { * @param {TNodeTransformerFactory} nodeTransformerFactory * @param {ITransformerNamesGroupsBuilder} nodeTransformerNamesGroupsBuilder */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__INodeTransformer) - nodeTransformerFactory: TNodeTransformerFactory, + nodeTransformerFactory: TNodeTransformerFactory, @inject(ServiceIdentifiers.INodeTransformerNamesGroupsBuilder) - nodeTransformerNamesGroupsBuilder: ITransformerNamesGroupsBuilder< - NodeTransformer, - INodeTransformer - >, + nodeTransformerNamesGroupsBuilder: ITransformerNamesGroupsBuilder ) { this.nodeTransformerFactory = nodeTransformerFactory; this.nodeTransformerNamesGroupsBuilder = nodeTransformerNamesGroupsBuilder; @@ -61,7 +58,7 @@ export class NodeTransformersRunner implements INodeTransformersRunner { * @param {NodeTransformationStage} nodeTransformationStage * @returns {T} */ - public transform ( + public transform( astTree: T, nodeTransformerNames: NodeTransformer[], nodeTransformationStage: NodeTransformationStage @@ -70,8 +67,10 @@ export class NodeTransformersRunner implements INodeTransformersRunner { return astTree; } - const normalizedNodeTransformers: TDictionary = - this.buildNormalizedNodeTransformers(nodeTransformerNames, nodeTransformationStage); + const normalizedNodeTransformers: TDictionary = this.buildNormalizedNodeTransformers( + nodeTransformerNames, + nodeTransformationStage + ); const nodeTransformerNamesGroups: NodeTransformer[][] = this.nodeTransformerNamesGroupsBuilder.build(normalizedNodeTransformers); @@ -114,26 +113,25 @@ export class NodeTransformersRunner implements INodeTransformersRunner { * @param {NodeTransformationStage} nodeTransformationStage * @returns {TDictionary} */ - private buildNormalizedNodeTransformers ( + private buildNormalizedNodeTransformers( nodeTransformerNames: NodeTransformer[], nodeTransformationStage: NodeTransformationStage ): TDictionary { - return nodeTransformerNames - .reduce>( - (acc: TDictionary, nodeTransformerName: NodeTransformer) => { - const nodeTransformer: INodeTransformer = this.nodeTransformerFactory(nodeTransformerName); + return nodeTransformerNames.reduce>( + (acc: TDictionary, nodeTransformerName: NodeTransformer) => { + const nodeTransformer: INodeTransformer = this.nodeTransformerFactory(nodeTransformerName); - if (!nodeTransformer.getVisitor(nodeTransformationStage)) { - return acc; - } + if (!nodeTransformer.getVisitor(nodeTransformationStage)) { + return acc; + } - return >{ - ...acc, - [nodeTransformerName]: nodeTransformer - }; - }, - {} - ); + return >{ + ...acc, + [nodeTransformerName]: nodeTransformer + }; + }, + {} + ); } /** @@ -141,7 +139,7 @@ export class NodeTransformersRunner implements INodeTransformersRunner { * @param {TVisitorDirection} direction * @returns {TVisitorFunction} */ - private mergeVisitorsForDirection (visitors: IVisitor[], direction: TVisitorDirection): TVisitorFunction { + private mergeVisitorsForDirection(visitors: IVisitor[], direction: TVisitorDirection): TVisitorFunction { const visitorsLength: number = visitors.length; if (!visitorsLength) { diff --git a/src/node-transformers/control-flow-transformers/BlockStatementControlFlowTransformer.ts b/src/node-transformers/control-flow-transformers/BlockStatementControlFlowTransformer.ts index 62ff4b8b..54a9356c 100644 --- a/src/node-transformers/control-flow-transformers/BlockStatementControlFlowTransformer.ts +++ b/src/node-transformers/control-flow-transformers/BlockStatementControlFlowTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -40,9 +40,9 @@ export class BlockStatementControlFlowTransformer extends AbstractNodeTransforme * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -57,24 +57,26 @@ export class BlockStatementControlFlowTransformer extends AbstractNodeTransforme * @param {Node} node * @returns {boolean} */ - private static isProhibitedStatementNode (node: ESTree.Node): boolean { - const isBreakOrContinueStatement: boolean = NodeGuards.isBreakStatementNode(node) - || NodeGuards.isContinueStatementNode(node); - const isVariableDeclarationWithLetOrConstKind: boolean = NodeGuards.isVariableDeclarationNode(node) - && (node.kind === 'const' || node.kind === 'let'); + private static isProhibitedStatementNode(node: ESTree.Node): boolean { + const isBreakOrContinueStatement: boolean = + NodeGuards.isBreakStatementNode(node) || NodeGuards.isContinueStatementNode(node); + const isVariableDeclarationWithLetOrConstKind: boolean = + NodeGuards.isVariableDeclarationNode(node) && (node.kind === 'const' || node.kind === 'let'); const isClassDeclaration: boolean = NodeGuards.isClassDeclarationNode(node); - return NodeGuards.isFunctionDeclarationNode(node) - || isBreakOrContinueStatement - || isVariableDeclarationWithLetOrConstKind - || isClassDeclaration; + return ( + NodeGuards.isFunctionDeclarationNode(node) || + isBreakOrContinueStatement || + isVariableDeclarationWithLetOrConstKind || + isClassDeclaration + ); } /** * @param {BlockStatement} blockStatementNode * @returns {boolean} */ - private static canTransformBlockStatementNode (blockStatementNode: ESTree.BlockStatement): boolean { + private static canTransformBlockStatementNode(blockStatementNode: ESTree.BlockStatement): boolean { let canTransform: boolean = true; estraverse.traverse(blockStatementNode, { @@ -100,7 +102,7 @@ export class BlockStatementControlFlowTransformer extends AbstractNodeTransforme * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.controlFlowFlattening) { return null; } @@ -125,7 +127,7 @@ export class BlockStatementControlFlowTransformer extends AbstractNodeTransforme * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (blockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node): ESTree.Node { + public transformNode(blockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node): ESTree.Node { if ( this.randomGenerator.getMathRandom() > this.options.controlFlowFlatteningThreshold || !BlockStatementControlFlowTransformer.canTransformBlockStatementNode(blockStatementNode) @@ -136,9 +138,12 @@ export class BlockStatementControlFlowTransformer extends AbstractNodeTransforme const blockStatementBody: ESTree.Statement[] = blockStatementNode.body; const originalKeys: number[] = this.arrayUtils.createWithRange(blockStatementBody.length); const shuffledKeys: number[] = this.arrayUtils.shuffle(originalKeys); - const originalKeysIndexesInShuffledArray: number[] = originalKeys.map((key: number) => shuffledKeys.indexOf(key)); - const blockStatementControlFlowFlatteningCustomNode: ICustomNode> = - this.controlFlowCustomNodeFactory(ControlFlowCustomNode.BlockStatementControlFlowFlatteningNode); + const originalKeysIndexesInShuffledArray: number[] = originalKeys.map((key: number) => + shuffledKeys.indexOf(key) + ); + const blockStatementControlFlowFlatteningCustomNode: ICustomNode< + TInitialData + > = this.controlFlowCustomNodeFactory(ControlFlowCustomNode.BlockStatementControlFlowFlatteningNode); blockStatementControlFlowFlatteningCustomNode.initialize( blockStatementBody, diff --git a/src/node-transformers/control-flow-transformers/FunctionControlFlowTransformer.ts b/src/node-transformers/control-flow-transformers/FunctionControlFlowTransformer.ts index 1e656219..362317f0 100644 --- a/src/node-transformers/control-flow-transformers/FunctionControlFlowTransformer.ts +++ b/src/node-transformers/control-flow-transformers/FunctionControlFlowTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -7,9 +7,7 @@ import * as ESTree from 'estree'; import { TControlFlowCustomNodeFactory } from '../../types/container/custom-nodes/TControlFlowCustomNodeFactory'; import { TControlFlowReplacerFactory } from '../../types/container/node-transformers/TControlFlowReplacerFactory'; import { TControlFlowStorageFactory } from '../../types/container/node-transformers/TControlFlowStorageFactory'; -import { - TControlFlowStorageFactoryCreator -} from '../../types/container/node-transformers/TControlFlowStorageFactoryCreator'; +import { TControlFlowStorageFactoryCreator } from '../../types/container/node-transformers/TControlFlowStorageFactoryCreator'; import { TInitialData } from '../../types/TInitialData'; import { TNodeWithStatements } from '../../types/node/TNodeWithStatements'; @@ -20,17 +18,13 @@ import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator'; import { IVisitor } from '../../interfaces/node-transformers/IVisitor'; import { ControlFlowCustomNode } from '../../enums/custom-nodes/ControlFlowCustomNode'; -import { - ControlFlowReplacer -} from '../../enums/node-transformers/control-flow-transformers/control-flow-replacers/ControlFlowReplacer'; +import { ControlFlowReplacer } from '../../enums/node-transformers/control-flow-transformers/control-flow-replacers/ControlFlowReplacer'; import { ControlFlowStorage } from '../../enums/storages/ControlFlowStorage'; import { NodeType } from '../../enums/node/NodeType'; import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage'; import { AbstractNodeTransformer } from '../AbstractNodeTransformer'; -import { - ControlFlowStorageNode -} from '../../custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ControlFlowStorageNode'; +import { ControlFlowStorageNode } from '../../custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/ControlFlowStorageNode'; import { NodeAppender } from '../../node/NodeAppender'; import { NodeGuards } from '../../node/NodeGuards'; import { NodeMetadata } from '../../node/NodeMetadata'; @@ -52,7 +46,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { /** * @type {Map } */ - protected readonly controlFlowReplacersMap: Map = new Map([ + protected readonly controlFlowReplacersMap: Map = new Map([ [NodeType.BinaryExpression, ControlFlowReplacer.BinaryExpressionControlFlowReplacer], [NodeType.CallExpression, ControlFlowReplacer.CallExpressionControlFlowReplacer], [NodeType.LogicalExpression, ControlFlowReplacer.LogicalExpressionControlFlowReplacer], @@ -62,12 +56,13 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { /** * @type {WeakMap} */ - protected readonly controlFlowData: WeakMap = new WeakMap(); + protected readonly controlFlowData: WeakMap = new WeakMap(); /** * @type {WeakMap} */ - protected readonly hostNodesWithControlFlowNode: WeakMap = new WeakMap(); + protected readonly hostNodesWithControlFlowNode: WeakMap = + new WeakMap(); /** * @type {TControlFlowReplacerFactory} @@ -96,19 +91,21 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__TControlFlowStorage) - controlFlowStorageFactoryCreator: TControlFlowStorageFactoryCreator, + controlFlowStorageFactoryCreator: TControlFlowStorageFactoryCreator, @inject(ServiceIdentifiers.Factory__IControlFlowReplacer) - controlFlowReplacerFactory: TControlFlowReplacerFactory, + controlFlowReplacerFactory: TControlFlowReplacerFactory, @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { super(randomGenerator, options); - this.controlFlowStorageFactory = controlFlowStorageFactoryCreator(ControlFlowStorage.FunctionControlFlowStorage); + this.controlFlowStorageFactory = controlFlowStorageFactoryCreator( + ControlFlowStorage.FunctionControlFlowStorage + ); this.controlFlowReplacerFactory = controlFlowReplacerFactory; this.controlFlowCustomNodeFactory = controlFlowCustomNodeFactory; } @@ -117,7 +114,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.controlFlowFlattening) { return null; } @@ -145,7 +142,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Function} */ - public transformNode (functionNode: ESTree.Function, parentNode: ESTree.Node): ESTree.Function { + public transformNode(functionNode: ESTree.Function, parentNode: ESTree.Node): ESTree.Function { this.visitedFunctionNodes.add(functionNode); if (!NodeGuards.isBlockStatementNode(functionNode.body)) { @@ -172,7 +169,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {BlockStatement} functionNode * @param {IControlFlowStorage} controlFlowStorage */ - protected transformFunctionBody (functionNode: ESTree.Function, controlFlowStorage: IControlFlowStorage): void { + protected transformFunctionBody(functionNode: ESTree.Function, controlFlowStorage: IControlFlowStorage): void { estraverse.replace(functionNode.body, { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): estraverse.VisitorOption | ESTree.Node => this.transformFunctionBodyNode(node, parentNode, functionNode, controlFlowStorage) @@ -186,22 +183,19 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {IControlFlowStorage} controlFlowStorage * @returns {ESTraverse.VisitorOption | Node} */ - protected transformFunctionBodyNode ( + protected transformFunctionBodyNode( node: ESTree.Node, parentNode: ESTree.Node | null, functionNode: ESTree.Function, controlFlowStorage: IControlFlowStorage ): estraverse.VisitorOption | ESTree.Node { - const shouldSkipTraverse = !parentNode - || NodeMetadata.isIgnoredNode(node) - || this.isVisitedFunctionNode(node); + const shouldSkipTraverse = !parentNode || NodeMetadata.isIgnoredNode(node) || this.isVisitedFunctionNode(node); if (shouldSkipTraverse) { return estraverse.VisitorOption.Skip; } - const controlFlowReplacerName: ControlFlowReplacer | null = this.controlFlowReplacersMap.get(node.type) - ?? null; + const controlFlowReplacerName: ControlFlowReplacer | null = this.controlFlowReplacersMap.get(node.type) ?? null; if (!controlFlowReplacerName) { return node; @@ -211,12 +205,11 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { return node; } - const replacedNode: ESTree.Node = this.controlFlowReplacerFactory(controlFlowReplacerName) - .replace( - node, - parentNode, - controlFlowStorage - ); + const replacedNode: ESTree.Node = this.controlFlowReplacerFactory(controlFlowReplacerName).replace( + node, + parentNode, + controlFlowStorage + ); NodeUtils.parentizeNode(replacedNode, parentNode); @@ -227,8 +220,9 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {BlockStatement} functionNodeBody * @returns {TNodeWithStatements} */ - protected getHostNode (functionNodeBody: ESTree.BlockStatement): TNodeWithStatements { - const blockScopesOfNode: TNodeWithStatements[] = NodeStatementUtils.getParentNodesWithStatements(functionNodeBody); + protected getHostNode(functionNodeBody: ESTree.BlockStatement): TNodeWithStatements { + const blockScopesOfNode: TNodeWithStatements[] = + NodeStatementUtils.getParentNodesWithStatements(functionNodeBody); if (blockScopesOfNode.length === 1) { return functionNodeBody; @@ -251,7 +245,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {TNodeWithStatements} hostNode * @returns {TControlFlowStorage} */ - protected getControlFlowStorage (hostNode: TNodeWithStatements): IControlFlowStorage { + protected getControlFlowStorage(hostNode: TNodeWithStatements): IControlFlowStorage { let controlFlowStorage: IControlFlowStorage; const hostControlFlowStorage: IControlFlowStorage | null = this.controlFlowData.get(hostNode) ?? null; @@ -278,7 +272,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {IControlFlowStorage} controlFlowStorage * @returns {VariableDeclaration} */ - protected getControlFlowStorageNode (controlFlowStorage: IControlFlowStorage): ESTree.VariableDeclaration { + protected getControlFlowStorageNode(controlFlowStorage: IControlFlowStorage): ESTree.VariableDeclaration { const controlFlowStorageCustomNode: ICustomNode> = this.controlFlowCustomNodeFactory(ControlFlowCustomNode.ControlFlowStorageNode); @@ -287,7 +281,9 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { const controlFlowStorageNode: ESTree.Node = controlFlowStorageCustomNode.getNode()[0]; if (!NodeGuards.isVariableDeclarationNode(controlFlowStorageNode)) { - throw new Error('`controlFlowStorageNode` should contain `VariableDeclaration` node with control flow storage object'); + throw new Error( + '`controlFlowStorageNode` should contain `VariableDeclaration` node with control flow storage object' + ); } return controlFlowStorageNode; @@ -297,7 +293,7 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {TNodeWithStatements} hostNode * @param {VariableDeclaration} controlFlowStorageNode */ - protected appendControlFlowStorageNode ( + protected appendControlFlowStorageNode( hostNode: TNodeWithStatements, controlFlowStorageNode: ESTree.VariableDeclaration ): void { @@ -311,14 +307,14 @@ export class FunctionControlFlowTransformer extends AbstractNodeTransformer { * @param {NodeGuards} node * @returns {boolean} */ - protected isVisitedFunctionNode (node: ESTree.Node): boolean { + protected isVisitedFunctionNode(node: ESTree.Node): boolean { return NodeGuards.isFunctionNode(node) && this.visitedFunctionNodes.has(node); } /** * @returns {boolean} */ - protected isAllowedTransformationByThreshold (): boolean { + protected isAllowedTransformationByThreshold(): boolean { return this.randomGenerator.getMathRandom() <= this.options.controlFlowFlatteningThreshold; } } diff --git a/src/node-transformers/control-flow-transformers/StringArrayControlFlowTransformer.ts b/src/node-transformers/control-flow-transformers/StringArrayControlFlowTransformer.ts index ab9cd7b3..0de2115a 100644 --- a/src/node-transformers/control-flow-transformers/StringArrayControlFlowTransformer.ts +++ b/src/node-transformers/control-flow-transformers/StringArrayControlFlowTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -6,9 +6,7 @@ import * as ESTree from 'estree'; import { TControlFlowCustomNodeFactory } from '../../types/container/custom-nodes/TControlFlowCustomNodeFactory'; import { TControlFlowReplacerFactory } from '../../types/container/node-transformers/TControlFlowReplacerFactory'; -import { - TControlFlowStorageFactoryCreator -} from '../../types/container/node-transformers/TControlFlowStorageFactoryCreator'; +import { TControlFlowStorageFactoryCreator } from '../../types/container/node-transformers/TControlFlowStorageFactoryCreator'; import { TNodeWithStatements } from '../../types/node/TNodeWithStatements'; import { IControlFlowStorage } from '../../interfaces/storages/control-flow-transformers/IControlFlowStorage'; @@ -39,7 +37,7 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf /** * @type {Map } */ - protected override readonly controlFlowReplacersMap: Map = new Map([ + protected override readonly controlFlowReplacersMap: Map = new Map([ [NodeType.Literal, ControlFlowReplacer.StringArrayCallControlFlowReplacer] ]); @@ -55,13 +53,13 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__TControlFlowStorage) - controlFlowStorageFactoryCreator: TControlFlowStorageFactoryCreator, + controlFlowStorageFactoryCreator: TControlFlowStorageFactoryCreator, @inject(ServiceIdentifiers.Factory__IControlFlowReplacer) - controlFlowReplacerFactory: TControlFlowReplacerFactory, + controlFlowReplacerFactory: TControlFlowReplacerFactory, @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -80,7 +78,7 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public override getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public override getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.stringArrayCallsTransform) { return null; } @@ -110,14 +108,14 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf * @param {IControlFlowStorage} controlFlowStorage * @returns {ESTraverse.VisitorOption | Node} */ - protected override transformFunctionBodyNode ( + protected override transformFunctionBodyNode( node: ESTree.Node, parentNode: ESTree.Node | null, functionNode: ESTree.Function, controlFlowStorage: IControlFlowStorage ): estraverse.VisitorOption | ESTree.Node { - const isControlFlowStorageNode = NodeGuards.isVariableDeclarationNode(node) - && this.controlFlowStorageNodes.has(node); + const isControlFlowStorageNode = + NodeGuards.isVariableDeclarationNode(node) && this.controlFlowStorageNodes.has(node); if (isControlFlowStorageNode) { return estraverse.VisitorOption.Skip; @@ -130,7 +128,7 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf * @param {TNodeWithStatements} hostNode * @returns {TControlFlowStorage} */ - protected override getControlFlowStorage (hostNode: TNodeWithStatements): IControlFlowStorage { + protected override getControlFlowStorage(hostNode: TNodeWithStatements): IControlFlowStorage { return this.controlFlowStorageFactory(); } @@ -138,7 +136,7 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf * @param {TNodeWithStatements} hostNode * @param {VariableDeclaration} controlFlowStorageNode */ - protected override appendControlFlowStorageNode ( + protected override appendControlFlowStorageNode( hostNode: TNodeWithStatements, controlFlowStorageNode: ESTree.VariableDeclaration ): void { @@ -150,7 +148,7 @@ export class StringArrayControlFlowTransformer extends FunctionControlFlowTransf /** * @returns {boolean} */ - protected override isAllowedTransformationByThreshold (): boolean { + protected override isAllowedTransformationByThreshold(): boolean { return this.randomGenerator.getMathRandom() <= this.options.stringArrayCallsTransformThreshold; } } diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/AbstractControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/AbstractControlFlowReplacer.ts index fde1f972..e26e2fee 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/AbstractControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/AbstractControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -38,7 +38,7 @@ export abstract class AbstractControlFlowReplacer implements IControlFlowReplace /** * @type {Map>} */ - protected readonly replacerDataByControlFlowStorageId: Map > = new Map(); + protected readonly replacerDataByControlFlowStorageId: Map> = new Map(); /** * @param {TControlFlowCustomNodeFactory} controlFlowCustomNodeFactory @@ -46,11 +46,11 @@ export abstract class AbstractControlFlowReplacer implements IControlFlowReplace * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -67,7 +67,7 @@ export abstract class AbstractControlFlowReplacer implements IControlFlowReplace * @param {IControlFlowStorage} controlFlowStorage * @returns {string} */ - public generateStorageKey (controlFlowStorage: IControlFlowStorage): string { + public generateStorageKey(controlFlowStorage: IControlFlowStorage): string { const key: string = this.randomGenerator.getRandomString(5); if (controlFlowStorage.has(key)) { @@ -84,19 +84,19 @@ export abstract class AbstractControlFlowReplacer implements IControlFlowReplace * @param {number} usingExistingIdentifierChance * @returns {string} */ - protected insertCustomNodeToControlFlowStorage ( + protected insertCustomNodeToControlFlowStorage( customNode: ICustomNode, controlFlowStorage: IControlFlowStorage, replacerId: string | number, usingExistingIdentifierChance: number ): string { const controlFlowStorageId: string = controlFlowStorage.getStorageId(); - const storageKeysById: Map = this.replacerDataByControlFlowStorageId.get(controlFlowStorageId) - ?? new Map (); + const storageKeysById: Map = + this.replacerDataByControlFlowStorageId.get(controlFlowStorageId) ?? new Map(); const storageKeysForCurrentId: string[] = storageKeysById.get(replacerId) ?? []; - const shouldPickFromStorageKeysById = this.randomGenerator.getMathRandom() < usingExistingIdentifierChance - && storageKeysForCurrentId.length; + const shouldPickFromStorageKeysById = + this.randomGenerator.getMathRandom() < usingExistingIdentifierChance && storageKeysForCurrentId.length; if (shouldPickFromStorageKeysById) { return this.randomGenerator.getRandomGenerator().pickone(storageKeysForCurrentId); @@ -119,7 +119,7 @@ export abstract class AbstractControlFlowReplacer implements IControlFlowReplace * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - public abstract replace ( + public abstract replace( node: ESTree.Node, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/BinaryExpressionControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/BinaryExpressionControlFlowReplacer.ts index d92e2a53..af926ae0 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/BinaryExpressionControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/BinaryExpressionControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -30,20 +30,15 @@ export class BinaryExpressionControlFlowReplacer extends ExpressionWithOperatorC * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - controlFlowCustomNodeFactory, - identifierNamesGeneratorFactory, - randomGenerator, - options - ); + super(controlFlowCustomNodeFactory, identifierNamesGeneratorFactory, randomGenerator, options); } /** @@ -53,7 +48,7 @@ export class BinaryExpressionControlFlowReplacer extends ExpressionWithOperatorC * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - public replace ( + public replace( binaryExpressionNode: ESTree.BinaryExpression, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/CallExpressionControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/CallExpressionControlFlowReplacer.ts index 17e2bf4d..e6362c81 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/CallExpressionControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/CallExpressionControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -33,20 +33,15 @@ export class CallExpressionControlFlowReplacer extends AbstractControlFlowReplac * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - controlFlowCustomNodeFactory, - identifierNamesGeneratorFactory, - randomGenerator, - options - ); + super(controlFlowCustomNodeFactory, identifierNamesGeneratorFactory, randomGenerator, options); } /** @@ -55,7 +50,7 @@ export class CallExpressionControlFlowReplacer extends AbstractControlFlowReplac * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - public replace ( + public replace( callExpressionNode: ESTree.CallExpression, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage @@ -86,7 +81,7 @@ export class CallExpressionControlFlowReplacer extends AbstractControlFlowReplac controlFlowStorage.getStorageId(), storageKey, callee, - expressionArguments, + expressionArguments ); } @@ -97,7 +92,7 @@ export class CallExpressionControlFlowReplacer extends AbstractControlFlowReplac * @param {(Expression | SpreadElement)[]} expressionArguments * @returns {NodeGuards} */ - protected getControlFlowStorageCallNode ( + protected getControlFlowStorageCallNode( controlFlowStorageId: string, storageKey: string, callee: ESTree.Expression, @@ -111,7 +106,9 @@ export class CallExpressionControlFlowReplacer extends AbstractControlFlowReplac const statementNode: TStatement = controlFlowStorageCallCustomNode.getNode()[0]; if (!statementNode || !NodeGuards.isExpressionStatementNode(statementNode)) { - throw new Error('`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node'); + throw new Error( + '`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node' + ); } return statementNode.expression; diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/ExpressionWithOperatorControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/ExpressionWithOperatorControlFlowReplacer.ts index 88e5129f..be9604ff 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/ExpressionWithOperatorControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/ExpressionWithOperatorControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -26,20 +26,15 @@ export abstract class ExpressionWithOperatorControlFlowReplacer extends Abstract * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - controlFlowCustomNodeFactory, - identifierNamesGeneratorFactory, - randomGenerator, - options - ); + super(controlFlowCustomNodeFactory, identifierNamesGeneratorFactory, randomGenerator, options); } /** @@ -49,21 +44,24 @@ export abstract class ExpressionWithOperatorControlFlowReplacer extends Abstract * @param {Expression} rightExpression * @returns {NodeGuards} */ - protected getControlFlowStorageCallNode ( + protected getControlFlowStorageCallNode( controlFlowStorageId: string, storageKey: string, leftExpression: ESTree.Expression, rightExpression: ESTree.Expression ): ESTree.Node { - const controlFlowStorageCallCustomNode: ICustomNode> = - this.controlFlowCustomNodeFactory(ControlFlowCustomNode.ExpressionWithOperatorControlFlowStorageCallNode); + const controlFlowStorageCallCustomNode: ICustomNode< + TInitialData + > = this.controlFlowCustomNodeFactory(ControlFlowCustomNode.ExpressionWithOperatorControlFlowStorageCallNode); controlFlowStorageCallCustomNode.initialize(controlFlowStorageId, storageKey, leftExpression, rightExpression); const statementNode: TStatement = controlFlowStorageCallCustomNode.getNode()[0]; if (!statementNode || !NodeGuards.isExpressionStatementNode(statementNode)) { - throw new Error('`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node'); + throw new Error( + '`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node' + ); } return statementNode.expression; diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/LogicalExpressionControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/LogicalExpressionControlFlowReplacer.ts index ef24c3a6..d77f1c60 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/LogicalExpressionControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/LogicalExpressionControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -32,20 +32,15 @@ export class LogicalExpressionControlFlowReplacer extends ExpressionWithOperator * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - controlFlowCustomNodeFactory, - identifierNamesGeneratorFactory, - randomGenerator, - options - ); + super(controlFlowCustomNodeFactory, identifierNamesGeneratorFactory, randomGenerator, options); } /** @@ -54,7 +49,7 @@ export class LogicalExpressionControlFlowReplacer extends ExpressionWithOperator * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - public replace ( + public replace( logicalExpressionNode: ESTree.LogicalExpression, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage @@ -89,7 +84,10 @@ export class LogicalExpressionControlFlowReplacer extends ExpressionWithOperator * @param {Expression} rightExpression * @returns {boolean} */ - private checkForProhibitedExpressions (leftExpression: ESTree.Expression, rightExpression: ESTree.Expression): boolean { + private checkForProhibitedExpressions( + leftExpression: ESTree.Expression, + rightExpression: ESTree.Expression + ): boolean { return [leftExpression, rightExpression].some((expressionNode: ESTree.Node | ESTree.Expression): boolean => { let nodeForCheck: ESTree.Node | ESTree.Expression; @@ -99,10 +97,12 @@ export class LogicalExpressionControlFlowReplacer extends ExpressionWithOperator nodeForCheck = NodeUtils.getUnaryExpressionArgumentNode(expressionNode); } - return !NodeGuards.isLiteralNode(nodeForCheck) && + return ( + !NodeGuards.isLiteralNode(nodeForCheck) && !NodeGuards.isIdentifierNode(nodeForCheck) && !NodeGuards.isObjectExpressionNode(nodeForCheck) && - !NodeGuards.isExpressionStatementNode(nodeForCheck); + !NodeGuards.isExpressionStatementNode(nodeForCheck) + ); }); } } diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/StringArrayCallControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/StringArrayCallControlFlowReplacer.ts index 0c90ec33..ea534005 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/StringArrayCallControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/StringArrayCallControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -19,9 +19,7 @@ import { AbstractControlFlowReplacer } from './AbstractControlFlowReplacer'; import { NodeGuards } from '../../../node/NodeGuards'; import { NodeLiteralUtils } from '../../../node/NodeLiteralUtils'; import { NodeMetadata } from '../../../node/NodeMetadata'; -import { - StringLiteralControlFlowStorageCallNode -} from '../../../custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/StringLiteralControlFlowStorageCallNode'; +import { StringLiteralControlFlowStorageCallNode } from '../../../custom-nodes/control-flow-flattening-nodes/control-flow-storage-nodes/StringLiteralControlFlowStorageCallNode'; import { LiteralNode } from '../../../custom-nodes/control-flow-flattening-nodes/LiteralNode'; @injectable() @@ -37,20 +35,15 @@ export class StringArrayCallControlFlowReplacer extends AbstractControlFlowRepla * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - controlFlowCustomNodeFactory, - identifierNamesGeneratorFactory, - randomGenerator, - options - ); + super(controlFlowCustomNodeFactory, identifierNamesGeneratorFactory, randomGenerator, options); } /** @@ -59,24 +52,23 @@ export class StringArrayCallControlFlowReplacer extends AbstractControlFlowRepla * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - public override replace ( + public override replace( literalNode: ESTree.Literal, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage ): ESTree.Node { - const isStringArrayCallLiteralNode = NodeMetadata.isStringArrayCallLiteralNode(literalNode) - && ( - NodeLiteralUtils.isNumberLiteralNode(literalNode) - || NodeLiteralUtils.isStringLiteralNode(literalNode) - ); + const isStringArrayCallLiteralNode = + NodeMetadata.isStringArrayCallLiteralNode(literalNode) && + (NodeLiteralUtils.isNumberLiteralNode(literalNode) || NodeLiteralUtils.isStringLiteralNode(literalNode)); if (!isStringArrayCallLiteralNode) { return literalNode; } const replacerId: string | number = literalNode.value; - const literalCustomNode: ICustomNode> = - this.controlFlowCustomNodeFactory(ControlFlowCustomNode.LiteralNode); + const literalCustomNode: ICustomNode> = this.controlFlowCustomNodeFactory( + ControlFlowCustomNode.LiteralNode + ); literalCustomNode.initialize(literalNode); @@ -96,9 +88,8 @@ export class StringArrayCallControlFlowReplacer extends AbstractControlFlowRepla * @param {IControlFlowStorage} controlFlowStorage * @returns {string} */ - public override generateStorageKey (controlFlowStorage: IControlFlowStorage): string { - const key: string = this.identifierNamesGenerator - .generateForLabel(controlFlowStorage.getStorageId()); + public override generateStorageKey(controlFlowStorage: IControlFlowStorage): string { + const key: string = this.identifierNamesGenerator.generateForLabel(controlFlowStorage.getStorageId()); if (controlFlowStorage.has(key)) { return this.generateStorageKey(controlFlowStorage); @@ -112,10 +103,7 @@ export class StringArrayCallControlFlowReplacer extends AbstractControlFlowRepla * @param {string} storageKey * @returns {NodeGuards} */ - protected getControlFlowStorageCallNode ( - controlFlowStorageId: string, - storageKey: string - ): ESTree.Node { + protected getControlFlowStorageCallNode(controlFlowStorageId: string, storageKey: string): ESTree.Node { const controlFlowStorageCallCustomNode: ICustomNode> = this.controlFlowCustomNodeFactory(ControlFlowCustomNode.StringLiteralControlFlowStorageCallNode); @@ -124,7 +112,9 @@ export class StringArrayCallControlFlowReplacer extends AbstractControlFlowRepla const statementNode: TStatement = controlFlowStorageCallCustomNode.getNode()[0]; if (!statementNode || !NodeGuards.isExpressionStatementNode(statementNode)) { - throw new Error('`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node'); + throw new Error( + '`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node' + ); } return statementNode.expression; diff --git a/src/node-transformers/control-flow-transformers/control-flow-replacers/StringLiteralControlFlowReplacer.ts b/src/node-transformers/control-flow-transformers/control-flow-replacers/StringLiteralControlFlowReplacer.ts index 9ed65afa..f4de203e 100644 --- a/src/node-transformers/control-flow-transformers/control-flow-replacers/StringLiteralControlFlowReplacer.ts +++ b/src/node-transformers/control-flow-transformers/control-flow-replacers/StringLiteralControlFlowReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -34,20 +34,15 @@ export class StringLiteralControlFlowReplacer extends AbstractControlFlowReplace * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IControlFlowCustomNode) - controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, + controlFlowCustomNodeFactory: TControlFlowCustomNodeFactory, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { - super( - controlFlowCustomNodeFactory, - identifierNamesGeneratorFactory, - randomGenerator, - options - ); + super(controlFlowCustomNodeFactory, identifierNamesGeneratorFactory, randomGenerator, options); } /** @@ -56,7 +51,7 @@ export class StringLiteralControlFlowReplacer extends AbstractControlFlowReplace * @param {IControlFlowStorage} controlFlowStorage * @returns {Node} */ - public replace ( + public replace( literalNode: ESTree.Literal, parentNode: ESTree.Node, controlFlowStorage: IControlFlowStorage @@ -70,8 +65,9 @@ export class StringLiteralControlFlowReplacer extends AbstractControlFlowReplace } const replacerId: string = literalNode.value; - const literalCustomNode: ICustomNode> = - this.controlFlowCustomNodeFactory(ControlFlowCustomNode.LiteralNode); + const literalCustomNode: ICustomNode> = this.controlFlowCustomNodeFactory( + ControlFlowCustomNode.LiteralNode + ); literalCustomNode.initialize(literalNode); @@ -90,10 +86,7 @@ export class StringLiteralControlFlowReplacer extends AbstractControlFlowReplace * @param {string} storageKey * @returns {NodeGuards} */ - protected getControlFlowStorageCallNode ( - controlFlowStorageId: string, - storageKey: string - ): ESTree.Node { + protected getControlFlowStorageCallNode(controlFlowStorageId: string, storageKey: string): ESTree.Node { const controlFlowStorageCallCustomNode: ICustomNode> = this.controlFlowCustomNodeFactory(ControlFlowCustomNode.StringLiteralControlFlowStorageCallNode); @@ -102,7 +95,9 @@ export class StringLiteralControlFlowReplacer extends AbstractControlFlowReplace const statementNode: TStatement = controlFlowStorageCallCustomNode.getNode()[0]; if (!statementNode || !NodeGuards.isExpressionStatementNode(statementNode)) { - throw new Error('`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node'); + throw new Error( + '`controlFlowStorageCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node' + ); } return statementNode.expression; diff --git a/src/node-transformers/converting-transformers/BooleanLiteralTransformer.ts b/src/node-transformers/converting-transformers/BooleanLiteralTransformer.ts index ba09a60e..f1bc652b 100644 --- a/src/node-transformers/converting-transformers/BooleanLiteralTransformer.ts +++ b/src/node-transformers/converting-transformers/BooleanLiteralTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -20,7 +20,7 @@ export class BooleanLiteralTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -31,7 +31,7 @@ export class BooleanLiteralTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -60,7 +60,7 @@ export class BooleanLiteralTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { + public transformNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { if (typeof literalNode.value !== 'boolean') { return literalNode; } @@ -79,20 +79,14 @@ export class BooleanLiteralTransformer extends AbstractNodeTransformer { /** * @return {ESTree.UnaryExpression} */ - private getTrueUnaryExpressionNode (): ESTree.UnaryExpression { - return NodeFactory.unaryExpressionNode( - '!', - this.getFalseUnaryExpressionNode() - ); + private getTrueUnaryExpressionNode(): ESTree.UnaryExpression { + return NodeFactory.unaryExpressionNode('!', this.getFalseUnaryExpressionNode()); } /** * @return {ESTree.UnaryExpression} */ - private getFalseUnaryExpressionNode (): ESTree.UnaryExpression { - return NodeFactory.unaryExpressionNode( - '!', - NodeFactory.arrayExpressionNode() - ); + private getFalseUnaryExpressionNode(): ESTree.UnaryExpression { + return NodeFactory.unaryExpressionNode('!', NodeFactory.arrayExpressionNode()); } } diff --git a/src/node-transformers/converting-transformers/ClassFieldTransformer.ts b/src/node-transformers/converting-transformers/ClassFieldTransformer.ts index dba2ad1e..a8ef3ac5 100644 --- a/src/node-transformers/converting-transformers/ClassFieldTransformer.ts +++ b/src/node-transformers/converting-transformers/ClassFieldTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -39,7 +39,7 @@ export class ClassFieldTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -50,17 +50,14 @@ export class ClassFieldTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => { if ( - parentNode - && ( - NodeGuards.isMethodDefinitionNode(node) - || NodeGuards.isPropertyDefinitionNode(node) - ) + parentNode && + (NodeGuards.isMethodDefinitionNode(node) || NodeGuards.isPropertyDefinitionNode(node)) ) { return this.transformNode(node, parentNode); } @@ -77,7 +74,7 @@ export class ClassFieldTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode ( + public transformNode( classFieldNode: ESTree.MethodDefinition | ESTree.PropertyDefinition, parentNode: ESTree.Node ): ESTree.Node { @@ -97,14 +94,11 @@ export class ClassFieldTransformer extends AbstractNodeTransformer { * @param {Identifier} keyNode * @returns {MethodDefinition | PropertyDefinition} */ - private replaceIdentifierKey ( + private replaceIdentifierKey( classFieldNode: ESTree.MethodDefinition | ESTree.PropertyDefinition, keyNode: ESTree.Identifier ): ESTree.MethodDefinition | ESTree.PropertyDefinition { - if ( - !ClassFieldTransformer.ignoredNames.includes(keyNode.name) - && !classFieldNode.computed - ) { + if (!ClassFieldTransformer.ignoredNames.includes(keyNode.name) && !classFieldNode.computed) { classFieldNode.computed = true; classFieldNode.key = NodeFactory.literalNode(keyNode.name); } @@ -117,14 +111,14 @@ export class ClassFieldTransformer extends AbstractNodeTransformer { * @param {Literal} keyNode * @returns {MethodDefinition | PropertyDefinition} */ - private replaceLiteralKey ( + private replaceLiteralKey( classFieldNode: ESTree.MethodDefinition | ESTree.PropertyDefinition, keyNode: ESTree.Literal ): ESTree.MethodDefinition | ESTree.PropertyDefinition { if ( - typeof keyNode.value === 'string' - && !ClassFieldTransformer.ignoredNames.includes(keyNode.value) - && !classFieldNode.computed + typeof keyNode.value === 'string' && + !ClassFieldTransformer.ignoredNames.includes(keyNode.value) && + !classFieldNode.computed ) { classFieldNode.computed = true; } diff --git a/src/node-transformers/converting-transformers/ExportSpecifierTransformer.ts b/src/node-transformers/converting-transformers/ExportSpecifierTransformer.ts index 16a85332..fd49aad2 100644 --- a/src/node-transformers/converting-transformers/ExportSpecifierTransformer.ts +++ b/src/node-transformers/converting-transformers/ExportSpecifierTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -19,7 +19,7 @@ export class ExportSpecifierTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -30,7 +30,7 @@ export class ExportSpecifierTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -57,7 +57,7 @@ export class ExportSpecifierTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public transformNode (exportSpecifierNode: ESTree.ExportSpecifier, parentNode: ESTree.Node): ESTree.Node { + public transformNode(exportSpecifierNode: ESTree.ExportSpecifier, parentNode: ESTree.Node): ESTree.Node { if (exportSpecifierNode.local.name === exportSpecifierNode.exported.name) { exportSpecifierNode.exported = NodeUtils.clone(exportSpecifierNode.local); } diff --git a/src/node-transformers/converting-transformers/MemberExpressionTransformer.ts b/src/node-transformers/converting-transformers/MemberExpressionTransformer.ts index 73124499..bf1e9cd6 100644 --- a/src/node-transformers/converting-transformers/MemberExpressionTransformer.ts +++ b/src/node-transformers/converting-transformers/MemberExpressionTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -20,7 +20,7 @@ export class MemberExpressionTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -31,7 +31,7 @@ export class MemberExpressionTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -63,8 +63,11 @@ export class MemberExpressionTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (memberExpressionNode: ESTree.MemberExpression, parentNode: ESTree.Node): ESTree.Node { - if (NodeMetadata.isIgnoredNode(memberExpressionNode.object) || NodeMetadata.isIgnoredNode(memberExpressionNode.property)) { + public transformNode(memberExpressionNode: ESTree.MemberExpression, parentNode: ESTree.Node): ESTree.Node { + if ( + NodeMetadata.isIgnoredNode(memberExpressionNode.object) || + NodeMetadata.isIgnoredNode(memberExpressionNode.property) + ) { return memberExpressionNode; } diff --git a/src/node-transformers/converting-transformers/NumberLiteralTransformer.ts b/src/node-transformers/converting-transformers/NumberLiteralTransformer.ts index edf7e4ba..cc84588c 100644 --- a/src/node-transformers/converting-transformers/NumberLiteralTransformer.ts +++ b/src/node-transformers/converting-transformers/NumberLiteralTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -22,23 +22,19 @@ export class NumberLiteralTransformer extends AbstractNodeTransformer { * * @type {NodeTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.NumberToNumericalExpressionTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.NumberToNumericalExpressionTransformer]; /** * @type {Map} */ - private readonly numberLiteralCache: Map < - ESTree.SimpleLiteral['value'] | ESTree.BigIntLiteral['value'], - string - > = new Map(); + private readonly numberLiteralCache: Map = + new Map(); /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -49,7 +45,7 @@ export class NumberLiteralTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -76,7 +72,7 @@ export class NumberLiteralTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { + public transformNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { if (typeof literalNode.value !== 'number' && typeof literalNode.value !== 'bigint') { return literalNode; } diff --git a/src/node-transformers/converting-transformers/NumberToNumericalExpressionTransformer.ts b/src/node-transformers/converting-transformers/NumberToNumericalExpressionTransformer.ts index 117f78fc..8ceaa0bd 100644 --- a/src/node-transformers/converting-transformers/NumberToNumericalExpressionTransformer.ts +++ b/src/node-transformers/converting-transformers/NumberToNumericalExpressionTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -38,9 +38,9 @@ export class NumberToNumericalExpressionTransformer extends AbstractNodeTransfor * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.INumberNumericalExpressionAnalyzer) - numberNumericalExpressionAnalyzer: INumberNumericalExpressionAnalyzer, + numberNumericalExpressionAnalyzer: INumberNumericalExpressionAnalyzer, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -53,7 +53,7 @@ export class NumberToNumericalExpressionTransformer extends AbstractNodeTransfor * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.numbersToExpressions) { return null; } @@ -78,7 +78,7 @@ export class NumberToNumericalExpressionTransformer extends AbstractNodeTransfor * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { + public transformNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { if (typeof literalNode.value !== 'number') { return literalNode; } @@ -89,8 +89,8 @@ export class NumberToNumericalExpressionTransformer extends AbstractNodeTransfor const baseNumber: number = literalNode.value; const [integerPart, decimalPart] = NumberUtils.extractIntegerAndDecimalParts(baseNumber); - const integerNumberNumericalExpressionData: TNumberNumericalExpressionData = this.numberNumericalExpressionAnalyzer - .analyze( + const integerNumberNumericalExpressionData: TNumberNumericalExpressionData = + this.numberNumericalExpressionAnalyzer.analyze( integerPart, NumberNumericalExpressionAnalyzer.defaultAdditionalPartsCount ); @@ -114,14 +114,9 @@ export class NumberToNumericalExpressionTransformer extends AbstractNodeTransfor * @param {boolean} isPositiveNumber * @returns {Expression} */ - private getNumberNumericalExpressionLiteralNode (number: number, isPositiveNumber: boolean): ESTree.Expression { + private getNumberNumericalExpressionLiteralNode(number: number, isPositiveNumber: boolean): ESTree.Expression { const numberLiteralNode: ESTree.Literal = NodeFactory.literalNode(number); - return isPositiveNumber - ? numberLiteralNode - : NodeFactory.unaryExpressionNode( - '-', - numberLiteralNode - ); + return isPositiveNumber ? numberLiteralNode : NodeFactory.unaryExpressionNode('-', numberLiteralNode); } } diff --git a/src/node-transformers/converting-transformers/ObjectExpressionKeysTransformer.ts b/src/node-transformers/converting-transformers/ObjectExpressionKeysTransformer.ts index 20efc1d3..15ac0ae2 100644 --- a/src/node-transformers/converting-transformers/ObjectExpressionKeysTransformer.ts +++ b/src/node-transformers/converting-transformers/ObjectExpressionKeysTransformer.ts @@ -42,9 +42,9 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IObjectExpressionExtractor) - objectExpressionExtractorFactory: TObjectExpressionExtractorFactory, + objectExpressionExtractorFactory: TObjectExpressionExtractorFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -59,33 +59,33 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {Statement} objectExpressionHostStatement * @returns {boolean} */ - private static isProhibitedObjectExpressionNode ( + private static isProhibitedObjectExpressionNode( objectExpressionNode: ESTree.ObjectExpression, objectExpressionParentNode: ESTree.Node, objectExpressionHostStatement: ESTree.Statement ): boolean { - return ObjectExpressionKeysTransformer.isReferencedIdentifierName( + return ( + ObjectExpressionKeysTransformer.isReferencedIdentifierName( objectExpressionNode, objectExpressionHostStatement - ) - || ObjectExpressionKeysTransformer.isProhibitedArrowFunctionExpression( + ) || + ObjectExpressionKeysTransformer.isProhibitedArrowFunctionExpression( objectExpressionNode, objectExpressionParentNode - ) - || ObjectExpressionKeysTransformer.isObjectExpressionWithCallExpression( - objectExpressionNode, - ) - || ObjectExpressionKeysTransformer.isProhibitedSequenceExpression( + ) || + ObjectExpressionKeysTransformer.isObjectExpressionWithCallExpression(objectExpressionNode) || + ObjectExpressionKeysTransformer.isProhibitedSequenceExpression( objectExpressionNode, objectExpressionHostStatement - ); + ) + ); } /** * @param {Identifier | ThisExpression} node * @returns {string} */ - private static getReferencedIdentifierName (node: ESTree.Identifier | ESTree.ThisExpression): string { + private static getReferencedIdentifierName(node: ESTree.Identifier | ESTree.ThisExpression): string { if (NodeGuards.isIdentifierNode(node)) { return node.name; } else { @@ -98,9 +98,9 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {Node} objectExpressionHostNode * @returns {boolean} */ - private static isReferencedIdentifierName ( + private static isReferencedIdentifierName( objectExpressionNode: ESTree.ObjectExpression, - objectExpressionHostNode: ESTree.Node, + objectExpressionHostNode: ESTree.Node ): boolean { const identifierNamesSet: Set = new Set(); @@ -151,25 +151,27 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {Node} objectExpressionNodeParentNode * @returns {boolean} */ - private static isProhibitedArrowFunctionExpression ( + private static isProhibitedArrowFunctionExpression( objectExpressionNode: ESTree.ObjectExpression, objectExpressionNodeParentNode: ESTree.Node ): boolean { - return NodeGuards.isArrowFunctionExpressionNode(objectExpressionNodeParentNode) - && objectExpressionNodeParentNode.body === objectExpressionNode; + return ( + NodeGuards.isArrowFunctionExpressionNode(objectExpressionNodeParentNode) && + objectExpressionNodeParentNode.body === objectExpressionNode + ); } /** * @param {ObjectExpression} objectExpressionNode * @returns {boolean} */ - private static isObjectExpressionWithCallExpression (objectExpressionNode: ESTree.ObjectExpression): boolean { + private static isObjectExpressionWithCallExpression(objectExpressionNode: ESTree.ObjectExpression): boolean { let isCallExpressionLikeNodeFound: boolean = false; estraverse.traverse(objectExpressionNode, { enter: (node: ESTree.Node): void | estraverse.VisitorOption => { - const isCallExpressionLikeNode = NodeGuards.isCallExpressionNode(node) - || NodeGuards.isNewExpressionNode(node); + const isCallExpressionLikeNode = + NodeGuards.isCallExpressionNode(node) || NodeGuards.isNewExpressionNode(node); if (!isCallExpressionLikeNode) { return; @@ -189,23 +191,25 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {Node} objectExpressionHostNode * @returns {boolean} */ - private static isProhibitedSequenceExpression ( + private static isProhibitedSequenceExpression( objectExpressionNode: ESTree.ObjectExpression, - objectExpressionHostNode: ESTree.Node, + objectExpressionHostNode: ESTree.Node ): boolean { - return NodeGuards.isExpressionStatementNode(objectExpressionHostNode) - && NodeGuards.isSequenceExpressionNode(objectExpressionHostNode.expression) - && objectExpressionHostNode.expression.expressions.some((expressionNode: ESTree.Expression) => - NodeGuards.isCallExpressionNode(expressionNode) - && NodeGuards.isSuperNode(expressionNode.callee) - ); + return ( + NodeGuards.isExpressionStatementNode(objectExpressionHostNode) && + NodeGuards.isSequenceExpressionNode(objectExpressionHostNode.expression) && + objectExpressionHostNode.expression.expressions.some( + (expressionNode: ESTree.Expression) => + NodeGuards.isCallExpressionNode(expressionNode) && NodeGuards.isSuperNode(expressionNode.callee) + ) + ); } /** * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.transformObjectKeys) { return null; } @@ -214,10 +218,7 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { case NodeTransformationStage.Converting: return { leave: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => { - if ( - parentNode - && NodeGuards.isObjectExpressionNode(node) - ) { + if (parentNode && NodeGuards.isObjectExpressionNode(node)) { return this.transformNode(node, parentNode); } } @@ -245,18 +246,20 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {NodeGuards} */ - public transformNode (objectExpressionNode: ESTree.ObjectExpression, parentNode: ESTree.Node): ESTree.Node { + public transformNode(objectExpressionNode: ESTree.ObjectExpression, parentNode: ESTree.Node): ESTree.Node { if (!objectExpressionNode.properties.length) { return objectExpressionNode; } const hostStatement: ESTree.Statement = NodeStatementUtils.getRootStatementOfNode(objectExpressionNode); - if (ObjectExpressionKeysTransformer.isProhibitedObjectExpressionNode( - objectExpressionNode, - parentNode, - hostStatement - )) { + if ( + ObjectExpressionKeysTransformer.isProhibitedObjectExpressionNode( + objectExpressionNode, + parentNode, + hostStatement + ) + ) { return objectExpressionNode; } @@ -273,7 +276,7 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { * @param {Statement} hostStatement * @returns {Node} */ - private applyObjectExpressionKeysExtractorsRecursive ( + private applyObjectExpressionKeysExtractorsRecursive( objectExpressionExtractorNames: ObjectExpressionExtractor[], objectExpressionNode: ESTree.ObjectExpression, hostStatement: ESTree.Statement @@ -290,8 +293,10 @@ export class ObjectExpressionKeysTransformer extends AbstractNodeTransformer { nodeToReplace, objectExpressionHostStatement: newObjectExpressionHostStatement, objectExpressionNode: newObjectExpressionNode - } = this.objectExpressionExtractorFactory(objectExpressionExtractor) - .extract(objectExpressionNode, hostStatement); + } = this.objectExpressionExtractorFactory(objectExpressionExtractor).extract( + objectExpressionNode, + hostStatement + ); this.applyObjectExpressionKeysExtractorsRecursive( newObjectExpressionExtractorNames, diff --git a/src/node-transformers/converting-transformers/ObjectExpressionTransformer.ts b/src/node-transformers/converting-transformers/ObjectExpressionTransformer.ts index b6981d07..828c60dd 100644 --- a/src/node-transformers/converting-transformers/ObjectExpressionTransformer.ts +++ b/src/node-transformers/converting-transformers/ObjectExpressionTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -26,7 +26,7 @@ export class ObjectExpressionTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -37,7 +37,7 @@ export class ObjectExpressionTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -58,23 +58,22 @@ export class ObjectExpressionTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (objectExpressionNode: ESTree.ObjectExpression, parentNode: ESTree.Node): ESTree.Node { - objectExpressionNode.properties - .forEach((property: ESTree.Property | ESTree.SpreadElement) => { - if (!NodeGuards.isPropertyNode(property)) { - return; - } + public transformNode(objectExpressionNode: ESTree.ObjectExpression, parentNode: ESTree.Node): ESTree.Node { + objectExpressionNode.properties.forEach((property: ESTree.Property | ESTree.SpreadElement) => { + if (!NodeGuards.isPropertyNode(property)) { + return; + } - if (!property.key) { - return; - } + if (!property.key) { + return; + } - if (property.computed) { - this.transformComputedProperty(property); - } else { - this.transformBaseProperty(property); - } - }); + if (property.computed) { + this.transformComputedProperty(property); + } else { + this.transformBaseProperty(property); + } + }); return objectExpressionNode; } @@ -82,7 +81,7 @@ export class ObjectExpressionTransformer extends AbstractNodeTransformer { /** * @param {Property} property */ - private transformComputedProperty (property: ESTree.Property): void { + private transformComputedProperty(property: ESTree.Property): void { if (!NodeGuards.isLiteralNode(property.key) || !(typeof property.key.value === 'string')) { return; } @@ -93,7 +92,7 @@ export class ObjectExpressionTransformer extends AbstractNodeTransformer { /** * @param {Property} property */ - private transformBaseProperty (property: ESTree.Property): void { + private transformBaseProperty(property: ESTree.Property): void { if (property.shorthand) { property.shorthand = false; } diff --git a/src/node-transformers/converting-transformers/ObjectPatternPropertiesTransformer.ts b/src/node-transformers/converting-transformers/ObjectPatternPropertiesTransformer.ts index 690da5ce..d4a80e39 100644 --- a/src/node-transformers/converting-transformers/ObjectPatternPropertiesTransformer.ts +++ b/src/node-transformers/converting-transformers/ObjectPatternPropertiesTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -22,7 +22,7 @@ export class ObjectPatternPropertiesTransformer extends AbstractNodeTransformer * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -33,7 +33,7 @@ export class ObjectPatternPropertiesTransformer extends AbstractNodeTransformer * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -60,14 +60,15 @@ export class ObjectPatternPropertiesTransformer extends AbstractNodeTransformer * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (propertyNode: ESTree.Property, parentNode: ESTree.Node): ESTree.Node { + public transformNode(propertyNode: ESTree.Property, parentNode: ESTree.Node): ESTree.Node { if (!NodeGuards.isObjectPatternNode(parentNode) || !propertyNode.shorthand) { return propertyNode; } if (!this.options.renameGlobals) { const lexicalScope: TNodeWithLexicalScope | undefined = NodeLexicalScopeUtils.getLexicalScope(propertyNode); - const shouldNotTransformGlobalPropertyNode: boolean = !!lexicalScope && NodeGuards.isProgramNode(lexicalScope); + const shouldNotTransformGlobalPropertyNode: boolean = + !!lexicalScope && NodeGuards.isProgramNode(lexicalScope); if (shouldNotTransformGlobalPropertyNode) { return propertyNode; diff --git a/src/node-transformers/converting-transformers/SplitStringTransformer.ts b/src/node-transformers/converting-transformers/SplitStringTransformer.ts index 8bf62e68..2481cd35 100644 --- a/src/node-transformers/converting-transformers/SplitStringTransformer.ts +++ b/src/node-transformers/converting-transformers/SplitStringTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -40,7 +40,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -53,21 +53,13 @@ export class SplitStringTransformer extends AbstractNodeTransformer { * @param {number} chunkSize * @returns {string[]} */ - private static chunkString ( - string: string, - stringLength: number, - chunkSize: number - ): string[] { + private static chunkString(string: string, stringLength: number, chunkSize: number): string[] { const chunksCount: number = Math.ceil(stringLength / chunkSize); const chunks: string[] = []; let nextChunkStartIndex: number = 0; - for ( - let chunkIndex: number = 0; - chunkIndex < chunksCount; - ++chunkIndex, nextChunkStartIndex += chunkSize - ) { + for (let chunkIndex: number = 0; chunkIndex < chunksCount; ++chunkIndex, nextChunkStartIndex += chunkSize) { // eslint-disable-next-line unicorn/prefer-string-slice chunks[chunkIndex] = stringz.substr(string, nextChunkStartIndex, chunkSize); } @@ -79,7 +71,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.splitStrings) { return null; } @@ -107,7 +99,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public transformNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { + public transformNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { if (NodeLiteralUtils.isProhibitedLiteralNode(literalNode, parentNode)) { return literalNode; } @@ -123,10 +115,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { // eslint-disable-next-line @typescript-eslint/no-shadow enter: (node: ESTree.Node, parentNode: ESTree.Node | null) => { if (NodeGuards.isLiteralNode(node)) { - return this.transformLiteralNodeByChunkLength( - node, - this.options.splitStringsChunkLength - ); + return this.transformLiteralNodeByChunkLength(node, this.options.splitStringsChunkLength); } } }); @@ -142,10 +131,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { * @param {number} chunkLength * @returns {Node} */ - private transformLiteralNodeByChunkLength ( - literalNode: ESTree.Literal, - chunkLength: number - ): ESTree.Node { + private transformLiteralNodeByChunkLength(literalNode: ESTree.Literal, chunkLength: number): ESTree.Node { if (!NodeLiteralUtils.isStringLiteralNode(literalNode)) { return literalNode; } @@ -156,11 +142,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { return literalNode; } - const stringChunks: string[] = SplitStringTransformer.chunkString( - literalNode.value, - valueLength, - chunkLength - ); + const stringChunks: string[] = SplitStringTransformer.chunkString(literalNode.value, valueLength, chunkLength); return this.transformStringChunksToBinaryExpressionNode(stringChunks); } @@ -169,7 +151,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { * @param {string[]} chunks * @returns {BinaryExpression} */ - private transformStringChunksToBinaryExpressionNode (chunks: string[]): ESTree.BinaryExpression { + private transformStringChunksToBinaryExpressionNode(chunks: string[]): ESTree.BinaryExpression { const firstChunk: string | undefined = chunks.shift(); const secondChunk: string | undefined = chunks.shift(); @@ -187,11 +169,7 @@ export class SplitStringTransformer extends AbstractNodeTransformer { (binaryExpressionNode: ESTree.BinaryExpression, chunk: string) => { const chunkLiteralNode: ESTree.Literal = NodeFactory.literalNode(chunk); - return NodeFactory.binaryExpressionNode( - '+', - binaryExpressionNode, - chunkLiteralNode - ); + return NodeFactory.binaryExpressionNode('+', binaryExpressionNode, chunkLiteralNode); }, initialBinaryExpressionNode ); diff --git a/src/node-transformers/converting-transformers/TemplateLiteralTransformer.ts b/src/node-transformers/converting-transformers/TemplateLiteralTransformer.ts index a6637463..ae684a59 100644 --- a/src/node-transformers/converting-transformers/TemplateLiteralTransformer.ts +++ b/src/node-transformers/converting-transformers/TemplateLiteralTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -24,7 +24,7 @@ export class TemplateLiteralTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -35,7 +35,7 @@ export class TemplateLiteralTransformer extends AbstractNodeTransformer { * @param {NodeGuards} node * @returns {boolean} */ - private static isLiteralNodeWithStringValue (node: ESTree.Node | undefined): boolean { + private static isLiteralNodeWithStringValue(node: ESTree.Node | undefined): boolean { return !!node && NodeGuards.isLiteralNode(node) && typeof node.value === 'string'; } @@ -43,7 +43,7 @@ export class TemplateLiteralTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Converting: return { @@ -64,7 +64,7 @@ export class TemplateLiteralTransformer extends AbstractNodeTransformer { * @param {ESTree.Node} parentNode * @returns {ESTree.Node} */ - public transformNode (templateLiteralNode: ESTree.TemplateLiteral, parentNode: ESTree.Node): ESTree.Node { + public transformNode(templateLiteralNode: ESTree.TemplateLiteral, parentNode: ESTree.Node): ESTree.Node { if (NodeGuards.isTaggedTemplateExpressionNode(parentNode)) { return templateLiteralNode; } @@ -77,7 +77,10 @@ export class TemplateLiteralTransformer extends AbstractNodeTransformer { * @param {ESTree.Node} parentNode * @returns {ESTree.Expression} */ - private transformTemplateLiteralNode (templateLiteralNode: ESTree.TemplateLiteral, parentNode: ESTree.Node): ESTree.Expression { + private transformTemplateLiteralNode( + templateLiteralNode: ESTree.TemplateLiteral, + parentNode: ESTree.Node + ): ESTree.Expression { const templateLiteralExpressions: ESTree.Expression[] = templateLiteralNode.expressions; let nodes: ESTree.Expression[] = []; diff --git a/src/node-transformers/converting-transformers/object-expression-extractors/BasePropertiesExtractor.ts b/src/node-transformers/converting-transformers/object-expression-extractors/BasePropertiesExtractor.ts index ee45587a..4eea6ae2 100644 --- a/src/node-transformers/converting-transformers/object-expression-extractors/BasePropertiesExtractor.ts +++ b/src/node-transformers/converting-transformers/object-expression-extractors/BasePropertiesExtractor.ts @@ -19,15 +19,12 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {Property} propertyNode * @returns {string | null} */ - private static getPropertyNodeKeyName (propertyNode: ESTree.Property): string | null { + private static getPropertyNodeKeyName(propertyNode: ESTree.Property): string | null { const propertyKeyNode: ESTree.Expression | ESTree.PrivateIdentifier = propertyNode.key; if ( - NodeGuards.isLiteralNode(propertyKeyNode) - && ( - typeof propertyKeyNode.value === 'string' - || typeof propertyKeyNode.value === 'number' - ) + NodeGuards.isLiteralNode(propertyKeyNode) && + (typeof propertyKeyNode.value === 'string' || typeof propertyKeyNode.value === 'number') ) { return propertyKeyNode.value.toString(); } @@ -43,7 +40,7 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {Property} node * @returns {boolean} */ - private static isProhibitedPropertyNode (node: ESTree.Property): boolean { + private static isProhibitedPropertyNode(node: ESTree.Property): boolean { return node.kind !== 'init'; } @@ -51,21 +48,22 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {Node} node * @returns {propertyValueNode is Pattern} */ - private static isProhibitedPattern (node: ESTree.Node): node is ESTree.Pattern { - return !node - || NodeGuards.isObjectPatternNode(node) - || NodeGuards.isArrayPatternNode(node) - || NodeGuards.isAssignmentPatternNode(node) - || NodeGuards.isRestElementNode(node); + private static isProhibitedPattern(node: ESTree.Node): node is ESTree.Pattern { + return ( + !node || + NodeGuards.isObjectPatternNode(node) || + NodeGuards.isArrayPatternNode(node) || + NodeGuards.isAssignmentPatternNode(node) || + NodeGuards.isRestElementNode(node) + ); } /** * @param {Property} property * @returns {boolean} */ - private static shouldCreateLiteralNode (property: ESTree.Property): boolean { - return !property.computed - || (property.computed && !!property.key && NodeGuards.isLiteralNode(property.key)); + private static shouldCreateLiteralNode(property: ESTree.Property): boolean { + return !property.computed || (property.computed && !!property.key && NodeGuards.isLiteralNode(property.key)); } /** @@ -84,17 +82,13 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {Statement} hostStatement * @returns {IObjectExpressionExtractorResult} */ - public extract ( + public extract( objectExpressionNode: ESTree.ObjectExpression, hostStatement: ESTree.Statement ): IObjectExpressionExtractorResult { const hostNode: ESTree.Node | undefined = objectExpressionNode.parentNode; - if ( - hostNode - && NodeGuards.isVariableDeclaratorNode(hostNode) - && NodeGuards.isIdentifierNode(hostNode.id) - ) { + if (hostNode && NodeGuards.isVariableDeclaratorNode(hostNode) && NodeGuards.isIdentifierNode(hostNode.id)) { return this.transformObjectExpressionNode(objectExpressionNode, hostStatement, hostNode.id); } @@ -111,18 +105,14 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {Expression} memberExpressionHostNode * @returns {IObjectExpressionExtractorResult} */ - private transformObjectExpressionNode ( + private transformObjectExpressionNode( objectExpressionNode: ESTree.ObjectExpression, hostStatement: ESTree.Statement, memberExpressionHostNode: ESTree.Expression ): IObjectExpressionExtractorResult { const properties: (ESTree.Property | ESTree.SpreadElement)[] = objectExpressionNode.properties; - const [expressionStatements, removablePropertyIds]: [ESTree.ExpressionStatement[], number[]] = this - .extractPropertiesToExpressionStatements( - properties, - hostStatement, - memberExpressionHostNode - ); + const [expressionStatements, removablePropertyIds]: [ESTree.ExpressionStatement[], number[]] = + this.extractPropertiesToExpressionStatements(properties, hostStatement, memberExpressionHostNode); const hostNodeWithStatements: TNodeWithStatements = NodeStatementUtils.getScopeOfNode(hostStatement); @@ -147,7 +137,7 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {Expression} memberExpressionHostNode * @returns {[ExpressionStatement[], number[]]} */ - private extractPropertiesToExpressionStatements ( + private extractPropertiesToExpressionStatements( properties: (ESTree.Property | ESTree.SpreadElement)[], hostStatement: ESTree.Statement, memberExpressionHostNode: ESTree.Expression @@ -158,7 +148,7 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { // have to iterate in the reversed order to fast check spread elements and break iteration on them for (let i: number = propertiesLength - 1; i >= 0; i--) { - const property: (ESTree.Property | ESTree.SpreadElement) = properties[i]; + const property: ESTree.Property | ESTree.SpreadElement = properties[i]; // spread element if (NodeGuards.isSpreadElementNode(property)) { @@ -192,8 +182,11 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { const memberExpressionProperty: ESTree.Expression = shouldCreateLiteralNode ? NodeFactory.literalNode(propertyKeyName) : NodeFactory.identifierNode(propertyKeyName); - const memberExpressionNode: ESTree.MemberExpression = NodeFactory - .memberExpressionNode(memberExpressionHostNode, memberExpressionProperty, true); + const memberExpressionNode: ESTree.MemberExpression = NodeFactory.memberExpressionNode( + memberExpressionHostNode, + memberExpressionProperty, + true + ); const expressionStatementNode: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( NodeFactory.assignmentExpressionNode('=', memberExpressionNode, propertyValue) ); @@ -219,13 +212,12 @@ export class BasePropertiesExtractor implements IObjectExpressionExtractor { * @param {ObjectExpression} objectExpressionNode * @param {number[]} removablePropertyIds */ - private filterExtractedObjectExpressionProperties ( + private filterExtractedObjectExpressionProperties( objectExpressionNode: ESTree.ObjectExpression, removablePropertyIds: number[] ): void { - objectExpressionNode.properties = objectExpressionNode.properties - .filter((property: ESTree.Property | ESTree.SpreadElement, index: number) => - !removablePropertyIds.includes(index) - ); + objectExpressionNode.properties = objectExpressionNode.properties.filter( + (property: ESTree.Property | ESTree.SpreadElement, index: number) => !removablePropertyIds.includes(index) + ); } } diff --git a/src/node-transformers/converting-transformers/object-expression-extractors/ObjectExpressionToVariableDeclarationExtractor.ts b/src/node-transformers/converting-transformers/object-expression-extractors/ObjectExpressionToVariableDeclarationExtractor.ts index 2ec99f9c..94158935 100644 --- a/src/node-transformers/converting-transformers/object-expression-extractors/ObjectExpressionToVariableDeclarationExtractor.ts +++ b/src/node-transformers/converting-transformers/object-expression-extractors/ObjectExpressionToVariableDeclarationExtractor.ts @@ -32,9 +32,9 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx /** * @param {TObjectExpressionKeysTransformerCustomNodeFactory} objectExpressionKeysTransformerCustomNodeFactory */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IObjectExpressionKeysTransformerCustomNode) - objectExpressionKeysTransformerCustomNodeFactory: TObjectExpressionKeysTransformerCustomNodeFactory, + objectExpressionKeysTransformerCustomNodeFactory: TObjectExpressionKeysTransformerCustomNodeFactory ) { this.objectExpressionKeysTransformerCustomNodeFactory = objectExpressionKeysTransformerCustomNodeFactory; } @@ -57,14 +57,11 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx * @param {Statement} hostStatement * @returns {IObjectExpressionExtractorResult} */ - public extract ( + public extract( objectExpressionNode: ESTree.ObjectExpression, hostStatement: ESTree.Statement ): IObjectExpressionExtractorResult { - return this.transformObjectExpressionToVariableDeclaration( - objectExpressionNode, - hostStatement - ); + return this.transformObjectExpressionToVariableDeclaration(objectExpressionNode, hostStatement); } /** @@ -72,14 +69,14 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx * @param {Statement} hostStatement * @returns {Node} */ - private transformObjectExpressionToVariableDeclaration ( + private transformObjectExpressionToVariableDeclaration( objectExpressionNode: ESTree.ObjectExpression, hostStatement: ESTree.Statement ): IObjectExpressionExtractorResult { const hostNodeWithStatements: TNodeWithStatements = NodeStatementUtils.getScopeOfNode(hostStatement); const lexicalScopeNode: TNodeWithLexicalScope | null = NodeGuards.isNodeWithLexicalScope(hostNodeWithStatements) ? hostNodeWithStatements - : NodeLexicalScopeUtils.getLexicalScope(hostNodeWithStatements) ?? null; + : (NodeLexicalScopeUtils.getLexicalScope(hostNodeWithStatements) ?? null); if (!lexicalScopeNode) { throw new Error('Cannot find lexical scope node for the host statement node'); @@ -97,8 +94,12 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx NodeUtils.parentizeAst(newObjectExpressionHostStatement); NodeUtils.parentizeNode(newObjectExpressionHostStatement, hostNodeWithStatements); - const newObjectExpressionIdentifier: ESTree.Identifier = this.getObjectExpressionIdentifierNode(newObjectExpressionHostStatement); - const newObjectExpressionNode: ESTree.ObjectExpression = this.getObjectExpressionNode(newObjectExpressionHostStatement); + const newObjectExpressionIdentifier: ESTree.Identifier = this.getObjectExpressionIdentifierNode( + newObjectExpressionHostStatement + ); + const newObjectExpressionNode: ESTree.ObjectExpression = this.getObjectExpressionNode( + newObjectExpressionHostStatement + ); return { nodeToReplace: newObjectExpressionIdentifier, @@ -112,24 +113,24 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx * @param {(Property | SpreadElement)[]} properties * @returns {VariableDeclaration} */ - private getObjectExpressionHostNode ( + private getObjectExpressionHostNode( lexicalScopeNode: TNodeWithLexicalScope, properties: (ESTree.Property | ESTree.SpreadElement)[] ): ESTree.VariableDeclaration { - const variableDeclarationHostNodeCustomNode: ICustomNode> = - this.objectExpressionKeysTransformerCustomNodeFactory( - ObjectExpressionKeysTransformerCustomNode.ObjectExpressionVariableDeclarationHostNode - ); + const variableDeclarationHostNodeCustomNode: ICustomNode< + TInitialData + > = this.objectExpressionKeysTransformerCustomNodeFactory( + ObjectExpressionKeysTransformerCustomNode.ObjectExpressionVariableDeclarationHostNode + ); variableDeclarationHostNodeCustomNode.initialize(lexicalScopeNode, properties); const statementNode: TStatement = variableDeclarationHostNodeCustomNode.getNode()[0]; - if ( - !statementNode - || !NodeGuards.isVariableDeclarationNode(statementNode) - ) { - throw new Error('`objectExpressionHostCustomNode.getNode()[0]` should returns array with `VariableDeclaration` node'); + if (!statementNode || !NodeGuards.isVariableDeclarationNode(statementNode)) { + throw new Error( + '`objectExpressionHostCustomNode.getNode()[0]` should returns array with `VariableDeclaration` node' + ); } return statementNode; @@ -139,11 +140,13 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx * @param {VariableDeclaration} objectExpressionHostNode * @returns {Identifier} */ - private getObjectExpressionIdentifierNode (objectExpressionHostNode: ESTree.VariableDeclaration): ESTree.Identifier { + private getObjectExpressionIdentifierNode(objectExpressionHostNode: ESTree.VariableDeclaration): ESTree.Identifier { const newObjectExpressionIdentifierNode: ESTree.Pattern = objectExpressionHostNode.declarations[0].id; if (!NodeGuards.isIdentifierNode(newObjectExpressionIdentifierNode)) { - throw new Error('`objectExpressionHostNode` should contain `VariableDeclarator` node with `Identifier` id property'); + throw new Error( + '`objectExpressionHostNode` should contain `VariableDeclarator` node with `Identifier` id property' + ); } return newObjectExpressionIdentifierNode; @@ -153,11 +156,13 @@ export class ObjectExpressionToVariableDeclarationExtractor implements IObjectEx * @param {VariableDeclaration} objectExpressionHostNode * @returns {Identifier} */ - private getObjectExpressionNode (objectExpressionHostNode: ESTree.VariableDeclaration): ESTree.ObjectExpression { + private getObjectExpressionNode(objectExpressionHostNode: ESTree.VariableDeclaration): ESTree.ObjectExpression { const newObjectExpressionNode: ESTree.Expression | null = objectExpressionHostNode.declarations[0].init ?? null; if (!newObjectExpressionNode || !NodeGuards.isObjectExpressionNode(newObjectExpressionNode)) { - throw new Error('`objectExpressionHostNode` should contain `VariableDeclarator` node with `ObjectExpression` init property'); + throw new Error( + '`objectExpressionHostNode` should contain `VariableDeclarator` node with `ObjectExpression` init property' + ); } return newObjectExpressionNode; diff --git a/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionIdentifiersTransformer.ts b/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionIdentifiersTransformer.ts index 8a1d99d0..04044b2a 100644 --- a/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionIdentifiersTransformer.ts +++ b/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionIdentifiersTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as eslintScope from 'eslint-scope'; @@ -39,7 +39,7 @@ export class DeadCodeInjectionIdentifiersTransformer extends AbstractNodeTransfo * @param {IOptions} options * @param {IScopeIdentifiersTraverser} scopeIdentifiersTraverser */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IIdentifierReplacer) identifierReplacer: IIdentifierReplacer, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @@ -55,7 +55,7 @@ export class DeadCodeInjectionIdentifiersTransformer extends AbstractNodeTransfo * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.RenameIdentifiers: return { @@ -76,15 +76,12 @@ export class DeadCodeInjectionIdentifiersTransformer extends AbstractNodeTransfo * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { + public transformNode(programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { this.scopeIdentifiersTraverser.traverseScopeThroughIdentifiers( programNode, parentNode, (data: IScopeThroughIdentifiersTraverserCallbackData) => { - const { - reference, - variableLexicalScopeNode - } = data; + const { reference, variableLexicalScopeNode } = data; this.transformScopeThroughIdentifiers(reference, variableLexicalScopeNode); } @@ -97,9 +94,9 @@ export class DeadCodeInjectionIdentifiersTransformer extends AbstractNodeTransfo * @param {Reference} reference * @param {TNodeWithLexicalScope} lexicalScopeNode */ - private transformScopeThroughIdentifiers ( + private transformScopeThroughIdentifiers( reference: eslintScope.Reference, - lexicalScopeNode: TNodeWithLexicalScope, + lexicalScopeNode: TNodeWithLexicalScope ): void { if (reference.resolved) { return; @@ -115,10 +112,7 @@ export class DeadCodeInjectionIdentifiersTransformer extends AbstractNodeTransfo * @param {Identifier} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - private storeIdentifierName ( - identifierNode: ESTree.Identifier, - lexicalScopeNode: TNodeWithLexicalScope - ): void { + private storeIdentifierName(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void { this.identifierReplacer.storeLocalName(identifierNode, lexicalScopeNode); } @@ -127,13 +121,12 @@ export class DeadCodeInjectionIdentifiersTransformer extends AbstractNodeTransfo * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {Variable} reference */ - private replaceIdentifierName ( + private replaceIdentifierName( identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope, reference: eslintScope.Reference ): void { - const newIdentifier: ESTree.Identifier = this.identifierReplacer - .replace(identifierNode, lexicalScopeNode); + const newIdentifier: ESTree.Identifier = this.identifierReplacer.replace(identifierNode, lexicalScopeNode); // rename of identifier reference.identifier.name = newIdentifier.name; diff --git a/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.ts b/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.ts index d1fd7bb1..d9508e32 100644 --- a/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.ts +++ b/src/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -56,7 +56,7 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { /** * @type {WeakSet } */ - private readonly deadCodeInjectionRootAstHostNodeSet: WeakSet = new WeakSet(); + private readonly deadCodeInjectionRootAstHostNodeSet: WeakSet = new WeakSet(); /** * @type {ESTree.BlockStatement[]} @@ -84,9 +84,9 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IDeadCodeInjectionCustomNode) - deadCodeInjectionCustomNodeFactory: TDeadNodeInjectionCustomNodeFactory, + deadCodeInjectionCustomNodeFactory: TDeadNodeInjectionCustomNodeFactory, @inject(ServiceIdentifiers.INodeTransformersRunner) transformersRunner: INodeTransformersRunner, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -101,22 +101,24 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {Node} targetNode * @returns {boolean} */ - private static isProhibitedNodeInsideCollectedBlockStatement (targetNode: ESTree.Node): boolean { - return NodeGuards.isFunctionDeclarationNode(targetNode) // can break code on strict mode - || NodeGuards.isBreakStatementNode(targetNode) - || NodeGuards.isContinueStatementNode(targetNode) - || NodeGuards.isAwaitExpressionNode(targetNode) - || NodeGuards.isYieldExpressionNode(targetNode) - || NodeGuards.isSuperNode(targetNode) - || (NodeGuards.isForOfStatementNode(targetNode) && targetNode.await) - || NodeGuards.isPrivateIdentifierNode(targetNode); + private static isProhibitedNodeInsideCollectedBlockStatement(targetNode: ESTree.Node): boolean { + return ( + NodeGuards.isFunctionDeclarationNode(targetNode) || // can break code on strict mode + NodeGuards.isBreakStatementNode(targetNode) || + NodeGuards.isContinueStatementNode(targetNode) || + NodeGuards.isAwaitExpressionNode(targetNode) || + NodeGuards.isYieldExpressionNode(targetNode) || + NodeGuards.isSuperNode(targetNode) || + (NodeGuards.isForOfStatementNode(targetNode) && targetNode.await) || + NodeGuards.isPrivateIdentifierNode(targetNode) + ); } /** * @param {Node} targetNode * @returns {boolean} */ - private static isScopeHoistingFunctionDeclaration (targetNode: ESTree.Node): boolean { + private static isScopeHoistingFunctionDeclaration(targetNode: ESTree.Node): boolean { if (!NodeGuards.isFunctionDeclarationNode(targetNode)) { return false; } @@ -154,7 +156,7 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {BlockStatement} blockStatementNode * @returns {boolean} */ - private static isValidCollectedBlockStatementNode (blockStatementNode: ESTree.BlockStatement): boolean { + private static isValidCollectedBlockStatementNode(blockStatementNode: ESTree.BlockStatement): boolean { if (!blockStatementNode.body.length) { return false; } @@ -169,9 +171,9 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { } if ( - nestedBlockStatementsCount > DeadCodeInjectionTransformer.maxNestedBlockStatementsCount - || DeadCodeInjectionTransformer.isProhibitedNodeInsideCollectedBlockStatement(node) - || DeadCodeInjectionTransformer.isScopeHoistingFunctionDeclaration(node) + nestedBlockStatementsCount > DeadCodeInjectionTransformer.maxNestedBlockStatementsCount || + DeadCodeInjectionTransformer.isProhibitedNodeInsideCollectedBlockStatement(node) || + DeadCodeInjectionTransformer.isScopeHoistingFunctionDeclaration(node) ) { isValidBlockStatementNode = false; @@ -188,7 +190,10 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {boolean} */ - private static isValidWrappedBlockStatementNode (blockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node): boolean { + private static isValidWrappedBlockStatementNode( + blockStatementNode: ESTree.BlockStatement, + parentNode: ESTree.Node + ): boolean { /** * Special case for ignoring all EvalHost nodes that are added by EvalCallExpressionTransformer * So, all content of eval expressions should not be affected by dead code injection @@ -217,8 +222,8 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { return false; } - const parentNodeWithStatements: TNodeWithStatements = NodeStatementUtils - .getParentNodeWithStatements(blockStatementNode); + const parentNodeWithStatements: TNodeWithStatements = + NodeStatementUtils.getParentNodeWithStatements(blockStatementNode); return parentNodeWithStatements.type !== NodeType.Program; } @@ -227,7 +232,7 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.DeadCodeInjection: return { @@ -253,7 +258,7 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { enter: ( node: ESTree.Node, parentNode: ESTree.Node | null - ): ESTree.Node | estraverse.VisitorOption |undefined => { + ): ESTree.Node | estraverse.VisitorOption | undefined => { if (parentNode && this.isDeadCodeInjectionRootAstHostNode(node)) { return this.restoreNode(node, parentNode); } @@ -269,7 +274,7 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {NodeGuards} programNode * @param {NodeGuards} parentNode */ - public prepareNode (programNode: ESTree.Node, parentNode: ESTree.Node): void { + public prepareNode(programNode: ESTree.Node, parentNode: ESTree.Node): void { estraverse.traverse(programNode, { enter: (node: ESTree.Node): void => { if (!NodeGuards.isBlockStatementNode(node)) { @@ -300,20 +305,21 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards | VisitorOption} */ - public transformNode ( + public transformNode( blockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node ): ESTree.Node | estraverse.VisitorOption { - const canBreakTraverse: boolean = !this.collectedBlockStatements.length - || this.collectedBlockStatementsTotalLength < DeadCodeInjectionTransformer.minCollectedBlockStatementsCount; + const canBreakTraverse: boolean = + !this.collectedBlockStatements.length || + this.collectedBlockStatementsTotalLength < DeadCodeInjectionTransformer.minCollectedBlockStatementsCount; if (canBreakTraverse) { return estraverse.VisitorOption.Break; } if ( - this.randomGenerator.getMathRandom() > this.options.deadCodeInjectionThreshold - || !DeadCodeInjectionTransformer.isValidWrappedBlockStatementNode(blockStatementNode, parentNode) + this.randomGenerator.getMathRandom() > this.options.deadCodeInjectionThreshold || + !DeadCodeInjectionTransformer.isValidWrappedBlockStatementNode(blockStatementNode, parentNode) ) { return blockStatementNode; } @@ -336,11 +342,13 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public restoreNode (deadCodeInjectionRootAstHostNode: ESTree.BlockStatement, parentNode: ESTree.Node): ESTree.Node { + public restoreNode(deadCodeInjectionRootAstHostNode: ESTree.BlockStatement, parentNode: ESTree.Node): ESTree.Node { const hostNodeFirstStatement: ESTree.Statement = deadCodeInjectionRootAstHostNode.body[0]; if (!NodeGuards.isFunctionDeclarationNode(hostNodeFirstStatement)) { - throw new Error('Wrong dead code injection root AST host node. Host node should contain `FunctionDeclaration` node'); + throw new Error( + 'Wrong dead code injection root AST host node. Host node should contain `FunctionDeclaration` node' + ); } return hostNodeFirstStatement.body; @@ -350,8 +358,9 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {Node} node * @returns {boolean} */ - private isDeadCodeInjectionRootAstHostNode (node: ESTree.Node): node is ESTree.BlockStatement { - const isDeadCodeInjectionRootAstHostNode = NodeGuards.isBlockStatementNode(node) && this.deadCodeInjectionRootAstHostNodeSet.has(node); + private isDeadCodeInjectionRootAstHostNode(node: ESTree.Node): node is ESTree.BlockStatement { + const isDeadCodeInjectionRootAstHostNode = + NodeGuards.isBlockStatementNode(node) && this.deadCodeInjectionRootAstHostNodeSet.has(node); if (isDeadCodeInjectionRootAstHostNode) { this.deadCodeInjectionRootAstHostNodeSet.delete(node); @@ -366,12 +375,10 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {BlockStatement} clonedBlockStatementNode * @returns {BlockStatement} */ - private makeClonedBlockStatementNodeUnique (clonedBlockStatementNode: ESTree.BlockStatement): ESTree.BlockStatement { + private makeClonedBlockStatementNodeUnique(clonedBlockStatementNode: ESTree.BlockStatement): ESTree.BlockStatement { // should wrap cloned block statement node into function node for correct scope encapsulation const hostNode: ESTree.Program = NodeFactory.programNode([ - NodeFactory.expressionStatementNode( - NodeFactory.functionExpressionNode([], clonedBlockStatementNode) - ) + NodeFactory.expressionStatementNode(NodeFactory.functionExpressionNode([], clonedBlockStatementNode)) ]); NodeUtils.parentizeAst(hostNode); @@ -392,7 +399,7 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {BlockStatement} */ - private replaceBlockStatementNode ( + private replaceBlockStatementNode( blockStatementNode: ESTree.BlockStatement, randomBlockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node @@ -415,12 +422,15 @@ export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { */ this.deadCodeInjectionRootAstHostNodeSet.add(deadCodeInjectionRootAstHostNode); - const blockStatementDeadCodeInjectionCustomNode: ICustomNode> = - this.deadCodeInjectionCustomNodeFactory(DeadCodeInjectionCustomNode.BlockStatementDeadCodeInjectionNode); + const blockStatementDeadCodeInjectionCustomNode: ICustomNode< + TInitialData + > = this.deadCodeInjectionCustomNodeFactory(DeadCodeInjectionCustomNode.BlockStatementDeadCodeInjectionNode); blockStatementDeadCodeInjectionCustomNode.initialize(blockStatementNode, deadCodeInjectionRootAstHostNode); - const newBlockStatementNode: ESTree.BlockStatement = blockStatementDeadCodeInjectionCustomNode.getNode()[0]; + const newBlockStatementNode: ESTree.BlockStatement = ( + blockStatementDeadCodeInjectionCustomNode.getNode()[0] + ); NodeUtils.parentizeNode(newBlockStatementNode, parentNode); diff --git a/src/node-transformers/finalizing-transformers/DirectivePlacementTransformer.ts b/src/node-transformers/finalizing-transformers/DirectivePlacementTransformer.ts index 5da2ffb5..63f41477 100644 --- a/src/node-transformers/finalizing-transformers/DirectivePlacementTransformer.ts +++ b/src/node-transformers/finalizing-transformers/DirectivePlacementTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -28,25 +28,23 @@ export class DirectivePlacementTransformer extends AbstractNodeTransformer { /** * @type {NodeTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.CustomCodeHelpersTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.CustomCodeHelpersTransformer]; /** * @type {WeakMap} */ - private readonly lexicalScopeDirectives: WeakMap< + private readonly lexicalScopeDirectives: WeakMap = new WeakMap< TNodeWithLexicalScope, ESTree.Directive - > = new WeakMap(); + >(); /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, - @inject(ServiceIdentifiers.IOptions) options: IOptions, + @inject(ServiceIdentifiers.IOptions) options: IOptions ) { super(randomGenerator, options); } @@ -55,7 +53,7 @@ export class DirectivePlacementTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -91,7 +89,7 @@ export class DirectivePlacementTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {TNodeWithLexicalScopeStatements} */ - public analyzeNode ( + public analyzeNode( nodeWithLexicalScopeStatements: TNodeWithLexicalScopeStatements, parentNode: ESTree.Node ): TNodeWithLexicalScopeStatements { @@ -113,7 +111,7 @@ export class DirectivePlacementTransformer extends AbstractNodeTransformer { * @param {Node | null} parentNode * @returns {TNodeWithLexicalScope} */ - public transformNode ( + public transformNode( nodeWithLexicalScopeStatements: TNodeWithLexicalScopeStatements, parentNode: ESTree.Node ): TNodeWithLexicalScopeStatements { diff --git a/src/node-transformers/finalizing-transformers/EscapeSequenceTransformer.ts b/src/node-transformers/finalizing-transformers/EscapeSequenceTransformer.ts index ee59d17c..19dde7df 100644 --- a/src/node-transformers/finalizing-transformers/EscapeSequenceTransformer.ts +++ b/src/node-transformers/finalizing-transformers/EscapeSequenceTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -22,9 +22,7 @@ export class EscapeSequenceTransformer extends AbstractNodeTransformer { /** * @type {NodeTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.CustomCodeHelpersTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.CustomCodeHelpersTransformer]; /** * @type {IEscapeSequenceEncoder} @@ -36,7 +34,7 @@ export class EscapeSequenceTransformer extends AbstractNodeTransformer { * @param {IOptions} options * @param {IEscapeSequenceEncoder} escapeSequenceEncoder */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @inject(ServiceIdentifiers.IEscapeSequenceEncoder) escapeSequenceEncoder: IEscapeSequenceEncoder @@ -50,7 +48,7 @@ export class EscapeSequenceTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Finalizing: return { @@ -71,7 +69,7 @@ export class EscapeSequenceTransformer extends AbstractNodeTransformer { * @param {Node | null} parentNode * @returns {Literal} */ - public transformNode (literalNode: ESTree.Literal, parentNode: ESTree.Node | null): ESTree.Literal { + public transformNode(literalNode: ESTree.Literal, parentNode: ESTree.Node | null): ESTree.Literal { if (!NodeLiteralUtils.isStringLiteralNode(literalNode)) { return literalNode; } diff --git a/src/node-transformers/initializing-transformers/CommentsTransformer.ts b/src/node-transformers/initializing-transformers/CommentsTransformer.ts index f3f861e6..d3877052 100644 --- a/src/node-transformers/initializing-transformers/CommentsTransformer.ts +++ b/src/node-transformers/initializing-transformers/CommentsTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -19,16 +19,13 @@ export class CommentsTransformer extends AbstractNodeTransformer { /** * @type {string[]} */ - private static readonly preservedWords: string[] = [ - '@license', - '@preserve' - ]; + private static readonly preservedWords: string[] = ['@license', '@preserve']; /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -39,7 +36,7 @@ export class CommentsTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Initializing: return { @@ -67,7 +64,7 @@ export class CommentsTransformer extends AbstractNodeTransformer { /** * Moves comments to their nodes */ - public transformNode (rootNode: ESTree.Program): ESTree.Node { + public transformNode(rootNode: ESTree.Program): ESTree.Node { rootNode = this.filterCommentsOnPrimaryTraverse(rootNode); if (!rootNode.comments?.length) { @@ -94,13 +91,14 @@ export class CommentsTransformer extends AbstractNodeTransformer { return; } - const commentIdx: number = comments.findIndex((comment: ESTree.Comment) => - comment.range && node.range && comment.range[0] < node.range[0] + const commentIdx: number = comments.findIndex( + (comment: ESTree.Comment) => comment.range && node.range && comment.range[0] < node.range[0] ); if (commentIdx >= 0) { - (isFirstNode ? rootNode : node).leadingComments = - comments.splice(commentIdx, comments.length - commentIdx).reverse(); + (isFirstNode ? rootNode : node).leadingComments = comments + .splice(commentIdx, comments.length - commentIdx) + .reverse(); } isFirstNode = false; @@ -121,10 +119,8 @@ export class CommentsTransformer extends AbstractNodeTransformer { * @param {ESTree.Program} rootNode * @returns {ESTree.Program} */ - private filterCommentsOnPrimaryTraverse (rootNode: ESTree.Program): ESTree.Program { - rootNode.comments = rootNode.comments?.filter((comment: ESTree.Comment) => - this.filterComment(comment, true) - ); + private filterCommentsOnPrimaryTraverse(rootNode: ESTree.Program): ESTree.Program { + rootNode.comments = rootNode.comments?.filter((comment: ESTree.Comment) => this.filterComment(comment, true)); return rootNode; } @@ -135,7 +131,7 @@ export class CommentsTransformer extends AbstractNodeTransformer { * @param {ESTree.Program} rootNode * @returns {ESTree.Program} */ - private filterCommentsOnFinalizingTraverse (rootNode: ESTree.Program): ESTree.Program { + private filterCommentsOnFinalizingTraverse(rootNode: ESTree.Program): ESTree.Program { estraverse.replace(rootNode, { enter: (node: ESTree.Node): ESTree.Node => { if (node.leadingComments) { @@ -162,12 +158,13 @@ export class CommentsTransformer extends AbstractNodeTransformer { * @param {boolean} keepConditionalComment * @returns {boolean} */ - private filterComment (comment: ESTree.Comment, keepConditionalComment: boolean): boolean { + private filterComment(comment: ESTree.Comment, keepConditionalComment: boolean): boolean { if (keepConditionalComment && ConditionalCommentObfuscatingGuard.isConditionalComment(comment)) { return true; } - return CommentsTransformer.preservedWords - .some((preservedWord: string) => comment.value.includes(preservedWord)); + return CommentsTransformer.preservedWords.some((preservedWord: string) => + comment.value.includes(preservedWord) + ); } } diff --git a/src/node-transformers/preparing-transformers/CustomCodeHelpersTransformer.ts b/src/node-transformers/preparing-transformers/CustomCodeHelpersTransformer.ts index e3deb6fb..b8cc19c4 100644 --- a/src/node-transformers/preparing-transformers/CustomCodeHelpersTransformer.ts +++ b/src/node-transformers/preparing-transformers/CustomCodeHelpersTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -60,10 +60,10 @@ export class CustomCodeHelpersTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.ICallsGraphAnalyzer) callsGraphAnalyzer: ICallsGraphAnalyzer, @inject(ServiceIdentifiers.IPrevailingKindOfVariablesAnalyzer) - prevailingKindOfVariablesAnalyzer: IPrevailingKindOfVariablesAnalyzer, + prevailingKindOfVariablesAnalyzer: IPrevailingKindOfVariablesAnalyzer, @inject(ServiceIdentifiers.TCustomNodeGroupStorage) customCodeHelperGroupStorage: TCustomCodeHelperGroupStorage, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -79,7 +79,7 @@ export class CustomCodeHelpersTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -110,7 +110,7 @@ export class CustomCodeHelpersTransformer extends AbstractNodeTransformer { * @param {Program} node * @param {Node | null} parentNode */ - public prepareNode (node: ESTree.Program, parentNode: ESTree.Node | null): void { + public prepareNode(node: ESTree.Program, parentNode: ESTree.Node | null): void { this.callsGraphData = this.callsGraphAnalyzer.analyze(node); this.prevailingKindOfVariablesAnalyzer.analyze(node); } @@ -120,7 +120,7 @@ export class CustomCodeHelpersTransformer extends AbstractNodeTransformer { * @param {Node | null} parentNode * @returns {Node} */ - public transformNode (node: ESTree.Program, parentNode: ESTree.Node | null): ESTree.Node { + public transformNode(node: ESTree.Program, parentNode: ESTree.Node | null): ESTree.Node { return node; } @@ -128,13 +128,11 @@ export class CustomCodeHelpersTransformer extends AbstractNodeTransformer { * @param {Program} node * @param {Node | null} parentNode */ - private appendCustomNodesForPreparingStage (node: ESTree.Program, parentNode: ESTree.Node | null): void { - this.customCodeHelperGroupStorage - .getStorage() - .forEach((customCodeHelperGroup: ICustomCodeHelperGroup) => { - customCodeHelperGroup.initialize(); - customCodeHelperGroup.appendOnPreparingStage?.(node, this.callsGraphData); - }); + private appendCustomNodesForPreparingStage(node: ESTree.Program, parentNode: ESTree.Node | null): void { + this.customCodeHelperGroupStorage.getStorage().forEach((customCodeHelperGroup: ICustomCodeHelperGroup) => { + customCodeHelperGroup.initialize(); + customCodeHelperGroup.appendOnPreparingStage?.(node, this.callsGraphData); + }); } /** @@ -142,17 +140,15 @@ export class CustomCodeHelpersTransformer extends AbstractNodeTransformer { * @param {Program} node * @param {Node | null} parentNode */ - private appendCustomNodesForStage ( + private appendCustomNodesForStage( nodeTransformationStage: NodeTransformationStage, node: ESTree.Program, parentNode: ESTree.Node | null ): void { - this.customCodeHelperGroupStorage - .getStorage() - .forEach((customCodeHelperGroup: ICustomCodeHelperGroup) => { - const methodName: TCustomCodeHelpersGroupAppendMethodName = `appendOn${nodeTransformationStage}Stage`; + this.customCodeHelperGroupStorage.getStorage().forEach((customCodeHelperGroup: ICustomCodeHelperGroup) => { + const methodName: TCustomCodeHelpersGroupAppendMethodName = `appendOn${nodeTransformationStage}Stage`; - customCodeHelperGroup[methodName]?.(node, this.callsGraphData); - }); + customCodeHelperGroup[methodName]?.(node, this.callsGraphData); + }); } } diff --git a/src/node-transformers/preparing-transformers/EvalCallExpressionTransformer.ts b/src/node-transformers/preparing-transformers/EvalCallExpressionTransformer.ts index f762fe44..137a4557 100644 --- a/src/node-transformers/preparing-transformers/EvalCallExpressionTransformer.ts +++ b/src/node-transformers/preparing-transformers/EvalCallExpressionTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -32,7 +32,7 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -43,15 +43,15 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {Expression | SpreadElement} node * @returns {string | null} */ - private static extractEvalStringFromCallExpressionArgument (node: ESTree.Expression | ESTree.SpreadElement): string | null { + private static extractEvalStringFromCallExpressionArgument( + node: ESTree.Expression | ESTree.SpreadElement + ): string | null { if (NodeGuards.isLiteralNode(node)) { - return EvalCallExpressionTransformer - .extractEvalStringFromLiteralNode(node); + return EvalCallExpressionTransformer.extractEvalStringFromLiteralNode(node); } if (NodeGuards.isTemplateLiteralNode(node)) { - return EvalCallExpressionTransformer - .extractEvalStringFromTemplateLiteralNode(node); + return EvalCallExpressionTransformer.extractEvalStringFromTemplateLiteralNode(node); } return null; @@ -61,7 +61,7 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {Literal} node * @returns {string | null} */ - private static extractEvalStringFromLiteralNode (node: ESTree.Literal): string | null { + private static extractEvalStringFromLiteralNode(node: ESTree.Literal): string | null { return typeof node.value === 'string' ? node.value : null; } @@ -69,7 +69,7 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {TemplateLiteral} node * @returns {string | null} */ - private static extractEvalStringFromTemplateLiteralNode (node: ESTree.TemplateLiteral): string | null { + private static extractEvalStringFromTemplateLiteralNode(node: ESTree.TemplateLiteral): string | null { const quasis: ESTree.TemplateElement[] = node.quasis; const allowedQuasisLength: number = 1; @@ -84,7 +84,7 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -114,11 +114,12 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public transformNode (node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node { - const isEvalCallExpressionNode = parentNode - && NodeGuards.isCallExpressionNode(node) - && NodeGuards.isIdentifierNode(node.callee) - && node.callee.name === 'eval'; + public transformNode(node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node { + const isEvalCallExpressionNode = + parentNode && + NodeGuards.isCallExpressionNode(node) && + NodeGuards.isIdentifierNode(node.callee) && + node.callee.name === 'eval'; if (!isEvalCallExpressionNode) { return node; @@ -130,8 +131,9 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { return node; } - const evalString: string | null = EvalCallExpressionTransformer - .extractEvalStringFromCallExpressionArgument(evalCallExpressionFirstArgument); + const evalString: string | null = EvalCallExpressionTransformer.extractEvalStringFromCallExpressionArgument( + evalCallExpressionFirstArgument + ); if (!evalString) { return node; @@ -150,8 +152,10 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * we should wrap AST-tree into the parent function expression node (ast root host node). * This function expression node will help to correctly transform AST-tree. */ - const evalRootAstHostNode: ESTree.FunctionExpression = NodeFactory - .functionExpressionNode([], NodeFactory.blockStatementNode(ast)); + const evalRootAstHostNode: ESTree.FunctionExpression = NodeFactory.functionExpressionNode( + [], + NodeFactory.blockStatementNode(ast) + ); NodeMetadata.set(evalRootAstHostNode, { evalHostNode: true }); @@ -166,7 +170,7 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public restoreNode (node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node { + public restoreNode(node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node { if (!this.isEvalRootAstHostNode(node)) { return node; } @@ -174,19 +178,16 @@ export class EvalCallExpressionTransformer extends AbstractNodeTransformer { const targetAst: ESTree.Statement[] = node.body.body; const obfuscatedCode: string = NodeUtils.convertStructureToCode(targetAst); - return NodeFactory.callExpressionNode( - NodeFactory.identifierNode('eval'), - [ - NodeFactory.literalNode(StringUtils.escapeJsString(obfuscatedCode)) - ] - ); + return NodeFactory.callExpressionNode(NodeFactory.identifierNode('eval'), [ + NodeFactory.literalNode(StringUtils.escapeJsString(obfuscatedCode)) + ]); } /** * @param {Node} node * @returns {boolean} */ - private isEvalRootAstHostNode (node: ESTree.Node): node is ESTree.FunctionExpression { + private isEvalRootAstHostNode(node: ESTree.Node): node is ESTree.FunctionExpression { return NodeMetadata.isEvalHostNode(node); } } diff --git a/src/node-transformers/preparing-transformers/MetadataTransformer.ts b/src/node-transformers/preparing-transformers/MetadataTransformer.ts index 0df45daf..dd916c8b 100644 --- a/src/node-transformers/preparing-transformers/MetadataTransformer.ts +++ b/src/node-transformers/preparing-transformers/MetadataTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -31,7 +31,7 @@ export class MetadataTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -42,7 +42,7 @@ export class MetadataTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -61,7 +61,7 @@ export class MetadataTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public transformNode (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node { + public transformNode(node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node { NodeMetadata.set(node, { ignoredNode: false }); if (NodeGuards.isLiteralNode(node)) { diff --git a/src/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.ts b/src/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.ts index dad6fc5d..c05f019b 100644 --- a/src/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.ts +++ b/src/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -54,7 +54,7 @@ export class ObfuscatingGuardsTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__INodeGuard) obfuscatingGuardFactory: TObfuscatingGuardFactory, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -68,7 +68,7 @@ export class ObfuscatingGuardsTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -87,9 +87,10 @@ export class ObfuscatingGuardsTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public transformNode (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node { - const obfuscatingGuardResults: ObfuscatingGuardResult[] = this.obfuscatingGuards - .map((obfuscatingGuard: IObfuscatingGuard) => obfuscatingGuard.check(node)); + public transformNode(node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node { + const obfuscatingGuardResults: ObfuscatingGuardResult[] = this.obfuscatingGuards.map( + (obfuscatingGuard: IObfuscatingGuard) => obfuscatingGuard.check(node) + ); this.setNodeMetadata(node, obfuscatingGuardResults); @@ -100,18 +101,18 @@ export class ObfuscatingGuardsTransformer extends AbstractNodeTransformer { * @param {Node} node * @param {ObfuscatingGuardResult[]} obfuscatingGuardResults */ - private setNodeMetadata (node: ESTree.Node, obfuscatingGuardResults: ObfuscatingGuardResult[]): void { - const isTransformNode: boolean = obfuscatingGuardResults - .every((obfuscatingGuardResult: ObfuscatingGuardResult) => obfuscatingGuardResult === ObfuscatingGuardResult.Transform); + private setNodeMetadata(node: ESTree.Node, obfuscatingGuardResults: ObfuscatingGuardResult[]): void { + const isTransformNode: boolean = obfuscatingGuardResults.every( + (obfuscatingGuardResult: ObfuscatingGuardResult) => + obfuscatingGuardResult === ObfuscatingGuardResult.Transform + ); let isForceTransformNode: boolean = false; let isIgnoredNode: boolean = false; if (!isTransformNode) { - isForceTransformNode = obfuscatingGuardResults - .includes(ObfuscatingGuardResult.ForceTransform); - isIgnoredNode = !isForceTransformNode && obfuscatingGuardResults - .includes(ObfuscatingGuardResult.Ignore); + isForceTransformNode = obfuscatingGuardResults.includes(ObfuscatingGuardResult.ForceTransform); + isIgnoredNode = !isForceTransformNode && obfuscatingGuardResults.includes(ObfuscatingGuardResult.Ignore); } NodeMetadata.set(node, { diff --git a/src/node-transformers/preparing-transformers/ParentificationTransformer.ts b/src/node-transformers/preparing-transformers/ParentificationTransformer.ts index 21ffd8df..4e2f2760 100644 --- a/src/node-transformers/preparing-transformers/ParentificationTransformer.ts +++ b/src/node-transformers/preparing-transformers/ParentificationTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -21,7 +21,7 @@ export class ParentificationTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -32,7 +32,7 @@ export class ParentificationTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -51,7 +51,7 @@ export class ParentificationTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {Node} */ - public transformNode (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node { + public transformNode(node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node { return NodeUtils.parentizeNode(node, parentNode); } } diff --git a/src/node-transformers/preparing-transformers/VariablePreserveTransformer.ts b/src/node-transformers/preparing-transformers/VariablePreserveTransformer.ts index 68232d50..dc932610 100644 --- a/src/node-transformers/preparing-transformers/VariablePreserveTransformer.ts +++ b/src/node-transformers/preparing-transformers/VariablePreserveTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import * as ESTree from 'estree'; import * as eslintScope from 'eslint-scope'; @@ -26,9 +26,7 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { /** * @type {NodeTransformer.ParentificationTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.ParentificationTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.ParentificationTransformer]; /** * @type {IIdentifierReplacer} @@ -46,7 +44,7 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { * @param {IOptions} options * @param {IScopeIdentifiersTraverser} scopeIdentifiersTraverser */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IIdentifierReplacer) identifierReplacer: IIdentifierReplacer, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @@ -64,7 +62,7 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: case NodeTransformationStage.Converting: @@ -87,7 +85,7 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { + public transformNode(programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { this.scopeIdentifiersTraverser.traverseScopeIdentifiers( programNode, parentNode, @@ -100,13 +98,8 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { /** * @param {IScopeIdentifiersTraverserCallbackData} data */ - private preserveScopeVariableIdentifiers (data: IScopeIdentifiersTraverserCallbackData): void { - const { - isGlobalDeclaration, - isBubblingDeclaration, - variable, - variableScope - } = data; + private preserveScopeVariableIdentifiers(data: IScopeIdentifiersTraverserCallbackData): void { + const { isGlobalDeclaration, isBubblingDeclaration, variable, variableScope } = data; for (const identifier of variable.identifiers) { if (isGlobalDeclaration || isBubblingDeclaration) { @@ -120,7 +113,7 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { /** * @param {Identifier} identifierNode */ - private preserveIdentifierNameForRootLexicalScope (identifierNode: ESTree.Identifier): void { + private preserveIdentifierNameForRootLexicalScope(identifierNode: ESTree.Identifier): void { this.identifierReplacer.preserveName(identifierNode); } @@ -128,7 +121,7 @@ export class VariablePreserveTransformer extends AbstractNodeTransformer { * @param {Identifier} identifierNode * @param {Scope} variableScope */ - private preserveIdentifierNameForLexicalScope ( + private preserveIdentifierNameForLexicalScope( identifierNode: ESTree.Identifier, variableScope: eslintScope.Scope ): void { diff --git a/src/node-transformers/preparing-transformers/obfuscating-guards/BlackListObfuscatingGuard.ts b/src/node-transformers/preparing-transformers/obfuscating-guards/BlackListObfuscatingGuard.ts index 2f0b7e3e..eb82e905 100644 --- a/src/node-transformers/preparing-transformers/obfuscating-guards/BlackListObfuscatingGuard.ts +++ b/src/node-transformers/preparing-transformers/obfuscating-guards/BlackListObfuscatingGuard.ts @@ -13,16 +13,14 @@ export class BlackListObfuscatingGuard implements IObfuscatingGuard { /** * @type {((node: Node) => boolean)[]} */ - private static readonly blackListGuards: ((node: ESTree.Node) => boolean)[] = [ - NodeGuards.isDirectiveNode - ]; + private static readonly blackListGuards: ((node: ESTree.Node) => boolean)[] = [NodeGuards.isDirectiveNode]; /** * @type {number} */ private readonly blackListGuardsLength: number; - public constructor () { + public constructor() { this.blackListGuardsLength = BlackListObfuscatingGuard.blackListGuards.length; } @@ -30,7 +28,7 @@ export class BlackListObfuscatingGuard implements IObfuscatingGuard { * @param {Node} node * @returns {ObfuscatingGuardResult} */ - public check (node: ESTree.Node): ObfuscatingGuardResult { + public check(node: ESTree.Node): ObfuscatingGuardResult { for (let i: number = 0; i < this.blackListGuardsLength; i++) { if (BlackListObfuscatingGuard.blackListGuards[i](node)) { return ObfuscatingGuardResult.Ignore; diff --git a/src/node-transformers/preparing-transformers/obfuscating-guards/ConditionalCommentObfuscatingGuard.ts b/src/node-transformers/preparing-transformers/obfuscating-guards/ConditionalCommentObfuscatingGuard.ts index e001b371..cc934a2b 100644 --- a/src/node-transformers/preparing-transformers/obfuscating-guards/ConditionalCommentObfuscatingGuard.ts +++ b/src/node-transformers/preparing-transformers/obfuscating-guards/ConditionalCommentObfuscatingGuard.ts @@ -29,16 +29,18 @@ export class ConditionalCommentObfuscatingGuard implements IObfuscatingGuard { * @param {Comment} comment * @returns {boolean} */ - public static isConditionalComment (comment: ESTree.Comment): boolean { - return ConditionalCommentObfuscatingGuard.obfuscationEnableCommentRegExp.test(comment.value) || - ConditionalCommentObfuscatingGuard.obfuscationDisableCommentRegExp.test(comment.value); + public static isConditionalComment(comment: ESTree.Comment): boolean { + return ( + ConditionalCommentObfuscatingGuard.obfuscationEnableCommentRegExp.test(comment.value) || + ConditionalCommentObfuscatingGuard.obfuscationDisableCommentRegExp.test(comment.value) + ); } /** * @param {Node} node * @returns {ObfuscatingGuardResult} */ - public check (node: ESTree.Node): ObfuscatingGuardResult { + public check(node: ESTree.Node): ObfuscatingGuardResult { if (NodeGuards.isNodeWithComments(node)) { const leadingComments: ESTree.Comment[] | undefined = node.leadingComments; @@ -47,16 +49,14 @@ export class ConditionalCommentObfuscatingGuard implements IObfuscatingGuard { } } - return this.obfuscationAllowed - ? ObfuscatingGuardResult.Transform - : ObfuscatingGuardResult.Ignore; + return this.obfuscationAllowed ? ObfuscatingGuardResult.Transform : ObfuscatingGuardResult.Ignore; } /** * @param {Comment[]} comments * @returns {boolean} */ - private checkComments (comments: ESTree.Comment[]): boolean { + private checkComments(comments: ESTree.Comment[]): boolean { const commentsLength: number = comments.length; let obfuscationAllowed: boolean = this.obfuscationAllowed; diff --git a/src/node-transformers/preparing-transformers/obfuscating-guards/ForceTransformStringObfuscatingGuard.ts b/src/node-transformers/preparing-transformers/obfuscating-guards/ForceTransformStringObfuscatingGuard.ts index d4a066ad..b3f70a26 100644 --- a/src/node-transformers/preparing-transformers/obfuscating-guards/ForceTransformStringObfuscatingGuard.ts +++ b/src/node-transformers/preparing-transformers/obfuscating-guards/ForceTransformStringObfuscatingGuard.ts @@ -21,9 +21,7 @@ export class ForceTransformStringObfuscatingGuard implements IObfuscatingGuard { /** * @param {IOptions} options */ - public constructor ( - @inject(ServiceIdentifiers.IOptions) options: IOptions - ) { + public constructor(@inject(ServiceIdentifiers.IOptions) options: IOptions) { this.options = options; } @@ -31,11 +29,11 @@ export class ForceTransformStringObfuscatingGuard implements IObfuscatingGuard { * @param {Node} node * @returns {ObfuscatingGuardResult} */ - public check (node: ESTree.Node): ObfuscatingGuardResult { + public check(node: ESTree.Node): ObfuscatingGuardResult { if ( - this.options.forceTransformStrings.length - && NodeGuards.isLiteralNode(node) - && typeof node.value === 'string' + this.options.forceTransformStrings.length && + NodeGuards.isLiteralNode(node) && + typeof node.value === 'string' ) { return !this.isForceTransformString(node.value) ? ObfuscatingGuardResult.Transform @@ -49,10 +47,9 @@ export class ForceTransformStringObfuscatingGuard implements IObfuscatingGuard { * @param {string} value * @returns {boolean} */ - private isForceTransformString (value: string): boolean { - return this.options.forceTransformStrings - .some((forceTransformString: string) => { - return new RegExp(forceTransformString, 'g').exec(value) !== null; - }); + private isForceTransformString(value: string): boolean { + return this.options.forceTransformStrings.some((forceTransformString: string) => { + return new RegExp(forceTransformString, 'g').exec(value) !== null; + }); } } diff --git a/src/node-transformers/preparing-transformers/obfuscating-guards/IgnoredImportObfuscatingGuard.ts b/src/node-transformers/preparing-transformers/obfuscating-guards/IgnoredImportObfuscatingGuard.ts index ff27b178..d80a62d2 100644 --- a/src/node-transformers/preparing-transformers/obfuscating-guards/IgnoredImportObfuscatingGuard.ts +++ b/src/node-transformers/preparing-transformers/obfuscating-guards/IgnoredImportObfuscatingGuard.ts @@ -21,9 +21,7 @@ export class IgnoredImportObfuscatingGuard implements IObfuscatingGuard { /** * @param {IOptions} options */ - public constructor ( - @inject(ServiceIdentifiers.IOptions) options: IOptions - ) { + public constructor(@inject(ServiceIdentifiers.IOptions) options: IOptions) { this.options = options; } @@ -31,7 +29,7 @@ export class IgnoredImportObfuscatingGuard implements IObfuscatingGuard { * @param {Node} node * @returns {boolean} */ - private static isDynamicImport (node: ESTree.Node): boolean { + private static isDynamicImport(node: ESTree.Node): boolean { return NodeGuards.isImportExpressionNode(node); } @@ -39,20 +37,23 @@ export class IgnoredImportObfuscatingGuard implements IObfuscatingGuard { * @param {Node} node * @returns {boolean} */ - private static isRequireImport (node: ESTree.Node): boolean { - return NodeGuards.isCallExpressionNode(node) - && NodeGuards.isIdentifierNode(node.callee) - && node.callee.name === 'require'; + private static isRequireImport(node: ESTree.Node): boolean { + return ( + NodeGuards.isCallExpressionNode(node) && + NodeGuards.isIdentifierNode(node.callee) && + node.callee.name === 'require' + ); } /** * @param {Node} node * @returns {ObfuscatingGuardResult} */ - public check (node: ESTree.Node): ObfuscatingGuardResult { + public check(node: ESTree.Node): ObfuscatingGuardResult { if (this.options.ignoreImports) { - const isIgnoredImport = IgnoredImportObfuscatingGuard.isDynamicImport(node) - || IgnoredImportObfuscatingGuard.isRequireImport(node); + const isIgnoredImport = + IgnoredImportObfuscatingGuard.isDynamicImport(node) || + IgnoredImportObfuscatingGuard.isRequireImport(node); if (isIgnoredImport) { return ObfuscatingGuardResult.Ignore; diff --git a/src/node-transformers/preparing-transformers/obfuscating-guards/ImportMetaObfuscationGuard.ts b/src/node-transformers/preparing-transformers/obfuscating-guards/ImportMetaObfuscationGuard.ts index 32ebd4b8..34bdc530 100644 --- a/src/node-transformers/preparing-transformers/obfuscating-guards/ImportMetaObfuscationGuard.ts +++ b/src/node-transformers/preparing-transformers/obfuscating-guards/ImportMetaObfuscationGuard.ts @@ -14,10 +14,12 @@ export class ImportMetaObfuscationGuard implements IObfuscatingGuard { * @param {Node} node * @returns {ObfuscatingGuardResult} */ - public check (node: ESTree.Node): ObfuscatingGuardResult { + public check(node: ESTree.Node): ObfuscatingGuardResult { const isMetaProperty = NodeGuards.isMetaPropertyNode(node); const isMetaPropertyParent = !!node?.parentNode && NodeGuards.isMetaPropertyNode(node.parentNode); - return isMetaProperty || isMetaPropertyParent ? ObfuscatingGuardResult.Ignore : ObfuscatingGuardResult.Transform; + return isMetaProperty || isMetaPropertyParent + ? ObfuscatingGuardResult.Ignore + : ObfuscatingGuardResult.Transform; } } diff --git a/src/node-transformers/preparing-transformers/obfuscating-guards/ReservedStringObfuscatingGuard.ts b/src/node-transformers/preparing-transformers/obfuscating-guards/ReservedStringObfuscatingGuard.ts index 21005fd8..d6769cec 100644 --- a/src/node-transformers/preparing-transformers/obfuscating-guards/ReservedStringObfuscatingGuard.ts +++ b/src/node-transformers/preparing-transformers/obfuscating-guards/ReservedStringObfuscatingGuard.ts @@ -21,9 +21,7 @@ export class ReservedStringObfuscatingGuard implements IObfuscatingGuard { /** * @param {IOptions} options */ - public constructor ( - @inject(ServiceIdentifiers.IOptions) options: IOptions - ) { + public constructor(@inject(ServiceIdentifiers.IOptions) options: IOptions) { this.options = options; } @@ -31,12 +29,8 @@ export class ReservedStringObfuscatingGuard implements IObfuscatingGuard { * @param {Node} node * @returns {ObfuscatingGuardResult} */ - public check (node: ESTree.Node): ObfuscatingGuardResult { - if ( - this.options.reservedStrings.length - && NodeGuards.isLiteralNode(node) - && typeof node.value === 'string' - ) { + public check(node: ESTree.Node): ObfuscatingGuardResult { + if (this.options.reservedStrings.length && NodeGuards.isLiteralNode(node) && typeof node.value === 'string') { return !this.isReservedString(node.value) ? ObfuscatingGuardResult.Transform : ObfuscatingGuardResult.Ignore; @@ -49,10 +43,9 @@ export class ReservedStringObfuscatingGuard implements IObfuscatingGuard { * @param {string} value * @returns {boolean} */ - private isReservedString (value: string): boolean { - return this.options.reservedStrings - .some((reservedString: string) => { - return new RegExp(reservedString, 'g').exec(value) !== null; - }); + private isReservedString(value: string): boolean { + return this.options.reservedStrings.some((reservedString: string) => { + return new RegExp(reservedString, 'g').exec(value) !== null; + }); } } diff --git a/src/node-transformers/rename-identifiers-transformers/LabeledStatementTransformer.ts b/src/node-transformers/rename-identifiers-transformers/LabeledStatementTransformer.ts index 3c12a6d5..b56ddbea 100644 --- a/src/node-transformers/rename-identifiers-transformers/LabeledStatementTransformer.ts +++ b/src/node-transformers/rename-identifiers-transformers/LabeledStatementTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -45,7 +45,7 @@ export class LabeledStatementTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IIdentifierReplacer) identifierReplacer: IIdentifierReplacer, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -59,7 +59,7 @@ export class LabeledStatementTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.RenameIdentifiers: return { @@ -80,8 +80,9 @@ export class LabeledStatementTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (labeledStatementNode: ESTree.LabeledStatement, parentNode: ESTree.Node): ESTree.Node { - const lexicalScopeNode: TNodeWithLexicalScope | undefined = NodeLexicalScopeUtils.getLexicalScope(labeledStatementNode); + public transformNode(labeledStatementNode: ESTree.LabeledStatement, parentNode: ESTree.Node): ESTree.Node { + const lexicalScopeNode: TNodeWithLexicalScope | undefined = + NodeLexicalScopeUtils.getLexicalScope(labeledStatementNode); if (!lexicalScopeNode) { return labeledStatementNode; @@ -97,7 +98,7 @@ export class LabeledStatementTransformer extends AbstractNodeTransformer { * @param {LabeledStatement} labeledStatementNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - private storeLabeledStatementName ( + private storeLabeledStatementName( labeledStatementNode: ESTree.LabeledStatement, lexicalScopeNode: TNodeWithLexicalScope ): void { @@ -108,15 +109,14 @@ export class LabeledStatementTransformer extends AbstractNodeTransformer { * @param {LabeledStatement} labeledStatementNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - private replaceLabeledStatementName ( + private replaceLabeledStatementName( labeledStatementNode: ESTree.LabeledStatement, lexicalScopeNode: TNodeWithLexicalScope ): void { estraverse.replace(labeledStatementNode, { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): void => { if (parentNode && NodeGuards.isLabelIdentifierNode(node, parentNode)) { - const newIdentifier: ESTree.Identifier = this.identifierReplacer - .replace(node, lexicalScopeNode); + const newIdentifier: ESTree.Identifier = this.identifierReplacer.replace(node, lexicalScopeNode); node.name = newIdentifier.name; } diff --git a/src/node-transformers/rename-identifiers-transformers/ScopeIdentifiersTransformer.ts b/src/node-transformers/rename-identifiers-transformers/ScopeIdentifiersTransformer.ts index 6eef3e98..028a5135 100644 --- a/src/node-transformers/rename-identifiers-transformers/ScopeIdentifiersTransformer.ts +++ b/src/node-transformers/rename-identifiers-transformers/ScopeIdentifiersTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as eslintScope from 'eslint-scope'; @@ -33,7 +33,8 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { /** * @type {WeakMap} */ - private readonly lexicalScopesWithObjectPatternWithoutDeclarationMap: WeakMap = new WeakMap(); + private readonly lexicalScopesWithObjectPatternWithoutDeclarationMap: WeakMap = + new WeakMap(); /** * @type {IScopeIdentifiersTraverser} @@ -46,7 +47,7 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {IOptions} options * @param {IScopeIdentifiersTraverser} scopeIdentifiersTraverser */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IIdentifierReplacer) identifierReplacer: IIdentifierReplacer, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @@ -62,7 +63,7 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.RenameIdentifiers: return { @@ -83,23 +84,18 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { + public transformNode(programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { this.scopeIdentifiersTraverser.traverseScopeIdentifiers( programNode, parentNode, (data: IScopeIdentifiersTraverserCallbackData) => { - const { - isGlobalDeclaration, - variable, - variableLexicalScopeNode - } = data; + const { isGlobalDeclaration, variable, variableLexicalScopeNode } = data; if (!this.options.renameGlobals && isGlobalDeclaration) { - const isImportBindingOrCatchClauseIdentifier: boolean = variable.defs - .every((definition: eslintScope.Definition) => - definition.type === 'ImportBinding' - || definition.type === 'CatchClause' - ); + const isImportBindingOrCatchClauseIdentifier: boolean = variable.defs.every( + (definition: eslintScope.Definition) => + definition.type === 'ImportBinding' || definition.type === 'CatchClause' + ); // skip all global identifiers except import statement and catch clause parameter identifiers if (!isImportBindingOrCatchClauseIdentifier) { @@ -107,11 +103,7 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { } } - this.transformScopeVariableIdentifiers( - variable, - variableLexicalScopeNode, - isGlobalDeclaration - ); + this.transformScopeVariableIdentifiers(variable, variableLexicalScopeNode, isGlobalDeclaration); } ); @@ -123,7 +115,7 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {boolean} isGlobalDeclaration */ - private transformScopeVariableIdentifiers ( + private transformScopeVariableIdentifiers( variable: eslintScope.Variable, lexicalScopeNode: TNodeWithLexicalScope, isGlobalDeclaration: boolean @@ -147,7 +139,7 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {boolean} isGlobalDeclaration */ - private storeIdentifierName ( + private storeIdentifierName( identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope, isGlobalDeclaration: boolean @@ -164,13 +156,12 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {TNodeWithLexicalScope} lexicalScopeNode * @param {Variable} variable */ - private replaceIdentifierName ( + private replaceIdentifierName( identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope, variable: eslintScope.Variable ): void { - const newIdentifier: ESTree.Identifier = this.identifierReplacer - .replace(identifierNode, lexicalScopeNode); + const newIdentifier: ESTree.Identifier = this.identifierReplacer.replace(identifierNode, lexicalScopeNode); // rename of identifiers variable.identifiers.forEach((identifier: ESTree.Identifier) => { @@ -190,24 +181,26 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @returns {boolean} */ // eslint-disable-next-line complexity - private isReplaceableIdentifierNode ( + private isReplaceableIdentifierNode( identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope, variable: eslintScope.Variable ): identifierNode is ESTree.Identifier & { parentNode: ESTree.Node } { const parentNode: ESTree.Node | undefined = identifierNode.parentNode; - return !!parentNode - && !NodeMetadata.isIgnoredNode(identifierNode) - && !this.isProhibitedPropertyIdentifierNode(identifierNode, parentNode) - && !this.isProhibitedPropertyAssignmentPatternIdentifierNode(identifierNode, parentNode) - && !this.isProhibitedClassDeclarationNameIdentifierNode(variable, identifierNode, parentNode) - && !this.isProhibitedExportNamedClassDeclarationIdentifierNode(identifierNode, parentNode) - && !this.isProhibitedExportNamedFunctionDeclarationIdentifierNode(identifierNode, parentNode) - && !this.isProhibitedExportNamedVariableDeclarationIdentifierNode(identifierNode, parentNode) - && !this.isProhibitedImportSpecifierNode(identifierNode, parentNode) - && !this.isProhibitedVariableNameUsedInObjectPatternNode(variable, identifierNode, lexicalScopeNode) - && !NodeGuards.isLabelIdentifierNode(identifierNode, parentNode); + return ( + !!parentNode && + !NodeMetadata.isIgnoredNode(identifierNode) && + !this.isProhibitedPropertyIdentifierNode(identifierNode, parentNode) && + !this.isProhibitedPropertyAssignmentPatternIdentifierNode(identifierNode, parentNode) && + !this.isProhibitedClassDeclarationNameIdentifierNode(variable, identifierNode, parentNode) && + !this.isProhibitedExportNamedClassDeclarationIdentifierNode(identifierNode, parentNode) && + !this.isProhibitedExportNamedFunctionDeclarationIdentifierNode(identifierNode, parentNode) && + !this.isProhibitedExportNamedVariableDeclarationIdentifierNode(identifierNode, parentNode) && + !this.isProhibitedImportSpecifierNode(identifierNode, parentNode) && + !this.isProhibitedVariableNameUsedInObjectPatternNode(variable, identifierNode, lexicalScopeNode) && + !NodeGuards.isLabelIdentifierNode(identifierNode, parentNode) + ); } /** @@ -216,14 +209,16 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {identifierNode is Identifier} */ - private isProhibitedClassDeclarationNameIdentifierNode ( + private isProhibitedClassDeclarationNameIdentifierNode( variable: eslintScope.Variable, identifierNode: ESTree.Identifier, parentNode: ESTree.Node ): identifierNode is ESTree.Identifier { - return NodeGuards.isClassDeclarationNode(variable.scope.block) - && NodeGuards.isClassDeclarationNode(parentNode) - && parentNode.id === identifierNode; + return ( + NodeGuards.isClassDeclarationNode(variable.scope.block) && + NodeGuards.isClassDeclarationNode(parentNode) && + parentNode.id === identifierNode + ); } /** @@ -231,14 +226,16 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {identifierNode is Identifier} */ - private isProhibitedExportNamedClassDeclarationIdentifierNode ( + private isProhibitedExportNamedClassDeclarationIdentifierNode( identifierNode: ESTree.Identifier, parentNode: ESTree.Node ): identifierNode is ESTree.Identifier { - return NodeGuards.isClassDeclarationNode(parentNode) - && parentNode.id === identifierNode - && !!parentNode.parentNode - && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode); + return ( + NodeGuards.isClassDeclarationNode(parentNode) && + parentNode.id === identifierNode && + !!parentNode.parentNode && + NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode) + ); } /** @@ -246,14 +243,16 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {identifierNode is Identifier} */ - private isProhibitedExportNamedFunctionDeclarationIdentifierNode ( + private isProhibitedExportNamedFunctionDeclarationIdentifierNode( identifierNode: ESTree.Identifier, parentNode: ESTree.Node ): identifierNode is ESTree.Identifier { - return NodeGuards.isFunctionDeclarationNode(parentNode) - && parentNode.id === identifierNode - && !!parentNode.parentNode - && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode); + return ( + NodeGuards.isFunctionDeclarationNode(parentNode) && + parentNode.id === identifierNode && + !!parentNode.parentNode && + NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode) + ); } /** @@ -261,16 +260,18 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {identifierNode is Identifier} */ - private isProhibitedExportNamedVariableDeclarationIdentifierNode ( + private isProhibitedExportNamedVariableDeclarationIdentifierNode( identifierNode: ESTree.Identifier, parentNode: ESTree.Node ): identifierNode is ESTree.Identifier { - return NodeGuards.isVariableDeclaratorNode(parentNode) - && parentNode.id === identifierNode - && !!parentNode.parentNode - && NodeGuards.isVariableDeclarationNode(parentNode.parentNode) - && !!parentNode.parentNode.parentNode - && NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode.parentNode); + return ( + NodeGuards.isVariableDeclaratorNode(parentNode) && + parentNode.id === identifierNode && + !!parentNode.parentNode && + NodeGuards.isVariableDeclarationNode(parentNode.parentNode) && + !!parentNode.parentNode.parentNode && + NodeGuards.isExportNamedDeclarationNode(parentNode.parentNode.parentNode) + ); } /** @@ -278,9 +279,8 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {boolean} */ - private isProhibitedImportSpecifierNode (identifierNode: ESTree.Identifier, parentNode: ESTree.Node): boolean { - return NodeGuards.isImportSpecifierNode(parentNode) - && parentNode.imported.name === parentNode.local.name; + private isProhibitedImportSpecifierNode(identifierNode: ESTree.Identifier, parentNode: ESTree.Node): boolean { + return NodeGuards.isImportSpecifierNode(parentNode) && parentNode.imported.name === parentNode.local.name; } /** @@ -288,16 +288,15 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {boolean} */ - private isProhibitedPropertyIdentifierNode ( - node: ESTree.Node, - parentNode: ESTree.Node - ): node is ESTree.Identifier { - return NodeGuards.isPropertyNode(parentNode) - && !parentNode.computed - && NodeGuards.isIdentifierNode(parentNode.key) - && NodeGuards.isIdentifierNode(node) - && parentNode.shorthand - && parentNode.key.name === node.name; + private isProhibitedPropertyIdentifierNode(node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier { + return ( + NodeGuards.isPropertyNode(parentNode) && + !parentNode.computed && + NodeGuards.isIdentifierNode(parentNode.key) && + NodeGuards.isIdentifierNode(node) && + parentNode.shorthand && + parentNode.key.name === node.name + ); } /** @@ -305,17 +304,19 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {Node} parentNode * @returns {boolean} */ - private isProhibitedPropertyAssignmentPatternIdentifierNode ( + private isProhibitedPropertyAssignmentPatternIdentifierNode( node: ESTree.Node, parentNode: ESTree.Node ): node is ESTree.Identifier { - return NodeGuards.isAssignmentPatternNode(parentNode) - && parentNode.left === node - && !!parentNode.parentNode - && NodeGuards.isPropertyNode(parentNode.parentNode) - && NodeGuards.isIdentifierNode(parentNode.left) - && NodeGuards.isIdentifierNode(parentNode.parentNode.key) - && parentNode.left.name === parentNode.parentNode.key.name; + return ( + NodeGuards.isAssignmentPatternNode(parentNode) && + parentNode.left === node && + !!parentNode.parentNode && + NodeGuards.isPropertyNode(parentNode.parentNode) && + NodeGuards.isIdentifierNode(parentNode.left) && + NodeGuards.isIdentifierNode(parentNode.parentNode.key) && + parentNode.left.name === parentNode.parentNode.key.name + ); } /** @@ -329,7 +330,7 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { * @param {TNodeWithLexicalScope} lexicalScopeNode * @returns {boolean} */ - private isProhibitedVariableNameUsedInObjectPatternNode ( + private isProhibitedVariableNameUsedInObjectPatternNode( variable: eslintScope.Variable, identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope @@ -342,7 +343,9 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { return false; } - const hasVarDefinitions: boolean = variable.defs.some((definition: eslintScope.Definition) => (definition).kind === 'var'); + const hasVarDefinitions: boolean = variable.defs.some( + (definition: eslintScope.Definition) => (definition).kind === 'var' + ); if (!hasVarDefinitions) { return false; @@ -353,20 +356,21 @@ export class ScopeIdentifiersTransformer extends AbstractNodeTransformer { estraverse.traverse(lexicalScopeNode, { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): void | estraverse.VisitorOption => { if ( - NodeGuards.isObjectPatternNode(node) - && parentNode - && NodeGuards.isAssignmentExpressionNode(parentNode) + NodeGuards.isObjectPatternNode(node) && + parentNode && + NodeGuards.isAssignmentExpressionNode(parentNode) ) { isLexicalScopeHasObjectPatternWithoutDeclaration = true; const properties: (ESTree.Property | ESTree.RestElement)[] = node.properties; for (const property of properties) { - isProhibitedVariableDeclaration = NodeGuards.isPropertyNode(property) - && !property.computed - && property.shorthand - && NodeGuards.isIdentifierNode(property.key) - && identifierNode.name === property.key.name; + isProhibitedVariableDeclaration = + NodeGuards.isPropertyNode(property) && + !property.computed && + property.shorthand && + NodeGuards.isIdentifierNode(property.key) && + identifierNode.name === property.key.name; if (!isProhibitedVariableDeclaration) { continue; diff --git a/src/node-transformers/rename-identifiers-transformers/ScopeThroughIdentifiersTransformer.ts b/src/node-transformers/rename-identifiers-transformers/ScopeThroughIdentifiersTransformer.ts index e1775d48..242bcecd 100644 --- a/src/node-transformers/rename-identifiers-transformers/ScopeThroughIdentifiersTransformer.ts +++ b/src/node-transformers/rename-identifiers-transformers/ScopeThroughIdentifiersTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as eslintScope from 'eslint-scope'; @@ -39,7 +39,7 @@ export class ScopeThroughIdentifiersTransformer extends AbstractNodeTransformer * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IThroughIdentifierReplacer) throughIdentifierReplacer: IThroughIdentifierReplacer, @inject(ServiceIdentifiers.IScopeIdentifiersTraverser) scopeIdentifiersTraverser: IScopeIdentifiersTraverser, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @@ -55,7 +55,7 @@ export class ScopeThroughIdentifiersTransformer extends AbstractNodeTransformer * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.RenameIdentifiers: return { @@ -76,20 +76,14 @@ export class ScopeThroughIdentifiersTransformer extends AbstractNodeTransformer * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { + public transformNode(programNode: ESTree.Program, parentNode: ESTree.Node): ESTree.Node { this.scopeIdentifiersTraverser.traverseScopeThroughIdentifiers( programNode, parentNode, (data: IScopeThroughIdentifiersTraverserCallbackData) => { - const { - reference, - variableLexicalScopeNode - } = data; + const { reference, variableLexicalScopeNode } = data; - this.transformScopeThroughIdentifiers( - reference, - variableLexicalScopeNode - ); + this.transformScopeThroughIdentifiers(reference, variableLexicalScopeNode); } ); @@ -100,7 +94,7 @@ export class ScopeThroughIdentifiersTransformer extends AbstractNodeTransformer * @param {Reference} reference * @param {TNodeWithLexicalScope} lexicalScopeNode */ - protected transformScopeThroughIdentifiers ( + protected transformScopeThroughIdentifiers( reference: eslintScope.Reference, lexicalScopeNode: TNodeWithLexicalScope ): void { @@ -114,7 +108,7 @@ export class ScopeThroughIdentifiersTransformer extends AbstractNodeTransformer /** * @param {Variable} reference */ - protected replaceIdentifierName (reference: eslintScope.Reference): void { + protected replaceIdentifierName(reference: eslintScope.Reference): void { const identifier: ESTree.Identifier = reference.identifier; const newIdentifier: ESTree.Identifier = this.throughIdentifierReplacer.replace(identifier); diff --git a/src/node-transformers/rename-identifiers-transformers/replacer/IdentifierReplacer.ts b/src/node-transformers/rename-identifiers-transformers/replacer/IdentifierReplacer.ts index 9fbd0c63..8a7d7084 100644 --- a/src/node-transformers/rename-identifiers-transformers/replacer/IdentifierReplacer.ts +++ b/src/node-transformers/rename-identifiers-transformers/replacer/IdentifierReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -40,11 +40,11 @@ export class IdentifierReplacer implements IIdentifierReplacer { * @param {IGlobalIdentifierNamesCacheStorage} identifierNamesCacheStorage * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IGlobalIdentifierNamesCacheStorage) - identifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage, + identifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { this.options = options; @@ -59,7 +59,7 @@ export class IdentifierReplacer implements IIdentifierReplacer { * @param {Node} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - public storeGlobalName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void { + public storeGlobalName(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void { const identifierName: string = identifierNode.name; if (this.isReservedName(identifierName)) { @@ -86,7 +86,7 @@ export class IdentifierReplacer implements IIdentifierReplacer { * @param {Identifier} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - public storeLocalName (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void { + public storeLocalName(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void { const identifierName: string = identifierNode.name; if (this.isReservedName(identifierName)) { @@ -105,7 +105,7 @@ export class IdentifierReplacer implements IIdentifierReplacer { * @param {TNodeWithLexicalScope} lexicalScopeNode * @returns {Identifier} */ - public replace (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): ESTree.Identifier { + public replace(identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): ESTree.Identifier { const namesMap: Map | null = this.blockScopesMap.get(lexicalScopeNode) ?? null; if (!namesMap) { @@ -126,7 +126,7 @@ export class IdentifierReplacer implements IIdentifierReplacer { * * @param {Identifier} identifierNode */ - public preserveName (identifierNode: ESTree.Identifier): void { + public preserveName(identifierNode: ESTree.Identifier): void { this.identifierNamesGenerator.preserveName(identifierNode.name); } @@ -136,7 +136,10 @@ export class IdentifierReplacer implements IIdentifierReplacer { * @param {Identifier} identifierNode * @param {TNodeWithLexicalScope} lexicalScopeNode */ - public preserveNameForLexicalScope (identifierNode: ESTree.Identifier, lexicalScopeNode: TNodeWithLexicalScope): void { + public preserveNameForLexicalScope( + identifierNode: ESTree.Identifier, + lexicalScopeNode: TNodeWithLexicalScope + ): void { this.identifierNamesGenerator.preserveNameForLexicalScope(identifierNode.name, lexicalScopeNode); } @@ -144,14 +147,13 @@ export class IdentifierReplacer implements IIdentifierReplacer { * @param {string} name * @returns {boolean} */ - private isReservedName (name: string): boolean { + private isReservedName(name: string): boolean { if (!this.options.reservedNames.length) { return false; } - return this.options.reservedNames - .some((reservedName: string) => { - return new RegExp(reservedName, 'g').exec(name) !== null; - }); + return this.options.reservedNames.some((reservedName: string) => { + return new RegExp(reservedName, 'g').exec(name) !== null; + }); } } diff --git a/src/node-transformers/rename-identifiers-transformers/through-replacer/ThroughIdentifierReplacer.ts b/src/node-transformers/rename-identifiers-transformers/through-replacer/ThroughIdentifierReplacer.ts index c12da4bd..9bd4f513 100644 --- a/src/node-transformers/rename-identifiers-transformers/through-replacer/ThroughIdentifierReplacer.ts +++ b/src/node-transformers/rename-identifiers-transformers/through-replacer/ThroughIdentifierReplacer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -25,9 +25,9 @@ export class ThroughIdentifierReplacer implements IThroughIdentifierReplacer { * @param {IGlobalIdentifierNamesCacheStorage} identifierNamesCacheStorage * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IGlobalIdentifierNamesCacheStorage) - identifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage, + identifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { this.identifierNamesCacheStorage = identifierNamesCacheStorage; @@ -38,11 +38,12 @@ export class ThroughIdentifierReplacer implements IThroughIdentifierReplacer { * @param {Identifier} identifierNode * @returns {Identifier} */ - public replace (identifierNode: ESTree.Identifier): ESTree.Identifier { + public replace(identifierNode: ESTree.Identifier): ESTree.Identifier { const identifierName: string = identifierNode.name; - const newIdentifierName: string = this.options.identifierNamesCache && !this.isReservedName(identifierName) - ? this.identifierNamesCacheStorage.get(identifierName) ?? identifierName - : identifierName; + const newIdentifierName: string = + this.options.identifierNamesCache && !this.isReservedName(identifierName) + ? (this.identifierNamesCacheStorage.get(identifierName) ?? identifierName) + : identifierName; return NodeFactory.identifierNode(newIdentifierName); } @@ -51,14 +52,13 @@ export class ThroughIdentifierReplacer implements IThroughIdentifierReplacer { * @param {string} name * @returns {boolean} */ - private isReservedName (name: string): boolean { + private isReservedName(name: string): boolean { if (!this.options.reservedNames.length) { return false; } - return this.options.reservedNames - .some((reservedName: string) => { - return new RegExp(reservedName, 'g').exec(name) !== null; - }); + return this.options.reservedNames.some((reservedName: string) => { + return new RegExp(reservedName, 'g').exec(name) !== null; + }); } } diff --git a/src/node-transformers/rename-properties-transformers/RenamePropertiesTransformer.ts b/src/node-transformers/rename-properties-transformers/RenamePropertiesTransformer.ts index 55a321a1..685b6d0d 100644 --- a/src/node-transformers/rename-properties-transformers/RenamePropertiesTransformer.ts +++ b/src/node-transformers/rename-properties-transformers/RenamePropertiesTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable} from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -28,7 +28,7 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRenamePropertiesReplacer) renamePropertiesReplacer: IRenamePropertiesReplacer, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions @@ -44,11 +44,8 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { * @returns {boolean} */ private static isValidPropertyNode< - TNode extends ESTree.Property - | ESTree.PropertyDefinition - | ESTree.MemberExpression - | ESTree.MethodDefinition - > ( + TNode extends ESTree.Property | ESTree.PropertyDefinition | ESTree.MemberExpression | ESTree.MethodDefinition + >( propertyNode: TNode, propertyKeyNode: ESTree.Expression | ESTree.PrivateIdentifier ): propertyKeyNode is ESTree.Identifier | ESTree.Literal { @@ -63,7 +60,7 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Preparing: return { @@ -92,15 +89,14 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { * @param {Node} node * @param {Node} parentNode */ - public prepareNode ( - node: ESTree.Node, - parentNode: ESTree.Node - ): void { - if ((NodeGuards.isPropertyNode(parentNode) && parentNode.key === node) - || NodeGuards.isMemberExpressionNode(parentNode) && parentNode.property === node - || NodeGuards.isMethodDefinitionNode(parentNode) && parentNode.key === node - || NodeGuards.isPropertyDefinitionNode(parentNode) && parentNode.key === node) { - NodeMetadata.set(node, {propertyKeyToRenameNode: true}); + public prepareNode(node: ESTree.Node, parentNode: ESTree.Node): void { + if ( + (NodeGuards.isPropertyNode(parentNode) && parentNode.key === node) || + (NodeGuards.isMemberExpressionNode(parentNode) && parentNode.property === node) || + (NodeGuards.isMethodDefinitionNode(parentNode) && parentNode.key === node) || + (NodeGuards.isPropertyDefinitionNode(parentNode) && parentNode.key === node) + ) { + NodeMetadata.set(node, { propertyKeyToRenameNode: true }); return; } @@ -115,7 +111,7 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {Node} */ - public transformNode (node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node { + public transformNode(node: ESTree.Node, parentNode: ESTree.Node): ESTree.Node { if (!NodeGuards.isIdentifierNode(node) && !NodeGuards.isLiteralNode(node)) { return node; } @@ -125,10 +121,11 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { } const isPropertyNode = NodeGuards.isPropertyNode(parentNode); - const isPropertyLikeNode = isPropertyNode - || NodeGuards.isPropertyDefinitionNode(parentNode) - || NodeGuards.isMemberExpressionNode(parentNode) - || NodeGuards.isMethodDefinitionNode(parentNode); + const isPropertyLikeNode = + isPropertyNode || + NodeGuards.isPropertyDefinitionNode(parentNode) || + NodeGuards.isMemberExpressionNode(parentNode) || + NodeGuards.isMethodDefinitionNode(parentNode); if (isPropertyLikeNode && !RenamePropertiesTransformer.isValidPropertyNode(parentNode, node)) { return node; @@ -145,10 +142,7 @@ export class RenamePropertiesTransformer extends AbstractNodeTransformer { * @param {Node} node * @param {Node} parentNode */ - private analyzeAutoExcludedPropertyNames ( - node: ESTree.Node, - parentNode: ESTree.Node - ): void { + private analyzeAutoExcludedPropertyNames(node: ESTree.Node, parentNode: ESTree.Node): void { if (!NodeGuards.isLiteralNode(node) || !NodeLiteralUtils.isStringLiteralNode(node)) { return; } diff --git a/src/node-transformers/rename-properties-transformers/replacer/RenamePropertiesReplacer.ts b/src/node-transformers/rename-properties-transformers/replacer/RenamePropertiesReplacer.ts index 95cbd95d..707a4925 100644 --- a/src/node-transformers/rename-properties-transformers/replacer/RenamePropertiesReplacer.ts +++ b/src/node-transformers/rename-properties-transformers/replacer/RenamePropertiesReplacer.ts @@ -1,5 +1,5 @@ /* eslint-disable no-console */ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -60,11 +60,11 @@ export class RenamePropertiesReplacer implements IRenamePropertiesReplacer { * @param {IPropertyIdentifierNamesCacheStorage} propertyIdentifierNamesCacheStorage * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IPropertyIdentifierNamesCacheStorage) - propertyIdentifierNamesCacheStorage: IPropertyIdentifierNamesCacheStorage, + propertyIdentifierNamesCacheStorage: IPropertyIdentifierNamesCacheStorage, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { this.identifierNamesGenerator = identifierNamesGeneratorFactory(options); @@ -75,25 +75,21 @@ export class RenamePropertiesReplacer implements IRenamePropertiesReplacer { /** * @param {string} propertyName */ - public excludePropertyName (propertyName: string): void { - this.excludedPropertyNames.add(propertyName); + public excludePropertyName(propertyName: string): void { + this.excludedPropertyNames.add(propertyName); } /** * @param {ESTree.Identifier | ESTree.Literal} node * @returns {ESTree.Identifier | ESTree.Literal} */ - public replace (node: ESTree.Identifier | ESTree.Literal): ESTree.Identifier | ESTree.Literal { + public replace(node: ESTree.Identifier | ESTree.Literal): ESTree.Identifier | ESTree.Literal { if (NodeGuards.isIdentifierNode(node)) { - return NodeFactory.identifierNode( - this.replacePropertyName(node.name) - ); + return NodeFactory.identifierNode(this.replacePropertyName(node.name)); } if (NodeGuards.isLiteralNode(node) && typeof node.value === 'string') { - return NodeFactory.literalNode( - this.replacePropertyName(node.value) - ); + return NodeFactory.literalNode(this.replacePropertyName(node.value)); } return node; @@ -104,7 +100,7 @@ export class RenamePropertiesReplacer implements IRenamePropertiesReplacer { * @returns {string} * @private */ - private replacePropertyName (propertyName: string): string { + private replacePropertyName(propertyName: string): string { if (this.isReservedName(propertyName)) { this.identifierNamesGenerator.preserveName(propertyName); @@ -112,12 +108,10 @@ export class RenamePropertiesReplacer implements IRenamePropertiesReplacer { } let renamedPropertyName: string | null = this.options.identifierNamesCache - ? this.propertyIdentifierNamesCacheStorage.get(propertyName) ?? null + ? (this.propertyIdentifierNamesCacheStorage.get(propertyName) ?? null) : null; - renamedPropertyName = renamedPropertyName - ?? this.propertyNamesMap.get(propertyName) - ?? null; + renamedPropertyName = renamedPropertyName ?? this.propertyNamesMap.get(propertyName) ?? null; if (renamedPropertyName !== null) { return renamedPropertyName; @@ -137,17 +131,15 @@ export class RenamePropertiesReplacer implements IRenamePropertiesReplacer { * @param {string} name * @returns {boolean} */ - private isReservedName (name: string): boolean { - return this.isExcludedName(name) - || this.isReservedOptionName(name) - || this.isReservedDomPropertyName(name); + private isReservedName(name: string): boolean { + return this.isExcludedName(name) || this.isReservedOptionName(name) || this.isReservedDomPropertyName(name); } /** * @param {string} name * @returns {boolean} */ - private isExcludedName (name: string): boolean { + private isExcludedName(name: string): boolean { return this.excludedPropertyNames.has(name); } @@ -155,22 +147,21 @@ export class RenamePropertiesReplacer implements IRenamePropertiesReplacer { * @param {string} name * @returns {boolean} */ - private isReservedOptionName (name: string): boolean { + private isReservedOptionName(name: string): boolean { if (!this.options.reservedNames.length) { return false; } - return this.options.reservedNames - .some((reservedName: string) => { - return new RegExp(reservedName, 'g').exec(name) !== null; - }); + return this.options.reservedNames.some((reservedName: string) => { + return new RegExp(reservedName, 'g').exec(name) !== null; + }); } /** * @param {string} name * @returns {boolean} */ - private isReservedDomPropertyName (name: string): boolean { + private isReservedDomPropertyName(name: string): boolean { return RenamePropertiesReplacer.reservedDomPropertiesList.has(name); } } diff --git a/src/node-transformers/simplifying-transformers/AbstractStatementSimplifyTransformer.ts b/src/node-transformers/simplifying-transformers/AbstractStatementSimplifyTransformer.ts index 24d92661..9014aa3a 100644 --- a/src/node-transformers/simplifying-transformers/AbstractStatementSimplifyTransformer.ts +++ b/src/node-transformers/simplifying-transformers/AbstractStatementSimplifyTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -31,7 +31,7 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -44,7 +44,7 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT * @param {ESTree.Statement | null | undefined} statementNode * @returns {IStatementSimplifyData | null} */ - protected getStatementSimplifyData ( + protected getStatementSimplifyData( statementNode: ESTree.Statement | null | undefined ): IStatementSimplifyData | null { if (!statementNode) { @@ -60,12 +60,8 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT }; } - const { - startIndex, - unwrappedExpressions, - hasReturnStatement, - hasStatementsAfterReturnStatement - } = this.collectIteratedStatementsSimplifyData(statementNode); + const { startIndex, unwrappedExpressions, hasReturnStatement, hasStatementsAfterReturnStatement } = + this.collectIteratedStatementsSimplifyData(statementNode); if (hasStatementsAfterReturnStatement) { return { @@ -114,7 +110,7 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT * @param {ESTree.Statement | null | undefined} statementNode * @returns {IIteratedStatementsSimplifyData} */ - protected collectIteratedStatementsSimplifyData ( + protected collectIteratedStatementsSimplifyData( statementNode: ESTree.BlockStatement ): IIteratedStatementsSimplifyData { const statementNodeBodyLength: number = statementNode.body.length; @@ -138,10 +134,7 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT continue; } - if ( - NodeGuards.isReturnStatementNode(statementBodyStatementNode) - && statementBodyStatementNode.argument - ) { + if (NodeGuards.isReturnStatementNode(statementBodyStatementNode) && statementBodyStatementNode.argument) { unwrappedExpressions.unshift(statementBodyStatementNode.argument); hasReturnStatement = true; hasStatementsAfterReturnStatement = i !== statementNodeBodyLength - 1; @@ -167,24 +160,27 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT * @param {number | null} startIndex * @returns {ESTree.Statement[]} */ - protected getLeadingStatements (statementNode: ESTree.BlockStatement, startIndex: number | null): ESTree.Statement[] { + protected getLeadingStatements( + statementNode: ESTree.BlockStatement, + startIndex: number | null + ): ESTree.Statement[] { // variant #1: no valid statements inside `BlockStatement` are found if (startIndex === null) { return statementNode.body; } return startIndex === 0 - // variant #2: all statements inside `BlockStatement` branch are valid - ? [] - // variant #3: only last N statements inside `BlockStatement` branch are valid - : statementNode.body.slice(0, startIndex); + ? // variant #2: all statements inside `BlockStatement` branch are valid + [] + : // variant #3: only last N statements inside `BlockStatement` branch are valid + statementNode.body.slice(0, startIndex); } /** * @param {IStatementSimplifyData} statementSimplifyData * @returns {ESTree.Statement} */ - protected getPartialStatement (statementSimplifyData: IStatementSimplifyData): ESTree.Statement { + protected getPartialStatement(statementSimplifyData: IStatementSimplifyData): ESTree.Statement { // variant #1: all statements inside `BlockStatement` branch are valid if (!statementSimplifyData.leadingStatements.length && statementSimplifyData.trailingStatement) { return statementSimplifyData.trailingStatement.statement; @@ -192,8 +188,8 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT // variant #2: only last N statements inside `BlockStatement` branch are valid return NodeFactory.blockStatementNode([ - ...statementSimplifyData.leadingStatements.length ? statementSimplifyData.leadingStatements : [], - ...statementSimplifyData.trailingStatement ? [statementSimplifyData.trailingStatement.statement] : [] + ...(statementSimplifyData.leadingStatements.length ? statementSimplifyData.leadingStatements : []), + ...(statementSimplifyData.trailingStatement ? [statementSimplifyData.trailingStatement.statement] : []) ]); } @@ -202,8 +198,5 @@ export abstract class AbstractStatementSimplifyTransformer extends AbstractNodeT * @param {ESTree.Node} parentNode * @returns {ESTree.Node} */ - public abstract override transformNode ( - statementNode: ESTree.Statement, - parentNode: ESTree.Node - ): ESTree.Node; + public abstract override transformNode(statementNode: ESTree.Statement, parentNode: ESTree.Node): ESTree.Node; } diff --git a/src/node-transformers/simplifying-transformers/BlockStatementSimplifyTransformer.ts b/src/node-transformers/simplifying-transformers/BlockStatementSimplifyTransformer.ts index 89d60ad4..010f9b5c 100644 --- a/src/node-transformers/simplifying-transformers/BlockStatementSimplifyTransformer.ts +++ b/src/node-transformers/simplifying-transformers/BlockStatementSimplifyTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -24,15 +24,13 @@ export class BlockStatementSimplifyTransformer extends AbstractStatementSimplify /** * @type {NodeTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.VariableDeclarationsMergeTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.VariableDeclarationsMergeTransformer]; /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -43,14 +41,11 @@ export class BlockStatementSimplifyTransformer extends AbstractStatementSimplify * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Simplifying: return { - leave: ( - node: ESTree.Node, - parentNode: ESTree.Node | null - ): ESTree.Node | undefined => { + leave: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => { if (parentNode && NodeGuards.isBlockStatementNode(node)) { return this.transformNode(node, parentNode); } @@ -67,10 +62,7 @@ export class BlockStatementSimplifyTransformer extends AbstractStatementSimplify * @param {ESTree.Node} parentNode * @returns {ESTree.Node} */ - public transformNode ( - statementNode: ESTree.Statement, - parentNode: ESTree.Node - ): ESTree.Node { + public transformNode(statementNode: ESTree.Statement, parentNode: ESTree.Node): ESTree.Node { const simplifyData: IStatementSimplifyData | null = this.getStatementSimplifyData(statementNode); if (!simplifyData) { diff --git a/src/node-transformers/simplifying-transformers/ExpressionStatementsMergeTransformer.ts b/src/node-transformers/simplifying-transformers/ExpressionStatementsMergeTransformer.ts index fd942f35..ef2dcf81 100644 --- a/src/node-transformers/simplifying-transformers/ExpressionStatementsMergeTransformer.ts +++ b/src/node-transformers/simplifying-transformers/ExpressionStatementsMergeTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -32,7 +32,7 @@ export class ExpressionStatementsMergeTransformer extends AbstractNodeTransforme * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -43,7 +43,7 @@ export class ExpressionStatementsMergeTransformer extends AbstractNodeTransforme * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Simplifying: return { @@ -67,7 +67,7 @@ export class ExpressionStatementsMergeTransformer extends AbstractNodeTransforme * @param {ESTree.Node} parentNode * @returns {ESTree.ExpressionStatement | estraverse.VisitorOption} */ - public transformNode ( + public transformNode( expressionStatementNode: ESTree.ExpressionStatement, parentNode: ESTree.Node ): ESTree.ExpressionStatement | estraverse.VisitorOption { @@ -75,7 +75,8 @@ export class ExpressionStatementsMergeTransformer extends AbstractNodeTransforme return expressionStatementNode; } - const prevStatement: TStatement | null = NodeStatementUtils.getPreviousSiblingStatement(expressionStatementNode); + const prevStatement: TStatement | null = + NodeStatementUtils.getPreviousSiblingStatement(expressionStatementNode); if (!prevStatement || !NodeGuards.isExpressionStatementNode(prevStatement)) { return expressionStatementNode; diff --git a/src/node-transformers/simplifying-transformers/IfStatementSimplifyTransformer.ts b/src/node-transformers/simplifying-transformers/IfStatementSimplifyTransformer.ts index cdb54845..7ff89e29 100644 --- a/src/node-transformers/simplifying-transformers/IfStatementSimplifyTransformer.ts +++ b/src/node-transformers/simplifying-transformers/IfStatementSimplifyTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -24,7 +24,7 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -35,14 +35,11 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Simplifying: return { - leave: ( - node: ESTree.Node, - parentNode: ESTree.Node | null - ): ESTree.Node | undefined => { + leave: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => { if (parentNode && NodeGuards.isIfStatementNode(node)) { return this.transformNode(node, parentNode); } @@ -59,11 +56,10 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * @param {ESTree.Node} parentNode * @returns {ESTree.IfStatement} */ - public transformNode ( - ifStatementNode: ESTree.IfStatement, - parentNode: ESTree.Node - ): ESTree.Node { - const consequentSimplifyData: IStatementSimplifyData | null = this.getStatementSimplifyData(ifStatementNode.consequent); + public transformNode(ifStatementNode: ESTree.IfStatement, parentNode: ESTree.Node): ESTree.Node { + const consequentSimplifyData: IStatementSimplifyData | null = this.getStatementSimplifyData( + ifStatementNode.consequent + ); // Variant #1: no valid consequent expression data if (!consequentSimplifyData) { @@ -76,14 +72,20 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra // Variant #2: valid data for consequent expression only transformedNode = this.getConsequentNode(ifStatementNode, consequentSimplifyData); } else { - const alternateSimplifyData: IStatementSimplifyData | null = this.getStatementSimplifyData(ifStatementNode.alternate); + const alternateSimplifyData: IStatementSimplifyData | null = this.getStatementSimplifyData( + ifStatementNode.alternate + ); if (!alternateSimplifyData) { return ifStatementNode; } // Variant #3: valid data for consequent and alternate expressions - transformedNode = this.getConsequentAndAlternateNode(ifStatementNode, consequentSimplifyData, alternateSimplifyData); + transformedNode = this.getConsequentAndAlternateNode( + ifStatementNode, + consequentSimplifyData, + alternateSimplifyData + ); } return NodeUtils.parentizeNode(transformedNode, parentNode); @@ -94,7 +96,7 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * @param {IStatementSimplifyData} consequentSimplifyData * @returns {ESTree.Node} */ - protected getConsequentNode ( + protected getConsequentNode( ifStatementNode: ESTree.IfStatement, consequentSimplifyData: IStatementSimplifyData ): ESTree.Node { @@ -112,14 +114,8 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * return console.log(1), 1; * } */ - if ( - consequentSimplifyData.leadingStatements.length - || !consequentSimplifyData.trailingStatement - ) { - return NodeFactory.ifStatementNode( - ifStatementNode.test, - this.getPartialStatement(consequentSimplifyData) - ); + if (consequentSimplifyData.leadingStatements.length || !consequentSimplifyData.trailingStatement) { + return NodeFactory.ifStatementNode(ifStatementNode.test, this.getPartialStatement(consequentSimplifyData)); } /** @@ -163,7 +159,7 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * @param {IStatementSimplifyData} alternateSimplifyData * @returns {ESTree.Node} */ - protected getConsequentAndAlternateNode ( + protected getConsequentAndAlternateNode( ifStatementNode: ESTree.IfStatement, consequentSimplifyData: IStatementSimplifyData, alternateSimplifyData: IStatementSimplifyData @@ -183,10 +179,10 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * } */ if ( - consequentSimplifyData.leadingStatements.length - || alternateSimplifyData.leadingStatements.length - || !consequentSimplifyData.trailingStatement - || !alternateSimplifyData.trailingStatement + consequentSimplifyData.leadingStatements.length || + alternateSimplifyData.leadingStatements.length || + !consequentSimplifyData.trailingStatement || + !alternateSimplifyData.trailingStatement ) { return NodeFactory.ifStatementNode( ifStatementNode.test, @@ -262,29 +258,29 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * @param {IStatementSimplifyData} statementSimplifyData * @returns {ESTree.Statement} */ - protected override getPartialStatement (statementSimplifyData: IStatementSimplifyData): ESTree.Statement { + protected override getPartialStatement(statementSimplifyData: IStatementSimplifyData): ESTree.Statement { const partialStatement: ESTree.Statement = super.getPartialStatement(statementSimplifyData); if (!NodeGuards.isBlockStatementNode(partialStatement)) { return partialStatement; } - return partialStatement.body.length === 1 - && !this.isProhibitedSingleStatementForIfStatementBranch(partialStatement.body[0]) + return partialStatement.body.length === 1 && + !this.isProhibitedSingleStatementForIfStatementBranch(partialStatement.body[0]) ? partialStatement.body[0] : partialStatement; - } /** * @param {ESTree.Statement} statement * @returns {boolean} */ - protected isProhibitedSingleStatementForIfStatementBranch (statement: ESTree.Statement): boolean { + protected isProhibitedSingleStatementForIfStatementBranch(statement: ESTree.Statement): boolean { /** * Function declaration is not allowed outside of block in `strict` mode */ - return NodeGuards.isFunctionDeclarationNode(statement) + return ( + NodeGuards.isFunctionDeclarationNode(statement) || /** * Have to ignore all `IfStatement` nodes * Also have to ignore any nodes with a single statement as a `body` @@ -307,9 +303,8 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * * See issue: https://github.com/javascript-obfuscator/javascript-obfuscator/issues/860 */ - || NodeGuards.isIfStatementNode(statement) - || NodeGuards.isNodeWithSingleStatementBody(statement) - + NodeGuards.isIfStatementNode(statement) || + NodeGuards.isNodeWithSingleStatementBody(statement) || /** * `let` and `const` variable declarations are not allowed outside of `IfStatement` block statement * Input: @@ -321,6 +316,7 @@ export class IfStatementSimplifyTransformer extends AbstractStatementSimplifyTra * if (condition1) * const foo = 1; */ - || (NodeGuards.isVariableDeclarationNode(statement) && statement.kind !== 'var'); + (NodeGuards.isVariableDeclarationNode(statement) && statement.kind !== 'var') + ); } } diff --git a/src/node-transformers/simplifying-transformers/VariableDeclarationsMergeTransformer.ts b/src/node-transformers/simplifying-transformers/VariableDeclarationsMergeTransformer.ts index 613f9627..d89c5c03 100644 --- a/src/node-transformers/simplifying-transformers/VariableDeclarationsMergeTransformer.ts +++ b/src/node-transformers/simplifying-transformers/VariableDeclarationsMergeTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -31,7 +31,7 @@ export class VariableDeclarationsMergeTransformer extends AbstractNodeTransforme * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -42,7 +42,7 @@ export class VariableDeclarationsMergeTransformer extends AbstractNodeTransforme * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.Simplifying: return { @@ -66,7 +66,7 @@ export class VariableDeclarationsMergeTransformer extends AbstractNodeTransforme * @param {ESTree.Node} parentNode * @returns {ESTree.VariableDeclaration | estraverse.VisitorOption} */ - public transformNode ( + public transformNode( variableDeclarationNode: ESTree.VariableDeclaration, parentNode: ESTree.Node ): ESTree.VariableDeclaration | estraverse.VisitorOption { @@ -74,7 +74,8 @@ export class VariableDeclarationsMergeTransformer extends AbstractNodeTransforme return variableDeclarationNode; } - const prevStatement: TStatement | null = NodeStatementUtils.getPreviousSiblingStatement(variableDeclarationNode); + const prevStatement: TStatement | null = + NodeStatementUtils.getPreviousSiblingStatement(variableDeclarationNode); if (!prevStatement || !NodeGuards.isVariableDeclarationNode(prevStatement)) { return variableDeclarationNode; diff --git a/src/node-transformers/string-array-transformers/StringArrayRotateFunctionTransformer.ts b/src/node-transformers/string-array-transformers/StringArrayRotateFunctionTransformer.ts index eac0bcba..4788a943 100644 --- a/src/node-transformers/string-array-transformers/StringArrayRotateFunctionTransformer.ts +++ b/src/node-transformers/string-array-transformers/StringArrayRotateFunctionTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; @@ -86,7 +86,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme * @param {TCustomCodeHelperFactory} customCodeHelperFactory * @param {INumberNumericalExpressionAnalyzer} numberNumericalExpressionAnalyzer */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @inject(ServiceIdentifiers.INodeTransformersRunner) transformersRunner: INodeTransformersRunner, @@ -94,7 +94,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme @inject(ServiceIdentifiers.IStringArrayStorageAnalyzer) stringArrayStorageAnalyzer: IStringArrayStorageAnalyzer, @inject(ServiceIdentifiers.Factory__ICustomCodeHelper) customCodeHelperFactory: TCustomCodeHelperFactory, @inject(ServiceIdentifiers.INumberNumericalExpressionAnalyzer) - numberNumericalExpressionAnalyzer: INumberNumericalExpressionAnalyzer + numberNumericalExpressionAnalyzer: INumberNumericalExpressionAnalyzer ) { super(randomGenerator, options); @@ -112,15 +112,12 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme * @param {Program} programNode * @returns {boolean} */ - private static isProgramNodeHasStringLiterals (programNode: ESTree.Program): boolean { + private static isProgramNodeHasStringLiterals(programNode: ESTree.Program): boolean { let hasStringLiterals: boolean = false; estraverse.traverse(programNode, { enter: (node: ESTree.Node): estraverse.VisitorOption | void => { - if ( - NodeGuards.isLiteralNode(node) - && NodeLiteralUtils.isStringLiteralNode(node) - ) { + if (NodeGuards.isLiteralNode(node) && NodeLiteralUtils.isStringLiteralNode(node)) { hasStringLiterals = true; return estraverse.VisitorOption.Break; @@ -135,7 +132,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.stringArrayRotate) { return null; } @@ -165,7 +162,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme * @param {Program} programNode * @returns {Node} */ - public transformNode (programNode: ESTree.Program): ESTree.Node { + public transformNode(programNode: ESTree.Program): ESTree.Node { const stringArrayRotateFunctionNode: TStatement = this.getStringArrayRotateFunctionNode(); const wrappedStringArrayRotateFunctionNode: ESTree.Program = NodeFactory.programNode([ stringArrayRotateFunctionNode @@ -193,10 +190,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme // as ignored to prevent additional transformation of these nodes estraverse.traverse(wrappedStringArrayRotateFunctionNode, { enter: (node: ESTree.Node): void => { - if ( - !NodeGuards.isLiteralNode(node) - || !NodeLiteralUtils.isStringLiteralNode(node) - ) { + if (!NodeGuards.isLiteralNode(node) || !NodeLiteralUtils.isStringLiteralNode(node)) { return; } @@ -205,7 +199,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme if (this.isComparisonExpressionStringLiteralNode(node)) { this.stringArrayStorageAnalyzer.addItemDataForLiteralNode(node); } else { - NodeMetadata.set(node, {ignoredNode: true}); + NodeMetadata.set(node, { ignoredNode: true }); } } }); @@ -218,7 +212,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme /** * @returns {TStatement} */ - private getStringArrayRotateFunctionNode (): TStatement { + private getStringArrayRotateFunctionNode(): TStatement { const comparisonValue: number = this.getComparisonValue(); const comparisonExpressionNumberNumericalExpressionData: TNumberNumericalExpressionData = this.numberNumericalExpressionAnalyzer.analyze( @@ -227,37 +221,36 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme ); let index: number = 1; - const comparisonExpressionNode: ESTree.Expression = NumericalExpressionDataToNodeConverter.convertIntegerNumberData( - comparisonExpressionNumberNumericalExpressionData, - ((number: number, isPositiveNumber) => { - const multipliedNumber: number = number * index; - const literalNode: ESTree.Literal = NodeFactory.literalNode( - `${multipliedNumber}${this.randomGenerator.getRandomString(6)}` - ); - const parseIntCallExpression: ESTree.CallExpression = NodeFactory.callExpressionNode( - NodeFactory.identifierNode('parseInt'), - [literalNode] - ); + const comparisonExpressionNode: ESTree.Expression = + NumericalExpressionDataToNodeConverter.convertIntegerNumberData( + comparisonExpressionNumberNumericalExpressionData, + (number: number, isPositiveNumber) => { + const multipliedNumber: number = number * index; + const literalNode: ESTree.Literal = NodeFactory.literalNode( + `${multipliedNumber}${this.randomGenerator.getRandomString(6)}` + ); + const parseIntCallExpression: ESTree.CallExpression = NodeFactory.callExpressionNode( + NodeFactory.identifierNode('parseInt'), + [literalNode] + ); - const binaryExpressionNode: ESTree.BinaryExpression = NodeFactory.binaryExpressionNode( - '/', - isPositiveNumber - ? parseIntCallExpression - : NodeFactory.unaryExpressionNode( - '-', - parseIntCallExpression - ), - NodeFactory.literalNode(index, index.toString()) - ); + const binaryExpressionNode: ESTree.BinaryExpression = NodeFactory.binaryExpressionNode( + '/', + isPositiveNumber + ? parseIntCallExpression + : NodeFactory.unaryExpressionNode('-', parseIntCallExpression), + NodeFactory.literalNode(index, index.toString()) + ); - index++; + index++; - return binaryExpressionNode; - }) - ); + return binaryExpressionNode; + } + ); - const stringArrayRotateFunctionCodeHelper: ICustomCodeHelper> = - this.customCodeHelperFactory(CustomCodeHelper.StringArrayRotateFunction); + const stringArrayRotateFunctionCodeHelper: ICustomCodeHelper< + TInitialData + > = this.customCodeHelperFactory(CustomCodeHelper.StringArrayRotateFunction); stringArrayRotateFunctionCodeHelper.initialize( this.stringArrayStorage.getStorageName(), @@ -272,7 +265,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme * @param {TStringLiteralNode} stringLiteralNode * @returns {boolean} */ - private isComparisonExpressionStringLiteralNode (stringLiteralNode: TStringLiteralNode): boolean { + private isComparisonExpressionStringLiteralNode(stringLiteralNode: TStringLiteralNode): boolean { return /\d/.test(stringLiteralNode.value); } @@ -281,7 +274,7 @@ export class StringArrayRotateFunctionTransformer extends AbstractNodeTransforme * * @returns {number} */ - private getComparisonValue (): number { + private getComparisonValue(): number { return this.randomGenerator.getRandomInteger(100000, 1_000_000); } } diff --git a/src/node-transformers/string-array-transformers/StringArrayScopeCallsWrapperTransformer.ts b/src/node-transformers/string-array-transformers/StringArrayScopeCallsWrapperTransformer.ts index 9f8c32e0..68a7eb3e 100644 --- a/src/node-transformers/string-array-transformers/StringArrayScopeCallsWrapperTransformer.ts +++ b/src/node-transformers/string-array-transformers/StringArrayScopeCallsWrapperTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -35,9 +35,7 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo /** * @type {NodeTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.StringArrayRotateFunctionTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.StringArrayRotateFunctionTransformer]; /** * @type {IStringArrayStorage} @@ -67,14 +65,16 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {IStringArrayScopeCallsWrappersDataStorage} stringArrayScopeCallsWrappersDataStorage * @param {TStringArrayCustomNodeFactory} stringArrayTransformerCustomNodeFactory */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, - @inject(ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage) visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage, + @inject(ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage) + visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, - @inject(ServiceIdentifiers.IStringArrayScopeCallsWrappersDataStorage) stringArrayScopeCallsWrappersDataStorage: IStringArrayScopeCallsWrappersDataStorage, + @inject(ServiceIdentifiers.IStringArrayScopeCallsWrappersDataStorage) + stringArrayScopeCallsWrappersDataStorage: IStringArrayScopeCallsWrappersDataStorage, @inject(ServiceIdentifiers.Factory__IStringArrayCustomNode) - stringArrayTransformerCustomNodeFactory: TStringArrayCustomNodeFactory + stringArrayTransformerCustomNodeFactory: TStringArrayCustomNodeFactory ) { super(randomGenerator, options); @@ -88,7 +88,7 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { if (!this.options.stringArrayWrappersCount) { return null; } @@ -119,9 +119,7 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {TNodeWithLexicalScopeStatements} lexicalScopeBodyNode * @returns {TNodeWithLexicalScopeStatements} */ - public transformNode ( - lexicalScopeBodyNode: TNodeWithLexicalScopeStatements - ): TNodeWithLexicalScopeStatements { + public transformNode(lexicalScopeBodyNode: TNodeWithLexicalScopeStatements): TNodeWithLexicalScopeStatements { const stringArrayScopeCallsWrappersDataByEncoding: TStringArrayScopeCallsWrappersDataByEncoding | null = this.stringArrayScopeCallsWrappersDataStorage.get(lexicalScopeBodyNode) ?? null; @@ -129,8 +127,9 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo return lexicalScopeBodyNode; } - const stringArrayScopeCallsWrappersDataList: (IStringArrayScopeCallsWrappersData | undefined)[] = - Object.values(stringArrayScopeCallsWrappersDataByEncoding); + const stringArrayScopeCallsWrappersDataList: (IStringArrayScopeCallsWrappersData | undefined)[] = Object.values( + stringArrayScopeCallsWrappersDataByEncoding + ); // iterates over data for each encoding type for (const stringArrayScopeCallsWrappersData of stringArrayScopeCallsWrappersDataList) { @@ -138,7 +137,7 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo continue; } - const {scopeCallsWrappersData} = stringArrayScopeCallsWrappersData; + const { scopeCallsWrappersData } = stringArrayScopeCallsWrappersData; const scopeCallsWrappersDataLength: number = scopeCallsWrappersData.length; /** @@ -147,8 +146,9 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo */ for (let i = scopeCallsWrappersDataLength - 1; i >= 0; i--) { const stringArrayScopeCallsWrapperData = scopeCallsWrappersData[i]; - const upperStringArrayCallsWrapperData = - this.getUpperStringArrayCallsWrapperData(stringArrayScopeCallsWrappersData); + const upperStringArrayCallsWrapperData = this.getUpperStringArrayCallsWrapperData( + stringArrayScopeCallsWrappersData + ); this.getAndAppendStringArrayScopeCallsWrapperNode( lexicalScopeBodyNode, @@ -165,10 +165,10 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {IStringArrayScopeCallsWrappersData} stringArrayScopeCallsWrappersData * @returns {IStringArrayScopeCallsWrapperData} */ - private getRootStringArrayCallsWrapperData ( - stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrappersData, + private getRootStringArrayCallsWrapperData( + stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrappersData ): IStringArrayScopeCallsWrapperData { - const {encoding} = stringArrayScopeCallsWrappersData; + const { encoding } = stringArrayScopeCallsWrappersData; return { name: this.stringArrayStorage.getStorageCallsWrapperName(encoding), @@ -181,29 +181,28 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {IStringArrayScopeCallsWrappersData} stringArrayScopeCallsWrappersData * @returns {IStringArrayScopeCallsWrapperData} */ - private getUpperStringArrayCallsWrapperData ( - stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrappersData, + private getUpperStringArrayCallsWrapperData( + stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrappersData ): IStringArrayScopeCallsWrapperData { - const {encoding} = stringArrayScopeCallsWrappersData; + const { encoding } = stringArrayScopeCallsWrappersData; - const rootStringArrayCallsWrapperData = - this.getRootStringArrayCallsWrapperData(stringArrayScopeCallsWrappersData); + const rootStringArrayCallsWrapperData = this.getRootStringArrayCallsWrapperData( + stringArrayScopeCallsWrappersData + ); if (!this.options.stringArrayWrappersChainedCalls) { return rootStringArrayCallsWrapperData; } const parentLexicalScopeBodyNode: TNodeWithLexicalScopeStatements | null = - this.visitedLexicalScopeNodesStackStorage.getLastElement() - ?? null; + this.visitedLexicalScopeNodesStackStorage.getLastElement() ?? null; if (!parentLexicalScopeBodyNode) { return rootStringArrayCallsWrapperData; } const parentLexicalScopeCallsWrappersDataByEncoding: TStringArrayScopeCallsWrappersDataByEncoding | null = - this.stringArrayScopeCallsWrappersDataStorage - .get(parentLexicalScopeBodyNode) ?? null; + this.stringArrayScopeCallsWrappersDataStorage.get(parentLexicalScopeBodyNode) ?? null; const parentScopeCallsWrappersData: IStringArrayScopeCallsWrapperData[] | null = parentLexicalScopeCallsWrappersDataByEncoding?.[encoding]?.scopeCallsWrappersData ?? null; @@ -211,9 +210,7 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo return rootStringArrayCallsWrapperData; } - return this.randomGenerator - .getRandomGenerator() - .pickone(parentScopeCallsWrappersData); + return this.randomGenerator.getRandomGenerator().pickone(parentScopeCallsWrappersData); } /** @@ -221,10 +218,10 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {IStringArrayScopeCallsWrapperData} stringArrayScopeCallsWrapperData * @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData */ - private getAndAppendStringArrayScopeCallsWrapperNode ( + private getAndAppendStringArrayScopeCallsWrapperNode( lexicalScopeBodyNode: TNodeWithLexicalScopeStatements, stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData, - upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData, + upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData ): void { let stringArrayScopeCallsWrapperNode: TStatement[]; @@ -237,14 +234,10 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo stringArrayScopeCallsWrapperNode = this.getStringArrayScopeCallsWrapperFunctionNode( stringArrayScopeCallsWrapperData, - upperStringArrayCallsWrapperData, + upperStringArrayCallsWrapperData ); - NodeAppender.insertAtIndex( - lexicalScopeBodyNode, - stringArrayScopeCallsWrapperNode, - randomIndex - ); + NodeAppender.insertAtIndex(lexicalScopeBodyNode, stringArrayScopeCallsWrapperNode, randomIndex); break; } @@ -256,10 +249,7 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo upperStringArrayCallsWrapperData ); - NodeAppender.prepend( - lexicalScopeBodyNode, - stringArrayScopeCallsWrapperNode - ); + NodeAppender.prepend(lexicalScopeBodyNode, stringArrayScopeCallsWrapperNode); } } } @@ -269,14 +259,15 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData * @returns {TStatement[]} */ - private getStringArrayScopeCallsWrapperVariableNode ( + private getStringArrayScopeCallsWrapperVariableNode( stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData, upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData ): TStatement[] { - const stringArrayScopeCallsWrapperVariableNode: ICustomNode> = - this.stringArrayTransformerCustomNodeFactory( - StringArrayCustomNode.StringArrayScopeCallsWrapperVariableNode - ); + const stringArrayScopeCallsWrapperVariableNode: ICustomNode< + TInitialData + > = this.stringArrayTransformerCustomNodeFactory( + StringArrayCustomNode.StringArrayScopeCallsWrapperVariableNode + ); stringArrayScopeCallsWrapperVariableNode.initialize( stringArrayScopeCallsWrapperData, @@ -291,14 +282,15 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo * @param {IStringArrayScopeCallsWrapperData} upperStringArrayCallsWrapperData * @returns {TStatement[]} */ - private getStringArrayScopeCallsWrapperFunctionNode ( + private getStringArrayScopeCallsWrapperFunctionNode( stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData, - upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData, + upperStringArrayCallsWrapperData: IStringArrayScopeCallsWrapperData ): TStatement[] { - const stringArrayScopeCallsWrapperFunctionNode: ICustomNode> = - this.stringArrayTransformerCustomNodeFactory( - StringArrayCustomNode.StringArrayScopeCallsWrapperFunctionNode - ); + const stringArrayScopeCallsWrapperFunctionNode: ICustomNode< + TInitialData + > = this.stringArrayTransformerCustomNodeFactory( + StringArrayCustomNode.StringArrayScopeCallsWrapperFunctionNode + ); stringArrayScopeCallsWrapperFunctionNode.initialize( stringArrayScopeCallsWrapperData, @@ -311,11 +303,11 @@ export class StringArrayScopeCallsWrapperTransformer extends AbstractNodeTransfo /** * @param {TNodeWithLexicalScopeStatements} lexicalScopeBodyNode */ - private onLexicalScopeNodeEnter (lexicalScopeBodyNode: TNodeWithLexicalScopeStatements): void { + private onLexicalScopeNodeEnter(lexicalScopeBodyNode: TNodeWithLexicalScopeStatements): void { this.visitedLexicalScopeNodesStackStorage.push(lexicalScopeBodyNode); } - private onLexicalScopeNodeLeave (): void { + private onLexicalScopeNodeLeave(): void { this.visitedLexicalScopeNodesStackStorage.pop(); } } diff --git a/src/node-transformers/string-array-transformers/StringArrayTransformer.ts b/src/node-transformers/string-array-transformers/StringArrayTransformer.ts index 5bd33e10..6c80f573 100644 --- a/src/node-transformers/string-array-transformers/StringArrayTransformer.ts +++ b/src/node-transformers/string-array-transformers/StringArrayTransformer.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as ESTree from 'estree'; @@ -51,9 +51,7 @@ export class StringArrayTransformer extends AbstractNodeTransformer { /** * @type {NodeTransformer[]} */ - public override readonly runAfter: NodeTransformer[] = [ - NodeTransformer.StringArrayRotateFunctionTransformer - ]; + public override readonly runAfter: NodeTransformer[] = [NodeTransformer.StringArrayRotateFunctionTransformer]; /** * @type {IIdentifierNamesGenerator} @@ -101,19 +99,20 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory * @param {TStringArrayCustomNodeFactory} stringArrayTransformerCustomNodeFactory */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @inject(ServiceIdentifiers.ILiteralNodesCacheStorage) literalNodesCacheStorage: ILiteralNodesCacheStorage, - @inject(ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage) visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage, + @inject(ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage) + visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage, @inject(ServiceIdentifiers.IStringArrayStorage) stringArrayStorage: IStringArrayStorage, @inject(ServiceIdentifiers.IStringArrayScopeCallsWrappersDataStorage) - stringArrayScopeCallsWrappersDataStorage: IStringArrayScopeCallsWrappersDataStorage, + stringArrayScopeCallsWrappersDataStorage: IStringArrayScopeCallsWrappersDataStorage, @inject(ServiceIdentifiers.IStringArrayStorageAnalyzer) stringArrayStorageAnalyzer: IStringArrayStorageAnalyzer, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.Factory__IStringArrayCustomNode) - stringArrayTransformerCustomNodeFactory: TStringArrayCustomNodeFactory + stringArrayTransformerCustomNodeFactory: TStringArrayCustomNodeFactory ) { super(randomGenerator, options); @@ -130,7 +129,7 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ - public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { + public getVisitor(nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.StringArray: return { @@ -140,9 +139,9 @@ export class StringArrayTransformer extends AbstractNodeTransformer { } if ( - parentNode - && NodeGuards.isLiteralNode(node) - && !NodeMetadata.isStringArrayCallLiteralNode(node) + parentNode && + NodeGuards.isLiteralNode(node) && + !NodeMetadata.isStringArrayCallLiteralNode(node) ) { return this.transformNode(node, parentNode); } @@ -157,7 +156,7 @@ export class StringArrayTransformer extends AbstractNodeTransformer { /** * @param {Program} programNode */ - public prepareNode (programNode: ESTree.Program): void { + public prepareNode(programNode: ESTree.Program): void { if (this.options.stringArray) { this.stringArrayStorageAnalyzer.analyze(programNode); } @@ -176,10 +175,10 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {NodeGuards} parentNode * @returns {NodeGuards} */ - public transformNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { + public transformNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): ESTree.Node { if ( - !NodeLiteralUtils.isStringLiteralNode(literalNode) - || NodeLiteralUtils.isProhibitedLiteralNode(literalNode, parentNode) + !NodeLiteralUtils.isStringLiteralNode(literalNode) || + NodeLiteralUtils.isProhibitedLiteralNode(literalNode, parentNode) ) { return literalNode; } @@ -189,7 +188,10 @@ export class StringArrayTransformer extends AbstractNodeTransformer { const stringArrayStorageItemData: IStringArrayStorageItemData | undefined = this.stringArrayStorageAnalyzer.getItemDataForLiteralNode(literalNode); const cacheKey: string = this.literalNodesCacheStorage.buildKey(literalValue, stringArrayStorageItemData); - const useCachedValue: boolean = this.literalNodesCacheStorage.shouldUseCachedValue(cacheKey, stringArrayStorageItemData); + const useCachedValue: boolean = this.literalNodesCacheStorage.shouldUseCachedValue( + cacheKey, + stringArrayStorageItemData + ); let resultNode: ESTree.Node; @@ -213,10 +215,10 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {IStringArrayStorageItemData} stringArrayStorageItemData * @returns {Expression} */ - private getStringArrayCallNode (stringArrayStorageItemData: IStringArrayStorageItemData): ESTree.Expression { + private getStringArrayCallNode(stringArrayStorageItemData: IStringArrayStorageItemData): ESTree.Expression { const stringArrayScopeCallsWrapperData: IStringArrayScopeCallsWrapperData = this.getStringArrayScopeCallsWrapperData(stringArrayStorageItemData); - const {decodeKey, index} = stringArrayStorageItemData; + const { decodeKey, index } = stringArrayStorageItemData; const stringArrayCallCustomNode: ICustomNode> = this.stringArrayTransformerCustomNodeFactory(StringArrayCustomNode.StringArrayCallNode); @@ -231,7 +233,9 @@ export class StringArrayTransformer extends AbstractNodeTransformer { const statementNode: TStatement = stringArrayCallCustomNode.getNode()[0]; if (!NodeGuards.isExpressionStatementNode(statementNode)) { - throw new Error('`stringArrayCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node'); + throw new Error( + '`stringArrayCallCustomNode.getNode()[0]` should returns array with `ExpressionStatement` node' + ); } return statementNode.expression; @@ -241,7 +245,7 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {IStringArrayStorageItemData} stringArrayStorageItemData * @returns {IStringArrayScopeCallsWrapperData} */ - private getStringArrayScopeCallsWrapperData ( + private getStringArrayScopeCallsWrapperData( stringArrayStorageItemData: IStringArrayStorageItemData ): IStringArrayScopeCallsWrapperData { return !this.options.stringArrayWrappersCount @@ -253,10 +257,10 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {IStringArrayStorageItemData} stringArrayStorageItemData * @returns {IStringArrayScopeCallsWrapperData} */ - private getRootStringArrayScopeCallsWrapperData ( + private getRootStringArrayScopeCallsWrapperData( stringArrayStorageItemData: IStringArrayStorageItemData ): IStringArrayScopeCallsWrapperData { - const {encoding} = stringArrayStorageItemData; + const { encoding } = stringArrayStorageItemData; const rootStringArrayCallsWrapperName: string = this.stringArrayStorage.getStorageCallsWrapperName(encoding); @@ -271,10 +275,10 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {IStringArrayStorageItemData} stringArrayStorageItemData * @returns {IStringArrayScopeCallsWrapperData} */ - private getUpperStringArrayScopeCallsWrapperData ( + private getUpperStringArrayScopeCallsWrapperData( stringArrayStorageItemData: IStringArrayStorageItemData ): IStringArrayScopeCallsWrapperData { - const {encoding} = stringArrayStorageItemData; + const { encoding } = stringArrayStorageItemData; const currentLexicalScopeBodyNode: TNodeWithLexicalScopeStatements | null = this.visitedLexicalScopeNodesStackStorage.getLastElement() ?? null; @@ -291,9 +295,7 @@ export class StringArrayTransformer extends AbstractNodeTransformer { const stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrapperData[] = stringArrayScopeCallsWrappersDataByEncoding[encoding]?.scopeCallsWrappersData ?? []; - return this.randomGenerator - .getRandomGenerator() - .pickone(stringArrayScopeCallsWrappersData); + return this.randomGenerator.getRandomGenerator().pickone(stringArrayScopeCallsWrappersData); } /** @@ -301,14 +303,13 @@ export class StringArrayTransformer extends AbstractNodeTransformer { * @param {IStringArrayStorageItemData} stringArrayStorageItemData * @returns {TStringArrayScopeCallsWrappersDataByEncoding} */ - private getAndUpdateStringArrayScopeCallsWrappersDataByEncoding ( + private getAndUpdateStringArrayScopeCallsWrappersDataByEncoding( currentLexicalScopeBodyNode: TNodeWithLexicalScopeStatements, - stringArrayStorageItemData: IStringArrayStorageItemData, + stringArrayStorageItemData: IStringArrayStorageItemData ): TStringArrayScopeCallsWrappersDataByEncoding { - const {encoding} = stringArrayStorageItemData; + const { encoding } = stringArrayStorageItemData; const stringArrayScopeCallsWrappersDataByEncoding: TStringArrayScopeCallsWrappersDataByEncoding = - this.stringArrayScopeCallsWrappersDataStorage.get(currentLexicalScopeBodyNode) - ?? {}; + this.stringArrayScopeCallsWrappersDataStorage.get(currentLexicalScopeBodyNode) ?? {}; const stringArrayScopeCallsWrappersData: IStringArrayScopeCallsWrapperData[] = stringArrayScopeCallsWrappersDataByEncoding[encoding]?.scopeCallsWrappersData ?? []; @@ -323,8 +324,7 @@ export class StringArrayTransformer extends AbstractNodeTransformer { const nextScopeCallsWrapperName: string = NodeGuards.isProgramNode(currentLexicalScopeBodyNode) ? this.identifierNamesGenerator.generateForGlobalScope() : this.identifierNamesGenerator.generateNext(); - const nextScopeCallsWrapperShiftedIndex: number = - this.getStringArrayCallsWrapperShiftedIndex(); + const nextScopeCallsWrapperShiftedIndex: number = this.getStringArrayCallsWrapperShiftedIndex(); const nextScopeCallsWrapperParameterIndexesData: IStringArrayScopeCallsWrapperParameterIndexesData | null = this.getStringArrayCallsWrapperParameterIndexesData(); @@ -351,19 +351,19 @@ export class StringArrayTransformer extends AbstractNodeTransformer { /** * @returns {number} */ - private getStringArrayCallsWrapperShiftedIndex (): number { + private getStringArrayCallsWrapperShiftedIndex(): number { return this.options.stringArrayWrappersType === StringArrayWrappersType.Function ? this.randomGenerator.getRandomInteger( - StringArrayTransformer.minShiftedIndexValue, - StringArrayTransformer.maxShiftedIndexValue - ) + StringArrayTransformer.minShiftedIndexValue, + StringArrayTransformer.maxShiftedIndexValue + ) : 0; } /** * @returns {IStringArrayScopeCallsWrapperParameterIndexesData | null} */ - private getStringArrayCallsWrapperParameterIndexesData (): IStringArrayScopeCallsWrapperParameterIndexesData | null { + private getStringArrayCallsWrapperParameterIndexesData(): IStringArrayScopeCallsWrapperParameterIndexesData | null { if (this.options.stringArrayWrappersType !== StringArrayWrappersType.Function) { return null; } @@ -371,10 +371,12 @@ export class StringArrayTransformer extends AbstractNodeTransformer { const minIndexValue: number = 0; const maxIndexValue: number = this.options.stringArrayWrappersParametersMaxCount - 1; - const valueIndexParameterIndex: number = this.randomGenerator - .getRandomInteger(minIndexValue, maxIndexValue); - const decodeKeyParameterIndex: number = this.randomGenerator - .getRandomIntegerExcluding(minIndexValue, maxIndexValue, [valueIndexParameterIndex]); + const valueIndexParameterIndex: number = this.randomGenerator.getRandomInteger(minIndexValue, maxIndexValue); + const decodeKeyParameterIndex: number = this.randomGenerator.getRandomIntegerExcluding( + minIndexValue, + maxIndexValue, + [valueIndexParameterIndex] + ); return { valueIndexParameterIndex, diff --git a/src/node/NodeAppender.ts b/src/node/NodeAppender.ts index 6600644d..461ec588 100644 --- a/src/node/NodeAppender.ts +++ b/src/node/NodeAppender.ts @@ -12,7 +12,7 @@ export class NodeAppender { * @param {TNodeWithStatements} nodeWithStatements * @param {TStatement[]} statements */ - public static append (nodeWithStatements: TNodeWithStatements, statements: TStatement[]): void { + public static append(nodeWithStatements: TNodeWithStatements, statements: TStatement[]): void { statements = NodeAppender.parentizeScopeStatementsBeforeAppend(nodeWithStatements, statements); const updatedStatements: TStatement[] = NodeAppender.getScopeStatements(nodeWithStatements).concat(statements); @@ -42,7 +42,7 @@ export class NodeAppender { * @param {TStatement[]} bodyStatements * @param {number} index */ - public static appendToOptimalBlockScope ( + public static appendToOptimalBlockScope( callsGraphData: ICallsGraphData[], nodeWithStatements: TNodeWithStatements, bodyStatements: TStatement[], @@ -63,7 +63,7 @@ export class NodeAppender { * @param {number} deep * @returns {BlockStatement} */ - public static getOptimalBlockScope ( + public static getOptimalBlockScope( callsGraphData: ICallsGraphData[], index: number, deep: number = Infinity @@ -85,7 +85,7 @@ export class NodeAppender { * @param {TNodeWithStatements} nodeWithStatements * @returns {TStatement[]} */ - public static getScopeStatements (nodeWithStatements: TNodeWithStatements): TStatement[] { + public static getScopeStatements(nodeWithStatements: TNodeWithStatements): TStatement[] { if (NodeGuards.isSwitchCaseNode(nodeWithStatements)) { return nodeWithStatements.consequent; } @@ -98,14 +98,12 @@ export class NodeAppender { * @param {TStatement[]} statements * @param {Node} target */ - public static insertBefore ( + public static insertBefore( nodeWithStatements: TNodeWithStatements, statements: TStatement[], target: ESTree.Statement ): void { - const indexInScopeStatement: number = NodeAppender - .getScopeStatements(nodeWithStatements) - .indexOf(target); + const indexInScopeStatement: number = NodeAppender.getScopeStatements(nodeWithStatements).indexOf(target); NodeAppender.insertAtIndex(nodeWithStatements, statements, indexInScopeStatement); } @@ -115,14 +113,12 @@ export class NodeAppender { * @param {TStatement[]} statements * @param {Node} target */ - public static insertAfter ( + public static insertAfter( nodeWithStatements: TNodeWithStatements, statements: TStatement[], target: ESTree.Statement ): void { - const indexInScopeStatement: number = NodeAppender - .getScopeStatements(nodeWithStatements) - .indexOf(target); + const indexInScopeStatement: number = NodeAppender.getScopeStatements(nodeWithStatements).indexOf(target); NodeAppender.insertAtIndex(nodeWithStatements, statements, indexInScopeStatement + 1); } @@ -132,7 +128,7 @@ export class NodeAppender { * @param {TStatement[]} statements * @param {number} index */ - public static insertAtIndex ( + public static insertAtIndex( nodeWithStatements: TNodeWithStatements, statements: TStatement[], index: number @@ -150,7 +146,7 @@ export class NodeAppender { * @param {TNodeWithStatements} nodeWithStatements * @param {TStatement[]} statements */ - public static prepend (nodeWithStatements: TNodeWithStatements, statements: TStatement[]): void { + public static prepend(nodeWithStatements: TNodeWithStatements, statements: TStatement[]): void { statements = NodeAppender.parentizeScopeStatementsBeforeAppend(nodeWithStatements, statements); const updatedStatements: TStatement[] = statements.concat(NodeAppender.getScopeStatements(nodeWithStatements)); @@ -162,7 +158,7 @@ export class NodeAppender { * @param {TNodeWithStatements} nodeWithStatements * @param {Statement} statement */ - public static remove (nodeWithStatements: TNodeWithStatements, statement: ESTree.Statement): void { + public static remove(nodeWithStatements: TNodeWithStatements, statement: ESTree.Statement): void { const scopeStatements: TStatement[] = NodeAppender.getScopeStatements(nodeWithStatements); const indexInScopeStatement: number = scopeStatements.indexOf(statement); @@ -181,7 +177,7 @@ export class NodeAppender { * @param {TStatement[]} statements * @returns {TStatement[]} */ - private static parentizeScopeStatementsBeforeAppend ( + private static parentizeScopeStatementsBeforeAppend( nodeWithStatements: TNodeWithStatements, statements: TStatement[] ): TStatement[] { @@ -196,7 +192,7 @@ export class NodeAppender { * @param {TNodeWithStatements} nodeWithStatements * @param {TStatement[]} statements */ - private static setScopeStatements (nodeWithStatements: TNodeWithStatements, statements: TStatement[]): void { + private static setScopeStatements(nodeWithStatements: TNodeWithStatements, statements: TStatement[]): void { if (NodeGuards.isSwitchCaseNode(nodeWithStatements)) { nodeWithStatements.consequent = statements; diff --git a/src/node/NodeFactory.ts b/src/node/NodeFactory.ts index 3449f2ef..6057ea1c 100644 --- a/src/node/NodeFactory.ts +++ b/src/node/NodeFactory.ts @@ -11,7 +11,7 @@ export class NodeFactory { * @param {TStatement[]} body * @returns {Program} */ - public static programNode (body: TStatement[] = []): ESTree.Program { + public static programNode(body: TStatement[] = []): ESTree.Program { return { type: NodeType.Program, body, @@ -24,7 +24,7 @@ export class NodeFactory { * @param {(Expression | SpreadElement)[]} elements * @returns {ArrayExpression} */ - public static arrayExpressionNode ( + public static arrayExpressionNode( elements: (ESTree.Expression | ESTree.SpreadElement)[] = [] ): ESTree.ArrayExpression { return { @@ -40,7 +40,7 @@ export class NodeFactory { * @param {Expression} right * @returns {AssignmentExpression} */ - public static assignmentExpressionNode ( + public static assignmentExpressionNode( operator: ESTree.AssignmentOperator, left: ESTree.Pattern | ESTree.MemberExpression, right: ESTree.Expression @@ -60,7 +60,7 @@ export class NodeFactory { * @param {Expression} right * @returns {BinaryExpression} */ - public static binaryExpressionNode ( + public static binaryExpressionNode( operator: ESTree.BinaryOperator, left: ESTree.Expression, right: ESTree.Expression @@ -78,7 +78,7 @@ export class NodeFactory { * @param {Statement[]} body * @returns {BlockStatement} */ - public static blockStatementNode (body: ESTree.Statement[] = []): ESTree.BlockStatement { + public static blockStatementNode(body: ESTree.Statement[] = []): ESTree.BlockStatement { return { type: NodeType.BlockStatement, body, @@ -90,7 +90,7 @@ export class NodeFactory { * @param {Identifier} label * @returns {BreakStatement} */ - public static breakStatement (label?: ESTree.Identifier): ESTree.BreakStatement { + public static breakStatement(label?: ESTree.Identifier): ESTree.BreakStatement { return { type: NodeType.BreakStatement, label, @@ -104,10 +104,10 @@ export class NodeFactory { * @param {boolean} optional * @returns {CallExpression} */ - public static callExpressionNode ( + public static callExpressionNode( callee: ESTree.Expression, args: (ESTree.Expression | ESTree.SpreadElement)[] = [], - optional: boolean = false, + optional: boolean = false ): ESTree.CallExpression { return { type: NodeType.CallExpression, @@ -122,9 +122,7 @@ export class NodeFactory { * @param {ChainElement} expression * @return {ChainExpression} */ - public static chainExpressionNode ( - expression: ESTree.ChainElement, - ): ESTree.ChainExpression { + public static chainExpressionNode(expression: ESTree.ChainElement): ESTree.ChainExpression { return { type: NodeType.ChainExpression, expression, @@ -138,7 +136,7 @@ export class NodeFactory { * @param {ESTree.Expression} alternate * @returns {ESTree.ConditionalExpression} */ - public static conditionalExpressionNode ( + public static conditionalExpressionNode( test: ESTree.Expression, consequent: ESTree.Expression, alternate: ESTree.Expression @@ -156,7 +154,7 @@ export class NodeFactory { * @param {Identifier} label * @returns {ContinueStatement} */ - public static continueStatement (label?: ESTree.Identifier): ESTree.ContinueStatement { + public static continueStatement(label?: ESTree.Identifier): ESTree.ContinueStatement { return { type: NodeType.ContinueStatement, label, @@ -169,10 +167,7 @@ export class NodeFactory { * @param {string} directive * @returns {Directive} */ - public static directiveNode ( - expression: ESTree.Literal, - directive: string - ): ESTree.Directive { + public static directiveNode(expression: ESTree.Literal, directive: string): ESTree.Directive { return { type: NodeType.ExpressionStatement, expression, @@ -186,7 +181,7 @@ export class NodeFactory { * @param {Expression} test * @returns {DoWhileStatement} */ - public static doWhileStatementNode (body: ESTree.Statement, test: ESTree.Expression): ESTree.DoWhileStatement { + public static doWhileStatementNode(body: ESTree.Statement, test: ESTree.Expression): ESTree.DoWhileStatement { return { type: NodeType.DoWhileStatement, body, @@ -200,7 +195,7 @@ export class NodeFactory { * @param {Identifier | null} exported * @returns {ExportAllDeclaration} */ - public static exportAllDeclarationNode ( + public static exportAllDeclarationNode( source: ESTree.Literal, exported: ESTree.Identifier | null ): ESTree.ExportAllDeclaration { @@ -217,7 +212,7 @@ export class NodeFactory { * @param {Literal} source * @returns {ExportNamedDeclaration} */ - public static exportNamedDeclarationNode ( + public static exportNamedDeclarationNode( specifiers: ESTree.ExportSpecifier[], source: ESTree.Literal ): ESTree.ExportNamedDeclaration { @@ -233,7 +228,7 @@ export class NodeFactory { * @param {Expression} expression * @returns {ExpressionStatement} */ - public static expressionStatementNode (expression: ESTree.Expression): ESTree.ExpressionStatement { + public static expressionStatementNode(expression: ESTree.Expression): ESTree.ExpressionStatement { return { type: NodeType.ExpressionStatement, expression, @@ -248,7 +243,7 @@ export class NodeFactory { * @param {Statement} body * @returns {ForStatement} */ - public static forStatementNode ( + public static forStatementNode( init: ESTree.VariableDeclaration | ESTree.Expression | null, test: ESTree.Expression | null, update: ESTree.Expression | null, @@ -270,7 +265,7 @@ export class NodeFactory { * @param {Statement} body * @returns {ForInStatement} */ - public static forInStatementNode ( + public static forInStatementNode( left: ESTree.VariableDeclaration | ESTree.Pattern, right: ESTree.Expression, body: ESTree.Statement @@ -291,7 +286,7 @@ export class NodeFactory { * @param {Statement} body * @returns {ForOfStatement} */ - public static forOfStatementNode ( + public static forOfStatementNode( asAwait: boolean, left: ESTree.VariableDeclaration | ESTree.Pattern, right: ESTree.Expression, @@ -313,7 +308,7 @@ export class NodeFactory { * @param {BlockStatement} body * @returns {FunctionDeclaration} */ - public static functionDeclarationNode ( + public static functionDeclarationNode( functionName: string, params: ESTree.Identifier[], body: ESTree.BlockStatement @@ -333,7 +328,7 @@ export class NodeFactory { * @param {BlockStatement} body * @returns {FunctionExpression} */ - public static functionExpressionNode ( + public static functionExpressionNode( params: ESTree.Pattern[], body: ESTree.BlockStatement ): ESTree.FunctionExpression { @@ -352,7 +347,7 @@ export class NodeFactory { * @param {ESTree.Statement | null} alternate * @returns {ESTree.IfStatement} */ - public static ifStatementNode ( + public static ifStatementNode( test: ESTree.Expression, consequent: ESTree.Statement, alternate?: ESTree.Statement | null @@ -361,7 +356,7 @@ export class NodeFactory { type: NodeType.IfStatement, test, consequent, - ...alternate && { alternate }, + ...(alternate && { alternate }), metadata: { ignoredNode: false } }; } @@ -370,7 +365,7 @@ export class NodeFactory { * @param {string} name * @returns {Identifier} */ - public static identifierNode (name: string): ESTree.Identifier { + public static identifierNode(name: string): ESTree.Identifier { return { type: NodeType.Identifier, name, @@ -383,7 +378,7 @@ export class NodeFactory { * @param {Literal} source * @returns {ImportDeclaration} */ - public static importDeclarationNode ( + public static importDeclarationNode( specifiers: (ESTree.ImportSpecifier | ESTree.ImportDefaultSpecifier | ESTree.ImportNamespaceSpecifier)[], source: ESTree.Literal ): ESTree.ImportDeclaration { @@ -400,10 +395,7 @@ export class NodeFactory { * @param {Statement} body * @returns {LabeledStatement} */ - public static labeledStatementNode ( - label: ESTree.Identifier, - body: ESTree.Statement - ): ESTree.LabeledStatement { + public static labeledStatementNode(label: ESTree.Identifier, body: ESTree.Statement): ESTree.LabeledStatement { return { type: NodeType.LabeledStatement, label, @@ -417,7 +409,7 @@ export class NodeFactory { * @param {string} raw * @returns {Literal} */ - public static literalNode (value: boolean | number | string, raw?: string): ESTree.Literal { + public static literalNode(value: boolean | number | string, raw?: string): ESTree.Literal { raw = raw ?? `'${value}'`; return { @@ -439,10 +431,10 @@ export class NodeFactory { * @param {Expression} right * @returns {LogicalExpression} */ - public static logicalExpressionNode ( + public static logicalExpressionNode( operator: ESTree.LogicalOperator, left: ESTree.Expression, - right: ESTree.Expression, + right: ESTree.Expression ): ESTree.LogicalExpression { return { type: NodeType.LogicalExpression, @@ -460,11 +452,11 @@ export class NodeFactory { * @param {boolean} optional * @returns {MemberExpression} */ - public static memberExpressionNode ( + public static memberExpressionNode( object: ESTree.Expression | ESTree.Super, property: ESTree.Expression, computed: boolean = false, - optional: boolean = false, + optional: boolean = false ): ESTree.MemberExpression { return { type: NodeType.MemberExpression, @@ -480,7 +472,9 @@ export class NodeFactory { * @param {(ESTree.Property | ESTree.SpreadElement)[]} properties * @returns {ESTree.ObjectExpression} */ - public static objectExpressionNode (properties: (ESTree.Property | ESTree.SpreadElement)[]): ESTree.ObjectExpression { + public static objectExpressionNode( + properties: (ESTree.Property | ESTree.SpreadElement)[] + ): ESTree.ObjectExpression { return { type: NodeType.ObjectExpression, properties, @@ -494,7 +488,7 @@ export class NodeFactory { * @param {boolean} computed * @returns {Property} */ - public static propertyNode ( + public static propertyNode( key: ESTree.Expression, value: ESTree.Expression | ESTree.Pattern, computed: boolean = false @@ -515,7 +509,7 @@ export class NodeFactory { * @param {Pattern} argument * @returns {SpreadElement} */ - public static restElementNode (argument: ESTree.Pattern): ESTree.RestElement { + public static restElementNode(argument: ESTree.Pattern): ESTree.RestElement { return { type: NodeType.RestElement, argument, @@ -527,7 +521,7 @@ export class NodeFactory { * @param {Expression} argument * @returns {ReturnStatement} */ - public static returnStatementNode (argument: ESTree.Expression): ESTree.ReturnStatement { + public static returnStatementNode(argument: ESTree.Expression): ESTree.ReturnStatement { return { type: NodeType.ReturnStatement, argument, @@ -539,7 +533,7 @@ export class NodeFactory { * @param {ESTree.Expression[]} expressions * @returns {ESTree.SequenceExpression} */ - public static sequenceExpressionNode (expressions: ESTree.Expression[]): ESTree.SequenceExpression { + public static sequenceExpressionNode(expressions: ESTree.Expression[]): ESTree.SequenceExpression { return { type: NodeType.SequenceExpression, expressions, @@ -551,7 +545,7 @@ export class NodeFactory { * @param {Expression} argument * @returns {SpreadElement} */ - public static spreadElementNode (argument: ESTree.Expression): ESTree.SpreadElement { + public static spreadElementNode(argument: ESTree.Expression): ESTree.SpreadElement { return { type: NodeType.SpreadElement, argument, @@ -563,7 +557,7 @@ export class NodeFactory { * @param {Statement[]} body * @returns {StaticBlock} */ - public static staticBlockNode (body: ESTree.Statement[] = []): ESTree.StaticBlock { + public static staticBlockNode(body: ESTree.Statement[] = []): ESTree.StaticBlock { return { type: NodeType.StaticBlock, body, @@ -576,7 +570,7 @@ export class NodeFactory { * @param {SwitchCase[]} cases * @returns {SwitchStatement} */ - public static switchStatementNode ( + public static switchStatementNode( discriminant: ESTree.Expression, cases: ESTree.SwitchCase[] ): ESTree.SwitchStatement { @@ -593,7 +587,7 @@ export class NodeFactory { * @param {Statement[]} consequent * @returns {SwitchCase} */ - public static switchCaseNode (test: ESTree.Expression, consequent: ESTree.Statement[]): ESTree.SwitchCase { + public static switchCaseNode(test: ESTree.Expression, consequent: ESTree.Statement[]): ESTree.SwitchCase { return { type: NodeType.SwitchCase, test, @@ -608,7 +602,7 @@ export class NodeFactory { * @param {true} prefix * @returns {UnaryExpression} */ - public static unaryExpressionNode ( + public static unaryExpressionNode( operator: ESTree.UnaryOperator, argument: ESTree.Expression, prefix: true = true @@ -627,7 +621,10 @@ export class NodeFactory { * @param {Expression} argumentExpr * @returns {UpdateExpression} */ - public static updateExpressionNode (operator: ESTree.UpdateOperator, argumentExpr: ESTree.Expression): ESTree.UpdateExpression { + public static updateExpressionNode( + operator: ESTree.UpdateOperator, + argumentExpr: ESTree.Expression + ): ESTree.UpdateExpression { return { type: NodeType.UpdateExpression, operator, @@ -642,7 +639,7 @@ export class NodeFactory { * @param {string} kind * @returns {VariableDeclaration} */ - public static variableDeclarationNode ( + public static variableDeclarationNode( declarations: ESTree.VariableDeclarator[] = [], kind: 'var' | 'let' | 'const' = 'var' ): ESTree.VariableDeclaration { @@ -659,7 +656,10 @@ export class NodeFactory { * @param {Expression | null} init * @returns {VariableDeclarator} */ - public static variableDeclaratorNode (id: ESTree.Identifier, init: ESTree.Expression | null): ESTree.VariableDeclarator { + public static variableDeclaratorNode( + id: ESTree.Identifier, + init: ESTree.Expression | null + ): ESTree.VariableDeclarator { return { type: NodeType.VariableDeclarator, id, @@ -673,7 +673,7 @@ export class NodeFactory { * @param {Statement} body * @returns {WhileStatement} */ - public static whileStatementNode (test: ESTree.Expression, body: ESTree.Statement): ESTree.WhileStatement { + public static whileStatementNode(test: ESTree.Expression, body: ESTree.Statement): ESTree.WhileStatement { return { type: NodeType.WhileStatement, test, diff --git a/src/node/NodeGuards.ts b/src/node/NodeGuards.ts index ee6d3568..b34962a3 100644 --- a/src/node/NodeGuards.ts +++ b/src/node/NodeGuards.ts @@ -16,14 +16,14 @@ export class NodeGuards { NodeType.ArrowFunctionExpression, NodeType.FunctionDeclaration, NodeType.FunctionExpression, - NodeType.MethodDefinition, + NodeType.MethodDefinition ]; /** * @param {Node} node * @returns {boolean} */ - public static isArrayPatternNode (node: ESTree.Node): node is ESTree.ArrayPattern { + public static isArrayPatternNode(node: ESTree.Node): node is ESTree.ArrayPattern { return node.type === NodeType.ArrayPattern; } @@ -31,7 +31,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isArrowFunctionExpressionNode (node: ESTree.Node): node is ESTree.ArrowFunctionExpression { + public static isArrowFunctionExpressionNode(node: ESTree.Node): node is ESTree.ArrowFunctionExpression { return node.type === NodeType.ArrowFunctionExpression; } @@ -39,7 +39,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isAssignmentExpressionNode (node: ESTree.Node): node is ESTree.AssignmentExpression { + public static isAssignmentExpressionNode(node: ESTree.Node): node is ESTree.AssignmentExpression { return node.type === NodeType.AssignmentExpression; } @@ -47,7 +47,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isAssignmentPatternNode (node: ESTree.Node): node is ESTree.AssignmentPattern { + public static isAssignmentPatternNode(node: ESTree.Node): node is ESTree.AssignmentPattern { return node.type === NodeType.AssignmentPattern; } @@ -55,7 +55,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isAwaitExpressionNode (node: ESTree.Node): node is ESTree.AwaitExpression { + public static isAwaitExpressionNode(node: ESTree.Node): node is ESTree.AwaitExpression { return node.type === NodeType.AwaitExpression; } @@ -63,7 +63,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isBigIntLiteralNode (node: ESTree.Node): node is ESTree.BigIntLiteral { + public static isBigIntLiteralNode(node: ESTree.Node): node is ESTree.BigIntLiteral { return NodeGuards.isLiteralNode(node) && !!(node).bigint; } @@ -71,7 +71,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isBlockStatementNode (node: ESTree.Node): node is ESTree.BlockStatement { + public static isBlockStatementNode(node: ESTree.Node): node is ESTree.BlockStatement { return node.type === NodeType.BlockStatement; } @@ -79,7 +79,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isBreakStatementNode (node: ESTree.Node): node is ESTree.BreakStatement { + public static isBreakStatementNode(node: ESTree.Node): node is ESTree.BreakStatement { return node.type === NodeType.BreakStatement; } @@ -87,25 +87,23 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isCallExpressionNode (node: ESTree.Node): node is ESTree.CallExpression { + public static isCallExpressionNode(node: ESTree.Node): node is ESTree.CallExpression { return node.type === NodeType.CallExpression; } - /** - * @param {Node} node - * @returns {boolean} - */ - public static isChainExpressionNode (node: ESTree.Node): node is ESTree.ChainExpression { - return node.type === NodeType.ChainExpression; - } - /** * @param {Node} node * @returns {boolean} */ - public static isClassBodyNode ( - node: ESTree.Node - ): node is ESTree.ClassBody { + public static isChainExpressionNode(node: ESTree.Node): node is ESTree.ChainExpression { + return node.type === NodeType.ChainExpression; + } + + /** + * @param {Node} node + * @returns {boolean} + */ + public static isClassBodyNode(node: ESTree.Node): node is ESTree.ClassBody { return node.type === NodeType.ClassBody; } @@ -113,7 +111,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isClassDeclarationNode ( + public static isClassDeclarationNode( node: ESTree.Node ): node is ESTree.ClassDeclaration & { id: ESTree.Identifier } { return node.type === NodeType.ClassDeclaration && node.id !== null; @@ -123,7 +121,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isConditionalExpressionNode (node: ESTree.Node): node is ESTree.ConditionalExpression { + public static isConditionalExpressionNode(node: ESTree.Node): node is ESTree.ConditionalExpression { return node.type === NodeType.ConditionalExpression; } @@ -131,7 +129,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isContinueStatementNode (node: ESTree.Node): node is ESTree.ContinueStatement { + public static isContinueStatementNode(node: ESTree.Node): node is ESTree.ContinueStatement { return node.type === NodeType.ContinueStatement; } @@ -139,16 +137,15 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isDirectiveNode (node: ESTree.Node): node is ESTree.Directive { - return node.type === NodeType.ExpressionStatement - && 'directive' in node; + public static isDirectiveNode(node: ESTree.Node): node is ESTree.Directive { + return node.type === NodeType.ExpressionStatement && 'directive' in node; } /** * @param {Node} node * @returns {boolean} */ - public static isDoWhileStatementNode (node: ESTree.Node): node is ESTree.DoWhileStatement { + public static isDoWhileStatementNode(node: ESTree.Node): node is ESTree.DoWhileStatement { return node.type === NodeType.DoWhileStatement; } @@ -156,7 +153,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isExportAllDeclarationNode (node: ESTree.Node): node is ESTree.ExportAllDeclaration { + public static isExportAllDeclarationNode(node: ESTree.Node): node is ESTree.ExportAllDeclaration { return node.type === NodeType.ExportAllDeclaration; } @@ -164,7 +161,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isExportNamedDeclarationNode (node: ESTree.Node): node is ESTree.ExportNamedDeclaration { + public static isExportNamedDeclarationNode(node: ESTree.Node): node is ESTree.ExportNamedDeclaration { return node.type === NodeType.ExportNamedDeclaration; } @@ -172,7 +169,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isExportSpecifierNode (node: ESTree.Node): node is ESTree.ExportSpecifier { + public static isExportSpecifierNode(node: ESTree.Node): node is ESTree.ExportSpecifier { return node.type === NodeType.ExportSpecifier; } @@ -180,16 +177,15 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isExpressionStatementNode (node: ESTree.Node): node is ESTree.ExpressionStatement { - return node.type === NodeType.ExpressionStatement - && !('directive' in node); + public static isExpressionStatementNode(node: ESTree.Node): node is ESTree.ExpressionStatement { + return node.type === NodeType.ExpressionStatement && !('directive' in node); } /** * @param {Node} node * @returns {boolean} */ - public static isForStatementNode (node: ESTree.Node): node is ESTree.ForStatement { + public static isForStatementNode(node: ESTree.Node): node is ESTree.ForStatement { return node.type === NodeType.ForStatement; } @@ -197,7 +193,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isForInStatementNode (node: ESTree.Node): node is ESTree.ForInStatement { + public static isForInStatementNode(node: ESTree.Node): node is ESTree.ForInStatement { return node.type === NodeType.ForInStatement; } @@ -205,7 +201,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isForOfStatementNode (node: ESTree.Node): node is ESTree.ForOfStatement { + public static isForOfStatementNode(node: ESTree.Node): node is ESTree.ForOfStatement { return node.type === NodeType.ForOfStatement; } @@ -213,17 +209,19 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isFunctionNode (node: ESTree.Node): node is ESTree.Function { - return NodeGuards.isFunctionDeclarationNode(node) || + public static isFunctionNode(node: ESTree.Node): node is ESTree.Function { + return ( + NodeGuards.isFunctionDeclarationNode(node) || NodeGuards.isFunctionExpressionNode(node) || - NodeGuards.isArrowFunctionExpressionNode(node); + NodeGuards.isArrowFunctionExpressionNode(node) + ); } /** * @param {Node} node * @returns {boolean} */ - public static isFunctionDeclarationNode ( + public static isFunctionDeclarationNode( node: ESTree.Node ): node is ESTree.FunctionDeclaration & { id: ESTree.Identifier } { return node.type === NodeType.FunctionDeclaration && node.id !== null; @@ -233,7 +231,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isFunctionExpressionNode (node: ESTree.Node): node is ESTree.FunctionExpression { + public static isFunctionExpressionNode(node: ESTree.Node): node is ESTree.FunctionExpression { return node.type === NodeType.FunctionExpression; } @@ -241,7 +239,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isIdentifierNode (node: ESTree.Node): node is ESTree.Identifier { + public static isIdentifierNode(node: ESTree.Node): node is ESTree.Identifier { return node.type === NodeType.Identifier; } @@ -249,7 +247,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isIfStatementNode (node: ESTree.Node): node is ESTree.IfStatement { + public static isIfStatementNode(node: ESTree.Node): node is ESTree.IfStatement { return node.type === NodeType.IfStatement; } @@ -257,20 +255,22 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isIfStatementNodeWithSingleStatementBody (node: ESTree.Node): node is ESTree.IfStatement { + public static isIfStatementNodeWithSingleStatementBody(node: ESTree.Node): node is ESTree.IfStatement { if (!NodeGuards.isIfStatementNode(node)) { - return false; + return false; } - return !NodeGuards.isBlockStatementNode(node.consequent) - || (!!node.alternate && !NodeGuards.isBlockStatementNode(node.alternate)); + return ( + !NodeGuards.isBlockStatementNode(node.consequent) || + (!!node.alternate && !NodeGuards.isBlockStatementNode(node.alternate)) + ); } /** * @param {Node} node * @returns {boolean} */ - public static isImportDeclarationNode (node: ESTree.Node): node is ESTree.ImportDeclaration { + public static isImportDeclarationNode(node: ESTree.Node): node is ESTree.ImportDeclaration { return node.type === NodeType.ImportDeclaration; } @@ -278,7 +278,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isImportExpressionNode (node: ESTree.Node): node is ESTree.ImportExpression { + public static isImportExpressionNode(node: ESTree.Node): node is ESTree.ImportExpression { return node.type === NodeType.ImportExpression; } @@ -286,7 +286,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isImportSpecifierNode (node: ESTree.Node): node is ESTree.ImportSpecifier { + public static isImportSpecifierNode(node: ESTree.Node): node is ESTree.ImportSpecifier { return node.type === NodeType.ImportSpecifier; } @@ -295,10 +295,13 @@ export class NodeGuards { * @param {Node} parentNode * @returns {boolean} */ - public static isLabelIdentifierNode (node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier { - const parentNodeIsLabeledStatementNode: boolean = NodeGuards.isLabeledStatementNode(parentNode) && parentNode.label === node; - const parentNodeIsContinueStatementNode: boolean = NodeGuards.isContinueStatementNode(parentNode) && parentNode.label === node; - const parentNodeIsBreakStatementNode: boolean = NodeGuards.isBreakStatementNode(parentNode) && parentNode.label === node; + public static isLabelIdentifierNode(node: ESTree.Node, parentNode: ESTree.Node): node is ESTree.Identifier { + const parentNodeIsLabeledStatementNode: boolean = + NodeGuards.isLabeledStatementNode(parentNode) && parentNode.label === node; + const parentNodeIsContinueStatementNode: boolean = + NodeGuards.isContinueStatementNode(parentNode) && parentNode.label === node; + const parentNodeIsBreakStatementNode: boolean = + NodeGuards.isBreakStatementNode(parentNode) && parentNode.label === node; return parentNodeIsLabeledStatementNode || parentNodeIsContinueStatementNode || parentNodeIsBreakStatementNode; } @@ -307,7 +310,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isLabeledStatementNode (node: ESTree.Node): node is ESTree.LabeledStatement { + public static isLabeledStatementNode(node: ESTree.Node): node is ESTree.LabeledStatement { return node.type === NodeType.LabeledStatement; } @@ -315,7 +318,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isLiteralNode (node: ESTree.Node): node is ESTree.Literal { + public static isLiteralNode(node: ESTree.Node): node is ESTree.Literal { return node.type === NodeType.Literal; } @@ -323,7 +326,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isLogicalExpressionNode (node: ESTree.Node): node is ESTree.LogicalExpression { + public static isLogicalExpressionNode(node: ESTree.Node): node is ESTree.LogicalExpression { return node.type === NodeType.LogicalExpression; } @@ -331,7 +334,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isMemberExpressionNode (node: ESTree.Node): node is ESTree.MemberExpression { + public static isMemberExpressionNode(node: ESTree.Node): node is ESTree.MemberExpression { return node.type === NodeType.MemberExpression; } @@ -339,7 +342,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isMetaPropertyNode (node: ESTree.Node): node is ESTree.MetaProperty { + public static isMetaPropertyNode(node: ESTree.Node): node is ESTree.MetaProperty { return node.type === NodeType.MetaProperty; } @@ -347,7 +350,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isMethodDefinitionNode (node: ESTree.Node): node is ESTree.MethodDefinition { + public static isMethodDefinitionNode(node: ESTree.Node): node is ESTree.MethodDefinition { return node.type === NodeType.MethodDefinition; } @@ -355,7 +358,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isNewExpressionNode (node: ESTree.Node): node is ESTree.NewExpression { + public static isNewExpressionNode(node: ESTree.Node): node is ESTree.NewExpression { return node.type === NodeType.NewExpression; } @@ -364,7 +367,7 @@ export class NodeGuards { * @returns {boolean} */ // eslint-disable-next-line @typescript-eslint/ban-types - public static isNode (object: Object & { type?: string }): object is ESTree.Node { + public static isNode(object: Object & { type?: string }): object is ESTree.Node { return object && !object.type !== undefined; } @@ -372,7 +375,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isNodeWithLexicalScope (node: ESTree.Node): node is TNodeWithLexicalScope { + public static isNodeWithLexicalScope(node: ESTree.Node): node is TNodeWithLexicalScope { return NodeGuards.isProgramNode(node) || NodeGuards.isFunctionNode(node); } @@ -380,10 +383,12 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isNodeWithBlockLexicalScope (node: ESTree.Node): node is TNodeWithLexicalScope { - return NodeGuards.isNodeWithLexicalScope(node) - || NodeGuards.isBlockStatementNode(node) - || NodeGuards.isStaticBlockNode(node); + public static isNodeWithBlockLexicalScope(node: ESTree.Node): node is TNodeWithLexicalScope { + return ( + NodeGuards.isNodeWithLexicalScope(node) || + NodeGuards.isBlockStatementNode(node) || + NodeGuards.isStaticBlockNode(node) + ); } /** @@ -397,7 +402,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isNodeWithSingleStatementBody (node: ESTree.Node): node is TNodeWithSingleStatementBody { + public static isNodeWithSingleStatementBody(node: ESTree.Node): node is TNodeWithSingleStatementBody { // Different approach for `IfStatement` node because this node hasn't `body` property if (NodeGuards.isIfStatementNode(node)) { return NodeGuards.isIfStatementNodeWithSingleStatementBody(node); @@ -405,14 +410,15 @@ export class NodeGuards { // All other nodes with `Statement` node as `body` property return ( - NodeGuards.isForStatementNode(node) - || NodeGuards.isForOfStatementNode(node) - || NodeGuards.isForInStatementNode(node) - || NodeGuards.isWhileStatementNode(node) - || NodeGuards.isDoWhileStatementNode(node) - || NodeGuards.isWithStatementNode(node) - || NodeGuards.isLabeledStatementNode(node) - ) && !NodeGuards.isBlockStatementNode(node.body); + (NodeGuards.isForStatementNode(node) || + NodeGuards.isForOfStatementNode(node) || + NodeGuards.isForInStatementNode(node) || + NodeGuards.isWhileStatementNode(node) || + NodeGuards.isDoWhileStatementNode(node) || + NodeGuards.isWithStatementNode(node) || + NodeGuards.isLabeledStatementNode(node)) && + !NodeGuards.isBlockStatementNode(node.body) + ); } /** @@ -420,30 +426,34 @@ export class NodeGuards { * @param {Node} parentNode * @returns {boolean} */ - public static isNodeWithLexicalScopeStatements ( + public static isNodeWithLexicalScopeStatements( node: ESTree.Node, parentNode: ESTree.Node ): node is TNodeWithLexicalScopeStatements { - return NodeGuards.isProgramNode(node) - || (NodeGuards.isBlockStatementNode(node) && NodeGuards.nodesWithLexicalStatements.includes(parentNode.type)); + return ( + NodeGuards.isProgramNode(node) || + (NodeGuards.isBlockStatementNode(node) && NodeGuards.nodesWithLexicalStatements.includes(parentNode.type)) + ); } /** * @param {Node} node * @returns {boolean} */ - public static isNodeWithStatements (node: ESTree.Node): node is TNodeWithStatements { - return NodeGuards.isProgramNode(node) - || NodeGuards.isBlockStatementNode(node) - || NodeGuards.isStaticBlockNode(node) - || NodeGuards.isSwitchCaseNode(node); + public static isNodeWithStatements(node: ESTree.Node): node is TNodeWithStatements { + return ( + NodeGuards.isProgramNode(node) || + NodeGuards.isBlockStatementNode(node) || + NodeGuards.isStaticBlockNode(node) || + NodeGuards.isSwitchCaseNode(node) + ); } /** * @param {Node} node * @returns {boolean} */ - public static isNodeWithComments (node: ESTree.Node): node is ESTree.Node { + public static isNodeWithComments(node: ESTree.Node): node is ESTree.Node { return Boolean(node.leadingComments) || Boolean(node.trailingComments); } @@ -451,7 +461,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isObjectPatternNode (node: ESTree.Node): node is ESTree.ObjectPattern { + public static isObjectPatternNode(node: ESTree.Node): node is ESTree.ObjectPattern { return node.type === NodeType.ObjectPattern; } @@ -459,7 +469,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isObjectExpressionNode (node: ESTree.Node): node is ESTree.ObjectExpression { + public static isObjectExpressionNode(node: ESTree.Node): node is ESTree.ObjectExpression { return node.type === NodeType.ObjectExpression; } @@ -467,7 +477,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isPrivateIdentifierNode (node: ESTree.Node): node is ESTree.PrivateIdentifier { + public static isPrivateIdentifierNode(node: ESTree.Node): node is ESTree.PrivateIdentifier { return node.type === NodeType.PrivateIdentifier; } @@ -475,7 +485,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isProgramNode (node: ESTree.Node): node is ESTree.Program { + public static isProgramNode(node: ESTree.Node): node is ESTree.Program { return node.type === NodeType.Program; } @@ -483,7 +493,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isPropertyNode (node: ESTree.Node): node is ESTree.Property { + public static isPropertyNode(node: ESTree.Node): node is ESTree.Property { return node.type === NodeType.Property; } @@ -491,7 +501,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isPropertyDefinitionNode (node: ESTree.Node): node is ESTree.PropertyDefinition { + public static isPropertyDefinitionNode(node: ESTree.Node): node is ESTree.PropertyDefinition { return node.type === NodeType.PropertyDefinition; } @@ -499,7 +509,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isRestElementNode (node: ESTree.Node): node is ESTree.RestElement { + public static isRestElementNode(node: ESTree.Node): node is ESTree.RestElement { return node.type === NodeType.RestElement; } @@ -507,7 +517,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isReturnStatementNode (node: ESTree.Node): node is ESTree.ReturnStatement { + public static isReturnStatementNode(node: ESTree.Node): node is ESTree.ReturnStatement { return node.type === NodeType.ReturnStatement; } @@ -515,7 +525,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isSequenceExpressionNode (node: ESTree.Node): node is ESTree.SequenceExpression { + public static isSequenceExpressionNode(node: ESTree.Node): node is ESTree.SequenceExpression { return node.type === NodeType.SequenceExpression; } @@ -523,7 +533,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isSpreadElementNode (node: ESTree.Node): node is ESTree.SpreadElement { + public static isSpreadElementNode(node: ESTree.Node): node is ESTree.SpreadElement { return node.type === NodeType.SpreadElement; } @@ -531,7 +541,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isStaticBlockNode (node: ESTree.Node): node is ESTree.StaticBlock { + public static isStaticBlockNode(node: ESTree.Node): node is ESTree.StaticBlock { return node.type === NodeType.StaticBlock; } @@ -539,7 +549,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isSuperNode (node: ESTree.Node): node is ESTree.Super { + public static isSuperNode(node: ESTree.Node): node is ESTree.Super { return node.type === NodeType.Super; } @@ -547,7 +557,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isSwitchCaseNode (node: ESTree.Node): node is ESTree.SwitchCase { + public static isSwitchCaseNode(node: ESTree.Node): node is ESTree.SwitchCase { return node.type === NodeType.SwitchCase; } @@ -555,7 +565,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isTaggedTemplateExpressionNode (node: ESTree.Node): node is ESTree.TaggedTemplateExpression { + public static isTaggedTemplateExpressionNode(node: ESTree.Node): node is ESTree.TaggedTemplateExpression { return node.type === NodeType.TaggedTemplateExpression; } @@ -563,7 +573,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isTemplateLiteralNode (node: ESTree.Node): node is ESTree.TemplateLiteral { + public static isTemplateLiteralNode(node: ESTree.Node): node is ESTree.TemplateLiteral { return node.type === NodeType.TemplateLiteral; } @@ -571,7 +581,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isThisExpressionNode (node: ESTree.Node): node is ESTree.ThisExpression { + public static isThisExpressionNode(node: ESTree.Node): node is ESTree.ThisExpression { return node.type === NodeType.ThisExpression; } @@ -579,7 +589,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isUnaryExpressionNode (node: ESTree.Node): node is ESTree.UnaryExpression { + public static isUnaryExpressionNode(node: ESTree.Node): node is ESTree.UnaryExpression { return node.type === NodeType.UnaryExpression; } @@ -587,7 +597,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isVariableDeclarationNode (node: ESTree.Node): node is ESTree.VariableDeclaration { + public static isVariableDeclarationNode(node: ESTree.Node): node is ESTree.VariableDeclaration { return node.type === NodeType.VariableDeclaration; } @@ -595,7 +605,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isVariableDeclaratorNode (node: ESTree.Node): node is ESTree.VariableDeclarator { + public static isVariableDeclaratorNode(node: ESTree.Node): node is ESTree.VariableDeclarator { return node.type === NodeType.VariableDeclarator; } @@ -603,7 +613,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isWithStatementNode (node: ESTree.Node): node is ESTree.WithStatement { + public static isWithStatementNode(node: ESTree.Node): node is ESTree.WithStatement { return node.type === NodeType.WithStatement; } @@ -611,7 +621,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isWhileStatementNode (node: ESTree.Node): node is ESTree.WhileStatement { + public static isWhileStatementNode(node: ESTree.Node): node is ESTree.WhileStatement { return node.type === NodeType.WhileStatement; } @@ -619,7 +629,7 @@ export class NodeGuards { * @param {Node} node * @returns {boolean} */ - public static isYieldExpressionNode (node: ESTree.Node): node is ESTree.YieldExpression { + public static isYieldExpressionNode(node: ESTree.Node): node is ESTree.YieldExpression { return node.type === NodeType.YieldExpression; } } diff --git a/src/node/NodeLexicalScopeUtils.ts b/src/node/NodeLexicalScopeUtils.ts index eefdbfc1..11950261 100644 --- a/src/node/NodeLexicalScopeUtils.ts +++ b/src/node/NodeLexicalScopeUtils.ts @@ -9,7 +9,7 @@ export class NodeLexicalScopeUtils { * @param {Node} node * @returns {TNodeWithLexicalScope} */ - public static getLexicalScope (node: ESTree.Node): TNodeWithLexicalScope | undefined { + public static getLexicalScope(node: ESTree.Node): TNodeWithLexicalScope | undefined { return NodeLexicalScopeUtils.getLexicalScopesRecursive(node, 1)[0]; } @@ -17,7 +17,7 @@ export class NodeLexicalScopeUtils { * @param {Node} node * @returns {TNodeWithLexicalScope[]} */ - public static getLexicalScopes (node: ESTree.Node): TNodeWithLexicalScope[] { + public static getLexicalScopes(node: ESTree.Node): TNodeWithLexicalScope[] { return NodeLexicalScopeUtils.getLexicalScopesRecursive(node); } @@ -28,7 +28,7 @@ export class NodeLexicalScopeUtils { * @param {number} depth * @returns {TNodeWithLexicalScope[]} */ - private static getLexicalScopesRecursive ( + private static getLexicalScopesRecursive( node: ESTree.Node, maxSize: number = Infinity, nodesWithLexicalScope: TNodeWithLexicalScope[] = [], diff --git a/src/node/NodeLiteralUtils.ts b/src/node/NodeLiteralUtils.ts index 037b207a..db45d690 100644 --- a/src/node/NodeLiteralUtils.ts +++ b/src/node/NodeLiteralUtils.ts @@ -10,7 +10,7 @@ export class NodeLiteralUtils { * @param {Literal} literalNode * @returns {literalNode is TNumberLiteralNode} */ - public static isNumberLiteralNode (literalNode: ESTree.Literal): literalNode is TNumberLiteralNode { + public static isNumberLiteralNode(literalNode: ESTree.Literal): literalNode is TNumberLiteralNode { return typeof literalNode.value === 'number'; } @@ -18,7 +18,7 @@ export class NodeLiteralUtils { * @param {Literal} literalNode * @returns {literalNode is TStringLiteralNode} */ - public static isStringLiteralNode (literalNode: ESTree.Literal): literalNode is TStringLiteralNode { + public static isStringLiteralNode(literalNode: ESTree.Literal): literalNode is TStringLiteralNode { return typeof literalNode.value === 'string'; } @@ -27,7 +27,7 @@ export class NodeLiteralUtils { * @param {Node} parentNode * @returns {boolean} */ - public static isProhibitedLiteralNode (literalNode: ESTree.Literal, parentNode: ESTree.Node): boolean { + public static isProhibitedLiteralNode(literalNode: ESTree.Literal, parentNode: ESTree.Node): boolean { if (NodeGuards.isPropertyNode(parentNode) && !parentNode.computed && parentNode.key === literalNode) { return true; } diff --git a/src/node/NodeMetadata.ts b/src/node/NodeMetadata.ts index aa93c85c..30fc98d8 100644 --- a/src/node/NodeMetadata.ts +++ b/src/node/NodeMetadata.ts @@ -5,7 +5,7 @@ export class NodeMetadata { * @param {T} node * @param {Partial} metadata */ - public static set (node: T, metadata: Partial): void { + public static set(node: T, metadata: Partial): void { node.metadata = Object.assign(node.metadata ?? {}, metadata); } @@ -14,20 +14,18 @@ export class NodeMetadata { * @param {keyof T} metadataKey * @returns {T[keyof T] | undefined} */ - public static get < - T extends ESTree.BaseNodeMetadata, - TMetadataKey extends keyof T - > (node: ESTree.Node, metadataKey: TMetadataKey): T[TMetadataKey] | undefined { - return node.metadata !== undefined - ? (node.metadata)[metadataKey] - : undefined; + public static get( + node: ESTree.Node, + metadataKey: TMetadataKey + ): T[TMetadataKey] | undefined { + return node.metadata !== undefined ? (node.metadata)[metadataKey] : undefined; } /** * @param {Node} node * @returns {boolean} */ - public static isEvalHostNode (node: ESTree.Node): boolean { + public static isEvalHostNode(node: ESTree.Node): boolean { return NodeMetadata.get(node, 'evalHostNode') === true; } @@ -35,7 +33,7 @@ export class NodeMetadata { * @param {Node} node * @returns {boolean} */ - public static isForceTransformNode (node: ESTree.Node): boolean { + public static isForceTransformNode(node: ESTree.Node): boolean { return NodeMetadata.get(node, 'forceTransformNode') === true; } @@ -43,7 +41,7 @@ export class NodeMetadata { * @param {Node} node * @returns {boolean} */ - public static isIgnoredNode (node: ESTree.Node): boolean { + public static isIgnoredNode(node: ESTree.Node): boolean { return NodeMetadata.get(node, 'ignoredNode') === true; } @@ -51,21 +49,25 @@ export class NodeMetadata { * @param {Identifier | Literal} node * @returns {boolean} */ - public static isPropertyKeyToRenameNode (node: ESTree.Identifier | ESTree.Literal): boolean { - return NodeMetadata.get( - node, - 'propertyKeyToRenameNode' - ) === true; + public static isPropertyKeyToRenameNode(node: ESTree.Identifier | ESTree.Literal): boolean { + return ( + NodeMetadata.get( + node, + 'propertyKeyToRenameNode' + ) === true + ); } /** * @param {Node} literalNode * @returns {boolean} */ - public static isStringArrayCallLiteralNode (literalNode: ESTree.Literal): boolean { - return NodeMetadata.get< - ESTree.LiteralNodeMetadata, - 'stringArrayCallLiteralNode' - >(literalNode, 'stringArrayCallLiteralNode') === true; + public static isStringArrayCallLiteralNode(literalNode: ESTree.Literal): boolean { + return ( + NodeMetadata.get( + literalNode, + 'stringArrayCallLiteralNode' + ) === true + ); } } diff --git a/src/node/NodeStatementUtils.ts b/src/node/NodeStatementUtils.ts index 0d31aa9f..6679a2fb 100644 --- a/src/node/NodeStatementUtils.ts +++ b/src/node/NodeStatementUtils.ts @@ -10,7 +10,7 @@ export class NodeStatementUtils { * @param {Node} node * @returns {TNodeWithStatements} */ - public static getParentNodeWithStatements (node: ESTree.Node): TNodeWithStatements { + public static getParentNodeWithStatements(node: ESTree.Node): TNodeWithStatements { return NodeStatementUtils.getParentNodesWithStatementsRecursive(node, 1)[0]; } @@ -18,7 +18,7 @@ export class NodeStatementUtils { * @param {Node} node * @returns {TNodeWithStatements[]} */ - public static getParentNodesWithStatements (node: ESTree.Node): TNodeWithStatements[] { + public static getParentNodesWithStatements(node: ESTree.Node): TNodeWithStatements[] { return NodeStatementUtils.getParentNodesWithStatementsRecursive(node); } @@ -26,7 +26,7 @@ export class NodeStatementUtils { * @param {Statement} statement * @returns {TStatement | null} */ - public static getNextSiblingStatement (statement: ESTree.Statement): TStatement | null { + public static getNextSiblingStatement(statement: ESTree.Statement): TStatement | null { return NodeStatementUtils.getSiblingStatementByOffset(statement, 1); } @@ -34,7 +34,7 @@ export class NodeStatementUtils { * @param {Statement} statement * @returns {TStatement | null} */ - public static getPreviousSiblingStatement (statement: ESTree.Statement): TStatement | null { + public static getPreviousSiblingStatement(statement: ESTree.Statement): TStatement | null { return NodeStatementUtils.getSiblingStatementByOffset(statement, -1); } @@ -42,7 +42,7 @@ export class NodeStatementUtils { * @param {Node} node * @returns {Statement} */ - public static getRootStatementOfNode (node: ESTree.Node): ESTree.Statement { + public static getRootStatementOfNode(node: ESTree.Node): ESTree.Statement { if (NodeGuards.isProgramNode(node)) { throw new Error('Unable to find root statement for `Program` node'); } @@ -64,7 +64,7 @@ export class NodeStatementUtils { * @param {NodeGuards} node * @returns {TNodeWithStatements} */ - public static getScopeOfNode (node: ESTree.Node): TNodeWithStatements { + public static getScopeOfNode(node: ESTree.Node): TNodeWithStatements { const parentNode: ESTree.Node | undefined = node.parentNode; if (!parentNode) { @@ -85,7 +85,7 @@ export class NodeStatementUtils { * @param {number} depth * @returns {TNodeWithStatements[]} */ - private static getParentNodesWithStatementsRecursive ( + private static getParentNodesWithStatementsRecursive( node: ESTree.Node, maxSize: number = Infinity, nodesWithStatements: TNodeWithStatements[] = [], @@ -112,7 +112,12 @@ export class NodeStatementUtils { } if (node !== parentNode) { - return NodeStatementUtils.getParentNodesWithStatementsRecursive(parentNode, maxSize, nodesWithStatements, ++depth); + return NodeStatementUtils.getParentNodesWithStatementsRecursive( + parentNode, + maxSize, + nodesWithStatements, + ++depth + ); } return nodesWithStatements; @@ -123,11 +128,9 @@ export class NodeStatementUtils { * @param {number} offset * @returns {TStatement | null} */ - private static getSiblingStatementByOffset (statement: ESTree.Statement, offset: number): TStatement | null { + private static getSiblingStatementByOffset(statement: ESTree.Statement, offset: number): TStatement | null { const scopeNode: TNodeWithStatements = NodeStatementUtils.getScopeOfNode(statement); - const scopeBody: TStatement[] = !NodeGuards.isSwitchCaseNode(scopeNode) - ? scopeNode.body - : scopeNode.consequent; + const scopeBody: TStatement[] = !NodeGuards.isSwitchCaseNode(scopeNode) ? scopeNode.body : scopeNode.consequent; const indexInScope: number = scopeBody.indexOf(statement); return scopeBody[indexInScope + offset] || null; diff --git a/src/node/NodeUtils.ts b/src/node/NodeUtils.ts index 22f23ed4..2834fb66 100644 --- a/src/node/NodeUtils.ts +++ b/src/node/NodeUtils.ts @@ -13,7 +13,7 @@ export class NodeUtils { * @param {ESTree.Literal} literalNode * @returns {ESTree.Literal} */ - public static addXVerbatimPropertyTo (literalNode: ESTree.Literal): ESTree.Literal { + public static addXVerbatimPropertyTo(literalNode: ESTree.Literal): ESTree.Literal { literalNode['x-verbatim-property'] = { content: literalNode.raw, precedence: escodegen.Precedence.Primary @@ -26,7 +26,7 @@ export class NodeUtils { * @param {T} astTree * @returns {T} */ - public static clone (astTree: T): T { + public static clone(astTree: T): T { return NodeUtils.parentizeAst(NodeUtils.cloneRecursive(astTree)); } @@ -34,14 +34,11 @@ export class NodeUtils { * @param {string} code * @returns {ESTree.Statement[]} */ - public static convertCodeToStructure (code: string): ESTree.Statement[] { - const structure: ESTree.Program = ASTParserFacade.parse( - code, - { - ecmaVersion, - sourceType: 'script' - } - ); + public static convertCodeToStructure(code: string): ESTree.Statement[] { + const structure: ESTree.Program = ASTParserFacade.parse(code, { + ecmaVersion, + sourceType: 'script' + }); estraverse.replace(structure, { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node => { @@ -64,11 +61,14 @@ export class NodeUtils { * @param {NodeGuards[]} structure * @returns {string} */ - public static convertStructureToCode (structure: ESTree.Node[]): string { + public static convertStructureToCode(structure: ESTree.Node[]): string { return structure.reduce((code: string, node: ESTree.Node) => { - return code + escodegen.generate(node, { - sourceMapWithCode: true - }).code; + return ( + code + + escodegen.generate(node, { + sourceMapWithCode: true + }).code + ); }, ''); } @@ -76,7 +76,7 @@ export class NodeUtils { * @param {UnaryExpression} unaryExpressionNode * @returns {NodeGuards} */ - public static getUnaryExpressionArgumentNode (unaryExpressionNode: ESTree.UnaryExpression): ESTree.Node { + public static getUnaryExpressionArgumentNode(unaryExpressionNode: ESTree.UnaryExpression): ESTree.Node { if (NodeGuards.isUnaryExpressionNode(unaryExpressionNode.argument)) { return NodeUtils.getUnaryExpressionArgumentNode(unaryExpressionNode.argument); } @@ -88,7 +88,7 @@ export class NodeUtils { * @param {T} astTree * @returns {T} */ - public static parentizeAst (astTree: T): T { + public static parentizeAst(astTree: T): T { const parentNode: ESTree.Node | null = astTree.parentNode ?? null; estraverse.replace(astTree, { @@ -107,7 +107,7 @@ export class NodeUtils { * @param {Node} parentNode * @returns {T} */ - public static parentizeNode (node: T, parentNode: ESTree.Node | null): T { + public static parentizeNode(node: T, parentNode: ESTree.Node | null): T { node.parentNode = parentNode ?? node; return node; @@ -117,7 +117,7 @@ export class NodeUtils { * @param {T} node * @returns {T} */ - private static cloneRecursive (node: NonNullable): T { + private static cloneRecursive(node: NonNullable): T { if (node === null) { return node; } @@ -125,28 +125,27 @@ export class NodeUtils { const copy: Partial = {}; const nodeKeys: (keyof T)[] = <(keyof T)[]>Object.keys(node); - nodeKeys - .forEach((property: keyof T) => { - if (property === 'parentNode') { - return; - } + nodeKeys.forEach((property: keyof T) => { + if (property === 'parentNode') { + return; + } - const value: T[keyof T] | T[keyof T][] | null = node[property] ?? null; + const value: T[keyof T] | T[keyof T][] | null = node[property] ?? null; - let clonedValue: T[keyof T] | T[keyof T][] | null; + let clonedValue: T[keyof T] | T[keyof T][] | null; - if (value === null || value instanceof RegExp) { - clonedValue = value; - } else if (value instanceof Array) { - clonedValue = value.map(NodeUtils.cloneRecursive); - } else if (typeof value === 'object') { - clonedValue = NodeUtils.cloneRecursive(value); - } else { - clonedValue = value; - } + if (value === null || value instanceof RegExp) { + clonedValue = value; + } else if (value instanceof Array) { + clonedValue = value.map(NodeUtils.cloneRecursive); + } else if (typeof value === 'object') { + clonedValue = NodeUtils.cloneRecursive(value); + } else { + clonedValue = value; + } - copy[property] = clonedValue; - }); + copy[property] = clonedValue; + }); return copy; } diff --git a/src/node/NumericalExpressionDataToNodeConverter.ts b/src/node/NumericalExpressionDataToNodeConverter.ts index 8c1253f4..d217d783 100644 --- a/src/node/NumericalExpressionDataToNodeConverter.ts +++ b/src/node/NumericalExpressionDataToNodeConverter.ts @@ -15,14 +15,14 @@ export class NumericalExpressionDataToNodeConverter { * @param {TNumericalExpressionDataToNodeConverterLiteralNodeGetter} literalNodeGetter * @returns {Expression} */ - public static convertIntegerNumberData ( + public static convertIntegerNumberData( numberNumericalExpressionData: TNumberNumericalExpressionData, literalNodeGetter: TNumericalExpressionDataToNodeConverterLiteralNodeGetter ): ESTree.Expression { - return NumericalExpressionDataToNodeConverter.convertNumericalExpressionDataToNode( - numberNumericalExpressionData, - literalNodeGetter - ); + return NumericalExpressionDataToNodeConverter.convertNumericalExpressionDataToNode( + numberNumericalExpressionData, + literalNodeGetter + ); } /** @@ -31,13 +31,13 @@ export class NumericalExpressionDataToNodeConverter { * @param {TNumericalExpressionDataToNodeConverterLiteralNodeGetter} literalNodeGetter * @returns {Expression} */ - public static convertFloatNumberData ( + public static convertFloatNumberData( integerNumberNumericalExpressionData: TNumberNumericalExpressionData, decimalPart: number, literalNodeGetter: TNumericalExpressionDataToNodeConverterLiteralNodeGetter ): ESTree.Expression { - const integerNumberNumericalExpressionNode: ESTree.Expression = NumericalExpressionDataToNodeConverter - .convertNumericalExpressionDataToNode( + const integerNumberNumericalExpressionNode: ESTree.Expression = + NumericalExpressionDataToNodeConverter.convertNumericalExpressionDataToNode( integerNumberNumericalExpressionData, literalNodeGetter ); @@ -55,24 +55,28 @@ export class NumericalExpressionDataToNodeConverter { * @param {BinaryOperator} operator * @returns {Expression} */ - private static convertNumericalExpressionDataToNode ( + private static convertNumericalExpressionDataToNode( numberNumericalExpressionData: TNumberNumericalExpressionData, literalNodeGetter: TNumericalExpressionDataToNodeConverterLiteralNodeGetter, operator: ESTree.BinaryOperator = '+' ): ESTree.Expression { const numberNumericalExpressionDataLength: number = numberNumericalExpressionData.length; - const leftParts: TNumberNumericalExpressionData = numberNumericalExpressionDataLength > 1 - ? numberNumericalExpressionData.slice(0, numberNumericalExpressionDataLength - 1) - : [numberNumericalExpressionData[0]]; - const rightParts: TNumberNumericalExpressionData = numberNumericalExpressionDataLength > 1 - ? numberNumericalExpressionData.slice(-1) - : []; + const leftParts: TNumberNumericalExpressionData = + numberNumericalExpressionDataLength > 1 + ? numberNumericalExpressionData.slice(0, numberNumericalExpressionDataLength - 1) + : [numberNumericalExpressionData[0]]; + const rightParts: TNumberNumericalExpressionData = + numberNumericalExpressionDataLength > 1 ? numberNumericalExpressionData.slice(-1) : []; // trailing iterations if (rightParts.length) { - return NumericalExpressionDataToNodeConverter - .convertPartsToBinaryExpression(operator, leftParts, rightParts, literalNodeGetter); + return NumericalExpressionDataToNodeConverter.convertPartsToBinaryExpression( + operator, + leftParts, + rightParts, + literalNodeGetter + ); } const firstLeftPartOrNumber: number | number[] | null = leftParts[0] ?? null; @@ -80,14 +84,14 @@ export class NumericalExpressionDataToNodeConverter { // last iteration when only single left part is left return Array.isArray(firstLeftPartOrNumber) ? NumericalExpressionDataToNodeConverter.convertNumericalExpressionDataToNode( - firstLeftPartOrNumber, - literalNodeGetter, - '*' - ) + firstLeftPartOrNumber, + literalNodeGetter, + '*' + ) : NumericalExpressionDataToNodeConverter.convertPartOrNumberToLiteralNode( - firstLeftPartOrNumber, - literalNodeGetter - ); + firstLeftPartOrNumber, + literalNodeGetter + ); } /** @@ -97,7 +101,7 @@ export class NumericalExpressionDataToNodeConverter { * @param {TNumericalExpressionDataToNodeConverterLiteralNodeGetter} literalNodeGetter * @returns {BinaryExpression} */ - private static convertPartsToBinaryExpression ( + private static convertPartsToBinaryExpression( operator: ESTree.BinaryOperator, leftParts: TNumberNumericalExpressionData, rightParts: TNumberNumericalExpressionData, @@ -127,10 +131,7 @@ export class NumericalExpressionDataToNodeConverter { leftParts, literalNodeGetter ), - this.convertPartOrNumberToLiteralNode( - rightPartOrNumber, - literalNodeGetter - ) + this.convertPartOrNumberToLiteralNode(rightPartOrNumber, literalNodeGetter) ); } } @@ -140,13 +141,11 @@ export class NumericalExpressionDataToNodeConverter { * @param {TNumericalExpressionDataToNodeConverterLiteralNodeGetter} literalNodeGetter * @returns {Expression} */ - private static convertPartOrNumberToLiteralNode ( + private static convertPartOrNumberToLiteralNode( partOrNumber: number | number[], literalNodeGetter: TNumericalExpressionDataToNodeConverterLiteralNodeGetter ): ESTree.Expression { - const number: number = Array.isArray(partOrNumber) - ? partOrNumber[0] - : partOrNumber; + const number: number = Array.isArray(partOrNumber) ? partOrNumber[0] : partOrNumber; const isPositiveNumber: boolean = NumberUtils.isPositive(number); const absoluteNumber: number = Math.abs(number); diff --git a/src/node/ScopeIdentifiersTraverser.ts b/src/node/ScopeIdentifiersTraverser.ts index cb50e484..7261bfa9 100644 --- a/src/node/ScopeIdentifiersTraverser.ts +++ b/src/node/ScopeIdentifiersTraverser.ts @@ -1,4 +1,4 @@ -import { inject, injectable, } from 'inversify'; +import { inject, injectable } from 'inversify'; import { ServiceIdentifiers } from '../container/ServiceIdentifiers'; import * as eslintScope from 'eslint-scope'; @@ -27,10 +27,7 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { /** * @type {string[]} */ - private static readonly globalScopeNames: string[] = [ - 'global', - 'module' - ]; + private static readonly globalScopeNames: string[] = ['global', 'module']; /** * @type {IScopeAnalyzer} @@ -40,9 +37,7 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { /** * @param {IScopeAnalyzer} scopeAnalyzer */ - public constructor ( - @inject(ServiceIdentifiers.IScopeAnalyzer) scopeAnalyzer: IScopeAnalyzer - ) { + public constructor(@inject(ServiceIdentifiers.IScopeAnalyzer) scopeAnalyzer: IScopeAnalyzer) { this.scopeAnalyzer = scopeAnalyzer; } @@ -51,7 +46,7 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { * @param {Node | null} parentNode * @param {TScopeIdentifiersTraverserCallback} callback */ - public traverseScopeIdentifiers ( + public traverseScopeIdentifiers( programNode: ESTree.Program, parentNode: ESTree.Node | null, callback: TScopeIdentifiersTraverserCallback @@ -68,7 +63,7 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { * @param {Node | null} parentNode * @param {TScopeIdentifiersTraverserCallback} callback */ - public traverseScopeThroughIdentifiers ( + public traverseScopeThroughIdentifiers( programNode: ESTree.Program, parentNode: ESTree.Node | null, callback: TScopeIdentifiersTraverserCallback @@ -85,13 +80,15 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { * @param {Scope} currentScope * @param {TScopeIdentifiersTraverserCallback} callback */ - private traverseScopeIdentifiersRecursive ( + private traverseScopeIdentifiersRecursive( rootScope: eslintScope.Scope, currentScope: eslintScope.Scope, callback: TScopeIdentifiersTraverserCallback ): void { const variableScope: eslintScope.Scope = currentScope.variableScope; - const variableLexicalScopeNode: TNodeWithLexicalScope | null = NodeGuards.isNodeWithBlockLexicalScope(variableScope.block) + const variableLexicalScopeNode: TNodeWithLexicalScope | null = NodeGuards.isNodeWithBlockLexicalScope( + variableScope.block + ) ? variableScope.block : null; const isGlobalDeclaration: boolean = ScopeIdentifiersTraverser.globalScopeNames.includes(variableScope.type); @@ -105,13 +102,12 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { continue; } - const isBubblingDeclaration: boolean = variable - .identifiers - .some((identifier: ESTree.Node) => - identifier.parentNode - && NodeGuards.isPropertyNode(identifier.parentNode) - && identifier.parentNode.shorthand - ); + const isBubblingDeclaration: boolean = variable.identifiers.some( + (identifier: ESTree.Node) => + identifier.parentNode && + NodeGuards.isPropertyNode(identifier.parentNode) && + identifier.parentNode.shorthand + ); callback({ isGlobalDeclaration, @@ -133,13 +129,15 @@ export class ScopeIdentifiersTraverser implements IScopeIdentifiersTraverser { * @param {Scope} currentScope * @param {TScopeIdentifiersTraverserCallback} callback */ - private traverseScopeThroughIdentifiersRecursive ( + private traverseScopeThroughIdentifiersRecursive( rootScope: eslintScope.Scope, currentScope: eslintScope.Scope, callback: TScopeIdentifiersTraverserCallback ): void { const variableScope: eslintScope.Scope = currentScope.variableScope; - const variableLexicalScopeNode: TNodeWithLexicalScope | null = NodeGuards.isNodeWithBlockLexicalScope(variableScope.block) + const variableLexicalScopeNode: TNodeWithLexicalScope | null = NodeGuards.isNodeWithBlockLexicalScope( + variableScope.block + ) ? variableScope.block : null; const isGlobalDeclaration: boolean = ScopeIdentifiersTraverser.globalScopeNames.includes(variableScope.type); diff --git a/src/options/Options.ts b/src/options/Options.ts index c47f091d..fc1d92d5 100644 --- a/src/options/Options.ts +++ b/src/options/Options.ts @@ -132,10 +132,7 @@ export class Options implements IOptions { @IsString({ each: true }) - @IsAllowedForObfuscationTargets([ - ObfuscationTarget.Browser, - ObfuscationTarget.BrowserNoEval, - ]) + @IsAllowedForObfuscationTargets([ObfuscationTarget.Browser, ObfuscationTarget.BrowserNoEval]) public readonly domainLock!: string[]; /** @@ -182,8 +179,9 @@ export class Options implements IOptions { @IsString({ each: true }) - @ValidateIf((options: IOptions) => - options.identifierNamesGenerator === IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator + @ValidateIf( + (options: IOptions) => + options.identifierNamesGenerator === IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator ) @ArrayNotEmpty() public readonly identifiersDictionary!: string[]; @@ -415,7 +413,12 @@ export class Options implements IOptions { /** * @type {ObfuscationTarget} */ - @IsIn([ObfuscationTarget.Browser, ObfuscationTarget.BrowserNoEval, ObfuscationTarget.Node, ObfuscationTarget.ServiceWorker]) + @IsIn([ + ObfuscationTarget.Browser, + ObfuscationTarget.BrowserNoEval, + ObfuscationTarget.Node, + ObfuscationTarget.ServiceWorker + ]) public readonly target!: TTypeFromEnum; /** @@ -439,7 +442,7 @@ export class Options implements IOptions { * @param {TInputOptions} inputOptions * @param {IOptionsNormalizer} optionsNormalizer */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.TInputOptions) inputOptions: TInputOptions, @inject(ServiceIdentifiers.IOptionsNormalizer) optionsNormalizer: IOptionsNormalizer ) { @@ -462,7 +465,7 @@ export class Options implements IOptions { * @param {TOptionsPreset} optionsPreset * @returns {TInputOptions} */ - public static getOptionsByPreset (optionsPreset: TOptionsPreset): TInputOptions { + public static getOptionsByPreset(optionsPreset: TOptionsPreset): TInputOptions { const options: TInputOptions | null = Options.optionPresetsMap.get(optionsPreset) ?? null; if (!options) { diff --git a/src/options/OptionsNormalizer.ts b/src/options/OptionsNormalizer.ts index e5f54e9a..613a3a6e 100644 --- a/src/options/OptionsNormalizer.ts +++ b/src/options/OptionsNormalizer.ts @@ -43,14 +43,14 @@ export class OptionsNormalizer implements IOptionsNormalizer { StringArrayRule, StringArrayCallsTransformThresholdRule, StringArrayEncodingRule, - StringArrayWrappersChainedCallsRule, + StringArrayWrappersChainedCallsRule ]; /** * @param {IOptions} options * @returns {IOptions} */ - public normalize (options: IOptions): IOptions { + public normalize(options: IOptions): IOptions { let normalizedOptions: IOptions = { ...options }; diff --git a/src/options/ValidationErrorsFormatter.ts b/src/options/ValidationErrorsFormatter.ts index 21c117b1..0e596c0f 100644 --- a/src/options/ValidationErrorsFormatter.ts +++ b/src/options/ValidationErrorsFormatter.ts @@ -7,7 +7,7 @@ export class ValidationErrorsFormatter { * @param {ValidationError[]} errors * @returns {string} */ - public static format (errors: ValidationError[]): string { + public static format(errors: ValidationError[]): string { return errors .reduce( (errorMessages: string[], error: ValidationError) => [ @@ -23,7 +23,7 @@ export class ValidationErrorsFormatter { * @param {ValidationError} error * @returns {string} */ - private static formatWithNestedConstraints (error: ValidationError): string { + private static formatWithNestedConstraints(error: ValidationError): string { const constraints: TDictionary | undefined = error.constraints; if (!constraints) { @@ -31,8 +31,7 @@ export class ValidationErrorsFormatter { } const rootError: string = `\`${error.property}\` errors:\n`; - const nestedErrors: string = Object - .keys(constraints) + const nestedErrors: string = Object.keys(constraints) .map((constraint: string) => ` - ${constraints[constraint]}\n`) .join(); diff --git a/src/options/normalizer-rules/InputFileNameRule.ts b/src/options/normalizer-rules/InputFileNameRule.ts index 0afc0612..753cc17f 100644 --- a/src/options/normalizer-rules/InputFileNameRule.ts +++ b/src/options/normalizer-rules/InputFileNameRule.ts @@ -12,11 +12,9 @@ export const InputFileNameRule: TOptionsNormalizerRule = (options: IOptions): IO let { inputFileName } = options; if (inputFileName) { - inputFileName = inputFileName - .replace(/^\/+/, '') - .split(StringSeparator.Dot) - .slice(0, -1) - .join(StringSeparator.Dot) || inputFileName; + inputFileName = + inputFileName.replace(/^\/+/, '').split(StringSeparator.Dot).slice(0, -1).join(StringSeparator.Dot) || + inputFileName; options = { ...options, diff --git a/src/options/normalizer-rules/SourceMapFileNameRule.ts b/src/options/normalizer-rules/SourceMapFileNameRule.ts index e2fa0746..ac5bf600 100644 --- a/src/options/normalizer-rules/SourceMapFileNameRule.ts +++ b/src/options/normalizer-rules/SourceMapFileNameRule.ts @@ -12,9 +12,7 @@ export const SourceMapFileNameRule: TOptionsNormalizerRule = (options: IOptions) let { sourceMapFileName }: { sourceMapFileName: string } = options; if (sourceMapFileName) { - sourceMapFileName = sourceMapFileName - .replace(/^\/+/, '') - .replace(/(?:\.js)?(?:\.map)?$/, ''); + sourceMapFileName = sourceMapFileName.replace(/^\/+/, '').replace(/(?:\.js)?(?:\.map)?$/, ''); let sourceMapFileNameParts: string[] = sourceMapFileName.split(StringSeparator.Dot); const sourceMapFileNamePartsCount: number = sourceMapFileNameParts.length; diff --git a/src/options/normalizer-rules/StringArrayEncodingRule.ts b/src/options/normalizer-rules/StringArrayEncodingRule.ts index 7782fba5..03399f43 100644 --- a/src/options/normalizer-rules/StringArrayEncodingRule.ts +++ b/src/options/normalizer-rules/StringArrayEncodingRule.ts @@ -12,11 +12,9 @@ export const StringArrayEncodingRule: TOptionsNormalizerRule = (options: IOption if (!options.stringArrayEncoding.length) { options = { ...options, - stringArrayEncoding: [ - StringArrayEncoding.None - ] + stringArrayEncoding: [StringArrayEncoding.None] }; } - + return options; }; diff --git a/src/options/normalizer-rules/StringArrayRule.ts b/src/options/normalizer-rules/StringArrayRule.ts index b766ae8b..c527b8f5 100644 --- a/src/options/normalizer-rules/StringArrayRule.ts +++ b/src/options/normalizer-rules/StringArrayRule.ts @@ -15,9 +15,7 @@ export const StringArrayRule: TOptionsNormalizerRule = (options: IOptions): IOpt stringArray: false, stringArrayCallsTransform: false, stringArrayCallsTransformThreshold: 0, - stringArrayEncoding: [ - StringArrayEncoding.None - ], + stringArrayEncoding: [StringArrayEncoding.None], stringArrayIndexShift: false, stringArrayRotate: false, stringArrayShuffle: false, diff --git a/src/options/presets/Default.ts b/src/options/presets/Default.ts index b8e059f3..7881bd14 100644 --- a/src/options/presets/Default.ts +++ b/src/options/presets/Default.ts @@ -53,12 +53,8 @@ export const DEFAULT_PRESET: TInputOptions = Object.freeze({ stringArray: true, stringArrayCallsTransform: false, stringArrayCallsTransformThreshold: 0.5, - stringArrayEncoding: [ - StringArrayEncoding.None - ], - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber - ], + stringArrayEncoding: [StringArrayEncoding.None], + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber], stringArrayIndexShift: true, stringArrayWrappersChainedCalls: true, stringArrayWrappersCount: 1, diff --git a/src/options/presets/HighObfuscation.ts b/src/options/presets/HighObfuscation.ts index 7dedef17..3044e404 100644 --- a/src/options/presets/HighObfuscation.ts +++ b/src/options/presets/HighObfuscation.ts @@ -14,9 +14,7 @@ export const HIGH_OBFUSCATION_PRESET: TInputOptions = Object.freeze({ optionsPreset: OptionsPreset.HighObfuscation, splitStringsChunkLength: 5, stringArrayCallsTransformThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.Rc4 - ], + stringArrayEncoding: [StringArrayEncoding.Rc4], stringArrayWrappersCount: 5, stringArrayWrappersParametersMaxCount: 5, stringArrayThreshold: 1 diff --git a/src/options/presets/MediumObfuscation.ts b/src/options/presets/MediumObfuscation.ts index 721a1cfe..24f8ae45 100644 --- a/src/options/presets/MediumObfuscation.ts +++ b/src/options/presets/MediumObfuscation.ts @@ -15,9 +15,7 @@ export const MEDIUM_OBFUSCATION_PRESET: TInputOptions = Object.freeze({ splitStrings: true, splitStringsChunkLength: 10, stringArrayCallsTransformThreshold: 0.75, - stringArrayEncoding: [ - StringArrayEncoding.Base64 - ], + stringArrayEncoding: [StringArrayEncoding.Base64], stringArrayWrappersCount: 2, stringArrayWrappersParametersMaxCount: 4, stringArrayWrappersType: StringArrayWrappersType.Function, diff --git a/src/options/presets/NoCustomNodes.ts b/src/options/presets/NoCustomNodes.ts index eb80d021..517f83a3 100644 --- a/src/options/presets/NoCustomNodes.ts +++ b/src/options/presets/NoCustomNodes.ts @@ -49,12 +49,8 @@ export const NO_ADDITIONAL_NODES_PRESET: TInputOptions = Object.freeze({ stringArray: false, stringArrayCallsTransform: false, stringArrayCallsTransformThreshold: 0, - stringArrayEncoding: [ - StringArrayEncoding.None - ], - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber - ], + stringArrayEncoding: [StringArrayEncoding.None], + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber], stringArrayIndexShift: false, stringArrayWrappersChainedCalls: false, stringArrayWrappersCount: 0, diff --git a/src/options/validators/IsAllowedForObfuscationTargets.ts b/src/options/validators/IsAllowedForObfuscationTargets.ts index 435cd44d..38f457c7 100644 --- a/src/options/validators/IsAllowedForObfuscationTargets.ts +++ b/src/options/validators/IsAllowedForObfuscationTargets.ts @@ -15,7 +15,7 @@ import { DEFAULT_PRESET } from '../presets/Default'; * @param {ValidationOptions} validationOptions * @returns {(options: IOptions, propertyName: keyof IOptions) => void} */ -export function IsAllowedForObfuscationTargets ( +export function IsAllowedForObfuscationTargets( obfuscationTargets: TTypeFromEnum[], validationOptions?: ValidationOptions ): (options: IOptions, propertyName: keyof IOptions) => void { @@ -32,7 +32,7 @@ export function IsAllowedForObfuscationTargets ( * @param {ValidationArguments} validationArguments * @returns {boolean} */ - validate (value: IOptions[keyof IOptions], validationArguments: ValidationArguments): boolean { + validate(value: IOptions[keyof IOptions], validationArguments: ValidationArguments): boolean { const options: IOptions = validationArguments.object; const defaultValue: IOptions[keyof IOptions] | undefined = DEFAULT_PRESET[propertyName]; const isDefaultValue: boolean = equal(value, defaultValue); @@ -44,8 +44,10 @@ export function IsAllowedForObfuscationTargets ( * @param {ValidationArguments} validationArguments * @returns {string} */ - defaultMessage (validationArguments: ValidationArguments): string { - const requiredObfuscationTargetsString: string = obfuscationTargets.join(`${StringSeparator.Comma} `); + defaultMessage(validationArguments: ValidationArguments): string { + const requiredObfuscationTargetsString: string = obfuscationTargets.join( + `${StringSeparator.Comma} ` + ); return `This option allowed only for obfuscation targets: ${requiredObfuscationTargetsString}`; } diff --git a/src/options/validators/IsDomainLockRedirectUrl.ts b/src/options/validators/IsDomainLockRedirectUrl.ts index 0fc0fe0e..fe2b42b3 100644 --- a/src/options/validators/IsDomainLockRedirectUrl.ts +++ b/src/options/validators/IsDomainLockRedirectUrl.ts @@ -15,16 +15,16 @@ import { IsAllowedForObfuscationTargets } from './IsAllowedForObfuscationTargets */ export const IsDomainLockRedirectUrl = (): PropertyDecorator => { return (target: any, key: string | symbol): void => { - ValidateIf(({domainLockRedirectUrl}: TInputOptions) => { + ValidateIf(({ domainLockRedirectUrl }: TInputOptions) => { return domainLockRedirectUrl !== DEFAULT_PRESET.domainLockRedirectUrl; })(target, key); IsUrl({ require_protocol: false, require_host: false })(target, key); - IsAllowedForObfuscationTargets([ - ObfuscationTarget.Browser, - ObfuscationTarget.BrowserNoEval, - ])(target, key); + IsAllowedForObfuscationTargets([ObfuscationTarget.Browser, ObfuscationTarget.BrowserNoEval])( + target, + key + ); }; }; diff --git a/src/options/validators/IsIdentifierNamesCache.ts b/src/options/validators/IsIdentifierNamesCache.ts index 4ccf441a..0bf762ed 100644 --- a/src/options/validators/IsIdentifierNamesCache.ts +++ b/src/options/validators/IsIdentifierNamesCache.ts @@ -40,7 +40,7 @@ const validateDictionary = (value: unknown | TIdentifierNamesCacheDictionary): b * @param {ValidationOptions} validationOptions * @returns {(options: IOptions, propertyName: keyof IOptions) => void} */ -export function IsIdentifierNamesCache ( +export function IsIdentifierNamesCache( validationOptions?: ValidationOptions ): (options: IOptions, propertyName: keyof IOptions) => void { return (optionsObject: IOptions, propertyName: keyof IOptions): void => { @@ -56,7 +56,7 @@ export function IsIdentifierNamesCache ( * @param {ValidationArguments} validationArguments * @returns {boolean} */ - validate (value: unknown, validationArguments: ValidationArguments): boolean { + validate(value: unknown, validationArguments: ValidationArguments): boolean { const defaultValue: IOptions[keyof IOptions] | undefined = DEFAULT_PRESET[propertyName]; const isDefaultValue: boolean = equal(value, defaultValue); @@ -78,7 +78,7 @@ export function IsIdentifierNamesCache ( /** * @returns {string} */ - defaultMessage (): string { + defaultMessage(): string { return 'Passed value must be an identifier names cache object or `null` value'; } } diff --git a/src/options/validators/IsInputFileName.ts b/src/options/validators/IsInputFileName.ts index 92b615be..5661d49d 100644 --- a/src/options/validators/IsInputFileName.ts +++ b/src/options/validators/IsInputFileName.ts @@ -10,7 +10,7 @@ import { SourceMapSourcesMode } from '../../enums/source-map/SourceMapSourcesMod export const IsInputFileName = (): PropertyDecorator => { return (target: any, key: string | symbol): void => { IsString()(target, key); - ValidateIf(({sourceMapSourcesMode}: TInputOptions) => { + ValidateIf(({ sourceMapSourcesMode }: TInputOptions) => { return sourceMapSourcesMode === SourceMapSourcesMode.Sources; })(target, key); IsNotEmpty()(target, key); diff --git a/src/source-code/ObfuscationResult.ts b/src/source-code/ObfuscationResult.ts index f9e6f953..30d10f58 100644 --- a/src/source-code/ObfuscationResult.ts +++ b/src/source-code/ObfuscationResult.ts @@ -52,12 +52,12 @@ export class ObfuscationResult implements IObfuscationResult { * @param {IPropertyIdentifierNamesCacheStorage} propertyIdentifierNamesCacheStorage * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.ICryptUtils) cryptUtils: ICryptUtils, @inject(ServiceIdentifiers.IGlobalIdentifierNamesCacheStorage) - globalIdentifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage, + globalIdentifierNamesCacheStorage: IGlobalIdentifierNamesCacheStorage, @inject(ServiceIdentifiers.IPropertyIdentifierNamesCacheStorage) - propertyIdentifierNamesCacheStorage: IPropertyIdentifierNamesCacheStorage, + propertyIdentifierNamesCacheStorage: IPropertyIdentifierNamesCacheStorage, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { this.cryptUtils = cryptUtils; @@ -70,7 +70,7 @@ export class ObfuscationResult implements IObfuscationResult { * @param {string} obfuscatedCode * @param {string} sourceMap */ - public initialize (obfuscatedCode: string, sourceMap: string): void { + public initialize(obfuscatedCode: string, sourceMap: string): void { this.obfuscatedCode = obfuscatedCode; this.sourceMap = sourceMap; } @@ -78,7 +78,7 @@ export class ObfuscationResult implements IObfuscationResult { /** * @returns {string} */ - public getIdentifierNamesCache (): TIdentifierNamesCache { + public getIdentifierNamesCache(): TIdentifierNamesCache { if (!this.options.identifierNamesCache) { return null; } @@ -92,35 +92,35 @@ export class ObfuscationResult implements IObfuscationResult { /** * @returns {string} */ - public getObfuscatedCode (): string { + public getObfuscatedCode(): string { return this.correctObfuscatedCode(); } /** * @returns {IOptions} */ - public getOptions (): IOptions { + public getOptions(): IOptions { return this.options; } /** * @returns {string} */ - public getSourceMap (): string { + public getSourceMap(): string { return this.sourceMap; } /** * @returns {string} */ - public toString (): string { + public toString(): string { return this.obfuscatedCode; } /** * @returns {string} */ - private correctObfuscatedCode (): string { + private correctObfuscatedCode(): string { if (!this.sourceMap) { return this.obfuscatedCode; } diff --git a/src/source-code/SourceCode.ts b/src/source-code/SourceCode.ts index ece6606b..7db97a29 100644 --- a/src/source-code/SourceCode.ts +++ b/src/source-code/SourceCode.ts @@ -15,7 +15,7 @@ export class SourceCode implements ISourceCode { * @param {string} sourceCode * @param {string} sourceMap */ - public constructor (sourceCode: string, sourceMap: string) { + public constructor(sourceCode: string, sourceMap: string) { this.sourceCode = sourceCode; this.sourceMap = sourceMap; } @@ -23,21 +23,21 @@ export class SourceCode implements ISourceCode { /** * @returns {string} */ - public getSourceCode (): string { + public getSourceCode(): string { return this.sourceCode; } /** * @returns {string} */ - public getSourceMap (): string { + public getSourceMap(): string { return this.sourceMap; } /** * @returns {string} */ - public toString (): string { + public toString(): string { return this.sourceCode; } } diff --git a/src/storages/ArrayStorage.ts b/src/storages/ArrayStorage.ts index a29d32c8..cb1fa91c 100644 --- a/src/storages/ArrayStorage.ts +++ b/src/storages/ArrayStorage.ts @@ -8,7 +8,7 @@ import { IRandomGenerator } from '../interfaces/utils/IRandomGenerator'; import { initializable } from '../decorators/Initializable'; @injectable() -export abstract class ArrayStorage implements IArrayStorage { +export abstract class ArrayStorage implements IArrayStorage { /** * @type {V[]} */ @@ -40,7 +40,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -49,7 +49,7 @@ export abstract class ArrayStorage implements IArrayStorage { } @postConstruct() - public initialize (): void { + public initialize(): void { this.storage = []; this.storageId = this.randomGenerator.getRandomString(6); } @@ -58,7 +58,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {number} key * @returns {V | undefined} */ - public delete (key: number): V | undefined { + public delete(key: number): V | undefined { const deletedElement: V | undefined = this.storage.splice(key, 1)[0] ?? undefined; if (deletedElement) { @@ -72,7 +72,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {number} key * @returns {V | undefined} */ - public get (key: number): V | undefined { + public get(key: number): V | undefined { return this.storage[key]; } @@ -80,7 +80,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {number} key * @returns {V} */ - public getOrThrow (key: number): V { + public getOrThrow(key: number): V { const value: V | undefined = this.get(key); if (!value) { @@ -94,7 +94,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {V} value * @returns {number} */ - public getKeyOf (value: V): number | null { + public getKeyOf(value: V): number | null { const key: number = this.storage.indexOf(value); return key >= 0 ? key : null; @@ -103,21 +103,21 @@ export abstract class ArrayStorage implements IArrayStorage { /** * @returns {number} */ - public getLength (): number { + public getLength(): number { return this.storageLength; } /** * @returns {V[]} */ - public getStorage (): V[] { + public getStorage(): V[] { return this.storage; } /** * @returns {string} */ - public getStorageId (): string { + public getStorageId(): string { return this.storageId; } @@ -125,7 +125,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {this} storage * @param {boolean} mergeId */ - public mergeWith (storage: this, mergeId: boolean = false): void { + public mergeWith(storage: this, mergeId: boolean = false): void { this.storage = [...this.storage, ...storage.getStorage()]; if (mergeId) { @@ -137,7 +137,7 @@ export abstract class ArrayStorage implements IArrayStorage { * @param {number} key * @param {V} value */ - public set (key: number, value: V): void { + public set(key: number, value: V): void { if (key === this.storageLength) { this.storage.push(value); } else { diff --git a/src/storages/MapStorage.ts b/src/storages/MapStorage.ts index cc9b8842..4935099f 100644 --- a/src/storages/MapStorage.ts +++ b/src/storages/MapStorage.ts @@ -9,7 +9,7 @@ import { initializable } from '../decorators/Initializable'; import { TDictionary } from '../types/TDictionary'; @injectable() -export abstract class MapStorage implements IMapStorage { +export abstract class MapStorage implements IMapStorage { /** * @type {string} */ @@ -20,7 +20,7 @@ export abstract class MapStorage implements IMapStorage { * @type {Map } */ @initializable() - protected storage!: Map ; + protected storage!: Map; /** * @type {IOptions} @@ -36,7 +36,7 @@ export abstract class MapStorage implements IMapStorage { * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -45,8 +45,8 @@ export abstract class MapStorage implements IMapStorage { } @postConstruct() - public initialize (): void { - this.storage = new Map (); + public initialize(): void { + this.storage = new Map(); this.storageId = this.randomGenerator.getRandomString(6); } @@ -54,7 +54,7 @@ export abstract class MapStorage implements IMapStorage { * @param {K} key * @returns {V | undefined} */ - public get (key: K): V | undefined { + public get(key: K): V | undefined { return this.storage.get(key); } @@ -62,7 +62,7 @@ export abstract class MapStorage implements IMapStorage { * @param {K} key * @returns {V} */ - public getOrThrow (key: K): V { + public getOrThrow(key: K): V { const value: V | undefined = this.get(key); if (!value) { @@ -76,7 +76,7 @@ export abstract class MapStorage implements IMapStorage { * @param {V} value * @returns {K | null} */ - public getKeyOf (value: V): K | null { + public getKeyOf(value: V): K | null { for (const [key, storageValue] of this.storage) { if (value === storageValue) { return key; @@ -89,28 +89,28 @@ export abstract class MapStorage implements IMapStorage { /** * @returns {number} */ - public getLength (): number { + public getLength(): number { return this.storage.size; } /** * @returns {Map} */ - public getStorage (): Map { + public getStorage(): Map { return this.storage; } /** * @returns {TDictionary} */ - public getStorageAsDictionary (): TDictionary { + public getStorageAsDictionary(): TDictionary { return Object.fromEntries(this.storage); } /** * @returns {string} */ - public getStorageId (): string { + public getStorageId(): string { return this.storageId; } @@ -118,7 +118,7 @@ export abstract class MapStorage implements IMapStorage { * @param {K} key * @returns {boolean} */ - public has (key: K): boolean { + public has(key: K): boolean { return this.storage.has(key); } @@ -126,8 +126,8 @@ export abstract class MapStorage implements IMapStorage { * @param {this} storage * @param {boolean} mergeId */ - public mergeWith (storage: this, mergeId: boolean = false): void { - this.storage = new Map ([...this.storage, ...storage.getStorage()]); + public mergeWith(storage: this, mergeId: boolean = false): void { + this.storage = new Map([...this.storage, ...storage.getStorage()]); if (mergeId) { this.storageId = storage.getStorageId(); @@ -138,7 +138,7 @@ export abstract class MapStorage implements IMapStorage { * @param {K} key * @param {V} value */ - public set (key: K, value: V): void { + public set(key: K, value: V): void { this.storage.set(key, value); } } diff --git a/src/storages/WeakMapStorage.ts b/src/storages/WeakMapStorage.ts index bfe2f7bc..9184940c 100644 --- a/src/storages/WeakMapStorage.ts +++ b/src/storages/WeakMapStorage.ts @@ -8,7 +8,7 @@ import { IWeakMapStorage } from '../interfaces/storages/IWeakMapStorage'; import { initializable } from '../decorators/Initializable'; @injectable() -export abstract class WeakMapStorage implements IWeakMapStorage { +export abstract class WeakMapStorage implements IWeakMapStorage { /** * @type {string} */ @@ -19,7 +19,7 @@ export abstract class WeakMapStorage implements IWeakMapSt * @type {WeakMap } */ @initializable() - protected storage!: WeakMap ; + protected storage!: WeakMap; /** * @type {IOptions} @@ -35,7 +35,7 @@ export abstract class WeakMapStorage implements IWeakMapSt * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -44,8 +44,8 @@ export abstract class WeakMapStorage implements IWeakMapSt } @postConstruct() - public initialize (): void { - this.storage = new Map (); + public initialize(): void { + this.storage = new Map(); this.storageId = this.randomGenerator.getRandomString(6); } @@ -53,7 +53,7 @@ export abstract class WeakMapStorage implements IWeakMapSt * @param {K} key * @returns {V | undefined} */ - public get (key: K): V | undefined { + public get(key: K): V | undefined { return this.storage.get(key); } @@ -61,7 +61,7 @@ export abstract class WeakMapStorage implements IWeakMapSt * @param {K} key * @returns {V} */ - public getOrThrow (key: K): V { + public getOrThrow(key: K): V { const value: V | undefined = this.get(key); if (!value) { @@ -74,14 +74,14 @@ export abstract class WeakMapStorage implements IWeakMapSt /** * @returns {WeakMap} */ - public getStorage (): WeakMap { + public getStorage(): WeakMap { return this.storage; } /** * @returns {string} */ - public getStorageId (): string { + public getStorageId(): string { return this.storageId; } @@ -89,7 +89,7 @@ export abstract class WeakMapStorage implements IWeakMapSt * @param {K} key * @returns {boolean} */ - public has (key: K): boolean { + public has(key: K): boolean { return this.storage.has(key); } @@ -97,7 +97,7 @@ export abstract class WeakMapStorage implements IWeakMapSt * @param {K} key * @param {V} value */ - public set (key: K, value: V): void { + public set(key: K, value: V): void { this.storage.set(key, value); } } diff --git a/src/storages/control-flow-transformers/FunctionControlFlowStorage.ts b/src/storages/control-flow-transformers/FunctionControlFlowStorage.ts index 655f23e1..30b4b9c0 100644 --- a/src/storages/control-flow-transformers/FunctionControlFlowStorage.ts +++ b/src/storages/control-flow-transformers/FunctionControlFlowStorage.ts @@ -5,16 +5,14 @@ import { TIdentifierNamesGeneratorFactory } from '../../types/container/generato import { IControlFlowStorage } from '../../interfaces/storages/control-flow-transformers/IControlFlowStorage'; import { ICustomNode } from '../../interfaces/custom-nodes/ICustomNode'; -import { - IIdentifierNamesGenerator -} from '../../interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator'; +import { IIdentifierNamesGenerator } from '../../interfaces/generators/identifier-names-generators/IIdentifierNamesGenerator'; import { IOptions } from '../../interfaces/options/IOptions'; import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator'; import { MapStorage } from '../MapStorage'; @injectable() -export class FunctionControlFlowStorage extends MapStorage implements IControlFlowStorage { +export class FunctionControlFlowStorage extends MapStorage implements IControlFlowStorage { /** * @type {IIdentifierNamesGenerator} */ @@ -25,11 +23,11 @@ export class FunctionControlFlowStorage extends MapStorage * @param {IOptions} options * @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory ) { super(randomGenerator, options); diff --git a/src/storages/control-flow-transformers/StringControlFlowStorage.ts b/src/storages/control-flow-transformers/StringControlFlowStorage.ts index 5ff22c7d..7288e7b2 100644 --- a/src/storages/control-flow-transformers/StringControlFlowStorage.ts +++ b/src/storages/control-flow-transformers/StringControlFlowStorage.ts @@ -15,17 +15,16 @@ export class StringControlFlowStorage extends FunctionControlFlowStorage { * @param {IOptions} options * @param {TIdentifierNamesGeneratorFactory} identifierNamesGeneratorFactory */ - public constructor ( - + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory ) { super(randomGenerator, options, identifierNamesGeneratorFactory); } - public override initialize (): void { + public override initialize(): void { super.initialize(); this.storageId = this.identifierNamesGenerator.generateForGlobalScope(); diff --git a/src/storages/custom-code-helpers/CustomCodeHelperGroupStorage.ts b/src/storages/custom-code-helpers/CustomCodeHelperGroupStorage.ts index 11cafa37..d43fa5af 100644 --- a/src/storages/custom-code-helpers/CustomCodeHelperGroupStorage.ts +++ b/src/storages/custom-code-helpers/CustomCodeHelperGroupStorage.ts @@ -12,7 +12,7 @@ import { CustomCodeHelperGroup } from '../../enums/custom-code-helpers/CustomCod import { MapStorage } from '../MapStorage'; @injectable() -export class CustomCodeHelperGroupStorage extends MapStorage { +export class CustomCodeHelperGroupStorage extends MapStorage { /** * @type {CustomCodeHelperGroup[]} */ @@ -34,8 +34,9 @@ export class CustomCodeHelperGroupStorage extends MapStorage { - const customCodeHelperGroup: ICustomCodeHelperGroup = this.customCodeHelperGroupFactory(customCodeHelperGroupName); + CustomCodeHelperGroupStorage.customCodeHelperGroupsList.forEach( + (customCodeHelperGroupName: CustomCodeHelperGroup) => { + const customCodeHelperGroup: ICustomCodeHelperGroup = + this.customCodeHelperGroupFactory(customCodeHelperGroupName); - this.storage.set(customCodeHelperGroupName, customCodeHelperGroup); - }); + this.storage.set(customCodeHelperGroupName, customCodeHelperGroup); + } + ); } } diff --git a/src/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.ts b/src/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.ts index 1453d0af..04fc83a1 100644 --- a/src/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.ts +++ b/src/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.ts @@ -8,12 +8,15 @@ import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator'; import { MapStorage } from '../MapStorage'; @injectable() -export class GlobalIdentifierNamesCacheStorage extends MapStorage implements IGlobalIdentifierNamesCacheStorage { - /** +export class GlobalIdentifierNamesCacheStorage + extends MapStorage + implements IGlobalIdentifierNamesCacheStorage +{ + /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -21,8 +24,8 @@ export class GlobalIdentifierNamesCacheStorage extends MapStorage implements IPropertyIdentifierNamesCacheStorage { - /** +export class PropertyIdentifierNamesCacheStorage + extends MapStorage + implements IPropertyIdentifierNamesCacheStorage +{ + /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -21,8 +24,8 @@ export class PropertyIdentifierNamesCacheStorage extends MapStorage implements ILiteralNodesCacheStorage { +export class LiteralNodesCacheStorage extends MapStorage implements ILiteralNodesCacheStorage { /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -30,10 +30,7 @@ export class LiteralNodesCacheStorage extends MapStorage i * @param {IStringArrayStorageItemData | undefined} stringArrayStorageItemData * @returns {string} */ - public buildKey ( - literalValue: string, - stringArrayStorageItemData: IStringArrayStorageItemData | undefined, - ): string { + public buildKey(literalValue: string, stringArrayStorageItemData: IStringArrayStorageItemData | undefined): string { return `${literalValue}-${Boolean(stringArrayStorageItemData)}`; } @@ -42,14 +39,16 @@ export class LiteralNodesCacheStorage extends MapStorage i * @param {IStringArrayStorageItemData | undefined} stringArrayStorageItemData * @returns {boolean} */ - public shouldUseCachedValue ( + public shouldUseCachedValue( key: string, stringArrayStorageItemData: IStringArrayStorageItemData | undefined ): boolean { // for each function scope different nodes will be created, so cache have no sense - return !this.options.stringArrayWrappersCount + return ( + !this.options.stringArrayWrappersCount && // different nodes will be created with different rc4 keys, so cache have no sense - && stringArrayStorageItemData?.encoding !== StringArrayEncoding.Rc4 - && this.storage.has(key); + stringArrayStorageItemData?.encoding !== StringArrayEncoding.Rc4 && + this.storage.has(key) + ); } } diff --git a/src/storages/string-array-transformers/StringArrayScopeCallsWrappersDataStorage.ts b/src/storages/string-array-transformers/StringArrayScopeCallsWrappersDataStorage.ts index 153b0abf..11d15a67 100644 --- a/src/storages/string-array-transformers/StringArrayScopeCallsWrappersDataStorage.ts +++ b/src/storages/string-array-transformers/StringArrayScopeCallsWrappersDataStorage.ts @@ -11,15 +11,15 @@ import { IStringArrayScopeCallsWrappersDataStorage } from '../../interfaces/stor import { WeakMapStorage } from '../WeakMapStorage'; @injectable() -export class StringArrayScopeCallsWrappersDataStorage extends WeakMapStorage < - TNodeWithLexicalScopeStatements, - TStringArrayScopeCallsWrappersDataByEncoding -> implements IStringArrayScopeCallsWrappersDataStorage { +export class StringArrayScopeCallsWrappersDataStorage + extends WeakMapStorage + implements IStringArrayScopeCallsWrappersDataStorage +{ /** * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { diff --git a/src/storages/string-array-transformers/StringArrayStorage.ts b/src/storages/string-array-transformers/StringArrayStorage.ts index 7d91579b..ebdd0407 100644 --- a/src/storages/string-array-transformers/StringArrayStorage.ts +++ b/src/storages/string-array-transformers/StringArrayStorage.ts @@ -18,7 +18,10 @@ import { StringArrayEncoding } from '../../enums/node-transformers/string-array- import { MapStorage } from '../MapStorage'; @injectable() -export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEncoding}`, IStringArrayStorageItemData> implements IStringArrayStorage { +export class StringArrayStorage + extends MapStorage<`${string}-${TStringArrayEncoding}`, IStringArrayStorageItemData> + implements IStringArrayStorage +{ /** * @type {number} */ @@ -106,9 +109,9 @@ export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEnc * @param {IOptions} options * @param {ICryptUtilsStringArray} cryptUtilsStringArray */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.Factory__IIdentifierNamesGenerator) - identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, + identifierNamesGeneratorFactory: TIdentifierNamesGeneratorFactory, @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions, @@ -120,68 +123,69 @@ export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEnc this.arrayUtils = arrayUtils; this.cryptUtilsStringArray = cryptUtilsStringArray; - this.rc4Keys = this.randomGenerator.getRandomGenerator() - .n( - () => this.randomGenerator.getRandomGenerator().string({ + this.rc4Keys = this.randomGenerator.getRandomGenerator().n( + () => + this.randomGenerator.getRandomGenerator().string({ length: StringArrayStorage.rc4KeyLength }), - StringArrayStorage.rc4KeysCount - ); + StringArrayStorage.rc4KeysCount + ); } @postConstruct() - public override initialize (): void { + public override initialize(): void { super.initialize(); this.indexShiftAmount = this.options.stringArrayIndexShift ? this.randomGenerator.getRandomInteger( - StringArrayStorage.minimumIndexShiftAmount, - StringArrayStorage.maximumIndexShiftAmount - ) + StringArrayStorage.minimumIndexShiftAmount, + StringArrayStorage.maximumIndexShiftAmount + ) : 0; this.rotationAmount = this.options.stringArrayRotate ? this.randomGenerator.getRandomInteger( - StringArrayStorage.minimumRotationAmount, - StringArrayStorage.maximumRotationAmount - ) + StringArrayStorage.minimumRotationAmount, + StringArrayStorage.maximumRotationAmount + ) : 0; } /** * @param {string} value */ - public override get (value: string): IStringArrayStorageItemData { + public override get(value: string): IStringArrayStorageItemData { return this.getOrSetIfDoesNotExist(value); } /** * @returns {number} */ - public getIndexShiftAmount (): number { + public getIndexShiftAmount(): number { return this.indexShiftAmount; } /** * @returns {number} */ - public getRotationAmount (): number { + public getRotationAmount(): number { return this.rotationAmount; } /** * @returns {string} */ - public getStorageName (): string { + public getStorageName(): string { return this.getStorageId(); } /** * @returns {string} */ - public override getStorageId (): string { + public override getStorageId(): string { if (!this.stringArrayStorageName) { - this.stringArrayStorageName = this.identifierNamesGenerator - .generateForGlobalScope(StringArrayStorage.stringArrayFunctionNameLength); + this.stringArrayStorageName = this.identifierNamesGenerator.generateForGlobalScope( + StringArrayStorage.stringArrayFunctionNameLength + ); } return this.stringArrayStorageName; @@ -191,56 +195,48 @@ export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEnc * @param {TStringArrayEncoding | null} stringArrayEncoding * @returns {IStringArrayCallsWrapperNames} */ - public getStorageCallsWrapperName (stringArrayEncoding: TStringArrayEncoding | null): string { - const storageCallsWrapperName: string | null = this.stringArrayStorageCallsWrapperNamesMap - .get(stringArrayEncoding) ?? null; + public getStorageCallsWrapperName(stringArrayEncoding: TStringArrayEncoding | null): string { + const storageCallsWrapperName: string | null = + this.stringArrayStorageCallsWrapperNamesMap.get(stringArrayEncoding) ?? null; if (storageCallsWrapperName) { return storageCallsWrapperName; } - const newStorageCallsWrapperName: string = this.identifierNamesGenerator - .generateForGlobalScope(StringArrayStorage.stringArrayFunctionNameLength); - - this.stringArrayStorageCallsWrapperNamesMap.set( - stringArrayEncoding, - newStorageCallsWrapperName + const newStorageCallsWrapperName: string = this.identifierNamesGenerator.generateForGlobalScope( + StringArrayStorage.stringArrayFunctionNameLength ); + this.stringArrayStorageCallsWrapperNamesMap.set(stringArrayEncoding, newStorageCallsWrapperName); + return newStorageCallsWrapperName; } - public rotateStorage (): void { + public rotateStorage(): void { if (!this.getLength()) { return; } - this.storage = new Map( - this.arrayUtils.rotate( - Array.from(this.storage.entries()), - this.rotationAmount - ) - ); + this.storage = new Map(this.arrayUtils.rotate(Array.from(this.storage.entries()), this.rotationAmount)); } - public shuffleStorage (): void { + public shuffleStorage(): void { this.storage = new Map( this.arrayUtils .shuffle(Array.from(this.storage.entries())) .map<[`${string}-${TStringArrayEncoding}`, IStringArrayStorageItemData]>( - ( - [value, stringArrayStorageItemData], - index: number - ) => { + ([value, stringArrayStorageItemData], index: number) => { stringArrayStorageItemData.index = index; return [value, stringArrayStorageItemData]; } ) - .sort(( - [, stringArrayStorageItemDataA]: [string, IStringArrayStorageItemData], - [, stringArrayStorageItemDataB]: [string, IStringArrayStorageItemData] - ) => stringArrayStorageItemDataA.index - stringArrayStorageItemDataB.index) + .sort( + ( + [, stringArrayStorageItemDataA]: [string, IStringArrayStorageItemData], + [, stringArrayStorageItemDataB]: [string, IStringArrayStorageItemData] + ) => stringArrayStorageItemDataA.index - stringArrayStorageItemDataB.index + ) ); } @@ -248,7 +244,7 @@ export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEnc * @param {string} value * @returns {IStringArrayStorageItemData} */ - private getOrSetIfDoesNotExist (value: string): IStringArrayStorageItemData { + private getOrSetIfDoesNotExist(value: string): IStringArrayStorageItemData { const { encodedValue, encoding, decodeKey }: IEncodedValue = this.getEncodedValue(value); const cacheKey: `${string}-${TStringArrayEncoding}` = `${encodedValue}-${encoding}`; @@ -275,11 +271,9 @@ export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEnc * @param {string} value * @returns {IEncodedValue} */ - private getEncodedValue (value: string): IEncodedValue { + private getEncodedValue(value: string): IEncodedValue { const encoding: TStringArrayEncoding | null = this.options.stringArrayEncoding.length - ? this.randomGenerator - .getRandomGenerator() - .pickone(this.options.stringArrayEncoding) + ? this.randomGenerator.getRandomGenerator().pickone(this.options.stringArrayEncoding) : null; if (!encoding) { @@ -303,12 +297,15 @@ export class StringArrayStorage extends MapStorage <`${string}-${TStringArrayEnc */ case StringArrayEncoding.Rc4: { const decodeKey: string = this.randomGenerator.getRandomGenerator().pickone(this.rc4Keys); - const encodedValue: string = this.cryptUtilsStringArray.btoa(this.cryptUtilsStringArray.rc4(value, decodeKey)); + const encodedValue: string = this.cryptUtilsStringArray.btoa( + this.cryptUtilsStringArray.rc4(value, decodeKey) + ); const encodedValueSources: string[] = this.rc4EncodedValuesSourcesCache.get(encodedValue) ?? []; let encodedValueSourcesLength: number = encodedValueSources.length; - const shouldAddValueToSourcesCache: boolean = !encodedValueSourcesLength || !encodedValueSources.includes(value); + const shouldAddValueToSourcesCache: boolean = + !encodedValueSourcesLength || !encodedValueSources.includes(value); if (shouldAddValueToSourcesCache) { encodedValueSources.push(value); diff --git a/src/storages/string-array-transformers/VisitedLexicalScopeNodesStackStorage.ts b/src/storages/string-array-transformers/VisitedLexicalScopeNodesStackStorage.ts index 80a5883e..cbc72fd3 100644 --- a/src/storages/string-array-transformers/VisitedLexicalScopeNodesStackStorage.ts +++ b/src/storages/string-array-transformers/VisitedLexicalScopeNodesStackStorage.ts @@ -11,7 +11,10 @@ import { IVisitedLexicalScopeNodesStackStorage } from '../../interfaces/storages import { ArrayStorage } from '../ArrayStorage'; @injectable() -export class VisitedLexicalScopeNodesStackStorage extends ArrayStorage implements IVisitedLexicalScopeNodesStackStorage { +export class VisitedLexicalScopeNodesStackStorage + extends ArrayStorage + implements IVisitedLexicalScopeNodesStackStorage +{ /** * @type {IArrayUtils} */ @@ -22,10 +25,10 @@ export class VisitedLexicalScopeNodesStackStorage extends ArrayStorage = {[key: string]: T}; +export type TDictionary = { [key: string]: T }; diff --git a/src/types/TIdentifierNamesCache.ts b/src/types/TIdentifierNamesCache.ts index 76c7ccee..de700601 100644 --- a/src/types/TIdentifierNamesCache.ts +++ b/src/types/TIdentifierNamesCache.ts @@ -4,4 +4,3 @@ export type TIdentifierNamesCache = { globalIdentifiers?: TIdentifierNamesCacheDictionary; propertyIdentifiers?: TIdentifierNamesCacheDictionary; } | null; - diff --git a/src/types/TInitialData.ts b/src/types/TInitialData.ts index bdc90063..044baa7f 100644 --- a/src/types/TInitialData.ts +++ b/src/types/TInitialData.ts @@ -1,3 +1,3 @@ import { IInitializable } from '../interfaces/IInitializable'; -export type TInitialData = Parameters; +export type TInitialData = Parameters; diff --git a/src/types/TObfuscationResultsObject.ts b/src/types/TObfuscationResultsObject.ts index 6c4be60a..55a3cb80 100644 --- a/src/types/TObfuscationResultsObject.ts +++ b/src/types/TObfuscationResultsObject.ts @@ -1,3 +1,3 @@ import { IObfuscationResult } from '../interfaces/source-code/IObfuscationResult'; -export type TObfuscationResultsObject = {[key in keyof TSourceCodesObject]: IObfuscationResult}; +export type TObfuscationResultsObject = { [key in keyof TSourceCodesObject]: IObfuscationResult }; diff --git a/src/types/cli/TCLISanitizer.ts b/src/types/cli/TCLISanitizer.ts index e1058160..ea12582c 100644 --- a/src/types/cli/TCLISanitizer.ts +++ b/src/types/cli/TCLISanitizer.ts @@ -1 +1 @@ -export type TCLISanitizer = (value: string) => T; +export type TCLISanitizer = (value: string) => T; diff --git a/src/types/container/custom-code-helpers/TCustomCodeHelperFactory.ts b/src/types/container/custom-code-helpers/TCustomCodeHelperFactory.ts index 01feb86f..b506406f 100644 --- a/src/types/container/custom-code-helpers/TCustomCodeHelperFactory.ts +++ b/src/types/container/custom-code-helpers/TCustomCodeHelperFactory.ts @@ -2,6 +2,6 @@ import { ICustomCodeHelper } from '../../../interfaces/custom-code-helpers/ICust import { CustomCodeHelper } from '../../../enums/custom-code-helpers/CustomCodeHelper'; -export type TCustomCodeHelperFactory = < - TInitialData extends unknown[] = unknown[] -> (customCodeHelperName: CustomCodeHelper) => ICustomCodeHelper; +export type TCustomCodeHelperFactory = ( + customCodeHelperName: CustomCodeHelper +) => ICustomCodeHelper; diff --git a/src/types/container/custom-code-helpers/TCustomCodeHelperGroupFactory.ts b/src/types/container/custom-code-helpers/TCustomCodeHelperGroupFactory.ts index eb22c680..c53553b2 100644 --- a/src/types/container/custom-code-helpers/TCustomCodeHelperGroupFactory.ts +++ b/src/types/container/custom-code-helpers/TCustomCodeHelperGroupFactory.ts @@ -2,4 +2,6 @@ import { ICustomCodeHelperGroup } from '../../../interfaces/custom-code-helpers/ import { CustomCodeHelperGroup } from '../../../enums/custom-code-helpers/CustomCodeHelperGroup'; -export type TCustomCodeHelperGroupFactory = (customCodeHelperGroupName: CustomCodeHelperGroup) => ICustomCodeHelperGroup; +export type TCustomCodeHelperGroupFactory = ( + customCodeHelperGroupName: CustomCodeHelperGroup +) => ICustomCodeHelperGroup; diff --git a/src/types/container/custom-nodes/TControlFlowCustomNodeFactory.ts b/src/types/container/custom-nodes/TControlFlowCustomNodeFactory.ts index b917b71b..5935b4f5 100644 --- a/src/types/container/custom-nodes/TControlFlowCustomNodeFactory.ts +++ b/src/types/container/custom-nodes/TControlFlowCustomNodeFactory.ts @@ -2,6 +2,6 @@ import { ICustomNode } from '../../../interfaces/custom-nodes/ICustomNode'; import { ControlFlowCustomNode } from '../../../enums/custom-nodes/ControlFlowCustomNode'; -export type TControlFlowCustomNodeFactory = < - TInitialData extends unknown[] = unknown[] -> (controlFlowCustomNodeName: ControlFlowCustomNode) => ICustomNode; +export type TControlFlowCustomNodeFactory = ( + controlFlowCustomNodeName: ControlFlowCustomNode +) => ICustomNode; diff --git a/src/types/container/custom-nodes/TDeadNodeInjectionCustomNodeFactory.ts b/src/types/container/custom-nodes/TDeadNodeInjectionCustomNodeFactory.ts index e10858f5..4efc1572 100644 --- a/src/types/container/custom-nodes/TDeadNodeInjectionCustomNodeFactory.ts +++ b/src/types/container/custom-nodes/TDeadNodeInjectionCustomNodeFactory.ts @@ -2,6 +2,6 @@ import { ICustomNode } from '../../../interfaces/custom-nodes/ICustomNode'; import { DeadCodeInjectionCustomNode } from '../../../enums/custom-nodes/DeadCodeInjectionCustomNode'; -export type TDeadNodeInjectionCustomNodeFactory = < - TInitialData extends unknown[] = unknown[] -> (deadCodeInjectionCustomNodeName: DeadCodeInjectionCustomNode) => ICustomNode ; +export type TDeadNodeInjectionCustomNodeFactory = ( + deadCodeInjectionCustomNodeName: DeadCodeInjectionCustomNode +) => ICustomNode; diff --git a/src/types/container/custom-nodes/TObjectExpressionKeysTransformerCustomNodeFactory.ts b/src/types/container/custom-nodes/TObjectExpressionKeysTransformerCustomNodeFactory.ts index 8cc94f03..92dbd03f 100644 --- a/src/types/container/custom-nodes/TObjectExpressionKeysTransformerCustomNodeFactory.ts +++ b/src/types/container/custom-nodes/TObjectExpressionKeysTransformerCustomNodeFactory.ts @@ -2,6 +2,6 @@ import { ICustomNode } from '../../../interfaces/custom-nodes/ICustomNode'; import { ObjectExpressionKeysTransformerCustomNode } from '../../../enums/custom-nodes/ObjectExpressionKeysTransformerCustomNode'; -export type TObjectExpressionKeysTransformerCustomNodeFactory = < - TInitialData extends unknown[] = unknown[] -> (objectExpressionKeysTransformerNodeName: ObjectExpressionKeysTransformerCustomNode) => ICustomNode ; +export type TObjectExpressionKeysTransformerCustomNodeFactory = ( + objectExpressionKeysTransformerNodeName: ObjectExpressionKeysTransformerCustomNode +) => ICustomNode; diff --git a/src/types/container/custom-nodes/TStringArrayCustomNodeFactory.ts b/src/types/container/custom-nodes/TStringArrayCustomNodeFactory.ts index b118f2e3..1de9aa26 100644 --- a/src/types/container/custom-nodes/TStringArrayCustomNodeFactory.ts +++ b/src/types/container/custom-nodes/TStringArrayCustomNodeFactory.ts @@ -2,6 +2,6 @@ import { ICustomNode } from '../../../interfaces/custom-nodes/ICustomNode'; import { StringArrayCustomNode } from '../../../enums/custom-nodes/StringArrayCustomNode'; -export type TStringArrayCustomNodeFactory = < - TInitialData extends unknown[] = unknown[] -> (stringArrayCustomNodeName: StringArrayCustomNode) => ICustomNode ; +export type TStringArrayCustomNodeFactory = ( + stringArrayCustomNodeName: StringArrayCustomNode +) => ICustomNode; diff --git a/src/types/container/node-transformers/TControlFlowStorageFactoryCreator.ts b/src/types/container/node-transformers/TControlFlowStorageFactoryCreator.ts index 3a2a1ecb..de596877 100644 --- a/src/types/container/node-transformers/TControlFlowStorageFactoryCreator.ts +++ b/src/types/container/node-transformers/TControlFlowStorageFactoryCreator.ts @@ -2,4 +2,6 @@ import { TControlFlowStorageFactory } from './TControlFlowStorageFactory'; import { ControlFlowStorage } from '../../../enums/storages/ControlFlowStorage'; -export type TControlFlowStorageFactoryCreator = (controlFlowStorageName: ControlFlowStorage) => TControlFlowStorageFactory; +export type TControlFlowStorageFactoryCreator = ( + controlFlowStorageName: ControlFlowStorage +) => TControlFlowStorageFactory; diff --git a/src/types/container/node-transformers/TObjectExpressionExtractorFactory.ts b/src/types/container/node-transformers/TObjectExpressionExtractorFactory.ts index 59e16175..75334c48 100644 --- a/src/types/container/node-transformers/TObjectExpressionExtractorFactory.ts +++ b/src/types/container/node-transformers/TObjectExpressionExtractorFactory.ts @@ -2,5 +2,6 @@ import { IObjectExpressionExtractor } from '../../../interfaces/node-transformer import { ObjectExpressionExtractor } from '../../../enums/node-transformers/converting-transformers/properties-extractors/ObjectExpressionExtractor'; -export type TObjectExpressionExtractorFactory = - (objectExpressionExtractorName: ObjectExpressionExtractor) => IObjectExpressionExtractor; +export type TObjectExpressionExtractorFactory = ( + objectExpressionExtractorName: ObjectExpressionExtractor +) => IObjectExpressionExtractor; diff --git a/src/types/node/TNodeWithSingleStatementBody.ts b/src/types/node/TNodeWithSingleStatementBody.ts index d2a4e5f4..d0e38708 100644 --- a/src/types/node/TNodeWithSingleStatementBody.ts +++ b/src/types/node/TNodeWithSingleStatementBody.ts @@ -1,21 +1,18 @@ import * as ESTree from 'estree'; -export type TNodeWithSingleStatementBody = ( - ESTree.LabeledStatement - | ESTree.WithStatement - | ESTree.WhileStatement - | ESTree.DoWhileStatement - | ESTree.ForStatement - | ESTree.ForInStatement - | ESTree.ForOfStatement - & { - body: Exclude; - } -) -| ( - ESTree.IfStatement - & { - consequent: Exclude; - alternate?: Exclude | null; - } -); +export type TNodeWithSingleStatementBody = + | ( + | ESTree.LabeledStatement + | ESTree.WithStatement + | ESTree.WhileStatement + | ESTree.DoWhileStatement + | ESTree.ForStatement + | ESTree.ForInStatement + | (ESTree.ForOfStatement & { + body: Exclude; + }) + ) + | (ESTree.IfStatement & { + consequent: Exclude; + alternate?: Exclude | null; + }); diff --git a/src/types/node/TNumberLiteralNode.ts b/src/types/node/TNumberLiteralNode.ts index 11ed90ee..c4db9545 100644 --- a/src/types/node/TNumberLiteralNode.ts +++ b/src/types/node/TNumberLiteralNode.ts @@ -1,3 +1,3 @@ import * as ESTree from 'estree'; -export type TNumberLiteralNode = ESTree.Literal & {value: number}; +export type TNumberLiteralNode = ESTree.Literal & { value: number }; diff --git a/src/types/node/TScopeIdentifiersTraverserCallback.ts b/src/types/node/TScopeIdentifiersTraverserCallback.ts index 1f79ea2a..aab19508 100644 --- a/src/types/node/TScopeIdentifiersTraverserCallback.ts +++ b/src/types/node/TScopeIdentifiersTraverserCallback.ts @@ -1 +1 @@ -export type TScopeIdentifiersTraverserCallback = (data: TData) => void; +export type TScopeIdentifiersTraverserCallback = (data: TData) => void; diff --git a/src/types/node/TStringLiteralNode.ts b/src/types/node/TStringLiteralNode.ts index 051c03f9..c23c0b95 100644 --- a/src/types/node/TStringLiteralNode.ts +++ b/src/types/node/TStringLiteralNode.ts @@ -1,3 +1,3 @@ import * as ESTree from 'estree'; -export type TStringLiteralNode = ESTree.Literal & {value: string}; +export type TStringLiteralNode = ESTree.Literal & { value: string }; diff --git a/src/types/storages/TCustomCodeHelperGroupStorage.ts b/src/types/storages/TCustomCodeHelperGroupStorage.ts index be1aeb0a..a0a3d5c2 100644 --- a/src/types/storages/TCustomCodeHelperGroupStorage.ts +++ b/src/types/storages/TCustomCodeHelperGroupStorage.ts @@ -1,4 +1,4 @@ import { ICustomCodeHelperGroup } from '../../interfaces/custom-code-helpers/ICustomCodeHelperGroup'; import { IMapStorage } from '../../interfaces/storages/IMapStorage'; -export type TCustomCodeHelperGroupStorage = IMapStorage ; +export type TCustomCodeHelperGroupStorage = IMapStorage; diff --git a/src/types/utils/TTransformersRelationEdge.ts b/src/types/utils/TTransformersRelationEdge.ts index 87681dfb..316867ba 100644 --- a/src/types/utils/TTransformersRelationEdge.ts +++ b/src/types/utils/TTransformersRelationEdge.ts @@ -1,4 +1,4 @@ -export type TTransformersRelationEdge = [ +export type TTransformersRelationEdge = [ transformerNameA: TTransformerName, transformerNameB: TTransformerName | null ]; diff --git a/src/types/utils/TTypeFromEnum.ts b/src/types/utils/TTypeFromEnum.ts index 9dd551e2..4ed6749b 100644 --- a/src/types/utils/TTypeFromEnum.ts +++ b/src/types/utils/TTypeFromEnum.ts @@ -1 +1 @@ -export type TTypeFromEnum = (T)[keyof T]; +export type TTypeFromEnum = T[keyof T]; diff --git a/src/utils/AbstractTransformerNamesGroupsBuilder.ts b/src/utils/AbstractTransformerNamesGroupsBuilder.ts index 4a9a38a2..08fdff6f 100644 --- a/src/utils/AbstractTransformerNamesGroupsBuilder.ts +++ b/src/utils/AbstractTransformerNamesGroupsBuilder.ts @@ -9,21 +9,19 @@ import { ITransformer } from '../interfaces/ITransformer'; import { ITransformerNamesGroupsBuilder } from '../interfaces/utils/ITransformerNamesGroupsBuilder'; @injectable() -export abstract class AbstractTransformerNamesGroupsBuilder < +export abstract class AbstractTransformerNamesGroupsBuilder< TTransformerName extends string, TTransformer extends ITransformer -> implements ITransformerNamesGroupsBuilder < - TTransformerName, - TTransformer -> { +> implements ITransformerNamesGroupsBuilder +{ /** * @type {ILevelledTopologicalSorter} */ private readonly levelledTopologicalSorter: ILevelledTopologicalSorter; - public constructor ( + public constructor( @inject(ServiceIdentifiers.ILevelledTopologicalSorter) - levelledTopologicalSorter: ILevelledTopologicalSorter + levelledTopologicalSorter: ILevelledTopologicalSorter ) { this.levelledTopologicalSorter = levelledTopologicalSorter; } @@ -51,7 +49,7 @@ export abstract class AbstractTransformerNamesGroupsBuilder < * @param {TDictionary} normalizedTransformers * @returns {TTransformerName[][]} */ - public build (normalizedTransformers: TDictionary): TTransformerName[][] { + public build(normalizedTransformers: TDictionary): TTransformerName[][] { const transformerNames: TTransformerName[] = Object.keys(normalizedTransformers); const relationEdges: TTransformersRelationEdge[] = this.buildTransformersRelationEdges( transformerNames, @@ -70,7 +68,7 @@ export abstract class AbstractTransformerNamesGroupsBuilder < * @param {TDictionary} normalizedTransformers * @returns {TTransformersRelationEdge[]} */ - private buildTransformersRelationEdges ( + private buildTransformersRelationEdges( transformerNames: TTransformerName[], normalizedTransformers: TDictionary ): TTransformersRelationEdge[] { diff --git a/src/utils/ArrayUtils.ts b/src/utils/ArrayUtils.ts index ad215158..718ee229 100644 --- a/src/utils/ArrayUtils.ts +++ b/src/utils/ArrayUtils.ts @@ -14,9 +14,7 @@ export class ArrayUtils implements IArrayUtils { /** * @param {IRandomGenerator} randomGenerator */ - public constructor ( - @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator - ) { + public constructor(@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator) { this.randomGenerator = randomGenerator; } @@ -24,7 +22,7 @@ export class ArrayUtils implements IArrayUtils { * @param {number} length * @returns {number[]} */ - public createWithRange (length: number): number[] { + public createWithRange(length: number): number[] { const range: number[] = []; for (let i: number = 0; i < length; i++) { @@ -39,7 +37,7 @@ export class ArrayUtils implements IArrayUtils { * @param {(index: number) => TValue} valueFunction * @returns {TValue[]} */ - public fillWithRange (length: number, valueFunction: (index: number) => TValue): TValue[] { + public fillWithRange(length: number, valueFunction: (index: number) => TValue): TValue[] { const range: TValue[] = []; for (let i: number = 0; i < length; i++) { @@ -53,14 +51,14 @@ export class ArrayUtils implements IArrayUtils { * @param {T[]} array * @returns {T | null} */ - public findMostOccurringElement (array: T[]): T | null { + public findMostOccurringElement(array: T[]): T | null { const arrayLength: number = array.length; if (!arrayLength) { return null; } - const elementsMap: Partial<{[key in T]: number}> = {}; + const elementsMap: Partial<{ [key in T]: number }> = {}; let mostOccurringElement: T = array[0]; let mostOccurringElementCount: number = 1; @@ -84,7 +82,7 @@ export class ArrayUtils implements IArrayUtils { * @param {T[]} array * @returns {T | undefined} */ - public getLastElement (array: T[]): T | undefined { + public getLastElement(array: T[]): T | undefined { return this.getLastElementByIndex(array, 0); } @@ -93,7 +91,7 @@ export class ArrayUtils implements IArrayUtils { * @param {number} index * @returns {T | undefined} */ - public getLastElementByIndex (array: T[], index: number): T | undefined { + public getLastElementByIndex(array: T[], index: number): T | undefined { const arrayLength: number = array.length; return array[arrayLength - 1 - index] ?? undefined; @@ -104,7 +102,7 @@ export class ArrayUtils implements IArrayUtils { * @param {number} times * @returns {T[]} */ - public rotate (array: T[], times: number): T[] { + public rotate(array: T[], times: number): T[] { if (!array.length) { throw new ReferenceError('Cannot rotate empty array.'); } @@ -132,7 +130,7 @@ export class ArrayUtils implements IArrayUtils { * @param {T[]} array * @returns {T[]} */ - public shuffle (array: T[]): T[] { + public shuffle(array: T[]): T[] { const shuffledArray: T[] = [...array]; for (let i: number = shuffledArray.length; i; i--) { diff --git a/src/utils/CryptUtils.ts b/src/utils/CryptUtils.ts index 84712efa..344ed4c2 100644 --- a/src/utils/CryptUtils.ts +++ b/src/utils/CryptUtils.ts @@ -24,9 +24,7 @@ export class CryptUtils implements ICryptUtils { /** * @param {IRandomGenerator} randomGenerator */ - public constructor ( - @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator - ) { + public constructor(@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator) { this.randomGenerator = randomGenerator; } @@ -34,7 +32,7 @@ export class CryptUtils implements ICryptUtils { * @param {string} string * @returns {string} */ - public btoa (string: string): string { + public btoa(string: string): string { const chars: string = this.base64Alphabet; let output: string = ''; @@ -45,16 +43,18 @@ export class CryptUtils implements ICryptUtils { for ( let block: number | undefined, charCode: number, idx: number = 0, map: string = chars; - string.charAt(idx | 0) || (map = '=', idx % 1); - output += map.charAt(63 & block >> 8 - idx % 1 * 8) + string.charAt(idx | 0) || ((map = '='), idx % 1); + output += map.charAt(63 & (block >> (8 - (idx % 1) * 8))) ) { - charCode = string.charCodeAt(idx += 3/4); + charCode = string.charCodeAt((idx += 3 / 4)); - if (charCode > 0xFF) { - throw new Error('\'btoa\' failed: The string to be encoded contains characters outside of the Latin1 range.'); + if (charCode > 0xff) { + throw new Error( + '\'btoa\' failed: The string to be encoded contains characters outside of the Latin1 range.' + ); } - block = block << 8 | charCode; + block = ((block) << 8) | charCode; } return output; @@ -67,9 +67,8 @@ export class CryptUtils implements ICryptUtils { * @param {number} length * @returns {[string , string]} */ - public hideString (str: string, length: number): [string, string] { - const escapeRegExp: (s: string) => string = (s: string) => - s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + public hideString(str: string, length: number): [string, string] { + const escapeRegExp: (s: string) => string = (s: string) => s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); const randomMerge: (s1: string, s2: string) => string = (s1: string, s2: string): string => { let i1: number = -1; @@ -92,10 +91,7 @@ export class CryptUtils implements ICryptUtils { pool: RandomGenerator.randomGeneratorPool }); - let randomStringDiff: string = randomString.replace( - new RegExp(`[${escapeRegExp(str)}]`, 'g'), - '' - ); + let randomStringDiff: string = randomString.replace(new RegExp(`[${escapeRegExp(str)}]`, 'g'), ''); const randomStringDiffArray: string[] = randomStringDiff.split(''); @@ -113,7 +109,7 @@ export class CryptUtils implements ICryptUtils { * @param {string} key * @returns {string} */ - public rc4 (string: string, key: string): string { + public rc4(string: string, key: string): string { const s: number[] = []; let j: number = 0; diff --git a/src/utils/CryptUtilsStringArray.ts b/src/utils/CryptUtilsStringArray.ts index 18132298..b5104927 100644 --- a/src/utils/CryptUtilsStringArray.ts +++ b/src/utils/CryptUtilsStringArray.ts @@ -18,9 +18,7 @@ export class CryptUtilsStringArray extends CryptUtils implements ICryptUtilsStri /** * @param {IRandomGenerator} randomGenerator */ - public constructor ( - @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator - ) { + public constructor(@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator) { super(randomGenerator); } @@ -30,7 +28,7 @@ export class CryptUtilsStringArray extends CryptUtils implements ICryptUtilsStri * @param {string} string * @returns {string} */ - public override btoa (string: string): string { + public override btoa(string: string): string { const output = super.btoa(string); return output.replace(/=+$/, ''); diff --git a/src/utils/EscapeSequenceEncoder.ts b/src/utils/EscapeSequenceEncoder.ts index 0600778a..6db012ab 100644 --- a/src/utils/EscapeSequenceEncoder.ts +++ b/src/utils/EscapeSequenceEncoder.ts @@ -22,14 +22,14 @@ export class EscapeSequenceEncoder implements IEscapeSequenceEncoder { /** * @type {Map} */ - private readonly stringsCache: Map = new Map(); + private readonly stringsCache: Map = new Map(); /** * @param {string} string * @param {boolean} encodeAllSymbols * @returns {string} */ - public encode (string: string, encodeAllSymbols: boolean): string { + public encode(string: string, encodeAllSymbols: boolean): string { const cacheKey: string = `${string}-${String(encodeAllSymbols)}`; if (this.stringsCache.has(cacheKey)) { @@ -43,8 +43,8 @@ export class EscapeSequenceEncoder implements IEscapeSequenceEncoder { let template: string; const result: string = string.replace(replaceRegExp, (character: string): string => { - const shouldEncodeCharacter: boolean = encodeAllSymbols - || EscapeSequenceEncoder.forceEscapeCharactersRegExp.test(character); + const shouldEncodeCharacter: boolean = + encodeAllSymbols || EscapeSequenceEncoder.forceEscapeCharactersRegExp.test(character); if (!shouldEncodeCharacter) { return character; diff --git a/src/utils/LevelledTopologicalSorter.ts b/src/utils/LevelledTopologicalSorter.ts index a38b1b0f..faccb341 100644 --- a/src/utils/LevelledTopologicalSorter.ts +++ b/src/utils/LevelledTopologicalSorter.ts @@ -4,7 +4,7 @@ import { ILevelledTopologicalSorter } from '../interfaces/utils/ILevelledTopolog type TVisitMark = 'ok' | 'visiting'; -interface IVisitMarks { +interface IVisitMarks { [key: string]: TVisitMark; } @@ -12,7 +12,7 @@ interface IVisitMarks { * Port and rework of https://github.com/loveencounterflow/ltsort */ @injectable() -export class LevelledTopologicalSorter implements ILevelledTopologicalSorter { +export class LevelledTopologicalSorter implements ILevelledTopologicalSorter { /** * @type {Map implemen * @param {TValue | null} consequent * @returns {this} */ - public add ( - precedent: TValue, - consequent: TValue | null = null - ): this { + public add(precedent: TValue, consequent: TValue | null = null): this { if (consequent !== null) { return this.link(precedent, consequent); } @@ -39,7 +36,7 @@ export class LevelledTopologicalSorter implemen * * @returns {TValue[]} */ - public sort (): TValue[] { + public sort(): TValue[] { const consequents: TValue[] = Array.from(this.graph.keys()); const results: TValue[] = []; @@ -59,7 +56,7 @@ export class LevelledTopologicalSorter implemen /** * @returns {TValue[][]} */ - public sortByGroups (): TValue[][] { + public sortByGroups(): TValue[][] { this.sort(); const resultItemsGroups: TValue[][] = []; @@ -80,7 +77,7 @@ export class LevelledTopologicalSorter implemen /** * @param {TValue} consequent */ - private delete (consequent: TValue): void { + private delete(consequent: TValue): void { const precedents: TValue[] = this.getPrecedents(consequent); if (precedents.length) { @@ -107,7 +104,7 @@ export class LevelledTopologicalSorter implemen /** * @returns {TValue[]} */ - private findRootNodes (): TValue[] { + private findRootNodes(): TValue[] { const consequents: TValue[] = Array.from(this.graph.keys()); const rootNodes: TValue[] = []; @@ -124,7 +121,7 @@ export class LevelledTopologicalSorter implemen * @param {TValue} consequent * @returns {TValue[]} */ - private getPrecedents (consequent: TValue): TValue[] { + private getPrecedents(consequent: TValue): TValue[] { const precedents: TValue[] | undefined = this.graph.get(consequent); if (!precedents) { @@ -137,7 +134,7 @@ export class LevelledTopologicalSorter implemen /** * @returns {boolean} */ - private hasNodes (): boolean { + private hasNodes(): boolean { return this.graph.size > 0; } @@ -145,7 +142,7 @@ export class LevelledTopologicalSorter implemen * @param {TValue} consequent * @returns {boolean} */ - private hasPrecedents (consequent: TValue): boolean { + private hasPrecedents(consequent: TValue): boolean { return this.getPrecedents(consequent).length > 0; } @@ -154,7 +151,7 @@ export class LevelledTopologicalSorter implemen * @param {TValue} consequent * @returns {this} */ - private link (precedent: TValue, consequent: TValue): this { + private link(precedent: TValue, consequent: TValue): this { this.register(precedent); this.register(consequent); @@ -171,7 +168,7 @@ export class LevelledTopologicalSorter implemen * @param {TValue} name * @returns {this} */ - private register (name: TValue): this { + private register(name: TValue): this { if (!this.graph.has(name)) { this.graph.set(name, []); } @@ -185,11 +182,7 @@ export class LevelledTopologicalSorter implemen * @param {TValue} name * @returns {null} */ - private visit ( - results: TValue[], - marks: IVisitMarks, - name: TValue - ): void { + private visit(results: TValue[], marks: IVisitMarks, name: TValue): void { const mark: TVisitMark = marks[name]; if (mark === 'visiting') { diff --git a/src/utils/NumberUtils.ts b/src/utils/NumberUtils.ts index 949229ef..c7f76705 100644 --- a/src/utils/NumberUtils.ts +++ b/src/utils/NumberUtils.ts @@ -5,12 +5,10 @@ export class NumberUtils { * @param {number} number * @returns {string} */ - public static toHex (number: number | bigint): string { + public static toHex(number: number | bigint): string { const radix: number = 16; - const basePart: string = typeof number === 'number' - ? number.toString(radix) - : `${number.toString(radix)}n`; + const basePart: string = typeof number === 'number' ? number.toString(radix) : `${number.toString(radix)}n`; return `${Utils.hexadecimalPrefix}${basePart}`; } @@ -19,11 +17,9 @@ export class NumberUtils { * @param {number} number * @returns {[number, (number | null)]} */ - public static extractIntegerAndDecimalParts (number: number): [number, number | null] { + public static extractIntegerAndDecimalParts(number: number): [number, number | null] { const integerPart: number = Math.trunc(number); - const decimalPart: number | null = number !== integerPart - ? number % 1 - : null; + const decimalPart: number | null = number !== integerPart ? number % 1 : null; return [integerPart, decimalPart]; } @@ -32,17 +28,15 @@ export class NumberUtils { * @param {number} number * @returns {boolean} */ - public static isCeil (number: number | bigint): boolean { - return typeof number === 'number' - ? number % 1 === 0 - : true; + public static isCeil(number: number | bigint): boolean { + return typeof number === 'number' ? number % 1 === 0 : true; } /** * @param {number} number * @returns {boolean} */ - public static isPositive (number: number): boolean { + public static isPositive(number: number): boolean { if (isNaN(number)) { throw new Error('Given value is NaN'); } @@ -66,7 +60,7 @@ export class NumberUtils { * @param {number} number * @returns {boolean} */ - public static isUnsafeNumber (number: number): boolean { + public static isUnsafeNumber(number: number): boolean { if (isNaN(number)) { throw new Error('Given value is NaN'); } @@ -81,7 +75,7 @@ export class NumberUtils { * @param {number} number * @returns {number[]} */ - public static getFactors (number: number): number[] { + public static getFactors(number: number): number[] { if (number === 0) { throw new Error('Invalid number. Allowed only non-zero number'); } @@ -99,13 +93,9 @@ export class NumberUtils { const isEven: boolean = number % 2 === 0; const incrementValue: number = isEven ? 1 : 2; - for ( - let currentFactor = 1; - currentFactor <= root; - currentFactor += incrementValue - ) { + for (let currentFactor = 1; currentFactor <= root; currentFactor += incrementValue) { const compliment: number = number / currentFactor; - const check = (number - Math.floor(compliment) * currentFactor) !== 0; + const check = number - Math.floor(compliment) * currentFactor !== 0; if (check) { continue; diff --git a/src/utils/RandomGenerator.ts b/src/utils/RandomGenerator.ts index a27daf4c..9381a6c0 100644 --- a/src/utils/RandomGenerator.ts +++ b/src/utils/RandomGenerator.ts @@ -41,7 +41,7 @@ export class RandomGenerator implements IRandomGenerator, IInitializable { * @param {ISourceCode} sourceCode * @param {IOptions} options */ - public constructor ( + public constructor( @inject(ServiceIdentifiers.ISourceCode) sourceCode: ISourceCode, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { @@ -50,21 +50,21 @@ export class RandomGenerator implements IRandomGenerator, IInitializable { } @postConstruct() - public initialize (): void { + public initialize(): void { this.randomGenerator = new Chance(this.getRawSeed()); } /** * @returns {number} */ - public getMathRandom (): number { + public getMathRandom(): number { return this.getRandomInteger(0, 99999) / 100000; } /** * @returns {Chance.Chance} */ - public getRandomGenerator (): Chance.Chance { + public getRandomGenerator(): Chance.Chance { return this.randomGenerator; } @@ -73,7 +73,7 @@ export class RandomGenerator implements IRandomGenerator, IInitializable { * @param {number} max * @returns {number} */ - public getRandomInteger (min: number, max: number): number { + public getRandomInteger(min: number, max: number): number { return this.getRandomGenerator().integer({ min: min, max: max @@ -86,7 +86,7 @@ export class RandomGenerator implements IRandomGenerator, IInitializable { * @param {number[]} valuesToExclude * @returns {number} */ - public getRandomIntegerExcluding (min: number, max: number, valuesToExclude: number[]): number { + public getRandomIntegerExcluding(min: number, max: number, valuesToExclude: number[]): number { const valuesToPickArray: number[] = []; for (let value: number = min; value <= max; value++) { @@ -105,14 +105,14 @@ export class RandomGenerator implements IRandomGenerator, IInitializable { * @param {string} pool * @returns {string} */ - public getRandomString (length: number, pool: string = RandomGenerator.randomGeneratorPool): string { + public getRandomString(length: number, pool: string = RandomGenerator.randomGeneratorPool): string { return this.getRandomGenerator().string({ length, pool }); } /** * @returns {string} */ - public getInputSeed (): string { + public getInputSeed(): string { return this.options.seed.toString(); } @@ -122,7 +122,7 @@ export class RandomGenerator implements IRandomGenerator, IInitializable { * * @returns {number} */ - public getRawSeed (): string { + public getRawSeed(): string { const inputSeed: string = this.getInputSeed(); const inputSeedParts: string[] = `${inputSeed}`.split('|'); diff --git a/src/utils/SetUtils.ts b/src/utils/SetUtils.ts index e19ef24b..1be1749f 100644 --- a/src/utils/SetUtils.ts +++ b/src/utils/SetUtils.ts @@ -14,9 +14,7 @@ export class SetUtils implements ISetUtils { /** * @param {IArrayUtils} arrayUtils */ - public constructor ( - @inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils - ) { + public constructor(@inject(ServiceIdentifiers.IArrayUtils) arrayUtils: IArrayUtils) { this.arrayUtils = arrayUtils; } @@ -24,7 +22,7 @@ export class SetUtils implements ISetUtils { * @param {Set} set * @returns {T | undefined} */ - public getLastElement (set: Set): T | undefined { + public getLastElement(set: Set): T | undefined { const array = [...set]; return this.arrayUtils.getLastElement(array); diff --git a/src/utils/StringUtils.ts b/src/utils/StringUtils.ts index 56c01d15..51b18249 100644 --- a/src/utils/StringUtils.ts +++ b/src/utils/StringUtils.ts @@ -5,7 +5,7 @@ export class StringUtils { * @param {string} string * @returns {string} */ - public static escapeJsString (string: string): string { + public static escapeJsString(string: string): string { return jsStringEscape(string); } } diff --git a/src/utils/Utils.ts b/src/utils/Utils.ts index 31b0a06b..fc44fa20 100644 --- a/src/utils/Utils.ts +++ b/src/utils/Utils.ts @@ -14,7 +14,7 @@ export class Utils { * @param {string} buildTimestamp * @returns {string} */ - public static buildVersionMessage (version?: string, buildTimestamp?: string): string { + public static buildVersionMessage(version?: string, buildTimestamp?: string): string { const isUnknownVersion = !version || !buildTimestamp; if (isUnknownVersion) { @@ -30,7 +30,7 @@ export class Utils { * @param {string} url * @returns {string} */ - public static extractDomainFrom (url: string): string { + public static extractDomainFrom(url: string): string { let domain: string; if (url.includes('://') || url.indexOf('//') === 0) { @@ -49,7 +49,7 @@ export class Utils { * @param {number} sourceCodeIndex * @returns {string} */ - public static getIdentifiersPrefixForMultipleSources ( + public static getIdentifiersPrefixForMultipleSources( identifiersPrefix: string | undefined, sourceCodeIndex: number ): string { @@ -64,10 +64,9 @@ export class Utils { * @param {TObject} enumLikeObject * @returns {Readonly} */ - public static makeEnum< - TObject extends {[index: string]: TValue}, - TValue extends string - > (enumLikeObject: TObject): Readonly { - return Object.freeze({...enumLikeObject}); + public static makeEnum( + enumLikeObject: TObject + ): Readonly { + return Object.freeze({ ...enumLikeObject }); } } diff --git a/test/declarations/index.d.ts b/test/declarations/index.d.ts index f0adad50..c86cc642 100644 --- a/test/declarations/index.d.ts +++ b/test/declarations/index.d.ts @@ -1,3 +1,3 @@ /// /// -/// \ No newline at end of file +/// diff --git a/test/declarations/source-map-resolve.d.ts b/test/declarations/source-map-resolve.d.ts index e36b6e30..3f5cfa6f 100644 --- a/test/declarations/source-map-resolve.d.ts +++ b/test/declarations/source-map-resolve.d.ts @@ -14,6 +14,6 @@ declare module 'source-map-resolve' { map: ExistingRawSourceMap, mapUrl: string, read: (path: string, callback: (error: Error | null, data: Buffer | string) => void) => void, - callback: (error: Error | null, result: ResolvedSources) => void, + callback: (error: Error | null, result: ResolvedSources) => void ): void; -} \ No newline at end of file +} diff --git a/test/dev/dev-compile-performance.ts b/test/dev/dev-compile-performance.ts index 3116dc5d..adb28ac6 100644 --- a/test/dev/dev-compile-performance.ts +++ b/test/dev/dev-compile-performance.ts @@ -7,9 +7,7 @@ import * as fs from 'fs'; let start: any = new Date(); - JavaScriptObfuscator.obfuscate( - fs.readFileSync('test/fixtures/compile-performance.js', 'utf8') - ).getObfuscatedCode(); + JavaScriptObfuscator.obfuscate(fs.readFileSync('test/fixtures/compile-performance.js', 'utf8')).getObfuscatedCode(); console.log(`Total time: ${new Date() - start}`); })(); diff --git a/test/dev/dev-runtime-performance.ts b/test/dev/dev-runtime-performance.ts index 0a0841cf..16d99c7c 100644 --- a/test/dev/dev-runtime-performance.ts +++ b/test/dev/dev-runtime-performance.ts @@ -3,7 +3,8 @@ (function () { const JavaScriptObfuscator: any = require('../../index'); - let obfuscatedCode: string = JavaScriptObfuscator.obfuscate(` + let obfuscatedCode: string = JavaScriptObfuscator.obfuscate( + ` var start = new Date(); var log = console.log; console.log = function () {}; @@ -73,7 +74,7 @@ console.log(new Date() - start); `, { - disableConsoleOutput: false, + disableConsoleOutput: false } ).getObfuscatedCode(); diff --git a/test/dev/dev.ts b/test/dev/dev.ts index 7190cd66..e0067263 100644 --- a/test/dev/dev.ts +++ b/test/dev/dev.ts @@ -10,29 +10,29 @@ } `, { - "compact": false, - "controlFlowFlattening": true, - "controlFlowFlatteningThreshold": 1, - "disableConsoleOutput": false, - "identifierNamesGenerator": "mangled", - "log": true, - "numbersToExpressions": true, - "renameProperties": true, - "renamePropertiesMode": "safe", - "simplify": false, - "stringArray": true, - "stringArrayCallsTransform": true, - "stringArrayIndexShift": true, - "stringArrayRotate": false, - "stringArrayShuffle": false, - "stringArrayWrappersCount": 5, - "stringArrayWrappersChainedCalls": true, - "stringArrayWrappersParametersMaxCount": 5, - "stringArrayWrappersType": "function", - "stringArrayThreshold": 0, - "transformObjectKeys": true, - "unicodeEscapeSequence": false, - "ignoreImports": false + compact: false, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + disableConsoleOutput: false, + identifierNamesGenerator: 'mangled', + log: true, + numbersToExpressions: true, + renameProperties: true, + renamePropertiesMode: 'safe', + simplify: false, + stringArray: true, + stringArrayCallsTransform: true, + stringArrayIndexShift: true, + stringArrayRotate: false, + stringArrayShuffle: false, + stringArrayWrappersCount: 5, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersParametersMaxCount: 5, + stringArrayWrappersType: 'function', + stringArrayThreshold: 0, + transformObjectKeys: true, + unicodeEscapeSequence: false, + ignoreImports: false } ).getObfuscatedCode(); diff --git a/test/fixtures/directory-obfuscation/baz.ts b/test/fixtures/directory-obfuscation/baz.ts index 034c08dc..d1660596 100644 --- a/test/fixtures/directory-obfuscation/baz.ts +++ b/test/fixtures/directory-obfuscation/baz.ts @@ -1 +1 @@ -var baz = 3; \ No newline at end of file +var baz = 3; diff --git a/test/functional-tests/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.spec.ts b/test/functional-tests/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.spec.ts index 0f6008d0..b91bd565 100644 --- a/test/functional-tests/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.spec.ts +++ b/test/functional-tests/analyzers/calls-graph-analyzer/CallsGraphAnalyzer.spec.ts @@ -25,8 +25,8 @@ import { NodeUtils } from '../../../../src/node/NodeUtils'; * @param name * @returns {ESTree.FunctionDeclaration|null} */ -function getFunctionDeclarationByName (astTree: ESTree.Node, name: string): ESTree.FunctionDeclaration|null { - let functionDeclarationNode: ESTree.FunctionDeclaration|null = null; +function getFunctionDeclarationByName(astTree: ESTree.Node, name: string): ESTree.FunctionDeclaration | null { + let functionDeclarationNode: ESTree.FunctionDeclaration | null = null; estraverse.traverse(astTree, { enter: (node: ESTree.Node): any => { @@ -50,8 +50,8 @@ function getFunctionDeclarationByName (astTree: ESTree.Node, name: string): ESTr * @param name * @returns {ESTree.FunctionExpression|null} */ -function getFunctionExpressionByName (astTree: ESTree.Node, name: string): ESTree.FunctionExpression|null { - let functionExpressionNode: ESTree.FunctionExpression|null = null; +function getFunctionExpressionByName(astTree: ESTree.Node, name: string): ESTree.FunctionExpression | null { + let functionExpressionNode: ESTree.FunctionExpression | null = null; estraverse.traverse(astTree, { enter: (node: ESTree.Node): any => { @@ -77,8 +77,8 @@ function getFunctionExpressionByName (astTree: ESTree.Node, name: string): ESTre * @param id * @returns {ESTree.FunctionExpression|null} */ -function getFunctionExpressionById (astTree: ESTree.Node, id: string): ESTree.FunctionExpression|null { - let functionExpressionNode: ESTree.FunctionExpression|null = null; +function getFunctionExpressionById(astTree: ESTree.Node, id: string): ESTree.FunctionExpression | null { + let functionExpressionNode: ESTree.FunctionExpression | null = null; estraverse.traverse(astTree, { enter: (node: ESTree.Node): any => { @@ -104,9 +104,13 @@ function getFunctionExpressionById (astTree: ESTree.Node, id: string): ESTree.Fu * @param name * @returns {ESTree.FunctionExpression|null} */ -function getObjectFunctionExpressionByName (astTree: ESTree.Node, objectName: string, name: string|number): ESTree.FunctionExpression|null { - let functionExpressionNode: ESTree.FunctionExpression|null = null, - targetObjectExpressionNode: ESTree.ObjectExpression|null = null; +function getObjectFunctionExpressionByName( + astTree: ESTree.Node, + objectName: string, + name: string | number +): ESTree.FunctionExpression | null { + let functionExpressionNode: ESTree.FunctionExpression | null = null, + targetObjectExpressionNode: ESTree.ObjectExpression | null = null; estraverse.traverse(astTree, { enter: (node: ESTree.Node): any => { @@ -133,10 +137,8 @@ function getObjectFunctionExpressionByName (astTree: ESTree.Node, objectName: st if ( NodeGuards.isPropertyNode(node) && NodeGuards.isFunctionExpressionNode(node.value) && - ( - (NodeGuards.isIdentifierNode(node.key) && node.key.name === name) || - (NodeGuards.isLiteralNode(node.key) && node.key.value === name) - ) + ((NodeGuards.isIdentifierNode(node.key) && node.key.name === name) || + (NodeGuards.isLiteralNode(node.key) && node.key.value === name)) ) { functionExpressionNode = node.value; @@ -158,16 +160,15 @@ describe('CallsGraphAnalyzer', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - callsGraphAnalyzer = inversifyContainerFacade - .get(ServiceIdentifiers.ICallsGraphAnalyzer); + callsGraphAnalyzer = inversifyContainerFacade.get( + ServiceIdentifiers.ICallsGraphAnalyzer + ); }); describe('Variant #1: basic-1', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/basic-1.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { @@ -186,20 +187,24 @@ describe('CallsGraphAnalyzer', () => { callsGraph: [ { name: 'inner2', - callee: (getFunctionDeclarationByName(astTree, 'inner2')).body, + callee: (getFunctionDeclarationByName(astTree, 'inner2')) + .body, callsGraph: [ { name: 'inner3', - callee: (getFunctionExpressionByName(astTree, 'inner3')).body, + callee: (( + getFunctionExpressionByName(astTree, 'inner3') + )).body, callsGraph: [] - }, + } ] }, { name: 'inner1', - callee: (getFunctionDeclarationByName(astTree, 'inner1')).body, + callee: (getFunctionDeclarationByName(astTree, 'inner1')) + .body, callsGraph: [] - }, + } ] } ]; @@ -215,9 +220,7 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #2: basic-2', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/basic-2.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { @@ -231,9 +234,10 @@ describe('CallsGraphAnalyzer', () => { callsGraph: [ { name: 'inner1', - callee: (getFunctionDeclarationByName(astTree, 'inner1')).body, + callee: (getFunctionDeclarationByName(astTree, 'inner1')) + .body, callsGraph: [] - }, + } ] }, { @@ -254,9 +258,7 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #3: deep conditions nesting', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/deep-conditions-nesting.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { @@ -270,9 +272,10 @@ describe('CallsGraphAnalyzer', () => { callsGraph: [ { name: 'inner1', - callee: (getFunctionDeclarationByName(astTree, 'inner1')).body, + callee: (getFunctionDeclarationByName(astTree, 'inner1')) + .body, callsGraph: [] - }, + } ] }, { @@ -293,9 +296,7 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #4: call before declaration', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-before-declaration.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { @@ -316,50 +317,55 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #5: call expression of object member #1', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-of-object-member-1.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { name: 'baz', - callee: (getObjectFunctionExpressionByName(astTree, 'object1', 'baz')).body, + callee: (( + getObjectFunctionExpressionByName(astTree, 'object1', 'baz') + )).body, callsGraph: [] }, { name: 'baz', - callee: (getObjectFunctionExpressionByName(astTree, 'object1', 'baz')).body, + callee: (( + getObjectFunctionExpressionByName(astTree, 'object1', 'baz') + )).body, callsGraph: [] }, { name: 'func', - callee: (getObjectFunctionExpressionByName(astTree, 'object1', 'func')).body, + callee: (( + getObjectFunctionExpressionByName(astTree, 'object1', 'func') + )).body, callsGraph: [] }, { name: 'bar', - callee: (getObjectFunctionExpressionByName(astTree, 'object1', 'bar')).body, + callee: (( + getObjectFunctionExpressionByName(astTree, 'object1', 'bar') + )).body, callsGraph: [ { name: 'inner1', - callee: (getFunctionDeclarationByName(astTree, 'inner1')).body, - callsGraph: [ - - ] - }, + callee: (getFunctionDeclarationByName(astTree, 'inner1')) + .body, + callsGraph: [] + } ] }, { name: 'bar', - callee: (getObjectFunctionExpressionByName(astTree, 'object', 'bar')).body, + callee: (getObjectFunctionExpressionByName(astTree, 'object', 'bar')) + .body, callsGraph: [ { name: 'inner', - callee: (getFunctionDeclarationByName(astTree, 'inner')).body, - callsGraph: [ - - ] - }, + callee: (getFunctionDeclarationByName(astTree, 'inner')) + .body, + callsGraph: [] + } ] } ]; @@ -375,21 +381,21 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #5: call expression of object member #2', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-of-object-member-2.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { name: 'baz', - callee: (getObjectFunctionExpressionByName(astTree, 'object', 'baz')).body, + callee: (getObjectFunctionExpressionByName(astTree, 'object', 'baz')) + .body, callsGraph: [] }, { name: 1, - callee: (getObjectFunctionExpressionByName(astTree, 'object1', 1)).body, + callee: (getObjectFunctionExpressionByName(astTree, 'object1', 1)) + .body, callsGraph: [] - }, + } ]; callsGraphData = callsGraphAnalyzer.analyze(astTree); @@ -403,9 +409,7 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #6: no call expressions', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/no-call-expressions.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = []; @@ -420,9 +424,7 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #7: only call expression', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/only-call-expression.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = []; @@ -437,27 +439,34 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #8: self-invoking functions', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/self-invoking-functions.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { name: null, callee: (getFunctionExpressionById(astTree, 'foo')).body, - callsGraph: [{ - name: null, - callee: (getFunctionExpressionById(astTree, 'bar')).body, - callsGraph: [{ + callsGraph: [ + { name: null, - callee: (getFunctionExpressionById(astTree, 'baz')).body, - callsGraph: [{ - name: 'inner', - callee: (getFunctionDeclarationByName(astTree, 'inner')).body, - callsGraph: [] - }] - }] - }] + callee: (getFunctionExpressionById(astTree, 'bar')).body, + callsGraph: [ + { + name: null, + callee: (getFunctionExpressionById(astTree, 'baz')) + .body, + callsGraph: [ + { + name: 'inner', + callee: (( + getFunctionDeclarationByName(astTree, 'inner') + )).body, + callsGraph: [] + } + ] + } + ] + } + ] } ]; @@ -472,9 +481,7 @@ describe('CallsGraphAnalyzer', () => { describe('Variant #9: no recursion', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/no-recursion.js'); - const astTree: TNodeWithStatements = NodeFactory.programNode( - NodeUtils.convertCodeToStructure(code) - ); + const astTree: TNodeWithStatements = NodeFactory.programNode(NodeUtils.convertCodeToStructure(code)); expectedCallsGraphData = [ { diff --git a/test/functional-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts b/test/functional-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts index 9adebc7e..b0f82d72 100644 --- a/test/functional-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts +++ b/test/functional-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts @@ -11,7 +11,7 @@ describe('ScopeAnalyzer', () => { /** * https://github.com/javascript-obfuscator/javascript-obfuscator/issues/804 */ - describe('Variant #1: should attach a valid missing ranges', function() { + describe('Variant #1: should attach a valid missing ranges', function () { this.timeout(120000); const samplesCount: number = 1000; @@ -21,21 +21,18 @@ describe('ScopeAnalyzer', () => { const code: string = readFileAsString(__dirname + '/fixtures/attach-missing-ranges.js'); for (let i = 0; i < samplesCount; i++) { - let obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - stringArray: false, - selfDefending: true, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 0.1, - splitStrings: false, - seed: i - } - ).getObfuscatedCode(); + let obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + stringArray: false, + selfDefending: true, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 0.1, + splitStrings: false, + seed: i + }).getObfuscatedCode(); try { eval(obfuscatedCode); - } catch ({message}) { + } catch ({ message }) { error = message; break; } diff --git a/test/functional-tests/cli/JavaScriptObfuscatorCLI.spec.ts b/test/functional-tests/cli/JavaScriptObfuscatorCLI.spec.ts index 0757aa81..9a15e89e 100644 --- a/test/functional-tests/cli/JavaScriptObfuscatorCLI.spec.ts +++ b/test/functional-tests/cli/JavaScriptObfuscatorCLI.spec.ts @@ -29,7 +29,6 @@ describe('JavaScriptObfuscatorCLI', function (): void { const configFileName: string = 'config.js'; const configFilePath: string = path.join(configDirName, configFileName); - describe('run', () => { before(() => { mkdirp.sync(outputDirName); @@ -94,19 +93,14 @@ describe('JavaScriptObfuscatorCLI', function (): void { }); }); - describe('`--output` option isn\'t set', () => { + describe("`--output` option isn't set", () => { describe('Variant #1: default behaviour', () => { - let outputFixturesFilePath: string, - isFileExist: boolean; + let outputFixturesFilePath: string, isFileExist: boolean; before(() => { outputFixturesFilePath = path.join(fixturesDirName, outputFileName); - JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - fixtureFilePath - ]); + JavaScriptObfuscatorCLI.obfuscate(['node', 'javascript-obfuscator', fixtureFilePath]); isFileExist = fs.existsSync(outputFixturesFilePath); }); @@ -124,11 +118,12 @@ describe('JavaScriptObfuscatorCLI', function (): void { let testFunc: () => void; before(() => { - testFunc = () => JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - path.join('wrong', 'file', 'path') - ]); + testFunc = () => + JavaScriptObfuscatorCLI.obfuscate([ + 'node', + 'javascript-obfuscator', + path.join('wrong', 'file', 'path') + ]); }); it(`should throw an error`, () => { @@ -136,7 +131,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { }); }); - describe('Variant #3: input file extension isn\'t `.js`', () => { + describe("Variant #3: input file extension isn't `.js`", () => { const expectedError: RegExp = /Given input path must be a valid/; const outputFileName: string = 'sample-obfuscated.ts'; const outputFilePath: string = path.join(outputDirName, outputFileName); @@ -146,11 +141,8 @@ describe('JavaScriptObfuscatorCLI', function (): void { before(() => { fs.writeFileSync(outputFilePath, 'data'); - testFunc = () => JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - outputFilePath - ]); + testFunc = () => + JavaScriptObfuscatorCLI.obfuscate(['node', 'javascript-obfuscator', outputFilePath]); }); it(`should throw an error`, () => { @@ -190,15 +182,16 @@ describe('JavaScriptObfuscatorCLI', function (): void { let testFunc: () => void; before(() => { - testFunc = () => JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - fixtureFilePath, - '--output', - outputFilePath, - '--exclude', - path.join('**', 'sample.js') - ]); + testFunc = () => + JavaScriptObfuscatorCLI.obfuscate([ + 'node', + 'javascript-obfuscator', + fixtureFilePath, + '--output', + outputFilePath, + '--exclude', + path.join('**', 'sample.js') + ]); }); it('should throw an error', () => { @@ -372,7 +365,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { it( `should create file \`${outputFileName1}\` with obfuscated code in ` + - `\`${path.join(fixturesDirName, outputDirectoryName)}\` directory`, + `\`${path.join(fixturesDirName, outputDirectoryName)}\` directory`, () => { assert.equal(isFileExist1, true); } @@ -380,7 +373,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { it( `should create file \`${outputFileName2}\` with obfuscated code in ` + - `\`${path.join(fixturesDirName, outputDirectoryName)}\` directory`, + `\`${path.join(fixturesDirName, outputDirectoryName)}\` directory`, () => { assert.equal(isFileExist2, true); } @@ -388,7 +381,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { it( `shouldn't create file \`${outputFileName3}\` in ` + - `\`${path.join(fixturesDirName, outputDirectoryName)}\` directory`, + `\`${path.join(fixturesDirName, outputDirectoryName)}\` directory`, () => { assert.equal(isFileExist3, false); } @@ -562,9 +555,8 @@ describe('JavaScriptObfuscatorCLI', function (): void { sourceMapObject = JSON.parse(sourceMapContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); } catch (e) { @@ -625,9 +617,8 @@ describe('JavaScriptObfuscatorCLI', function (): void { sourceMapObject = JSON.parse(sourceMapContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); } catch (e) { @@ -686,15 +677,16 @@ describe('JavaScriptObfuscatorCLI', function (): void { try { sourceCodeContent = fs.readFileSync(fixtureFilePath, { encoding: 'utf8' }); - const sourceMapContent: string = fs.readFileSync(outputSourceMapFilePath, { encoding: 'utf8' }); + const sourceMapContent: string = fs.readFileSync(outputSourceMapFilePath, { + encoding: 'utf8' + }); isFileExist = true; sourceMapObject = JSON.parse(sourceMapContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); } catch (e) { @@ -752,15 +744,16 @@ describe('JavaScriptObfuscatorCLI', function (): void { try { sourceCodeContent = fs.readFileSync(fixtureFilePath, { encoding: 'utf8' }); - const sourceMapContent: string = fs.readFileSync(outputSourceMapPath, { encoding: 'utf8' }); + const sourceMapContent: string = fs.readFileSync(outputSourceMapPath, { + encoding: 'utf8' + }); isFileExist = true; sourceMapObject = JSON.parse(sourceMapContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); } catch (e) { @@ -825,15 +818,16 @@ describe('JavaScriptObfuscatorCLI', function (): void { try { sourceCodeContent = fs.readFileSync(fixtureFilePath, { encoding: 'utf8' }); - const sourceMapContent: string = fs.readFileSync(outputSourceMapPath, { encoding: 'utf8' }); + const sourceMapContent: string = fs.readFileSync(outputSourceMapPath, { + encoding: 'utf8' + }); isFileExist = true; sourceMapObject = JSON.parse(sourceMapContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); } catch (e) { @@ -901,14 +895,13 @@ describe('JavaScriptObfuscatorCLI', function (): void { sourceMapObject = parseSourceMapFromObfuscatedCode(obfuscatedCodeContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); }); - it('shouldn\'t create file with source map', () => { + it("shouldn't create file with source map", () => { assert.equal(isFileExist, false); }); @@ -956,14 +949,13 @@ describe('JavaScriptObfuscatorCLI', function (): void { sourceMapObject = parseSourceMapFromObfuscatedCode(obfuscatedCodeContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); }); - it('shouldn\'t create file with source map', () => { + it("shouldn't create file with source map", () => { assert.equal(isFileExist, false); }); @@ -1026,14 +1018,13 @@ describe('JavaScriptObfuscatorCLI', function (): void { sourceMapObject = parseSourceMapFromObfuscatedCode(obfuscatedCodeContent); resolveSources(sourceMapObject, fixtureFilePath, fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); }); - it('shouldn\'t create file with source map', () => { + it("shouldn't create file with source map", () => { assert.equal(isFileExist, false); }); @@ -1062,9 +1053,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { }); describe('help output', () => { - let callback: sinon.SinonSpy, - stdoutWriteMock: StdoutWriteMock, - stubExit: sinon.SinonStub; + let callback: sinon.SinonSpy, stdoutWriteMock: StdoutWriteMock, stubExit: sinon.SinonStub; beforeEach(() => { stubExit = sinon.stub(process, 'exit'); @@ -1078,11 +1067,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { beforeEach(() => { stdoutWriteMock.mute(); - JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - '--help' - ]); + JavaScriptObfuscatorCLI.obfuscate(['node', 'javascript-obfuscator', '--help']); stdoutWriteMock.restore(); isConsoleLogCalled = callback.called; @@ -1099,12 +1084,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { beforeEach(() => { stdoutWriteMock.mute(); - JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - '--help', - fixtureFilePath - ]); + JavaScriptObfuscatorCLI.obfuscate(['node', 'javascript-obfuscator', '--help', fixtureFilePath]); stdoutWriteMock.restore(); isConsoleLogCalled = callback.called; @@ -1121,12 +1101,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { beforeEach(() => { stdoutWriteMock.mute(); - JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator', - fixtureFilePath, - '--help' - ]); + JavaScriptObfuscatorCLI.obfuscate(['node', 'javascript-obfuscator', fixtureFilePath, '--help']); stdoutWriteMock.restore(); isConsoleLogCalled = callback.called; @@ -1143,10 +1118,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { beforeEach(() => { stdoutWriteMock.mute(); - JavaScriptObfuscatorCLI.obfuscate([ - 'node', - 'javascript-obfuscator' - ]); + JavaScriptObfuscatorCLI.obfuscate(['node', 'javascript-obfuscator']); stdoutWriteMock.restore(); isConsoleLogCalled = callback.called; @@ -1167,8 +1139,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { describe('Base options', () => { const outputSourceMapPath: string = `${outputFilePath}.map`; - let isFileExist: boolean, - sourceMapObject: any; + let isFileExist: boolean, sourceMapObject: any; before(() => { JavaScriptObfuscatorCLI.obfuscate([ @@ -1182,7 +1153,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { ]); try { - const content: string = fs.readFileSync(outputSourceMapPath, {encoding: 'utf8'}); + const content: string = fs.readFileSync(outputSourceMapPath, { encoding: 'utf8' }); isFileExist = true; sourceMapObject = JSON.parse(content); @@ -1269,11 +1240,11 @@ describe('JavaScriptObfuscatorCLI', function (): void { '--config', configFilePath, '--source-map', - 'false', + 'false' ]); try { - fs.readFileSync(outputSourceMapPath, {encoding: 'utf8'}); + fs.readFileSync(outputSourceMapPath, { encoding: 'utf8' }); isFileExist = true; } catch (e) { @@ -1349,8 +1320,7 @@ describe('JavaScriptObfuscatorCLI', function (): void { const expectedLoggingMessage1: string = `[javascript-obfuscator-cli] Error in file: ${inputFilePath}...`; - let consoleLogSpy: sinon.SinonSpy, - loggingMessageResult: string + let consoleLogSpy: sinon.SinonSpy, loggingMessageResult: string; before(() => { consoleLogSpy = sinon.spy(console, 'log'); diff --git a/test/functional-tests/code-transformers/preparing-transformers/hashbang-operator-transformer/HashbangOperatorTransformer.spec.ts b/test/functional-tests/code-transformers/preparing-transformers/hashbang-operator-transformer/HashbangOperatorTransformer.spec.ts index eb77332a..ab221ed9 100644 --- a/test/functional-tests/code-transformers/preparing-transformers/hashbang-operator-transformer/HashbangOperatorTransformer.spec.ts +++ b/test/functional-tests/code-transformers/preparing-transformers/hashbang-operator-transformer/HashbangOperatorTransformer.spec.ts @@ -11,22 +11,16 @@ describe('HashbangOperatorTransformer', () => { const lineSeparator: string = '\r?\n'; describe('Variant #1: simple', () => { - const regExp: RegExp = new RegExp( - `^#!\/usr\/bin\/env node${lineSeparator}` + - `var foo *= *'abc';` - ); + const regExp: RegExp = new RegExp(`^#!\/usr\/bin\/env node${lineSeparator}` + `var foo *= *'abc';`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should remove hashbang operator before ast transformation and append it after', () => { @@ -35,22 +29,16 @@ describe('HashbangOperatorTransformer', () => { }); describe('Variant #2: multiple new lines', () => { - const regExp: RegExp = new RegExp( - `^#!\/usr\/bin\/env node${lineSeparator.repeat(4)}` + - `var foo *= *'abc';` - ); + const regExp: RegExp = new RegExp(`^#!\/usr\/bin\/env node${lineSeparator.repeat(4)}` + `var foo *= *'abc';`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-new-lines.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should remove hashbang operator before ast transformation and append it after', () => { @@ -60,8 +48,7 @@ describe('HashbangOperatorTransformer', () => { describe('Variant #3: `stringArray` option enabled', () => { const regExp: RegExp = new RegExp( - `^#!\/usr\/bin\/env node${lineSeparator}.*` + - `${getStringArrayRegExp(['abc']).source}` + `^#!\/usr\/bin\/env node${lineSeparator}.*` + `${getStringArrayRegExp(['abc']).source}` ); let obfuscatedCode: string; @@ -69,14 +56,11 @@ describe('HashbangOperatorTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should remove hashbang operator before ast transformation and append it after', () => { @@ -85,21 +69,16 @@ describe('HashbangOperatorTransformer', () => { }); describe('Variant #4: invalid hashbang indent', () => { - const regExp: RegExp = new RegExp( - `^var foo *= *'abc';` - ); + const regExp: RegExp = new RegExp(`^var foo *= *'abc';`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/hashbang-indent.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should remove invalid hashbang operator', () => { @@ -108,21 +87,16 @@ describe('HashbangOperatorTransformer', () => { }); describe('Variant #5: hashbang as a string value', () => { - const regExp: RegExp = new RegExp( - `^var foo *= *'#!/usr/bin/env\\\\x20node';$` - ); + const regExp: RegExp = new RegExp(`^var foo *= *'#!/usr/bin/env\\\\x20node';$`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/hashbang-as-string-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should keep hashbang operator as a string value', () => { diff --git a/test/functional-tests/custom-code-helpers/console-output/ConsoleOutputDisableExpressionCodeHelper.spec.ts b/test/functional-tests/custom-code-helpers/console-output/ConsoleOutputDisableExpressionCodeHelper.spec.ts index 23086096..6ab766a8 100644 --- a/test/functional-tests/custom-code-helpers/console-output/ConsoleOutputDisableExpressionCodeHelper.spec.ts +++ b/test/functional-tests/custom-code-helpers/console-output/ConsoleOutputDisableExpressionCodeHelper.spec.ts @@ -7,7 +7,8 @@ import { readFileAsString } from '../../../helpers/readFileAsString'; import { JavaScriptObfuscator } from '../../../../src/JavaScriptObfuscatorFacade'; describe('ConsoleOutputDisableExpressionCodeHelper', () => { - const consoleGetterRegExp: RegExp = /var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\['console'] *= *_0x([a-f0-9]){4,6}\['console'] *\|| *{};/; + const consoleGetterRegExp: RegExp = + /var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\['console'] *= *_0x([a-f0-9]){4,6}\['console'] *\|| *{};/; describe('`disableConsoleOutput` option is set', () => { let obfuscatedCode: string; @@ -15,13 +16,10 @@ describe('ConsoleOutputDisableExpressionCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - disableConsoleOutput: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + disableConsoleOutput: true + }).getObfuscatedCode(); }); it('match #1: should correctly append code helper into the obfuscated code', () => { @@ -29,22 +27,19 @@ describe('ConsoleOutputDisableExpressionCodeHelper', () => { }); }); - describe('`disableConsoleOutput` option isn\'t set', () => { + describe("`disableConsoleOutput` option isn't set", () => { let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - disableConsoleOutput: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + disableConsoleOutput: false + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t append code helper into the obfuscated code', () => { + it("match #1: shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, consoleGetterRegExp); }); }); diff --git a/test/functional-tests/custom-code-helpers/console-output/templates/ConsoleOutputDisableTemplate.spec.ts b/test/functional-tests/custom-code-helpers/console-output/templates/ConsoleOutputDisableTemplate.spec.ts index 6ae24866..3b9840af 100644 --- a/test/functional-tests/custom-code-helpers/console-output/templates/ConsoleOutputDisableTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/console-output/templates/ConsoleOutputDisableTemplate.spec.ts @@ -48,7 +48,7 @@ const getPartialConsoleObjectGlobalVariableTemplate: () => string = () => ` * @param {string} additionalCode * @returns {Function} */ -function getFunctionFromTemplate ( +function getFunctionFromTemplate( templateData: any, callsControllerFunctionName: string, consoleMethod: keyof Console, @@ -102,7 +102,7 @@ describe('ConsoleOutputDisableTemplate', () => { { consoleLogDisableFunctionName, callControllerFunctionName, - globalVariableTemplate: GlobalVariableTemplate1(), + globalVariableTemplate: GlobalVariableTemplate1() }, callControllerFunctionName, consoleMethodName @@ -126,7 +126,7 @@ describe('ConsoleOutputDisableTemplate', () => { { consoleLogDisableFunctionName, callControllerFunctionName, - globalVariableTemplate: getPartialConsoleObjectGlobalVariableTemplate(), + globalVariableTemplate: getPartialConsoleObjectGlobalVariableTemplate() }, callControllerFunctionName, consoleMethodName @@ -150,7 +150,7 @@ describe('ConsoleOutputDisableTemplate', () => { { consoleLogDisableFunctionName, callControllerFunctionName, - globalVariableTemplate: getUndefinedConsoleObjectGlobalVariableTemplate(), + globalVariableTemplate: getUndefinedConsoleObjectGlobalVariableTemplate() }, callControllerFunctionName, consoleMethodName @@ -174,7 +174,7 @@ describe('ConsoleOutputDisableTemplate', () => { { consoleLogDisableFunctionName, callControllerFunctionName, - globalVariableTemplate: getWrongGlobalVariableTemplate(), + globalVariableTemplate: getWrongGlobalVariableTemplate() }, callControllerFunctionName, consoleMethodName @@ -196,16 +196,17 @@ describe('ConsoleOutputDisableTemplate', () => { let testFunc: () => void; beforeEach(() => { - testFunc = () => getFunctionFromTemplate( - { - consoleLogDisableFunctionName, + testFunc = () => + getFunctionFromTemplate( + { + consoleLogDisableFunctionName, + callControllerFunctionName, + globalVariableTemplate: GlobalVariableTemplate1() + }, callControllerFunctionName, - globalVariableTemplate: GlobalVariableTemplate1(), - }, - callControllerFunctionName, - consoleMethodName, - `console.${consoleMethodName}.bind();` - )(); + consoleMethodName, + `console.${consoleMethodName}.bind();` + )(); }); it(`should does not throw error during \`console.${consoleMethodName}.bind\` call`, () => { diff --git a/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-call-template/DebugProtectionFunctionCallTemplate.spec.ts b/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-call-template/DebugProtectionFunctionCallTemplate.spec.ts index 5a617364..ca3dba89 100644 --- a/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-call-template/DebugProtectionFunctionCallTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-call-template/DebugProtectionFunctionCallTemplate.spec.ts @@ -25,23 +25,19 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled debug protection', () => { @@ -58,23 +54,19 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled debug protection', () => { @@ -91,24 +83,20 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['foo', 'bar', 'baz', 'bark', 'hawk', 'eagle'] + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['foo', 'bar', 'baz', 'bark', 'hawk', 'eagle'] + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled debug protection', () => { @@ -125,23 +113,19 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - target: ObfuscationTarget.BrowserNoEval + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + target: ObfuscationTarget.BrowserNoEval + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled debug protection', () => { @@ -158,23 +142,19 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - target: ObfuscationTarget.ServiceWorker + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + target: ObfuscationTarget.ServiceWorker + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled debug protection', () => { @@ -191,23 +171,19 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true + }).getObfuscatedCode(); obfuscatedCode = obfuscatedCode.replace(/\+\+ *_0x([a-f0-9]){4,6}/, ''); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; + } - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should enter code in infinity loop', () => { @@ -224,22 +200,18 @@ describe('DebugProtectionFunctionCallTemplate', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/single-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled debug protection', () => { diff --git a/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-interval-template/DebugProtectionFunctionIntervalTemplate.spec.ts b/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-interval-template/DebugProtectionFunctionIntervalTemplate.spec.ts index 8f6a061f..52db40fd 100644 --- a/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-interval-template/DebugProtectionFunctionIntervalTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/debug-protection/templates/debug-protection-function-interval-template/DebugProtectionFunctionIntervalTemplate.spec.ts @@ -12,24 +12,18 @@ describe('DebugProtectionFunctionIntervalTemplate', function () { describe('Variant #1 - `high-obfuscation` preset interval', () => { const debugProtectionIntervalRegExp: RegExp = new RegExp( - `${variableMatch}\\['setInterval'\\]\\( *` + - `${variableMatch}, *` + - '0xfa0 *' + - `\\);` + `${variableMatch}\\['setInterval'\\]\\( *` + `${variableMatch}, *` + '0xfa0 *' + `\\);` ); let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - debugProtectionInterval: HIGH_OBFUSCATION_PRESET.debugProtectionInterval - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + debugProtectionInterval: HIGH_OBFUSCATION_PRESET.debugProtectionInterval + }).getObfuscatedCode(); console.log(obfuscatedCode); }); @@ -41,24 +35,18 @@ describe('DebugProtectionFunctionIntervalTemplate', function () { describe('Variant #2 - custom interval', () => { const debugProtectionIntervalRegExp: RegExp = new RegExp( - `${variableMatch}\\['setInterval'\\]\\( *` + - `${variableMatch}, *` + - '0x64 *' + - `\\);` + `${variableMatch}\\['setInterval'\\]\\( *` + `${variableMatch}, *` + '0x64 *' + `\\);` ); let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - debugProtectionInterval: 100 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + debugProtectionInterval: 100 + }).getObfuscatedCode(); }); it('Should add debug protection interval code with default interval value', () => { @@ -67,20 +55,17 @@ describe('DebugProtectionFunctionIntervalTemplate', function () { }); describe('Variant #3 - no interval', () => { - const debugProtectionIntervalRegExp: RegExp = /setInterval/ + const debugProtectionIntervalRegExp: RegExp = /setInterval/; let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - debugProtection: true, - debugProtectionInterval: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + debugProtection: true, + debugProtectionInterval: 0 + }).getObfuscatedCode(); }); it('Should not add debug protection interval code', () => { diff --git a/test/functional-tests/custom-code-helpers/domain-lock/DomainLockCodeHelper.spec.ts b/test/functional-tests/custom-code-helpers/domain-lock/DomainLockCodeHelper.spec.ts index fe187499..bcf0af63 100644 --- a/test/functional-tests/custom-code-helpers/domain-lock/DomainLockCodeHelper.spec.ts +++ b/test/functional-tests/custom-code-helpers/domain-lock/DomainLockCodeHelper.spec.ts @@ -18,13 +18,10 @@ describe('DomainLockCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: ['.example.com'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: ['.example.com'] + }).getObfuscatedCode(); }); it('should correctly append code helper into the obfuscated code', () => { @@ -39,15 +36,12 @@ describe('DomainLockCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: ['.example.com'], - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'foo' - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: ['.example.com'], + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'foo' + }).getObfuscatedCode(); }); it('should add prefix to the helper identifiers inside global scope', () => { @@ -62,15 +56,12 @@ describe('DomainLockCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/append-inside-function-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: ['.example.com'], - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'foo' - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: ['.example.com'], + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'foo' + }).getObfuscatedCode(); }); it('should not add prefix to the helper identifiers inside global scope', () => { @@ -79,7 +70,7 @@ describe('DomainLockCodeHelper', () => { }); }); - describe('`domainLock` option isn\'t set', () => { + describe("`domainLock` option isn't set", () => { const regExp: RegExp = /var _0x([a-f0-9]){4,6} *= *new RegExp/; let obfuscatedCode: string; @@ -87,16 +78,13 @@ describe('DomainLockCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: [] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: [] + }).getObfuscatedCode(); }); - it('shouldn\'t append code helper into the obfuscated code', () => { + it("shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, regExp); }); }); diff --git a/test/functional-tests/custom-code-helpers/domain-lock/templates/DomainLockNodeTemplate.spec.ts b/test/functional-tests/custom-code-helpers/domain-lock/templates/DomainLockNodeTemplate.spec.ts index 9e6dd434..6f30afa6 100644 --- a/test/functional-tests/custom-code-helpers/domain-lock/templates/DomainLockNodeTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/domain-lock/templates/DomainLockNodeTemplate.spec.ts @@ -24,7 +24,7 @@ import { readFileAsString } from '../../../../helpers/readFileAsString'; * @param {string} documentTemplate * @returns {Function} */ -function getFunctionFromTemplate ( +function getFunctionFromTemplate( templateData: any, callsControllerFunctionName: string, documentTemplate: string @@ -68,21 +68,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -115,21 +115,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -162,21 +162,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -210,21 +210,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -257,21 +257,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -304,21 +304,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -351,21 +351,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -399,21 +399,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -437,7 +437,7 @@ describe('DomainLockTemplate', () => { }); }); - describe('Variant #6: current domain doesn\'t match with `domainsString`', () => { + describe("Variant #6: current domain doesn't match with `domainsString`", () => { describe('Variant #1', () => { const domainsString: string = ['www.example.com'].join(';'); const domainLockRedirectUrl: string = 'about:blank'; @@ -447,21 +447,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -494,24 +494,25 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; - testFunc = getFunctionFromTemplate({ + testFunc = getFunctionFromTemplate( + { domainLockFunctionName: 'domainLockFunction', domainsStringDiff, domains: hiddenDomainsString, @@ -540,21 +541,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -587,21 +588,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -634,21 +635,21 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentDomain, - location: undefined, - }, + location: undefined + } }; testFunc = getFunctionFromTemplate( @@ -683,22 +684,22 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { location: { - hostname: currentHostName, - }, - }, + hostname: currentHostName + } + } }; testFunc = getFunctionFromTemplate( @@ -722,7 +723,7 @@ describe('DomainLockTemplate', () => { }); }); - describe('Variant #2: current location.hostname doesn\'t match with `domainsString`', () => { + describe("Variant #2: current location.hostname doesn't match with `domainsString`", () => { const domainsString: string = ['www.example.com'].join(';'); const domainLockRedirectUrl: string = 'about:blank'; const currentHostName: string = 'www.test.com'; @@ -731,22 +732,22 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { location: { - hostname: currentHostName, - }, - }, + hostname: currentHostName + } + } }; testFunc = getFunctionFromTemplate( @@ -781,23 +782,23 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentHostName, location: { - hostname: currentHostName, - }, - }, + hostname: currentHostName + } + } }; testFunc = getFunctionFromTemplate( @@ -821,7 +822,7 @@ describe('DomainLockTemplate', () => { }); }); - describe('Variant #2: current domain doesn\'t match with `domainsString`', () => { + describe("Variant #2: current domain doesn't match with `domainsString`", () => { const domainsString: string = ['www.example.com'].join(';'); const domainLockRedirectUrl: string = 'about:blank'; const currentHostName: string = 'www.test.com'; @@ -830,23 +831,23 @@ describe('DomainLockTemplate', () => { let root: any; before(() => { - const [ - hiddenDomainsString, - domainsStringDiff - ] = cryptUtils.hideString(domainsString, domainsString.length * 3); + const [hiddenDomainsString, domainsStringDiff] = cryptUtils.hideString( + domainsString, + domainsString.length * 3 + ); - const [ - hiddenDomainLockRedirectUrl, - domainLockRedirectUrlDiff - ] = cryptUtils.hideString(domainLockRedirectUrl, domainLockRedirectUrl.length * 3); + const [hiddenDomainLockRedirectUrl, domainLockRedirectUrlDiff] = cryptUtils.hideString( + domainLockRedirectUrl, + domainLockRedirectUrl.length * 3 + ); root = { document: { domain: currentHostName, location: { - hostname: currentHostName, - }, - }, + hostname: currentHostName + } + } }; testFunc = getFunctionFromTemplate( @@ -885,15 +886,12 @@ describe('DomainLockTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: ['obfuscator.io'], - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: ['obfuscator.io'], + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -913,15 +911,12 @@ describe('DomainLockTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: ['obfuscator.io'], - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: ['obfuscator.io'], + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -941,15 +936,12 @@ describe('DomainLockTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - domainLock: ['obfuscator.io'], - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + domainLock: ['obfuscator.io'], + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); diff --git a/test/functional-tests/custom-code-helpers/self-defending/SelfDefendingCodeHelper.spec.ts b/test/functional-tests/custom-code-helpers/self-defending/SelfDefendingCodeHelper.spec.ts index 61533dff..2da4fe28 100644 --- a/test/functional-tests/custom-code-helpers/self-defending/SelfDefendingCodeHelper.spec.ts +++ b/test/functional-tests/custom-code-helpers/self-defending/SelfDefendingCodeHelper.spec.ts @@ -17,15 +17,12 @@ describe('SelfDefendingCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'foo', - selfDefending: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'foo', + selfDefending: true + }).getObfuscatedCode(); }); it('should add prefix to the helper identifiers inside global scope', () => { @@ -40,15 +37,12 @@ describe('SelfDefendingCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/append-inside-function-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'foo', - selfDefending: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'foo', + selfDefending: true + }).getObfuscatedCode(); }); it('should not add prefix to the helper identifiers inside global scope', () => { diff --git a/test/functional-tests/custom-code-helpers/self-defending/templates/SelfDefendingTemplate.spec.ts b/test/functional-tests/custom-code-helpers/self-defending/templates/SelfDefendingTemplate.spec.ts index 20fafd2d..f9633af0 100644 --- a/test/functional-tests/custom-code-helpers/self-defending/templates/SelfDefendingTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/self-defending/templates/SelfDefendingTemplate.spec.ts @@ -30,23 +30,19 @@ describe('SelfDefendingTemplate', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...baseOptions, - selfDefending: true, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...baseOptions, + selfDefending: true, + identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, correctEvaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, correctEvaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled self defending', () => { @@ -63,23 +59,19 @@ describe('SelfDefendingTemplate', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - baseOptions, - selfDefending: true, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + baseOptions, + selfDefending: true, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, correctEvaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, correctEvaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled self defending', () => { @@ -96,24 +88,20 @@ describe('SelfDefendingTemplate', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - baseOptions, - selfDefending: true, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['foo', 'bar', 'baz', 'bark', 'hawk', 'eagle'] + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + baseOptions, + selfDefending: true, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['foo', 'bar', 'baz', 'bark', 'hawk', 'eagle'] + }).getObfuscatedCode(); + + return evaluateInWorker(obfuscatedCode, correctEvaluationTimeout).then((result: string | null) => { + if (!result) { + return; } - ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, correctEvaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } - - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should correctly evaluate code with enabled self defending', () => { @@ -131,23 +119,19 @@ describe('SelfDefendingTemplate', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...baseOptions, - selfDefending: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...baseOptions, + selfDefending: true + }).getObfuscatedCode(); obfuscatedCode = beautifyCode(obfuscatedCode, 'space'); - return evaluateInWorker(obfuscatedCode, redosEvaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } + return evaluateInWorker(obfuscatedCode, redosEvaluationTimeout).then((result: string | null) => { + if (!result) { + return; + } - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should enter code in infinity loop', () => { @@ -164,23 +148,19 @@ describe('SelfDefendingTemplate', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...baseOptions, - selfDefending: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...baseOptions, + selfDefending: true + }).getObfuscatedCode(); obfuscatedCode = beautifyCode(obfuscatedCode, 'tab'); - return evaluateInWorker(obfuscatedCode, redosEvaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } + return evaluateInWorker(obfuscatedCode, redosEvaluationTimeout).then((result: string | null) => { + if (!result) { + return; + } - evaluationResult = parseInt(result, 10); - }); + evaluationResult = parseInt(result, 10); + }); }); it('should enter code in infinity loop', () => { @@ -211,14 +191,13 @@ describe('SelfDefendingTemplate', function () { } ).getObfuscatedCode(); - return evaluateInWorker(obfuscatedCode, evaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } + return evaluateInWorker(obfuscatedCode, evaluationTimeout).then((result: string | null) => { + if (!result) { + return; + } - evaluationResult = result; - }); + evaluationResult = result; + }); }); it('should correctly evaluate code with enabled self defending', () => { @@ -247,14 +226,13 @@ describe('SelfDefendingTemplate', function () { ).getObfuscatedCode(); obfuscatedCode = beautifyCode(obfuscatedCode, 'space'); - return evaluateInWorker(obfuscatedCode, redosEvaluationTimeout) - .then((result: string | null) => { - if (!result) { - return; - } + return evaluateInWorker(obfuscatedCode, redosEvaluationTimeout).then((result: string | null) => { + if (!result) { + return; + } - evaluationResult = result; - }); + evaluationResult = result; + }); }); it('should enter code in infinity loop', () => { diff --git a/test/functional-tests/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.spec.ts b/test/functional-tests/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.spec.ts index b5efc053..6f2aff93 100644 --- a/test/functional-tests/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/StringArrayCallsWrapperCodeHelper.spec.ts @@ -25,14 +25,11 @@ describe('StringArrayCallsWrapperCodeHelper', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (obfuscatedCode.match(stringArrayCallsWrapperAtFirstPositionRegExp)) { stringArrayCallsWrapperAtFirstPositionMatchesCount++; @@ -59,14 +56,11 @@ describe('StringArrayCallsWrapperCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should correctly append code helper into the obfuscated code', () => { @@ -74,49 +68,45 @@ describe('StringArrayCallsWrapperCodeHelper', () => { }); }); - describe('`stringArray` option isn\'t set', () => { + describe("`stringArray` option isn't set", () => { let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: false + }).getObfuscatedCode(); }); - it('shouldn\'t append code helper into the obfuscated code', () => { + it("shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, stringCallsWrapperRegExp); }); }); describe('Preserve string array name', () => { - const callsWrapperRegExp: RegExp = new RegExp(`` + - `function *b *\\(c, *d\\) *{ *` + - `c *= *c *- *0x0; *` + - `var e *= *a *\\(\\);` + - `var f *= *e\\[c]; *` + - ``); + const callsWrapperRegExp: RegExp = new RegExp( + `` + + `function *b *\\(c, *d\\) *{ *` + + `c *= *c *- *0x0; *` + + `var e *= *a *\\(\\);` + + `var f *= *e\\[c]; *` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [StringArrayEncoding.Base64] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.Base64] + }).getObfuscatedCode(); }); it('should preserve string array name', () => { diff --git a/test/functional-tests/custom-code-helpers/string-array/StringArrayCodeHelper.spec.ts b/test/functional-tests/custom-code-helpers/string-array/StringArrayCodeHelper.spec.ts index 3b4fa970..324c8873 100644 --- a/test/functional-tests/custom-code-helpers/string-array/StringArrayCodeHelper.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/StringArrayCodeHelper.spec.ts @@ -23,14 +23,11 @@ describe('StringArrayCodeHelper', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (obfuscatedCode.match(stringArrayAtFirstPositionRegExp)) { stringArrayAtFirstPositionMatchesCount++; @@ -51,22 +48,19 @@ describe('StringArrayCodeHelper', () => { }); }); - describe('`stringArray` option isn\'t set', () => { + describe("`stringArray` option isn't set", () => { let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: false + }).getObfuscatedCode(); }); - it('shouldn\'t append code helper into the obfuscated code', () => { + it("shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, stringArrayRegExp); }); }); diff --git a/test/functional-tests/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.spec.ts b/test/functional-tests/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.spec.ts index 7c4443ed..8913566a 100644 --- a/test/functional-tests/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/StringArrayRotateFunctionCodeHelper.spec.ts @@ -18,15 +18,12 @@ describe('StringArrayRotateFunctionCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should correctly append code helper into the obfuscated code', () => { @@ -34,24 +31,21 @@ describe('StringArrayRotateFunctionCodeHelper', () => { }); }); - describe('`stringArray` option isn\'t set', () => { + describe("`stringArray` option isn't set", () => { let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: false, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: false, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t append code helper into the obfuscated code', () => { + it("shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, regExp); }); }); @@ -59,22 +53,20 @@ describe('StringArrayRotateFunctionCodeHelper', () => { describe('Comparison expression', () => { describe('Should add comparison expression to the code helper', () => { - const comparisonExpressionRegExp: RegExp = /var _0x([a-f0-9]){4,6} *= *-?parseInt\(_0x([a-f0-9]){4,6}\(0x.\)\)/; + const comparisonExpressionRegExp: RegExp = + /var _0x([a-f0-9]){4,6} *= *-?parseInt\(_0x([a-f0-9]){4,6}\(0x.\)\)/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add comparison expression to the code', () => { @@ -92,16 +84,13 @@ describe('StringArrayRotateFunctionCodeHelper', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should preserve string array name', () => { diff --git a/test/functional-tests/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.spec.ts b/test/functional-tests/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.spec.ts index 10c350ca..dba52ab1 100644 --- a/test/functional-tests/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/group/StringArrayCodeHelperGroup.spec.ts @@ -13,12 +13,10 @@ import { JavaScriptObfuscator } from '../../../../../src/JavaScriptObfuscatorFac describe('StringArrayCodeHelperGroup', () => { const regExp: RegExp = new RegExp( 'function *\\w *\\(\\w, *\\w\\) *{.*return \\w;}.*' + - 'function *\\w *\\(\\w, *\\w\\) *{.*return \\w;}.*' + - 'function *\\w *\\(\\w, *\\w\\) *{.*return \\w;}' - ); - const stringArrayCallsWrapperRegExp: RegExp = new RegExp( - `function *(\\w) *\\(\\w, *\\w\\) *{.*return \\w;}.*` + 'function *\\w *\\(\\w, *\\w\\) *{.*return \\w;}.*' + + 'function *\\w *\\(\\w, *\\w\\) *{.*return \\w;}' ); + const stringArrayCallsWrapperRegExp: RegExp = new RegExp(`function *(\\w) *\\(\\w, *\\w\\) *{.*return \\w;}.*`); describe('StringArrayCallsWrapper code helper names', function () { this.timeout(10000); @@ -33,20 +31,13 @@ describe('StringArrayCodeHelperGroup', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64, StringArrayEncoding.Rc4] + }).getObfuscatedCode(); const callsWrapperName: string = getRegExpMatch(obfuscatedCode, stringArrayCallsWrapperRegExp); diff --git a/test/functional-tests/custom-code-helpers/string-array/templates/string-array-calls-wrapper-node-template/StringArrayCallsWrapperTemplate.spec.ts b/test/functional-tests/custom-code-helpers/string-array/templates/string-array-calls-wrapper-node-template/StringArrayCallsWrapperTemplate.spec.ts index 31f74032..68a39350 100644 --- a/test/functional-tests/custom-code-helpers/string-array/templates/string-array-calls-wrapper-node-template/StringArrayCallsWrapperTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/templates/string-array-calls-wrapper-node-template/StringArrayCallsWrapperTemplate.spec.ts @@ -34,17 +34,16 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobFunctionName: string = 'atob'; const rc4FunctionName: string = 'rc4'; - let cryptUtilsSwappedAlphabet: ICryptUtilsStringArray, - randomGenerator: IRandomGenerator; + let cryptUtilsSwappedAlphabet: ICryptUtilsStringArray, randomGenerator: IRandomGenerator; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - cryptUtilsSwappedAlphabet = inversifyContainerFacade - .get(ServiceIdentifiers.ICryptUtilsStringArray); - randomGenerator = inversifyContainerFacade - .get(ServiceIdentifiers.IRandomGenerator); + cryptUtilsSwappedAlphabet = inversifyContainerFacade.get( + ServiceIdentifiers.ICryptUtilsStringArray + ); + randomGenerator = inversifyContainerFacade.get(ServiceIdentifiers.IRandomGenerator); }); describe('Variant #1: `base64` encoding', () => { @@ -69,16 +68,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, indexShiftAmount, @@ -119,16 +115,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, indexShiftAmount, @@ -167,16 +160,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, indexShiftAmount, @@ -216,7 +206,7 @@ describe('StringArrayCallsWrapperTemplate', () => { let decodedValue: string; - before(async() => { + before(async () => { const stringArrayTemplate = format(StringArrayTemplate(), { stringArrayName, stringArrayFunctionName, @@ -225,16 +215,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = await minimizeCode( format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, @@ -268,7 +255,7 @@ describe('StringArrayCallsWrapperTemplate', () => { let decodedValue: string; - before(async() => { + before(async () => { const stringArrayTemplate = format(StringArrayTemplate(), { stringArrayName, stringArrayFunctionName, @@ -277,16 +264,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = await minimizeCode( format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, @@ -331,16 +315,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, indexShiftAmount, @@ -381,16 +362,13 @@ describe('StringArrayCallsWrapperTemplate', () => { const atobPolyfill = format(AtobTemplate(selfDefendingEnabled), { atobFunctionName }); - const atobDecodeTemplate: string = format( - StringArrayBase64DecodeTemplate(randomGenerator), - { - atobPolyfill, - atobFunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const atobDecodeTemplate: string = format(StringArrayBase64DecodeTemplate(randomGenerator), { + atobPolyfill, + atobFunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: atobDecodeTemplate, indexShiftAmount, @@ -443,17 +421,14 @@ describe('StringArrayCallsWrapperTemplate', () => { atobFunctionName, rc4FunctionName }); - const rc4decodeCodeHelperTemplate: string = format( - StringArrayRC4DecodeTemplate(randomGenerator), - { - atobPolyfill, - rc4Polyfill, - rc4FunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const rc4decodeCodeHelperTemplate: string = format(StringArrayRC4DecodeTemplate(randomGenerator), { + atobPolyfill, + rc4Polyfill, + rc4FunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: rc4decodeCodeHelperTemplate, indexShiftAmount, @@ -499,17 +474,14 @@ describe('StringArrayCallsWrapperTemplate', () => { atobFunctionName, rc4FunctionName }); - const rc4decodeCodeHelperTemplate: string = format( - StringArrayRC4DecodeTemplate(randomGenerator), - { - atobPolyfill, - rc4Polyfill, - rc4FunctionName, - selfDefendingCode: '', - stringArrayCacheName, - stringArrayCallsWrapperName - } - ); + const rc4decodeCodeHelperTemplate: string = format(StringArrayRC4DecodeTemplate(randomGenerator), { + atobPolyfill, + rc4Polyfill, + rc4FunctionName, + selfDefendingCode: '', + stringArrayCacheName, + stringArrayCallsWrapperName + }); const stringArrayCallsWrapperTemplate: string = format(StringArrayCallsWrapperTemplate(), { decodeCodeHelperTemplate: rc4decodeCodeHelperTemplate, indexShiftAmount, @@ -547,7 +519,7 @@ describe('StringArrayCallsWrapperTemplate', () => { let decodedValue: string; - before(async() => { + before(async () => { const stringArrayTemplate = format(StringArrayTemplate(), { stringArrayName, stringArrayFunctionName, @@ -661,18 +633,16 @@ describe('StringArrayCallsWrapperTemplate', () => { describe('Prevailing kind of variables', () => { describe('`var` kind', () => { let obfuscatedCode: string, - stringArrayCallsWrapperVariableRegExp: RegExp = /var (_0x(\w){4,6}) *= *(_0x(\w){4,6})\[(_0x(\w){4,6})];/; + stringArrayCallsWrapperVariableRegExp: RegExp = + /var (_0x(\w){4,6}) *= *(_0x(\w){4,6})\[(_0x(\w){4,6})];/; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -688,18 +658,16 @@ describe('StringArrayCallsWrapperTemplate', () => { describe('`const` kind', () => { let obfuscatedCode: string, - stringArrayCallsWrapperVariableRegExp: RegExp = /let (_0x(\w){4,6}) *= *(_0x(\w){4,6})\[(_0x(\w){4,6})];/; + stringArrayCallsWrapperVariableRegExp: RegExp = + /let (_0x(\w){4,6}) *= *(_0x(\w){4,6})\[(_0x(\w){4,6})];/; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -715,18 +683,16 @@ describe('StringArrayCallsWrapperTemplate', () => { describe('`let` kind', () => { let obfuscatedCode: string, - stringArrayCallsWrapperVariableRegExp: RegExp = /let (_0x(\w){4,6}) *= *(_0x(\w){4,6})\[(_0x(\w){4,6})];/; + stringArrayCallsWrapperVariableRegExp: RegExp = + /let (_0x(\w){4,6}) *= *(_0x(\w){4,6})\[(_0x(\w){4,6})];/; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); diff --git a/test/functional-tests/custom-code-helpers/string-array/templates/string-array-rotate-function-template/StringArrayRotateFunctionTemplate.spec.ts b/test/functional-tests/custom-code-helpers/string-array/templates/string-array-rotate-function-template/StringArrayRotateFunctionTemplate.spec.ts index 7e1c59f7..ee54ef2f 100644 --- a/test/functional-tests/custom-code-helpers/string-array/templates/string-array-rotate-function-template/StringArrayRotateFunctionTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/templates/string-array-rotate-function-template/StringArrayRotateFunctionTemplate.spec.ts @@ -19,15 +19,12 @@ describe('StringArrayRotateFunctionTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayRotate: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayRotate: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -49,15 +46,12 @@ describe('StringArrayRotateFunctionTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayRotate: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayRotate: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -79,15 +73,12 @@ describe('StringArrayRotateFunctionTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayRotate: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayRotate: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -107,15 +98,12 @@ describe('StringArrayRotateFunctionTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayRotate: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayRotate: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -135,15 +123,12 @@ describe('StringArrayRotateFunctionTemplate', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayRotate: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayRotate: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); diff --git a/test/functional-tests/custom-code-helpers/string-array/templates/string-array-template/StringArrayTemplate.spec.ts b/test/functional-tests/custom-code-helpers/string-array/templates/string-array-template/StringArrayTemplate.spec.ts index 3742c78e..bd6c2d25 100644 --- a/test/functional-tests/custom-code-helpers/string-array/templates/string-array-template/StringArrayTemplate.spec.ts +++ b/test/functional-tests/custom-code-helpers/string-array/templates/string-array-template/StringArrayTemplate.spec.ts @@ -14,18 +14,15 @@ describe('StringArrayTemplate', () => { describe('Prevailing kind of variables', () => { describe('`var` kind', () => { let obfuscatedCode: string, - stringArrayRegExp: RegExp = getStringArrayRegExp(['foo'], {kind: 'var'}); + stringArrayRegExp: RegExp = getStringArrayRegExp(['foo'], { kind: 'var' }); beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -41,18 +38,15 @@ describe('StringArrayTemplate', () => { describe('`const` kind', () => { let obfuscatedCode: string, - stringArrayRegExp: RegExp = getStringArrayRegExp(['foo'], {kind: 'const'}); + stringArrayRegExp: RegExp = getStringArrayRegExp(['foo'], { kind: 'const' }); beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); @@ -68,18 +62,15 @@ describe('StringArrayTemplate', () => { describe('`let` kind', () => { let obfuscatedCode: string, - stringArrayRegExp: RegExp = getStringArrayRegExp(['foo'], {kind: 'const'}); + stringArrayRegExp: RegExp = getStringArrayRegExp(['foo'], { kind: 'const' }); beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); }); diff --git a/test/functional-tests/generators/identifier-names-generators/dictionary-identifier-names-generator/DictionaryIdentifierNamesGenerator.spec.ts b/test/functional-tests/generators/identifier-names-generators/dictionary-identifier-names-generator/DictionaryIdentifierNamesGenerator.spec.ts index 8d2520d2..28132ffb 100644 --- a/test/functional-tests/generators/identifier-names-generators/dictionary-identifier-names-generator/DictionaryIdentifierNamesGenerator.spec.ts +++ b/test/functional-tests/generators/identifier-names-generators/dictionary-identifier-names-generator/DictionaryIdentifierNamesGenerator.spec.ts @@ -14,13 +14,10 @@ describe('DictionaryIdentifierNamesGenerator', () => { describe('generateWithPrefix', () => { describe('Variant #1: should not generate same name for string array as existing name in code', () => { describe('Variant #1: `renameGlobals` option is disabled', () => { - const stringArrayStorageRegExp: RegExp = getStringArrayRegExp( - ['_aa', '_ab'], - { - name: '\\w*', - kind: 'const' - } - ); + const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['_aa', '_ab'], { + name: '\\w*', + kind: 'const' + }); const variableDeclarationIdentifierNameRegExp1: RegExp = /const (\w*) *= *\w*\(0x0\);/; const variableDeclarationIdentifierNameRegExp2: RegExp = /const (\w*) *= *\w*\(0x1\);/; @@ -30,21 +27,20 @@ describe('DictionaryIdentifierNamesGenerator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['a', 'b', 'c'], - identifiersPrefix: 'a', - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1, - seed: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['a', 'b', 'c'], + identifiersPrefix: 'a', + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1, + seed: 1 + }).getObfuscatedCode(); stringArrayName = getRegExpMatch(obfuscatedCode, stringArrayStorageRegExp); variableDeclarationIdentifierName1 = getRegExpMatch( @@ -71,13 +67,10 @@ describe('DictionaryIdentifierNamesGenerator', () => { }); describe('Variant #2: `renameGlobals` option is enabled', () => { - const stringArrayStorageRegExp: RegExp = getStringArrayRegExp( - ['_aa', '_ab'], - { - name: '\\w*', - kind: 'const' - } - ); + const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['_aa', '_ab'], { + name: '\\w*', + kind: 'const' + }); const variableDeclarationIdentifierNameRegExp1: RegExp = /const (\w*) *= *\w*\(0x0\);/; const variableDeclarationIdentifierNameRegExp2: RegExp = /const (\w*) *= *\w*\(0x1\);/; @@ -87,21 +80,20 @@ describe('DictionaryIdentifierNamesGenerator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['a', 'b', 'c', 'd'], - identifiersPrefix: 'a', - renameGlobals: true, - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['a', 'b', 'c', 'd'], + identifiersPrefix: 'a', + renameGlobals: true, + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); stringArrayName = getRegExpMatch(obfuscatedCode, stringArrayStorageRegExp); variableDeclarationIdentifierName1 = getRegExpMatch( @@ -134,36 +126,35 @@ describe('DictionaryIdentifierNamesGenerator', () => { const samplesCount: number = 30; describe('Variant #1: `renameGlobals` option is disabled', () => { - const stringArrayStorageRegExp: RegExp = getStringArrayRegExp( - ['first', 'abc'], - { - name: '\\w*', - kind: 'const' - } - ); + const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['first', 'abc'], { + name: '\\w*', + kind: 'const' + }); const variableDeclarationIdentifierNameRegExp: RegExp = /const (\w*) *= *\w*\(0x0\);/; let isIdentifiersAreConflicted: boolean = false; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-2.js' + ); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['a', 'b', 'aa'], - identifiersPrefix: 'a', - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['a', 'b', 'aa'], + identifiersPrefix: 'a', + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const stringArrayStorageName: string = getRegExpMatch(obfuscatedCode, stringArrayStorageRegExp); - const variableDeclarationIdentifierName: string = getRegExpMatch(obfuscatedCode, variableDeclarationIdentifierNameRegExp); + const variableDeclarationIdentifierName: string = getRegExpMatch( + obfuscatedCode, + variableDeclarationIdentifierNameRegExp + ); if (stringArrayStorageName === variableDeclarationIdentifierName) { isIdentifiersAreConflicted = true; @@ -179,37 +170,36 @@ describe('DictionaryIdentifierNamesGenerator', () => { }); describe('Variant #2: `renameGlobals` option is enabled', () => { - const stringArrayStorageRegExp: RegExp = getStringArrayRegExp( - ['first', 'abc'], - { - name: '\\w*', - kind: 'const' - } - ); + const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['first', 'abc'], { + name: '\\w*', + kind: 'const' + }); const variableDeclarationIdentifierNameRegExp: RegExp = /const (\w*) *= *\w*\(0x0\);/; let isIdentifiersAreConflicted: boolean = false; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-2.js' + ); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['a', 'b', 'aa'], - identifiersPrefix: 'a', - renameGlobals: true, - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['a', 'b', 'aa'], + identifiersPrefix: 'a', + renameGlobals: true, + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const stringArrayStorageName: string = getRegExpMatch(obfuscatedCode, stringArrayStorageRegExp); - const variableDeclarationIdentifierName: string = getRegExpMatch(obfuscatedCode, variableDeclarationIdentifierNameRegExp); + const variableDeclarationIdentifierName: string = getRegExpMatch( + obfuscatedCode, + variableDeclarationIdentifierNameRegExp + ); if (stringArrayStorageName === variableDeclarationIdentifierName) { isIdentifiersAreConflicted = true; diff --git a/test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/MangledIdentifierNamesGenerator.spec.ts b/test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/MangledIdentifierNamesGenerator.spec.ts index 62d8800a..1dc01f54 100644 --- a/test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/MangledIdentifierNamesGenerator.spec.ts +++ b/test/functional-tests/generators/identifier-names-generators/mangled-identifier-names-generator/MangledIdentifierNamesGenerator.spec.ts @@ -22,19 +22,18 @@ describe('MangledIdentifierNamesGenerator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'a', - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'a', + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should generate correct identifier for string array', () => { @@ -56,20 +55,19 @@ describe('MangledIdentifierNamesGenerator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'a', - renameGlobals: true, - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'a', + renameGlobals: true, + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should generate correct identifier for string array', () => { @@ -94,19 +92,18 @@ describe('MangledIdentifierNamesGenerator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'a', - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'a', + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should generate correct identifier name for string array', () => { @@ -133,20 +130,19 @@ describe('MangledIdentifierNamesGenerator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-name-conflict-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-name-conflict-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'a', - renameGlobals: true, - transformObjectKeys: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'a', + renameGlobals: true, + transformObjectKeys: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should generate correct identifier name for string array', () => { @@ -176,13 +172,10 @@ describe('MangledIdentifierNamesGenerator', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Match #1: should keep identifier name for variable declaration', () => { @@ -208,14 +201,11 @@ describe('MangledIdentifierNamesGenerator', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should generate valid identifier name for variable declaration', () => { @@ -247,15 +237,12 @@ describe('MangledIdentifierNamesGenerator', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should generate valid identifier names for string array', () => { @@ -289,16 +276,13 @@ describe('MangledIdentifierNamesGenerator', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - renameGlobals: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + renameGlobals: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should generate valid identifier names for string array', () => { @@ -321,30 +305,29 @@ describe('MangledIdentifierNamesGenerator', () => { describe('Variant #3: Should generate different names set for different lexical scopes: nested functions', () => { describe('Variant #1: `renameGlobals` option is disabled', () => { - const regExp: RegExp = new RegExp(`` + - `var foo *= *'abc'; *` + - `function bar *\\(a, *b\\) *{` + + const regExp: RegExp = new RegExp( + `` + + `var foo *= *'abc'; *` + + `function bar *\\(a, *b\\) *{` + `function c *\\(e, *f\\) *{ *} *` + `function d *\\(e, *f\\) *{ *} *` + - `} *` + - `function baz *\\(a, *b\\) *{` + + `} *` + + `function baz *\\(a, *b\\) *{` + `function c *\\(e, *f\\) *{ *} *` + `function d *\\(e, *f\\) *{ *} *` + - `}` + - ``); + `}` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Match #1: should generate valid identifier names', () => { @@ -353,31 +336,30 @@ describe('MangledIdentifierNamesGenerator', () => { }); describe('Variant #2: `renameGlobals` option is enabled', () => { - const regExp: RegExp = new RegExp(`` + - `var a *= *'abc'; *` + - `function b *\\(d, *e\\) *{` + + const regExp: RegExp = new RegExp( + `` + + `var a *= *'abc'; *` + + `function b *\\(d, *e\\) *{` + `function f *\\(h, *i\\) *{ *} *` + `function g *\\(h, *i\\) *{ *} *` + - `} *` + - `function c *\\(d, *e\\) *{` + + `} *` + + `function c *\\(d, *e\\) *{` + `function f *\\(h, *i\\) *{ *} *` + `function g *\\(h, *i\\) *{ *} *` + - `}` + - ``); + `}` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/lexical-block-scope-identifiers-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should generate valid identifier names', () => { diff --git a/test/functional-tests/generators/identifier-names-generators/mangled-shuffled-identifier-names-generator/MangledShuffledIdentifierNamesGenerator.spec.ts b/test/functional-tests/generators/identifier-names-generators/mangled-shuffled-identifier-names-generator/MangledShuffledIdentifierNamesGenerator.spec.ts index 4c41473f..b17f62db 100644 --- a/test/functional-tests/generators/identifier-names-generators/mangled-shuffled-identifier-names-generator/MangledShuffledIdentifierNamesGenerator.spec.ts +++ b/test/functional-tests/generators/identifier-names-generators/mangled-shuffled-identifier-names-generator/MangledShuffledIdentifierNamesGenerator.spec.ts @@ -12,9 +12,9 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { describe('Variant #1: prevent name sequence mutation of base `mangled` generator', () => { const functionsRegExp: RegExp = new RegExp( 'function foo *\\(a, *b\\) *{} *' + - 'function foo *\\(a, *b\\) *{} *' + - 'function foo *\\(a, *b\\) *{} *' + - 'function foo *\\(a, *b\\) *{}' + 'function foo *\\(a, *b\\) *{} *' + + 'function foo *\\(a, *b\\) *{} *' + + 'function foo *\\(a, *b\\) *{}' ); let obfuscatedCode: string = ''; @@ -23,17 +23,15 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { const code: string = readFileAsString(__dirname + '/fixtures/prevent-name-sequence-mutation.js'); for (let i = 0; i < 4; i++) { - const identifierNamesGenerator = i % 2 === 0 - ? IdentifierNamesGenerator.MangledIdentifierNamesGenerator - : IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator; + const identifierNamesGenerator = + i % 2 === 0 + ? IdentifierNamesGenerator.MangledIdentifierNamesGenerator + : IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator; - obfuscatedCode += JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode += JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator + }).getObfuscatedCode(); } }); diff --git a/test/functional-tests/issues/issue321.spec.ts b/test/functional-tests/issues/issue321.spec.ts index a5fe68e5..31318945 100644 --- a/test/functional-tests/issues/issue321.spec.ts +++ b/test/functional-tests/issues/issue321.spec.ts @@ -13,14 +13,10 @@ describe('Issue #321', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/issue321.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: false, - } - ).getObfuscatedCode(); - + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: false + }).getObfuscatedCode(); }); it('does not break on run', () => { diff --git a/test/functional-tests/issues/issue355.spec.ts b/test/functional-tests/issues/issue355.spec.ts index d16d716e..eb4738a7 100644 --- a/test/functional-tests/issues/issue355.spec.ts +++ b/test/functional-tests/issues/issue355.spec.ts @@ -2,7 +2,7 @@ import { assert } from 'chai'; import { NO_ADDITIONAL_NODES_PRESET } from '../../../src/options/presets/NoCustomNodes'; import { readFileAsString } from '../../helpers/readFileAsString'; import { JavaScriptObfuscator } from '../../../src/JavaScriptObfuscatorFacade'; -import { IdentifierNamesGenerator } from "../../../src/enums/generators/identifier-names-generators/IdentifierNamesGenerator"; +import { IdentifierNamesGenerator } from '../../../src/enums/generators/identifier-names-generators/IdentifierNamesGenerator'; // // https://github.com/javascript-obfuscator/javascript-obfuscator/issues/355 @@ -14,15 +14,11 @@ describe('Issue #355', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/issue355.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: false, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); - + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: false, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('does not break on run', () => { diff --git a/test/functional-tests/issues/issue419.spec.ts b/test/functional-tests/issues/issue419.spec.ts index 2afb5295..2222603a 100644 --- a/test/functional-tests/issues/issue419.spec.ts +++ b/test/functional-tests/issues/issue419.spec.ts @@ -15,13 +15,10 @@ describe('Issue #419', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/issue419.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - compact: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + compact: true + }).getObfuscatedCode(); }); it('does not break on obfuscating', () => { diff --git a/test/functional-tests/issues/issue424.spec.ts b/test/functional-tests/issues/issue424.spec.ts index 1cba1f4b..7f0a51a1 100644 --- a/test/functional-tests/issues/issue424.spec.ts +++ b/test/functional-tests/issues/issue424.spec.ts @@ -13,14 +13,10 @@ describe('Issue #424', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/issue424.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: false - } - ).getObfuscatedCode(); - + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: false + }).getObfuscatedCode(); }); it('does not break on run', () => { diff --git a/test/functional-tests/issues/issue437.spec.ts b/test/functional-tests/issues/issue437.spec.ts index b6144608..04503496 100644 --- a/test/functional-tests/issues/issue437.spec.ts +++ b/test/functional-tests/issues/issue437.spec.ts @@ -13,13 +13,11 @@ describe('Issue #437', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/issue437.js'); - testFunc = () => JavaScriptObfuscator.obfuscate( - code, - { + testFunc = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, transformObjectKeys: true - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('does not break on obfuscating', () => { diff --git a/test/functional-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts b/test/functional-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts index 07761c9f..6a12c7ab 100644 --- a/test/functional-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts +++ b/test/functional-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts @@ -33,17 +33,13 @@ import { readFileAsString } from '../../helpers/readFileAsString'; describe('JavaScriptObfuscator', () => { describe('obfuscate', () => { describe('correct source code', () => { - let obfuscatedCode: string, - sourceMap: string; + let obfuscatedCode: string, sourceMap: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); sourceMap = obfuscationResult.getSourceMap(); @@ -65,9 +61,7 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/empty-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code).getObfuscatedCode(); }); it('should return an empty obfuscated code', () => { @@ -81,13 +75,10 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/comments-only.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - controlFlowFlattening: true, - deadCodeInjection: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + controlFlowFlattening: true, + deadCodeInjection: true + }).getObfuscatedCode(); }); it('should return an empty obfuscated code', () => { @@ -99,9 +90,7 @@ describe('JavaScriptObfuscator', () => { let obfuscatedCode: string; beforeEach(() => { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - 1 as unknown as string - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(1 as unknown as string).getObfuscatedCode(); }); it('should return an empty obfuscated code', () => { @@ -112,27 +101,19 @@ describe('JavaScriptObfuscator', () => { describe('`sourceMap` option is `true`', () => { describe('`sourceMapMode` is `separate`', () => { - let code: string, - obfuscatedCode: string, - sourceMap: ISourceMap, - resolvedSources: string; + let code: string, obfuscatedCode: string, sourceMap: ISourceMap, resolvedSources: string; beforeEach((done) => { code = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - sourceMap: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + sourceMap: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); sourceMap = JSON.parse(obfuscationResult.getSourceMap()); resolveSources(sourceMap, '/', fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); }); @@ -161,28 +142,20 @@ describe('JavaScriptObfuscator', () => { describe('`sourceMapMode` is `inline`', () => { const regExp: RegExp = /sourceMappingURL=data:application\/json;base64/; - let code: string, - obfuscatedCode: string, - sourceMap: ISourceMap, - resolvedSources: string; + let code: string, obfuscatedCode: string, sourceMap: ISourceMap, resolvedSources: string; beforeEach((done) => { code = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - sourceMap: true, - sourceMapMode: SourceMapMode.Inline - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + sourceMap: true, + sourceMapMode: SourceMapMode.Inline + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); sourceMap = JSON.parse(obfuscationResult.getSourceMap()); resolveSources(sourceMap, '/', fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); }); @@ -221,12 +194,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/empty-input.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - sourceMap: true - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + sourceMap: true + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); @@ -256,28 +226,21 @@ describe('JavaScriptObfuscator', () => { describe('`sourceMapSourceMode` is set', () => { describe('`sourcesContent` value', () => { - let code: string, - obfuscatedCode: string, - sourceMap: ISourceMap, - resolvedSources: string; + let code: string, obfuscatedCode: string, sourceMap: ISourceMap, resolvedSources: string; beforeEach((done) => { code = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - sourceMap: true, - sourceMapSourcesMode: SourceMapSourcesMode.SourcesContent - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + sourceMap: true, + sourceMapSourcesMode: SourceMapSourcesMode.SourcesContent + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); sourceMap = JSON.parse(obfuscationResult.getSourceMap()); resolveSources(sourceMap, '/', fs.readFile, (error, result) => { - resolvedSources = typeof result.sourcesContent[0] === 'string' - ? result.sourcesContent[0] - : ''; + resolvedSources = + typeof result.sourcesContent[0] === 'string' ? result.sourcesContent[0] : ''; done(); }); }); @@ -313,21 +276,16 @@ describe('JavaScriptObfuscator', () => { describe('`sources` value', () => { describe('`inputFileName` option is set', () => { - let code: string, - obfuscatedCode: string, - sourceMap: ISourceMap; + let code: string, obfuscatedCode: string, sourceMap: ISourceMap; beforeEach(() => { code = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - inputFileName: 'someFile.js', - sourceMap: true, - sourceMapSourcesMode: SourceMapSourcesMode.Sources - } - ); + const obfuscationResult: IObfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + inputFileName: 'someFile.js', + sourceMap: true, + sourceMapSourcesMode: SourceMapSourcesMode.Sources + }); obfuscatedCode = obfuscationResult.getObfuscatedCode(); sourceMap = JSON.parse(obfuscationResult.getSourceMap()); @@ -352,21 +310,19 @@ describe('JavaScriptObfuscator', () => { it('should define placeholder `sources` field for source map', () => { assert.deepEqual(sourceMap.sources, ['someFile.js']); }); - }) + }); describe('`inputFileName` option is not set', () => { let testFunc: () => IObfuscationResult; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - testFunc = () => JavaScriptObfuscator.obfuscate( - code, - { + testFunc = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, sourceMap: true, sourceMapSourcesMode: SourceMapSourcesMode.Sources - } - ); + }); }); it('should throw an error', () => { @@ -386,12 +342,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should return correct obfuscated code', () => { @@ -407,13 +360,10 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('should return correct obfuscated code', () => { @@ -429,14 +379,11 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifiersPrefix: 'foo' - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifiersPrefix: 'foo' + }).getObfuscatedCode(); }); it('should return correct obfuscated code', () => { @@ -447,9 +394,9 @@ describe('JavaScriptObfuscator', () => { describe('Variant #4: with `stringArray`, `renameGlobals` and `identifiersPrefix` options', () => { const stringArrayRegExp: RegExp = new RegExp( 'function foo_0x([a-f0-9]){4} *\\(\\) *{' + - 'var _0x([a-f0-9]){4,6} *= *\\[\'abc\'];.*' + + "var _0x([a-f0-9]){4,6} *= *\\['abc'];.*" + 'return foo_0x([a-f0-9]){4}\\(\\); *' + - '}' + '}' ); const stringArrayCallRegExp: RegExp = /var foo_0x(\w){4,6} *= *foo_0x(\w){4}\(0x0\);/; @@ -458,16 +405,13 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifiersPrefix: 'foo', - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifiersPrefix: 'foo', + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should return correct obfuscated code', () => { @@ -488,12 +432,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/block-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should return correct obfuscated code', () => { @@ -513,14 +454,11 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifiers-prefix.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifiersPrefix: 'foo' - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifiersPrefix: 'foo' + }).getObfuscatedCode(); }); it('match #1: should return correct obfuscated code', () => { @@ -550,14 +488,11 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should return correct obfuscated code', () => { @@ -572,9 +507,9 @@ describe('JavaScriptObfuscator', () => { describe('cyrillic literal variable value', () => { const stringArrayCyrillicRegExp: RegExp = new RegExp( 'function _0x(\\w){4} *\\(\\) *{' + - 'var _0x([a-f0-9]){4,6} *= *\\[\'абц\'];.*' + + "var _0x([a-f0-9]){4,6} *= *\\['абц'];.*" + 'return _0x(\\w){4}\\(\\); *' + - '}' + '}' ); const stringArrayCallRegExp: RegExp = /var test *= *_0x(\w){4}\(0x0\);/; @@ -583,14 +518,11 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input-cyrillic.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should return correct obfuscated code', () => { @@ -620,18 +552,12 @@ describe('JavaScriptObfuscator', () => { seed++; } - obfuscatedCode1 = JavaScriptObfuscator.obfuscate( - code, - { - seed: seed - } - ).getObfuscatedCode(); - obfuscatedCode2 = JavaScriptObfuscator.obfuscate( - code, - { - seed: seed - } - ).getObfuscatedCode(); + obfuscatedCode1 = JavaScriptObfuscator.obfuscate(code, { + seed: seed + }).getObfuscatedCode(); + obfuscatedCode2 = JavaScriptObfuscator.obfuscate(code, { + seed: seed + }).getObfuscatedCode(); if (obfuscatedCode1 === obfuscatedCode2) { equalsCount++; @@ -647,22 +573,15 @@ describe('JavaScriptObfuscator', () => { describe('Variant #1: different seed on each run', () => { const code: string = readFileAsString('./test/fixtures/sample.js'); - let obfuscatedCode1: string, - obfuscatedCode2: string; + let obfuscatedCode1: string, obfuscatedCode2: string; beforeEach(() => { - obfuscatedCode1 = JavaScriptObfuscator.obfuscate( - code, - { - seed: 12345 - } - ).getObfuscatedCode(); - obfuscatedCode2 = JavaScriptObfuscator.obfuscate( - code, - { - seed: 12346 - } - ).getObfuscatedCode(); + obfuscatedCode1 = JavaScriptObfuscator.obfuscate(code, { + seed: 12345 + }).getObfuscatedCode(); + obfuscatedCode2 = JavaScriptObfuscator.obfuscate(code, { + seed: 12346 + }).getObfuscatedCode(); }); it('should return different obfuscated code with different `seed` option value', () => { @@ -673,22 +592,15 @@ describe('JavaScriptObfuscator', () => { describe('Variant #2: different seed on each run', () => { const code: string = readFileAsString('./test/fixtures/sample.js'); - let obfuscatedCode1: string, - obfuscatedCode2: string; + let obfuscatedCode1: string, obfuscatedCode2: string; beforeEach(() => { - obfuscatedCode1 = JavaScriptObfuscator.obfuscate( - code, - { - seed: 0 - } - ).getObfuscatedCode(); - obfuscatedCode2 = JavaScriptObfuscator.obfuscate( - code, - { - seed: 0 - } - ).getObfuscatedCode(); + obfuscatedCode1 = JavaScriptObfuscator.obfuscate(code, { + seed: 0 + }).getObfuscatedCode(); + obfuscatedCode2 = JavaScriptObfuscator.obfuscate(code, { + seed: 0 + }).getObfuscatedCode(); }); it('should return different obfuscated code with different `seed` option value', () => { @@ -702,29 +614,22 @@ describe('JavaScriptObfuscator', () => { const regExp: RegExp = new RegExp( 'function _0x(\\w){4} *\\(\\) *{' + - 'var _0x([a-f0-9]){4,6} *= *\\[\'.*\'];.*' + + "var _0x([a-f0-9]){4,6} *= *\\['.*'];.*" + 'return _0x(\\w){4}\\(\\); *' + - '}' + '}' ); - let match1: string, - match2: string; + let match1: string, match2: string; beforeEach(() => { - const obfuscatedCode1: string = JavaScriptObfuscator.obfuscate( - code1, - { - seed: 123, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); - const obfuscatedCode2: string = JavaScriptObfuscator.obfuscate( - code2, - { - seed: 123, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode1: string = JavaScriptObfuscator.obfuscate(code1, { + seed: 123, + stringArrayThreshold: 1 + }).getObfuscatedCode(); + const obfuscatedCode2: string = JavaScriptObfuscator.obfuscate(code2, { + seed: 123, + stringArrayThreshold: 1 + }).getObfuscatedCode(); match1 = getRegExpMatch(obfuscatedCode1, regExp); match2 = getRegExpMatch(obfuscatedCode2, regExp); @@ -747,12 +652,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-single-rest-element.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should not break on `ObjectPattern` with single `RestElement`', () => { @@ -769,14 +671,13 @@ describe('JavaScriptObfuscator', () => { let obfuscatedCode: string; beforeEach(() => { - const code: string = readFileAsString(__dirname + '/fixtures/precedence-of-sequence-expression-in-computed-property.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/precedence-of-sequence-expression-in-computed-property.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should generate a valid js code', () => { @@ -792,12 +693,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/new-target.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should keep new.target MetaProperty', () => { @@ -813,12 +711,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/import-meta.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support `import.meta`', () => { @@ -837,12 +732,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/export-all-named-support.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support `export * as` syntax', () => { @@ -861,12 +753,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/exponentiation-operator-precedence.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support exponentiation operator', () => { @@ -882,12 +771,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/bigint-support.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support BigInt', () => { @@ -898,9 +784,9 @@ describe('JavaScriptObfuscator', () => { describe('Optional chaining support', () => { const regExp: RegExp = new RegExp( 'const _0x(\\w){4,6} *= *{ *' + - '\'bar\': *\\(\\) *=> *{} *' + - '}; *' + - '_0x(\\w){4,6}\\?\\.\\[\'bar\']\\?\\.\\(\\);' + "'bar': *\\(\\) *=> *{} *" + + '}; *' + + "_0x(\\w){4,6}\\?\\.\\['bar']\\?\\.\\(\\);" ); let obfuscatedCode: string; @@ -908,12 +794,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/optional-chaining-support.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support optional chaining', () => { @@ -929,12 +812,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/nullish-coalescing-support.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support nullish coalescing operator', () => { @@ -950,12 +830,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/numeric-separators-support.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support numeric separators', () => { @@ -971,12 +848,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/top-level-await-support.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should support top-level await', () => { @@ -987,15 +861,15 @@ describe('JavaScriptObfuscator', () => { describe('Class static block support', () => { const regExp: RegExp = new RegExp( 'let _0x(\\w){4,6} *= *0x1; *' + - 'class _0x(\\w){4,6} *{ *' + - 'static *\\[\'_0x(\\w){4,6}\']; *' + + 'class _0x(\\w){4,6} *{ *' + + "static *\\['_0x(\\w){4,6}']; *" + 'static *{ *' + - 'let _0x(\\w){4,6} *= *0x2; *' + - '_0x(\\w){4,6}\\[\'_0x(\\w){4,6}\'] *= *0x3; *' + - '_0x(\\w){4,6} *= *0x4; *' + - '_0x(\\w){4,6} *= *0x5; *' + + 'let _0x(\\w){4,6} *= *0x2; *' + + "_0x(\\w){4,6}\\['_0x(\\w){4,6}'] *= *0x3; *" + + '_0x(\\w){4,6} *= *0x4; *' + + '_0x(\\w){4,6} *= *0x5; *' + '} *' + - '}' + '}' ); let obfuscatedCode: string; @@ -1003,14 +877,11 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/class-static-block-support-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - renameProperties: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + renameProperties: true + }).getObfuscatedCode(); console.log(obfuscatedCode); }); @@ -1022,12 +893,7 @@ describe('JavaScriptObfuscator', () => { describe('Private identifiers support', () => { const regExp: RegExp = new RegExp( - 'class Foo *{ *' + - '#bar *= *0x1; *' + - '\\[\'method\'] *\\(\\) *{ *' + - 'this\.#bar *= *0x2;' + - '} *' + - '}' + 'class Foo *{ *' + '#bar *= *0x1; *' + "\\['method'] *\\(\\) *{ *" + 'this\.#bar *= *0x2;' + '} *' + '}' ); let obfuscatedCode: string; @@ -1035,13 +901,10 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/private-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true + }).getObfuscatedCode(); }); it('should support private identifiers', () => { @@ -1058,18 +921,15 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-class-expression.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should not throw', () => { assert.match(obfuscatedCode, regExp); }); - }); + }); describe('mangled identifier names generator', () => { const regExp: RegExp = /var c *= *0x1/; @@ -1079,15 +939,12 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/mangle.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should mangle obfuscated code', () => { @@ -1103,12 +960,9 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/mangle.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - identifierNamesGenerator: IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + identifierNamesGenerator: IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('should mangle obfuscated code', () => { @@ -1125,14 +979,11 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/dictionary-identifiers.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, - identifiersDictionary: ['a', 'b', 'c'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, + identifiersDictionary: ['a', 'b', 'c'] + }).getObfuscatedCode(); }); it('Match #1: should generate identifier based on the dictionary', () => { @@ -1199,20 +1050,17 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-names-cache-1.js'); - identifierNamesCache = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - baz: 'baz_value_from_cache' - }, - propertyIdentifiers: {} + identifierNamesCache = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + baz: 'baz_value_from_cache' }, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getIdentifierNamesCache(); + propertyIdentifiers: {} + }, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getIdentifierNamesCache(); }); it('Match #1: should correctly generate identifier names cache', () => { @@ -1234,18 +1082,15 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-names-cache-1.js'); - identifierNamesCache = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - }, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getIdentifierNamesCache(); + identifierNamesCache = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} + }, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getIdentifierNamesCache(); }); it('Match #1: should correctly generate identifier names cache', () => { @@ -1264,18 +1109,15 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-names-cache-2.js'); - identifierNamesCache = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - }, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getIdentifierNamesCache(); + identifierNamesCache = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} + }, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getIdentifierNamesCache(); }); it('Match #1: should correctly generate identifier names cache', () => { @@ -1291,15 +1133,12 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-names-cache-1.js'); - identifierNamesCache = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: null, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getIdentifierNamesCache(); + identifierNamesCache = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: null, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getIdentifierNamesCache(); }); it('Match #1: should correctly generate identifier names cache', () => { @@ -1318,40 +1157,34 @@ describe('JavaScriptObfuscator', () => { beforeEach(() => { const code: string = buildLargeCode(expectedValue); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - compact: true, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - disableConsoleOutput: false, - numbersToExpressions: true, - simplify: true, - renameProperties: true, - stringArrayRotate: true, - stringArray: true, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ], - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber, - StringArrayIndexesType.HexadecimalNumericString - ], - stringArrayIndexShift: true, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 10, - stringArrayWrappersParametersMaxCount: 5, - stringArrayWrappersType: StringArrayWrappersType.Function, - stringArrayThreshold: 1, - transformObjectKeys: true, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + compact: true, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + disableConsoleOutput: false, + numbersToExpressions: true, + simplify: true, + renameProperties: true, + stringArrayRotate: true, + stringArray: true, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.Base64, StringArrayEncoding.Rc4], + stringArrayIndexesType: [ + StringArrayIndexesType.HexadecimalNumber, + StringArrayIndexesType.HexadecimalNumericString + ], + stringArrayIndexShift: true, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 10, + stringArrayWrappersParametersMaxCount: 5, + stringArrayWrappersType: StringArrayWrappersType.Function, + stringArrayThreshold: 1, + transformObjectKeys: true, + unicodeEscapeSequence: false + }).getObfuscatedCode(); result = eval(obfuscatedCode); }); @@ -1372,26 +1205,23 @@ describe('JavaScriptObfuscator', () => { const code: string = readFileAsString(__dirname + '/fixtures/eval-hello-world.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - compact: false, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - disableConsoleOutput: true, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - renameProperties: true, - simplify: false, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 1, - stringArrayWrappersType: StringArrayWrappersType.Variable - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + compact: false, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + disableConsoleOutput: true, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + renameProperties: true, + simplify: false, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 1, + stringArrayWrappersType: StringArrayWrappersType.Variable + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -1413,25 +1243,25 @@ describe('JavaScriptObfuscator', () => { const samplesCount: number = 30; let collisionError: string | null = null; - let obfuscateFunc: (identifierNamesGenerator: TTypeFromEnum) => IObfuscationResult; + let obfuscateFunc: ( + identifierNamesGenerator: TTypeFromEnum + ) => IObfuscationResult; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/custom-nodes-identifier-names-collision.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/custom-nodes-identifier-names-collision.js' + ); obfuscateFunc = (identifierNamesGenerator: TTypeFromEnum) => { - return JavaScriptObfuscator.obfuscate( - code, - { - identifierNamesGenerator, - compact: false, - renameGlobals: true, - identifiersDictionary: ['foo', 'bar', 'baz', 'bark', 'hawk', 'foozmos', 'cow', 'chikago'], - stringArray: true - } - ); + return JavaScriptObfuscator.obfuscate(code, { + identifierNamesGenerator, + compact: false, + renameGlobals: true, + identifiersDictionary: ['foo', 'bar', 'baz', 'bark', 'hawk', 'foozmos', 'cow', 'chikago'], + stringArray: true + }); }; - [ IdentifierNamesGenerator.DictionaryIdentifierNamesGenerator, IdentifierNamesGenerator.MangledIdentifierNamesGenerator @@ -1480,14 +1310,11 @@ describe('JavaScriptObfuscator', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ...baseParams, - stringArrayEncoding: [StringArrayEncoding.Rc4] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ...baseParams, + stringArrayEncoding: [StringArrayEncoding.Rc4] + }).getObfuscatedCode(); }); it('does not break on run', () => { @@ -1500,17 +1327,15 @@ describe('JavaScriptObfuscator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); - - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ...baseParams, - stringArrayEncoding: [StringArrayEncoding.Rc4] - } - ).getObfuscatedCode(); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-const.js' + ); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ...baseParams, + stringArrayEncoding: [StringArrayEncoding.Rc4] + }).getObfuscatedCode(); }); it('does not break on run', () => { @@ -1522,16 +1347,15 @@ describe('JavaScriptObfuscator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-const.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ...baseParams, - stringArrayEncoding: [StringArrayEncoding.Rc4] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ...baseParams, + stringArrayEncoding: [StringArrayEncoding.Rc4] + }).getObfuscatedCode(); }); it('does not break on run', () => { @@ -1545,17 +1369,15 @@ describe('JavaScriptObfuscator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ...baseParams, - stringArrayEncoding: [StringArrayEncoding.Rc4] - } - ).getObfuscatedCode(); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-let.js' + ); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ...baseParams, + stringArrayEncoding: [StringArrayEncoding.Rc4] + }).getObfuscatedCode(); }); it('does not break on run', () => { @@ -1567,17 +1389,15 @@ describe('JavaScriptObfuscator', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ...baseParams, - stringArrayEncoding: [StringArrayEncoding.Base64] - } - ).getObfuscatedCode(); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-let.js' + ); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ...baseParams, + stringArrayEncoding: [StringArrayEncoding.Base64] + }).getObfuscatedCode(); }); it('does not break on run', () => { @@ -1627,13 +1447,11 @@ describe('JavaScriptObfuscator', () => { let testFunc: () => TDictionary; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscateMultiple( - 'foo' as any, - { + testFunc = () => + JavaScriptObfuscator.obfuscateMultiple('foo' as any, { ...NO_ADDITIONAL_NODES_PRESET, renameGlobals: true - } - ); + }); }); it('Should throw an error if source codes object is not a plain object', () => { diff --git a/test/functional-tests/node-transformers/control-flow-transformers/block-statement-control-flow-transformer/BlockStatementControlFlowTransformer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/block-statement-control-flow-transformer/BlockStatementControlFlowTransformer.spec.ts index 5eea8be8..de0fb56a 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/block-statement-control-flow-transformer/BlockStatementControlFlowTransformer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/block-statement-control-flow-transformer/BlockStatementControlFlowTransformer.spec.ts @@ -25,17 +25,14 @@ describe('BlockStatementControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - describe('`console.log` statements', ()=> { + describe('`console.log` statements', () => { const statementRegExp1: RegExp = getStatementRegExp('0x1'); const statementRegExp2: RegExp = getStatementRegExp('0x2'); const statementRegExp3: RegExp = getStatementRegExp('0x3'); @@ -84,7 +81,8 @@ describe('BlockStatementControlFlowTransformer', function () { }); describe('switch-case map', () => { - const switchCaseMapVariableRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\)/; + const switchCaseMapVariableRegExp: RegExp = + /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\)/; const switchCaseMapIndexVariableRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *0x0;/; const switchCaseMapStringRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *\{'.*' *: *'(.*)'\};/; const expectedSwitchCasesSequence: string[] = ['0', '1', '2', '3', '4']; @@ -117,18 +115,15 @@ describe('BlockStatementControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + unicodeEscapeSequence: false + }).getObfuscatedCode(); }); - describe('`console.log` statements', ()=> { + describe('`console.log` statements', () => { const statementRegExp1: RegExp = getStatementRegExp('0x1'); const statementRegExp2: RegExp = getStatementRegExp('0x2'); const statementRegExp3: RegExp = getStatementRegExp('0x3'); @@ -177,7 +172,8 @@ describe('BlockStatementControlFlowTransformer', function () { }); describe('switch-case map', () => { - const switchCaseMapVariableRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\)/; + const switchCaseMapVariableRegExp: RegExp = + /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\)/; const switchCaseMapStringRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *\{'.*' *: *'(.*)'\};/; const expectedSwitchCasesSequence: string[] = ['0', '1', '2', '3', '4']; @@ -207,132 +203,119 @@ describe('BlockStatementControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/one-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #4: block statement contain variable declaration with `const` kind', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *const _0x([a-f0-9]){4,6} *= *0x1; *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *const _0x([a-f0-9]){4,6} *= *0x1; *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/const-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #5: block statement contain variable declaration with `let` kind', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *let _0x([a-f0-9]){4,6} *= *0x1; *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *let _0x([a-f0-9]){4,6} *= *0x1; *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/let-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #6: block statement contain break statement #1', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *break; *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *break; *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/break-statement-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #7: block statement contain break statement #2', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *\{ *break; *\} *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *\{ *break; *\} *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/break-statement-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #8: block statement contain break statement #3', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *break; *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *break; *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/break-statement-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); @@ -342,20 +325,18 @@ describe('BlockStatementControlFlowTransformer', function () { const switchCaseLengthRegExp: RegExp = /case *'[0-5]': *console\['log'\]\(0x[0-6]\);/g; const expectedSwitchCaseLength: number = 5; - let obfuscatedCode: string, - switchCaseLength: number; + let obfuscatedCode: string, switchCaseLength: number; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/break-statement-inside-while-statement-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/break-statement-inside-while-statement-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); switchCaseLength = obfuscatedCode.match(switchCaseLengthRegExp)!.length; }); @@ -373,20 +354,18 @@ describe('BlockStatementControlFlowTransformer', function () { const switchCaseLengthRegExp: RegExp = /case *'[0-5]': *console\['log'\]\(0x[0-6]\);/g; const expectedSwitchCaseLength: number = 5; - let obfuscatedCode: string, - switchCaseLength: number; + let obfuscatedCode: string, switchCaseLength: number; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/break-statement-inside-while-statement-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/break-statement-inside-while-statement-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); switchCaseLength = obfuscatedCode.match(switchCaseLengthRegExp)!.length; }); @@ -400,70 +379,64 @@ describe('BlockStatementControlFlowTransformer', function () { }); describe('Variant #11: block statement contain continue statement #1', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *continue; *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *continue; *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/continue-statement-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #12: block statement contain continue statement #2', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *\{ *continue; *\} *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *\{ *continue; *\} *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/continue-statement-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #13: block statement contain continue statement #3', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *continue; *console\['log'\]\(0x1\);/; + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *while *\(!!\[\]\) *\{ *if *\(!!\[\]\) *continue; *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/continue-statement-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); @@ -473,20 +446,18 @@ describe('BlockStatementControlFlowTransformer', function () { const switchCaseLengthRegExp: RegExp = /case *'[0-5]': *console\['log'\]\(0x[0-6]\);/g; const expectedSwitchCaseLength: number = 5; - let obfuscatedCode: string, - switchCaseLength: number; + let obfuscatedCode: string, switchCaseLength: number; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/continue-statement-inside-while-statement-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/continue-statement-inside-while-statement-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); switchCaseLength = obfuscatedCode.match(switchCaseLengthRegExp)!.length; }); @@ -504,20 +475,18 @@ describe('BlockStatementControlFlowTransformer', function () { const switchCaseLengthRegExp: RegExp = /case *'[0-5]': *console\['log'\]\(0x[0-6]\);/g; const expectedSwitchCaseLength: number = 5; - let obfuscatedCode: string, - switchCaseLength: number; + let obfuscatedCode: string, switchCaseLength: number; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/continue-statement-inside-while-statement-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/continue-statement-inside-while-statement-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); switchCaseLength = obfuscatedCode.match(switchCaseLengthRegExp)!.length; }); @@ -531,47 +500,43 @@ describe('BlockStatementControlFlowTransformer', function () { }); describe('Variant #16: block statement contain function declaration', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *\{ *function *_0x([a-f0-9]){4,6} *\( *\) *\{ *\} *console\['log'\]\(0x1\);/ + const statementRegExp: RegExp = + /^\(function *\( *\) *\{ *function *_0x([a-f0-9]){4,6} *\( *\) *\{ *\} *console\['log'\]\(0x1\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); describe('Variant #17: block statement contain class declaration', () => { - const statementRegExp: RegExp = /^\(function *\( *\) *{ * *class *_0x([a-f0-9]){4,6} *{.*?} *}.*class *_0x([a-f0-9]){4,6} *{.*?} *}.*class *_0x([a-f0-9]){4,6} *{.*?} *}/; + const statementRegExp: RegExp = + /^\(function *\( *\) *{ * *class *_0x([a-f0-9]){4,6} *{.*?} *}.*class *_0x([a-f0-9]){4,6} *{.*?} *}.*class *_0x([a-f0-9]){4,6} *{.*?} *}/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/class-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t transform block statement', () => { + it("shouldn't transform block statement", () => { assert.match(obfuscatedCode, statementRegExp); }); }); @@ -585,27 +550,19 @@ describe('BlockStatementControlFlowTransformer', function () { const regExp1: RegExp = /switch *\(_0x([a-f0-9]){4,6}\[_0x([a-f0-9]){4,6}\+\+\]\) *\{/g; const regExp2: RegExp = /\(function *\( *\) *\{ *console\['log'\]\(0x1\);/g; - let transformedStatementPercentage: number, - untouchedStatementPercentage: number; + let transformedStatementPercentage: number, untouchedStatementPercentage: number; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code.repeat(samples), - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: controlFlowFlatteningThreshold, - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code.repeat(samples), { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: controlFlowFlatteningThreshold + }).getObfuscatedCode(); - const transformedStatementMatchesLength: number = obfuscatedCode - .match(regExp1)! - .length; - const untouchedStatementMatchesLength: number = obfuscatedCode - .match(regExp2)! - .length; + const transformedStatementMatchesLength: number = obfuscatedCode.match(regExp1)!.length; + const untouchedStatementMatchesLength: number = obfuscatedCode.match(regExp2)!.length; transformedStatementPercentage = transformedStatementMatchesLength / samples; untouchedStatementPercentage = untouchedStatementMatchesLength / samples; @@ -626,20 +583,16 @@ describe('BlockStatementControlFlowTransformer', function () { const returnStatementRegExp: RegExp = /case *'[0-5]': *return; *(case|})/; const expectedSwitchCaseLength: number = 5; - let obfuscatedCode: string, - switchCaseLength: number; + let obfuscatedCode: string, switchCaseLength: number; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/no-unreachable-code-warning.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); switchCaseLength = obfuscatedCode.match(switchCaseLengthRegExp)!.length; }); @@ -663,18 +616,16 @@ describe('BlockStatementControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); describe('switch-case map', () => { - const switchCaseMapVariableRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\);/; + const switchCaseMapVariableRegExp: RegExp = + /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\);/; const switchCaseMapIndexVariableRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *0x0;/; const switchCaseMapStringRegExp: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *\{'.*' *: *'(.*)'\};/; const expectedSwitchCasesSequence: string[] = ['0', '1', '2', '3', '4']; @@ -705,20 +656,20 @@ describe('BlockStatementControlFlowTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-const.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); describe('switch-case map', () => { - const switchCaseMapVariableRegExp: RegExp = /const _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\);/; + const switchCaseMapVariableRegExp: RegExp = + /const _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\);/; const switchCaseMapIndexVariableRegExp: RegExp = /let _0x(?:[a-f0-9]){4,6} *= *0x0;/; const switchCaseMapStringRegExp: RegExp = /const _0x(?:[a-f0-9]){4,6} *= *\{'.*' *: *'(.*)'\};/; const expectedSwitchCasesSequence: string[] = ['0', '1', '2', '3', '4']; @@ -751,18 +702,16 @@ describe('BlockStatementControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); describe('switch-case map', () => { - const switchCaseMapVariableRegExp: RegExp = /const _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\)/; + const switchCaseMapVariableRegExp: RegExp = + /const _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6}\['.*'\]\['split'\]\('\|'\)/; const switchCaseMapIndexVariableRegExp: RegExp = /let _0x(?:[a-f0-9]){4,6} *= *0x0;/; const switchCaseMapStringRegExp: RegExp = /const _0x(?:[a-f0-9]){4,6} *= *\{'.*' *: *'(.*)'\};/; const expectedSwitchCasesSequence: string[] = ['0', '1', '2', '3', '4']; diff --git a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/binary-expression-control-flow-replacer/BinaryExpressionControlFlowReplacer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/binary-expression-control-flow-replacer/BinaryExpressionControlFlowReplacer.spec.ts index 1886150d..b6675367 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/binary-expression-control-flow-replacer/BinaryExpressionControlFlowReplacer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/binary-expression-control-flow-replacer/BinaryExpressionControlFlowReplacer.spec.ts @@ -22,14 +22,11 @@ describe('BinaryExpressionControlFlowReplacer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace binary expression node with call to control flow storage node', () => { @@ -65,14 +62,11 @@ describe('BinaryExpressionControlFlowReplacer', function () { equalsValue: number = 0; for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); firstMatchArray = obfuscatedCode.match(controlFlowStorageCallRegExp1); secondMatchArray = obfuscatedCode.match(controlFlowStorageCallRegExp2); diff --git a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/call-expression-control-flow-replacer/CallExpressionControlFlowReplacer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/call-expression-control-flow-replacer/CallExpressionControlFlowReplacer.spec.ts index a1d0699d..ea3b91a2 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/call-expression-control-flow-replacer/CallExpressionControlFlowReplacer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/call-expression-control-flow-replacer/CallExpressionControlFlowReplacer.spec.ts @@ -22,14 +22,11 @@ describe('CallExpressionControlFlowReplacer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace call expression node with call to control flow storage node', () => { @@ -65,14 +62,11 @@ describe('CallExpressionControlFlowReplacer', function () { equalsValue: number = 0; for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); firstMatchArray = obfuscatedCode.match(controlFlowStorageCallRegExp1); secondMatchArray = obfuscatedCode.match(controlFlowStorageCallRegExp2); @@ -104,26 +98,21 @@ describe('CallExpressionControlFlowReplacer', function () { }); describe('Variant #3 - call expression callee is member expression node', () => { - const regExp: RegExp = new RegExp( - `var ${variableMatch} *= *${variableMatch}\\['sum'\\]\\(0x1, *0x2\\);` - ); + const regExp: RegExp = new RegExp(`var ${variableMatch} *= *${variableMatch}\\['sum'\\]\\(0x1, *0x2\\);`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t replace call expression node with call to control flow storage node', () => { + it("shouldn't replace call expression node with call to control flow storage node", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -132,25 +121,24 @@ describe('CallExpressionControlFlowReplacer', function () { const controlFlowStorageCallRegExp: RegExp = new RegExp( `${variableMatch}\\['\\w{5}']\\(${variableMatch}, *\\.\\.\\.${variableMatch}, *${variableMatch}\\);` ); - const controlFlowStorageNodeRegExp: RegExp = new RegExp(`` + - `'\\w{5}' *: *function *\\(${variableMatch}, *\.\.\.${variableMatch}\\) *\\{` + + const controlFlowStorageNodeRegExp: RegExp = new RegExp( + `` + + `'\\w{5}' *: *function *\\(${variableMatch}, *\.\.\.${variableMatch}\\) *\\{` + `return *${variableMatch}\\(\.\.\.${variableMatch}\\);` + - `\\}` + - ``); + `\\}` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/rest-as-start-call-argument.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace call expression node with call to control flow storage node', () => { @@ -166,25 +154,24 @@ describe('CallExpressionControlFlowReplacer', function () { const controlFlowStorageCallRegExp: RegExp = new RegExp( `${variableMatch}\\['\\w{5}']\\(${variableMatch}, *${variableMatch}, *\\.\\.\\.${variableMatch}, *${variableMatch}\\);` ); - const controlFlowStorageNodeRegExp: RegExp = new RegExp(`` + - `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}, *\.\.\.${variableMatch}\\) *\\{` + + const controlFlowStorageNodeRegExp: RegExp = new RegExp( + `` + + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}, *\.\.\.${variableMatch}\\) *\\{` + `return *${variableMatch}\\(${variableMatch}, *\.\.\.${variableMatch}\\);` + - `\\}` + - ``); + `\\}` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/rest-as-middle-call-argument.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace call expression node with call to control flow storage node', () => { @@ -200,25 +187,24 @@ describe('CallExpressionControlFlowReplacer', function () { const controlFlowStorageCallRegExp: RegExp = new RegExp( `${variableMatch}\\['\\w{5}']\\(${variableMatch}, *${variableMatch}, *\\.\\.\\.${variableMatch}\\);` ); - const controlFlowStorageNodeRegExp: RegExp = new RegExp(`` + - `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}, *\.\.\.${variableMatch}\\) *\\{` + - `return *${variableMatch}\\(${variableMatch}, *\.\.\.${variableMatch}\\);` + - `\\}` + - ``); + const controlFlowStorageNodeRegExp: RegExp = new RegExp( + `` + + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}, *\.\.\.${variableMatch}\\) *\\{` + + `return *${variableMatch}\\(${variableMatch}, *\.\.\.${variableMatch}\\);` + + `\\}` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/rest-as-last-call-argument.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace call expression node with call to control flow storage node', () => { @@ -232,36 +218,35 @@ describe('CallExpressionControlFlowReplacer', function () { describe('Variant #7 - keep optional chaining operator', () => { const controlFlowStorageCallRegExp: RegExp = new RegExp( - `${variableMatch}\\['\\w{5}']\\(${variableMatch}, *0x1, *0x2\\);` + `${variableMatch}\\['\\w{5}']\\(${variableMatch}, *0x1, *0x2\\);` ); - const controlFlowStorageNodeRegExp: RegExp = new RegExp(`` + - `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}, *${variableMatch}\\) *\\{` + + const controlFlowStorageNodeRegExp: RegExp = new RegExp( + `` + + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}, *${variableMatch}\\) *\\{` + `return *${variableMatch}\\?\\.\\(${variableMatch}, *${variableMatch}\\);` + - `\\}` + - ``); + `\\}` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/optional-chaining-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace call expression node with call to control flow storage node', () => { - assert.match(obfuscatedCode, controlFlowStorageCallRegExp); + assert.match(obfuscatedCode, controlFlowStorageCallRegExp); }); it('should wrap call expression into chain expression', () => { - assert.match(obfuscatedCode, controlFlowStorageNodeRegExp); + assert.match(obfuscatedCode, controlFlowStorageNodeRegExp); }); }); - }); + }); }); diff --git a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/logical-expression-control-flow-replacer/LogicalExpressionControlFlowReplacer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/logical-expression-control-flow-replacer/LogicalExpressionControlFlowReplacer.spec.ts index 4ad5ccd5..91589112 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/logical-expression-control-flow-replacer/LogicalExpressionControlFlowReplacer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/logical-expression-control-flow-replacer/LogicalExpressionControlFlowReplacer.spec.ts @@ -22,14 +22,11 @@ describe('LogicalExpressionControlFlowReplacer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace logical expression node with call to control flow storage node', () => { @@ -65,14 +62,11 @@ describe('LogicalExpressionControlFlowReplacer', function () { equalsValue: number = 0; for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); firstMatchArray = obfuscatedCode.match(controlFlowStorageCallRegExp1); secondMatchArray = obfuscatedCode.match(controlFlowStorageCallRegExp2); @@ -113,14 +107,11 @@ describe('LogicalExpressionControlFlowReplacer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should replace logical unary expression with call to control flow storage node', () => { @@ -138,17 +129,14 @@ describe('LogicalExpressionControlFlowReplacer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prohibited-nodes.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: .1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 0.1 + }).getObfuscatedCode(); }); - it('shouldn\'t replace prohibited expression nodes', () => { + it("shouldn't replace prohibited expression nodes", () => { assert.match(obfuscatedCode, regExp); }); }); diff --git a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/string-litertal-control-flow-replacer/StringLiteralControlFlowReplacer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/string-litertal-control-flow-replacer/StringLiteralControlFlowReplacer.spec.ts index 4ea956aa..6a7aa4e5 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/string-litertal-control-flow-replacer/StringLiteralControlFlowReplacer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/control-flow-replacers/string-litertal-control-flow-replacer/StringLiteralControlFlowReplacer.spec.ts @@ -12,7 +12,6 @@ describe('StringLiteralControlFlowReplacer', () => { const variableMatch: string = '_0x([a-f0-9]){4,6}'; describe('Variant #1 - base behavior', () => { - const controlFlowStorageStringLiteralRegExp: RegExp = new RegExp( `var ${variableMatch} *= *\\{'\\w{5}' *: *'test'\\};` ); @@ -25,14 +24,11 @@ describe('StringLiteralControlFlowReplacer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should add string literal node as property of control flow storage node', () => { @@ -51,20 +47,19 @@ describe('StringLiteralControlFlowReplacer', () => { let storageCallsMatchesCount: number; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/same-storage-key-for-same-string-values.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/same-storage-key-for-same-string-values.js' + ); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - compact: false, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + compact: false, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); const storageKeyMatch = getRegExpMatch(obfuscatedCode, storageKeyRegExp); - const storageCallsRegExp = new RegExp(`${variableMatch}\\[\'${storageKeyMatch}\']`, 'g') + const storageCallsRegExp = new RegExp(`${variableMatch}\\[\'${storageKeyMatch}\']`, 'g'); storageCallsMatchesCount = obfuscatedCode.match(storageCallsRegExp)?.length ?? 0; }); diff --git a/test/functional-tests/node-transformers/control-flow-transformers/function-control-flow-transformer/FunctionControlFlowTransformer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/function-control-flow-transformer/FunctionControlFlowTransformer.spec.ts index 55dc0b45..539e9a39 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/function-control-flow-transformer/FunctionControlFlowTransformer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/function-control-flow-transformer/FunctionControlFlowTransformer.spec.ts @@ -10,20 +10,22 @@ describe('FunctionControlFlowTransformer', function () { this.timeout(100000); const variableMatch: string = '_0x([a-f0-9]){4,6}'; - const rootControlFlowStorageNodeMatch: string = `` + + const rootControlFlowStorageNodeMatch: string = + `` + `var ${variableMatch} *= *\\{` + - `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + - `return *${variableMatch} *\\+ *${variableMatch};` + - `\\}` + + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + + `return *${variableMatch} *\\+ *${variableMatch};` + + `\\}` + `\\};` + - ``; - const innerControlFlowStorageNodeMatch: string = `` + + ``; + const innerControlFlowStorageNodeMatch: string = + `` + `var ${variableMatch} *= *\\{` + - `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + - `return *${variableMatch}\\['\\w{5}'\\]\\(${variableMatch}, *${variableMatch}\\);` + - `\\}` + + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + + `return *${variableMatch}\\['\\w{5}'\\]\\(${variableMatch}, *${variableMatch}\\);` + + `\\}` + `\\};` + - ``; + ``; describe('transformNode', () => { describe('Variant #1 - single `control flow storage` node with single item', () => { @@ -34,14 +36,11 @@ describe('FunctionControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node to the obfuscated code', () => { @@ -55,10 +54,7 @@ describe('FunctionControlFlowTransformer', function () { const samplesCount: number = 1000; const delta: number = 0.1; - const regExp1: RegExp = new RegExp( - `\\(function\\(\\) *\\{ *${rootControlFlowStorageNodeMatch}`, - 'g' - ); + const regExp1: RegExp = new RegExp(`\\(function\\(\\) *\\{ *${rootControlFlowStorageNodeMatch}`, 'g'); const regExp2: RegExp = new RegExp( `function *${variableMatch} *\\(\\) *\\{ *${innerControlFlowStorageNodeMatch}`, 'g' @@ -73,14 +69,11 @@ describe('FunctionControlFlowTransformer', function () { totalValue: number = 0; for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); if (regExp1.test(obfuscatedCode)) { totalValue += obfuscatedCode.match(regExp1)!.length; @@ -103,12 +96,12 @@ describe('FunctionControlFlowTransformer', function () { const regexp: RegExp = new RegExp( `var ${variableMatch} *= *\\{` + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + - `return *${variableMatch} *\\+ *${variableMatch};` + + `return *${variableMatch} *\\+ *${variableMatch};` + `\\}, *` + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + - `return *${variableMatch} *- *${variableMatch};` + + `return *${variableMatch} *- *${variableMatch};` + `\\}` + - `\\};` + `\\};` ); let obfuscatedCode: string; @@ -116,14 +109,11 @@ describe('FunctionControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-items.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node with multiple items to the obfuscated code', () => { @@ -139,17 +129,14 @@ describe('FunctionControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/root-block-scope-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('should\'t add control flow storage node', () => { + it("should't add control flow storage node", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -161,9 +148,9 @@ describe('FunctionControlFlowTransformer', function () { const regExp: RegExp = new RegExp( `var [a-zA-Z]{6} *= *\\{` + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + - `return *${variableMatch} *\\+ *${variableMatch};` + + `return *${variableMatch} *\\+ *${variableMatch};` + `\\}` + - `\\};` + `\\};` ); const code: string = readFileAsString(__dirname + '/fixtures/root-block-scope-2.js'); @@ -172,15 +159,11 @@ describe('FunctionControlFlowTransformer', function () { before(() => { for (let i = 0; i < samplesCount; i++) { - - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); if (regExp.test(obfuscatedCode)) { totalValue++; @@ -188,7 +171,7 @@ describe('FunctionControlFlowTransformer', function () { } }); - it('should\'t add control flow storage node to the root block scope', () => { + it("should't add control flow storage node to the root block scope", () => { assert.equal(totalValue, expectedValue); }); }); @@ -202,21 +185,18 @@ describe('FunctionControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/zero-threshold.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 0 + }).getObfuscatedCode(); }); - it('shouldn\'t add call to control flow storage node to the obfuscated code', () => { + it("shouldn't add call to control flow storage node to the obfuscated code", () => { assert.match(obfuscatedCode, regexp); }); - it('shouldn\'t add `control flow storage` node to the obfuscated code', () => { + it("shouldn't add `control flow storage` node to the obfuscated code", () => { assert.notMatch(obfuscatedCode, controlFlowStorageRegExp); }); }); @@ -228,16 +208,15 @@ describe('FunctionControlFlowTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/arrow-function-expression-with-body.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/arrow-function-expression-with-body.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node to the obfuscated code', () => { @@ -251,19 +230,18 @@ describe('FunctionControlFlowTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/arrow-function-expression-without-body.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/arrow-function-expression-without-body.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t add `control flow storage` node to the obfuscated code', () => { + it("shouldn't add `control flow storage` node to the obfuscated code", () => { assert.match(obfuscatedCode, regexp); }); }); @@ -278,14 +256,11 @@ describe('FunctionControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should use correct kind of variables for `control flow storage`', () => { @@ -299,16 +274,15 @@ describe('FunctionControlFlowTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-const.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should use correct kind of variables for `control flow storage`', () => { @@ -324,14 +298,11 @@ describe('FunctionControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should use correct kind of variables for `control flow storage`', () => { diff --git a/test/functional-tests/node-transformers/control-flow-transformers/string-array-control-flow-transformer/StringArrayControlFlowTransformer.spec.ts b/test/functional-tests/node-transformers/control-flow-transformers/string-array-control-flow-transformer/StringArrayControlFlowTransformer.spec.ts index 4e65fa2e..c0b801bd 100644 --- a/test/functional-tests/node-transformers/control-flow-transformers/string-array-control-flow-transformer/StringArrayControlFlowTransformer.spec.ts +++ b/test/functional-tests/node-transformers/control-flow-transformers/string-array-control-flow-transformer/StringArrayControlFlowTransformer.spec.ts @@ -1,11 +1,7 @@ import { assert } from 'chai'; -import { - IdentifierNamesGenerator -} from '../../../../../src/enums/generators/identifier-names-generators/IdentifierNamesGenerator'; -import { - StringArrayIndexesType -} from '../../../../../src/enums/node-transformers/string-array-transformers/StringArrayIndexesType'; +import { IdentifierNamesGenerator } from '../../../../../src/enums/generators/identifier-names-generators/IdentifierNamesGenerator'; +import { StringArrayIndexesType } from '../../../../../src/enums/node-transformers/string-array-transformers/StringArrayIndexesType'; import { NO_ADDITIONAL_NODES_PRESET } from '../../../../../src/options/presets/NoCustomNodes'; @@ -22,10 +18,11 @@ describe('StringArrayControlFlowTransformer', function () { describe('Variant #1 - hexadecimal number generator', () => { const stringArrayVariableMatch: string = '_0x([a-f0-9]){4}'; - const controlFlowStorageMatch: string = `var ${hexadecimalVariableMatch} *= *\\{` + + const controlFlowStorageMatch: string = + `var ${hexadecimalVariableMatch} *= *\\{` + `${hexadecimalVariableMatch} *: *0x0, *` + `${hexadecimalVariableMatch} *: *0x1 *` + - `\\};`; + `\\};`; const controlFlowStorageCallMatch: string = `${stringArrayVariableMatch}\\(${hexadecimalVariableMatch}.${hexadecimalVariableMatch}\\)`; describe('Variant #1 - positive cases', () => { @@ -41,17 +38,14 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber], - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber], + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node to the obfuscated code', () => { @@ -68,7 +62,7 @@ describe('StringArrayControlFlowTransformer', function () { `var ${hexadecimalVariableMatch} *= *\\{` + `${hexadecimalVariableMatch} *: *'0x0', *` + `${hexadecimalVariableMatch} *: *'0x1' *` + - `\\};` + `\\};` ); const controlFlowStorageCallRegExp: RegExp = new RegExp( @@ -80,17 +74,14 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString], - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString], + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node to the obfuscated code', () => { @@ -108,11 +99,9 @@ describe('StringArrayControlFlowTransformer', function () { const samplesCount: number = 1000; const delta: number = 0.1; - const regExp1: RegExp = new RegExp( - `\\(function\\(\\) *\\{ *${controlFlowStorageMatch}`, - ); + const regExp1: RegExp = new RegExp(`\\(function\\(\\) *\\{ *${controlFlowStorageMatch}`); const regExp2: RegExp = new RegExp( - `function *${hexadecimalVariableMatch} *\\(${hexadecimalVariableMatch}\\) *\\{ *${controlFlowStorageMatch}`, + `function *${hexadecimalVariableMatch} *\\(${hexadecimalVariableMatch}\\) *\\{ *${controlFlowStorageMatch}` ); let appendToScopeThreshold1: number = 0; @@ -126,16 +115,13 @@ describe('StringArrayControlFlowTransformer', function () { totalValue2: number = 0; for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); if (!regExp1.test(obfuscatedCode) && !regExp2.test(obfuscatedCode)) { console.log(obfuscatedCode); @@ -167,7 +153,7 @@ describe('StringArrayControlFlowTransformer', function () { `${hexadecimalVariableMatch} *: *0x1, *` + `${hexadecimalVariableMatch} *: *0x2, *` + `${hexadecimalVariableMatch} *: *0x3 *` + - `\\};` + `\\};` ); let obfuscatedCode: string; @@ -175,16 +161,13 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-items.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node with multiple items to the obfuscated code', () => { @@ -197,12 +180,11 @@ describe('StringArrayControlFlowTransformer', function () { `var ${hexadecimalVariableMatch} *= *\\{` + `${hexadecimalVariableMatch} *: *0x0, *` + `${hexadecimalVariableMatch} *: *0x1 *` + - `\\}; *` + - `var ${hexadecimalVariableMatch} *= *\\{` + - + `\\}; *` + + `var ${hexadecimalVariableMatch} *= *\\{` + `${hexadecimalVariableMatch} *: *0x2, *` + `${hexadecimalVariableMatch} *: *0x3 *` + - `\\};` + `\\};` ); let obfuscatedCode: string; @@ -210,16 +192,13 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-storages-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); console.log(obfuscatedCode); }); @@ -242,20 +221,17 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/root-block-scope-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); console.log(obfuscatedCode); }); - it('shouldn\'t add control flow storage node', () => { + it("shouldn't add control flow storage node", () => { assert.notMatch(obfuscatedCode, controlFlowStorageRegExp); assert.match(obfuscatedCode, stringArrayCallsRegExp); }); @@ -272,21 +248,18 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 0 + }).getObfuscatedCode(); console.log(obfuscatedCode); }); - it('shouldn\'t add control flow storage node', () => { + it("shouldn't add control flow storage node", () => { assert.notMatch(obfuscatedCode, controlFlowStorageRegExp); assert.match(obfuscatedCode, stringArrayCallsRegExp); }); @@ -297,31 +270,23 @@ describe('StringArrayControlFlowTransformer', function () { describe('Variant #2 - mangled number generator', () => { describe('Variant #1 - single control flow storage', () => { const controlFlowStorageRegExp: RegExp = new RegExp( - `var d *= *\\{` + - `c *: *0x0, *` + - `e *: *0x1 *` + - `\\};` - ); - const controlFlowStorageCallRegExp: RegExp = new RegExp( - `var c *= *b\\(d.c\\) *\\+ *b\\(d.e\\);` + `var d *= *\\{` + `c *: *0x0, *` + `e *: *0x1 *` + `\\};` ); + const controlFlowStorageCallRegExp: RegExp = new RegExp(`var c *= *b\\(d.c\\) *\\+ *b\\(d.e\\);`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should add `control flow storage` node to the obfuscated code', () => { @@ -335,41 +300,28 @@ describe('StringArrayControlFlowTransformer', function () { describe('Variant #2 - multiple control flow storages', () => { const controlFlowStorageRegExp1: RegExp = new RegExp( - `var d *= *\\{` + - `c *: *0x0, *` + - `e *: *0x1 *` + - `\\};` - ); - const controlFlowStorageCallRegExp1: RegExp = new RegExp( - `var c *= *b\\(d.c\\) *\\+ *b\\(d.e\\);` + `var d *= *\\{` + `c *: *0x0, *` + `e *: *0x1 *` + `\\};` ); + const controlFlowStorageCallRegExp1: RegExp = new RegExp(`var c *= *b\\(d.c\\) *\\+ *b\\(d.e\\);`); const controlFlowStorageRegExp2: RegExp = new RegExp( - `var e *= *\\{` + - `c *: *0x0, *` + - `f *: *0x1 *` + - `\\};` - ); - const controlFlowStorageCallRegExp2: RegExp = new RegExp( - `var c *= *b\\(e.c\\) *\\+ *b\\(e.f\\);` + `var e *= *\\{` + `c *: *0x0, *` + `f *: *0x1 *` + `\\};` ); + const controlFlowStorageCallRegExp2: RegExp = new RegExp(`var c *= *b\\(e.c\\) *\\+ *b\\(e.f\\);`); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-storages-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('Match #1: should add `control flow storage` №1 and its calls to the obfuscated code', () => { @@ -393,16 +345,13 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should use correct kind of variables for `control flow storage`', () => { @@ -416,18 +365,17 @@ describe('StringArrayControlFlowTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevailing-kind-of-variables-const.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should use correct kind of variables for `control flow storage`', () => { @@ -443,16 +391,13 @@ describe('StringArrayControlFlowTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1 + }).getObfuscatedCode(); }); it('should use correct kind of variables for `control flow storage`', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/boolean-literal-transformer/BooleanLiteralTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/boolean-literal-transformer/BooleanLiteralTransformer.spec.ts index dfaf962b..de8f025b 100644 --- a/test/functional-tests/node-transformers/converting-transformers/boolean-literal-transformer/BooleanLiteralTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/boolean-literal-transformer/BooleanLiteralTransformer.spec.ts @@ -15,14 +15,11 @@ describe('BooleanLiteralTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/true-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should transform boolean literal node', () => { @@ -38,14 +35,11 @@ describe('BooleanLiteralTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/false-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should transform boolean literal node', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/class-field-transformer/ClassFieldTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/class-field-transformer/ClassFieldTransformer.spec.ts index d39281cd..7dae5624 100644 --- a/test/functional-tests/node-transformers/converting-transformers/class-field-transformer/ClassFieldTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/class-field-transformer/ClassFieldTransformer.spec.ts @@ -18,12 +18,9 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should replace method definition node `key` property with square brackets literal', () => { @@ -40,22 +37,19 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add method definition node `key` property to string array', () => { - assert.match(obfuscatedCode, stringArrayRegExp); + assert.match(obfuscatedCode, stringArrayRegExp); }); it('should replace method definition node `key` property with call to string array', () => { - assert.match(obfuscatedCode, stringArrayCallRegExp); + assert.match(obfuscatedCode, stringArrayCallRegExp); }); }); @@ -67,15 +61,12 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t transform method definition node with `constructor` key', () => { + it("shouldn't transform method definition node with `constructor` key", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -90,12 +81,9 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/literal-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should replace method definition node `key` property with square brackets literal', () => { @@ -112,22 +100,19 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/literal-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add method definition node `key` property to string array', () => { - assert.match(obfuscatedCode, stringArrayRegExp); + assert.match(obfuscatedCode, stringArrayRegExp); }); it('should replace method definition node `key` property with call to string array', () => { - assert.match(obfuscatedCode, stringArrayCallRegExp); + assert.match(obfuscatedCode, stringArrayCallRegExp); }); }); @@ -139,15 +124,12 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/literal-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t transform method definition node with `constructor` key', () => { + it("shouldn't transform method definition node with `constructor` key", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -162,12 +144,9 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/async-get-method.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should rename class declaration name', () => { @@ -190,12 +169,9 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should replace property definition node `key` property with square brackets literal', () => { @@ -212,22 +188,19 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add property definition node `key` property to string array', () => { - assert.match(obfuscatedCode, stringArrayRegExp); + assert.match(obfuscatedCode, stringArrayRegExp); }); it('should replace property definition node `key` property with call to string array', () => { - assert.match(obfuscatedCode, stringArrayCallRegExp); + assert.match(obfuscatedCode, stringArrayCallRegExp); }); }); }); @@ -241,12 +214,9 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/literal-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should replace property definition node `key` property with square brackets literal', () => { @@ -263,22 +233,19 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/literal-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add property definition node `key` property to string array', () => { - assert.match(obfuscatedCode, stringArrayRegExp); + assert.match(obfuscatedCode, stringArrayRegExp); }); it('should replace property definition node `key` property with call to string array', () => { - assert.match(obfuscatedCode, stringArrayCallRegExp); + assert.match(obfuscatedCode, stringArrayCallRegExp); }); }); }); @@ -292,12 +259,9 @@ describe('ClassFieldTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/async-get-method.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should rename class declaration name', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/export-specifier-transformer/ExportSpecifierTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/export-specifier-transformer/ExportSpecifierTransformer.spec.ts index 6fd1abb1..dce42a8d 100644 --- a/test/functional-tests/node-transformers/converting-transformers/export-specifier-transformer/ExportSpecifierTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/export-specifier-transformer/ExportSpecifierTransformer.spec.ts @@ -10,8 +10,7 @@ describe('ExportSpecifierTransformer', () => { describe('Variant #1: exported constant', () => { describe('Variant #1:`renameGlobals` option is enabled', () => { const regExp: RegExp = new RegExp( - 'const _0x([a-f0-9]){4,6} *= *0x1; *' + - 'export *{_0x([a-f0-9]){4,6} as foo};' + 'const _0x([a-f0-9]){4,6} *= *0x1; *' + 'export *{_0x([a-f0-9]){4,6} as foo};' ); let obfuscatedCode: string; @@ -19,13 +18,10 @@ describe('ExportSpecifierTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/exported-constant.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('should transform export specifier node', () => { @@ -34,23 +30,17 @@ describe('ExportSpecifierTransformer', () => { }); describe('Variant #2: `renameGlobals` option is disabled', () => { - const regExp: RegExp = new RegExp( - 'const foo *= *0x1; *' + - 'export *{foo};' - ); + const regExp: RegExp = new RegExp('const foo *= *0x1; *' + 'export *{foo};'); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/exported-constant.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: false + }).getObfuscatedCode(); }); it('should not transform export specifier node', () => { @@ -62,8 +52,7 @@ describe('ExportSpecifierTransformer', () => { describe('Variant #2: exported import', () => { describe('Variant #1:`renameGlobals` option is enabled', () => { const regExp: RegExp = new RegExp( - 'import _0x([a-f0-9]){4,6} from *\'./bar\'; *' + - 'export *{_0x([a-f0-9]){4,6} as foo};' + "import _0x([a-f0-9]){4,6} from *'./bar'; *" + 'export *{_0x([a-f0-9]){4,6} as foo};' ); let obfuscatedCode: string; @@ -71,13 +60,10 @@ describe('ExportSpecifierTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/exported-import.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('should transform export specifier node', () => { @@ -87,8 +73,7 @@ describe('ExportSpecifierTransformer', () => { describe('Variant #2: `renameGlobals` option is disabled', () => { const regExp: RegExp = new RegExp( - 'import _0x([a-f0-9]){4,6} from *\'./bar\'; *' + - 'export *{_0x([a-f0-9]){4,6} as foo};' + "import _0x([a-f0-9]){4,6} from *'./bar'; *" + 'export *{_0x([a-f0-9]){4,6} as foo};' ); let obfuscatedCode: string; @@ -96,13 +81,10 @@ describe('ExportSpecifierTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/exported-import.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: false + }).getObfuscatedCode(); }); it('should transform export specifier node', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/member-expression-transformer/MemberExpressionTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/member-expression-transformer/MemberExpressionTransformer.spec.ts index 48b752b5..bfae1d6c 100644 --- a/test/functional-tests/node-transformers/converting-transformers/member-expression-transformer/MemberExpressionTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/member-expression-transformer/MemberExpressionTransformer.spec.ts @@ -17,16 +17,13 @@ describe('MemberExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/dot-notation-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should replace member expression dot notation call with literal value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); @@ -39,14 +36,11 @@ describe('MemberExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/dot-notation-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add member expression identifier to string array', () => { @@ -69,14 +63,11 @@ describe('MemberExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/square-brackets-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add member expression square brackets literal to string array', () => { @@ -96,12 +87,9 @@ describe('MemberExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/square-brackets-with-identifier-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should ignore square brackets call with identifier value', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/number-literal-transformer/NumberLiteralTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/number-literal-transformer/NumberLiteralTransformer.spec.ts index 9835d584..9dfec6a7 100644 --- a/test/functional-tests/node-transformers/converting-transformers/number-literal-transformer/NumberLiteralTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/number-literal-transformer/NumberLiteralTransformer.spec.ts @@ -15,14 +15,11 @@ describe('NumberLiteralTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/number-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should transform literal node', () => { @@ -38,14 +35,11 @@ describe('NumberLiteralTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/bigint-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should transform literal node', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/numbers-to-numerical-expressions-transformer/NumbersToNumericalExpressionsTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/numbers-to-numerical-expressions-transformer/NumbersToNumericalExpressionsTransformer.spec.ts index c5d1f426..0a53304c 100644 --- a/test/functional-tests/node-transformers/converting-transformers/numbers-to-numerical-expressions-transformer/NumbersToNumericalExpressionsTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/numbers-to-numerical-expressions-transformer/NumbersToNumericalExpressionsTransformer.spec.ts @@ -17,13 +17,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { for (let i = initialNumber; i < lastNumber; i++) { const number: number = i; - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); const result: number = eval(obfuscatedCode); @@ -48,13 +45,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); const result: number = eval(obfuscatedCode); @@ -78,13 +72,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); const result: number = eval(obfuscatedCode); @@ -108,13 +99,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); const result: number = eval(obfuscatedCode); @@ -140,13 +128,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); const result: number = eval(obfuscatedCode); @@ -169,13 +154,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { let obfuscatedCode: string; before(() => { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); }); it('should not transform unsafe integer to expressions', () => { @@ -191,13 +173,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); const result: number = eval(obfuscatedCode); @@ -220,13 +199,10 @@ describe('NumbersToNumericalExpressionsTransformer', function () { let obfuscatedCode: string; before(() => { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - `${number};`, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(`${number};`, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); }); it('should not transform unsafe integer to expressions', () => { @@ -243,17 +219,14 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/non-computed-object-key.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); }); it('should not replace non-computed object property literal with expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); @@ -265,17 +238,14 @@ describe('NumbersToNumericalExpressionsTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/member-expression.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - numbersToExpressions: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + numbersToExpressions: true + }).getObfuscatedCode(); }); it('should replace member expression with literal object with expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); diff --git a/test/functional-tests/node-transformers/converting-transformers/object-expression-keys-transformer/ObjectExpressionKeysTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/object-expression-keys-transformer/ObjectExpressionKeysTransformer.spec.ts index 5085de46..d261014a 100644 --- a/test/functional-tests/node-transformers/converting-transformers/object-expression-keys-transformer/ObjectExpressionKeysTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/object-expression-keys-transformer/ObjectExpressionKeysTransformer.spec.ts @@ -13,11 +13,12 @@ describe('ObjectExpressionKeysTransformer', () => { describe('transformation of object keys', () => { describe('Variant #1: simple', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -25,56 +26,54 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: variable declaration without initialization', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `${variableMatch} *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declaration-without-initialization.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declaration-without-initialization.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: return statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `return *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -82,78 +81,76 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/return-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #4: object expression inside array expression', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `var ${variableMatch} *= *\\[${variableMatch}];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-inside-array-expression.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-inside-array-expression.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #5: object expression inside call expression', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `console\\['log']\\(${variableMatch}\\);` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-inside-call-expression.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-inside-call-expression.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #6: nested objects #1', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['baz'] *= *'bark';` + `var ${variableMatch} *= *{};` + @@ -162,7 +159,7 @@ describe('ObjectExpressionKeysTransformer', () => { `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['inner'] *= *${variableMatch};` + `var object *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -170,22 +167,20 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/nested-objects-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #7: nested objects #2', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['hawk'] *= *'geek';` + `var ${variableMatch} *= *{};` + @@ -197,7 +192,7 @@ describe('ObjectExpressionKeysTransformer', () => { `${variableMatch}\\['inner'] *= *${variableMatch};` + `${variableMatch}\\['ball'] *= *'door';` + `var object *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -205,22 +200,20 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/nested-objects-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #8: nested objects #3', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['hawk'] *= *'geek';` + `var ${variableMatch} *= *{};` + @@ -232,7 +225,7 @@ describe('ObjectExpressionKeysTransformer', () => { `${variableMatch}\\['inner'] *= *${variableMatch};` + `${variableMatch}\\['ball'] *= *'door';` + `return ${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -240,57 +233,55 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/nested-objects-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #9: correct integration with control flow flattening object #1', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['\\w{5}'] *= *function *\\(${variableMatch}, *${variableMatch}\\) *{` + - `return *${variableMatch} *\\+ *${variableMatch};` + + `return *${variableMatch} *\\+ *${variableMatch};` + `};` + `var ${variableMatch} *= *${variableMatch};` + `var ${variableMatch} *= *${variableMatch}\\['\\w{5}']\\(0x1, *0x2\\);` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/integration-with-control-flow-flattening-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/integration-with-control-flow-flattening-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #10: correct integration with control flow flattening object #2', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['\\w{5}'] *= *function *\\(${variableMatch}, *${variableMatch}\\) *{` + - `return *${variableMatch} *\\+ *${variableMatch};` + + `return *${variableMatch} *\\+ *${variableMatch};` + `};` + `var ${variableMatch} *= *${variableMatch};` + `var ${variableMatch} *= *{};` + @@ -298,148 +289,146 @@ describe('ObjectExpressionKeysTransformer', () => { `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x2;` + `var ${variableMatch} *= *${variableMatch}\\['\\w{5}']\\(${variableMatch}\\['foo'], *${variableMatch}\\['bar']\\);` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/integration-with-control-flow-flattening-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/integration-with-control-flow-flattening-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #11: variable declarator object call inside other variable declarator', () => { describe('Variant #1', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'foo';` + `var ${variableMatch} *= *${variableMatch}, *` + `${variableMatch} *= *${variableMatch}\\['foo'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-with-object-call-4.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-with-object-call-4.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'foo';` + `var ${variableMatch} *= *${variableMatch}, *` + `${variableMatch} *= *\\[${variableMatch}\\['foo']];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-with-object-call-5.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-with-object-call-5.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3', () => { - const match: string = `` + - `var ${variableMatch} *= *0x1, *${variableMatch} *= *{'foo' *: *${variableMatch}};` + - ``; + const match: string = + `` + `var ${variableMatch} *= *0x1, *${variableMatch} *= *{'foo' *: *${variableMatch}};` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-with-object-call-6.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-with-object-call-6.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #12: assignment expression and member expression', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch}; *` + `var ${variableMatch} *= *{}; *` + `${variableMatch}\\['foo'] *= *'bar';` + `\\(${variableMatch} *= *${variableMatch}\\)\\['baz'] *= *${variableMatch}\\['foo'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/assignment-expression-and-member-expression.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/assignment-expression-and-member-expression.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #13: should keep numeric object keys', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['0'] *= *'foo';` + `${variableMatch}\\['bar'] *= *'bar';` + `${variableMatch}\\['2'] *= *'baz';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -447,27 +436,25 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/numeric-keys.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #14: template literal', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `var foo *= *'' *\\+ *_0x[a-f0-9]{4,6};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -475,24 +462,22 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/template-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #15: function default values', () => { // issue https://github.com/javascript-obfuscator/javascript-obfuscator/issues/516 describe('Variant #1: base', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['value'] *= *0x1;` + `function test *\\(${variableMatch} *= *0x1, *${variableMatch} *= *${variableMatch}\\) *{ *}` + @@ -504,55 +489,45 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-default-values.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore default parameter object if it references other parameter', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: mangled name of object host node', () => { - const match1: string = `` + - `var a *= *{};` + - `a\\['bar'] *= *0x1;` + - `function foo *\\(c *= *a\\) *{ *}` + - ``; - const match2: string = `` + - `var b *= *{};` + - `b\\['bark'] *= *0x1;` + - `function baz *\\(c *= *b\\) *{ *}` + - ``; + const match1: string = + `` + `var a *= *{};` + `a\\['bar'] *= *0x1;` + `function foo *\\(c *= *a\\) *{ *}` + ``; + const match2: string = + `` + `var b *= *{};` + `b\\['bark'] *= *0x1;` + `function baz *\\(c *= *b\\) *{ *}` + ``; const regExp1: RegExp = new RegExp(match1); const regExp2: RegExp = new RegExp(match2); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/function-default-values-mangled-name.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/function-default-values-mangled-name.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('Match #1: shouldn generate correct name for object host node', () => { - assert.match(obfuscatedCode, regExp1); + assert.match(obfuscatedCode, regExp1); }); it('Match #2: shouldn generate correct name for object host node', () => { - assert.match(obfuscatedCode, regExp2); + assert.match(obfuscatedCode, regExp2); }); }); }); @@ -561,124 +536,125 @@ describe('ObjectExpressionKeysTransformer', () => { describe('Variant #16: object expression inside variable declaration', () => { describe('Without reference on other property', () => { describe('Variant #1: Single variable declarator and object expression parent node is expression node', () => { - const match: string = `` + + const match: string = + `` + `var passthrough *= *${variableMatch} *=> *${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *0x1;` + `var foo *= *passthrough *\\(${variableMatch}\\);` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-inside-variable-declaration-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-inside-variable-declaration-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object expression keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: Multiple variable declarators and object expression parent node is variable declarator node', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *0x1;` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x2;` + `var foo *= *${variableMatch}, *bar *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-inside-variable-declaration-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-inside-variable-declaration-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object expressions keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('With reference on other property', () => { describe('Variant #1: Object expression parent node is variable declarator node', () => { - const match: string = `` + + const match: string = + `` + `var passthrough *= *${variableMatch} *=> *${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *0x1;` + `var foo *= *${variableMatch}, *bar *= *{'bar': *foo\\['foo']};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-inside-variable-declaration-3.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-inside-variable-declaration-3.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform first object expression keys and ignore second object expression keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: Object expression parent node is any expression node', () => { - const match: string = `` + + const match: string = + `` + `var passthrough *= *${variableMatch} *=> *${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *0x1;` + `var foo *= *${variableMatch}, *bar *= *passthrough *\\({ *'bar' *: *foo\\['foo'] *}\\);` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-inside-variable-declaration-4.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-inside-variable-declaration-4.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform first object expression keys and ignore second object expression keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); }); describe('Variant #17: sequence expression object expressions', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + @@ -687,30 +663,30 @@ describe('ObjectExpressionKeysTransformer', () => { `${variableMatch}\\['bar'] *= *0x2;` + `${variableMatch} *= *${variableMatch}, *` + `${variableMatch} *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/sequence-expression-object-expressions.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/sequence-expression-object-expressions.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform sequence expression object expressions keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #18: return statement sequence expression object expressions', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + @@ -720,31 +696,31 @@ describe('ObjectExpressionKeysTransformer', () => { `return ${variableMatch} *= *${variableMatch}, *` + `${variableMatch} *= *${variableMatch}, *` + `${variableMatch}\\['bar'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-sequence-expression-object-expressions.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-sequence-expression-object-expressions.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform sequence expression object expressions keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #19: object spread as member', () => { describe('Variant #1: object spread as first member', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{};` + `${variableMatch}\\['baz'] *= *0x1;` + `const foo *= *${variableMatch};` + @@ -752,7 +728,7 @@ describe('ObjectExpressionKeysTransformer', () => { `${variableMatch}\\['baz'] *= *0x2;` + `${variableMatch}\\['bark'] *= *0x3;` + `const bar *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -760,32 +736,30 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-spread-as-first-member.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform object expressions keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: object spread as middle member', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{};` + `${variableMatch}\\['baz'] *= *0x1;` + `const foo *= *${variableMatch};` + `const ${variableMatch} *= *{ *` + - `'baz': *0x2, *` + - `\.\.\.foo *` + + `'baz': *0x2, *` + + `\.\.\.foo *` + `};` + `${variableMatch}\\['bark'] *= *0x3;` + `const bar *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -793,17 +767,14 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-spread-as-middle-member.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn transform object expressions keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); @@ -811,12 +782,13 @@ describe('ObjectExpressionKeysTransformer', () => { describe('Variant #20: `this` expression', () => { describe('Variant #1: base', () => { describe('Variant #1: `this` expression as object expression', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `this\\['object'] *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -824,26 +796,24 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/this-expression-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: `this` expression as property value without `this` reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *this\\['foo'];` + `var ${variableMatch} *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -851,27 +821,25 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/this-expression-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: `this` expression as property value with `this` reference after object expression', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *this\\['foo'];` + `var ${variableMatch} *= *${variableMatch};` + `this\\['bar'] *= *'bar';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -879,28 +847,26 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/this-expression-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #4: `this` expression as property value with `this` reference before and after object expression', () => { - const match: string = `` + + const match: string = + `` + `this\\['foo'] *= *'foo';` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *this\\['foo'];` + `var ${variableMatch} *= *${variableMatch};` + `this\\['bar'] *= *'bar';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -908,47 +874,44 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/this-expression-4.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #2: Sequence expression', () => { describe('Variant #1: sequence expression, `this` reference after object expression', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'foo';` + `this\\['foo'] *= *${variableMatch},` + `this\\['foo'] *= *'foo';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/sequence-expression-this-reference-after.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/sequence-expression-this-reference-after.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); @@ -957,12 +920,13 @@ describe('ObjectExpressionKeysTransformer', () => { describe('member expression as host of object expression', () => { describe('Variant #1: simple', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `this\\['state'] *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -970,27 +934,25 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/member-expression-host-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: long members chain', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + `this\\['state']\\['foo'] *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -998,17 +960,14 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/member-expression-host-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); @@ -1016,13 +975,14 @@ describe('ObjectExpressionKeysTransformer', () => { describe('correct placement of expression statements', () => { describe('Variant #1: if statement', () => { describe('Variant #1: with block statement', () => { - const match: string = `` + + const match: string = + `` + `if *\\(!!\\[]\\) *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['foo'] *= *'bar';` + - `var ${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['foo'] *= *'bar';` + + `var ${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1030,91 +990,89 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-if-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: without block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['baz'] *= *'baz';` + `if *\\(!!\\[]\\)` + - `${variableMatch} *= *${variableMatch};` + + `${variableMatch} *= *${variableMatch};` + `else *` + - `${variableMatch} *= *${variableMatch};` + - ``; + `${variableMatch} *= *${variableMatch};` + + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-if-statement-without-block-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-if-statement-without-block-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: inside condition', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `if *\\(${variableMatch} *= *${variableMatch}\\) *{}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-if-statement-condition.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-if-statement-condition.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #2: for statement', () => { describe('Variant #1: with block statement', () => { - const match: string = `` + + const match: string = + `` + `for *\\(var ${variableMatch} *= *0x0; *${variableMatch} *< *0xa; *${variableMatch}\\+\\+\\) *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['foo'] *= *'bar';` + - `var ${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['foo'] *= *'bar';` + + `var ${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1122,60 +1080,58 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-for-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: without block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `for *\\(var ${variableMatch} *= *0x0; *${variableMatch} *< *0xa; *${variableMatch}\\+\\+\\) *` + - `${variableMatch} *= *${variableMatch};` + - ``; + `${variableMatch} *= *${variableMatch};` + + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-for-statement-without-block-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-for-statement-without-block-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #3: for in statement', () => { describe('Variant #1: with block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `for *\\(var ${variableMatch} in *${variableMatch}\\) *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['bar'] *= *'bar';` + - `${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['bar'] *= *'bar';` + + `${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1183,60 +1139,58 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-for-in-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: without block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `for *\\(var ${variableMatch} in *${variableMatch}\\) *` + - `${variableMatch} *= *${variableMatch};` + - ``; + `${variableMatch} *= *${variableMatch};` + + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-for-in-statement-without-block-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-for-in-statement-without-block-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #4: for of statement', () => { describe('Variant #1: with block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *\\[];` + `for *\\(var ${variableMatch} of *${variableMatch}\\) *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['bar'] *= *'bar';` + - `${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['bar'] *= *'bar';` + + `${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1244,59 +1198,57 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-for-of-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: without block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *\\[];` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `for *\\(var ${variableMatch} of *${variableMatch}\\) *` + - `${variableMatch} *= *${variableMatch};` + + `${variableMatch} *= *${variableMatch};` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-for-of-statement-without-block-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-for-of-statement-without-block-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #5: while statement', () => { describe('Variant #1: with block statement', () => { - const match: string = `` + + const match: string = + `` + `while *\\(!!\\[]\\) *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['foo'] *= *'bar';` + - `var ${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['foo'] *= *'bar';` + + `var ${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1304,87 +1256,85 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-while-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: without block statement', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `while *\\(!!\\[]\\)` + - `${variableMatch} *= *${variableMatch};` + - ``; + `${variableMatch} *= *${variableMatch};` + + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-while-statement-without-block-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-while-statement-without-block-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: inside condition', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `while *\\(${variableMatch} *= *${variableMatch}\\) *{}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-while-statement-condition.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/placement-inside-while-statement-condition.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #6: try statement', () => { - const match: string = `` + + const match: string = + `` + `try *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['foo'] *= *'bar';` + - `var ${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['foo'] *= *'bar';` + + `var ${variableMatch} *= *${variableMatch};` + `} *catch *\\(${variableMatch}\\) *{` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1392,29 +1342,27 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-try-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #7: catch clause statement', () => { - const match: string = `` + + const match: string = + `` + `try *{` + `} *catch *\\(${variableMatch}\\) *{` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['foo'] *= *'bar';` + - `var ${variableMatch} *= *${variableMatch};` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['foo'] *= *'bar';` + + `var ${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1422,29 +1370,27 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-catch-clause.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #8: switch catch statement', () => { - const match: string = `` + + const match: string = + `` + `switch *\\(!!\\[]\\) *{` + - `case *!!\\[]:` + - `var ${variableMatch} *= *{};` + - `${variableMatch}\\['foo'] *= *'bar';` + - `var ${variableMatch} *= *${variableMatch};` + + `case *!!\\[]:` + + `var ${variableMatch} *= *{};` + + `${variableMatch}\\['foo'] *= *'bar';` + + `var ${variableMatch} *= *${variableMatch};` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1452,107 +1398,104 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/placement-inside-switch-case.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #9: variable declarator with object call', () => { describe('Variant #1', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{}; *` + `${variableMatch}\\['foo'] *= *'foo'; *` + `const ${variableMatch} *= *${variableMatch};` + `const ${variableMatch} *= *${variableMatch}\\['foo'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-with-object-call-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-with-object-call-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{}; *` + `${variableMatch}\\['foo'] *= *'foo'; *` + `const ${variableMatch} *= *0x1, *` + - `${variableMatch} *= *${variableMatch}; *` + + `${variableMatch} *= *${variableMatch}; *` + `const ${variableMatch} *= *${variableMatch}\\['foo'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-with-object-call-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-with-object-call-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform object keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: two objects', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'foo';` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *'bar';` + `var ${variableMatch} *= *${variableMatch}, *` + - `${variableMatch} *= *${variableMatch}, *` + - `${variableMatch} *= *${variableMatch}\\['bar']; *` + + `${variableMatch} *= *${variableMatch}, *` + + `${variableMatch} *= *${variableMatch}\\['bar']; *` + `console\\['log']\\(${variableMatch}\\);` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-with-object-call-3.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-with-object-call-3.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly transform objects keys', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); @@ -1560,11 +1503,12 @@ describe('ObjectExpressionKeysTransformer', () => { describe('prevailing kind of variables', () => { describe('Variant #1: `var` kind`', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1572,26 +1516,24 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-var.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should use correct kind of variables', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: `const` kind`', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1599,26 +1541,24 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should use correct kind of variables', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: `let` kind`', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'bar';` + `${variableMatch}\\['baz'] *= *'bark';` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1626,29 +1566,21 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-let.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should use correct kind of variables', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Ignore transformation', () => { describe('Variant #1: disabled option', () => { - const match: string = `` + - `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *'bark'` + - `}` + - ``; + const match: string = `` + `var ${variableMatch} *= *{` + `'foo': *'bar',` + `'baz': *'bark'` + `}` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1656,16 +1588,13 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t transform object keys', () => { - assert.match(obfuscatedCode, regExp); + it("shouldn't transform object keys", () => { + assert.match(obfuscatedCode, regExp); }); }); @@ -1678,23 +1607,21 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/empty-object-expression.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t transform object keys', () => { - assert.match(obfuscatedCode, regExp); + it("shouldn't transform object keys", () => { + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: function default value reference', () => { - const match: string = `` + + const match: string = + `` + `function test *\\(${variableMatch} *= *0x1, *${variableMatch} *= *{'value' *: *${variableMatch}}\\) *{ *}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1702,29 +1629,27 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-default-value-reference.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore default parameter object if it references other parameter', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #4: member expression node as property key', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *'test';` + `var foo *= *${variableMatch};` + `var ${variableMatch} *= *{\\[foo\\['foo']] *: *'1'};` + `${variableMatch}\\['bar'] *= *'2';` + `var bar *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -1732,53 +1657,51 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/computed-key-member-expression.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore extraction of property with member expression key', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #5: sequence expression identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['foo'] *= *0x1;` + `${variableMatch} *= *${variableMatch}, *` + `${variableMatch} *= *{'bar' *: *${variableMatch}\\['foo']};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/sequence-expression-identifier-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/sequence-expression-identifier-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore sequence expression object expression if it references other sequence expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #6: return statement sequence expression identifier reference', () => { describe('Variant #1: reference on other sequence expression identifier', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + @@ -1786,232 +1709,228 @@ describe('ObjectExpressionKeysTransformer', () => { `return ${variableMatch} *= *${variableMatch}, *` + `${variableMatch} *= *{'bar' *: *${variableMatch}\\['foo']}, *` + `${variableMatch}\\['bar'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-sequence-expression-identifier-reference-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-sequence-expression-identifier-reference-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore sequence expression object expression if it references other sequence expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: reference on same sequence expression identifier', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['props'] *= *0x1;` + `return *\\(${variableMatch} *= *${variableMatch}\\)\\['state'] *= *{'expanded' *: *${variableMatch}\\['props']}, *` + `${variableMatch}\\['state']\\['expanded'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-sequence-expression-identifier-reference-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-sequence-expression-identifier-reference-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore sequence expression object expression if it references other sequence expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #7: conditional expression identifier reference', () => { describe('Variant #1: conditional expression identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `${variableMatch} *\\? *{'bar' *: *${variableMatch}\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/conditional-expression-identifier-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/conditional-expression-identifier-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: return statement conditional expression identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `return ${variableMatch} *\\? *{'bar' *: *${variableMatch}\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-conditional-expression-identifier-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-conditional-expression-identifier-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: assignment expression conditional expression identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `${variableMatch} *= *${variableMatch} *\\? *{'bar' *: *${variableMatch}\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/assignment-expression-conditional-expression-identifier-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/assignment-expression-conditional-expression-identifier-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #4: variable declarator conditional expression identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch};` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `var ${variableMatch} *= *${variableMatch} *\\? *{'bar' *: *${variableMatch}\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-conditional-expression-identifier-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-conditional-expression-identifier-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #8: variable declarator identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var passthrough *= *${variableMatch} *=> *${variableMatch};` + `var foo *= *0x1, *bar *= *{'baz' *: *passthrough\\(foo\\)};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-identifier-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarator-identifier-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore variable declarator object expression if it references other variable declarator identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #9: sequence expression super call expression', () => { - const match: string = `` + - `super\\(\\), *` + - `this\\['state'] *= *{ *'foo': *0x1 *};` + - ``; + const match: string = `` + `super\\(\\), *` + `this\\['state'] *= *{ *'foo': *0x1 *};` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/sequence-expression-super-call-expression.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/sequence-expression-super-call-expression.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); - it('shouldn\'t ignore sequence expression object expression if this sequence expression contains super call expression', () => { - assert.match(obfuscatedCode, regExp); + it("shouldn't ignore sequence expression object expression if this sequence expression contains super call expression", () => { + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #10: computed property key name', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *'foo';` + `const ${variableMatch} *= *{};` + `${variableMatch}\\[${variableMatch}] *= *'bar';` + `const ${variableMatch} *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2019,28 +1938,26 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/computed-key-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly generate name for the computed key identifier', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #11: `get` and `set` property kinds', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{ *` + - `get \'baz\' *\\(\\) *{ *return 0x2; *}, *` + - `set \'bark\' *\\(${variableMatch}\\) *{ *this\\[\'bark\'] *= *${variableMatch}; *} *` + + `get \'baz\' *\\(\\) *{ *return 0x2; *}, *` + + `set \'bark\' *\\(${variableMatch}\\) *{ *this\\[\'bark\'] *= *${variableMatch}; *} *` + `}; *` + `${variableMatch}\\[\'bar\'] *= *0x1;` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2048,32 +1965,30 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/get-set-property-kind.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should keep property nodes with `get` and `set` kind in the object', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #12: object spread as last member', () => { - const match: string = `` + + const match: string = + `` + `const ${variableMatch} *= *{};` + `${variableMatch}\\['baz'] *= *0x1;` + `const foo *= *${variableMatch};` + `const ${variableMatch} *= *{ *` + - `'baz': *0x2 *,` + - `'bark': *0x3 *,` + - `\.\.\.foo *` + + `'baz': *0x2 *,` + + `'bark': *0x3 *,` + + `\.\.\.foo *` + `};` + `const bar *= *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2081,52 +1996,41 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-spread-as-last-member.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expressions keys transformation', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #13: object expression as body of arrow function expression', () => { - const match: string = `` + - `const test *= *\\(\\) *=> *\\({`+ - `'foo' *: *'bar'` + - `}\\);` + - ``; + const match: string = `` + `const test *= *\\(\\) *=> *\\({` + `'foo' *: *'bar'` + `}\\);` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-as-body-of-arrow-function-expression.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-as-body-of-arrow-function-expression.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expressions keys transformation', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #14: sequence expression `this` reference', () => { - const match: string = `` + - `this\\['foo'] *= *0x1, *` + - `this\\['bar'] *= *{'bar' *: *this\\['foo']};` + - ``; + const match: string = `` + `this\\['foo'] *= *0x1, *` + `this\\['bar'] *= *{'bar' *: *this\\['foo']};` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2134,162 +2038,157 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/sequence-expression-this-reference.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore sequence expression object expression if it references other sequence expression `this` expression`', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #15: return statement sequence expression `this` reference', () => { describe('Variant #1: reference on other sequence expression `this` expression`', () => { - const match: string = `` + - `return this\\['foo'] *= *0x1, *` + - `this\\['bar'] *= *{'bar' *: *this\\['foo']};` + - ``; + const match: string = + `` + `return this\\['foo'] *= *0x1, *` + `this\\['bar'] *= *{'bar' *: *this\\['foo']};` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-sequence-expression-this-reference-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-sequence-expression-this-reference-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore sequence expression object expression if it references other sequence expression `this` expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: reference on same sequence expression `this` expression', () => { - const match: string = `` + + const match: string = + `` + `return *\\(this\\['foo'] *= *${variableMatch}\\)\\['state'] *= *{'expanded' *: *this\\['foo']\\['props']}, *` + `this\\['foo']\\['state']\\['expanded'];` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-sequence-expression-this-reference-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-sequence-expression-this-reference-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore sequence expression object expression if it references other sequence expression `this` expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #16: conditional expression `this` reference', () => { describe('Variant #1: conditional expression identifier reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `this\\['foo'] *\\? *{'bar' *: *this\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/conditional-expression-this-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/conditional-expression-this-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression `this` expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: return statement conditional expression `this` reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `return this\\['foo'] *\\? *{'bar' *: *this\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/return-statement-conditional-expression-this-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/return-statement-conditional-expression-this-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression `this` expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: assignment expression conditional expression `this` reference', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{};` + `${variableMatch}\\['bar'] *= *0x1;` + `this\\['bar'] *= *this\\['foo'] *\\? *{'bar' *: *this\\['foo']} *: *${variableMatch};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/assignment-expression-conditional-expression-this-reference.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/assignment-expression-conditional-expression-this-reference.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore conditional expression object expression if it references other conditional expression `this` expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #17: variable declarator `this` reference', () => { - const match: string = `` + + const match: string = + `` + `var passthrough *= *${variableMatch} *=> *${variableMatch};` + `var foo *= *this\\['foo'], *bar *= *{'baz' *: *passthrough\\(this\\['foo']\\)};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2297,28 +2196,21 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/variable-declarator-this-reference.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore variable declarator object expression if it references other variable declarator `this` expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #18: call expression as property value', () => { describe('Variant #1: call expression as a direct property value', () => { - const match: string = `` + - `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *${variableMatch}\\(\\)` + - `}` + - ``; + const match: string = + `` + `var ${variableMatch} *= *{` + `'foo': *'bar',` + `'baz': *${variableMatch}\\(\\)` + `}` + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2326,27 +2218,25 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a call expression as a direct property value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: call expression as an indirect property value', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *'call' *\\+ *${variableMatch}\\(\\)` + + `'foo': *'bar',` + + `'baz': *'call' *\\+ *${variableMatch}\\(\\)` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2354,29 +2244,27 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a call expression as an indirect property value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: call expression as a nested object expression as property value', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *{` + - `'bark': *${variableMatch}\\(\\)` + - `}` + + `'foo': *'bar',` + + `'baz': *{` + + `'bark': *${variableMatch}\\(\\)` + `}` + - ``; + `}` + + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2384,28 +2272,26 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a call expression as a nested object expression as property value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #4: call expression as a a property value after object expression property', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *${variableMatch},` + - `'eagle': *${variableMatch}\\(\\)` + + `'foo': *'bar',` + + `'baz': *${variableMatch},` + + `'eagle': *${variableMatch}\\(\\)` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2413,29 +2299,27 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-4.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a call expression and the previous property value is object expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); describe('Variant #19: new expression as property value', () => { describe('Variant #1: new expression as a direct property value', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *new ${variableMatch}\\(\\)` + + `'foo': *'bar',` + + `'baz': *new ${variableMatch}\\(\\)` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2443,27 +2327,25 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/new-expression-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a new expression as a direct property value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #2: new expression as an indirect property value', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *'call' *\\+ *new ${variableMatch}\\(\\)` + + `'foo': *'bar',` + + `'baz': *'call' *\\+ *new ${variableMatch}\\(\\)` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2471,29 +2353,27 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/new-expression-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a new expression as an indirect property value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #3: new expression as a nested object expression as property value', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *{` + - `'bark': *new ${variableMatch}\\(\\)` + - `}` + + `'foo': *'bar',` + + `'baz': *{` + + `'bark': *new ${variableMatch}\\(\\)` + `}` + - ``; + `}` + + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2501,28 +2381,26 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/new-expression-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a new expression as a nested object expression as property value', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); describe('Variant #4: new expression as a a property value after object expression property', () => { - const match: string = `` + + const match: string = + `` + `var ${variableMatch} *= *{` + - `'foo': *'bar',` + - `'baz': *${variableMatch},` + - `'eagle': *new ${variableMatch}\\(\\)` + + `'foo': *'bar',` + + `'baz': *${variableMatch},` + + `'eagle': *new ${variableMatch}\\(\\)` + `}` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -2530,17 +2408,14 @@ describe('ObjectExpressionKeysTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/new-expression-4.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('shouldn ignore object expression if it contains a new expression and the previous property value is object expression', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); diff --git a/test/functional-tests/node-transformers/converting-transformers/object-expression-transformer/ObjectExpressionTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/object-expression-transformer/ObjectExpressionTransformer.spec.ts index a5d61a44..3cde0c22 100644 --- a/test/functional-tests/node-transformers/converting-transformers/object-expression-transformer/ObjectExpressionTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/object-expression-transformer/ObjectExpressionTransformer.spec.ts @@ -10,7 +10,7 @@ import { ObjectPatternPropertiesTransformer } from '../../../../../src/node-tran describe('ObjectExpressionTransformer', () => { describe('default behaviour', () => { - describe('Variant #1: `unicodeEscapeSequence` option is disabled\'', () => { + describe("Variant #1: `unicodeEscapeSequence` option is disabled'", () => { const regExp: RegExp = /var test *= *\{'foo':0x0\};/; let obfuscatedCode: string; @@ -18,13 +18,10 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-with-identifier-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); }); it('should replace object expression node `key` property with identifier value by property with literal value', () => { @@ -40,13 +37,10 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-with-identifier-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('should replace object expression node `key` property with identifier value by property with encoded literal value', () => { @@ -63,12 +57,9 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/shorthand-object-expression.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should correct convert shorthand ES6 object expression to non-shorthand object expression', () => { @@ -85,12 +76,9 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/computed-property-name-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should ignore computed property identifier', () => { @@ -107,13 +95,10 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/computed-property-name-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); }); it('should ignore computed property literal value', () => { @@ -129,13 +114,10 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/computed-property-name-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('should encode computed property literal value', () => { @@ -156,12 +138,9 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-rest.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform object name', () => { @@ -176,19 +155,17 @@ describe('ObjectExpressionTransformer', () => { describe('object spread', () => { const object1RegExp: RegExp = /var _0x[a-f0-9]{4,6} *= *\{'foo': *0x1\};/; const object2RegExp: RegExp = /var _0x[a-f0-9]{4,6} *= *\{'bar': *0x2\};/; - const objectSpreadRegExp: RegExp = /var _0x[a-f0-9]{4,6} *= *\{\.\.\._0x[a-f0-9]{4,6}, *\.\.\._0x[a-f0-9]{4,6}\};/; + const objectSpreadRegExp: RegExp = + /var _0x[a-f0-9]{4,6} *= *\{\.\.\._0x[a-f0-9]{4,6}, *\.\.\._0x[a-f0-9]{4,6}\};/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-spread.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform object name', () => { @@ -216,14 +193,11 @@ describe('ObjectExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-spread-unicode-escape-sequence.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('Match #1: should transform object declaration', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/object-pattern-properties-transformer/ObjectPatternPropertiesTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/object-pattern-properties-transformer/ObjectPatternPropertiesTransformer.spec.ts index 3c5da4b1..69a87036 100644 --- a/test/functional-tests/node-transformers/converting-transformers/object-pattern-properties-transformer/ObjectPatternPropertiesTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/object-pattern-properties-transformer/ObjectPatternPropertiesTransformer.spec.ts @@ -14,8 +14,8 @@ describe('ObjectPatternPropertiesTransformer', () => { 'foo: *_0x([a-f0-9]){4,6}, *' + 'bar: *_0x([a-f0-9]){4,6}, *' + '..._0x([a-f0-9]){4,6}' + - '} *= *{}; *' + - 'console\\[\'log\']\\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\\);' + '} *= *{}; *' + + "console\\['log']\\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\\);" ); let obfuscatedCode: string; @@ -23,13 +23,10 @@ describe('ObjectPatternPropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: false + }).getObfuscatedCode(); }); it('should transform object properties', () => { @@ -43,8 +40,8 @@ describe('ObjectPatternPropertiesTransformer', () => { 'foo: *_0x([a-f0-9]){4,6}, *' + 'bar: *_0x([a-f0-9]){4,6}, *' + '..._0x([a-f0-9]){4,6}' + - '} *= *{}; *' + - 'console\\[\'log\']\\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\\);' + '} *= *{}; *' + + "console\\['log']\\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\\);" ); let obfuscatedCode: string; @@ -52,13 +49,10 @@ describe('ObjectPatternPropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('should transform object properties', () => { @@ -71,10 +65,10 @@ describe('ObjectPatternPropertiesTransformer', () => { 'const { *' + 'foo: *_0x([a-f0-9]){4,6}, *' + 'bar: *_0x([a-f0-9]){4,6} *' + - '} *= *{}; *' + - 'const _0x([a-f0-9]){4,6} *= *{};' + - '_0x([a-f0-9]){4,6}\\[\'prop\'] *= *0x1;' + - 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6};' + '} *= *{}; *' + + 'const _0x([a-f0-9]){4,6} *= *{};' + + "_0x([a-f0-9]){4,6}\\['prop'] *= *0x1;" + + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6};' ); let obfuscatedCode: string; @@ -82,14 +76,11 @@ describe('ObjectPatternPropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-scope-wrong-parentize.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: false, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: false, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should transform object properties', () => { @@ -105,8 +96,8 @@ describe('ObjectPatternPropertiesTransformer', () => { 'foo, *' + 'bar, *' + '...rest' + - '} *= *{}; *' + - 'console\\[\'log\']\\(foo, *bar, *rest\\);' + '} *= *{}; *' + + "console\\['log']\\(foo, *bar, *rest\\);" ); let obfuscatedCode: string; @@ -114,13 +105,10 @@ describe('ObjectPatternPropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/global-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: false + }).getObfuscatedCode(); }); it('should transform object properties', () => { @@ -134,8 +122,8 @@ describe('ObjectPatternPropertiesTransformer', () => { 'foo: *_0x([a-f0-9]){4,6}, *' + 'bar: *_0x([a-f0-9]){4,6}, *' + '..._0x([a-f0-9]){4,6}' + - '} *= *{}; *' + - 'console\\[\'log\']\\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\\);' + '} *= *{}; *' + + "console\\['log']\\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\\);" ); let obfuscatedCode: string; @@ -143,13 +131,10 @@ describe('ObjectPatternPropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/global-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('should transform object properties', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/split-string-transformer/SplitStringTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/split-string-transformer/SplitStringTransformer.spec.ts index 45a01dc0..a5c8f951 100644 --- a/test/functional-tests/node-transformers/converting-transformers/split-string-transformer/SplitStringTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/split-string-transformer/SplitStringTransformer.spec.ts @@ -10,21 +10,18 @@ import { JavaScriptObfuscator } from '../../../../../src/JavaScriptObfuscatorFac describe('SplitStringTransformer', () => { let obfuscatedCode: string; - + describe('Variant #1: simple string literal', () => { it('should transform string literal to binary expression', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'ab' *\+ *'cd' *\+ *'ef' *\+ *'g';$/); + assert.match(obfuscatedCode, /^var test *= *'ab' *\+ *'cd' *\+ *'ef' *\+ *'g';$/); }); }); @@ -32,16 +29,13 @@ describe('SplitStringTransformer', () => { it('should keep original string literal', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: false, - splitStringsChunkLength: 10 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: false, + splitStringsChunkLength: 10 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'abcdefg';$/); + assert.match(obfuscatedCode, /^var test *= *'abcdefg';$/); }); }); @@ -49,16 +43,13 @@ describe('SplitStringTransformer', () => { it('should keep original string literal', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 10 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 10 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'abcdefg';$/); + assert.match(obfuscatedCode, /^var test *= *'abcdefg';$/); }); }); @@ -66,14 +57,12 @@ describe('SplitStringTransformer', () => { it('should throw an validation error ', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - const testFunc = () => JavaScriptObfuscator.obfuscate( - code, - { + const testFunc = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, splitStrings: true, splitStringsChunkLength: 0 - } - ); + }); assert.throws(testFunc, /validation failed/i); }); @@ -83,16 +72,13 @@ describe('SplitStringTransformer', () => { it('should transform string literals to binary expressions', () => { const code: string = readFileAsString(__dirname + '/fixtures/strings-concatenation.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'ab' *\+ *'cd' *\+ *\( *'ef' *\+ *'g' *\);$/); + assert.match(obfuscatedCode, /^var test *= *'ab' *\+ *'cd' *\+ *\( *'ef' *\+ *'g' *\);$/); }); }); @@ -100,17 +86,17 @@ describe('SplitStringTransformer', () => { it('should convert strings to unicode escape sequence view', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2, + unicodeEscapeSequence: true + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'\\x61\\x62' *\+ *'\\x63\\x64' *\+ *'\\x65\\x66' *\+ *'\\x67';$/); + assert.match( + obfuscatedCode, + /^var test *= *'\\x61\\x62' *\+ *'\\x63\\x64' *\+ *'\\x65\\x66' *\+ *'\\x67';$/ + ); }); }); @@ -118,16 +104,13 @@ describe('SplitStringTransformer', () => { it('should apply string splitting on template literal strings', () => { const code: string = readFileAsString(__dirname + '/fixtures/template-literal-string.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'ab' *\+ *'cd' *\+ *'ef' *\+ *'g';$/); + assert.match(obfuscatedCode, /^var test *= *'ab' *\+ *'cd' *\+ *'ef' *\+ *'g';$/); }); }); @@ -135,16 +118,13 @@ describe('SplitStringTransformer', () => { it('should keep original key string literal and transform value string literal', () => { const code: string = readFileAsString(__dirname + '/fixtures/object-string-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *{'abcdefg' *: *'ab' *\+ *'cd' *\+ *'ef' *\+ *'g'};$/); + assert.match(obfuscatedCode, /^var test *= *{'abcdefg' *: *'ab' *\+ *'cd' *\+ *'ef' *\+ *'g'};$/); }); }); @@ -152,16 +132,13 @@ describe('SplitStringTransformer', () => { it('should transform string literal to binary expression', () => { const code: string = readFileAsString(__dirname + '/fixtures/object-computed-key-string-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *{\['ab' *\+ *'cd' *\+ *'ef' *\+ *'g'] *: *0x1};$/); + assert.match(obfuscatedCode, /^var test *= *{\['ab' *\+ *'cd' *\+ *'ef' *\+ *'g'] *: *0x1};$/); }); }); @@ -172,16 +149,13 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 1 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); it('should correctly evaluate splitted string with emoji', () => { @@ -189,14 +163,11 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 1 + }).getObfuscatedCode(); const resultString: string = eval(obfuscatedCode); @@ -210,16 +181,13 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 1 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); it('should correctly evaluate splitted string with emoji', () => { @@ -227,14 +195,11 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 1 + }).getObfuscatedCode(); const resultString: string = eval(obfuscatedCode); @@ -248,16 +213,13 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 3 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 3 + }).getObfuscatedCode(); - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); it('should correctly evaluate splitted string with emoji', () => { @@ -265,14 +227,11 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 3 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 3 + }).getObfuscatedCode(); const resultString: string = eval(obfuscatedCode); @@ -290,19 +249,14 @@ describe('SplitStringTransformer', () => { const code: string = readFileAsString(__dirname + '/fixtures/string-with-emoji-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 3, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.Base64 - ] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 3, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.Base64] + }).getObfuscatedCode(); const resultString: string = eval(obfuscatedCode); @@ -315,27 +269,23 @@ describe('SplitStringTransformer', () => { describe('Variant #12: Integration with `transformObjectKeys` option', () => { it('should correctly transform string when `transformObjectKeys` option is enabled', () => { - const regExp: RegExp = new RegExp(`` + - `var _0x[a-f0-9]{4,6} *= *{};` + - `*_0x[a-f0-9]{4,6}\\['ab' *\\+ *'cd' *\\+ *'ef' *\\+ *'g'] *= *'ab' *\\+ *'cd' *\\+ *'ef' *\\+ *'g';` + - `var test *= *_0x[a-f0-9]{4,6};` + - ``); + const regExp: RegExp = new RegExp( + `` + + `var _0x[a-f0-9]{4,6} *= *{};` + + `*_0x[a-f0-9]{4,6}\\['ab' *\\+ *'cd' *\\+ *'ef' *\\+ *'g'] *= *'ab' *\\+ *'cd' *\\+ *'ef' *\\+ *'g';` + + `var test *= *_0x[a-f0-9]{4,6};` + + `` + ); const code: string = readFileAsString(__dirname + '/fixtures/object-string-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2, + transformObjectKeys: true + }).getObfuscatedCode(); - assert.match( - obfuscatedCode, - regExp - ); + assert.match(obfuscatedCode, regExp); }); }); @@ -343,15 +293,12 @@ describe('SplitStringTransformer', () => { it('should correctly ignore strings from `reservedStrings` option', () => { const code: string = readFileAsString(__dirname + '/fixtures/ignore-reserved-strings.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 3, - reservedStrings: ['bar'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 3, + reservedStrings: ['bar'] + }).getObfuscatedCode(); assert.match( obfuscatedCode, @@ -364,19 +311,14 @@ describe('SplitStringTransformer', () => { it('Should does not throw `Maximum call stack size exceeded` error on a large string', () => { const code: string = `var foo = '${'a'.repeat(10000)}';`; - const testFunc = () => JavaScriptObfuscator.obfuscate( - code, - { + const testFunc = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, splitStrings: true, splitStringsChunkLength: 2 - } - ); + }); - assert.doesNotThrow( - testFunc, - Error - ); + assert.doesNotThrow(testFunc, Error); }); }); @@ -388,14 +330,11 @@ describe('SplitStringTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/import-declaration-source.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); }); it('Should not split `ImportDeclaration` source literal', () => { @@ -411,14 +350,11 @@ describe('SplitStringTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/export-all-declaration-source.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); }); it('Should not split `ExportAllDeclaration` source literal', () => { @@ -434,14 +370,11 @@ describe('SplitStringTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/export-named-declaration-source.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - splitStrings: true, - splitStringsChunkLength: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + splitStrings: true, + splitStringsChunkLength: 2 + }).getObfuscatedCode(); }); it('Should not split `ExportNamedDeclaration` source literal', () => { diff --git a/test/functional-tests/node-transformers/converting-transformers/template-literal-transformer/TemplateLiteralTransformer.spec.ts b/test/functional-tests/node-transformers/converting-transformers/template-literal-transformer/TemplateLiteralTransformer.spec.ts index e07b8b7d..7bd07ae7 100644 --- a/test/functional-tests/node-transformers/converting-transformers/template-literal-transformer/TemplateLiteralTransformer.spec.ts +++ b/test/functional-tests/node-transformers/converting-transformers/template-literal-transformer/TemplateLiteralTransformer.spec.ts @@ -8,20 +8,17 @@ import { JavaScriptObfuscator } from '../../../../../src/JavaScriptObfuscatorFac describe('TemplateLiteralTransformer', () => { let obfuscatedCode: string; - + describe('Variant #1: simple template literal', () => { it('should transform es6 template literal to es5', () => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'abc\\x20' *\+ *foo;$/); + assert.match(obfuscatedCode, /^var test *= *'abc\\x20' *\+ *foo;$/); }); }); @@ -29,71 +26,64 @@ describe('TemplateLiteralTransformer', () => { it('Variant #1: should transform es6 multiline template literal to es5', () => { const code: string = readFileAsString(__dirname + '/fixtures/multiline-template-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'foo\\x0abar';$/); + assert.match(obfuscatedCode, /^var test *= *'foo\\x0abar';$/); }); it('Variant #2: should transform es6 multiline template literal inside return statement', () => { - const code: string = readFileAsString(__dirname + '/fixtures/multiline-template-literal-return-statement-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/multiline-template-literal-return-statement-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /{ *return *'foo\\x0abar'; *}$/); + assert.match(obfuscatedCode, /{ *return *'foo\\x0abar'; *}$/); }); it('Variant #3: should transform es6 multiline template literal inside return statement', () => { - const code: string = readFileAsString(__dirname + '/fixtures/multiline-template-literal-return-statement-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/multiline-template-literal-return-statement-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /case *!!\[] *: *return *'foo\\x0abar'; *} *}$/); + assert.match(obfuscatedCode, /case *!!\[] *: *return *'foo\\x0abar'; *} *}$/); }); it('Variant #4: should transform es6 multiline template literal inside binary expression inside return statement', () => { - const code: string = readFileAsString(__dirname + '/fixtures/multiline-template-literal-binary-expression-return-statement-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/multiline-template-literal-binary-expression-return-statement-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /{ *return *'foo\\x0abar' *\+ *0x1; *}$/); + assert.match(obfuscatedCode, /{ *return *'foo\\x0abar' *\+ *0x1; *}$/); }); it('Variant #5: should transform es6 multiline template literal inside binary expression inside return statement', () => { - const code: string = readFileAsString(__dirname + '/fixtures/multiline-template-literal-binary-expression-return-statement-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/multiline-template-literal-binary-expression-return-statement-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /case *!!\[] *: *return *'foo\\x0abar' *\+ *0x1; *} *}$/); + assert.match(obfuscatedCode, /case *!!\[] *: *return *'foo\\x0abar' *\+ *0x1; *} *}$/); }); }); @@ -101,15 +91,12 @@ describe('TemplateLiteralTransformer', () => { it('should transform es6 template literal to es5 and add empty literal node before expression node', () => { const code: string = readFileAsString(__dirname + '/fixtures/expression-only.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'' *\+ *foo;$/); + assert.match(obfuscatedCode, /^var test *= *'' *\+ *foo;$/); }); }); @@ -117,15 +104,12 @@ describe('TemplateLiteralTransformer', () => { it('should transform es6 template literal to es5', () => { const code: string = readFileAsString(__dirname + '/fixtures/literal-inside-expression.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^var test *= *'abc';$/); + assert.match(obfuscatedCode, /^var test *= *'abc';$/); }); }); @@ -133,37 +117,25 @@ describe('TemplateLiteralTransformer', () => { it('should transform es6 template literal to es5', () => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-expressions.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match( - obfuscatedCode, - /^var test *= *0x1 *\+ *0x1 *\+ *'\\x20abc\\x20' *\+ *\(0x1 *\+ *0x1\);$/ - ); + assert.match(obfuscatedCode, /^var test *= *0x1 *\+ *0x1 *\+ *'\\x20abc\\x20' *\+ *\(0x1 *\+ *0x1\);$/); }); }); describe('Variant #6: tagged template literal', () => { - it('shouldn\'t transform es6 tagged template literal to es5', () => { + it("shouldn't transform es6 tagged template literal to es5", () => { const code: string = readFileAsString(__dirname + '/fixtures/tagged-template-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match( - obfuscatedCode, - /tag`foo *\${0x1 *\+ *0x1} *bar`;/ - ); + assert.match(obfuscatedCode, /tag`foo *\${0x1 *\+ *0x1} *bar`;/); }); }); @@ -171,24 +143,22 @@ describe('TemplateLiteralTransformer', () => { it('should parentize transformed template literal node', () => { const code: string = readFileAsString(__dirname + '/fixtures/template-literal-parentize.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: false + }).getObfuscatedCode(); - assert.match(obfuscatedCode, /^\[]\['map']\(\(\) *=> *'foo'\);$/); + assert.match(obfuscatedCode, /^\[]\['map']\(\(\) *=> *'foo'\);$/); }); }); describe('Variant #8: parentize node', () => { - const match: string = `` + + const match: string = + `` + `var _0x[a-f0-9]{4,6} *= *{};` + `_0x[a-f0-9]{4,6}\\['foo'] *= *'bar';` + `var foo *= *'' *\\+ *_0x[a-f0-9]{4,6};` + - ``; + ``; const regExp: RegExp = new RegExp(match); let obfuscatedCode: string; @@ -196,17 +166,14 @@ describe('TemplateLiteralTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/parentize-node.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should correctly obfuscate code without maximum call stack error', () => { - assert.match(obfuscatedCode, regExp); + assert.match(obfuscatedCode, regExp); }); }); }); diff --git a/test/functional-tests/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.spec.ts b/test/functional-tests/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.spec.ts index 8024e4b1..386ac44a 100644 --- a/test/functional-tests/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.spec.ts +++ b/test/functional-tests/node-transformers/dead-code-injection-transformers/DeadCodeInjectionTransformer.spec.ts @@ -19,11 +19,11 @@ describe('DeadCodeInjectionTransformer', () => { describe('Variant #1 - 5 simple block statements', () => { const regExp: RegExp = new RegExp( - `if *\\(${variableMatch}\\(${hexMatch}\\) *[=|!]== *${variableMatch}\\(${hexMatch}\\)\\) *\\{`+ + `if *\\(${variableMatch}\\(${hexMatch}\\) *[=|!]== *${variableMatch}\\(${hexMatch}\\)\\) *\\{` + `(?:console|${variableMatch})\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\} *else *\\{`+ + `\\} *else *\\{` + `(?:console|${variableMatch})\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\}`, + `\\}`, 'g' ); const expectedMatchesLength: number = 5; @@ -33,16 +33,13 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const matches: RegExpMatchArray = obfuscatedCode.match(regExp); if (matches) { @@ -59,7 +56,7 @@ describe('DeadCodeInjectionTransformer', () => { const regexp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, + `\\};`, 'g' ); const expectedMatchesLength: number = 4; @@ -69,16 +66,13 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/block-statements-min-count.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const matches: RegExpMatchArray = obfuscatedCode.match(regexp); if (matches) { @@ -86,7 +80,7 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('shouldn\'t add dead code', () => { + it("shouldn't add dead code", () => { assert.equal(matchesLength, expectedMatchesLength); }); }); @@ -95,7 +89,7 @@ describe('DeadCodeInjectionTransformer', () => { const regexp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, + `\\};`, 'g' ); const expectedMatchesLength: number = 5; @@ -105,16 +99,13 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 0, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 0, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const matches: RegExpMatchArray = obfuscatedCode.match(regexp); if (matches) { @@ -122,7 +113,7 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('shouldn\'t add dead code', () => { + it("shouldn't add dead code", () => { assert.equal(matchesLength, expectedMatchesLength); }); }); @@ -132,7 +123,7 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, + `\\};`, 'g' ); const functionDeclarationRegExp: RegExp = new RegExp( @@ -146,20 +137,21 @@ describe('DeadCodeInjectionTransformer', () => { functionDeclarationMatchesLength: number = 0; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/function-declaration-inside-block-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/function-declaration-inside-block-statement.js' + ); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); - const loopMatches: RegExpMatchArray = obfuscatedCode.match(functionDeclarationRegExp); + const loopMatches: RegExpMatchArray = ( + obfuscatedCode.match(functionDeclarationRegExp) + ); if (functionMatches) { functionMatchesLength = functionMatches.length; @@ -170,11 +162,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(functionDeclarationMatchesLength, expectedFunctionDeclarationMatchesLength); }); }); @@ -184,13 +176,13 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, + `\\};`, 'g' ); const loopRegExp: RegExp = new RegExp( `for *\\(var ${variableMatch} *= *${hexMatch}; *${variableMatch} *< *${hexMatch}; *${variableMatch}\\+\\+\\) *\\{` + - `(?:continue|break);` + - `\\}`, + `(?:continue|break);` + + `\\}`, 'g' ); const expectedFunctionMatchesLength: number = 4; @@ -202,17 +194,16 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/break-continue-statement-1.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); - const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); + const functionMatches: RegExpMatchArray = ( + obfuscatedCode.match(functionRegExp) + ); const loopMatches: RegExpMatchArray = obfuscatedCode.match(loopRegExp); if (functionMatches) { @@ -224,11 +215,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(loopMatchesLength, expectedLoopMatchesLength); }); }); @@ -237,7 +228,7 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, + `\\};`, 'g' ); const loopRegExp: RegExp = new RegExp( @@ -254,17 +245,16 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/break-continue-statement-2.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); - const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); + const functionMatches: RegExpMatchArray = ( + obfuscatedCode.match(functionRegExp) + ); const loopMatches: RegExpMatchArray = obfuscatedCode.match(loopRegExp); if (functionMatches) { @@ -276,11 +266,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(loopMatchesLength, expectedLoopMatchesLength); }); }); @@ -290,13 +280,10 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, - 'g' - ); - const awaitExpressionRegExp: RegExp = new RegExp( - `await *${variableMatch}\\(\\)`, + `\\};`, 'g' ); + const awaitExpressionRegExp: RegExp = new RegExp(`await *${variableMatch}\\(\\)`, 'g'); const expectedFunctionMatchesLength: number = 4; const expectedAwaitExpressionMatchesLength: number = 1; @@ -306,18 +293,17 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/await-expression.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); - const awaitExpressionMatches: RegExpMatchArray = obfuscatedCode.match(awaitExpressionRegExp); + const awaitExpressionMatches: RegExpMatchArray = ( + obfuscatedCode.match(awaitExpressionRegExp) + ); if (functionMatches) { functionMatchesLength = functionMatches.length; @@ -328,11 +314,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(awaitExpressionMatchesLength, expectedAwaitExpressionMatchesLength); }); }); @@ -341,13 +327,10 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, - 'g' - ); - const yieldExpressionRegExp: RegExp = new RegExp( - `yield *${variableMatch}\\(\\)`, + `\\};`, 'g' ); + const yieldExpressionRegExp: RegExp = new RegExp(`yield *${variableMatch}\\(\\)`, 'g'); const expectedFunctionMatchesLength: number = 4; const expectedAwaitExpressionMatchesLength: number = 1; @@ -357,18 +340,17 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/yield-expression.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); - const yieldExpressionMatches: RegExpMatchArray = obfuscatedCode.match(yieldExpressionRegExp); + const yieldExpressionMatches: RegExpMatchArray = ( + obfuscatedCode.match(yieldExpressionRegExp) + ); if (functionMatches) { functionMatchesLength = functionMatches.length; @@ -379,11 +361,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(yieldExpressionMatchesLength, expectedAwaitExpressionMatchesLength); }); }); @@ -392,13 +374,10 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, - 'g' - ); - const superExpressionRegExp: RegExp = new RegExp( - `super *\\(\\);`, + `\\};`, 'g' ); + const superExpressionRegExp: RegExp = new RegExp(`super *\\(\\);`, 'g'); const expectedFunctionMatchesLength: number = 4; const expectedSuperExpressionMatchesLength: number = 1; @@ -408,18 +387,17 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/super-expression.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); - const superExpressionMatches: RegExpMatchArray = obfuscatedCode.match(superExpressionRegExp); + const superExpressionMatches: RegExpMatchArray = ( + obfuscatedCode.match(superExpressionRegExp) + ); if (functionMatches) { functionMatchesLength = functionMatches.length; @@ -430,11 +408,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(superExpressionMatchesLength, expectedSuperExpressionMatchesLength); }); }); @@ -443,7 +421,7 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, + `\\};`, 'g' ); const awaitExpressionRegExp: RegExp = new RegExp( @@ -459,18 +437,17 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/for-await-expression.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); - const awaitExpressionMatches: RegExpMatchArray = obfuscatedCode.match(awaitExpressionRegExp); + const awaitExpressionMatches: RegExpMatchArray = ( + obfuscatedCode.match(awaitExpressionRegExp) + ); if (functionMatches) { functionMatchesLength = functionMatches.length; @@ -481,11 +458,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(awaitExpressionMatchesLength, expectedAwaitExpressionMatchesLength); }); }); @@ -494,13 +471,10 @@ describe('DeadCodeInjectionTransformer', () => { const functionRegExp: RegExp = new RegExp( `var ${variableMatch} *= *function *\\(\\) *\\{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\};`, - 'g' - ); - const privateIdentifierRegExp: RegExp = new RegExp( - `this\.#private *= *0x1;`, + `\\};`, 'g' ); + const privateIdentifierRegExp: RegExp = new RegExp(`this\.#private *= *0x1;`, 'g'); const expectedFunctionMatchesLength: number = 4; const expectedPrivateIdentifierMatchesLength: number = 1; @@ -510,18 +484,17 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/private-identifier.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(functionRegExp); - const privateIdentifierMatches: RegExpMatchArray = obfuscatedCode.match(privateIdentifierRegExp); + const privateIdentifierMatches: RegExpMatchArray = ( + obfuscatedCode.match(privateIdentifierRegExp) + ); if (functionMatches) { functionMatchesLength = functionMatches.length; @@ -532,11 +505,11 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('match #1: shouldn\'t add dead code', () => { + it("match #1: shouldn't add dead code", () => { assert.equal(functionMatchesLength, expectedFunctionMatchesLength); }); - it('match #2: shouldn\'t add dead code', () => { + it("match #2: shouldn't add dead code", () => { assert.equal(privateIdentifierMatchesLength, expectedPrivateIdentifierMatchesLength); }); }); @@ -550,34 +523,38 @@ describe('DeadCodeInjectionTransformer', () => { const ifMatch: string = `if *\\(!!\\[\\]\\) *\\{`; const functionMatch: string = `var ${variableMatch} *= *function *\\(\\) *\\{`; - const match1: string = `` + + const match1: string = + `` + `if *\\(${stringArrayCallMatch} *=== *${stringArrayCallMatch}\\) *\\{` + - `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + + `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + `\\} *else *\\{` + - `${variableMatch}\\(${stringArrayCallMatch}\\);` + + `${variableMatch}\\(${stringArrayCallMatch}\\);` + `\\}` + - ``; - const match2: string = `` + + ``; + const match2: string = + `` + `if *\\(${stringArrayCallMatch} *!== *${stringArrayCallMatch}\\) *\\{` + - `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + + `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + `\\} *else *\\{` + - `${variableMatch}\\(${stringArrayCallMatch}\\);` + + `${variableMatch}\\(${stringArrayCallMatch}\\);` + `\\}` + - ``; - const match3: string = `` + + ``; + const match3: string = + `` + `if *\\(${stringArrayCallMatch} *=== *${stringArrayCallMatch}\\) *\\{` + - `${variableMatch}\\(${stringArrayCallMatch}\\);` + + `${variableMatch}\\(${stringArrayCallMatch}\\);` + `\\} *else *\\{` + - `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + + `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + `\\}` + - ``; - const match4: string = `` + + ``; + const match4: string = + `` + `if *\\(${stringArrayCallMatch} *!== *${stringArrayCallMatch}\\) *\\{` + - `${variableMatch}\\(${stringArrayCallMatch}\\);` + + `${variableMatch}\\(${stringArrayCallMatch}\\);` + `\\} *else *\\{` + - `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + + `console\\[${stringArrayCallMatch}]\\(${stringArrayCallMatch}\\);` + `\\}` + - ``; + ``; let distribution1: number = 0, distribution2: number = 0, @@ -598,17 +575,13 @@ describe('DeadCodeInjectionTransformer', () => { let count4: number = 0; for (let i = 0; i < samplesCount; i++) { - - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (regExp1.test(obfuscatedCode)) { count1++; @@ -648,7 +621,7 @@ describe('DeadCodeInjectionTransformer', () => { const regExp: RegExp = new RegExp( `if *\\(!!\\[\\]\\) *{` + `console\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\}` + `\\}` ); let obfuscatedCode: string; @@ -656,19 +629,16 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/block-scope-is-program-node.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t add dead code in block statements with `ProgramNode` block scope', () => { + it("shouldn't add dead code in block statements with `ProgramNode` block scope", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -679,17 +649,16 @@ describe('DeadCodeInjectionTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/obfuscation-of-dead-code-block-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/obfuscation-of-dead-code-block-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - debugProtection: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + debugProtection: true + }).getObfuscatedCode(); }); it('should correctly obfuscate dead-code block statements and prevent any exposing of internal variable names', () => { @@ -757,18 +726,17 @@ describe('DeadCodeInjectionTransformer', () => { * This should never happen. */ describe('Variant #1', () => { - const functionParameterMatch: string = `` + - `\\(function\\((\\w)\\){` + - ``; - const deadCodeMatch: string = `` + + const functionParameterMatch: string = `` + `\\(function\\((\\w)\\){` + ``; + const deadCodeMatch: string = + `` + `function \\w *\\(\\w\\) *{` + - `if *\\(.{0,30}\\) *{` + - `var (\\w).*?;` + - `} *else *{` + - `return *(\\w).*?;` + - `}` + + `if *\\(.{0,30}\\) *{` + + `var (\\w).*?;` + + `} *else *{` + + `return *(\\w).*?;` + `}` + - ``; + `}` + + ``; const functionParameterRegExp: RegExp = new RegExp(functionParameterMatch); const deadCodeRegExp: RegExp = new RegExp(deadCodeMatch); @@ -778,23 +746,20 @@ describe('DeadCodeInjectionTransformer', () => { variableDeclarationIdentifierName: string | null, obfuscatedCode: string; - before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/unique-names-for-dead-code-identifiers.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/unique-names-for-dead-code-identifiers.js' + ); for (let i: number = 0; i < 100; i++) { while (true) { try { - - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); functionIdentifierName = getRegExpMatch(obfuscatedCode, functionParameterRegExp, 0); variableDeclarationIdentifierName = getRegExpMatch(obfuscatedCode, deadCodeRegExp, 0); returnIdentifierName = getRegExpMatch(obfuscatedCode, deadCodeRegExp, 1); @@ -821,18 +786,17 @@ describe('DeadCodeInjectionTransformer', () => { }); describe('Variant #2', () => { - const functionParameterMatch: string = `` + - `\\(function\\((\\w)\\){` + - ``; - const deadCodeMatch: string = `` + + const functionParameterMatch: string = `` + `\\(function\\((\\w)\\){` + ``; + const deadCodeMatch: string = + `` + `function \\w *\\(\\w\\) *{` + - `if *\\(.{0,30}\\) *{` + - `return *(\\w).{0,40};` + - `} *else *{` + - `var (\\w).*?;` + - `}` + + `if *\\(.{0,30}\\) *{` + + `return *(\\w).{0,40};` + + `} *else *{` + + `var (\\w).*?;` + `}` + - ``; + `}` + + ``; const functionParameterRegExp: RegExp = new RegExp(functionParameterMatch); const deadCodeRegExp: RegExp = new RegExp(deadCodeMatch); @@ -842,23 +806,20 @@ describe('DeadCodeInjectionTransformer', () => { variableDeclarationIdentifierName: string | null, obfuscatedCode: string; - before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/unique-names-for-dead-code-identifiers.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/unique-names-for-dead-code-identifiers.js' + ); for (let i: number = 0; i < 100; i++) { while (true) { try { - - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); functionIdentifierName = getRegExpMatch(obfuscatedCode, functionParameterRegExp, 0); returnIdentifierName = getRegExpMatch(obfuscatedCode, deadCodeRegExp, 0); variableDeclarationIdentifierName = getRegExpMatch(obfuscatedCode, deadCodeRegExp, 1); @@ -888,8 +849,7 @@ describe('DeadCodeInjectionTransformer', () => { describe('Variant #9 - block statements with empty body', () => { const regExp: RegExp = new RegExp( - `function *${variableMatch} *\\(\\) *{ *} *` + - `${variableMatch} *\\(\\); *`, + `function *${variableMatch} *\\(\\) *{ *} *` + `${variableMatch} *\\(\\); *`, 'g' ); const expectedMatchesLength: number = 5; @@ -899,16 +859,13 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/block-statement-empty-body.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(regExp); @@ -917,7 +874,7 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('shouldn\'t add dead code conditions to the block empty block statements', () => { + it("shouldn't add dead code conditions to the block empty block statements", () => { assert.isAtLeast(matchesLength, expectedMatchesLength); }); }); @@ -926,8 +883,8 @@ describe('DeadCodeInjectionTransformer', () => { describe('Variant #1: collecting of block statements', () => { const regExp: RegExp = new RegExp( `${variableMatch} *\\(\\); *` + - `var ${variableMatch} *= *0x2; *` + - `function *${variableMatch} *\\(\\) *{ *} *`, + `var ${variableMatch} *= *0x2; *` + + `function *${variableMatch} *\\(\\) *{ *} *`, 'g' ); const expectedMatchesLength: number = 5; @@ -935,18 +892,17 @@ describe('DeadCodeInjectionTransformer', () => { let matchesLength: number = 0; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/block-statement-with-scope-hoisting-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/block-statement-with-scope-hoisting-1.js' + ); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1 + }).getObfuscatedCode(); const functionMatches: RegExpMatchArray = obfuscatedCode.match(regExp); @@ -955,7 +911,7 @@ describe('DeadCodeInjectionTransformer', () => { } }); - it('shouldn\'t collect block statements with scope-hoisting', () => { + it("shouldn't collect block statements with scope-hoisting", () => { assert.equal(matchesLength, expectedMatchesLength); }); }); @@ -968,28 +924,27 @@ describe('DeadCodeInjectionTransformer', () => { `var ${variableMatch} *= *0x2; *` + `function *${variableMatch} *\\(\\) *{ *} *` + `var ${variableMatch} *= *0x3; *` + - `}`, + `}`, 'g' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/block-statement-with-scope-hoisting-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/block-statement-with-scope-hoisting-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t wrap block statements in dead code conditions', () => { + it("shouldn't wrap block statements in dead code conditions", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -998,13 +953,11 @@ describe('DeadCodeInjectionTransformer', () => { describe('Variant #11 - prevailing kind of variables of inserted code', () => { describe('Variant #1: base', () => { const variableDeclarationsRegExp: RegExp = new RegExp( - `const ${variableMatch} *= *\\[\\]; *` + - `var ${variableMatch} *= *\\[\\]; *`, + `const ${variableMatch} *= *\\[\\]; *` + `var ${variableMatch} *= *\\[\\]; *`, 'g' ); const invalidVariableDeclarationsRegExp: RegExp = new RegExp( - `var ${variableMatch} *= *\\[\\]; *` + - `var ${variableMatch} *= *\\[\\]; *`, + `var ${variableMatch} *= *\\[\\]; *` + `var ${variableMatch} *= *\\[\\]; *`, 'g' ); @@ -1022,29 +975,26 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prevailing-kind-of-variables-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1 + }).getObfuscatedCode(); }); - it('Match #1: shouldn\'t replace kinds of variables of inserted original code', () => { + it("Match #1: shouldn't replace kinds of variables of inserted original code", () => { assert.match(obfuscatedCode, variableDeclarationsRegExp); }); - it('Match #2: shouldn\'t replace kinds of variables of inserted original code', () => { + it("Match #2: shouldn't replace kinds of variables of inserted original code", () => { assert.notMatch(obfuscatedCode, invalidVariableDeclarationsRegExp); }); - it('Match #3: shouldn\'t replace kinds of variables of inserted original code', () => { + it("Match #3: shouldn't replace kinds of variables of inserted original code", () => { assert.match(obfuscatedCode, forLoopRegExp); }); - it('Match #4: shouldn\'t replace kinds of variables of inserted original code', () => { + it("Match #4: shouldn't replace kinds of variables of inserted original code", () => { assert.notMatch(obfuscatedCode, invalidForLoopRegExp); }); }); @@ -1053,11 +1003,11 @@ describe('DeadCodeInjectionTransformer', () => { describe('Variant #12 - correct integration with `stringArrayWrappersChainedCalls` option', () => { const regExp: RegExp = new RegExp( `var ${variableMatch} *= *${variableMatch}; *` + - `if *\\(${variableMatch}\\(${hexMatch}\\) *[=|!]== *${variableMatch}\\(${hexMatch}\\)\\) *\\{`+ + `if *\\(${variableMatch}\\(${hexMatch}\\) *[=|!]== *${variableMatch}\\(${hexMatch}\\)\\) *\\{` + `(?:console|${variableMatch})\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\} *else *\\{`+ + `\\} *else *\\{` + `(?:console|${variableMatch})\\[${variableMatch}\\(${hexMatch}\\)\\]\\(${variableMatch}\\(${hexMatch}\\)\\);` + - `\\}`, + `\\}`, 'g' ); const expectedMatchesLength: number = 5; @@ -1067,18 +1017,15 @@ describe('DeadCodeInjectionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input-1.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1, - stringArrayWrappersChainedCalls: true - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1, + stringArrayWrappersChainedCalls: true + }).getObfuscatedCode(); const matches: RegExpMatchArray = obfuscatedCode.match(regExp); if (matches) { @@ -1092,30 +1039,26 @@ describe('DeadCodeInjectionTransformer', () => { }); describe('Variant #13 - correct integration with `EvalCallExpressionTransformer`', () => { - const evalWithDeadCodeRegExp: RegExp = new RegExp( - `eval\\(\'if *\\(${variableMatch}`, - 'g' - ); + const evalWithDeadCodeRegExp: RegExp = new RegExp(`eval\\(\'if *\\(${variableMatch}`, 'g'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/eval-call-expression-transformer-integration.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/eval-call-expression-transformer-integration.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); console.log(obfuscatedCode); }); - it('match #1: shouldn\'t add dead code to the eval call expression', () => { + it("match #1: shouldn't add dead code to the eval call expression", () => { assert.notMatch(obfuscatedCode, evalWithDeadCodeRegExp); }); }); diff --git a/test/functional-tests/node-transformers/finalizing-transformers/directive-placement-transformer/DirectivePlacementTransformer.spec.ts b/test/functional-tests/node-transformers/finalizing-transformers/directive-placement-transformer/DirectivePlacementTransformer.spec.ts index 3ad9387a..35862d37 100644 --- a/test/functional-tests/node-transformers/finalizing-transformers/directive-placement-transformer/DirectivePlacementTransformer.spec.ts +++ b/test/functional-tests/node-transformers/finalizing-transformers/directive-placement-transformer/DirectivePlacementTransformer.spec.ts @@ -12,24 +12,18 @@ describe('DirectivePlacementTransformer', function () { describe('Variant #1: program scope', () => { describe('Variant #1: directive at the top of program scope', () => { - const directiveRegExp: RegExp = new RegExp( - '^\'use strict\';.*' + - getStringArrayRegExp(['test']).source - ); + const directiveRegExp: RegExp = new RegExp("^'use strict';.*" + getStringArrayRegExp(['test']).source); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/top-of-program-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should keep directive at the top of program scope', () => { @@ -40,8 +34,7 @@ describe('DirectivePlacementTransformer', function () { describe('Variant #2: directive-like string literal at the middle of program scope', () => { const stringArrayStorageRegExp: RegExp = getStringArrayRegExp(['test', 'use\\\\x20strict']); const directiveRegExp: RegExp = new RegExp( - 'var test *= *_0x([a-f0-9]){4}\\(0x0\\);.*' + - '_0x([a-f0-9]){4}\\(0x1\\);' + 'var test *= *_0x([a-f0-9]){4}\\(0x0\\);.*' + '_0x([a-f0-9]){4}\\(0x1\\);' ); let obfuscatedCode: string; @@ -49,14 +42,11 @@ describe('DirectivePlacementTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/middle-of-program-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add directive-like string literal to the string array', () => { @@ -73,7 +63,7 @@ describe('DirectivePlacementTransformer', function () { describe('Variant #1: directive at the top of function declaration scope', () => { const directiveRegExp: RegExp = new RegExp( 'function test\\(\\) *{ *' + - '\'use strict\'; *' + + "'use strict'; *" + 'var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4}; *' + 'var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x0\\);' ); @@ -83,15 +73,12 @@ describe('DirectivePlacementTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/top-of-function-declaration-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should keep directive at the top of function declaration scope', () => { @@ -112,28 +99,25 @@ describe('DirectivePlacementTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/middle-of-function-declaration-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should keep directive-like string literal at the middle of function declaration scope', () => { assert.match(obfuscatedCode, directiveRegExp); }); - }) + }); }); describe('Variant #3: function expression scope', () => { describe('Variant #1: directive at the top of function expression scope', () => { const directiveRegExp: RegExp = new RegExp( 'var test *= *function *\\(\\) *{ *' + - '\'use strict\'; *' + + "'use strict'; *" + 'var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4}; *' + 'var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x0\\);' ); @@ -143,15 +127,12 @@ describe('DirectivePlacementTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/top-of-function-expression-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should keep directive at the top of function expression scope', () => { @@ -172,28 +153,25 @@ describe('DirectivePlacementTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/middle-of-function-expression-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should keep directive-like string literal at the middle of function expression scope', () => { assert.match(obfuscatedCode, directiveRegExp); }); - }) + }); }); describe('Variant #4: arrow function expression scope', () => { describe('Variant #1: directive at the top of arrow function expression scope', () => { const directiveRegExp: RegExp = new RegExp( 'var test *= *\\(\\) *=> *{ *' + - '\'use strict\'; *' + + "'use strict'; *" + 'var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4}; *' + 'var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x0\\);' ); @@ -201,17 +179,16 @@ describe('DirectivePlacementTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/top-of-arrow-function-expression-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/top-of-arrow-function-expression-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should keep directive at the top of arrow function expression scope', () => { @@ -230,22 +207,21 @@ describe('DirectivePlacementTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/middle-of-arrow-function-expression-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/middle-of-arrow-function-expression-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should keep directive-like string literal at the middle of arrow function expression scope', () => { assert.match(obfuscatedCode, directiveRegExp); }); - }) + }); }); }); diff --git a/test/functional-tests/node-transformers/finalizing-transformers/escape-sequence-transformer/EscapeSequenceTransformer.spec.ts b/test/functional-tests/node-transformers/finalizing-transformers/escape-sequence-transformer/EscapeSequenceTransformer.spec.ts index 016f06f5..d20ffa39 100644 --- a/test/functional-tests/node-transformers/finalizing-transformers/escape-sequence-transformer/EscapeSequenceTransformer.spec.ts +++ b/test/functional-tests/node-transformers/finalizing-transformers/escape-sequence-transformer/EscapeSequenceTransformer.spec.ts @@ -19,17 +19,15 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/error-when-non-latin.js'); - testFunc = () => JavaScriptObfuscator.obfuscate( - code, - { + testFunc = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, stringArray: true, stringArrayThreshold: 1 - } - ); + }); }); - it('should\'t throw an error', () => { + it("should't throw an error", () => { assert.doesNotThrow(testFunc); }); }); @@ -42,14 +40,10 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - unicodeEscapeSequence: true - - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('should replace literal node value with unicode escape sequence', () => { @@ -66,18 +60,13 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumericString - ], - stringArrayThreshold: 1, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString], + stringArrayThreshold: 1, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('match #1: should replace literal node value with unicode escape sequence from string array', () => { @@ -99,14 +88,11 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-strings-option-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - reservedStrings: ['foo'], - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + reservedStrings: ['foo'], + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('match #1: should ignore reserved strings', () => { @@ -126,13 +112,10 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-strings-option-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - reservedStrings: ['a'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + reservedStrings: ['a'] + }).getObfuscatedCode(); }); it('match #1: should ignore reserved strings', () => { @@ -150,14 +133,11 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['bar'], - unicodeEscapeSequence: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['bar'], + unicodeEscapeSequence: false + }).getObfuscatedCode(); }); it('match #1: should not encode force transform string with unicode escape sequence', () => { @@ -172,15 +152,15 @@ describe('EscapeSequenceTransformer', function () { describe('Variant #6: `stringArrayWrappersCount` option enabled', () => { const stringArrayCallRegExp: RegExp = new RegExp( 'const f *= *b;.*' + - 'const foo *= *f\\(\'\\\\x30\\\\x78\\\\x30\'\\);.*' + - 'const bar *= *f\\(\'\\\\x30\\\\x78\\\\x31\'\\);.*' + - 'const baz *= *f\\(\'\\\\x30\\\\x78\\\\x32\'\\);.*' + - 'function test\\( *\\) *{' + + "const foo *= *f\\('\\\\x30\\\\x78\\\\x30'\\);.*" + + "const bar *= *f\\('\\\\x30\\\\x78\\\\x31'\\);.*" + + "const baz *= *f\\('\\\\x30\\\\x78\\\\x32'\\);.*" + + 'function test\\( *\\) *{' + 'const g *= *f;' + - 'const c *= *g\\(\'\\\\x30\\\\x78\\\\x33\'\\);' + - 'const d *= *g\\(\'\\\\x30\\\\x78\\\\x34\'\\);' + - 'const e *= *g\\(\'\\\\x30\\\\x78\\\\x35\'\\);' + - '}' + "const c *= *g\\('\\\\x30\\\\x78\\\\x33'\\);" + + "const d *= *g\\('\\\\x30\\\\x78\\\\x34'\\);" + + "const e *= *g\\('\\\\x30\\\\x78\\\\x35'\\);" + + '}' ); let obfuscatedCode: string; @@ -188,21 +168,16 @@ describe('EscapeSequenceTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumericString - ], - stringArrayThreshold: 1, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 1, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString], + stringArrayThreshold: 1, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 1, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }); it('should encode calls to the string array wrappers', () => { diff --git a/test/functional-tests/node-transformers/initializing-transformers/comments-transformer/CommentsTransformer.spec.ts b/test/functional-tests/node-transformers/initializing-transformers/comments-transformer/CommentsTransformer.spec.ts index ef1d22af..cce522b8 100644 --- a/test/functional-tests/node-transformers/initializing-transformers/comments-transformer/CommentsTransformer.spec.ts +++ b/test/functional-tests/node-transformers/initializing-transformers/comments-transformer/CommentsTransformer.spec.ts @@ -18,12 +18,9 @@ describe('CommentsTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/no-preserved-words.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should remove comments without preserved words', () => { @@ -39,12 +36,9 @@ describe('CommentsTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/preserved-words.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should keep comments with preserved words', () => { @@ -60,12 +54,9 @@ describe('CommentsTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/combined-words-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should keep comments with preserved words', () => { @@ -74,26 +65,25 @@ describe('CommentsTransformer', () => { }); describe('Variant #4: comment with preserved and non-preserved words', () => { - const regExp: RegExp = new RegExp(``+ - `^\\/\\*\\* *${lineSeparatorEscaped}` + - ` *\\* *@license *${lineSeparatorEscaped}` + - ` *\\* *test${lineSeparatorEscaped}` + - ` *\\*\\/${lineSeparatorEscaped}` + - `var test *= *0x1;` + - ` *\\/\\*\\* *@preserved *\\*\\/$` + - ``); + const regExp: RegExp = new RegExp( + `` + + `^\\/\\*\\* *${lineSeparatorEscaped}` + + ` *\\* *@license *${lineSeparatorEscaped}` + + ` *\\* *test${lineSeparatorEscaped}` + + ` *\\*\\/${lineSeparatorEscaped}` + + `var test *= *0x1;` + + ` *\\/\\*\\* *@preserved *\\*\\/$` + + `` + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/combined-words-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should keep comments with preserved words', () => { @@ -107,12 +97,9 @@ describe('CommentsTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/comments-only-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should remove comment without preserved words', () => { @@ -128,12 +115,9 @@ describe('CommentsTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/comments-only-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should keep comments with preserved words', () => { @@ -144,23 +128,21 @@ describe('CommentsTransformer', () => { describe('Variant #7: simple comment with preserved words and additional code helper is inserted', () => { describe('Variant #1: `stringArray` code helper', () => { const regExp: RegExp = new RegExp( - '^\\/\\/ *@license *test *comment *\\n*.*' + - getStringArrayRegExp(['abc']).source + '^\\/\\/ *@license *test *comment *\\n*.*' + getStringArrayRegExp(['abc']).source ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/preserved-words-additional-code-helper-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/preserved-words-additional-code-helper-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should keep comments with preserved words and move heading comment to the top', () => { @@ -171,22 +153,21 @@ describe('CommentsTransformer', () => { describe('Variant #2: `transformObjectKeys` code helper', () => { const regExp: RegExp = new RegExp( '^\\/\\/ *@license *test *comment *\\n*var _0x([a-f0-9]){4,6} *= *{};\\n*' + - '_0x([a-f0-9]){4,6}\\[\'foo\'] *= *\'bar\';\\n*' + - 'var test *= *_0x([a-f0-9]){4,6};$' + "_0x([a-f0-9]){4,6}\\['foo'] *= *'bar';\\n*" + + 'var test *= *_0x([a-f0-9]){4,6};$' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/preserved-words-additional-code-helper-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/preserved-words-additional-code-helper-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should keep comments with preserved words and move heading comment to the top', () => { diff --git a/test/functional-tests/node-transformers/preparing-transformers/eval-call-expression-transformer/EvalCallExpressionTransformer.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/eval-call-expression-transformer/EvalCallExpressionTransformer.spec.ts index 0032215d..b438ae1c 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/eval-call-expression-transformer/EvalCallExpressionTransformer.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/eval-call-expression-transformer/EvalCallExpressionTransformer.spec.ts @@ -22,12 +22,9 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-reference.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionIdentifierName = getRegExpMatch(obfuscatedCode, functionIdentifierRegExp); variableReferenceIdentifierName = getRegExpMatch(obfuscatedCode, evalExpressionRegExp); @@ -53,12 +50,9 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/call-expression-identifier-reference.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionIdentifierName = getRegExpMatch(obfuscatedCode, functionIdentifierRegExp); variableReferenceIdentifierName = getRegExpMatch(obfuscatedCode, evalExpressionRegExp); @@ -81,12 +75,9 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-statements-eval.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should obfuscate eval string', () => { @@ -97,24 +88,20 @@ describe('EvalCallExpressionTransformer', () => { describe('Variant #4: string array calls wrapper call', () => { describe('Variant #1: hexadecimal number indexes type', () => { const stringArrayRegExp: RegExp = getStringArrayRegExp(['log', 'bar']); - const stringArrayCallsWrapperRegExp: RegExp = /eval *\('console\[_0x([a-f0-9]){4,6}\(0\)]\(_0x([a-f0-9]){4,6}\(1\)\);'\);/; + const stringArrayCallsWrapperRegExp: RegExp = + /eval *\('console\[_0x([a-f0-9]){4,6}\(0\)]\(_0x([a-f0-9]){4,6}\(1\)\);'\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-calls-wrapper-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber - ], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber], + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should add strings from eval expression to the string array', () => { @@ -128,24 +115,20 @@ describe('EvalCallExpressionTransformer', () => { describe('Variant #1: hexadecimal numeric string indexes type', () => { const stringArrayRegExp: RegExp = getStringArrayRegExp(['log', 'bar']); - const stringArrayCallsWrapperRegExp: RegExp = /eval *\('console\[_0x([a-f0-9]){4,6}\(\\'0x0\\'\)]\(_0x([a-f0-9]){4,6}\(\\'0x1\\'\)\);'\);/; + const stringArrayCallsWrapperRegExp: RegExp = + /eval *\('console\[_0x([a-f0-9]){4,6}\(\\'0x0\\'\)]\(_0x([a-f0-9]){4,6}\(\\'0x1\\'\)\);'\);/; let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-calls-wrapper-call.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumericString - ], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString], + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should add strings from eval expression to the string array', () => { @@ -169,12 +152,9 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/eval-expression-as-argument.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionIdentifierName = getRegExpMatch(obfuscatedCode, functionIdentifierRegExp); variableReferenceIdentifierName = getRegExpMatch(obfuscatedCode, evalExpressionRegExp); @@ -190,15 +170,17 @@ describe('EvalCallExpressionTransformer', () => { }); describe('Variant #6: nested eval expressions', () => { - const functionIdentifierRegExp: RegExp = /function *_0x(?:[a-f0-9]){4,6} *\((_0x(?:[a-f0-9]){4,6}), *(_0x(?:[a-f0-9]){4,6})\)/; - const evalExpressionMatch: string = `` + + const functionIdentifierRegExp: RegExp = + /function *_0x(?:[a-f0-9]){4,6} *\((_0x(?:[a-f0-9]){4,6}), *(_0x(?:[a-f0-9]){4,6})\)/; + const evalExpressionMatch: string = + `` + `eval *\\('` + - `var (_0x(?:[a-f0-9]){4,6}) *= *(_0x(?:[a-f0-9]){4,6}) *\\+ *(_0x(?:[a-f0-9]){4,6});` + - `eval\\(\\\\'` + - `(_0x(?:[a-f0-9]){4,6}) *\\+ *(_0x(?:[a-f0-9]){4,6});` + - `\\\\'\\);` + + `var (_0x(?:[a-f0-9]){4,6}) *= *(_0x(?:[a-f0-9]){4,6}) *\\+ *(_0x(?:[a-f0-9]){4,6});` + + `eval\\(\\\\'` + + `(_0x(?:[a-f0-9]){4,6}) *\\+ *(_0x(?:[a-f0-9]){4,6});` + + `\\\\'\\);` + `'\\);` + - ``; + ``; const evalExpressionRegExp: RegExp = new RegExp(evalExpressionMatch); const expectedEvaluationResult: number = 4; @@ -215,12 +197,9 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/nested-eval-expressions.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionIdentifierAName = getRegExpMatch(obfuscatedCode, functionIdentifierRegExp, 0); functionIdentifierBName = getRegExpMatch(obfuscatedCode, functionIdentifierRegExp, 1); @@ -267,17 +246,14 @@ describe('EvalCallExpressionTransformer', () => { describe('Variant #7: wrong eval string', () => { const evalExpressionRegExp: RegExp = /eval *\('~'\);/; - let obfuscatedCode: string + let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrong-eval-string.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should skip obfuscation of eval string', () => { @@ -296,12 +272,9 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/eval-expression-template-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionIdentifierName = getRegExpMatch(obfuscatedCode, functionIdentifierRegExp); variableReferenceIdentifierName = getRegExpMatch(obfuscatedCode, evalExpressionRegExp); @@ -318,13 +291,14 @@ describe('EvalCallExpressionTransformer', () => { describe('Variant #9: integration with control flow flattening', () => { const variableMatch: string = '_0x([a-f0-9]){4,6}'; - const controlFlowStorageNodeMatch: string = `` + + const controlFlowStorageNodeMatch: string = + `` + `var ${variableMatch} *= *\\{` + - `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + - `return *${variableMatch} *\\+ *${variableMatch};` + - `\\}` + + `'\\w{5}' *: *function *\\(${variableMatch}, *${variableMatch}\\) *\\{` + + `return *${variableMatch} *\\+ *${variableMatch};` + + `\\}` + `\\};` + - ``; + ``; const controlFlowStorageNodeRegExp: RegExp = new RegExp(controlFlowStorageNodeMatch); const evalExpressionRegExp: RegExp = new RegExp( `eval *\\('${variableMatch}\\[\\\\'\\w{5}\\\\']\\(${variableMatch}, *${variableMatch}\\);'\\);` @@ -335,14 +309,11 @@ describe('EvalCallExpressionTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/control-flow-flattening-integration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('should add control flow storage node', () => { diff --git a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/black-list-obfuscating-guard/BlackListObfuscatingGuard.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/black-list-obfuscating-guard/BlackListObfuscatingGuard.spec.ts index 2b08f7ea..55da05b2 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/black-list-obfuscating-guard/BlackListObfuscatingGuard.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/black-list-obfuscating-guard/BlackListObfuscatingGuard.spec.ts @@ -9,7 +9,7 @@ import { readFileAsString } from '../../../../../helpers/readFileAsString'; describe('BlackListObfuscatingGuard', () => { describe('check', () => { - describe('`\'use strict\';` operator', () => { + describe("`'use strict';` operator", () => { const useStrictOperatorRegExp: RegExp = /'use *strict';/; const stringArrayLatinRegExp: RegExp = getStringArrayRegExp(['abc']); const stringArrayCallRegExp: RegExp = /var test *= *_0x(\w){4}\(0x0\)/; @@ -19,17 +19,14 @@ describe('BlackListObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/use-strict-operator.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t obfuscate `use strict` operator', () => { + it("match #1: shouldn't obfuscate `use strict` operator", () => { assert.match(obfuscatedCode, useStrictOperatorRegExp); }); diff --git a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/conditional-comment-obfuscating-guard/ConditionalCommentObfuscatingGuard.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/conditional-comment-obfuscating-guard/ConditionalCommentObfuscatingGuard.spec.ts index 0d77c570..c8822dfb 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/conditional-comment-obfuscating-guard/ConditionalCommentObfuscatingGuard.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/conditional-comment-obfuscating-guard/ConditionalCommentObfuscatingGuard.spec.ts @@ -19,12 +19,9 @@ describe('ConditionalCommentObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should remove `disable` conditional comment from the code', () => { @@ -56,12 +53,9 @@ describe('ConditionalCommentObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/disable-and-enable-comments-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should remove `disable` conditional comment from the code', () => { @@ -94,13 +88,10 @@ describe('ConditionalCommentObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/disable-and-enable-comments-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('match #1: should ignore variable declaration after `disable` conditional comment', () => { @@ -121,12 +112,9 @@ describe('ConditionalCommentObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/disable-from-beginning.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should ignore variable declaration after `disable` conditional comment', () => { @@ -139,7 +127,8 @@ describe('ConditionalCommentObfuscatingGuard', () => { }); describe('Variant #5: `disable` and `enable` conditional comments with dead code injection', () => { - const obfuscatedFunctionExpressionRegExp: RegExp = /var _0x([a-f0-9]){4,6} *= *function *\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\) *{/g; + const obfuscatedFunctionExpressionRegExp: RegExp = + /var _0x([a-f0-9]){4,6} *= *function *\(_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}, *_0x([a-f0-9]){4,6}\) *{/g; const expectedObfuscatedFunctionExpressionLength: number = 3; const ignoredFunctionExpression1RegExp: RegExp = /var bar *= *function *\(a, *b, *c\) *{/; @@ -158,21 +147,17 @@ describe('ConditionalCommentObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/dead-code-injection.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1 + }).getObfuscatedCode(); const obfuscatedFunctionExpressionMatches: RegExpMatchArray | null = obfuscatedCode.match( obfuscatedFunctionExpressionRegExp ); - const obfuscatedFunctionCallMatches: RegExpMatchArray | null = obfuscatedCode.match( - obfuscatedFunctionCallRegExp - ); + const obfuscatedFunctionCallMatches: RegExpMatchArray | null = + obfuscatedCode.match(obfuscatedFunctionCallRegExp); obfuscatedFunctionExpressionMatchesLength = obfuscatedFunctionExpressionMatches ? obfuscatedFunctionExpressionMatches.length @@ -209,7 +194,8 @@ describe('ConditionalCommentObfuscatingGuard', () => { }); describe('Variant #6: `disable` and `enable` conditional comments with control flow flattening', () => { - const obfuscatedVariableDeclarationRegExp: RegExp = /var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\['\w{5}'];/; + const obfuscatedVariableDeclarationRegExp: RegExp = + /var _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\['\w{5}'];/; const ignoredVariableDeclarationRegExp: RegExp = /var bar *= *'bar';/; let obfuscatedCode: string; @@ -217,14 +203,11 @@ describe('ConditionalCommentObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/control-flow-flattening.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should obfuscate variable declaration before `disable` conditional comment', () => { diff --git a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/force-transform-string-obfuscating-guard/ForceTransformStringObfuscatingGuard.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/force-transform-string-obfuscating-guard/ForceTransformStringObfuscatingGuard.spec.ts index d4d0784a..85be4c19 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/force-transform-string-obfuscating-guard/ForceTransformStringObfuscatingGuard.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/force-transform-string-obfuscating-guard/ForceTransformStringObfuscatingGuard.spec.ts @@ -11,26 +11,20 @@ import { readFileAsString } from '../../../../../helpers/readFileAsString'; describe('ForceTransformStringObfuscatingGuard', () => { describe('check', () => { describe('`forceTransformStrings` option is enabled', () => { - const obfuscatingGuardRegExp: RegExp = new RegExp( - 'var foo *= *\'foo\';.*' + - 'var bar *= *b\\(0x0\\);' - ); + const obfuscatingGuardRegExp: RegExp = new RegExp("var foo *= *'foo';.*" + 'var bar *= *b\\(0x0\\);'); let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/base-behaviour.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['bar'], - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['bar'], + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); it('match #1: should obfuscate force transform strings', () => { @@ -39,29 +33,23 @@ describe('ForceTransformStringObfuscatingGuard', () => { }); describe('`forceTransformStrings` option is disabled', () => { - const obfuscatingGuardRegExp: RegExp = new RegExp( - 'var foo *= *\'foo\';' + - 'var bar *= *\'bar\';' - ); + const obfuscatingGuardRegExp: RegExp = new RegExp("var foo *= *'foo';" + "var bar *= *'bar';"); let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/base-behaviour.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: [], - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: [], + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t obfuscate strings', () => { + it("match #1: shouldn't obfuscate strings", () => { assert.match(obfuscatedCode, obfuscatingGuardRegExp); }); }); diff --git a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/ignored-import-obfuscating-guard/IgnoredImportObfuscatingGuard.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/ignored-import-obfuscating-guard/IgnoredImportObfuscatingGuard.spec.ts index fe6e7167..ea77a67a 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/ignored-import-obfuscating-guard/IgnoredImportObfuscatingGuard.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/ignored-import-obfuscating-guard/IgnoredImportObfuscatingGuard.spec.ts @@ -10,10 +10,10 @@ describe('IgnoredImportObfuscatingGuard', () => { describe('check', () => { describe('`ignoreImports` option is enabled', () => { const obfuscatingGuardRegExp: RegExp = new RegExp( - 'const foo *= *require\\(\'\\./foo\'\\);.*' + - 'import _0x(?:[a-f0-9]){4,6} from *\'\\./bar\';.*' + - 'const baz *= *_0x(?:[a-f0-9]){4,6}\\(0x0\\);.*' + - 'const bark *= *await import\\(\'\\./bark\'\\);' + "const foo *= *require\\('\\./foo'\\);.*" + + "import _0x(?:[a-f0-9]){4,6} from *'\\./bar';.*" + + 'const baz *= *_0x(?:[a-f0-9]){4,6}\\(0x0\\);.*' + + "const bark *= *await import\\('\\./bark'\\);" ); let obfuscatedCode: string; @@ -21,18 +21,15 @@ describe('IgnoredImportObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/base-behaviour.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ignoreImports: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ignoreImports: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t obfuscate imports', () => { + it("match #1: shouldn't obfuscate imports", () => { assert.match(obfuscatedCode, obfuscatingGuardRegExp); }); }); @@ -40,9 +37,9 @@ describe('IgnoredImportObfuscatingGuard', () => { describe('`ignoreImports` option is disabled', () => { const obfuscatingGuardRegExp: RegExp = new RegExp( 'const foo *= *require\\(_0x(?:[a-f0-9]){4,6}\\(0x0\\)\\);.*' + - 'import _0x(?:[a-f0-9]){4,6} from *\'\\./bar\';.*' + - 'const baz *= *_0x(?:[a-f0-9]){4,6}\\(0x1\\);.*' + - 'const bark *= *await import\\(_0x(?:[a-f0-9]){4,6}\\(0x2\\)\\);' + "import _0x(?:[a-f0-9]){4,6} from *'\\./bar';.*" + + 'const baz *= *_0x(?:[a-f0-9]){4,6}\\(0x1\\);.*' + + 'const bark *= *await import\\(_0x(?:[a-f0-9]){4,6}\\(0x2\\)\\);' ); let obfuscatedCode: string; @@ -50,15 +47,12 @@ describe('IgnoredImportObfuscatingGuard', () => { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/base-behaviour.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - ignoreImports: false, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + ignoreImports: false, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should obfuscate imports', () => { diff --git a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/reserved-string-obfuscating-guard/ReservedStringObfuscatingGuard.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/reserved-string-obfuscating-guard/ReservedStringObfuscatingGuard.spec.ts index 206ec658..2b25bac2 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/reserved-string-obfuscating-guard/ReservedStringObfuscatingGuard.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/obfuscating-guards/reserved-string-obfuscating-guard/ReservedStringObfuscatingGuard.spec.ts @@ -9,46 +9,42 @@ import { readFileAsString } from '../../../../../helpers/readFileAsString'; describe('ReservedStringObfuscatingGuard', () => { describe('check', () => { describe('`reservedStrings` option is enabled', () => { - const obfuscatingGuardRegExp: RegExp = /var test1 *= *'foo' *\+ *'foo'; *var test2 *= *'barbar'; *var test3 *= *'baz' *\+ *'baz';/; + const obfuscatingGuardRegExp: RegExp = + /var test1 *= *'foo' *\+ *'foo'; *var test2 *= *'barbar'; *var test3 *= *'baz' *\+ *'baz';/; let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/base-behaviour.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - reservedStrings: ['bar'], - splitStrings: true, - splitStringsChunkLength: 3 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + reservedStrings: ['bar'], + splitStrings: true, + splitStringsChunkLength: 3 + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t obfuscate reserved strings', () => { + it("match #1: shouldn't obfuscate reserved strings", () => { assert.match(obfuscatedCode, obfuscatingGuardRegExp); }); }); describe('`reservedStrings` option is disabled', () => { - const obfuscatingGuardRegExp: RegExp = /var test1 *= *'foo' *\+ *'foo'; *var test2 *= *'bar' *\+ *'bar'; *var test3 *= *'baz' *\+ *'baz';/; + const obfuscatingGuardRegExp: RegExp = + /var test1 *= *'foo' *\+ *'foo'; *var test2 *= *'bar' *\+ *'bar'; *var test3 *= *'baz' *\+ *'baz';/; let obfuscatedCode: string; beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/base-behaviour.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - reservedStrings: [], - splitStrings: true, - splitStringsChunkLength: 3 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + reservedStrings: [], + splitStrings: true, + splitStringsChunkLength: 3 + }).getObfuscatedCode(); }); it('match #1: should obfuscate all strings', () => { diff --git a/test/functional-tests/node-transformers/preparing-transformers/variable-preserve-transformer/VariablePreserveTransformer.spec.ts b/test/functional-tests/node-transformers/preparing-transformers/variable-preserve-transformer/VariablePreserveTransformer.spec.ts index 17895c56..1aab5aa1 100644 --- a/test/functional-tests/node-transformers/preparing-transformers/variable-preserve-transformer/VariablePreserveTransformer.spec.ts +++ b/test/functional-tests/node-transformers/preparing-transformers/variable-preserve-transformer/VariablePreserveTransformer.spec.ts @@ -21,17 +21,16 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-identifier-name-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-identifier-name-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should generate non-preserved name for string array storage', () => { @@ -53,18 +52,17 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/string-array-storage-identifier-name-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/string-array-storage-identifier-name-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - renameGlobals: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + renameGlobals: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should generate non-preserved name for string array storage', () => { @@ -85,16 +83,15 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/transform-object-keys-identifier-name-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/transform-object-keys-identifier-name-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should generate non-preserved name for `transformObjectKeys` identifier', () => { @@ -113,17 +110,16 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/transform-object-keys-identifier-name-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/transform-object-keys-identifier-name-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - renameGlobals: true, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + renameGlobals: true, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('should generate non-preserved name for `transformObjectKeys` identifier', () => { @@ -146,14 +142,11 @@ describe('VariablePreserveTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/ignored-node-identifier-name-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + renameGlobals: true + }).getObfuscatedCode(); }); it('should generate non-preserved name for global identifier', () => { @@ -176,16 +169,15 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/destructed-object-property-identifier-name-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/destructed-object-property-identifier-name-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + renameGlobals: false + }).getObfuscatedCode(); }); it('should generate non-preserved name for variable name', () => { @@ -205,16 +197,15 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/destructed-object-property-identifier-name-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/destructed-object-property-identifier-name-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + renameGlobals: true + }).getObfuscatedCode(); }); it('should generate non-preserved name for variable declaration', () => { @@ -238,16 +229,15 @@ describe('VariablePreserveTransformer', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/destructed-object-property-identifier-name-3.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/destructed-object-property-identifier-name-3.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: 'mangled', - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: 'mangled', + renameGlobals: false + }).getObfuscatedCode(); }); it('should generate non-preserved name for variable declaration', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/identifier-replacer/IdentifierReplacer.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/identifier-replacer/IdentifierReplacer.spec.ts index 42c8bacc..26da60ef 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/identifier-replacer/IdentifierReplacer.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/identifier-replacer/IdentifierReplacer.spec.ts @@ -14,20 +14,14 @@ describe('IdentifierReplacer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/local-reserved-names.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - reservedNames: ['[abc|ghi]'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + reservedNames: ['[abc|ghi]'] + }).getObfuscatedCode(); }); it('Should keep reserved names without transformations when `reservedNames` option is enabled', () => { - assert.match( - obfuscatedCode, - /var abc *= *0x1; *var _0x([a-f0-9]){4,6} *= *0x2; *var ghi *= *0x3;/ - ); + assert.match(obfuscatedCode, /var abc *= *0x1; *var _0x([a-f0-9]){4,6} *= *0x2; *var ghi *= *0x3;/); }); }); @@ -37,21 +31,15 @@ describe('IdentifierReplacer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/global-reserved-names.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - reservedNames: ['[abc|ghi]'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + reservedNames: ['[abc|ghi]'] + }).getObfuscatedCode(); }); it('Should keep reserved names without transformations when `reservedNames` option is enabled', () => { - assert.match( - obfuscatedCode, - /var abc *= *0x1; *var _0x([a-f0-9]){4,6} *= *0x2; *var ghi *= *0x3;/ - ); + assert.match(obfuscatedCode, /var abc *= *0x1; *var _0x([a-f0-9]){4,6} *= *0x2; *var ghi *= *0x3;/); }); }); }); diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/labeled-statement-transformer/LabeledStatementTransformer.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/labeled-statement-transformer/LabeledStatementTransformer.spec.ts index 38cef9d9..9ac6de41 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/labeled-statement-transformer/LabeledStatementTransformer.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/labeled-statement-transformer/LabeledStatementTransformer.spec.ts @@ -14,19 +14,16 @@ describe('LabeledStatementTransformer', () => { const breakStatementRegExp: RegExp = /break *(_0x([a-f0-9]){4,6});/; let obfuscatedCode: string, - firstMatch: string|undefined, - secondMatch: string|undefined, - thirdMatch: string|undefined; + firstMatch: string | undefined, + secondMatch: string | undefined, + thirdMatch: string | undefined; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); firstMatch = getRegExpMatch(obfuscatedCode, labeledStatementRegExp); secondMatch = getRegExpMatch(obfuscatedCode, continueStatementRegExp); diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/catch-clause/CatchClause.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/catch-clause/CatchClause.spec.ts index 466d996b..2c6db06d 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/catch-clause/CatchClause.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/catch-clause/CatchClause.spec.ts @@ -16,18 +16,14 @@ describe('ScopeIdentifiersTransformer CatchClause identifiers', () => { const paramNameRegExp: RegExp = /catch *\((_0x([a-f0-9]){4,6})\) *\{/; const bodyParamNameRegExp: RegExp = /console\['log'\]\((_0x([a-f0-9]){4,6})\);/; - let firstMatch: string | undefined, - secondMatch: string | undefined; + let firstMatch: string | undefined, secondMatch: string | undefined; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); firstMatch = getRegExpMatch(obfuscatedCode, paramNameRegExp); secondMatch = getRegExpMatch(obfuscatedCode, bodyParamNameRegExp); }); @@ -54,19 +50,16 @@ describe('ScopeIdentifiersTransformer CatchClause identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform function parameter object pattern identifier', () => { + it("match #1: shouldn't transform function parameter object pattern identifier", () => { assert.match(obfuscatedCode, functionParameterMatch); }); - it('match #2: shouldn\'t transform function parameter object pattern identifier', () => { + it("match #2: shouldn't transform function parameter object pattern identifier", () => { assert.match(obfuscatedCode, functionBodyMatch); }); }); @@ -78,12 +71,9 @@ describe('ScopeIdentifiersTransformer CatchClause identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/optional-catch-binding.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform catch clause node', () => { @@ -102,15 +92,12 @@ describe('ScopeIdentifiersTransformer CatchClause identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/global-variable-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform variable identifier if `renameGlobals` option is disabled', () => { + it("match #1: shouldn't transform variable identifier if `renameGlobals` option is disabled", () => { assert.match(obfuscatedCode, globalVariableRegExp); }); }); @@ -121,13 +108,10 @@ describe('ScopeIdentifiersTransformer CatchClause identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/global-variable-scope.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('match #1: should transform variable identifier if `renameGlobals` option is enabled', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts index 2be6ed5d..989eb4d9 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts @@ -16,19 +16,14 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { const classNameIdentifierRegExp: RegExp = /class *(_0x[a-f0-9]{4,6}) *\{/; const classCallIdentifierRegExp: RegExp = /new *(_0x[a-f0-9]{4,6}) *\( *\);/; - let obfuscatedCode: string, - classNameIdentifier: string, - classCallIdentifier: string; + let obfuscatedCode: string, classNameIdentifier: string, classCallIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); classCallIdentifier = getRegExpMatch(obfuscatedCode, classCallIdentifierRegExp); }); @@ -47,21 +42,20 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/parent-block-scope-is-program-node.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform class name', () => { + it("match #1: shouldn't transform class name", () => { assert.match(obfuscatedCode, classNameIdentifierRegExp); }); - it('match #2: shouldn\'t transform class name', () => { + it("match #2: shouldn't transform class name", () => { assert.match(obfuscatedCode, classCallIdentifierRegExp); }); }); @@ -75,26 +69,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - target: ObfuscationTarget.Browser - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + target: ObfuscationTarget.Browser + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform class name', () => { + it("match #1: shouldn't transform class name", () => { assert.match(obfuscatedCode, classNameIdentifierRegExp); }); - it('match #2: shouldn\'t transform class name reference outside of class', () => { + it("match #2: shouldn't transform class name reference outside of class", () => { assert.match(obfuscatedCode, outerClassNameReferenceRegExp); }); - it('match #3: shouldn\'t transform class name reference inside class', () => { + it("match #3: shouldn't transform class name reference inside class", () => { assert.match(obfuscatedCode, innerClassNameReferenceRegExp); }); }); @@ -110,19 +103,24 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-function-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-function-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - target: ObfuscationTarget.Browser - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + target: ObfuscationTarget.Browser + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -156,26 +154,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - target: ObfuscationTarget.Node - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + target: ObfuscationTarget.Node + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform class name', () => { + it("match #1: shouldn't transform class name", () => { assert.match(obfuscatedCode, classNameIdentifierRegExp); }); - it('match #2: shouldn\'t transform class name reference outside of class', () => { + it("match #2: shouldn't transform class name reference outside of class", () => { assert.match(obfuscatedCode, outerClassNameReferenceRegExp); }); - it('match #3: shouldn\'t transform class name reference inside class', () => { + it("match #3: shouldn't transform class name reference inside class", () => { assert.match(obfuscatedCode, innerClassNameReferenceRegExp); }); }); @@ -191,19 +188,24 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-function-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-function-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - target: ObfuscationTarget.Node - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + target: ObfuscationTarget.Node + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -237,26 +239,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - target: ObfuscationTarget.ServiceWorker - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + target: ObfuscationTarget.ServiceWorker + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform class name', () => { + it("match #1: shouldn't transform class name", () => { assert.match(obfuscatedCode, classNameIdentifierRegExp); }); - it('match #2: shouldn\'t transform class name reference outside of class', () => { + it("match #2: shouldn't transform class name reference outside of class", () => { assert.match(obfuscatedCode, outerClassNameReferenceRegExp); }); - it('match #3: shouldn\'t transform class name reference inside class', () => { + it("match #3: shouldn't transform class name reference inside class", () => { assert.match(obfuscatedCode, innerClassNameReferenceRegExp); }); }); @@ -272,19 +273,24 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-function-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-function-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - target: ObfuscationTarget.ServiceWorker - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + target: ObfuscationTarget.ServiceWorker + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -318,15 +324,14 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/parent-block-scope-is-program-node.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('match #1: should transform class name', () => { @@ -345,15 +350,14 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/rename-globals-identifier-transformation.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/rename-globals-identifier-transformation.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('match #1: should transform identifier name inside class method', () => { @@ -377,20 +381,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - target: ObfuscationTarget.Browser - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + target: ObfuscationTarget.Browser + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -425,20 +434,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-function-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-function-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - target: ObfuscationTarget.Browser - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + target: ObfuscationTarget.Browser + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -475,20 +489,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - target: ObfuscationTarget.Node - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + target: ObfuscationTarget.Node + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -523,20 +542,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-function-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-function-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - target: ObfuscationTarget.Node - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + target: ObfuscationTarget.Node + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -573,20 +597,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - target: ObfuscationTarget.ServiceWorker - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + target: ObfuscationTarget.ServiceWorker + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -621,20 +650,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let innerClassNameReferenceIdentifierName: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/class-name-references-function-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/class-name-references-function-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - target: ObfuscationTarget.ServiceWorker - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + target: ObfuscationTarget.ServiceWorker + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); - outerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, outerClassNameReferenceRegExp); - innerClassNameReferenceIdentifierName = getRegExpMatch(obfuscatedCode, innerClassNameReferenceRegExp); + outerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + outerClassNameReferenceRegExp + ); + innerClassNameReferenceIdentifierName = getRegExpMatch( + obfuscatedCode, + innerClassNameReferenceRegExp + ); }); it('match #1: should transform class name', () => { @@ -661,7 +695,7 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { }); }); - describe('Variant #3: preserved identifier names shouldn\'t be used as identifier names', () => { + describe("Variant #3: preserved identifier names shouldn't be used as identifier names", () => { const classDeclarationRegExp: RegExp = /class *e *{/; const variableDeclarationsRegExp: RegExp = /let f, *g, *h, *i;/; const classReferenceRegExp: RegExp = /new e\(\);/; @@ -669,26 +703,25 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevent-using-of-preserved-identifiers.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevent-using-of-preserved-identifiers.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); - it('Match #1: shouldn\'t use preserved identifier name as class declaration name', () => { + it("Match #1: shouldn't use preserved identifier name as class declaration name", () => { assert.match(obfuscatedCode, classDeclarationRegExp); }); - it('Match #2: shouldn\'t use preserved identifier name as variable declarations', () => { + it("Match #2: shouldn't use preserved identifier name as variable declarations", () => { assert.match(obfuscatedCode, variableDeclarationsRegExp); }); - it('Match #3: shouldn\'t use preserved identifier name as class reference identifier', () => { + it("Match #3: shouldn't use preserved identifier name as class reference identifier", () => { assert.match(obfuscatedCode, classReferenceRegExp); }); }); @@ -701,16 +734,13 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/named-export.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); - it('shouldn\'t transform identifiers in named export', () => { + it("shouldn't transform identifiers in named export", () => { assert.match(obfuscatedCode, namedExportRegExp); }); }); @@ -724,13 +754,10 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-export.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should transform identifiers in variable declaration', () => { @@ -750,13 +777,10 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-export-inline.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should produce correct code', () => { @@ -772,12 +796,9 @@ describe('ScopeIdentifiersTransformer ClassDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/super-class-expression-parenthesis.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should keep super class expression parenthesis', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-expression/ClassExpression.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-expression/ClassExpression.spec.ts index e5e07857..5ea1c3c5 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-expression/ClassExpression.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/class-expression/ClassExpression.spec.ts @@ -13,19 +13,14 @@ describe('ScopeIdentifiersTransformer ClassExpression identifiers', () => { const classNameIdentifierRegExp: RegExp = /var (_0x[a-f0-9]{4,6}) *= *class *\{/; const classCallIdentifierRegExp: RegExp = /new *(_0x[a-f0-9]{4,6}) *\( *\);/; - let obfuscatedCode: string, - classNameIdentifier: string, - classCallIdentifier: string; + let obfuscatedCode: string, classNameIdentifier: string, classCallIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/base.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); classNameIdentifier = getRegExpMatch(obfuscatedCode, classNameIdentifierRegExp); classCallIdentifier = getRegExpMatch(obfuscatedCode, classCallIdentifierRegExp); }); @@ -44,19 +39,16 @@ describe('ScopeIdentifiersTransformer ClassExpression identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform class name', () => { + it("match #1: shouldn't transform class name", () => { assert.match(obfuscatedCode, classNameIdentifierRegExp); }); - it('match #2: shouldn\'t transform class name', () => { + it("match #2: shouldn't transform class name", () => { assert.match(obfuscatedCode, classCallIdentifierRegExp); }); }); diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts index 6c6bc402..9fc22b04 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts @@ -14,19 +14,14 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { const functionNameIdentifierRegExp: RegExp = /function *(_0x[a-f0-9]{4,6}) *\(\) *\{/; const functionCallIdentifierRegExp: RegExp = /(_0x[a-f0-9]{4,6}) *\( *\);/; - let obfuscatedCode: string, - functionNameIdentifier: string, - functionCallIdentifier: string; + let obfuscatedCode: string, functionNameIdentifier: string, functionCallIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionNameIdentifier = getRegExpMatch(obfuscatedCode, functionNameIdentifierRegExp); functionCallIdentifier = getRegExpMatch(obfuscatedCode, functionCallIdentifierRegExp); }); @@ -44,21 +39,20 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/parent-block-scope-is-program-node.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform function name', () => { + it("match #1: shouldn't transform function name", () => { assert.match(obfuscatedCode, functionNameIdentifierRegExp); }); - it('match #2: shouldn\'t transform function name', () => { + it("match #2: shouldn't transform function name", () => { assert.match(obfuscatedCode, functionCallIdentifierRegExp); }); }); @@ -70,15 +64,14 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/parent-block-scope-is-program-node.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('match #1: should transform function name', () => { @@ -95,19 +88,14 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { const functionNameIdentifierRegExp: RegExp = /function *\* *(_0x[a-f0-9]{4,6}) *\(\) *\{/; const functionCallIdentifierRegExp: RegExp = /let _0x[a-f0-9]{4,6} *= *(_0x[a-f0-9]{4,6}) *\( *\);/; - let obfuscatedCode: string, - functionNameIdentifier: string, - functionCallIdentifier: string; + let obfuscatedCode: string, functionNameIdentifier: string, functionCallIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/generator-function.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionNameIdentifier = getRegExpMatch(obfuscatedCode, functionNameIdentifierRegExp); functionCallIdentifier = getRegExpMatch(obfuscatedCode, functionCallIdentifierRegExp); }); @@ -121,19 +109,14 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { const functionNameIdentifierRegExp: RegExp = /async *function *(_0x[a-f0-9]{4,6}) *\(\) *\{/; const functionCallIdentifierRegExp: RegExp = /await *(_0x[a-f0-9]{4,6}) *\( *\);/; - let obfuscatedCode: string, - functionNameIdentifier: string, - functionCallIdentifier: string; + let obfuscatedCode: string, functionNameIdentifier: string, functionCallIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/async-function.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); functionNameIdentifier = getRegExpMatch(obfuscatedCode, functionNameIdentifierRegExp); functionCallIdentifier = getRegExpMatch(obfuscatedCode, functionCallIdentifierRegExp); }); @@ -143,7 +126,7 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { }); }); - describe('Variant #5: preserved identifier names shouldn\'t be used as identifier names', () => { + describe("Variant #5: preserved identifier names shouldn't be used as identifier names", () => { describe('Variant #1', () => { const functionDeclarationRegExp: RegExp = /function *e\(\) *{/; const variableDeclarationsRegExp: RegExp = /let f, *g, *h, *i;/; @@ -151,22 +134,21 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevent-using-of-preserved-identifiers-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevent-using-of-preserved-identifiers-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); - it('Match #1: shouldn\'t use preserved identifier name as function declaration name', () => { + it("Match #1: shouldn't use preserved identifier name as function declaration name", () => { assert.match(obfuscatedCode, functionDeclarationRegExp); }); - it('Match #2: shouldn\'t use preserved identifier name as variable declarations', () => { + it("Match #2: shouldn't use preserved identifier name as variable declarations", () => { assert.match(obfuscatedCode, variableDeclarationsRegExp); }); }); @@ -180,16 +162,13 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/named-export.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); - it('shouldn\'t transform identifiers in named export', () => { + it("shouldn't transform identifiers in named export", () => { assert.match(obfuscatedCode, namedExportRegExp); }); }); @@ -203,13 +182,10 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-export.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should transform identifiers in variable declaration', () => { @@ -229,13 +205,10 @@ describe('ScopeIdentifiersTransformer FunctionDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-export-inline.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should produce correct code', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function/Function.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function/Function.spec.ts index 46cd48d1..fc908e90 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function/Function.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/function/Function.spec.ts @@ -26,21 +26,19 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); - const functionParamIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionParamIdentifierRegExp); - const functionBodyIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionBodyIdentifierRegExp); - const variableDeclarationIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(variableDeclarationRegExp); - const returnStatementIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(returnStatementIdentifierRegExp); + const functionParamIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionParamIdentifierRegExp); + const functionBodyIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionBodyIdentifierRegExp); + const variableDeclarationIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(variableDeclarationRegExp); + const returnStatementIdentifierMatch: RegExpMatchArray | null = obfuscatedCode.match( + returnStatementIdentifierRegExp + ); functionParamIdentifierName = (functionParamIdentifierMatch)[1]; functionBodyIdentifierName = (functionBodyIdentifierMatch)[1]; @@ -60,7 +58,7 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { assert.equal(variableDeclarationIdentifierName, returnStatementIdentifierName); }); - it('shouldn\'t transform other variables in function body', () => { + it("shouldn't transform other variables in function body", () => { assert.match(obfuscatedCode, variableReferenceRegExp); }); }); @@ -79,19 +77,18 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-id-name-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); - const functionExpressionParamIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionExpressionParamIdentifierRegExp); - const innerFunctionNameIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(innerFunctionNameIdentifierRegExp); - const functionObjectIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionObjectIdentifierRegExp); + const functionExpressionParamIdentifierMatch: RegExpMatchArray | null = obfuscatedCode.match( + functionExpressionParamIdentifierRegExp + ); + const innerFunctionNameIdentifierMatch: RegExpMatchArray | null = obfuscatedCode.match( + innerFunctionNameIdentifierRegExp + ); + const functionObjectIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionObjectIdentifierRegExp); functionExpressionParamIdentifierName = (functionExpressionParamIdentifierMatch)[1]; innerFunctionNameIdentifierName = (innerFunctionNameIdentifierMatch)[1]; @@ -135,17 +132,14 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-id-name-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); - const functionIdentifiersMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionIdentifiersRegExp); - const functionObjectIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionObjectIdentifierRegExp); + const functionIdentifiersMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionIdentifiersRegExp); + const functionObjectIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionObjectIdentifierRegExp); functionIdentifierName = (functionIdentifiersMatch)[1]; functionParamIdentifierName = (functionIdentifiersMatch)[2]; @@ -164,7 +158,7 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { assert.equal(functionIdentifierName, functionObjectIdentifierName); }); - it('should\'t generate same names for function id and parameter identifiers', () => { + it("should't generate same names for function id and parameter identifiers", () => { assert.notEqual(functionIdentifierName, functionParamIdentifierName); }); }); @@ -182,18 +176,15 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-id-name-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: false - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: false + }).getObfuscatedCode(); - const functionIdentifiersMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionIdentifiersRegExp); - const functionObjectIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionObjectIdentifierRegExp); + const functionIdentifiersMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionIdentifiersRegExp); + const functionObjectIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionObjectIdentifierRegExp); functionIdentifierName = (functionIdentifiersMatch)[1]; functionParamIdentifierName = (functionIdentifiersMatch)[2]; @@ -233,18 +224,15 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-id-name-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); - const functionIdentifiersMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionIdentifiersRegExp); - const functionObjectIdentifierMatch: RegExpMatchArray|null = obfuscatedCode - .match(functionObjectIdentifierRegExp); + const functionIdentifiersMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionIdentifiersRegExp); + const functionObjectIdentifierMatch: RegExpMatchArray | null = + obfuscatedCode.match(functionObjectIdentifierRegExp); functionIdentifierName = (functionIdentifiersMatch)[1]; functionParamIdentifierName = (functionIdentifiersMatch)[2]; @@ -263,11 +251,11 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { assert.equal(functionIdentifierName, functionObjectIdentifierName); }); - it('shouldn\'t generate same names for function parameter and function object identifiers', () => { + it("shouldn't generate same names for function parameter and function object identifiers", () => { assert.notEqual(functionParamIdentifierName, functionObjectIdentifierName); }); - it('shouldn\'t generate same names for function id and parameter identifiers', () => { + it("shouldn't generate same names for function id and parameter identifiers", () => { assert.notEqual(functionIdentifierName, functionParamIdentifierName); }); }); @@ -286,25 +274,23 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform function parameter object pattern identifier', () => { + it("match #1: shouldn't transform function parameter object pattern identifier", () => { assert.match(obfuscatedCode, functionParameterRegExp); }); - it('match #2: shouldn\'t transform function parameter object pattern identifier', () => { + it("match #2: shouldn't transform function parameter object pattern identifier", () => { assert.match(obfuscatedCode, functionBodyRegExp); }); }); describe('Variant #2: correct transformation when identifier with same name in parent scope exist', () => { - const functionParameterRegExp: RegExp = /^\(function *\(\) *{ *function *_0x[a-f0-9]{4,6} *\(_0x[a-f0-9]{4,6}\) *\{/; + const functionParameterRegExp: RegExp = + /^\(function *\(\) *{ *function *_0x[a-f0-9]{4,6} *\(_0x[a-f0-9]{4,6}\) *\{/; const callbackParameterRegExp: RegExp = /\['then'] *\(\({ *data *}\)/; const callbackBodyRegExp: RegExp = /console\['log']\(data\)/; const returnRegExp: RegExp = /return _0x[a-f0-9]{4,6};/; @@ -314,23 +300,20 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform function parameter identifier', () => { assert.match(obfuscatedCode, functionParameterRegExp); }); - it('match #2: shouldn\'t transform callback parameter object pattern identifier', () => { + it("match #2: shouldn't transform callback parameter object pattern identifier", () => { assert.match(obfuscatedCode, callbackParameterRegExp); }); - it('match #3: shouldn\'t transform callback body identifier', () => { + it("match #3: shouldn't transform callback body identifier", () => { assert.match(obfuscatedCode, callbackBodyRegExp); }); @@ -340,7 +323,8 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { }); describe('Variant #3: correct transformation when parent scope identifier conflicts with current scope object pattern identifier', () => { - const functionObjectPatternParameterRegExp1: RegExp = /function _0x[a-f0-9]{4,6} *\({data, *\.\.\._0x[a-f0-9]{4,6}}\) *{/; + const functionObjectPatternParameterRegExp1: RegExp = + /function _0x[a-f0-9]{4,6} *\({data, *\.\.\._0x[a-f0-9]{4,6}}\) *{/; const functionObjectPatternParameterRegExp2: RegExp = /function _0x[a-f0-9]{4,6} *\({options}\) *{/; const returnRegExp1: RegExp = /return data *\+ *options *\+ *_0x[a-f0-9]{4,6};/; const returnRegExp2: RegExp = /return _0x[a-f0-9]{4,6};/; @@ -350,12 +334,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform function parameter object pattern rest identifier', () => { @@ -377,7 +358,8 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { describe('Variant #4: shorthand property node', () => { const functionObjectPatternParameterRegExp1: RegExp = /function _0x[a-f0-9]{4,6} *\({id}\) *{/; - const functionObjectPatternParameterRegExp2: RegExp = /function _0x[a-f0-9]{4,6} *\({id: *_0x[a-f0-9]{4,6}}\) *{/; + const functionObjectPatternParameterRegExp2: RegExp = + /function _0x[a-f0-9]{4,6} *\({id: *_0x[a-f0-9]{4,6}}\) *{/; const consoleLogRegExp: RegExp = /console\['log']\(id\);/; const returnRegExp: RegExp = /return id *\+ *_0x[a-f0-9]{4,6};/; @@ -386,12 +368,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-4.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform function parameter object pattern rest identifier', () => { @@ -418,15 +397,12 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-5.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform function parameter identifier and reference identifier', () => { + it("match #1: shouldn't transform function parameter identifier and reference identifier", () => { assert.match(obfuscatedCode, objectPatternRegExp); }); }); @@ -440,19 +416,16 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-6.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform function parameter object pattern property identifier', () => { + it("match #1: shouldn't transform function parameter object pattern property identifier", () => { assert.match(obfuscatedCode, functionParameterRegExp); }); - it('match #2: shouldn\'t transform function body identifier', () => { + it("match #2: shouldn't transform function body identifier", () => { assert.match(obfuscatedCode, functionBodyRegExp); }); }); @@ -466,12 +439,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-parameter-7.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should correctly transform function parameter identifiers', () => { @@ -494,12 +464,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/assignment-pattern-as-parameter-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform function parameter assignment pattern identifier', () => { @@ -525,12 +492,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/assignment-pattern-as-parameter-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); variableDeclarationIdentifierName = getRegExpMatch(obfuscatedCode, variableDeclarationRegExp); functionParameterIdentifierName = getRegExpMatch(obfuscatedCode, functionParameterRegExp); functionDefaultParameterIdentifierName = getRegExpMatch(obfuscatedCode, functionParameterRegExp, 1); @@ -560,7 +524,8 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { describe('Variant #3: identifier as right value', () => { const variableDeclarationRegExp: RegExp = /var (_0x[a-f0-9]{4,6}) *= *0x1;/; - const functionParameterRegExp: RegExp = /function *\((_0x[a-f0-9]{4,6}), *(_0x[a-f0-9]{4,6}) *= *(_0x[a-f0-9]{4,6})\) *\{/; + const functionParameterRegExp: RegExp = + /function *\((_0x[a-f0-9]{4,6}), *(_0x[a-f0-9]{4,6}) *= *(_0x[a-f0-9]{4,6})\) *\{/; const functionBodyRegExp: RegExp = /return *(_0x[a-f0-9]{4,6}) *\+ *(_0x[a-f0-9]{4,6});/; let obfuscatedCode: string, @@ -574,12 +539,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/assignment-pattern-as-parameter-3.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); variableDeclarationIdentifierName = getRegExpMatch(obfuscatedCode, variableDeclarationRegExp); functionParameterIdentifierName = getRegExpMatch(obfuscatedCode, functionParameterRegExp); @@ -602,15 +564,15 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { assert.match(obfuscatedCode, functionBodyRegExp); }); - it('equal #1:shouldn\'t keep same names for variable declaration identifier and function parameters identifiers', () => { + it("equal #1:shouldn't keep same names for variable declaration identifier and function parameters identifiers", () => { assert.notEqual(variableDeclarationIdentifierName, functionParameterIdentifierName); }); - it('equal #2: shouldn\'t keep same names for variable declaration identifier and function parameters identifiers', () => { + it("equal #2: shouldn't keep same names for variable declaration identifier and function parameters identifiers", () => { assert.notEqual(variableDeclarationIdentifierName, functionDefaultParameterIdentifierName1); }); - it('equal #3: shouldn\'t keep same names for variable declaration identifier and function parameters identifiers', () => { + it("equal #3: shouldn't keep same names for variable declaration identifier and function parameters identifiers", () => { assert.notEqual(variableDeclarationIdentifierName, functionDefaultParameterIdentifierName2); }); @@ -640,12 +602,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/array-pattern-as-parameter.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); arrayPatternIdentifierName1 = getRegExpMatch(obfuscatedCode, functionParameterRegExp); arrayPatternIdentifierName2 = getRegExpMatch(obfuscatedCode, functionParameterRegExp, 1); @@ -671,12 +630,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/rest-parameter.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform function rest parameter', () => { @@ -697,12 +653,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/array-rest-parameter.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform function rest parameter', () => { @@ -725,12 +678,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-rest-parameter.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform function rest parameter', () => { @@ -753,12 +703,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-parameter-as-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: shouldn transform variable declaration', () => { @@ -773,8 +720,6 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { assert.match(obfuscatedCode, functionBodyRegExp); }); }); - - }); describe('ignored identifier names set', () => { @@ -786,12 +731,9 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/identifier-names-set-object-pattern.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should transform identifiers in function body', () => { @@ -802,24 +744,24 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { describe('correct block scope detection of arrow function expression', () => { describe('Variant #1: block statement body', () => { - const regExpMatch: string = `` + + const regExpMatch: string = + `` + `\\[]` + `\\['map']\\(_0x[a-f0-9]{4,6} *=> *\\{ *return 0x1; *\\}\\)` + `\\['map']\\(_0x[a-f0-9]{4,6} *=> *\\[foo]\\);` + - ``; + ``; const regExp: RegExp = new RegExp(regExpMatch); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/arrow-function-with-expression-body-block-scope-detection-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/arrow-function-with-expression-body-block-scope-detection-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should transform identifiers in arrow function expression body', () => { @@ -828,24 +770,24 @@ describe('ScopeIdentifiersTransformer Function identifiers', () => { }); describe('Variant #2: expression statement body', () => { - const regExpMatch: string = `` + + const regExpMatch: string = + `` + `\\[]` + `\\['map']\\(_0x[a-f0-9]{4,6} *=> *0x1\\)` + `\\['map']\\(_0x[a-f0-9]{4,6} *=> *\\[foo]\\);` + - ``; + ``; const regExp: RegExp = new RegExp(regExpMatch); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/arrow-function-with-expression-body-block-scope-detection-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/arrow-function-with-expression-body-block-scope-detection-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should transform identifiers in arrow function expression body', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/import-declaration/ImportDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/import-declaration/ImportDeclaration.spec.ts index 21d9d588..4b580037 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/import-declaration/ImportDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/import-declaration/ImportDeclaration.spec.ts @@ -13,19 +13,14 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { const importSpecifierRegExp: RegExp = /import (_0x[a-f0-9]{4,6}) from *'\.\/foo';/; const consoleLogRegExp: RegExp = /console\['log']\((_0x[a-f0-9]{4,6})\);/; - let obfuscatedCode: string, - importSpecifierIdentifier: string, - consoleLogIdentifier: string; + let obfuscatedCode: string, importSpecifierIdentifier: string, consoleLogIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-import.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); importSpecifierIdentifier = getRegExpMatch(obfuscatedCode, importSpecifierRegExp); consoleLogIdentifier = getRegExpMatch(obfuscatedCode, consoleLogRegExp); }); @@ -39,19 +34,14 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { const importSpecifierRegExp: RegExp = /import *\* *as *(_0x[a-f0-9]{4,6}) *from *'\.\/foo';/; const consoleLogRegExp: RegExp = /console\['log']\((_0x[a-f0-9]{4,6})\);/; - let obfuscatedCode: string, - importSpecifierIdentifier: string, - consoleLogIdentifier: string; + let obfuscatedCode: string, importSpecifierIdentifier: string, consoleLogIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/namespace-import.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); importSpecifierIdentifier = getRegExpMatch(obfuscatedCode, importSpecifierRegExp); consoleLogIdentifier = getRegExpMatch(obfuscatedCode, consoleLogRegExp); }); @@ -71,19 +61,16 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/named-import-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('Match #1: shouldn\'t transform import specifier identifier name', () => { + it("Match #1: shouldn't transform import specifier identifier name", () => { assert.match(obfuscatedCode, importSpecifierRegExp); }); - it('Match #2: shouldn\'t transform import specifier identifier name', () => { + it("Match #2: shouldn't transform import specifier identifier name", () => { assert.match(obfuscatedCode, consoleLogRegExp); }); }); @@ -92,19 +79,14 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { const importSpecifierRegExp: RegExp = /import *{foo as (_0x[a-f0-9]{4,6})} *from *'\.\/foo';/; const consoleLogRegExp: RegExp = /console\['log']\((_0x[a-f0-9]{4,6})\);/; - let obfuscatedCode: string, - importSpecifierIdentifier: string, - consoleLogIdentifier: string; + let obfuscatedCode: string, importSpecifierIdentifier: string, consoleLogIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/named-import-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); importSpecifierIdentifier = getRegExpMatch(obfuscatedCode, importSpecifierRegExp); consoleLogIdentifier = getRegExpMatch(obfuscatedCode, consoleLogRegExp); }); @@ -119,20 +101,15 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { const importSpecifierRegExp: RegExp = /import *\* *as *(bark_0x[a-f0-9]{4,6}) *from *'\.\/foo';/; const consoleLogRegExp: RegExp = /console\['log']\((bark_0x[a-f0-9]{4,6})\);/; - let obfuscatedCode: string, - importSpecifierIdentifier: string, - consoleLogIdentifier: string; + let obfuscatedCode: string, importSpecifierIdentifier: string, consoleLogIdentifier: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/namespace-import.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifiersPrefix: 'bark' - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifiersPrefix: 'bark' + }).getObfuscatedCode(); importSpecifierIdentifier = getRegExpMatch(obfuscatedCode, importSpecifierRegExp); consoleLogIdentifier = getRegExpMatch(obfuscatedCode, consoleLogRegExp); }); @@ -152,13 +129,10 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/no-invalid-mark-as-renamed-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match 1: should transform first import specifier identifier name', () => { @@ -182,13 +156,10 @@ describe('ScopeIdentifiersTransformer ImportDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/dynamic-import.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('should support dynamic import', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts index 60430f45..d1be2207 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts @@ -21,12 +21,9 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform `variableDeclaration` node', () => { @@ -48,19 +45,16 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform `variableDeclaration` node', () => { + it("match #1: shouldn't transform `variableDeclaration` node", () => { assert.match(obfuscatedCode, variableDeclarationRegExp); }); - it('match #2: shouldn\'t transform `variableDeclaration` node', () => { + it("match #2: shouldn't transform `variableDeclaration` node", () => { assert.match(obfuscatedCode, variableCallRegExp); }); }); @@ -74,13 +68,10 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/parent-block-scope-is-program-node.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('match #1: should transform `variableDeclaration` node', () => { @@ -101,12 +92,9 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/var-kind.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should transform variable call (`identifier` node) outside of block scope of node in which this variable was declared with `var` kind', () => { @@ -122,15 +110,12 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/let-kind.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t transform variable call (`identifier` node) outside of block scope of node in which this variable was declared with `let` kind', () => { + it("shouldn't transform variable call (`identifier` node) outside of block scope of node in which this variable was declared with `let` kind", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -142,14 +127,13 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-call-before-variable-declaration-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-call-before-variable-declaration-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should transform variable call (`identifier` node name) before variable declaration if this call is inside function body', () => { @@ -162,27 +146,27 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { }); describe(`Variant #6: variable calls before variable declaration when function param has the same name as variables name`, () => { - const functionParamIdentifierRegExp: RegExp = /function *_0x[a-f0-9]{4,6} *\((_0x[a-f0-9]{4,6})\,(_0x[a-f0-9]{4,6})\) *\{/; + const functionParamIdentifierRegExp: RegExp = + /function *_0x[a-f0-9]{4,6} *\((_0x[a-f0-9]{4,6})\,(_0x[a-f0-9]{4,6})\) *\{/; const innerFunctionParamIdentifierRegExp: RegExp = /function _0x[a-f0-9]{4,6} *\((_0x[a-f0-9]{4,6})\) *\{/; const consoleLogIdentifierRegExp: RegExp = /console\['log'\]\((_0x[a-f0-9]{4,6})\)/; const objectIdentifierRegExp: RegExp = /return\{'t':(_0x[a-f0-9]{4,6})\}/; const variableDeclarationIdentifierRegExp: RegExp = /var (_0x[a-f0-9]{4,6});/; - let outerFunctionParamIdentifierName: string|null, - innerFunctionParamIdentifierName: string|null, - consoleLogIdentifierName: string|null, - objectIdentifierName: string|null, - variableDeclarationIdentifierName: string|null; + let outerFunctionParamIdentifierName: string | null, + innerFunctionParamIdentifierName: string | null, + consoleLogIdentifierName: string | null, + objectIdentifierName: string | null, + variableDeclarationIdentifierName: string | null; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-call-before-variable-declaration-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-call-before-variable-declaration-2.js' + ); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); outerFunctionParamIdentifierName = getRegExpMatch(obfuscatedCode, functionParamIdentifierRegExp); innerFunctionParamIdentifierName = getRegExpMatch(obfuscatedCode, innerFunctionParamIdentifierRegExp); @@ -223,21 +207,20 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { const objectIdentifierRegExp: RegExp = /return\{'t':(_0x[a-f0-9]{4,6})\}/; const variableDeclarationIdentifierRegExp: RegExp = /var (_0x[a-f0-9]{4,6});/; - let catchClauseParamIdentifierName: string|null, - innerFunctionParamIdentifierName: string|null, - consoleLogIdentifierName: string|null, - objectIdentifierName: string|null, - variableDeclarationIdentifierName: string|null; + let catchClauseParamIdentifierName: string | null, + innerFunctionParamIdentifierName: string | null, + consoleLogIdentifierName: string | null, + objectIdentifierName: string | null, + variableDeclarationIdentifierName: string | null; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-call-before-variable-declaration-3.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-call-before-variable-declaration-3.js' + ); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); catchClauseParamIdentifierName = getRegExpMatch(obfuscatedCode, catchClauseParamIdentifierRegExp); innerFunctionParamIdentifierName = getRegExpMatch(obfuscatedCode, innerFunctionParamIdentifierRegExp); @@ -280,15 +263,12 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t replace property node identifier', () => { + it("shouldn't replace property node identifier", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -301,15 +281,12 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/member-expression-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t replace computed member expression identifier', () => { + it("shouldn't replace computed member expression identifier", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -327,26 +304,24 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform object pattern variable declarator', () => { + it("match #1: shouldn't transform object pattern variable declarator", () => { assert.match(obfuscatedCode, objectPatternVariableDeclaratorRegExp); }); - it('match #2: shouldn\'t transform object pattern variable declarator', () => { + it("match #2: shouldn't transform object pattern variable declarator", () => { assert.match(obfuscatedCode, variableUsageRegExp); }); }); describe('Variant #2: nested object pattern with property alias', () => { - const objectPatternVariableDeclaratorRegExp: RegExp = /var \{ *bar *: *{ *baz *: *_0x([a-f0-9]){4,6} *= *0x1 *\} *\} *= *\{ *'bar' *: *\{ *'baz' *: *0x2 *\} *\};/; + const objectPatternVariableDeclaratorRegExp: RegExp = + /var \{ *bar *: *{ *baz *: *_0x([a-f0-9]){4,6} *= *0x1 *\} *\} *= *\{ *'bar' *: *\{ *'baz' *: *0x2 *\} *\};/; const variableUsageRegExp: RegExp = /console\['log'\]\(bar, *baz, *_0x([a-f0-9]){4,6}\);/; let obfuscatedCode: string; @@ -354,27 +329,25 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); - it('match #1: shouldn\'t transform object pattern variable declarator', () => { + it("match #1: shouldn't transform object pattern variable declarator", () => { assert.match(obfuscatedCode, objectPatternVariableDeclaratorRegExp); }); - it('match #2: shouldn\'t transform object pattern variable declarator', () => { + it("match #2: shouldn't transform object pattern variable declarator", () => { assert.match(obfuscatedCode, variableUsageRegExp); }); }); }); describe('Variant #10: array pattern as variable declarator', () => { - const objectPatternVariableDeclaratorRegExp: RegExp = /var \[ *(_0x([a-f0-9]){4,6}), *(_0x([a-f0-9]){4,6}) *\] *= *\[0x1, *0x2\];/; + const objectPatternVariableDeclaratorRegExp: RegExp = + /var \[ *(_0x([a-f0-9]){4,6}), *(_0x([a-f0-9]){4,6}) *\] *= *\[0x1, *0x2\];/; const variableUsageRegExp: RegExp = /console\['log'\]\((_0x([a-f0-9]){4,6}), *(_0x([a-f0-9]){4,6})\);/; let obfuscatedCode: string, @@ -386,12 +359,9 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/array-pattern.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); objectPatternIdentifierName1 = getRegExpMatch(obfuscatedCode, objectPatternVariableDeclaratorRegExp); objectPatternIdentifierName2 = getRegExpMatch(obfuscatedCode, objectPatternVariableDeclaratorRegExp, 1); @@ -424,12 +394,9 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/computed-object-expression-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('should transform computed object expression identifier', () => { @@ -445,20 +412,17 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/method-definition-identifier.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t transform method definition node key identifier', () => { + it("shouldn't transform method definition node key identifier", () => { assert.match(obfuscatedCode, regExp); }); }); - describe('Variant #13: preserved identifier names shouldn\'t be used as identifier names', () => { + describe("Variant #13: preserved identifier names shouldn't be used as identifier names", () => { describe('Variant #1', () => { const variableDeclarationRegExp: RegExp = /var e *= *0x1;/; const functionDeclarationRegExp1: RegExp = /function *f *\(\) *{}/; @@ -469,34 +433,33 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevent-using-of-preserved-identifiers-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevent-using-of-preserved-identifiers-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); - it('Match #1: shouldn\'t use preserved identifier name as variable declaration name', () => { + it("Match #1: shouldn't use preserved identifier name as variable declaration name", () => { assert.match(obfuscatedCode, variableDeclarationRegExp); }); - it('Match #2: shouldn\'t use preserved identifier name as function declaration name', () => { + it("Match #2: shouldn't use preserved identifier name as function declaration name", () => { assert.match(obfuscatedCode, functionDeclarationRegExp1); }); - it('Match #3: shouldn\'t use preserved identifier name as function declaration name', () => { + it("Match #3: shouldn't use preserved identifier name as function declaration name", () => { assert.match(obfuscatedCode, functionDeclarationRegExp2); }); - it('Match #4: shouldn\'t use preserved identifier name as function declaration name', () => { + it("Match #4: shouldn't use preserved identifier name as function declaration name", () => { assert.match(obfuscatedCode, functionDeclarationRegExp3); }); - it('Match #5: shouldn\'t use preserved identifier name as function declaration name', () => { + it("Match #5: shouldn't use preserved identifier name as function declaration name", () => { assert.match(obfuscatedCode, functionDeclarationRegExp4); }); }); @@ -510,30 +473,29 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/prevent-using-of-preserved-identifiers-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/prevent-using-of-preserved-identifiers-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); - it('Match #1: shouldn\'t use preserved identifier name as variable declaration name', () => { + it("Match #1: shouldn't use preserved identifier name as variable declaration name", () => { assert.match(obfuscatedCode, variableDeclarationRegExp1); }); - it('Match #2: shouldn\'t use preserved identifier name as variable declaration name', () => { + it("Match #2: shouldn't use preserved identifier name as variable declaration name", () => { assert.match(obfuscatedCode, variableDeclarationRegExp2); }); - it('Match #3: shouldn\'t use preserved identifier name as function declaration name', () => { + it("Match #3: shouldn't use preserved identifier name as function declaration name", () => { assert.match(obfuscatedCode, functionDeclarationRegExp); }); - it('Match #4: shouldn\'t use preserved identifier name as variable declaration name', () => { + it("Match #4: shouldn't use preserved identifier name as variable declaration name", () => { assert.match(obfuscatedCode, variableDeclarationRegExp3); }); }); @@ -547,16 +509,13 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/named-export.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); - it('shouldn\'t transform identifiers in named export', () => { + it("shouldn't transform identifiers in named export", () => { assert.match(obfuscatedCode, namedExportRegExp); }); }); @@ -570,13 +529,10 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/default-export.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should transform identifiers in variable declaration', () => { @@ -597,12 +553,9 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/array-rest.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform object name', () => { @@ -625,12 +578,9 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-rest-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('Match #1: should transform object name', () => { @@ -653,14 +603,13 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/destructing-assignment-without-declaration-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/destructing-assignment-without-declaration-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform variables declaration', () => { @@ -681,22 +630,24 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { }); describe('Variant #19: destructing assignment without declaration #2', () => { - const variablesDeclaration: RegExp = /var _0x[a-f0-9]{4,6} *= *'a', *_0x[a-f0-9]{4,6} *= *'b', *_0x[a-f0-9]{4,6};/; - const destructingAssignmentRegExp: RegExp = /\({ *\[_0x[a-f0-9]{4,6}]: *_0x[a-f0-9]{4,6}, *\[_0x[a-f0-9]{4,6}]: *_0x[a-f0-9]{4,6} *} *= *{ *'a' *: *0x1, *'b' *: *0x2 *}\);/; + const variablesDeclaration: RegExp = + /var _0x[a-f0-9]{4,6} *= *'a', *_0x[a-f0-9]{4,6} *= *'b', *_0x[a-f0-9]{4,6};/; + const destructingAssignmentRegExp: RegExp = + /\({ *\[_0x[a-f0-9]{4,6}]: *_0x[a-f0-9]{4,6}, *\[_0x[a-f0-9]{4,6}]: *_0x[a-f0-9]{4,6} *} *= *{ *'a' *: *0x1, *'b' *: *0x2 *}\);/; const identifierAssignmentRegExp: RegExp = /_0x[a-f0-9]{4,6} *= *0x3;/; - const variablesUsageRegExp: RegExp = /console\['log']\(_0x[a-f0-9]{4,6}, *_0x[a-f0-9]{4,6}, *_0x[a-f0-9]{4,6}\);/; + const variablesUsageRegExp: RegExp = + /console\['log']\(_0x[a-f0-9]{4,6}, *_0x[a-f0-9]{4,6}, *_0x[a-f0-9]{4,6}\);/; let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/destructing-assignment-without-declaration-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/destructing-assignment-without-declaration-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform variables declaration', () => { @@ -720,20 +671,20 @@ describe('ScopeIdentifiersTransformer VariableDeclaration identifiers', () => { stubNodeTransformers([ObjectPatternPropertiesTransformer]); const variablesDeclaration: RegExp = /var a, *_0x[a-f0-9]{4,6};/; - const destructingAssignmentRegExp: RegExp = /\({ *a, *\.\.\._0x[a-f0-9]{4,6} *} *= *{ *'a' *: *0x1, *'b' *: *0x2 *}\);/; + const destructingAssignmentRegExp: RegExp = + /\({ *a, *\.\.\._0x[a-f0-9]{4,6} *} *= *{ *'a' *: *0x1, *'b' *: *0x2 *}\);/; const variablesUsageRegExp: RegExp = /console\['log']\(a, *_0x[a-f0-9]{4,6}\);/; let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/destructing-assignment-without-declaration-3.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/destructing-assignment-without-declaration-3.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); it('match #1: should transform variables declaration', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts index fb413c8b..8cfedca2 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/class-declaration/ClassDeclaration.spec.ts @@ -16,19 +16,16 @@ describe('ScopeThroughIdentifiersTransformer ClassDeclaration identifiers', () = before(() => { const code: string = readFileAsString(__dirname + '/fixtures/class-call-with-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'Foo': 'Foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + Foo: 'Foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should skip transformation of class name', () => { @@ -49,19 +46,16 @@ describe('ScopeThroughIdentifiersTransformer ClassDeclaration identifiers', () = before(() => { const code: string = readFileAsString(__dirname + '/fixtures/class-call-without-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'Foo': 'Foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + Foo: 'Foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should transform class name', () => { @@ -77,17 +71,14 @@ describe('ScopeThroughIdentifiersTransformer ClassDeclaration identifiers', () = before(() => { const code: string = readFileAsString(__dirname + '/fixtures/class-call-without-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not transform class name', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts index 0a8ab014..e8885df8 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/function-declaration/FunctionDeclaration.spec.ts @@ -16,19 +16,16 @@ describe('ScopeThroughIdentifiersTransformer FunctionDeclaration identifiers', ( before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-call-with-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should skip transformation of function name', () => { @@ -49,19 +46,16 @@ describe('ScopeThroughIdentifiersTransformer FunctionDeclaration identifiers', ( before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-call-without-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should transform function name', () => { @@ -77,17 +71,14 @@ describe('ScopeThroughIdentifiersTransformer FunctionDeclaration identifiers', ( before(() => { const code: string = readFileAsString(__dirname + '/fixtures/function-call-without-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not transform function name', () => { diff --git a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts index dad4ef79..c1bba81e 100644 --- a/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts +++ b/test/functional-tests/node-transformers/rename-identifiers-transformers/scope-through-identifiers-transformer/variable-declaration/VariableDeclaration.spec.ts @@ -16,19 +16,16 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( before(() => { const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-with-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should skip transformation of variable declaration name', () => { @@ -48,21 +45,20 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-without-declaration-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-reference-without-declaration-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should transform variable reference name', () => { @@ -76,19 +72,18 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-without-declaration-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-reference-without-declaration-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not transform variable reference name', () => { @@ -102,22 +97,21 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-without-declaration-global-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-reference-without-declaration-global-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' }, - reservedNames: ['^foo$'] - } - ).getObfuscatedCode(); + propertyIdentifiers: {} + }, + reservedNames: ['^foo$'] + }).getObfuscatedCode(); }); it('should not transform variable reference name', () => { @@ -133,21 +127,20 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-without-declaration-local-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-reference-without-declaration-local-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' + }, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should transform variable reference name', () => { @@ -161,19 +154,18 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-without-declaration-local-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-reference-without-declaration-local-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not transform variable reference name', () => { @@ -187,22 +179,21 @@ describe('ScopeThroughIdentifiersTransformer VariableDeclaration identifiers', ( let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-reference-without-declaration-local-scope.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-reference-without-declaration-local-scope.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameGlobals: true, - identifierNamesCache: { - globalIdentifiers: { - 'foo': 'foo_from_cache' - }, - propertyIdentifiers: {} + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameGlobals: true, + identifierNamesCache: { + globalIdentifiers: { + foo: 'foo_from_cache' }, - reservedNames: ['^foo$'] - } - ).getObfuscatedCode(); + propertyIdentifiers: {} + }, + reservedNames: ['^foo$'] + }).getObfuscatedCode(); }); it('should not transform variable reference name', () => { diff --git a/test/functional-tests/node-transformers/rename-properties-transformers/rename-properties-transformer/RenamePropertiesTransformer.spec.ts b/test/functional-tests/node-transformers/rename-properties-transformers/rename-properties-transformer/RenamePropertiesTransformer.spec.ts index 8f0a46ef..10d1112e 100644 --- a/test/functional-tests/node-transformers/rename-properties-transformers/rename-properties-transformer/RenamePropertiesTransformer.spec.ts +++ b/test/functional-tests/node-transformers/rename-properties-transformers/rename-properties-transformer/RenamePropertiesTransformer.spec.ts @@ -19,21 +19,17 @@ describe('RenamePropertiesTransformer', () => { const property3RegExp: RegExp = /\['(_0x[a-f0-9]{4,6})']: *0x3/; const property4RegExp: RegExp = /\[hawk]: *0x4/; - let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/base.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Match #1: should rename property', () => { @@ -64,15 +60,12 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-definition-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Match #1: should rename property definition', () => { @@ -100,21 +93,17 @@ describe('RenamePropertiesTransformer', () => { const property3RegExp: RegExp = /\['c']: *0x3/; const property4RegExp: RegExp = /\[hawk]: *0x4/; - let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/base.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Match #1: should rename property', () => { @@ -145,15 +134,12 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-definition-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Match #1: should rename property definition', () => { @@ -181,22 +167,18 @@ describe('RenamePropertiesTransformer', () => { const property3RegExp: RegExp = /\['c']: *0x3/; const property4RegExp: RegExp = /\[d]: *0x4/; - let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/base.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - renameGlobals: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + renameGlobals: true + }).getObfuscatedCode(); }); it('Match #1: should rename variable name', () => { @@ -225,29 +207,28 @@ describe('RenamePropertiesTransformer', () => { }); describe('Variant #4: properties rename of nested objects', () => { - const regExp: RegExp = new RegExp('' + - 'const foo *= *{' + - '\'a\': *{' + - '\'b\': *0x1' + + const regExp: RegExp = new RegExp( + '' + + 'const foo *= *{' + + "'a': *{" + + "'b': *0x1" + '}' + - '};' + - 'const bar *= *foo\\[\'a\']\\[\'b\'];' + - ''); + '};' + + "const bar *= *foo\\['a']\\['b'];" + + '' + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/nested-objects.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Should rename property', () => { @@ -256,28 +237,27 @@ describe('RenamePropertiesTransformer', () => { }); describe('Variant #5: properties rename of rest element', () => { - const regExp: RegExp = new RegExp('' + - 'const foo *= *{' + - '\'a\': *0x1' + - '};' + - 'const \\{a: *bar} *= *foo;' + - 'const baz *= *bar;' + - ''); + const regExp: RegExp = new RegExp( + '' + + 'const foo *= *{' + + "'a': *0x1" + + '};' + + 'const \\{a: *bar} *= *foo;' + + 'const baz *= *bar;' + + '' + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/rest-element.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Should rename property', () => { @@ -286,30 +266,29 @@ describe('RenamePropertiesTransformer', () => { }); describe('Variant #6: reserved dom properties', () => { - const regExp: RegExp = new RegExp('' + - 'const foo *= *{' + - '\'a\': *0x1,' + - '\'join\': *0x2,' + - '\'b\': *0x3,' + - '\'c\': *0x4' + - '};' + - 'const baz *= *foo\\[\'a\'] *\\+ *foo\\[\'join\'] *\\+ *foo\\[\'b\'] *\\+ *foo\\[\'c\'];' + - ''); + const regExp: RegExp = new RegExp( + '' + + 'const foo *= *{' + + "'a': *0x1," + + "'join': *0x2," + + "'b': *0x3," + + "'c': *0x4" + + '};' + + "const baz *= *foo\\['a'] *\\+ *foo\\['join'] *\\+ *foo\\['b'] *\\+ *foo\\['c'];" + + '' + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-properties.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Should rename non-reserved properties', () => { @@ -318,31 +297,30 @@ describe('RenamePropertiesTransformer', () => { }); describe('Variant #7: reserved names properties', () => { - const regExp: RegExp = new RegExp('' + - 'const foo *= *{' + - '\'a\': *0x1,' + - '\'join\': *0x2,' + - '\'reserved\': *0x3,' + - '\'private_\': *0x4' + - '};' + - 'const baz *= *foo\\[\'a\'] *\\+ *foo\\[\'join\'] *\\+ *foo\\[\'reserved\'] *\\+ *foo\\[\'private_\'];' + - ''); + const regExp: RegExp = new RegExp( + '' + + 'const foo *= *{' + + "'a': *0x1," + + "'join': *0x2," + + "'reserved': *0x3," + + "'private_': *0x4" + + '};' + + "const baz *= *foo\\['a'] *\\+ *foo\\['join'] *\\+ *foo\\['reserved'] *\\+ *foo\\['private_'];" + + '' + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-properties.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - reservedNames: ['^reserved$', '_$'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + reservedNames: ['^reserved$', '_$'] + }).getObfuscatedCode(); }); it('Should rename non-reserved properties', () => { @@ -351,29 +329,28 @@ describe('RenamePropertiesTransformer', () => { }); describe('Variant #8: class methods', () => { - const regExp: RegExp = new RegExp('' + - 'class Foo *{' + - '\\[\'a\'] *\\(\\) *{}' + - '}' + - 'const foo *= *new Foo\\(\\);' + - 'foo\\[\'a\']\\(\\);' + - ''); + const regExp: RegExp = new RegExp( + '' + + 'class Foo *{' + + "\\['a'] *\\(\\) *{}" + + '}' + + 'const foo *= *new Foo\\(\\);' + + "foo\\['a']\\(\\);" + + '' + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/class-methods.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - reservedNames: ['^reserved$', '_$'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + reservedNames: ['^reserved$', '_$'] + }).getObfuscatedCode(); }); it('Should rename class method name', () => { @@ -384,9 +361,9 @@ describe('RenamePropertiesTransformer', () => { describe('Variant #9: integration with `splitStrings` option', () => { const propertyRegExp: RegExp = new RegExp( 'const foo *= *{' + - '\'a\': *\'long\' *\\+ *\'Prop\' *\\+ *\'erty\' *\\+ *\'Valu\' *\\+ *\'e\'' + - '};' + - 'foo\\[\'a\'];' + "'a': *'long' *\\+ *'Prop' *\\+ *'erty' *\\+ *'Valu' *\\+ *'e'" + + '};' + + "foo\\['a'];" ); let obfuscatedCode: string; @@ -394,17 +371,14 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/split-strings-integration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - splitStrings: true, - splitStringsChunkLength: 4 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + splitStrings: true, + splitStringsChunkLength: 4 + }).getObfuscatedCode(); }); it('Should rename property before `splitStrings` option will applied', () => { @@ -415,30 +389,29 @@ describe('RenamePropertiesTransformer', () => { describe('Variant #10: integration with `controlFlowFlattening` option', () => { const propertyRegExp: RegExp = new RegExp( 'const b *= *{ *' + - '\'\\w{5}\' *: *\'a\' *' + - '}; *' + - 'const c *= *{' + - '\'a\': *0x1' + - '};' + - 'c\\[b\\[\'\\w{5}\']];' + "'\\w{5}' *: *'a' *" + + '}; *' + + 'const c *= *{' + + "'a': *0x1" + + '};' + + "c\\[b\\['\\w{5}']];" ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/control-flow-flattening-integration.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/control-flow-flattening-integration.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1 + }).getObfuscatedCode(); }); it('Should correctly rename property when `controlFlowFlattening` option is enabled', () => { @@ -448,27 +421,23 @@ describe('RenamePropertiesTransformer', () => { describe('Variant #11: integration with `transformObjectKeys` option', () => { const propertyRegExp: RegExp = new RegExp( - 'const b *= *{}; *' + - 'b\\[\'a\'] *= *0x1;' + - 'const foo *= *b;' + - 'foo\\[\'a\'];' + 'const b *= *{}; *' + "b\\['a'] *= *0x1;" + 'const foo *= *b;' + "foo\\['a'];" ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/transform-object-keys-integration.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/transform-object-keys-integration.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - transformObjectKeys: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + transformObjectKeys: true + }).getObfuscatedCode(); }); it('Should correctly rename property when `transformObjectKeys` option is enabled', () => { @@ -486,14 +455,11 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/boolean-literal-node.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe + }).getObfuscatedCode(); }); it('Match #1: should skip literal property with invalid type', () => { @@ -510,16 +476,13 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/duplicated-generated-names-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Unsafe, - identifierNamesGenerator: 'mangled', - reservedNames: ['^a$'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Unsafe, + identifierNamesGenerator: 'mangled', + reservedNames: ['^a$'] + }).getObfuscatedCode(); }); it('Match #1: should skip literal property with invalid type', () => { @@ -530,43 +493,44 @@ describe('RenamePropertiesTransformer', () => { describe('Mode: `safe`', () => { describe('Variant #1: base properties rename', () => { - const declarationsRegExp: RegExp = new RegExp('' + - 'const object *= *{' + - '\'foo\': *0x1, *' + - '\'a\': *0x2 *' + - '}; *' + - 'class Class *{ *' + - '\\[\'baz\'] *= *0x1; *' + - 'static *\\[\'b\'] *= *0x2;*' + - 'static *\\[\'hawk\'] *\\(\\) *{} *' + - 'static *\\[\'c\'] *\\(\\) *{} *' + - '}' + - ''); - const referencesRegExp: RegExp = new RegExp('' + - 'console\\[\'log\']\\(' + - 'object\\[\'foo\'], *' + - 'object\\[\'a\'], *' + - 'Class\\[\'baz\'], *' + - 'Class\\[\'b\'], *' + - 'Class\\[\'hawk\'], *' + - 'Class\\[\'c\'] *' + - '\\);' + - ''); + const declarationsRegExp: RegExp = new RegExp( + '' + + 'const object *= *{' + + "'foo': *0x1, *" + + "'a': *0x2 *" + + '}; *' + + 'class Class *{ *' + + "\\['baz'] *= *0x1; *" + + "static *\\['b'] *= *0x2;*" + + "static *\\['hawk'] *\\(\\) *{} *" + + "static *\\['c'] *\\(\\) *{} *" + + '}' + + '' + ); + const referencesRegExp: RegExp = new RegExp( + '' + + "console\\['log']\\(" + + "object\\['foo'], *" + + "object\\['a'], *" + + "Class\\['baz'], *" + + "Class\\['b'], *" + + "Class\\['hawk'], *" + + "Class\\['c'] *" + + '\\);' + + '' + ); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/safe-mode.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Safe, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Safe, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('Should rename property declarations', () => { @@ -586,16 +550,13 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/duplicated-generated-names-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - renamePropertiesMode: RenamePropertiesMode.Safe, - identifierNamesGenerator: 'mangled', - reservedNames: ['^a$'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + renamePropertiesMode: RenamePropertiesMode.Safe, + identifierNamesGenerator: 'mangled', + reservedNames: ['^a$'] + }).getObfuscatedCode(); }); it('Match #1: should skip literal property with invalid type', () => { @@ -615,17 +576,14 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-identifier-names-cache.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: {} - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: {} } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('Match #1: should rename property', () => { @@ -651,20 +609,17 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-identifier-names-cache.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: { - bar: 'bar_from_cache', - baz: 'baz_from_cache' - } + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: { + bar: 'bar_from_cache', + baz: 'baz_from_cache' } } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('Match #1: should rename property based on the cache value', () => { @@ -690,21 +645,18 @@ describe('RenamePropertiesTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/property-identifier-names-cache.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - renameProperties: true, - identifierNamesCache: { - globalIdentifiers: {}, - propertyIdentifiers: { - bar: 'bar_from_cache', - baz: 'baz_from_cache' - } - }, - reservedNames: ['^baz$'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + renameProperties: true, + identifierNamesCache: { + globalIdentifiers: {}, + propertyIdentifiers: { + bar: 'bar_from_cache', + baz: 'baz_from_cache' + } + }, + reservedNames: ['^baz$'] + }).getObfuscatedCode(); }); it('Match #1: should rename property based on the cache value', () => { diff --git a/test/functional-tests/node-transformers/simplifying-transformers/block-statement-simplify-transformer/BlockStatementSimplifyTransformer.spec.ts b/test/functional-tests/node-transformers/simplifying-transformers/block-statement-simplify-transformer/BlockStatementSimplifyTransformer.spec.ts index 10928997..73151a55 100644 --- a/test/functional-tests/node-transformers/simplifying-transformers/block-statement-simplify-transformer/BlockStatementSimplifyTransformer.spec.ts +++ b/test/functional-tests/node-transformers/simplifying-transformers/block-statement-simplify-transformer/BlockStatementSimplifyTransformer.spec.ts @@ -10,25 +10,17 @@ describe('BlockStatementSimplifyTransformer', () => { describe('Full `BlockStatement` simplify cases', () => { describe('No `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - 'function foo *\\(\\) *{ *' + - 'bar\\(\\); *' + - '}' - ); - + const regExp: RegExp = new RegExp('function foo *\\(\\) *{ *' + 'bar\\(\\); *' + '}'); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/full-no-return-single-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify block statement', () => { @@ -38,24 +30,20 @@ describe('BlockStatementSimplifyTransformer', () => { describe('Variant #2: multiple statements', () => { const regExp: RegExp = new RegExp( - 'function foo *\\(\\) *{ *' + - 'bar\\(\\), *baz\\(\\), *bark\\(\\); *' + - '}' + 'function foo *\\(\\) *{ *' + 'bar\\(\\), *baz\\(\\), *bark\\(\\); *' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-no-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-no-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify block statement', () => { @@ -66,25 +54,17 @@ describe('BlockStatementSimplifyTransformer', () => { describe('With `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - 'function foo *\\(\\) *{ *' + - 'return bar\\(\\); *' + - '}' - ); - + const regExp: RegExp = new RegExp('function foo *\\(\\) *{ *' + 'return bar\\(\\); *' + '}'); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/full-return-single-statement.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify block statement', () => { @@ -94,24 +74,18 @@ describe('BlockStatementSimplifyTransformer', () => { describe('Variant #2: multiple statements', () => { const regExp: RegExp = new RegExp( - 'function foo *\\(\\) *{ *' + - 'return bar\\(\\), *baz\\(\\), *bark\\(\\); *' + - '}' + 'function foo *\\(\\) *{ *' + 'return bar\\(\\), *baz\\(\\), *bark\\(\\); *' + '}' ); - let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/full-return-multiple-statements.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify block statement', () => { @@ -125,24 +99,20 @@ describe('BlockStatementSimplifyTransformer', () => { describe('No `ReturnStatement`', () => { describe('Variant #1: single statement', () => { const regExp: RegExp = new RegExp( - 'function foo *\\(\\) *{ *' + - 'var _0x([a-f0-9]){4,6} *= *baz\\(\\);' + - '}' + 'function foo *\\(\\) *{ *' + 'var _0x([a-f0-9]){4,6} *= *baz\\(\\);' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-no-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-no-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify block statement', () => { @@ -155,22 +125,20 @@ describe('BlockStatementSimplifyTransformer', () => { 'function foo *\\(\\) *{ *' + 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'bark\\(\\), *hawk\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-no-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-no-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify block statement', () => { @@ -185,22 +153,20 @@ describe('BlockStatementSimplifyTransformer', () => { 'function foo *\\(\\) *{ *' + 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'return bark\\(\\), *hawk\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify block statement', () => { @@ -216,24 +182,22 @@ describe('BlockStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'function foo *\\(\\) *{ *' + 'var _0x([a-f0-9]){4,6} *= *function *\\(\\) *{}, *' + - '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{}, *' + - '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{}; *' + - '}' + '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{}, *' + + '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{}; *' + + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarations-merge-transformer-integration-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarations-merge-transformer-integration-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify block statement', () => { diff --git a/test/functional-tests/node-transformers/simplifying-transformers/expression-statements-merge-transformer/ExpressionStatementsMergeTransformer.spec.ts b/test/functional-tests/node-transformers/simplifying-transformers/expression-statements-merge-transformer/ExpressionStatementsMergeTransformer.spec.ts index c7388021..0f9ffeb1 100644 --- a/test/functional-tests/node-transformers/simplifying-transformers/expression-statements-merge-transformer/ExpressionStatementsMergeTransformer.spec.ts +++ b/test/functional-tests/node-transformers/simplifying-transformers/expression-statements-merge-transformer/ExpressionStatementsMergeTransformer.spec.ts @@ -9,26 +9,18 @@ import { JavaScriptObfuscator } from '../../../../../src/JavaScriptObfuscatorFac describe('ExpressionStatementsMergeTransformer', () => { describe('Variant #1: simple', () => { const regExp: RegExp = new RegExp( - 'function foo *\\(\\) *{ *' + - 'bar\\(\\), *' + - 'baz\\(\\), *' + - 'bark\\(\\); *' + - '}' + 'function foo *\\(\\) *{ *' + 'bar\\(\\), *' + 'baz\\(\\), *' + 'bark\\(\\); *' + '}' ); - let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge expression statements', () => { @@ -39,30 +31,26 @@ describe('ExpressionStatementsMergeTransformer', () => { describe('Variant #2: complex', () => { const regExp: RegExp = new RegExp( 'function foo *\\(\\) *{ *' + - 'console\\[\'log\']\\(0x1\\), *' + - 'console\\[\'log\']\\(0x2\\); *' + + "console\\['log']\\(0x1\\), *" + + "console\\['log']\\(0x2\\); *" + 'function _0x([a-f0-9]){4,6} *\\(\\) *{ *} *' + - 'console\\[\'log\']\\(0x3\\), *' + - 'console\\[\'log\']\\(0x4\\), *' + - 'console\\[\'log\']\\(0x5\\); *' + + "console\\['log']\\(0x3\\), *" + + "console\\['log']\\(0x4\\), *" + + "console\\['log']\\(0x5\\); *" + 'const _0x([a-f0-9]){4,6} *= *0x6; *' + - 'console\\[\'log\']\\(0x7\\); *' + - '}' + "console\\['log']\\(0x7\\); *" + + '}' ); - let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/complex.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge expression statements', () => { diff --git a/test/functional-tests/node-transformers/simplifying-transformers/if-statement-simplify-transformer/IfStatementSimplifyTransformer.spec.ts b/test/functional-tests/node-transformers/simplifying-transformers/if-statement-simplify-transformer/IfStatementSimplifyTransformer.spec.ts index f24c1623..6889daf5 100644 --- a/test/functional-tests/node-transformers/simplifying-transformers/if-statement-simplify-transformer/IfStatementSimplifyTransformer.spec.ts +++ b/test/functional-tests/node-transformers/simplifying-transformers/if-statement-simplify-transformer/IfStatementSimplifyTransformer.spec.ts @@ -11,23 +11,19 @@ describe('IfStatementSimplifyTransformer', () => { describe('Consequent only', () => { describe('No `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - '!!\\[] *&& *bar\\(\\);' - ); - + const regExp: RegExp = new RegExp('!!\\[] *&& *bar\\(\\);'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-only-no-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-only-no-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -36,23 +32,19 @@ describe('IfStatementSimplifyTransformer', () => { }); describe('Variant #2: multiple statements', () => { - const regExp: RegExp = new RegExp( - '!!\\[] *&& *\\(bar\\(\\) *, *baz\\(\\) *, *bark\\(\\)\\);' - ); - + const regExp: RegExp = new RegExp('!!\\[] *&& *\\(bar\\(\\) *, *baz\\(\\) *, *bark\\(\\)\\);'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-only-no-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-only-no-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -63,24 +55,19 @@ describe('IfStatementSimplifyTransformer', () => { describe('With `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *' + - 'return *bar\\(\\);' - ); - + const regExp: RegExp = new RegExp('if *\\(!!\\[]\\) *' + 'return *bar\\(\\);'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-only-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-only-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -90,23 +77,20 @@ describe('IfStatementSimplifyTransformer', () => { describe('Variant #2: multiple statements', () => { const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *' + - 'return *bar\\(\\) *, *baz\\(\\) *, *bark\\(\\);' + 'if *\\(!!\\[]\\) *' + 'return *bar\\(\\) *, *baz\\(\\) *, *bark\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-only-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-only-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -118,22 +102,20 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *\\{ *' + 'bar\\(\\), *baz\\(\\); *return bark\\(\\); *hawk\\(\\), *eagle\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-only-statements-after-return.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-only-statements-after-return.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -146,25 +128,19 @@ describe('IfStatementSimplifyTransformer', () => { describe('Consequent and alternate', () => { describe('No `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - '!!\\[] *' + - '\\? *bar\\(\\) *' + - ': *baz\\(\\);' - ); - + const regExp: RegExp = new RegExp('!!\\[] *' + '\\? *bar\\(\\) *' + ': *baz\\(\\);'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-no-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-no-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -179,19 +155,17 @@ describe('IfStatementSimplifyTransformer', () => { ': *\\(hawk\\(\\) *, *pork\\(\\) *, *eagle\\(\\)\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-no-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-no-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -203,25 +177,20 @@ describe('IfStatementSimplifyTransformer', () => { describe('With consequent `ReturnStatement`', () => { describe('Variant #1: single statement', () => { const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *' + - 'return *bar\\(\\); *' + - 'else *' + - 'baz\\(\\);' + 'if *\\(!!\\[]\\) *' + 'return *bar\\(\\); *' + 'else *' + 'baz\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-consequent-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-consequent-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -233,23 +202,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'return *bar\\(\\) *, *baz\\(\\) *, *bark\\(\\); *' + - 'else *' + + 'else *' + 'hawk\\(\\) *, *pork\\(\\) *, *eagle\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-consequent-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/full-consequent-and-alternate-consequent-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -261,22 +229,21 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *\\{ *' + 'bar\\(\\), *baz\\(\\); *return bark\\(\\); *cat\\(\\), *dog\\(\\); *' + - '\\} *else *' + + '\\} *else *' + 'hawk\\(\\), *pork\\(\\), *eagle\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-consequent-statements-after-return.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-consequent-statements-after-return.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -288,25 +255,20 @@ describe('IfStatementSimplifyTransformer', () => { describe('With alternate `ReturnStatement`', () => { describe('Variant #1: single statement', () => { const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *' + - 'bar\\(\\); *' + - 'else *' + - 'return *baz\\(\\);' + 'if *\\(!!\\[]\\) *' + 'bar\\(\\); *' + 'else *' + 'return *baz\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-alternate-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-alternate-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -318,23 +280,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'bar\\(\\) *, *baz\\(\\) *, *bark\\(\\); *' + - 'else *' + + 'else *' + 'return *hawk\\(\\) *, *pork\\(\\) *, *eagle\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-alternate-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/full-consequent-and-alternate-alternate-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -346,23 +307,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'bar\\(\\), *baz\\(\\), *bark\\(\\); *' + - 'else *\\{ *' + + 'else *\\{ *' + 'hawk\\(\\), *eagle\\(\\); *return cow\\(\\); *cat\\(\\), *dog\\(\\);' + - '\\}' + '\\}' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-alternate-statements-after-return.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-alternate-statements-after-return.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -373,25 +333,19 @@ describe('IfStatementSimplifyTransformer', () => { describe('With consequent and alternate `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - 'return *!!\\[] *' + - '\\? *bar\\(\\) *' + - ': *baz\\(\\);' - ); - + const regExp: RegExp = new RegExp('return *!!\\[] *' + '\\? *bar\\(\\) *' + ': *baz\\(\\);'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -406,19 +360,17 @@ describe('IfStatementSimplifyTransformer', () => { ': *\\(hawk\\(\\) *, *pork\\(\\) *, *eagle\\(\\)\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/full-consequent-and-alternate-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/full-consequent-and-alternate-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -433,24 +385,19 @@ describe('IfStatementSimplifyTransformer', () => { describe('Consequent only', () => { describe('No `ReturnStatement`', () => { describe('Variant #1: single statement', () => { - const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *' + - 'var _0x([a-f0-9]){4,6} *= *baz\\(\\);' - ); - + const regExp: RegExp = new RegExp('if *\\(!!\\[]\\) *' + 'var _0x([a-f0-9]){4,6} *= *baz\\(\\);'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-only-no-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-only-no-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -463,22 +410,20 @@ describe('IfStatementSimplifyTransformer', () => { 'if *\\(!!\\[]\\) *{ *' + 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'bark\\(\\), *hawk\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-only-no-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-only-no-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -493,22 +438,20 @@ describe('IfStatementSimplifyTransformer', () => { 'if *\\(!!\\[]\\) *{ *' + 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'return bark\\(\\), *hawk\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-only-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-only-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -522,22 +465,20 @@ describe('IfStatementSimplifyTransformer', () => { 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'return bark\\(\\); *' + 'hawk\\(\\), *eagle\\(\\); *' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-only-statements-after-return.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-only-statements-after-return.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -553,23 +494,21 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'var *_0x([a-f0-9]){4,6} *= *baz\\(\\); *' + - 'else *' + + 'else *' + 'var *_0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-no-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-and-alternate-no-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -581,27 +520,25 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\), *' + - '_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + + '_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + 'eagle\\(\\), *pork\\(\\);' + - '} *else *{ *' + + '} *else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *cow\\(\\); *' + 'lion\\(\\), *pig\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-no-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-and-alternate-no-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -613,25 +550,23 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'var *_0x([a-f0-9]){4,6} *= *baz\\(\\); *' + - 'else *{ *' + + 'else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + 'eagle\\(\\), *dog\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-no-return-mixed-statements-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-and-alternate-no-return-mixed-statements-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -643,25 +578,23 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\), *' + - '_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + + '_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + 'eagle\\(\\), *pork\\(\\);' + - '} *else *' + + '} *else *' + 'var *_0x([a-f0-9]){4,6} *= *cow\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-no-return-mixed-statements-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-and-alternate-no-return-mixed-statements-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -675,23 +608,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'return *bar\\(\\); *' + - 'else *' + + 'else *' + 'var *_0x([a-f0-9]){4,6} *= *bark\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-consequent-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/partial-consequent-and-alternate-consequent-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -703,27 +635,26 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\), *' + - '_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + + '_0x([a-f0-9]){4,6} *= *hawk\\(\\); *' + 'return *eagle\\(\\), *cat\\(\\);' + - '} *else *{ *' + + '} *else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *pig\\(\\); *' + 'lion\\(\\), *dog\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-consequent-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/partial-consequent-and-alternate-consequent-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -737,25 +668,24 @@ describe('IfStatementSimplifyTransformer', () => { 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'return hawk\\(\\); *' + 'eagle\\(\\), *cat\\(\\);' + - '} *else *{ *' + + '} *else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *pig\\(\\); *' + 'lion\\(\\), *dog\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-consequent-statements-after-return.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/partial-consequent-and-alternate-consequent-statements-after-return.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -769,23 +699,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'var *_0x([a-f0-9]){4,6} *= *baz\\(\\); *' + - 'else *' + + 'else *' + 'return *bark\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-alternate-return-single-statement.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/partial-consequent-and-alternate-alternate-return-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -798,26 +727,25 @@ describe('IfStatementSimplifyTransformer', () => { 'if *\\(!!\\[]\\) *{ *' + 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'bark\\(\\), *hawk\\(\\);' + - '} *else *{ *' + + '} *else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *pork\\(\\), *' + - '_0x([a-f0-9]){4,6} *= *dog\\(\\); *' + + '_0x([a-f0-9]){4,6} *= *dog\\(\\); *' + 'return *pig\\(\\), *lion\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-alternate-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/partial-consequent-and-alternate-alternate-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -830,26 +758,25 @@ describe('IfStatementSimplifyTransformer', () => { 'if *\\(!!\\[]\\) *{ *' + 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\); *' + 'bark\\(\\), *hawk\\(\\);' + - '} *else *{ *' + + '} *else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *pork\\(\\); *' + 'return dog\\(\\); *' + 'pig\\(\\), *lion\\(\\); *' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-alternate-statements-after-return.js'); + const code: string = readFileAsString( + __dirname + + '/fixtures/partial-consequent-and-alternate-alternate-statements-after-return.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -863,28 +790,26 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'const *_0x([a-f0-9]){4,6} *= *baz\\(\\), *' + - '_0x([a-f0-9]){4,6} *= *eagle\\(\\); *' + + '_0x([a-f0-9]){4,6} *= *eagle\\(\\); *' + 'return *hawk\\(\\), *lion\\(\\);' + - '} *else *{ *' + + '} *else *{ *' + 'const *_0x([a-f0-9]){4,6} *= *dog\\(\\), *' + - '_0x([a-f0-9]){4,6} *= *hamster\\(\\); *' + + '_0x([a-f0-9]){4,6} *= *hamster\\(\\); *' + 'return *parrot\\(\\), *bull\\(\\);' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/partial-consequent-and-alternate-return-multiple-statements.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/partial-consequent-and-alternate-return-multiple-statements.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -901,23 +826,21 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *' + 'var _0x([a-f0-9]){4,6} *= *function *\\(\\) *{}, *' + - '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{}, *' + - '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{};' + '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{}, *' + + '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{};' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/variable-declarations-merge-transformer-integration-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/variable-declarations-merge-transformer-integration-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should simplify if statement', () => { @@ -928,28 +851,26 @@ describe('IfStatementSimplifyTransformer', () => { describe('Prohibited single statement', () => { describe('Variant #1: `IfStatement` as prohibited single statement', () => { - describe('Variant #1: `IfStatement` with `var` variable inside`' , () => { + describe('Variant #1: `IfStatement` with `var` variable inside`', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'if *\\(!\\[]\\) *' + - 'var _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + - '} *else *' + + 'var _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/if-statement-as-prohibited-single-statement-1.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/if-statement-as-prohibited-single-statement-1.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -957,29 +878,27 @@ describe('IfStatementSimplifyTransformer', () => { }); }); - describe('Variant #2: `IfStatement` with `const` variable inside`' , () => { + describe('Variant #2: `IfStatement` with `const` variable inside`', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'if *\\(!\\[]\\) *{ *' + - 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + + 'const _0x([a-f0-9]){4,6} *= *baz\\(\\); *' + '} *' + - '} *else *' + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/if-statement-as-prohibited-single-statement-2.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/if-statement-as-prohibited-single-statement-2.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -993,27 +912,26 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'for *\\( *' + - 'let _0x([a-f0-9]){4,6} *= *0x0; *' + - '_0x([a-f0-9]){4,6} *< *0x1; *' + - '_0x([a-f0-9]){4,6}\\+\\+ *' + + 'let _0x([a-f0-9]){4,6} *= *0x0; *' + + '_0x([a-f0-9]){4,6} *< *0x1; *' + + '_0x([a-f0-9]){4,6}\\+\\+ *' + '\\) *' + - 'console\\[\'log\']\\(_0x([a-f0-9]){4,6}\\); *' + - '} *else *' + + "console\\['log']\\(_0x([a-f0-9]){4,6}\\); *" + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/single-line-for-statement-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/single-line-for-statement-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1025,23 +943,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'for *\\(const _0x([a-f0-9]){4,6} of *\\[\\]\\) *' + - 'console\\[\'log\']\\(_0x([a-f0-9]){4,6}\\); *' + - '} *else *' + + "console\\['log']\\(_0x([a-f0-9]){4,6}\\); *" + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/single-line-for-of-statement-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/single-line-for-of-statement-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1053,23 +970,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'for *\\(const _0x([a-f0-9]){4,6} in *\\{\\}\\) *' + - 'console\\[\'log\']\\(_0x([a-f0-9]){4,6}\\); *' + - '} *else *' + + "console\\['log']\\(_0x([a-f0-9]){4,6}\\); *" + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/single-line-for-in-statement-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/single-line-for-in-statement-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1081,23 +997,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'while *\\(!!\\[]\\) *' + - 'console\\[\'log\']\\(0x1\\); *' + - '} *else *' + + "console\\['log']\\(0x1\\); *" + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/single-line-while-statement-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/single-line-while-statement-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1109,24 +1024,23 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'do *' + - 'console\\[\'log\']\\(0x1\\); *' + + "console\\['log']\\(0x1\\); *" + 'while *\\(!!\\[]\\); *' + - '} *else *' + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/single-line-do-while-statement-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/single-line-do-while-statement-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1138,23 +1052,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + '_0x([a-f0-9]){4,6}: *' + - 'console\\[\'log\']\\(0x1\\); *' + - '} *else *' + + "console\\['log']\\(0x1\\); *" + + '} *else *' + 'var _0x([a-f0-9]){4,6} *= *hawk\\(\\);' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/single-line-labeled-statement-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/single-line-labeled-statement-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1167,24 +1080,22 @@ describe('IfStatementSimplifyTransformer', () => { const regExp: RegExp = new RegExp( 'if *\\(!!\\[]\\) *{ *' + 'function _0x([a-f0-9]){4,6} *\\(\\) *{} *' + - '} *else *{ *' + + '} *else *{ *' + 'function _0x([a-f0-9]){4,6} *\\(\\) *{} *' + - '}' + '}' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/function-declaration-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/function-declaration-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1193,25 +1104,19 @@ describe('IfStatementSimplifyTransformer', () => { }); describe('Variant #4: `let` `VariableDeclaration` as prohibited single statement', () => { - const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *{ *' + - 'let foo *= *0x1; *' + - '}' - ); - + const regExp: RegExp = new RegExp('if *\\(!!\\[]\\) *{ *' + 'let foo *= *0x1; *' + '}'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/let-variable-declaration-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/let-variable-declaration-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { @@ -1220,25 +1125,19 @@ describe('IfStatementSimplifyTransformer', () => { }); describe('Variant #5: `const` `VariableDeclaration` as prohibited single statement', () => { - const regExp: RegExp = new RegExp( - 'if *\\(!!\\[]\\) *{ *' + - 'const foo *= *0x1; *' + - '}' - ); - + const regExp: RegExp = new RegExp('if *\\(!!\\[]\\) *{ *' + 'const foo *= *0x1; *' + '}'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/const-variable-declaration-as-prohibited-single-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/const-variable-declaration-as-prohibited-single-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should not simplify if statement', () => { diff --git a/test/functional-tests/node-transformers/simplifying-transformers/variable-declarations-merge-transformer/VariableDeclarationsMergeTransformer.spec.ts b/test/functional-tests/node-transformers/simplifying-transformers/variable-declarations-merge-transformer/VariableDeclarationsMergeTransformer.spec.ts index 168edecd..f91c2842 100644 --- a/test/functional-tests/node-transformers/simplifying-transformers/variable-declarations-merge-transformer/VariableDeclarationsMergeTransformer.spec.ts +++ b/test/functional-tests/node-transformers/simplifying-transformers/variable-declarations-merge-transformer/VariableDeclarationsMergeTransformer.spec.ts @@ -11,23 +11,17 @@ import { ObjectPatternPropertiesTransformer } from '../../../../../src/node-tran describe('VariableDeclarationsMergeTransformer', () => { describe('base behaviour', () => { describe('Variant #1: single variable declaration', () => { - const regExp: RegExp = new RegExp( - 'var foo *= *0x1;' - ); - + const regExp: RegExp = new RegExp('var foo *= *0x1;'); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/single-declaration.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should keep single declaration', () => { @@ -36,25 +30,17 @@ describe('VariableDeclarationsMergeTransformer', () => { }); describe('Variant #2: multiple variable declarations', () => { - const regExp: RegExp = new RegExp( - 'var foo *= *0x1, *' + - 'bar *= *0x2, *' + - 'baz *= *0x3;' - ); - + const regExp: RegExp = new RegExp('var foo *= *0x1, *' + 'bar *= *0x2, *' + 'baz *= *0x3;'); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/multiple-declarations.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge variable declarations', () => { @@ -64,24 +50,20 @@ describe('VariableDeclarationsMergeTransformer', () => { describe('Variant #3: multiple variable declarations with multiple declarators', () => { const regExp: RegExp = new RegExp( - 'var foo *= *0x1, *' + - 'bar *= *0x2, *' + - 'baz *= *0x3, *' + - 'bark *= *0x4;' + 'var foo *= *0x1, *' + 'bar *= *0x2, *' + 'baz *= *0x3, *' + 'bark *= *0x4;' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/multiple-declarations-with-multiple-declarators.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/multiple-declarations-with-multiple-declarators.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge variable declarations', () => { @@ -93,23 +75,22 @@ describe('VariableDeclarationsMergeTransformer', () => { const regExp: RegExp = new RegExp( 'var foo *= *0x1, *' + 'bar *= *0x2; *' + - 'console\\[\'log\']\\(\'123\'\\); *' + - 'var baz *= *0x3, *' + + "console\\['log']\\('123'\\); *" + + 'var baz *= *0x3, *' + 'bark *= *0x4;' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/splitted-declarations-with-other-statement.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/splitted-declarations-with-other-statement.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge variable declarations', () => { @@ -118,25 +99,19 @@ describe('VariableDeclarationsMergeTransformer', () => { }); describe('Variant #5: multiple variable declarations without declarators', () => { - const regExp: RegExp = new RegExp( - 'var foo, *' + - 'bar, *' + - 'baz;' - ); - + const regExp: RegExp = new RegExp('var foo, *' + 'bar, *' + 'baz;'); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/multiple-declarations-without-declarators.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/multiple-declarations-without-declarators.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge variable declarations', () => { @@ -148,27 +123,25 @@ describe('VariableDeclarationsMergeTransformer', () => { const regExp: RegExp = new RegExp( 'var foo *= *function *\\(\\) *{ *}, *' + 'bar *= *function *\\(\\) *{ *' + - 'var _0x([a-f0-9]){4,6} *= *function *\\(\\) *{ *}, *' + - '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{ *' + - 'var _0x([a-f0-9]){4,6} *= *0x1, *' + - '_0x([a-f0-9]){4,6} *= *0x2; *' + - '}; *' + + 'var _0x([a-f0-9]){4,6} *= *function *\\(\\) *{ *}, *' + + '_0x([a-f0-9]){4,6} *= *function *\\(\\) *{ *' + + 'var _0x([a-f0-9]){4,6} *= *0x1, *' + + '_0x([a-f0-9]){4,6} *= *0x2; *' + + '}; *' + '};' ); - let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/declarations-inside-nested-function-expressions.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/declarations-inside-nested-function-expressions.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge variable declarations', () => { @@ -180,24 +153,17 @@ describe('VariableDeclarationsMergeTransformer', () => { describe('object pattern as initializer', () => { stubNodeTransformers([ObjectPatternPropertiesTransformer]); - const regExp: RegExp = new RegExp( - 'var foo *= *0x1, *' + - '{bar} *= *{\'bar\': *0x2}, *' + - 'baz *= *0x3;' - ); + const regExp: RegExp = new RegExp('var foo *= *0x1, *' + "{bar} *= *{'bar': *0x2}, *" + 'baz *= *0x3;'); let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-pattern-as-initializer.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should merge variable declarations with object pattern', () => { @@ -209,9 +175,9 @@ describe('VariableDeclarationsMergeTransformer', () => { const regExp: RegExp = new RegExp( 'var foo *= *0x1, *' + 'bar *= *0x2; *' + - 'let baz *= *0x3, *' + + 'let baz *= *0x3, *' + 'bark *= *0x4;' + - 'const hawk *= *0x5, *' + + 'const hawk *= *0x5, *' + 'pork *= *0x6;' ); @@ -220,13 +186,10 @@ describe('VariableDeclarationsMergeTransformer', () => { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/different-variables-kind.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - simplify: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + simplify: true + }).getObfuscatedCode(); }); it('should keep unmerged variable declarations with different variable kinds', () => { diff --git a/test/functional-tests/node-transformers/string-array-transformers/string-array-rotate-function-transformer/StringArrayRotateFunctionTransformer.spec.ts b/test/functional-tests/node-transformers/string-array-transformers/string-array-rotate-function-transformer/StringArrayRotateFunctionTransformer.spec.ts index a5b99b10..c5f162cb 100644 --- a/test/functional-tests/node-transformers/string-array-transformers/string-array-rotate-function-transformer/StringArrayRotateFunctionTransformer.spec.ts +++ b/test/functional-tests/node-transformers/string-array-transformers/string-array-rotate-function-transformer/StringArrayRotateFunctionTransformer.spec.ts @@ -27,15 +27,12 @@ describe('StringArrayRotateFunctionTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should correctly append code helper into the obfuscated code', () => { @@ -43,24 +40,21 @@ describe('StringArrayRotateFunctionTransformer', function () { }); }); - describe('`stringArray` option isn\'t set', () => { + describe("`stringArray` option isn't set", () => { let obfuscatedCode: string; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: false, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: false, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t append code helper into the obfuscated code', () => { + it("shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, regExp); }); }); @@ -71,15 +65,12 @@ describe('StringArrayRotateFunctionTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 0.00001 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 0.00001 + }).getObfuscatedCode(); }); it('should correctly append code helper into the obfuscated code', () => { @@ -93,15 +84,12 @@ describe('StringArrayRotateFunctionTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); it('should correctly append code helper into the obfuscated code', () => { @@ -115,18 +103,15 @@ describe('StringArrayRotateFunctionTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/no-string-literals.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t append code helper into the obfuscated code', () => { + it("shouldn't append code helper into the obfuscated code", () => { assert.notMatch(obfuscatedCode, regExp); }); }); @@ -139,58 +124,51 @@ describe('StringArrayRotateFunctionTransformer', function () { let hasRuntimeErrors: boolean = false; - before(async() => { + before(async () => { const code: string = readFileAsString(__dirname + '/fixtures/code-evaluation.js'); const obfuscateFunc = () => { - return JavaScriptObfuscator.obfuscate( - code, - { - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 1, - deadCodeInjection: true, - deadCodeInjectionThreshold: 1, - debugProtection: true, - disableConsoleOutput: true, - identifierNamesGenerator: IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator, - numbersToExpressions: true, - simplify: true, - renameProperties: true, - stringArrayRotate: true, - selfDefending: true, - splitStrings: true, - splitStringsChunkLength: 3, - stringArray: true, - stringArrayCallsTransform: true, - stringArrayCallsTransformThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ], - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber, - StringArrayIndexesType.HexadecimalNumericString - ], - stringArrayIndexShift: true, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5, - stringArrayWrappersParametersMaxCount: 5, - stringArrayWrappersType: StringArrayWrappersType.Function, - stringArrayThreshold: 1, - transformObjectKeys: true, - unicodeEscapeSequence: true - } - ).getObfuscatedCode(); + return JavaScriptObfuscator.obfuscate(code, { + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 1, + deadCodeInjection: true, + deadCodeInjectionThreshold: 1, + debugProtection: true, + disableConsoleOutput: true, + identifierNamesGenerator: IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator, + numbersToExpressions: true, + simplify: true, + renameProperties: true, + stringArrayRotate: true, + selfDefending: true, + splitStrings: true, + splitStringsChunkLength: 3, + stringArray: true, + stringArrayCallsTransform: true, + stringArrayCallsTransformThreshold: 1, + stringArrayEncoding: [ + StringArrayEncoding.None, + StringArrayEncoding.Base64, + StringArrayEncoding.Rc4 + ], + stringArrayIndexesType: [ + StringArrayIndexesType.HexadecimalNumber, + StringArrayIndexesType.HexadecimalNumericString + ], + stringArrayIndexShift: true, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5, + stringArrayWrappersParametersMaxCount: 5, + stringArrayWrappersType: StringArrayWrappersType.Function, + stringArrayThreshold: 1, + transformObjectKeys: true, + unicodeEscapeSequence: true + }).getObfuscatedCode(); }; - for (let i = 0; i < samplesCount; i++) { try { - const evaluationResult = await evaluateInWorker( - obfuscateFunc(), - evaluationTimeout - ); + const evaluationResult = await evaluateInWorker(obfuscateFunc(), evaluationTimeout); if (evaluationResult !== 'fooooooo') { hasRuntimeErrors = true; @@ -229,21 +207,18 @@ describe('StringArrayRotateFunctionTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/early-successful-comparison.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - seed: i, - stringArrayRotate: true, - stringArrayShuffle: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + seed: i, + stringArrayRotate: true, + stringArrayShuffle: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); try { await evaluateInWorker(obfuscatedCode, evaluationTimeout); } catch (error) { - evaluationError = error + evaluationError = error; break; } @@ -257,7 +232,7 @@ describe('StringArrayRotateFunctionTransformer', function () { after(() => { numberNumericalExpressionAnalyzerAnalyzeStub.restore(); stringArrayRotateFunctionTransformerGetComparisonValueStub.restore(); - }) + }); }); }); }); diff --git a/test/functional-tests/node-transformers/string-array-transformers/string-array-scope-calls-wrapper-transformer/StringArrayScopeCallsWrapperTransformer.spec.ts b/test/functional-tests/node-transformers/string-array-transformers/string-array-scope-calls-wrapper-transformer/StringArrayScopeCallsWrapperTransformer.spec.ts index 49b58313..cc904f9d 100644 --- a/test/functional-tests/node-transformers/string-array-transformers/string-array-scope-calls-wrapper-transformer/StringArrayScopeCallsWrapperTransformer.spec.ts +++ b/test/functional-tests/node-transformers/string-array-transformers/string-array-scope-calls-wrapper-transformer/StringArrayScopeCallsWrapperTransformer.spec.ts @@ -21,11 +21,11 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #1: option value is lower then count `literal` nodes in the scope', () => { const stringArrayCallRegExp: RegExp = new RegExp( '(? { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -52,11 +49,11 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #2: option value is bigger then count `literal` nodes in the scope', () => { const stringArrayCallRegExp: RegExp = new RegExp( '(? { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -83,10 +77,10 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #3: correct wrappers order', () => { const stringArrayCallRegExp: RegExp = new RegExp( 'const f *= *b;.*' + - 'const g *= *b;.*' + - 'const foo *= *[f|g]\\(0x0\\);.*' + - 'const bar *= *[f|g]\\(0x1\\);.*' + - 'const baz *= *[f|g]\\(0x2\\);' + 'const g *= *b;.*' + + 'const foo *= *[f|g]\\(0x0\\);.*' + + 'const bar *= *[f|g]\\(0x1\\);.*' + + 'const baz *= *[f|g]\\(0x2\\);' ); let obfuscatedCode: string; @@ -94,16 +88,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -114,10 +105,10 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #4: `identifiersPrefix` option is set', () => { const stringArrayCallRegExp: RegExp = new RegExp( 'const foo_d *= *foo_b;.*' + - 'const foo_e *= *foo_b;.*' + - 'const foo *= *foo_[d|e]\\(0x0\\);.*' + - 'const bar *= *foo_[d|e]\\(0x1\\);.*' + - 'const baz *= *foo_[d|e]\\(0x2\\);' + 'const foo_e *= *foo_b;.*' + + 'const foo *= *foo_[d|e]\\(0x0\\);.*' + + 'const bar *= *foo_[d|e]\\(0x1\\);.*' + + 'const baz *= *foo_[d|e]\\(0x2\\);' ); let obfuscatedCode: string; @@ -125,17 +116,14 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'foo_', - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'foo_', + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -153,7 +141,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x3\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x4\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x5\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -161,15 +149,12 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -186,7 +171,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x3\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x4\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x5\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -194,15 +179,12 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -218,7 +200,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { 'const c *= *[h|i]\\(0x3\\);' + 'const d *= *[h|i]\\(0x4\\);' + 'const e *= *[h|i]\\(0x5\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -226,16 +208,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -246,28 +225,27 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #4: correct wrapper for the function default parameter', () => { const stringArrayCallRegExp: RegExp = new RegExp( 'const e *= *b;.*' + - 'const foo *= *e\\(0x0\\);.*' + - 'function test *\\(c *= *e\\(0x1\\)\\) *{' + + 'const foo *= *e\\(0x0\\);.*' + + 'function test *\\(c *= *e\\(0x1\\)\\) *{' + 'const f *= *b;' + 'const d *= *f\\(0x2\\);' + - '}' + '}' ); let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/wrapper-for-the-function-default-parameter.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/wrapper-for-the-function-default-parameter.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -283,7 +261,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { 'const a *= *[f|g]\\(0x3\\);' + 'const b *= *[f|g]\\(0x4\\);' + 'const c *= *[f|g]\\(0x5\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -291,17 +269,14 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - identifiersPrefix: 'foo_', - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + identifiersPrefix: 'foo_', + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers', () => { @@ -313,10 +288,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #3: prohibited scopes', () => { describe('Variant #1: if statement scope', () => { const stringArrayCallRegExp: RegExp = new RegExp( - 'var c *= *b;.*' + - 'if *\\(!!\\[]\\) *{' + - 'var foo *= *c\\(0x0\\);' + - '}' + 'var c *= *b;.*' + 'if *\\(!!\\[]\\) *{' + 'var foo *= *c\\(0x0\\);' + '}' ); let obfuscatedCode: string; @@ -324,16 +296,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prohibited-scope-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should not add scope calls wrappers to a prohibited scope', () => { @@ -343,8 +312,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #2: arrow function scope without statements', () => { const stringArrayCallRegExp: RegExp = new RegExp( - 'var c *= *b;.*' + - '\\[]\\[c\\(0x0\\)]\\(\\(\\) *=> *c\\(0x1\\)\\);' + 'var c *= *b;.*' + '\\[]\\[c\\(0x0\\)]\\(\\(\\) *=> *c\\(0x1\\)\\);' ); let obfuscatedCode: string; @@ -352,16 +320,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/prohibited-scope-2.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should not add scope calls wrappers to a prohibited scope', () => { @@ -373,11 +338,11 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #4: prevailing kind of variables', () => { const stringArrayCallRegExp: RegExp = new RegExp( '(? { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-var.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2 + }).getObfuscatedCode(); }); it('should add scope calls wrappers with a correct variables kind', () => { @@ -408,15 +370,12 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-eval.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); evaluationResult = eval(obfuscatedCode); }); @@ -431,25 +390,25 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #1: `Mangled` identifier names generator', () => { const stringArrayCallRegExp: RegExp = new RegExp( 'const q *= *b;.*' + - 'const foo *= *q\\(0x0\\);.*' + - 'function test\\(c, *d\\) *{' + + 'const foo *= *q\\(0x0\\);.*' + + 'function test\\(c, *d\\) *{' + 'const r *= *q;' + 'const e *= *r\\(0x1\\);' + 'const f *= *r\\(0x2\\);' + 'function g\\(h, *i\\) *{' + - 'const s *= *r;' + - 'const j *= *s\\(0x3\\);' + - 'const k *= *s\\(0x4\\);' + - 'function l\\(m, *n *\\) *{' + - 'const t *= *s;' + - 'const o *= *t\\(0x3\\);' + - 'const p *= *t\\(0x4\\);' + - 'return o *\\+ *p;' + - '}' + - 'return j *\\+ *k;' + + 'const s *= *r;' + + 'const j *= *s\\(0x3\\);' + + 'const k *= *s\\(0x4\\);' + + 'function l\\(m, *n *\\) *{' + + 'const t *= *s;' + + 'const o *= *t\\(0x3\\);' + + 'const p *= *t\\(0x4\\);' + + 'return o *\\+ *p;' + + '}' + + 'return j *\\+ *k;' + '}' + 'return e *\\+ *f *\\+ *g\\(\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -457,17 +416,14 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-1.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 1 + }).getObfuscatedCode(); }); it('should add correct scope calls wrappers', () => { @@ -487,21 +443,16 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-1.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: + IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -526,21 +477,15 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-1.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -567,21 +512,16 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-2.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: + IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -606,21 +546,15 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-2.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -647,26 +581,24 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #1: `hexadecimal-number` indexes type', () => { const getStringArrayCallsWrapperMatch = (stringArrayCallsWrapperName: string) => `function *${stringArrayCallsWrapperName} *\\(c, *d\\) *{` + - `return b\\([cd] *-(?: -)?${hexadecimalIndexMatch}, *[cd]\\);` + + `return b\\([cd] *-(?: -)?${hexadecimalIndexMatch}, *[cd]\\);` + '}'; const stringArrayScopeCallsWrapperRegExp1: RegExp = new RegExp( getStringArrayCallsWrapperMatch('f') ); const stringArrayScopeCallsWrapperRegExp2: RegExp = new RegExp( - 'function test *\\( *\\) *{.*' + - `${getStringArrayCallsWrapperMatch('g')}.*?` + - '}' + 'function test *\\( *\\) *{.*' + `${getStringArrayCallsWrapperMatch('g')}.*?` + '}' ); const stringArrayCallsWrapperCallsRegExp: RegExp = new RegExp( `const foo *= *f\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + - `const bar *= *f\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + - `const baz *= *f\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + - 'function test *\\( *\\) *{.*' + + `const bar *= *f\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + + `const baz *= *f\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + + 'function test *\\( *\\) *{.*' + `const c *= *g\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + `const d *= *g\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + `const e *= *g\\(-? *${hexadecimalIndexMatch}\\, *-? *${hexadecimalIndexMatch}\\);.*` + - '}' + '}' ); let obfuscatedCode: string; @@ -674,21 +606,17 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - const getObfuscatedCode: () => string = () => JavaScriptObfuscator.obfuscate( - code, - { + const getObfuscatedCode: () => string = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, stringArray: true, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber - ], + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber], stringArrayThreshold: 1, stringArrayWrappersChainedCalls: false, stringArrayWrappersCount: 1, stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); obfuscatedCode = getObfuscatedCode(); areSuccessEvaluations = checkCodeEvaluation( @@ -717,26 +645,24 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #2: `hexadecimal-numeric-string` indexes type', () => { const getStringArrayCallsWrapperMatch = (stringArrayCallsWrapperName: string) => `function *${stringArrayCallsWrapperName} *\\(c, *d\\) *{` + - `return b\\([cd] *-(?: -)?'${hexadecimalIndexMatch}', *[cd]\\);` + + `return b\\([cd] *-(?: -)?'${hexadecimalIndexMatch}', *[cd]\\);` + '}'; const stringArrayScopeCallsWrapperRegExp1: RegExp = new RegExp( getStringArrayCallsWrapperMatch('f') ); const stringArrayScopeCallsWrapperRegExp2: RegExp = new RegExp( - 'function test *\\( *\\) *{.*' + - `${getStringArrayCallsWrapperMatch('g')}.*?` + - '}' + 'function test *\\( *\\) *{.*' + `${getStringArrayCallsWrapperMatch('g')}.*?` + '}' ); const stringArrayCallsWrapperCallRegExp: RegExp = new RegExp( `const foo *= *f\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + - `const bar *= *f\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + - `const baz *= *f\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + - 'function test *\\( *\\) *{.*' + + `const bar *= *f\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + + `const baz *= *f\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + + 'function test *\\( *\\) *{.*' + `const c *= *g\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + `const d *= *g\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + `const e *= *g\\(-? *'${hexadecimalIndexMatch}', *-? *'${hexadecimalIndexMatch}'\\);.*` + - '}' + '}' ); let obfuscatedCode: string; @@ -744,21 +670,17 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - const getObfuscatedCode = () => JavaScriptObfuscator.obfuscate( - code, - { + const getObfuscatedCode = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, stringArray: true, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumericString - ], + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString], stringArrayThreshold: 1, stringArrayWrappersChainedCalls: false, stringArrayWrappersCount: 1, stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); obfuscatedCode = getObfuscatedCode(); areSuccessEvaluations = checkCodeEvaluation( @@ -789,28 +711,28 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const stringArrayScopeCallsWrapperRegExp1: RegExp = new RegExp( 'function *f *\\(c, *d\\) *{' + `return b\\([cd] *-(?: -)?${hexadecimalIndexMatch}, *[cd]\\);` + - '}.*' + '}.*' ); const stringArrayScopeCallsWrapperRegExp2: RegExp = new RegExp( 'function test *\\( *\\) *{.*' + 'function *g *\\(c, *d\\) *{' + - `return f\\(` + - // order of arguments depends on the parent wrapper parameters order - `[cd](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cd](?: *-(?: -)?${hexadecimalIndexMatch})?` + - `\\);` + + `return f\\(` + + // order of arguments depends on the parent wrapper parameters order + `[cd](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cd](?: *-(?: -)?${hexadecimalIndexMatch})?` + + `\\);` + '}.*' + - '}' + '}' ); const stringArrayCallsWrapperCallRegExp: RegExp = new RegExp( `const foo *= *f\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + - `const bar *= *f\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + - `const baz *= *f\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + - 'function test *\\( *\\) *{.*' + + `const bar *= *f\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + + `const baz *= *f\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + + 'function test *\\( *\\) *{.*' + `const c *= *g\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + `const d *= *g\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + `const e *= *g\\(-? *${hexadecimalIndexMatch}, *-? *${hexadecimalIndexMatch}\\);.*` + - '}' + '}' ); let obfuscatedCode: string; @@ -818,9 +740,8 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - const getObfuscatedCode = () => JavaScriptObfuscator.obfuscate( - code, - { + const getObfuscatedCode = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, stringArray: true, @@ -828,8 +749,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { stringArrayWrappersChainedCalls: true, stringArrayWrappersCount: 1, stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); obfuscatedCode = getObfuscatedCode(); areSuccessEvaluations = checkCodeEvaluation( @@ -859,27 +779,28 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const stringArrayScopeCallsWrapperRegExp: RegExp = new RegExp( 'function test *\\( *\\) *{.*' + 'function *f*\\(c, *d\\) *{' + - `return b\\([cd] *-(?: -)?${hexadecimalIndexMatch}, *[cd]\\);` + + `return b\\([cd] *-(?: -)?${hexadecimalIndexMatch}, *[cd]\\);` + '}.*' + - '}' + '}' ); const stringArrayCallsWrapperCallRegExp: RegExp = new RegExp( '(? { - const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const-no-root-wrappers.js'); - const getObfuscatedCode = () => JavaScriptObfuscator.obfuscate( - code, - { + const code: string = readFileAsString( + __dirname + '/fixtures/wrappers-count-const-no-root-wrappers.js' + ); + const getObfuscatedCode = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, stringArray: true, @@ -887,8 +808,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { stringArrayWrappersChainedCalls: true, stringArrayWrappersCount: 1, stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); obfuscatedCode = getObfuscatedCode(); areSuccessEvaluations = checkCodeEvaluation( @@ -921,21 +841,17 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-1.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5, - stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: + IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5, + stringArrayWrappersType: StringArrayWrappersType.Function + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -960,21 +876,16 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-1.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5, - stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5, + stringArrayWrappersType: StringArrayWrappersType.Function + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -1001,22 +912,17 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-2.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5, - stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: + IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5, + stringArrayWrappersType: StringArrayWrappersType.Function + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -1041,22 +947,16 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/chained-calls-2.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 5, - stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 5, + stringArrayWrappersType: StringArrayWrappersType.Function + }).getObfuscatedCode(); const evaluationResult: string = eval(obfuscatedCode); @@ -1083,32 +983,32 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const stringArrayScopeCallsWrapperRegExp1: RegExp = new RegExp( 'function *f *\\(c, *d, *e, *h, *i\\) *{' + `return b\\([cdehi] *-(?: -)?${hexadecimalIndexMatch}, *[cdehi]\\);` + - '}.*' + '}.*' ); const stringArrayScopeCallsWrapperRegExp2: RegExp = new RegExp( 'function test *\\( *\\) *{.*' + 'function *g *\\(c, *d, *e, *h, *i\\) *{' + - `return f\\(` + - // order of arguments depends on the parent wrapper parameters order - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?` + - `\\);` + + `return f\\(` + + // order of arguments depends on the parent wrapper parameters order + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?` + + `\\);` + '}.*' + - '}' + '}' ); const stringArrayCallsWrapperCallRegExp: RegExp = new RegExp( `const foo *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - `const bar *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - `const baz *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - 'function test *\\( *\\) *{.*' + + `const bar *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + + `const baz *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + + 'function test *\\( *\\) *{.*' + `const c *= *g\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + `const d *= *g\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + `const e *= *g\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - '}' + '}' ); let obfuscatedCode: string; @@ -1116,9 +1016,8 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - const getObfuscatedCode = () => JavaScriptObfuscator.obfuscate( - code, - { + const getObfuscatedCode = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, stringArray: true, @@ -1127,8 +1026,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { stringArrayWrappersCount: 1, stringArrayWrappersParametersMaxCount: 5, stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); obfuscatedCode = getObfuscatedCode(); areSuccessEvaluations = checkCodeEvaluation( @@ -1162,32 +1060,32 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { const stringArrayScopeCallsWrapperRegExp1: RegExp = new RegExp( 'function *f *\\(c, *d, *e, *h, *i\\) *{' + `return b\\([cdehi] *-(?: -)?${hexadecimalIndexMatch}, *[cdehi]\\);` + - '}.*' + '}.*' ); const stringArrayScopeCallsWrapperRegExp2: RegExp = new RegExp( 'function test *\\( *\\) *{.*' + 'function *g *\\(c, *d, *e, *h, *i\\) *{' + - `return f\\(` + - // order of arguments depends on the parent wrapper parameters order - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + - `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?` + - `\\);` + + `return f\\(` + + // order of arguments depends on the parent wrapper parameters order + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?, *` + + `[cdehi](?: *-(?: -)?${hexadecimalIndexMatch})?` + + `\\);` + '}.*' + - '}' + '}' ); const stringArrayCallsWrapperCallRegExp: RegExp = new RegExp( `const foo *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - `const bar *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - `const baz *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - 'function test *\\( *\\) *{.*' + + `const bar *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + + `const baz *= *f\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + + 'function test *\\( *\\) *{.*' + `const c *= *g\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + `const d *= *g\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + `const e *= *g\\(${stringArrayWrapperArgumentsRegExpString}\\);.*` + - '}' + '}' ); let obfuscatedCode: string; @@ -1195,22 +1093,18 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - const getObfuscatedCode = () => JavaScriptObfuscator.obfuscate( - code, - { + const getObfuscatedCode = () => + JavaScriptObfuscator.obfuscate(code, { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.Rc4 - ], + stringArrayEncoding: [StringArrayEncoding.Rc4], stringArrayThreshold: 1, stringArrayWrappersChainedCalls: true, stringArrayWrappersCount: 1, stringArrayWrappersParametersMaxCount: 5, stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); obfuscatedCode = getObfuscatedCode(); areSuccessEvaluations = checkCodeEvaluation( @@ -1240,7 +1134,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #6: different indexes for calls wrappers', () => { const getStringArrayScopeCallsWrapperMatch = (stringArrayScopeCallsWrapperName: string) => `function *${stringArrayScopeCallsWrapperName} *\\(e, *f\\) *{` + - `return b\\([ef] *-(?: -)?(${hexadecimalIndexMatch}), *[ef]\\);` + + `return b\\([ef] *-(?: -)?(${hexadecimalIndexMatch}), *[ef]\\);` + '}.*'; const stringArrayScopeCallsWrapperIndexRegExp1: RegExp = new RegExp( @@ -1255,22 +1149,21 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { let differentIndexesMatchesDelta: number = 3; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/function-calls-wrappers-different-indexes.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/function-calls-wrappers-different-indexes.js' + ); for (let i = 0; i < differentIndexesMatchesSamplesCount; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, - stringArray: true, - stringArrayThreshold: 1, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersCount: 2, - stringArrayWrappersParametersMaxCount: 2, - stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator, + stringArray: true, + stringArrayThreshold: 1, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersCount: 2, + stringArrayWrappersParametersMaxCount: 2, + stringArrayWrappersType: StringArrayWrappersType.Function + }).getObfuscatedCode(); const indexMatch1 = getRegExpMatch(obfuscatedCode, stringArrayScopeCallsWrapperIndexRegExp1); const indexMatch2 = getRegExpMatch(obfuscatedCode, stringArrayScopeCallsWrapperIndexRegExp2); @@ -1297,13 +1190,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #1: `1` scope calls wrapper for each encoding type', () => { const stringArrayWrappersRegExp: RegExp = new RegExp( '(? { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64 - ], - stringArrayWrappersCount: 1, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64], + stringArrayWrappersCount: 1, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add scope calls wrappers for both `none` and `base64` string array wrappers', () => { @@ -1334,13 +1221,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { describe('Variant #2: `2` scope calls wrappers for each encoding type', () => { const stringArrayWrappersRegExp: RegExp = new RegExp( '(? { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64 - ], - stringArrayWrappersCount: 2, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64], + stringArrayWrappersCount: 2, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add scope calls wrappers for both `none` and `base64` string array wrappers', () => { @@ -1380,7 +1261,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x3\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x4\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x5\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -1388,19 +1269,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64 - ], - stringArrayWrappersCount: 1, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64], + stringArrayWrappersCount: 1, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add scope calls wrappers for both `none` and `base64` string array wrappers', () => { @@ -1419,7 +1294,7 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x3\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x4\\);' + 'const _0x([a-f0-9]){4,6} *= *_0x([a-f0-9]){4,6}\\(0x5\\);' + - '}' + '}' ); let obfuscatedCode: string; @@ -1427,19 +1302,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-const.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64 - ], - stringArrayWrappersCount: 2, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64], + stringArrayWrappersCount: 2, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should add scope calls wrappers for both `none` and `base64` string array wrappers', () => { @@ -1457,19 +1326,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-eval.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); evaluationResult = eval(obfuscatedCode); }); @@ -1488,19 +1351,13 @@ describe('StringArrayScopeCallsWrapperTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/wrappers-count-eval.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ], - stringArrayWrappersCount: 5 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayEncoding: [StringArrayEncoding.Base64, StringArrayEncoding.Rc4], + stringArrayWrappersCount: 5 + }).getObfuscatedCode(); evaluationResult = eval(obfuscatedCode); }); diff --git a/test/functional-tests/node-transformers/string-array-transformers/string-array-transformer/StringArrayTransformer.spec.ts b/test/functional-tests/node-transformers/string-array-transformers/string-array-transformer/StringArrayTransformer.spec.ts index 8646325a..74e323bf 100644 --- a/test/functional-tests/node-transformers/string-array-transformers/string-array-transformer/StringArrayTransformer.spec.ts +++ b/test/functional-tests/node-transformers/string-array-transformers/string-array-transformer/StringArrayTransformer.spec.ts @@ -26,14 +26,11 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should replace literal node value with value from string array', () => { @@ -53,15 +50,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET + }).getObfuscatedCode(); }); - it('shouldn\'t replace literal node value with value from string array', () => { + it("shouldn't replace literal node value with value from string array", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -75,17 +69,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber - ] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumber] + }).getObfuscatedCode(); }); it('match #1: should transform string array index with the passed index type', () => { @@ -101,17 +90,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumericString - ] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexesType: [StringArrayIndexesType.HexadecimalNumericString] + }).getObfuscatedCode(); }); it('match #1: should transform string array index with the passed index type', () => { @@ -137,18 +121,15 @@ describe('StringArrayTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - const obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexesType: [ - StringArrayIndexesType.HexadecimalNumber, - StringArrayIndexesType.HexadecimalNumericString - ] - } - ).getObfuscatedCode(); + const obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexesType: [ + StringArrayIndexesType.HexadecimalNumber, + StringArrayIndexesType.HexadecimalNumericString + ] + }).getObfuscatedCode(); if (obfuscatedCode.match(hexadecimalNumberIndexTypeRegExp)) { hexadecimalNumberIndexTypeMatchesCount += 1; @@ -159,7 +140,8 @@ describe('StringArrayTransformer', function () { } hexadecimalNumberIndexTypeMatchesChance = hexadecimalNumberIndexTypeMatchesCount / samplesCount; - hexadecimalNumericStringIndexTypeMatchesChance = hexadecimalNumericStringIndexTypeMatchesCount / samplesCount; + hexadecimalNumericStringIndexTypeMatchesChance = + hexadecimalNumericStringIndexTypeMatchesCount / samplesCount; } }); @@ -168,16 +150,24 @@ describe('StringArrayTransformer', function () { }); it('should transform string array indexes with a `hexadecimal-numeric-string` type', () => { - assert.closeTo(hexadecimalNumericStringIndexTypeMatchesChance, expectedMatchesChance, expectedMatchesDelta); + assert.closeTo( + hexadecimalNumericStringIndexTypeMatchesChance, + expectedMatchesChance, + expectedMatchesDelta + ); }); }); }); describe('Variant #4: `stringArrayIndexShift` option is enabled', () => { - const stringArrayIndexShiftRegExp: RegExp = /_0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6} *- *(0x[a-z0-9]{1,3});/; - const stringArrayCallRegExp1: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4}\((0x[a-z0-9]{1,3})\) *\+ *0x1;/; - const stringArrayCallRegExp2: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4}\((0x[a-z0-9]{1,3})\) *\+ *0x2;/; - const stringArrayCallRegExp3: RegExp = /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4}\((0x[a-z0-9]{1,3})\) *\+ *0x3;/; + const stringArrayIndexShiftRegExp: RegExp = + /_0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4,6} *- *(0x[a-z0-9]{1,3});/; + const stringArrayCallRegExp1: RegExp = + /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4}\((0x[a-z0-9]{1,3})\) *\+ *0x1;/; + const stringArrayCallRegExp2: RegExp = + /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4}\((0x[a-z0-9]{1,3})\) *\+ *0x2;/; + const stringArrayCallRegExp3: RegExp = + /var _0x(?:[a-f0-9]){4,6} *= *_0x(?:[a-f0-9]){4}\((0x[a-z0-9]{1,3})\) *\+ *0x3;/; const expectedEvaluationResult: string = 'foo1bar2baz3'; @@ -194,17 +184,17 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-index-shift.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexShift: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexShift: true + }).getObfuscatedCode(); - stringArrayIndexShiftIndexValue = parseInt(getRegExpMatch(obfuscatedCode, stringArrayIndexShiftRegExp), 16); + stringArrayIndexShiftIndexValue = parseInt( + getRegExpMatch(obfuscatedCode, stringArrayIndexShiftRegExp), + 16 + ); stringArrayCallIndexValue1 = parseInt(getRegExpMatch(obfuscatedCode, stringArrayCallRegExp1), 16); stringArrayCallIndexValue2 = parseInt(getRegExpMatch(obfuscatedCode, stringArrayCallRegExp2), 16); stringArrayCallIndexValue3 = parseInt(getRegExpMatch(obfuscatedCode, stringArrayCallRegExp3), 16); @@ -237,18 +227,18 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-index-shift.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexShift: true, - stringArrayRotate: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexShift: true, + stringArrayRotate: true + }).getObfuscatedCode(); - stringArrayIndexShiftIndexValue = parseInt(getRegExpMatch(obfuscatedCode, stringArrayIndexShiftRegExp), 16); + stringArrayIndexShiftIndexValue = parseInt( + getRegExpMatch(obfuscatedCode, stringArrayIndexShiftRegExp), + 16 + ); stringArrayCallIndexValue1 = parseInt(getRegExpMatch(obfuscatedCode, stringArrayCallRegExp1), 16); stringArrayCallIndexValue2 = parseInt(getRegExpMatch(obfuscatedCode, stringArrayCallRegExp2), 16); stringArrayCallIndexValue3 = parseInt(getRegExpMatch(obfuscatedCode, stringArrayCallRegExp3), 16); @@ -269,16 +259,13 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-index-shift.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexShift: true, - stringArrayShuffle: true - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexShift: true, + stringArrayShuffle: true + }).getObfuscatedCode(); evaluationResult = eval(obfuscatedCode); }); @@ -296,17 +283,14 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-index-shift.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - stringArrayIndexShift: true, - stringArrayWrappersCount: 1, - stringArrayWrappersType: StringArrayWrappersType.Function - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + stringArrayIndexShift: true, + stringArrayWrappersCount: 1, + stringArrayWrappersType: StringArrayWrappersType.Function + }).getObfuscatedCode(); evaluationResult = eval(obfuscatedCode); }); @@ -324,23 +308,18 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-index-shift.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArrayShuffle: true, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.Rc4 - ], - stringArrayIndexShift: true, - stringArrayThreshold: 1, - stringArrayWrappersCount: 2, - stringArrayWrappersChainedCalls: true, - stringArrayWrappersType: 'function' - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArrayShuffle: true, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.Rc4], + stringArrayIndexShift: true, + stringArrayThreshold: 1, + stringArrayWrappersCount: 2, + stringArrayWrappersChainedCalls: true, + stringArrayWrappersType: 'function' + }).getObfuscatedCode(); evaluationResult = eval(obfuscatedCode); }); @@ -364,14 +343,11 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/same-literal-values.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should create only one item in string array for same literal node values', () => { @@ -391,17 +367,14 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/short-literal-value.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); - it('shouldn\'t replace short literal node value with value from string array', () => { + it("shouldn't replace short literal node value with value from string array", () => { assert.match(obfuscatedCode, regExp); }); }); @@ -411,7 +384,7 @@ describe('StringArrayTransformer', function () { 'function _0x([a-f0-9]){4} *\\(\\) *{' + `var _0x([a-f0-9]){4,6} *= *\\[\'${swapLettersCase('dGVzdA')}\'];.*` + 'return _0x([a-f0-9]){4}\\(\\); *' + - '}' + '}' ); const stringArrayCallRegExp: RegExp = /var test *= *_0x([a-f0-9]){4}\(0x0\);/; @@ -420,15 +393,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [StringArrayEncoding.Base64], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.Base64], + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should replace literal node value with value from string array encoded using base64', () => { @@ -449,15 +419,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [StringArrayEncoding.Rc4], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.Rc4], + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('should replace literal node value with value from string array encoded using rc4', () => { @@ -477,16 +444,13 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/same-literal-values.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - seed: 1, // set seed to prevent rare case when all encoded values are the same - stringArray: true, - stringArrayEncoding: [StringArrayEncoding.Rc4], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + seed: 1, // set seed to prevent rare case when all encoded values are the same + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.Rc4], + stringArrayThreshold: 1 + }).getObfuscatedCode(); encodedLiteralValue1 = getRegExpMatch(obfuscatedCode, variableRegExp1); encodedLiteralValue2 = getRegExpMatch(obfuscatedCode, variableRegExp2); @@ -526,18 +490,12 @@ describe('StringArrayTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64 - ], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64], + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (obfuscatedCode.match(noneEncodingRegExp)) { noneEncodingMatchesCount = noneEncodingMatchesCount + 1; @@ -582,18 +540,12 @@ describe('StringArrayTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Rc4 - ], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Rc4], + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (obfuscatedCode.match(noneEncodingRegExp)) { noneEncodingMatchesCount = noneEncodingMatchesCount + 1; @@ -638,18 +590,12 @@ describe('StringArrayTransformer', function () { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); for (let i = 0; i < samplesCount; i++) { - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayEncoding: [ - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ], - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.Base64, StringArrayEncoding.Rc4], + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (obfuscatedCode.match(base64EncodingRegExp)) { base64EncodingMatchesCount = base64EncodingMatchesCount + 1; @@ -682,27 +628,19 @@ describe('StringArrayTransformer', function () { const regExp1: RegExp = /var test *= *_0x([a-f0-9]){4}\(0x0\);/g; const regExp2: RegExp = /var test *= *'test';/g; - let stringArrayProbability: number, - noStringArrayProbability: number; + let stringArrayProbability: number, noStringArrayProbability: number; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/simple-input.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - `${code}\n`.repeat(samples), - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: stringArrayThreshold - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(`${code}\n`.repeat(samples), { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: stringArrayThreshold + }).getObfuscatedCode(); - const stringArrayMatchesLength: number = obfuscatedCode - .match(regExp1)! - .length; - const noStringArrayMatchesLength: number = obfuscatedCode - .match(regExp2)! - .length; + const stringArrayMatchesLength: number = obfuscatedCode.match(regExp1)!.length; + const noStringArrayMatchesLength: number = obfuscatedCode.match(regExp2)!.length; stringArrayProbability = stringArrayMatchesLength / samples; noStringArrayProbability = noStringArrayMatchesLength / samples; @@ -712,7 +650,7 @@ describe('StringArrayTransformer', function () { assert.closeTo(stringArrayProbability, stringArrayThreshold, delta); }); - it('Variant #2: shouldn\'t replace literal node value with value from string array with `(1 - stringArrayThreshold)` chance', () => { + it("Variant #2: shouldn't replace literal node value with value from string array with `(1 - stringArrayThreshold)` chance", () => { assert.closeTo(noStringArrayProbability, stringArrayThreshold, delta); }); }); @@ -725,15 +663,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/string-array-calls-wrapper-name.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + identifierNamesGenerator: IdentifierNamesGenerator.MangledIdentifierNamesGenerator + }).getObfuscatedCode(); }); it('match #1: should keep identifier with string array calls wrapper name untouched after obfuscation', () => { @@ -752,15 +687,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - reservedStrings: ['foo'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + reservedStrings: ['foo'] + }).getObfuscatedCode(); }); it('match #1: should ignore reserved strings', () => { @@ -781,15 +713,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - reservedStrings: ['foo', 'bar'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + reservedStrings: ['foo', 'bar'] + }).getObfuscatedCode(); }); it('match #1: should ignore reserved strings', () => { @@ -812,15 +741,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - reservedStrings: ['ar$'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + reservedStrings: ['ar$'] + }).getObfuscatedCode(); }); it('match #1: should transform non-reserved strings', () => { @@ -841,15 +767,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/reserved-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1, - reservedStrings: ['^fo', '.ar'] - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1, + reservedStrings: ['^fo', '.ar'] + }).getObfuscatedCode(); }); it('match #1: should ignore reserved strings', () => { @@ -874,15 +797,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['bar'], - stringArray: true, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['bar'], + stringArray: true, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); it('match #1: should not transform string', () => { @@ -903,15 +823,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['foo', 'bar'], - stringArray: true, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['foo', 'bar'], + stringArray: true, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); it('match #1: should transform force transform string', () => { @@ -934,15 +851,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['ar$'], - stringArray: true, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['ar$'], + stringArray: true, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); it('match #1: should not transform string', () => { @@ -963,15 +877,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['^fo', '.ar'], - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['^fo', '.ar'], + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should transform force transform string', () => { @@ -994,15 +905,12 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['foo', 'bar'], - stringArray: false, - stringArrayThreshold: 0 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['foo', 'bar'], + stringArray: false, + stringArrayThreshold: 0 + }).getObfuscatedCode(); }); it('match #1: should not transform string', () => { @@ -1025,16 +933,13 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['bar'], - reservedStrings: ['foo', 'bar'], - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['bar'], + reservedStrings: ['foo', 'bar'], + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should not transform string', () => { @@ -1056,17 +961,16 @@ describe('StringArrayTransformer', function () { let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/force-transform-strings-option-conditional-comments.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/force-transform-strings-option-conditional-comments.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - forceTransformStrings: ['bar'], - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + forceTransformStrings: ['bar'], + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should not transform string', () => { @@ -1086,7 +990,7 @@ describe('StringArrayTransformer', function () { describe('Variant #16: object expression key literal', () => { describe('Variant #1: base key literal', () => { - const stringArrayRegExp: RegExp = getStringArrayRegExp(['bar']) + const stringArrayRegExp: RegExp = getStringArrayRegExp(['bar']); const objectExpressionRegExp: RegExp = /var test *= *{'foo' *: *_0x([a-f0-9]){4}\(0x0\)};/; let obfuscatedCode: string; @@ -1094,14 +998,11 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/object-expression-key-literal.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should not add object expression key literal to the string array', () => { @@ -1114,22 +1015,22 @@ describe('StringArrayTransformer', function () { }); describe('Variant #2: computed key literal', () => { - const stringArrayRegExp: RegExp = getStringArrayRegExp(['foo', 'bar']) - const objectExpressionRegExp: RegExp = /var test *= *{\[_0x([a-f0-9]){4}\(0x0\)] *: *_0x([a-f0-9]){4}\(0x1\)};/; + const stringArrayRegExp: RegExp = getStringArrayRegExp(['foo', 'bar']); + const objectExpressionRegExp: RegExp = + /var test *= *{\[_0x([a-f0-9]){4}\(0x0\)] *: *_0x([a-f0-9]){4}\(0x1\)};/; let obfuscatedCode: string; before(() => { - const code: string = readFileAsString(__dirname + '/fixtures/object-expression-computed-key-literal.js'); + const code: string = readFileAsString( + __dirname + '/fixtures/object-expression-computed-key-literal.js' + ); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('match #1: should add object expression computed key literal to the string array', () => { @@ -1150,14 +1051,11 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/import-declaration-source.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Should not add `ImportDeclaration` source literal to the string array', () => { @@ -1173,14 +1071,11 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/export-all-declaration-source.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Should not add `ExportAllDeclaration` source literal to the string array', () => { @@ -1196,14 +1091,11 @@ describe('StringArrayTransformer', function () { before(() => { const code: string = readFileAsString(__dirname + '/fixtures/export-named-declaration-source.js'); - obfuscatedCode = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + obfuscatedCode = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); }); it('Should not add `ExportNamedDeclaration` source literal to the string array', () => { diff --git a/test/functional-tests/options/Options.spec.ts b/test/functional-tests/options/Options.spec.ts index 86c69389..53cc30ad 100644 --- a/test/functional-tests/options/Options.spec.ts +++ b/test/functional-tests/options/Options.spec.ts @@ -24,19 +24,17 @@ use(chaiExclude); /** * @param {TInputOptions} inputOptions */ -function getOptions (inputOptions: TInputOptions): IOptions { +function getOptions(inputOptions: TInputOptions): IOptions { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', inputOptions); - return inversifyContainerFacade - .get(ServiceIdentifiers.IOptions); + return inversifyContainerFacade.get(ServiceIdentifiers.IOptions); } describe('Options', () => { describe('Options preset', () => { - let options: IOptions, - expectedOptions: TInputOptions; + let options: IOptions, expectedOptions: TInputOptions; describe('Preset selection', () => { describe('Default preset', () => { diff --git a/test/functional-tests/options/OptionsNormalizer.spec.ts b/test/functional-tests/options/OptionsNormalizer.spec.ts index 76622cf6..d09abc24 100644 --- a/test/functional-tests/options/OptionsNormalizer.spec.ts +++ b/test/functional-tests/options/OptionsNormalizer.spec.ts @@ -20,15 +20,15 @@ import { InversifyContainerFacade } from '../../../src/container/InversifyContai * @param optionsPreset * @returns {IOptions} */ -function getNormalizedOptions (optionsPreset: TInputOptions): TInputOptions { +function getNormalizedOptions(optionsPreset: TInputOptions): TInputOptions { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', optionsPreset); - const options: IOptions = inversifyContainerFacade - .get(ServiceIdentifiers.IOptions); - const optionsNormalizer: IOptionsNormalizer = inversifyContainerFacade - .get(ServiceIdentifiers.IOptionsNormalizer); + const options: IOptions = inversifyContainerFacade.get(ServiceIdentifiers.IOptions); + const optionsNormalizer: IOptionsNormalizer = inversifyContainerFacade.get( + ServiceIdentifiers.IOptionsNormalizer + ); return optionsNormalizer.normalize(options); } @@ -42,8 +42,7 @@ function getDefaultOptions(): TInputOptions { describe('OptionsNormalizer', () => { describe('normalize', () => { - let optionsPreset: TInputOptions, - expectedOptionsPreset: TInputOptions; + let optionsPreset: TInputOptions, expectedOptionsPreset: TInputOptions; describe('controlFlowFlatteningThresholdRule', () => { before(() => { @@ -164,17 +163,13 @@ describe('OptionsNormalizer', () => { before(() => { optionsPreset = getNormalizedOptions({ ...getDefaultOptions(), - domainLock: [ - 'localhost' - ], + domainLock: ['localhost'], domainLockRedirectUrl: 'https://example.com' }); expectedOptionsPreset = { ...getDefaultOptions(), - domainLock: [ - 'localhost' - ], + domainLock: ['localhost'], domainLockRedirectUrl: 'https://example.com' }; }); @@ -209,18 +204,12 @@ describe('OptionsNormalizer', () => { before(() => { optionsPreset = getNormalizedOptions({ ...getDefaultOptions(), - domainLock: [ - '//localhost:9000', - 'https://google.ru/abc?cde=fgh' - ] + domainLock: ['//localhost:9000', 'https://google.ru/abc?cde=fgh'] }); expectedOptionsPreset = { ...getDefaultOptions(), - domainLock: [ - 'localhost', - 'google.ru' - ] + domainLock: ['localhost', 'google.ru'] }; }); @@ -230,7 +219,7 @@ describe('OptionsNormalizer', () => { }); describe('inputFileNameRule', () => { - describe('Variant #1: extension isn\'t set', () => { + describe("Variant #1: extension isn't set", () => { before(() => { optionsPreset = getNormalizedOptions({ ...getDefaultOptions(), @@ -536,7 +525,7 @@ describe('OptionsNormalizer', () => { before(() => { optionsPreset = getNormalizedOptions({ ...getDefaultOptions(), - sourceMapBaseUrl: 'http://localhost:9000', + sourceMapBaseUrl: 'http://localhost:9000' }); expectedOptionsPreset = { @@ -800,9 +789,7 @@ describe('OptionsNormalizer', () => { expectedOptionsPreset = { ...getDefaultOptions(), - stringArrayEncoding: [ - StringArrayEncoding.None - ] + stringArrayEncoding: [StringArrayEncoding.None] }; }); @@ -831,4 +818,4 @@ describe('OptionsNormalizer', () => { }); }); }); -}); \ No newline at end of file +}); diff --git a/test/functional-tests/options/domain-lock-destination/Validation.spec.ts b/test/functional-tests/options/domain-lock-destination/Validation.spec.ts index 4fb8b2a8..155ab6b3 100644 --- a/test/functional-tests/options/domain-lock-destination/Validation.spec.ts +++ b/test/functional-tests/options/domain-lock-destination/Validation.spec.ts @@ -11,13 +11,11 @@ describe('`domainLockRedirectUrl` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLockRedirectUrl: 'https://example.com/path' - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -29,13 +27,11 @@ describe('`domainLockRedirectUrl` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLockRedirectUrl: 'example.com/path' - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -47,13 +43,11 @@ describe('`domainLockRedirectUrl` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLockRedirectUrl: '/path' - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -65,13 +59,11 @@ describe('`domainLockRedirectUrl` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLockRedirectUrl: 'about:blank' - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -86,13 +78,11 @@ describe('`domainLockRedirectUrl` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLockRedirectUrl: 'foo' - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { diff --git a/test/functional-tests/options/domain-lock/Validation.spec.ts b/test/functional-tests/options/domain-lock/Validation.spec.ts index 4ec195dd..765ffd0a 100644 --- a/test/functional-tests/options/domain-lock/Validation.spec.ts +++ b/test/functional-tests/options/domain-lock/Validation.spec.ts @@ -13,14 +13,12 @@ describe('`domainLock` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLock: ['www.example.com'], target: ObfuscationTarget.Browser - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation when obfuscation target is `browser`', () => { @@ -32,14 +30,12 @@ describe('`domainLock` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLock: [], target: ObfuscationTarget.Node - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation when obfuscation target is `node` and value is default', () => { @@ -54,14 +50,12 @@ describe('`domainLock` validation', () => { describe('Variant #1: obfuscation target: `node`', () => { beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLock: ['www.example.com'], target: ObfuscationTarget.Node - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation when obfuscation target is `node` and value is not default', () => { @@ -71,14 +65,12 @@ describe('`domainLock` validation', () => { describe('Variant #1: obfuscation target: `service-worker`', () => { beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, domainLock: ['www.example.com'], target: ObfuscationTarget.ServiceWorker - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation when obfuscation target is `service-worker` and value is not default', () => { diff --git a/test/functional-tests/options/identifier-names-cache/Validation.spec.ts b/test/functional-tests/options/identifier-names-cache/Validation.spec.ts index b6f60c10..e4c3c8b3 100644 --- a/test/functional-tests/options/identifier-names-cache/Validation.spec.ts +++ b/test/functional-tests/options/identifier-names-cache/Validation.spec.ts @@ -11,9 +11,8 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: { @@ -23,8 +22,7 @@ describe('`identifierNamesCache` validation', () => { bar: '_0x654321' } } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -36,9 +34,8 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: { @@ -46,8 +43,7 @@ describe('`identifierNamesCache` validation', () => { }, propertyIdentifiers: {} } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -59,16 +55,14 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: {}, propertyIdentifiers: {} } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -80,17 +74,15 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: { foo: '_0x123456' } } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -102,13 +94,11 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: {} - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -120,13 +110,11 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: null - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -142,13 +130,11 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: 'cache' - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { @@ -160,19 +146,17 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: { foo: 1, - bar: 2, + bar: 2 }, propertyIdentifiers: {} } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { @@ -184,22 +168,20 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: { foo: 1, - bar: 2, + bar: 2 }, propertyIdentifiers: { baz: 3, - bark: 4, + bark: 4 } } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { @@ -211,21 +193,19 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: { foo: 1, - bar: '_0x1234567', + bar: '_0x1234567' }, propertyIdentifiers: { foo: '_0x123456' } } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { @@ -237,16 +217,14 @@ describe('`identifierNamesCache` validation', () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, identifierNamesCache: { globalIdentifiers: null, propertyIdentifiers: null } - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { diff --git a/test/functional-tests/options/input-file-name/Validation.spec.ts b/test/functional-tests/options/input-file-name/Validation.spec.ts index 501b0944..a4273c86 100644 --- a/test/functional-tests/options/input-file-name/Validation.spec.ts +++ b/test/functional-tests/options/input-file-name/Validation.spec.ts @@ -8,18 +8,16 @@ import { SourceMapSourcesMode } from '../../../../src/enums/source-map/SourceMap describe('`inputFileName` validation', () => { describe('IsInputFileName', () => { describe('Variant #1: positive validation', () => { - describe('Variant #1: empty string when `sourceMapSourcesMode: \'sources-content\'', () => { + describe("Variant #1: empty string when `sourceMapSourcesMode: 'sources-content'", () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, inputFileName: '', sourceMapSourcesMode: SourceMapSourcesMode.SourcesContent - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -27,18 +25,16 @@ describe('`inputFileName` validation', () => { }); }); - describe('Variant #2: string with input file name when `sourceMapSourcesMode: \'sources\'', () => { + describe("Variant #2: string with input file name when `sourceMapSourcesMode: 'sources'", () => { let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, inputFileName: 'some-file.js', sourceMapSourcesMode: SourceMapSourcesMode.Sources - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should pass validation', () => { @@ -48,19 +44,17 @@ describe('`inputFileName` validation', () => { }); describe('Variant #2: negative validation', () => { - describe('Variant #1: empty string when `sourceMapSourcesMode: \'sources\'', () => { + describe("Variant #1: empty string when `sourceMapSourcesMode: 'sources'", () => { const expectedError: string = 'should not be empty'; let testFunc: () => string; beforeEach(() => { - testFunc = () => JavaScriptObfuscator.obfuscate( - '', - { + testFunc = () => + JavaScriptObfuscator.obfuscate('', { ...NO_ADDITIONAL_NODES_PRESET, inputFileName: '', sourceMapSourcesMode: SourceMapSourcesMode.Sources - } - ).getObfuscatedCode(); + }).getObfuscatedCode(); }); it('should not pass validation', () => { diff --git a/test/functional-tests/storages/string-array-transformers/string-array-storage/StringArrayStorage.spec.ts b/test/functional-tests/storages/string-array-transformers/string-array-storage/StringArrayStorage.spec.ts index 4ac2960a..507fb1c4 100644 --- a/test/functional-tests/storages/string-array-transformers/string-array-storage/StringArrayStorage.spec.ts +++ b/test/functional-tests/storages/string-array-transformers/string-array-storage/StringArrayStorage.spec.ts @@ -19,8 +19,7 @@ describe('StringArrayStorage', () => { const stringArrayVariantRegExp: RegExp = /var.*= *\[(?:'.*?', *)?'test'(?:, *'.*?')?];.*/; const literalNodeVariantRegExp: RegExp = /var test *= *_0x([a-f0-9]){4}\(0x.\);/g; - let stringArrayVariantProbability: number, - literalNodeVariantProbability: number; + let stringArrayVariantProbability: number, literalNodeVariantProbability: number; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/one-string.js'); @@ -28,25 +27,22 @@ describe('StringArrayStorage', () => { let stringArrayVariantMatchesLength: number = 0; let literalNodeVariantMatchesLength: number = 0; - for (let i = 0; i < samples; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + for (let i = 0; i < samples; i++) { + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); - if (obfuscatedCode.match(stringArrayVariantRegExp)) { - stringArrayVariantMatchesLength++; - } + if (obfuscatedCode.match(stringArrayVariantRegExp)) { + stringArrayVariantMatchesLength++; + } - if (obfuscatedCode.match(literalNodeVariantRegExp)) { - literalNodeVariantMatchesLength++; - } - } + if (obfuscatedCode.match(literalNodeVariantRegExp)) { + literalNodeVariantMatchesLength++; + } + } stringArrayVariantProbability = stringArrayVariantMatchesLength / samples; literalNodeVariantProbability = literalNodeVariantMatchesLength / samples; @@ -76,13 +72,13 @@ describe('StringArrayStorage', () => { const stringArrayVariantRegExps: RegExp[] = [ /var.*= *\['foo', *'bar', *'baz'(?:, *'.*?')+];.*/, - /var.*= *\[(?:'.*?', *)+'foo', *'bar', *'baz'];.*/, + /var.*= *\[(?:'.*?', *)+'foo', *'bar', *'baz'];.*/ ]; const literalNodeVariantRegExps: RegExp[] = [ new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x.\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x.\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x.\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x.\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x.\\);` ) ]; @@ -96,15 +92,12 @@ describe('StringArrayStorage', () => { const code: string = readFileAsString(__dirname + '/fixtures/three-strings.js'); for (let i = 0; i < samples; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayRotate: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayRotate: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); for (let variantIndex = 0; variantIndex < stringArrayVariantsCount; variantIndex++) { if (obfuscatedCode.match(stringArrayVariantRegExps[variantIndex])) { @@ -118,11 +111,13 @@ describe('StringArrayStorage', () => { } for (let variantIndex = 0; variantIndex < stringArrayVariantsCount; variantIndex++) { - stringArrayVariantProbabilities[variantIndex] = stringArrayVariantMatchesLength[variantIndex] / samples; + stringArrayVariantProbabilities[variantIndex] = + stringArrayVariantMatchesLength[variantIndex] / samples; } for (let variantIndex = 0; variantIndex < literalNodeVariantsCount; variantIndex++) { - literalNodeVariantProbabilities[variantIndex] = literalNodeVariantMatchesLength[variantIndex] / samples; + literalNodeVariantProbabilities[variantIndex] = + literalNodeVariantMatchesLength[variantIndex] / samples; } }); @@ -131,7 +126,11 @@ describe('StringArrayStorage', () => { const variantNumber: number = variantIndex + 1; it(`Variant #${variantNumber}: should create string array variant`, () => { - assert.closeTo(stringArrayVariantProbabilities[variantIndex], expectedStringArrayVariantProbability, delta); + assert.closeTo( + stringArrayVariantProbabilities[variantIndex], + expectedStringArrayVariantProbability, + delta + ); }); } }); @@ -141,7 +140,11 @@ describe('StringArrayStorage', () => { const variantNumber: number = variantIndex + 1; it(`Variant #${variantNumber}: should replace literal node with call to string array variant`, () => { - assert.closeTo(literalNodeVariantProbabilities[variantIndex], expectedLiteralNodeVariantProbability, delta); + assert.closeTo( + literalNodeVariantProbabilities[variantIndex], + expectedLiteralNodeVariantProbability, + delta + ); }); } }); @@ -159,8 +162,7 @@ describe('StringArrayStorage', () => { const stringArrayVariantRegExp1: RegExp = getStringArrayRegExp(['test']); const literalNodeVariant1RegExp: RegExp = /var test *= *_0x([a-f0-9]){4}\(0x0\);/g; - let stringArrayVariant1Probability: number, - literalNodeVariant1Probability: number; + let stringArrayVariant1Probability: number, literalNodeVariant1Probability: number; before(() => { const code: string = readFileAsString(__dirname + '/fixtures/one-string.js'); @@ -169,15 +171,12 @@ describe('StringArrayStorage', () => { let literalNodeVariant1MatchesLength: number = 0; for (let i = 0; i < samples; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayShuffle: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayShuffle: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); if (obfuscatedCode.match(stringArrayVariantRegExp1)) { stringArrayVariant1MatchesLength++; @@ -224,33 +223,33 @@ describe('StringArrayStorage', () => { const literalNodeVariantRegExps: RegExp[] = [ new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x0\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x1\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x2\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x1\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x2\\);` ), new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x0\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x2\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x1\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x2\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x1\\);` ), new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x1\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x0\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x2\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x0\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x2\\);` ), new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x1\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x2\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x0\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x2\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x0\\);` ), new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x2\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x0\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x1\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x0\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x1\\);` ), new RegExp( `var foo *= *_0x([a-f0-9]){4}\\(0x2\\);.*` + - `var bar *= *_0x([a-f0-9]){4}\\(0x1\\);.*` + - `var baz *= *_0x([a-f0-9]){4}\\(0x0\\);` + `var bar *= *_0x([a-f0-9]){4}\\(0x1\\);.*` + + `var baz *= *_0x([a-f0-9]){4}\\(0x0\\);` ) ]; @@ -264,15 +263,12 @@ describe('StringArrayStorage', () => { const code: string = readFileAsString(__dirname + '/fixtures/three-strings.js'); for (let i = 0; i < samples; i++) { - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...NO_ADDITIONAL_NODES_PRESET, - stringArrayShuffle: true, - stringArray: true, - stringArrayThreshold: 1 - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...NO_ADDITIONAL_NODES_PRESET, + stringArrayShuffle: true, + stringArray: true, + stringArrayThreshold: 1 + }).getObfuscatedCode(); for (let variantIndex = 0; variantIndex < variantsCount; variantIndex++) { if (obfuscatedCode.match(stringArrayVariantRegExps[variantIndex])) { @@ -286,10 +282,11 @@ describe('StringArrayStorage', () => { } for (let variantIndex = 0; variantIndex < variantsCount; variantIndex++) { - stringArrayVariantProbabilities[variantIndex] = stringArrayVariantMatchesLength[variantIndex] / samples; - literalNodeVariantProbabilities[variantIndex] = literalNodeVariantMatchesLength[variantIndex] / samples; + stringArrayVariantProbabilities[variantIndex] = + stringArrayVariantMatchesLength[variantIndex] / samples; + literalNodeVariantProbabilities[variantIndex] = + literalNodeVariantMatchesLength[variantIndex] / samples; } - }); for (let variantIndex = 0; variantIndex < variantsCount; variantIndex++) { diff --git a/test/helpers/atob.ts b/test/helpers/atob.ts index b98c72a3..eaf98905 100644 --- a/test/helpers/atob.ts +++ b/test/helpers/atob.ts @@ -2,6 +2,6 @@ * @param {string} encodedString * @returns {string} */ -export function atob (encodedString: string): string { +export function atob(encodedString: string): string { return Buffer.from(encodedString, 'base64').toString(); } diff --git a/test/helpers/beautifyCode.ts b/test/helpers/beautifyCode.ts index 48422086..f116dd3e 100644 --- a/test/helpers/beautifyCode.ts +++ b/test/helpers/beautifyCode.ts @@ -7,10 +7,10 @@ const beautify = require('js-beautify').js; * @param {" " | " "} character * @returns {string} */ -export function beautifyCode (code: string, character: 'space' | 'tab'): string { +export function beautifyCode(code: string, character: 'space' | 'tab'): string { const indentCharacter: string = character === 'space' ? '\x20' : '\x09'; return beautify(code, { indent_char: indentCharacter }); -} \ No newline at end of file +} diff --git a/test/helpers/buildLargeCode.ts b/test/helpers/buildLargeCode.ts index a7fc67f5..42adac7d 100644 --- a/test/helpers/buildLargeCode.ts +++ b/test/helpers/buildLargeCode.ts @@ -1,4 +1,4 @@ -export function buildLargeCode (linesOfCode: number): string { +export function buildLargeCode(linesOfCode: number): string { return new LargeCodeBuilder(linesOfCode).build(); } @@ -16,11 +16,11 @@ class LargeCodeBuilder { /** * @param {number} linesOfCode */ - constructor (linesOfCode: number) { + constructor(linesOfCode: number) { this.linesOfCode = linesOfCode; } - public build (): string { + public build(): string { const lastLineIndex: number = this.linesOfCode - 1; let funcIndex: number = 0, @@ -77,7 +77,7 @@ class LargeCodeBuilder { * @param {string} line * @returns {string} */ - private addLine (line: string): void { + private addLine(line: string): void { this.code += `\n${line}`; } } diff --git a/test/helpers/checkCodeEvaluation.ts b/test/helpers/checkCodeEvaluation.ts index edda4f5c..bf78b9d0 100644 --- a/test/helpers/checkCodeEvaluation.ts +++ b/test/helpers/checkCodeEvaluation.ts @@ -6,7 +6,7 @@ * @param expectedResult * @returns {{areSuccessEvaluations: boolean, errorMessage?: string}} */ -export function checkCodeEvaluation ( +export function checkCodeEvaluation( codeGetterFunction: () => string, runsAmount: number, expectedResult?: any @@ -35,4 +35,4 @@ export function checkCodeEvaluation ( return { areSuccessEvaluations: true }; -} \ No newline at end of file +} diff --git a/test/helpers/evaluateInWorker.ts b/test/helpers/evaluateInWorker.ts index 12d73932..b2627e5d 100644 --- a/test/helpers/evaluateInWorker.ts +++ b/test/helpers/evaluateInWorker.ts @@ -4,10 +4,7 @@ import { spawn, Thread, Worker } from 'threads'; * @param {string} code * @returns {Promise} */ -export function evaluateInWorker( - code: string, - waitTimeout: number -): Promise { +export function evaluateInWorker(code: string, waitTimeout: number): Promise { return new Promise(async (resolve, reject) => { const evaluationWorker = await spawn(new Worker('./workers/evaluation-worker')); @@ -30,4 +27,4 @@ export function evaluateInWorker( reject(error); } }); -} \ No newline at end of file +} diff --git a/test/helpers/get-string-array-regexp.ts b/test/helpers/get-string-array-regexp.ts index 94f4997c..46f2b691 100644 --- a/test/helpers/get-string-array-regexp.ts +++ b/test/helpers/get-string-array-regexp.ts @@ -1,28 +1,25 @@ const defaultOptions = { name: '_0x([a-f0-9]){4}', kind: 'var' -} +}; /** * Returns string array RegExp * * @returns {RegExp} */ -export function getStringArrayRegExp( - stringArrayItems: string[], - options: Partial = {} -): RegExp { +export function getStringArrayRegExp(stringArrayItems: string[], options: Partial = {}): RegExp { const mergedOptions = { ...defaultOptions, ...options }; - const {name, kind} = mergedOptions; + const { name, kind } = mergedOptions; return new RegExp( `function (${name}) *\\(\\) *{` + `${kind}.*= *\\[${stringArrayItems.map((item: string) => `\'${item}\'`).join(',')}];.*` + `return ${name}\\(\\); *` + - '}' + '}' ); -} \ No newline at end of file +} diff --git a/test/helpers/getRegExpMatch.ts b/test/helpers/getRegExpMatch.ts index f03fd973..fcf21463 100644 --- a/test/helpers/getRegExpMatch.ts +++ b/test/helpers/getRegExpMatch.ts @@ -4,7 +4,7 @@ * @param matchIndex * @return {string} */ -export function getRegExpMatch (str: string, regExp: RegExp, matchIndex: number = 0): string { +export function getRegExpMatch(str: string, regExp: RegExp, matchIndex: number = 0): string { const match: RegExpMatchArray | null = str.match(regExp); if (!match) { diff --git a/test/helpers/minimizeCode.ts b/test/helpers/minimizeCode.ts index 622b8292..b0827fd2 100644 --- a/test/helpers/minimizeCode.ts +++ b/test/helpers/minimizeCode.ts @@ -1,4 +1,4 @@ -import {minify} from 'terser'; +import { minify } from 'terser'; /** * Minimizes code @@ -6,8 +6,8 @@ import {minify} from 'terser'; * @param {string} code * @returns {string} */ -export async function minimizeCode (code: string): Promise { +export async function minimizeCode(code: string): Promise { const result = await minify(code); return result.code ?? ''; -} \ No newline at end of file +} diff --git a/test/helpers/parseSourceMapFromObfuscatedCode.ts b/test/helpers/parseSourceMapFromObfuscatedCode.ts index 75e04462..eeb62631 100644 --- a/test/helpers/parseSourceMapFromObfuscatedCode.ts +++ b/test/helpers/parseSourceMapFromObfuscatedCode.ts @@ -6,6 +6,6 @@ import { atob } from './atob'; * @param {string} obfuscatedCodeWithInlineSourceMap * @returns {ISourceMap} */ -export function parseSourceMapFromObfuscatedCode (obfuscatedCodeWithInlineSourceMap: string): ISourceMap { +export function parseSourceMapFromObfuscatedCode(obfuscatedCodeWithInlineSourceMap: string): ISourceMap { return JSON.parse(atob(obfuscatedCodeWithInlineSourceMap.split('base64,')[1])); } diff --git a/test/helpers/readFileAsString.ts b/test/helpers/readFileAsString.ts index 1d5dde0d..3e39b71f 100644 --- a/test/helpers/readFileAsString.ts +++ b/test/helpers/readFileAsString.ts @@ -4,6 +4,6 @@ import * as fs from 'fs'; * @param path * @returns {string} */ -export function readFileAsString (path: string): string { +export function readFileAsString(path: string): string { return fs.readFileSync(path, 'utf8'); -} \ No newline at end of file +} diff --git a/test/helpers/removeRangesFromStructure.ts b/test/helpers/removeRangesFromStructure.ts index db26a3a4..38fa3ec1 100644 --- a/test/helpers/removeRangesFromStructure.ts +++ b/test/helpers/removeRangesFromStructure.ts @@ -7,7 +7,7 @@ import { TStatement } from '../../src/types/node/TStatement'; * @param {TStatement[]} structure * @returns {TStatement[]} */ -export function removeRangesFromStructure (structure: TStatement[]): TStatement[] { +export function removeRangesFromStructure(structure: TStatement[]): TStatement[] { for (const statement of structure) { estraverse.replace(statement, { enter: (node: ESTree.Node): ESTree.Node => { @@ -25,4 +25,4 @@ export function removeRangesFromStructure (structure: TStatement[]): TStatement[ } return structure; -} \ No newline at end of file +} diff --git a/test/helpers/stubNodeTransformers.ts b/test/helpers/stubNodeTransformers.ts index 4e5125f0..ade2c8a6 100644 --- a/test/helpers/stubNodeTransformers.ts +++ b/test/helpers/stubNodeTransformers.ts @@ -3,14 +3,12 @@ import * as sinon from 'sinon'; import { INodeTransformer } from '../../src/interfaces/node-transformers/INodeTransformer'; -export function stubNodeTransformers (nodeTransformers: (new (...args: any[]) => INodeTransformer)[]): void { +export function stubNodeTransformers(nodeTransformers: (new (...args: any[]) => INodeTransformer)[]): void { const transformerStubs: sinon.SinonStub[] = []; mocha.before(() => { for (const nodeTransformer of nodeTransformers) { - const stub: sinon.SinonStub = sinon - .stub(nodeTransformer.prototype, 'getVisitor') - .callsFake(() => null); + const stub: sinon.SinonStub = sinon.stub(nodeTransformer.prototype, 'getVisitor').callsFake(() => null); transformerStubs.push(stub); } diff --git a/test/helpers/swapLettersCase.ts b/test/helpers/swapLettersCase.ts index aa18ffdb..a5a664ba 100644 --- a/test/helpers/swapLettersCase.ts +++ b/test/helpers/swapLettersCase.ts @@ -2,13 +2,9 @@ * @param {string} value * @returns {string} */ -export function swapLettersCase (value: string): string { +export function swapLettersCase(value: string): string { return value .split('') - .map((letter: string) => - letter === letter.toUpperCase() - ? letter.toLowerCase() - : letter.toUpperCase() - ) + .map((letter: string) => (letter === letter.toUpperCase() ? letter.toLowerCase() : letter.toUpperCase())) .join(''); } diff --git a/test/index.spec.ts b/test/index.spec.ts index d8ed26eb..4c585766 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -48,7 +48,7 @@ import './unit-tests/utils/CryptUtilsStringArray.spec'; import './unit-tests/utils/EscapeSequenceEncoder.spec'; import './unit-tests/utils/LevelledTopologicalSorter.spec'; import './unit-tests/utils/NumberUtils.spec'; -import './unit-tests/utils/ObfuscatedCodeFileUtils.spec' +import './unit-tests/utils/ObfuscatedCodeFileUtils.spec'; import './unit-tests/utils/RandomGenerator.spec'; import './unit-tests/utils/SetUtils.spec'; import './unit-tests/utils/StringUtils.spec'; diff --git a/test/mocks/StdoutWriteMock.ts b/test/mocks/StdoutWriteMock.ts index c7881795..97b86c8b 100644 --- a/test/mocks/StdoutWriteMock.ts +++ b/test/mocks/StdoutWriteMock.ts @@ -7,20 +7,20 @@ export class StdoutWriteMock { /** * @type any */ - private stdoutWriteMock: any = (() => {}); + private stdoutWriteMock: any = () => {}; /** * @param stdoutWrite */ - constructor (stdoutWrite: any) { + constructor(stdoutWrite: any) { this.stdoutWrite = stdoutWrite; } - public mute (): void { + public mute(): void { process.stdout.write = this.stdoutWriteMock; } - public restore (): void { + public restore(): void { process.stdout.write = this.stdoutWrite; } } diff --git a/test/performance-tests/JavaScriptObfuscatorMemory.spec.ts b/test/performance-tests/JavaScriptObfuscatorMemory.spec.ts index 2f58cecb..e8b78da3 100644 --- a/test/performance-tests/JavaScriptObfuscatorMemory.spec.ts +++ b/test/performance-tests/JavaScriptObfuscatorMemory.spec.ts @@ -6,7 +6,7 @@ import { StringArrayEncoding } from '../../src/enums/node-transformers/string-ar import { JavaScriptObfuscator } from '../../src/JavaScriptObfuscatorFacade'; -const heapValueToMB = (value: number) => Math.round(value / 1024 / 1024 * 100) / 100; +const heapValueToMB = (value: number) => Math.round((value / 1024 / 1024) * 100) / 100; describe('JavaScriptObfuscator memory', function () { const iterationsCount: number = 500; @@ -23,32 +23,29 @@ describe('JavaScriptObfuscator memory', function () { let prevHeapUsed: number | null = null; for (let i: number = 0; i < iterationsCount; i++) { - JavaScriptObfuscator.obfuscate( - sourceCode, - { - compact: true, - controlFlowFlattening: true, - controlFlowFlatteningThreshold: 0.75, - deadCodeInjection: true, - deadCodeInjectionThreshold: 0.4, - debugProtection: false, - debugProtectionInterval: 0, - disableConsoleOutput: true, - identifierNamesGenerator: 'mangled', - log: false, - renameGlobals: false, - stringArrayRotate: true, - selfDefending: true, - stringArrayShuffle: true, - splitStrings: true, - splitStringsChunkLength: 2, - stringArray: true, - stringArrayEncoding: [StringArrayEncoding.Base64], - stringArrayThreshold: 0.75, - transformObjectKeys: true, - unicodeEscapeSequence: false - } - ); + JavaScriptObfuscator.obfuscate(sourceCode, { + compact: true, + controlFlowFlattening: true, + controlFlowFlatteningThreshold: 0.75, + deadCodeInjection: true, + deadCodeInjectionThreshold: 0.4, + debugProtection: false, + debugProtectionInterval: 0, + disableConsoleOutput: true, + identifierNamesGenerator: 'mangled', + log: false, + renameGlobals: false, + stringArrayRotate: true, + selfDefending: true, + stringArrayShuffle: true, + splitStrings: true, + splitStringsChunkLength: 2, + stringArray: true, + stringArrayEncoding: [StringArrayEncoding.Base64], + stringArrayThreshold: 0.75, + transformObjectKeys: true, + unicodeEscapeSequence: false + }); const heap = process.memoryUsage(); const heapUsed: number = heapValueToMB(heap.heapUsed); diff --git a/test/runtime-tests/JavaScriptObfuscatorRuntime.spec.ts b/test/runtime-tests/JavaScriptObfuscatorRuntime.spec.ts index 1078400a..79537378 100644 --- a/test/runtime-tests/JavaScriptObfuscatorRuntime.spec.ts +++ b/test/runtime-tests/JavaScriptObfuscatorRuntime.spec.ts @@ -40,11 +40,7 @@ describe('JavaScriptObfuscator runtime eval', function () { stringArray: true, stringArrayCallsTransform: true, stringArrayCallsTransformThreshold: 1, - stringArrayEncoding: [ - StringArrayEncoding.None, - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ], + stringArrayEncoding: [StringArrayEncoding.None, StringArrayEncoding.Base64, StringArrayEncoding.Rc4], stringArrayIndexesType: [ StringArrayIndexesType.HexadecimalNumber, StringArrayIndexesType.HexadecimalNumericString @@ -168,7 +164,7 @@ describe('JavaScriptObfuscator runtime eval', function () { let evaluationResult: string; try { - evaluationResult = eval(obfuscatedCode) + evaluationResult = eval(obfuscatedCode); } catch (e) { throw new Error(`Evaluation error: ${e.message}. Code: ${obfuscatedCode}`); } @@ -194,10 +190,7 @@ describe('JavaScriptObfuscator runtime eval', function () { } ).getObfuscatedCode(); - assert.equal( - eval(obfuscatedCode), - '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08' - ); + assert.equal(eval(obfuscatedCode), '9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'); }); }); @@ -209,14 +202,11 @@ describe('JavaScriptObfuscator runtime eval', function () { beforeEach(() => { const code: string = readFileAsString(process.cwd() + '/dist/index.js'); - const obfuscationResult = JavaScriptObfuscator.obfuscate( - code, - { - ...baseOptions, - ...options, - renameProperties: false - } - ); + const obfuscationResult = JavaScriptObfuscator.obfuscate(code, { + ...baseOptions, + ...options, + renameProperties: false + }); const obfuscatorOptions = obfuscationResult.getOptions(); const obfuscatedCode: string = obfuscationResult.getObfuscatedCode(); @@ -241,10 +231,7 @@ describe('JavaScriptObfuscator runtime eval', function () { }); it('should obfuscate code without any runtime errors after obfuscation: Variant #3 obfuscator', () => { - assert.equal( - evaluationResult, - 'var foo=0x1;' - ); + assert.equal(evaluationResult, 'var foo=0x1;'); }); }); @@ -281,15 +268,12 @@ describe('JavaScriptObfuscator runtime eval', function () { beforeEach(() => { const code: string = readFileAsString(__dirname + '/fixtures/webpack-bootstrap.js'); - const obfuscatedCode: string = JavaScriptObfuscator.obfuscate( - code, - { - ...baseOptions, - ...options, - ...webpackBootstrapOptions, - reservedNames: ['^foo$'] - } - ).getObfuscatedCode(); + const obfuscatedCode: string = JavaScriptObfuscator.obfuscate(code, { + ...baseOptions, + ...options, + ...webpackBootstrapOptions, + reservedNames: ['^foo$'] + }).getObfuscatedCode(); try { evaluationResult = eval(` diff --git a/test/unit-tests/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.spec.ts b/test/unit-tests/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.spec.ts index dc203fd9..4bf41553 100644 --- a/test/unit-tests/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.spec.ts +++ b/test/unit-tests/analyzers/number-numerical-expression-analyzer/NumberNumericalExpressionAnalyzer.spec.ts @@ -18,11 +18,11 @@ import { NumberNumericalExpressionAnalyzer } from '../../../../src/analyzers/num */ const numberNumericalExpressionDataToString = (data: TNumberNumericalExpressionData) => data - .map((part: number | number[]) => Array.isArray(part) ? part.join('*') : part) + .map((part: number | number[]) => (Array.isArray(part) ? part.join('*') : part)) .join('+') .replace(/\+-/g, '-'); -describe('NumberNumericalExpressionAnalyzer', function() { +describe('NumberNumericalExpressionAnalyzer', function () { let numberNumericalExpressionAnalyzer: INumberNumericalExpressionAnalyzer; this.timeout(10000); @@ -31,8 +31,9 @@ describe('NumberNumericalExpressionAnalyzer', function() { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - numberNumericalExpressionAnalyzer = inversifyContainerFacade - .get(ServiceIdentifiers.INumberNumericalExpressionAnalyzer); + numberNumericalExpressionAnalyzer = inversifyContainerFacade.get( + ServiceIdentifiers.INumberNumericalExpressionAnalyzer + ); }); describe('analyze', () => { @@ -192,10 +193,11 @@ describe('NumberNumericalExpressionAnalyzer', function() { let testFunc: () => void; before(() => { - testFunc = () => numberNumericalExpressionAnalyzer.analyze( - number, - NumberNumericalExpressionAnalyzer.defaultAdditionalPartsCount - ); + testFunc = () => + numberNumericalExpressionAnalyzer.analyze( + number, + NumberNumericalExpressionAnalyzer.defaultAdditionalPartsCount + ); }); it('should throw error', () => { diff --git a/test/unit-tests/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.spec.ts b/test/unit-tests/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.spec.ts index 92174018..e50d254b 100644 --- a/test/unit-tests/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.spec.ts +++ b/test/unit-tests/analyzers/prevailing-kind-of-variables-analyzer/PrevailingKindOfVariablesAnalyzer.spec.ts @@ -18,8 +18,9 @@ describe('PrevailingKindOfVariablesAnalyzer', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - prevailingKindOfVariablesAnalyzer = inversifyContainerFacade - .get(ServiceIdentifiers.IPrevailingKindOfVariablesAnalyzer); + prevailingKindOfVariablesAnalyzer = inversifyContainerFacade.get( + ServiceIdentifiers.IPrevailingKindOfVariablesAnalyzer + ); }); describe('analyze', () => { @@ -31,30 +32,15 @@ describe('PrevailingKindOfVariablesAnalyzer', () => { before(() => { const astTree: ESTree.Program = NodeFactory.programNode([ NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('foo'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('foo'), null)], 'var' ), NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('bar'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('bar'), null)], 'const' ), NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('baz'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('baz'), null)], 'var' ) ]); @@ -74,30 +60,15 @@ describe('PrevailingKindOfVariablesAnalyzer', () => { before(() => { const astTree: ESTree.Program = NodeFactory.programNode([ NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('foo'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('foo'), null)], 'let' ), NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('bar'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('bar'), null)], 'var' ), NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('baz'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('baz'), null)], 'let' ) ]); @@ -117,30 +88,15 @@ describe('PrevailingKindOfVariablesAnalyzer', () => { before(() => { const astTree: ESTree.Program = NodeFactory.programNode([ NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('foo'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('foo'), null)], 'let' ), NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('bar'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('bar'), null)], 'const' ), NodeFactory.variableDeclarationNode( - [ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('baz'), - null - ) - ], + [NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('baz'), null)], 'const' ) ]); diff --git a/test/unit-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts b/test/unit-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts index 979655a3..8c74a373 100644 --- a/test/unit-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts +++ b/test/unit-tests/analyzers/scope-analyzer/ScopeAnalyzer.spec.ts @@ -19,8 +19,7 @@ describe('ScopeAnalyzer', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - scopeAnalyzer = inversifyContainerFacade - .get(ServiceIdentifiers.IScopeAnalyzer); + scopeAnalyzer = inversifyContainerFacade.get(ServiceIdentifiers.IScopeAnalyzer); }); describe('analyze', () => { @@ -65,10 +64,7 @@ describe('ScopeAnalyzer', () => { beforeEach(() => { const variableDeclarationNode: ESTree.VariableDeclaration = NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('foo'), - NodeFactory.literalNode(1) - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('foo'), NodeFactory.literalNode(1)) ]); const programNode: ESTree.Program = NodeFactory.programNode([variableDeclarationNode]); @@ -112,10 +108,7 @@ describe('ScopeAnalyzer', () => { beforeEach(() => { const variableDeclarationNode: ESTree.VariableDeclaration = NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('foo'), - NodeFactory.literalNode(1) - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('foo'), NodeFactory.literalNode(1)) ]); const programNode: ESTree.Program = NodeFactory.programNode([variableDeclarationNode]); @@ -137,28 +130,17 @@ describe('ScopeAnalyzer', () => { beforeEach(() => { const variableDeclarationNode: ESTree.VariableDeclaration = NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('foo'), - NodeFactory.literalNode(1) - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('foo'), NodeFactory.literalNode(1)) ]); const programNode: ESTree.Program = NodeFactory.programNode([ NodeFactory.ifStatementNode( - NodeFactory.binaryExpressionNode( - '+', - NodeFactory.literalNode(1), - NodeFactory.literalNode(2) - ), - NodeFactory.blockStatementNode([ - variableDeclarationNode - ]), + NodeFactory.binaryExpressionNode('+', NodeFactory.literalNode(1), NodeFactory.literalNode(2)), + NodeFactory.blockStatementNode([variableDeclarationNode]), NodeFactory.blockStatementNode([ NodeFactory.functionDeclarationNode( 'bar', [], - NodeFactory.blockStatementNode([ - variableDeclarationNode - ]) + NodeFactory.blockStatementNode([variableDeclarationNode]) ) ]) ) diff --git a/test/unit-tests/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.spec.ts b/test/unit-tests/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.spec.ts index 4196b4bb..72e19f7b 100644 --- a/test/unit-tests/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.spec.ts +++ b/test/unit-tests/analyzers/string-array-storage-analyzer/StringArrayStorageAnalyzer.spec.ts @@ -194,10 +194,7 @@ describe('StringArrayStorageAnalyzer', () => { NodeFactory.variableDeclaratorNode( NodeFactory.identifierNode('bar'), NodeFactory.objectExpressionNode([ - NodeFactory.propertyNode( - literalNode2, - NodeFactory.literalNode(1) - ) + NodeFactory.propertyNode(literalNode2, NodeFactory.literalNode(1)) ]) ) ]) @@ -220,7 +217,7 @@ describe('StringArrayStorageAnalyzer', () => { describe('Analyzes of the AST tree with ignored string literal nodes', () => { const literalNode1: ESTree.Literal = NodeFactory.literalNode('foo'); const literalNode2: ESTree.Literal = NodeFactory.literalNode('bar'); - NodeMetadata.set(literalNode2, {ignoredNode: true}); + NodeMetadata.set(literalNode2, { ignoredNode: true }); const expectedStringArrayStorageItemData1: IStringArrayStorageItemData = { encodedValue: 'foo', @@ -263,7 +260,7 @@ describe('StringArrayStorageAnalyzer', () => { describe('Variant #1: Force obfuscate string when threshold is `0`', () => { const literalNode1: ESTree.Literal = NodeFactory.literalNode('foo'); const literalNode2: ESTree.Literal = NodeFactory.literalNode('bar'); - NodeMetadata.set(literalNode2, {forceTransformNode: true}); + NodeMetadata.set(literalNode2, { forceTransformNode: true }); const expectedStringArrayStorageItemData1: undefined = undefined; const expectedStringArrayStorageItemData2: IStringArrayStorageItemData = { @@ -305,7 +302,7 @@ describe('StringArrayStorageAnalyzer', () => { describe('Variant #2: Force obfuscate string when string value shorter than allowed length', () => { const literalNode1: ESTree.Literal = NodeFactory.literalNode('a'); const literalNode2: ESTree.Literal = NodeFactory.literalNode('b'); - NodeMetadata.set(literalNode2, {forceTransformNode: true}); + NodeMetadata.set(literalNode2, { forceTransformNode: true }); const expectedStringArrayStorageItemData1: undefined = undefined; const expectedStringArrayStorageItemData2: IStringArrayStorageItemData = { @@ -416,7 +413,8 @@ describe('StringArrayStorageAnalyzer', () => { const stringArrayStorageItemData2: IStringArrayStorageItemData | undefined = stringArrayStorageAnalyzer.getItemDataForLiteralNode(literalNode2); - isStringArrayStorageItemDataEmpty = !stringArrayStorageItemData1 && !stringArrayStorageItemData2; + isStringArrayStorageItemDataEmpty = + !stringArrayStorageItemData1 && !stringArrayStorageItemData2; if (!isStringArrayStorageItemDataEmpty) { break; diff --git a/test/unit-tests/cli/sanitizers/BooleanSanitizer.spec.ts b/test/unit-tests/cli/sanitizers/BooleanSanitizer.spec.ts index 90b8141c..c81559a3 100644 --- a/test/unit-tests/cli/sanitizers/BooleanSanitizer.spec.ts +++ b/test/unit-tests/cli/sanitizers/BooleanSanitizer.spec.ts @@ -2,7 +2,6 @@ import { assert } from 'chai'; import { BooleanSanitizer } from '../../../../src/cli/sanitizers/BooleanSanitizer'; - describe('BooleanSanitizer', () => { describe('Variant #1: input value `true`', () => { const inputValue: string = 'true'; diff --git a/test/unit-tests/cli/utils/IdentifierNamesCacheFileUtils.spec.ts b/test/unit-tests/cli/utils/IdentifierNamesCacheFileUtils.spec.ts index b0ff913f..6e2b47c0 100644 --- a/test/unit-tests/cli/utils/IdentifierNamesCacheFileUtils.spec.ts +++ b/test/unit-tests/cli/utils/IdentifierNamesCacheFileUtils.spec.ts @@ -19,7 +19,7 @@ describe('IdentifierNamesCacheFileUtils', () => { propertyIdentifiers: { bar: '_0x654321' } - } + }; const fileContent: string = JSON.stringify(expectedIdentifierNamesCache); const tmpDirectoryPath: string = path.join('test', 'tmp'); diff --git a/test/unit-tests/cli/utils/ObfuscatedCodeFileUtils.spec.ts b/test/unit-tests/cli/utils/ObfuscatedCodeFileUtils.spec.ts index 4556b5d6..ce87401e 100644 --- a/test/unit-tests/cli/utils/ObfuscatedCodeFileUtils.spec.ts +++ b/test/unit-tests/cli/utils/ObfuscatedCodeFileUtils.spec.ts @@ -11,11 +11,8 @@ describe('obfuscatedCodeFileUtils', () => { describe('getOutputCodePath', () => { before(() => { - mkdirp.sync(path.join(tmpDirectoryPath, 'input', 'nested',)); - fs.writeFileSync( - path.join(tmpDirectoryPath, 'input', 'nested', 'test-input.js'), - 'var foo = 1;' - ); + mkdirp.sync(path.join(tmpDirectoryPath, 'input', 'nested')); + fs.writeFileSync(path.join(tmpDirectoryPath, 'input', 'nested', 'test-input.js'), 'var foo = 1;'); }); describe('Variant #1: raw input path is a file path, raw output path is a file path', () => { @@ -27,12 +24,9 @@ describe('obfuscatedCodeFileUtils', () => { let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -50,12 +44,9 @@ describe('obfuscatedCodeFileUtils', () => { let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -72,12 +63,9 @@ describe('obfuscatedCodeFileUtils', () => { let testFunc: () => string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); testFunc = () => obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -91,21 +79,14 @@ describe('obfuscatedCodeFileUtils', () => { const inputPath: string = path.join(tmpDirectoryPath, 'input', 'test-input.js'); const rawInputPath: string = path.join(tmpDirectoryPath, 'input'); const rawOutputPath: string = path.join(tmpDirectoryPath, 'output'); - const expectedOutputCodePath: string = path.join( - tmpDirectoryPath, - 'output', - 'test-input.js' - ); + const expectedOutputCodePath: string = path.join(tmpDirectoryPath, 'output', 'test-input.js'); let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -118,21 +99,14 @@ describe('obfuscatedCodeFileUtils', () => { const inputPath: string = path.join(tmpDirectoryPath, 'input', 'test-input.js'); const rawInputPath: string = path.join(tmpDirectoryPath, 'input'); const rawOutputPath: string = path.join('.', tmpDirectoryPath, 'output'); - const expectedOutputCodePath: string = path.join( - tmpDirectoryPath, - 'output', - 'test-input.js' - ); + const expectedOutputCodePath: string = path.join(tmpDirectoryPath, 'output', 'test-input.js'); let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -145,22 +119,14 @@ describe('obfuscatedCodeFileUtils', () => { const inputPath: string = path.join(tmpDirectoryPath, 'input', 'nested', 'test-input.js'); const rawInputPath: string = path.join(tmpDirectoryPath, 'input'); const rawOutputPath: string = path.join(tmpDirectoryPath, 'output'); - const expectedOutputCodePath: string = path.join( - tmpDirectoryPath, - 'output', - 'nested', - 'test-input.js' - ); + const expectedOutputCodePath: string = path.join(tmpDirectoryPath, 'output', 'nested', 'test-input.js'); let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -184,12 +150,9 @@ describe('obfuscatedCodeFileUtils', () => { let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -202,21 +165,14 @@ describe('obfuscatedCodeFileUtils', () => { const inputPath: string = path.join('test-input.js'); const rawInputPath: string = path.join('.'); const rawOutputPath: string = path.join(tmpDirectoryPath, 'output'); - const expectedOutputCodePath: string = path.join( - tmpDirectoryPath, - 'output', - 'test-input.js' - ); + const expectedOutputCodePath: string = path.join(tmpDirectoryPath, 'output', 'test-input.js'); let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -229,21 +185,14 @@ describe('obfuscatedCodeFileUtils', () => { const inputPath: string = path.join('test-input.js'); const rawInputPath: string = path.join('./'); const rawOutputPath: string = path.join(tmpDirectoryPath, 'output'); - const expectedOutputCodePath: string = path.join( - tmpDirectoryPath, - 'output', - 'test-input.js' - ); + const expectedOutputCodePath: string = path.join(tmpDirectoryPath, 'output', 'test-input.js'); let outputCodePath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); outputCodePath = obfuscatedCodeFileUtils.getOutputCodePath(inputPath); }); @@ -266,7 +215,13 @@ describe('obfuscatedCodeFileUtils', () => { describe('Variant #1: raw input absolute path is a directory path, raw output absolute path is a directory path', () => { describe('Variant #1: base directory name', () => { - const inputPath: string = path.join(baseDirnamePath, tmpDirectoryPath, 'input', 'nested', 'test-input.js'); + const inputPath: string = path.join( + baseDirnamePath, + tmpDirectoryPath, + 'input', + 'nested', + 'test-input.js' + ); const rawInputPath: string = path.join(baseDirnamePath, tmpDirectoryPath, 'input'); const rawOutputPath: string = path.join(baseDirnamePath, tmpDirectoryPath, 'output'); const expectedOutputCodePath: string = path.join( @@ -313,7 +268,11 @@ describe('obfuscatedCodeFileUtils', () => { const rawInputPath: string = path.join(tmpDirectoryPath, 'input', 'test-input.js'); const rawOutputPath: string = path.join(tmpDirectoryPath, 'output', 'test-output.js'); const outputCodePath: string = path.join(tmpDirectoryPath, 'output', 'test-output.js'); - const expectedOutputSourceMapPath: string = path.join(tmpDirectoryPath, 'output', 'test-output.js.map'); + const expectedOutputSourceMapPath: string = path.join( + tmpDirectoryPath, + 'output', + 'test-output.js.map' + ); let outputSourceMapPath: string; @@ -336,7 +295,11 @@ describe('obfuscatedCodeFileUtils', () => { const rawInputPath: string = path.join(tmpDirectoryPath, 'input.with.dot', 'test-input.js'); const rawOutputPath: string = path.join(tmpDirectoryPath, 'output.with.dot', 'test-output.js'); const outputCodePath: string = path.join(tmpDirectoryPath, 'output.with.dot', 'test-output.js'); - const expectedOutputSourceMapPath: string = path.join(tmpDirectoryPath, 'output.with.dot', 'test-output.js.map'); + const expectedOutputSourceMapPath: string = path.join( + tmpDirectoryPath, + 'output.with.dot', + 'test-output.js.map' + ); let outputSourceMapPath: string; @@ -373,7 +336,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -397,7 +363,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -421,7 +390,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -434,7 +406,12 @@ describe('obfuscatedCodeFileUtils', () => { const rawOutputPath: string = path.join(tmpDirectoryPath, 'output', 'test-output.js'); const outputCodePath: string = path.join(tmpDirectoryPath, 'output', 'test-output.js'); const sourceMapFileName: string = path.join('parent', 'foo.js.map'); - const expectedOutputSourceMapPath: string = path.join(tmpDirectoryPath, 'output', 'parent', 'foo.js.map'); + const expectedOutputSourceMapPath: string = path.join( + tmpDirectoryPath, + 'output', + 'parent', + 'foo.js.map' + ); let outputSourceMapPath: string; @@ -445,7 +422,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -458,7 +438,12 @@ describe('obfuscatedCodeFileUtils', () => { const rawOutputPath: string = path.join(tmpDirectoryPath, 'output.with.dot', 'test-output.js'); const outputCodePath: string = path.join(tmpDirectoryPath, 'output.with.dot', 'test-output.js'); const sourceMapFileName: string = path.join('parent', 'foo.js.map'); - const expectedOutputSourceMapPath: string = path.join(tmpDirectoryPath, 'output.with.dot', 'parent', 'foo.js.map'); + const expectedOutputSourceMapPath: string = path.join( + tmpDirectoryPath, + 'output.with.dot', + 'parent', + 'foo.js.map' + ); let outputSourceMapPath: string; @@ -469,7 +454,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -541,7 +529,12 @@ describe('obfuscatedCodeFileUtils', () => { const rawOutputPath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'test-output.js'); const outputCodePath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'test-output.js'); const sourceMapFileName: string = path.join('foo'); - const expectedOutputSourceMapPath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'foo.js.map'); + const expectedOutputSourceMapPath: string = path.join( + 'C:\\', + tmpDirectoryPath, + 'output', + 'foo.js.map' + ); let outputSourceMapPath: string; @@ -552,7 +545,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -565,7 +561,12 @@ describe('obfuscatedCodeFileUtils', () => { const rawOutputPath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'test-output.js'); const outputCodePath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'test-output.js'); const sourceMapFileName: string = path.join('foo.js.map'); - const expectedOutputSourceMapPath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'foo.js.map'); + const expectedOutputSourceMapPath: string = path.join( + 'C:\\', + tmpDirectoryPath, + 'output', + 'foo.js.map' + ); let outputSourceMapPath: string; @@ -576,7 +577,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -589,7 +593,13 @@ describe('obfuscatedCodeFileUtils', () => { const rawOutputPath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'test-output.js'); const outputCodePath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'test-output.js'); const sourceMapFileName: string = path.join('C:\\', 'parent', 'foo.js.map'); - const expectedOutputSourceMapPath: string = path.join('C:\\', tmpDirectoryPath, 'output', 'parent', 'foo.js.map'); + const expectedOutputSourceMapPath: string = path.join( + 'C:\\', + tmpDirectoryPath, + 'output', + 'parent', + 'foo.js.map' + ); let outputSourceMapPath: string; @@ -600,7 +610,10 @@ describe('obfuscatedCodeFileUtils', () => { output: rawOutputPath } ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName + ); }); it('should return output path for source map', () => { @@ -619,12 +632,9 @@ describe('obfuscatedCodeFileUtils', () => { let testFunc: () => string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); testFunc = () => obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath); }); @@ -643,13 +653,13 @@ describe('obfuscatedCodeFileUtils', () => { let outputSourceMapPath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); }); it('should return output path for source map', () => { @@ -667,13 +677,13 @@ describe('obfuscatedCodeFileUtils', () => { let outputSourceMapPath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); }); it('should return output path for source map', () => { @@ -691,13 +701,13 @@ describe('obfuscatedCodeFileUtils', () => { let outputSourceMapPath: string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); + outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath( + outputCodePath, + sourceMapFileName ); - outputSourceMapPath = obfuscatedCodeFileUtils.getOutputSourceMapPath(outputCodePath, sourceMapFileName); }); it('should return output path for source map', () => { @@ -713,12 +723,9 @@ describe('obfuscatedCodeFileUtils', () => { let testFunc: () => string; before(() => { - const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils( - rawInputPath, - { - output: rawOutputPath - } - ); + const obfuscatedCodeFileUtils: ObfuscatedCodeFileUtils = new ObfuscatedCodeFileUtils(rawInputPath, { + output: rawOutputPath + }); testFunc = () => obfuscatedCodeFileUtils.getOutputSourceMapPath('', ''); }); diff --git a/test/unit-tests/cli/utils/SourceCodeFileUtils.spec.ts b/test/unit-tests/cli/utils/SourceCodeFileUtils.spec.ts index d69ab1bb..f7dbb843 100644 --- a/test/unit-tests/cli/utils/SourceCodeFileUtils.spec.ts +++ b/test/unit-tests/cli/utils/SourceCodeFileUtils.spec.ts @@ -23,10 +23,12 @@ describe('SourceCodeFileUtils', () => { describe('Variant #1: `inputPath` is a valid path', () => { const tmpFileName: string = 'test.js'; const inputPath: string = path.join(tmpDirectoryPath, tmpFileName); - const expectedFilesData: IFileData[] = [{ - content: fileContent, - filePath: inputPath - }]; + const expectedFilesData: IFileData[] = [ + { + content: fileContent, + filePath: inputPath + } + ]; let filesData: IFileData[]; @@ -80,24 +82,23 @@ describe('SourceCodeFileUtils', () => { }); describe('Variant #4: `exclude` option', () => { - describe('Variant #1: `inputPath` isn\'t excluded path', () => { + describe("Variant #1: `inputPath` isn't excluded path", () => { const tmpFileName: string = 'test.js'; const inputPath: string = path.join(tmpDirectoryPath, tmpFileName); - const expectedFilesData: IFileData[] = [{ - content: fileContent, - filePath: inputPath - }]; + const expectedFilesData: IFileData[] = [ + { + content: fileContent, + filePath: inputPath + } + ]; let filesData: IFileData[]; before(() => { fs.writeFileSync(inputPath, fileContent); - filesData = new SourceCodeFileUtils( - inputPath, - { - exclude: [path.join('**', 'foo.js')] - } - ).readSourceCode(); + filesData = new SourceCodeFileUtils(inputPath, { + exclude: [path.join('**', 'foo.js')] + }).readSourceCode(); }); it('should return valid files data', () => { @@ -118,12 +119,10 @@ describe('SourceCodeFileUtils', () => { before(() => { fs.writeFileSync(inputPath, fileContent); - testFunc = () => new SourceCodeFileUtils( - inputPath, - { + testFunc = () => + new SourceCodeFileUtils(inputPath, { exclude: [path.join('**', tmpFileName)] - } - ).readSourceCode(); + }).readSourceCode(); }); it('should throw an error if `inputPath` is the excluded file path', () => { @@ -143,12 +142,10 @@ describe('SourceCodeFileUtils', () => { before(() => { fs.writeFileSync(inputPath, fileContent); - testFunc = () => new SourceCodeFileUtils( - inputPath, - { + testFunc = () => + new SourceCodeFileUtils(inputPath, { exclude: [tmpFileName] - } - ).readSourceCode(); + }).readSourceCode(); }); it('should throw an error if `inputPath` is the excluded file path', () => { @@ -168,12 +165,10 @@ describe('SourceCodeFileUtils', () => { before(() => { fs.writeFileSync(inputPath, fileContent); - testFunc = () => new SourceCodeFileUtils( - inputPath, - { + testFunc = () => + new SourceCodeFileUtils(inputPath, { exclude: [inputPath] - } - ).readSourceCode(); + }).readSourceCode(); }); it('should throw an error if `inputPath` is the excluded file path', () => { @@ -306,7 +301,7 @@ describe('SourceCodeFileUtils', () => { }); describe('Variant #4: `exclude` option', () => { - describe('Variant #1: `inputPath` isn\'t excluded path', () => { + describe("Variant #1: `inputPath` isn't excluded path", () => { const tmpFileName1: string = 'foo.js'; const tmpFileName2: string = 'bar.js'; const tmpFileName3: string = 'baz.png'; @@ -334,12 +329,9 @@ describe('SourceCodeFileUtils', () => { fs.writeFileSync(filePath2, fileContent); fs.writeFileSync(filePath3, fileContent); fs.writeFileSync(filePath4, fileContent); - result = new SourceCodeFileUtils( - tmpDirectoryPath, - { - exclude: ['**/hawk.js'] - } - ).readSourceCode(); + result = new SourceCodeFileUtils(tmpDirectoryPath, { + exclude: ['**/hawk.js'] + }).readSourceCode(); }); it('should return files data', () => { @@ -383,15 +375,9 @@ describe('SourceCodeFileUtils', () => { fs.writeFileSync(filePath2, fileContent); fs.writeFileSync(filePath3, fileContent); fs.writeFileSync(filePath4, fileContent); - result = new SourceCodeFileUtils( - tmpDirectoryPath, - { - exclude: [ - `**/${tmpFileName2}`, - `**/${tmpFileName4}` - ] - } - ).readSourceCode(); + result = new SourceCodeFileUtils(tmpDirectoryPath, { + exclude: [`**/${tmpFileName2}`, `**/${tmpFileName4}`] + }).readSourceCode(); }); it('should return files data', () => { @@ -434,15 +420,9 @@ describe('SourceCodeFileUtils', () => { fs.writeFileSync(filePath2, fileContent); fs.writeFileSync(filePath3, fileContent); fs.writeFileSync(filePath4, fileContent); - result = new SourceCodeFileUtils( - tmpDirectoryPath, - { - exclude: [ - tmpFileName2, - tmpFileName4 - ] - } - ).readSourceCode(); + result = new SourceCodeFileUtils(tmpDirectoryPath, { + exclude: [tmpFileName2, tmpFileName4] + }).readSourceCode(); }); it('should return files data', () => { @@ -485,15 +465,9 @@ describe('SourceCodeFileUtils', () => { fs.writeFileSync(filePath2, fileContent); fs.writeFileSync(filePath3, fileContent); fs.writeFileSync(filePath4, fileContent); - result = new SourceCodeFileUtils( - tmpDirectoryPath, - { - exclude: [ - filePath2, - filePath4 - ] - } - ).readSourceCode(); + result = new SourceCodeFileUtils(tmpDirectoryPath, { + exclude: [filePath2, filePath4] + }).readSourceCode(); }); it('should return files data', () => { @@ -525,12 +499,10 @@ describe('SourceCodeFileUtils', () => { fs.writeFileSync(filePath2, fileContent); fs.writeFileSync(filePath3, fileContent); fs.writeFileSync(filePath4, fileContent); - testFunc = () => new SourceCodeFileUtils( - tmpDirectoryPath, - { + testFunc = () => + new SourceCodeFileUtils(tmpDirectoryPath, { exclude: [tmpDirectoryPath] - } - ).readSourceCode(); + }).readSourceCode(); }); it('should return files data', () => { diff --git a/test/unit-tests/decorators/initializable/Initializable.spec.ts b/test/unit-tests/decorators/initializable/Initializable.spec.ts index 7d3f0733..5396acee 100644 --- a/test/unit-tests/decorators/initializable/Initializable.spec.ts +++ b/test/unit-tests/decorators/initializable/Initializable.spec.ts @@ -12,7 +12,7 @@ describe('@initializable', () => { @initializable() public property!: string; - public initialize (property: string): void { + public initialize(property: string): void { this.property = property; } } @@ -24,7 +24,7 @@ describe('@initializable', () => { foo.property; }; - it('shouldn\'t throws an errors if property was initialized', () => { + it("shouldn't throws an errors if property was initialized", () => { assert.doesNotThrow(testFunc, Error); }); }); @@ -36,11 +36,11 @@ describe('@initializable', () => { @initializable() public property!: string; - public initialize (property: string): void { + public initialize(property: string): void { this.property = property; } - public bar (): void {} + public bar(): void {} } const foo: Foo = new Foo(); @@ -49,7 +49,7 @@ describe('@initializable', () => { foo.bar(); }; - it('shouldn\'t throw an error if `initialize` method was called first', () => { + it("shouldn't throw an error if `initialize` method was called first", () => { assert.doesNotThrow(testFunc, /Class should be initialized/); }); }); @@ -60,11 +60,11 @@ describe('@initializable', () => { @initializable() public property!: string; - public initialize (property: string): void { + public initialize(property: string): void { this.innerInitialize(property); } - public innerInitialize (property: string): void { + public innerInitialize(property: string): void { this.property = property; } } @@ -74,7 +74,7 @@ describe('@initializable', () => { foo.initialize('baz'); }; - it('shouldn\'t throw an error if other method was called inside `initialize` method', () => { + it("shouldn't throw an error if other method was called inside `initialize` method", () => { assert.doesNotThrow(testFunc, /Class should be initialized/); }); }); @@ -85,12 +85,11 @@ describe('@initializable', () => { @initializable() public property!: string; - public initialize (property: string): void { + public initialize(property: string): void { this.innerInitialize(property); } - public innerInitialize (property: string): void { - } + public innerInitialize(property: string): void {} } const foo: Foo = new Foo(); @@ -103,17 +102,17 @@ describe('@initializable', () => { }); }); - describe('Variant #4: `initialize` method wasn\'t called first', () => { + describe("Variant #4: `initialize` method wasn't called first", () => { const testFunc: () => void = () => { class Foo { @initializable() public property!: string; - public initialize (property: string): void { + public initialize(property: string): void { this.property = property; } - public bar (): void {} + public bar(): void {} } const foo: Foo = new Foo(); @@ -122,22 +121,22 @@ describe('@initializable', () => { foo.initialize('baz'); }; - it('should throws an error if `initialize` method wasn\'t called first', () => { + it("should throws an error if `initialize` method wasn't called first", () => { assert.throws(testFunc, /Class should be initialized/); }); }); - describe('Variant #5: `initialize` method wasn\'t called', () => { + describe("Variant #5: `initialize` method wasn't called", () => { const testFunc: () => void = () => { class Foo { @initializable() public property!: string; - public initialize (property: string): void { + public initialize(property: string): void { this.property = property; } - public bar (): void {} + public bar(): void {} } const foo: Foo = new Foo(); @@ -145,20 +144,19 @@ describe('@initializable', () => { foo.bar(); }; - it('should throws an error if `initialize` method wasn\'t called first', () => { + it("should throws an error if `initialize` method wasn't called first", () => { assert.throws(testFunc, /Class should be initialized/); }); }); }); - describe('Variant #3: property didn\'t initialized', () => { + describe("Variant #3: property didn't initialized", () => { const testFunc: () => void = () => { class Foo implements IInitializable { @initializable() public property!: string; - public initialize (property: string): void { - } + public initialize(property: string): void {} } const foo: Foo = new Foo(); @@ -168,7 +166,7 @@ describe('@initializable', () => { foo.property; }; - it('should throws an error if property didn\'t initialized', () => { + it("should throws an error if property didn't initialized", () => { assert.throws(testFunc, /Property `property` is not initialized/); }); }); diff --git a/test/unit-tests/generators/identifier-names-generators/DictionarylIdentifierNamesGenerator.spec.ts b/test/unit-tests/generators/identifier-names-generators/DictionarylIdentifierNamesGenerator.spec.ts index 69a36211..55e63bb1 100644 --- a/test/unit-tests/generators/identifier-names-generators/DictionarylIdentifierNamesGenerator.spec.ts +++ b/test/unit-tests/generators/identifier-names-generators/DictionarylIdentifierNamesGenerator.spec.ts @@ -12,8 +12,7 @@ import { IdentifierNamesGenerator } from '../../../../src/enums/generators/ident import { InversifyContainerFacade } from '../../../../src/container/InversifyContainerFacade'; describe('DictionaryIdentifierNamesGenerator', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - dictionaryIdentifierName: string; + let identifierNamesGenerator: IIdentifierNamesGenerator, dictionaryIdentifierName: string; describe('generateNext', () => { describe('Base behaviour', () => { diff --git a/test/unit-tests/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.spec.ts b/test/unit-tests/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.spec.ts index 3800b771..190edad8 100644 --- a/test/unit-tests/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.spec.ts +++ b/test/unit-tests/generators/identifier-names-generators/HexadecimalIdentifierNamesGenerator.spec.ts @@ -14,9 +14,7 @@ import { InversifyContainerFacade } from '../../../../src/container/InversifyCon describe('HexadecimalIdentifierNamesGenerator', () => { describe('generateNext', () => { describe('Base', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - hexadecimalIdentifierName: string, - regExp: RegExp; + let identifierNamesGenerator: IIdentifierNamesGenerator, hexadecimalIdentifierName: string, regExp: RegExp; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -33,13 +31,11 @@ describe('HexadecimalIdentifierNamesGenerator', () => { it('should return hexadecimal name', () => { assert.match(hexadecimalIdentifierName, regExp); - }) + }); }); describe('Custom length', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - hexadecimalIdentifierName: string, - regExp: RegExp; + let identifierNamesGenerator: IIdentifierNamesGenerator, hexadecimalIdentifierName: string, regExp: RegExp; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -56,15 +52,14 @@ describe('HexadecimalIdentifierNamesGenerator', () => { it('should return hexadecimal name', () => { assert.match(hexadecimalIdentifierName, regExp); - }) + }); }); }); describe('generateForGlobalScope', () => { const regExp: RegExp = /^foo_0x(\w){4,6}$/; - let identifierNamesGenerator: IIdentifierNamesGenerator, - hexadecimalIdentifierName: string; + let identifierNamesGenerator: IIdentifierNamesGenerator, hexadecimalIdentifierName: string; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -82,7 +77,7 @@ describe('HexadecimalIdentifierNamesGenerator', () => { it('should return hexadecimal name with prefix', () => { assert.match(hexadecimalIdentifierName, regExp); - }) + }); }); describe('generateForLabel', () => { @@ -105,25 +100,25 @@ describe('HexadecimalIdentifierNamesGenerator', () => { IdentifierNamesGenerator.HexadecimalIdentifierNamesGenerator ); - identifierNamesGenerator.generateForLabel(label1) - identifierNamesGenerator.generateForLabel(label1) + identifierNamesGenerator.generateForLabel(label1); + identifierNamesGenerator.generateForLabel(label1); hexadecimalIdentifierName1 = identifierNamesGenerator.generateForLabel(label1); - identifierNamesGenerator.generateForLabel(label2) - identifierNamesGenerator.generateForLabel(label2) + identifierNamesGenerator.generateForLabel(label2); + identifierNamesGenerator.generateForLabel(label2); hexadecimalIdentifierName2 = identifierNamesGenerator.generateForLabel(label2); }); it('should return valid hexadecimal name 1', () => { assert.match(hexadecimalIdentifierName1, regExp); - }) + }); it('should return valid hexadecimal name 2', () => { assert.match(hexadecimalIdentifierName2, regExp); - }) + }); it('should generate different hexadecimal names for different labels', () => { assert.notEqual(hexadecimalIdentifierName1, hexadecimalIdentifierName2); - }) + }); }); }); diff --git a/test/unit-tests/generators/identifier-names-generators/MangledShuffledlIdentifierNamesGenerator.spec.ts b/test/unit-tests/generators/identifier-names-generators/MangledShuffledlIdentifierNamesGenerator.spec.ts index 2e53bb9d..79519a24 100644 --- a/test/unit-tests/generators/identifier-names-generators/MangledShuffledlIdentifierNamesGenerator.spec.ts +++ b/test/unit-tests/generators/identifier-names-generators/MangledShuffledlIdentifierNamesGenerator.spec.ts @@ -14,8 +14,7 @@ import { MangledShuffledIdentifierNamesGenerator } from '../../../../src/generat describe('MangledShuffledIdentifierNamesGenerator', () => { describe('generateNext', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - mangledIdentifierName: string; + let identifierNamesGenerator: IIdentifierNamesGenerator, mangledIdentifierName: string; beforeEach(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -86,8 +85,7 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { }); describe('generateForGlobalScope', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - mangledIdentifierName: string; + let identifierNamesGenerator: IIdentifierNamesGenerator, mangledIdentifierName: string; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -145,7 +143,7 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { it('should return the same mangled names set for different labels', () => { assert.deepEqual(mangledNames1, mangledNames2); - }) + }); }); describe('isIncrementedMangledName', function () { @@ -155,10 +153,11 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - const identifierNamesGenerator: IIdentifierNamesGenerator = inversifyContainerFacade.getNamed( - ServiceIdentifiers.IIdentifierNamesGenerator, - IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator - ); + const identifierNamesGenerator: IIdentifierNamesGenerator = + inversifyContainerFacade.getNamed( + ServiceIdentifiers.IIdentifierNamesGenerator, + IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator + ); let isSuccessComparison: boolean = true; let mangledName: string = ''; @@ -169,10 +168,13 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { let resultReversed: boolean; mangledName = identifierNamesGenerator.generateNext(); - resultNormal = (identifierNamesGenerator) - .isIncrementedMangledName(mangledName, prevMangledName); - resultReversed = (identifierNamesGenerator) - .isIncrementedMangledName(prevMangledName, mangledName); + resultNormal = (identifierNamesGenerator).isIncrementedMangledName( + mangledName, + prevMangledName + ); + resultReversed = (( + identifierNamesGenerator + )).isIncrementedMangledName(prevMangledName, mangledName); if (!resultNormal || resultReversed) { isSuccessComparison = false; @@ -197,7 +199,7 @@ describe('MangledShuffledIdentifierNamesGenerator', () => { beforeEach(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); - inversifyContainerFacade.load('', '', {} ); + inversifyContainerFacade.load('', '', {}); identifierNamesGenerator = inversifyContainerFacade.getNamed( ServiceIdentifiers.IIdentifierNamesGenerator, IdentifierNamesGenerator.MangledShuffledIdentifierNamesGenerator diff --git a/test/unit-tests/generators/identifier-names-generators/MangledlIdentifierNamesGenerator.spec.ts b/test/unit-tests/generators/identifier-names-generators/MangledlIdentifierNamesGenerator.spec.ts index 8b812510..e64af856 100644 --- a/test/unit-tests/generators/identifier-names-generators/MangledlIdentifierNamesGenerator.spec.ts +++ b/test/unit-tests/generators/identifier-names-generators/MangledlIdentifierNamesGenerator.spec.ts @@ -14,8 +14,7 @@ import { MangledIdentifierNamesGenerator } from '../../../../src/generators/iden describe('MangledIdentifierNamesGenerator', () => { describe('generateNext', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - mangledIdentifierName: string; + let identifierNamesGenerator: IIdentifierNamesGenerator, mangledIdentifierName: string; beforeEach(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -105,8 +104,7 @@ describe('MangledIdentifierNamesGenerator', () => { const expectedMangledIdentifierPosition1: number = 261; const expectedMangledIdentifierPosition2: number = 262; - let mangledIdentifierName1: string, - mangledIdentifierName2: string; + let mangledIdentifierName1: string, mangledIdentifierName2: string; beforeEach(() => { for (let i: number = 0; i <= expectedMangledIdentifierPosition2; i++) { @@ -124,15 +122,14 @@ describe('MangledIdentifierNamesGenerator', () => { assert.equal(mangledIdentifierName1, expectedMangledIdentifierName1); }); - it('shouldn\'t return reserved mangled name', () => { + it("shouldn't return reserved mangled name", () => { assert.equal(mangledIdentifierName2, expectedMangledIdentifierName2); }); }); }); describe('generateForGlobalScope', () => { - let identifierNamesGenerator: IIdentifierNamesGenerator, - mangledIdentifierName: string; + let identifierNamesGenerator: IIdentifierNamesGenerator, mangledIdentifierName: string; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); @@ -178,8 +175,8 @@ describe('MangledIdentifierNamesGenerator', () => { const mangledNames1: string[] = []; const mangledNames2: string[] = []; - const expectedMangledNames1: string[] = ['a', 'b', 'c'] - const expectedMangledNames2: string[] = ['a', 'b'] + const expectedMangledNames1: string[] = ['a', 'b', 'c']; + const expectedMangledNames2: string[] = ['a', 'b']; let identifierNamesGenerator: IIdentifierNamesGenerator; @@ -204,11 +201,11 @@ describe('MangledIdentifierNamesGenerator', () => { it('should return valid mangled names for label 1', () => { assert.deepEqual(mangledNames1, expectedMangledNames1); - }) + }); it('should return valid mangled names for label 2', () => { assert.deepEqual(mangledNames2, expectedMangledNames2); - }) + }); }); describe('isIncrementedMangledName', function () { @@ -218,10 +215,11 @@ describe('MangledIdentifierNamesGenerator', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - const identifierNamesGenerator: IIdentifierNamesGenerator = inversifyContainerFacade.getNamed( - ServiceIdentifiers.IIdentifierNamesGenerator, - IdentifierNamesGenerator.MangledIdentifierNamesGenerator - ); + const identifierNamesGenerator: IIdentifierNamesGenerator = + inversifyContainerFacade.getNamed( + ServiceIdentifiers.IIdentifierNamesGenerator, + IdentifierNamesGenerator.MangledIdentifierNamesGenerator + ); let isSuccessComparison: boolean = true; let mangledName: string = ''; @@ -232,10 +230,14 @@ describe('MangledIdentifierNamesGenerator', () => { let resultReversed: boolean; mangledName = identifierNamesGenerator.generateNext(); - resultNormal = (identifierNamesGenerator) - .isIncrementedMangledName(mangledName, prevMangledName); - resultReversed = (identifierNamesGenerator) - .isIncrementedMangledName(prevMangledName, mangledName); + resultNormal = (identifierNamesGenerator).isIncrementedMangledName( + mangledName, + prevMangledName + ); + resultReversed = (identifierNamesGenerator).isIncrementedMangledName( + prevMangledName, + mangledName + ); if (!resultNormal || resultReversed) { isSuccessComparison = false; @@ -322,7 +324,7 @@ describe('MangledIdentifierNamesGenerator', () => { beforeEach(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); - inversifyContainerFacade.load('', '', {} ); + inversifyContainerFacade.load('', '', {}); identifierNamesGenerator = inversifyContainerFacade.getNamed( ServiceIdentifiers.IIdentifierNamesGenerator, IdentifierNamesGenerator.MangledIdentifierNamesGenerator diff --git a/test/unit-tests/javascript-obfuscator/ASTParserFacade.spec.ts b/test/unit-tests/javascript-obfuscator/ASTParserFacade.spec.ts index abdb2d45..2546cebe 100644 --- a/test/unit-tests/javascript-obfuscator/ASTParserFacade.spec.ts +++ b/test/unit-tests/javascript-obfuscator/ASTParserFacade.spec.ts @@ -8,8 +8,9 @@ describe('ASTParserFacade', () => { describe(`parse`, () => { describe(`\`Unexpected token\` error code preview`, () => { describe('Variant #1: 5 lines of code', () => { - const sourceCode: string = `` + - `var foo = 1; + const sourceCode: string = + `` + + `var foo = 1; var bar = 2; var baz = 3;, var bark = 4; @@ -27,8 +28,9 @@ describe('ASTParserFacade', () => { }); describe('Variant #2: 15 lines of code', () => { - const sourceCode: string = `` + - `var var1 = 1; + const sourceCode: string = + `` + + `var var1 = 1; var var2 = 2; var var3 = 3; var var4 = 4; @@ -51,12 +53,16 @@ describe('ASTParserFacade', () => { }); it('should output code preview when AST parser throws a parse error', () => { - assert.throws(testFunc, /ERROR at line 13: Unexpected token \(13:28\)\n.*\.\.\.var baz = 3;,\.\.\./); + assert.throws( + testFunc, + /ERROR at line 13: Unexpected token \(13:28\)\n.*\.\.\.var baz = 3;,\.\.\./ + ); }); }); describe('Variant #3: code with functions', () => { - const sourceCode: string = `` + + const sourceCode: string = + `` + `function bar () { var a = 1; } @@ -74,7 +80,10 @@ describe('ASTParserFacade', () => { }); it('should output code preview when AST parser throws a parse error', () => { - assert.throws(testFunc, /ERROR at line 4: Unexpected token \(4:28\)\n.*\.\.\.functin baz \(\) {\.\.\./); + assert.throws( + testFunc, + /ERROR at line 4: Unexpected token \(4:28\)\n.*\.\.\.functin baz \(\) {\.\.\./ + ); }); }); }); diff --git a/test/unit-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts b/test/unit-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts index f4334e5b..ca05b734 100644 --- a/test/unit-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts +++ b/test/unit-tests/javascript-obfuscator/JavaScriptObfuscator.spec.ts @@ -21,24 +21,19 @@ describe('JavaScriptObfuscator', () => { describe('Variant #1: default behaviour', () => { const regExp: RegExp = new RegExp(`sourceMappingURL=${sourceMapUrl}`); - let obfuscatedCode: string, - sourceMapObject: any; + let obfuscatedCode: string, sourceMapObject: any; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); - inversifyContainerFacade.load( - '', - '', - { - ...NO_ADDITIONAL_NODES_PRESET, - sourceMap: true, - sourceMapFileName: sourceMapUrl - } + inversifyContainerFacade.load('', '', { + ...NO_ADDITIONAL_NODES_PRESET, + sourceMap: true, + sourceMapFileName: sourceMapUrl + }); + javaScriptObfuscator = inversifyContainerFacade.get( + ServiceIdentifiers.IJavaScriptObfuscator ); - javaScriptObfuscator = inversifyContainerFacade - .get(ServiceIdentifiers.IJavaScriptObfuscator); - const obfuscationResult: IObfuscationResult = javaScriptObfuscator.obfuscate(code); @@ -59,25 +54,20 @@ describe('JavaScriptObfuscator', () => { const sourceMapBaseUrl: string = 'http://localhost:9000'; const regExp: RegExp = new RegExp(`sourceMappingURL=${sourceMapBaseUrl}/${sourceMapUrl}$`); - let obfuscatedCode: string, - sourceMapObject: any; + let obfuscatedCode: string, sourceMapObject: any; before(() => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); - inversifyContainerFacade.load( - '', - '', - { - ...NO_ADDITIONAL_NODES_PRESET, - sourceMap: true, - sourceMapBaseUrl: sourceMapBaseUrl, - sourceMapFileName: sourceMapUrl - } + inversifyContainerFacade.load('', '', { + ...NO_ADDITIONAL_NODES_PRESET, + sourceMap: true, + sourceMapBaseUrl: sourceMapBaseUrl, + sourceMapFileName: sourceMapUrl + }); + javaScriptObfuscator = inversifyContainerFacade.get( + ServiceIdentifiers.IJavaScriptObfuscator ); - javaScriptObfuscator = inversifyContainerFacade - .get(ServiceIdentifiers.IJavaScriptObfuscator); - const obfuscationResult: IObfuscationResult = javaScriptObfuscator.obfuscate(code); diff --git a/test/unit-tests/logger/Logger.spec.ts b/test/unit-tests/logger/Logger.spec.ts index a490f88a..92885c5a 100644 --- a/test/unit-tests/logger/Logger.spec.ts +++ b/test/unit-tests/logger/Logger.spec.ts @@ -21,9 +21,7 @@ describe('Logger', () => { const loggingMessage: string = '[javascript-obfuscator] foo'; const expectedConsoleLogCallResult: boolean = true; - let consoleLogSpy: sinon.SinonSpy, - consoleLogCallResult: boolean, - loggingMessageResult: string; + let consoleLogSpy: sinon.SinonSpy, consoleLogCallResult: boolean, loggingMessageResult: string; before(() => { consoleLogSpy = sinon.spy(console, 'log'); @@ -106,7 +104,7 @@ describe('Logger', () => { consoleLogCallResult = consoleLogSpy.called; }); - it('shouldn\'t call `console.log`', () => { + it("shouldn't call `console.log`", () => { assert.equal(consoleLogCallResult, expectedConsoleLogCallResult); }); @@ -177,7 +175,7 @@ describe('Logger', () => { consoleLogCallResult = consoleLogSpy.called; }); - it('shouldn\'t call `console.log`', () => { + it("shouldn't call `console.log`", () => { assert.equal(consoleLogCallResult, expectedConsoleLogCallResult); }); @@ -248,7 +246,7 @@ describe('Logger', () => { consoleLogCallResult = consoleLogSpy.called; }); - it('shouldn\'t call `console.log`', () => { + it("shouldn't call `console.log`", () => { assert.equal(consoleLogCallResult, expectedConsoleLogCallResult); }); diff --git a/test/unit-tests/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.spec.ts b/test/unit-tests/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.spec.ts index 411ef6a9..3e06b257 100644 --- a/test/unit-tests/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.spec.ts +++ b/test/unit-tests/node-transformers/preparing-transformers/ObfuscatingGuardsTransformer.spec.ts @@ -20,23 +20,19 @@ describe('ObfuscatingGuardsTransformer', () => { const forceTransformString: string = 'important string'; const ignoredAndForceTransformString: string = 'important ignored string'; - let inversifyContainerFacade: IInversifyContainerFacade, - obfuscatingGuardsTransformer: INodeTransformer; + let inversifyContainerFacade: IInversifyContainerFacade, obfuscatingGuardsTransformer: INodeTransformer; before(() => { inversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', { - forceTransformStrings: [ - forceTransformString, - ignoredAndForceTransformString - ], - reservedStrings: [ - ignoredAndForceTransformString - ] + forceTransformStrings: [forceTransformString, ignoredAndForceTransformString], + reservedStrings: [ignoredAndForceTransformString] }); - obfuscatingGuardsTransformer = inversifyContainerFacade - .getNamed(ServiceIdentifiers.INodeTransformer, NodeTransformer.ObfuscatingGuardsTransformer); + obfuscatingGuardsTransformer = inversifyContainerFacade.getNamed( + ServiceIdentifiers.INodeTransformer, + NodeTransformer.ObfuscatingGuardsTransformer + ); }); describe('Variant #1: transform node', () => { @@ -82,8 +78,9 @@ describe('ObfuscatingGuardsTransformer', () => { ignoredNode: true }); - result = obfuscatingGuardsTransformer - .transformNode(expressionStatement, expressionStatement); + result = ( + obfuscatingGuardsTransformer.transformNode(expressionStatement, expressionStatement) + ); }); it('should add `ignoredNode` property with `true` value to given node', () => { @@ -92,7 +89,7 @@ describe('ObfuscatingGuardsTransformer', () => { }); describe('Variant #3: force transform node', () => { - const literalNode: ESTree.Literal = NodeFactory.literalNode(forceTransformString); + const literalNode: ESTree.Literal = NodeFactory.literalNode(forceTransformString); const expectedResult: ESTree.Literal = NodeUtils.clone(literalNode); @@ -107,8 +104,7 @@ describe('ObfuscatingGuardsTransformer', () => { ignoredNode: false }); - result = obfuscatingGuardsTransformer - .transformNode(literalNode, literalNode); + result = obfuscatingGuardsTransformer.transformNode(literalNode, literalNode); }); it('should add `forceTransformNode` property with `true` value to given node', () => { @@ -132,8 +128,7 @@ describe('ObfuscatingGuardsTransformer', () => { ignoredNode: false }); - result = obfuscatingGuardsTransformer - .transformNode(literalNode, literalNode); + result = obfuscatingGuardsTransformer.transformNode(literalNode, literalNode); }); it('should add correct metadata to given node', () => { diff --git a/test/unit-tests/node/node-appender/NodeAppender.spec.ts b/test/unit-tests/node/node-appender/NodeAppender.spec.ts index c0891eeb..a4451c9d 100644 --- a/test/unit-tests/node/node-appender/NodeAppender.spec.ts +++ b/test/unit-tests/node/node-appender/NodeAppender.spec.ts @@ -25,11 +25,7 @@ import { NodeUtils } from '../../../../src/node/NodeUtils'; * @return {TStatement[]} */ const convertCodeToStructure: (fixturePath: string) => TStatement[] = (fixturePath) => { - return removeRangesFromStructure( - NodeUtils.convertCodeToStructure( - readFileAsString(`${__dirname}${fixturePath}`) - ) - ); + return removeRangesFromStructure(NodeUtils.convertCodeToStructure(readFileAsString(`${__dirname}${fixturePath}`))); }; /** @@ -42,9 +38,7 @@ const convertCodeToAst: (fixturePath: string) => ESTree.Program = (fixturePath) describe('NodeAppender', () => { describe('append', () => { - let astTree: ESTree.Program, - expectedAstTree: ESTree.Program, - node: TStatement[]; + let astTree: ESTree.Program, expectedAstTree: ESTree.Program, node: TStatement[]; before(() => { node = convertCodeToStructure('/fixtures/simple-input.js'); @@ -73,8 +67,9 @@ describe('NodeAppender', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - callsGraphAnalyzer = inversifyContainerFacade - .get(ServiceIdentifiers.ICallsGraphAnalyzer); + callsGraphAnalyzer = inversifyContainerFacade.get( + ServiceIdentifiers.ICallsGraphAnalyzer + ); }); beforeEach(() => { @@ -84,7 +79,9 @@ describe('NodeAppender', () => { describe('Variant #1: nested function calls', () => { beforeEach(() => { astTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/variant-1.js'); - expectedAstTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/variant-1-expected.js'); + expectedAstTree = convertCodeToAst( + '/fixtures/append-node-to-optimal-block-scope/variant-1-expected.js' + ); callsGraphData = callsGraphAnalyzer.analyze(astTree); NodeAppender.appendToOptimalBlockScope(callsGraphData, astTree, node); @@ -98,11 +95,12 @@ describe('NodeAppender', () => { describe('Variant #2: nested function calls', () => { beforeEach(() => { astTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/variant-2.js'); - expectedAstTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/variant-2-expected.js'); + expectedAstTree = convertCodeToAst( + '/fixtures/append-node-to-optimal-block-scope/variant-2-expected.js' + ); callsGraphData = callsGraphAnalyzer.analyze(astTree); NodeAppender.appendToOptimalBlockScope(callsGraphData, astTree, node); - }); it('should append node into first and deepest function call in nested function calls', () => { @@ -119,11 +117,12 @@ describe('NodeAppender', () => { describe('Variant #1: append by specific index in nested function calls', () => { beforeEach(() => { - expectedAstTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/by-index-variant-1-expected.js'); + expectedAstTree = convertCodeToAst( + '/fixtures/append-node-to-optimal-block-scope/by-index-variant-1-expected.js' + ); callsGraphData = callsGraphAnalyzer.analyze(astTree); NodeAppender.appendToOptimalBlockScope(callsGraphData, astTree, node, 2); - }); it('should append node into deepest function call by specified index in nested function calls', () => { @@ -133,11 +132,12 @@ describe('NodeAppender', () => { describe('Variant #2: append by specific index in nested function calls', () => { beforeEach(() => { - expectedAstTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/by-index-variant-2-expected.js'); + expectedAstTree = convertCodeToAst( + '/fixtures/append-node-to-optimal-block-scope/by-index-variant-2-expected.js' + ); callsGraphData = callsGraphAnalyzer.analyze(astTree); NodeAppender.appendToOptimalBlockScope(callsGraphData, astTree, node, 1); - }); it('should append node into deepest function call by specified index in nested function calls', () => { @@ -148,16 +148,12 @@ describe('NodeAppender', () => { describe('Variant #3: append by specific index in nested function calls', () => { beforeEach(() => { astTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/by-index-variant-3.js'); - expectedAstTree = convertCodeToAst('/fixtures/append-node-to-optimal-block-scope/by-index-variant-3-expected.js'); - - callsGraphData = callsGraphAnalyzer.analyze(astTree); - NodeAppender.appendToOptimalBlockScope( - callsGraphData, - astTree, - node, - callsGraphData.length - 1 + expectedAstTree = convertCodeToAst( + '/fixtures/append-node-to-optimal-block-scope/by-index-variant-3-expected.js' ); + callsGraphData = callsGraphAnalyzer.analyze(astTree); + NodeAppender.appendToOptimalBlockScope(callsGraphData, astTree, node, callsGraphData.length - 1); }); it('should append node into deepest function call by specified index in nested function calls', () => { @@ -214,9 +210,7 @@ describe('NodeAppender', () => { }); describe('insertAtIndex', () => { - let astTree: ESTree.Program, - expectedAstTree: ESTree.Program, - node: TStatement[]; + let astTree: ESTree.Program, expectedAstTree: ESTree.Program, node: TStatement[]; before(() => { node = convertCodeToStructure('/fixtures/simple-input.js'); @@ -235,9 +229,7 @@ describe('NodeAppender', () => { }); describe('prepend', () => { - let astTree: ESTree.Program, - expectedAstTree: ESTree.Program, - node: TStatement[]; + let astTree: ESTree.Program, expectedAstTree: ESTree.Program, node: TStatement[]; before(() => { node = convertCodeToStructure('/fixtures/simple-input.js'); @@ -257,8 +249,7 @@ describe('NodeAppender', () => { describe('remove', () => { describe('Variant #1: valid index', () => { - let astTree: ESTree.Program, - expectedAstTree: ESTree.Program; + let astTree: ESTree.Program, expectedAstTree: ESTree.Program; before(() => { astTree = convertCodeToAst('/fixtures/remove-node/valid-index.js'); @@ -276,8 +267,7 @@ describe('NodeAppender', () => { }); describe('Variant #2: invalid index', () => { - let astTree: ESTree.Program, - expectedAstTree: ESTree.Program; + let astTree: ESTree.Program, expectedAstTree: ESTree.Program; before(() => { astTree = convertCodeToAst('/fixtures/remove-node/invalid-index.js'); diff --git a/test/unit-tests/node/node-guards/NodeGuards.spec.ts b/test/unit-tests/node/node-guards/NodeGuards.spec.ts index df9f82e0..00f9324d 100644 --- a/test/unit-tests/node/node-guards/NodeGuards.spec.ts +++ b/test/unit-tests/node/node-guards/NodeGuards.spec.ts @@ -13,9 +13,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -34,13 +32,9 @@ describe('NodeGuards', () => { const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ]), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -58,12 +52,8 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)), + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -99,15 +89,9 @@ describe('NodeGuards', () => { const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ]), - NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) - ]) + NodeFactory.blockStatementNode([NodeFactory.expressionStatementNode(NodeFactory.literalNode(true))]) ); let result: boolean; @@ -128,11 +112,7 @@ describe('NodeGuards', () => { describe('Variant #1: block statement of function declaration', () => { const expectedResult: boolean = true; const node: ESTree.Node = NodeFactory.blockStatementNode(); - const parentNode: ESTree.FunctionDeclaration = NodeFactory.functionDeclarationNode( - 'foo', - [], - node - ); + const parentNode: ESTree.FunctionDeclaration = NodeFactory.functionDeclarationNode('foo', [], node); let result: boolean; @@ -149,10 +129,7 @@ describe('NodeGuards', () => { describe('Variant #2: block statement of function expression', () => { const expectedResult: boolean = true; const node: ESTree.Node = NodeFactory.blockStatementNode(); - const parentNode: ESTree.FunctionExpression = NodeFactory.functionExpressionNode( - [], - node - ); + const parentNode: ESTree.FunctionExpression = NodeFactory.functionExpressionNode([], node); let result: boolean; @@ -170,10 +147,7 @@ describe('NodeGuards', () => { describe('false checks', () => { describe('Variant #1: switch-case node', () => { const expectedResult: boolean = false; - const node: ESTree.Node = NodeFactory.switchCaseNode( - NodeFactory.literalNode(1), - [] - ); + const node: ESTree.Node = NodeFactory.switchCaseNode(NodeFactory.literalNode(1), []); const parentNode: ESTree.FunctionDeclaration = NodeFactory.functionDeclarationNode( 'foo', [], @@ -181,10 +155,7 @@ describe('NodeGuards', () => { NodeFactory.switchStatementNode( NodeFactory.memberExpressionNode( NodeFactory.identifierNode('bar'), - NodeFactory.updateExpressionNode( - '++', - NodeFactory.identifierNode('baz') - ), + NodeFactory.updateExpressionNode('++', NodeFactory.identifierNode('baz')), true ), [node] @@ -212,10 +183,7 @@ describe('NodeGuards', () => { [], NodeFactory.blockStatementNode([ NodeFactory.expressionStatementNode( - NodeFactory.callExpressionNode( - NodeFactory.identifierNode('bar'), - [node] - ) + NodeFactory.callExpressionNode(NodeFactory.identifierNode('bar'), [node]) ) ]) ); @@ -261,9 +229,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -282,13 +248,9 @@ describe('NodeGuards', () => { const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ]), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -306,12 +268,8 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)), + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -330,23 +288,11 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.ForStatement = NodeFactory.forStatementNode( NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('i'), - NodeFactory.literalNode(0) - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('i'), NodeFactory.literalNode(0)) ]), - NodeFactory.binaryExpressionNode( - '<', - NodeFactory.identifierNode('i'), - NodeFactory.literalNode(10) - ), - NodeFactory.updateExpressionNode( - '++', - NodeFactory.identifierNode('i') - ), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.binaryExpressionNode('<', NodeFactory.identifierNode('i'), NodeFactory.literalNode(10)), + NodeFactory.updateExpressionNode('++', NodeFactory.identifierNode('i')), + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -364,17 +310,10 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.ForInStatement = NodeFactory.forInStatementNode( NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('key'), - null - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('key'), null) ]), - NodeFactory.objectExpressionNode( - [] - ), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.objectExpressionNode([]), + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -393,17 +332,10 @@ describe('NodeGuards', () => { const node: ESTree.ForOfStatement = NodeFactory.forOfStatementNode( false, NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('key'), - null - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('key'), null) ]), - NodeFactory.objectExpressionNode( - [] - ), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.objectExpressionNode([]), + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -421,9 +353,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.WhileStatement = NodeFactory.whileStatementNode( NodeFactory.literalNode(true), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -440,9 +370,7 @@ describe('NodeGuards', () => { describe('Variant #6: `DoWhileStatement` node', () => { const expectedResult: boolean = true; const node: ESTree.DoWhileStatement = NodeFactory.doWhileStatementNode( - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ), + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)), NodeFactory.literalNode(true) ); @@ -461,9 +389,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = true; const node: ESTree.LabeledStatement = NodeFactory.labeledStatementNode( NodeFactory.identifierNode('label'), - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ); let result: boolean; @@ -485,14 +411,10 @@ describe('NodeGuards', () => { const node: ESTree.IfStatement = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ]), NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ]) ); @@ -512,25 +434,11 @@ describe('NodeGuards', () => { const expectedResult: boolean = false; const node: ESTree.ForStatement = NodeFactory.forStatementNode( NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('i'), - NodeFactory.literalNode(0) - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('i'), NodeFactory.literalNode(0)) ]), - NodeFactory.binaryExpressionNode( - '<', - NodeFactory.identifierNode('i'), - NodeFactory.literalNode(10) - ), - NodeFactory.updateExpressionNode( - '++', - NodeFactory.identifierNode('i') - ), - NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) - ]) + NodeFactory.binaryExpressionNode('<', NodeFactory.identifierNode('i'), NodeFactory.literalNode(10)), + NodeFactory.updateExpressionNode('++', NodeFactory.identifierNode('i')), + NodeFactory.blockStatementNode([NodeFactory.expressionStatementNode(NodeFactory.literalNode(true))]) ); let result: boolean; @@ -548,19 +456,10 @@ describe('NodeGuards', () => { const expectedResult: boolean = false; const node: ESTree.ForInStatement = NodeFactory.forInStatementNode( NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('key'), - null - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('key'), null) ]), - NodeFactory.objectExpressionNode( - [] - ), - NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) - ]) + NodeFactory.objectExpressionNode([]), + NodeFactory.blockStatementNode([NodeFactory.expressionStatementNode(NodeFactory.literalNode(true))]) ); let result: boolean; @@ -579,19 +478,10 @@ describe('NodeGuards', () => { const node: ESTree.ForOfStatement = NodeFactory.forOfStatementNode( false, NodeFactory.variableDeclarationNode([ - NodeFactory.variableDeclaratorNode( - NodeFactory.identifierNode('key'), - null - ) + NodeFactory.variableDeclaratorNode(NodeFactory.identifierNode('key'), null) ]), - NodeFactory.objectExpressionNode( - [] - ), - NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) - ]) + NodeFactory.objectExpressionNode([]), + NodeFactory.blockStatementNode([NodeFactory.expressionStatementNode(NodeFactory.literalNode(true))]) ); let result: boolean; @@ -609,11 +499,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = false; const node: ESTree.WhileStatement = NodeFactory.whileStatementNode( NodeFactory.literalNode(true), - NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) - ]) + NodeFactory.blockStatementNode([NodeFactory.expressionStatementNode(NodeFactory.literalNode(true))]) ); let result: boolean; @@ -631,9 +517,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = false; const node: ESTree.DoWhileStatement = NodeFactory.doWhileStatementNode( NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode(true)) ]), NodeFactory.literalNode(true) ); @@ -653,11 +537,7 @@ describe('NodeGuards', () => { const expectedResult: boolean = false; const node: ESTree.LabeledStatement = NodeFactory.labeledStatementNode( NodeFactory.identifierNode('label'), - NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode(true) - ) - ]) + NodeFactory.blockStatementNode([NodeFactory.expressionStatementNode(NodeFactory.literalNode(true))]) ); let result: boolean; @@ -723,10 +603,7 @@ describe('NodeGuards', () => { describe('Variant #4: switch case node', () => { const expectedResult: boolean = true; - const node: ESTree.Node = NodeFactory.switchCaseNode( - NodeFactory.literalNode(1), - [] - ); + const node: ESTree.Node = NodeFactory.switchCaseNode(NodeFactory.literalNode(1), []); let result: boolean; @@ -791,10 +668,7 @@ describe('NodeGuards', () => { describe('Variant #4: switch-statement node', () => { const expectedResult: boolean = false; - const node: ESTree.Node = NodeFactory.switchStatementNode( - NodeFactory.identifierNode('foo'), - [] - ); + const node: ESTree.Node = NodeFactory.switchStatementNode(NodeFactory.identifierNode('foo'), []); let result: boolean; diff --git a/test/unit-tests/node/node-lexical-scope-utils/NodeLexicalScopeUtils.spec.ts b/test/unit-tests/node/node-lexical-scope-utils/NodeLexicalScopeUtils.spec.ts index 9b1a58ea..a68024fb 100644 --- a/test/unit-tests/node/node-lexical-scope-utils/NodeLexicalScopeUtils.spec.ts +++ b/test/unit-tests/node/node-lexical-scope-utils/NodeLexicalScopeUtils.spec.ts @@ -33,9 +33,7 @@ describe('NodeLexicalScopeUtils', () => { ifStatementBlockStatementNode2 ); - ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ - ifStatementNode2 - ]); + ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ifStatementNode2]); ifStatementNode1 = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), @@ -47,11 +45,13 @@ describe('NodeLexicalScopeUtils', () => { ifStatementNode1 ]); - functionDeclarationNode = NodeFactory.functionDeclarationNode('test', [], functionDeclarationBlockStatementNode); + functionDeclarationNode = NodeFactory.functionDeclarationNode( + 'test', + [], + functionDeclarationBlockStatementNode + ); - programNode = NodeFactory.programNode([ - functionDeclarationNode - ]); + programNode = NodeFactory.programNode([functionDeclarationNode]); programNode.parentNode = programNode; functionDeclarationNode.parentNode = programNode; @@ -73,7 +73,10 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `functionDeclaration blockStatement` node child node', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScope(functionDeclarationBlockStatementNode), functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScope(functionDeclarationBlockStatementNode), + functionDeclarationNode + ); }); it('should return lexical scope node for `expressionStatement` node #1 child node', () => { @@ -85,11 +88,17 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `ifStatement blockStatement` node #1 child node', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScope(ifStatementBlockStatementNode1), functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScope(ifStatementBlockStatementNode1), + functionDeclarationNode + ); }); it('should return lexical scope node for `ifStatement blockStatement` node #2 child node', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScope(ifStatementBlockStatementNode2), functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScope(ifStatementBlockStatementNode2), + functionDeclarationNode + ); }); it('should return lexical scope node for `expressionStatement` node #3 child node', () => { @@ -128,9 +137,7 @@ describe('NodeLexicalScopeUtils', () => { ifStatementBlockStatementNode2 ); - ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ - ifStatementNode2 - ]); + ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ifStatementNode2]); ifStatementNode1 = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), @@ -142,11 +149,13 @@ describe('NodeLexicalScopeUtils', () => { ifStatementNode1 ]); - functionDeclarationNode = NodeFactory.functionDeclarationNode('test', [], functionDeclarationBlockStatementNode); + functionDeclarationNode = NodeFactory.functionDeclarationNode( + 'test', + [], + functionDeclarationBlockStatementNode + ); - programNode = NodeFactory.programNode([ - functionDeclarationNode - ]); + programNode = NodeFactory.programNode([functionDeclarationNode]); programNode.parentNode = programNode; functionDeclarationNode.parentNode = programNode; @@ -164,7 +173,10 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `functionDeclaration` node child node #1', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScopes(functionDeclarationNode)[0], functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScopes(functionDeclarationNode)[0], + functionDeclarationNode + ); }); it('should return lexical scope node for `functionDeclaration` node child node #2', () => { @@ -172,11 +184,17 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `functionDeclaration blockStatement` node child node #1', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScopes(functionDeclarationBlockStatementNode)[0], functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScopes(functionDeclarationBlockStatementNode)[0], + functionDeclarationNode + ); }); it('should return lexical scope node for `expressionStatement` node #1 child node #1', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScopes(expressionStatementNode1)[0], functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScopes(expressionStatementNode1)[0], + functionDeclarationNode + ); }); it('should return lexical scope node for `expressionStatement` node #1 child node #2', () => { @@ -192,7 +210,10 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `ifStatement blockStatement` node #1 child node #1', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScopes(ifStatementBlockStatementNode1)[0], functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScopes(ifStatementBlockStatementNode1)[0], + functionDeclarationNode + ); }); it('should return lexical scope node for `ifStatement blockStatement` node #1 child node #2', () => { @@ -200,7 +221,10 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `ifStatement blockStatement` node #2 child node #1', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScopes(ifStatementBlockStatementNode2)[0], functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScopes(ifStatementBlockStatementNode2)[0], + functionDeclarationNode + ); }); it('should return lexical scope node for `ifStatement blockStatement` node #1 child node #2', () => { @@ -208,7 +232,10 @@ describe('NodeLexicalScopeUtils', () => { }); it('should return lexical scope node for `expressionStatement` node #3 child node #1', () => { - assert.deepEqual(NodeLexicalScopeUtils.getLexicalScopes(expressionStatementNode3)[0], functionDeclarationNode); + assert.deepEqual( + NodeLexicalScopeUtils.getLexicalScopes(expressionStatementNode3)[0], + functionDeclarationNode + ); }); it('should return lexical scope node for `expressionStatement` node #3 child node #2', () => { diff --git a/test/unit-tests/node/node-literal-utils/NodeLiteralUtils.spec.ts b/test/unit-tests/node/node-literal-utils/NodeLiteralUtils.spec.ts index 90e0e2c4..6342bbdb 100644 --- a/test/unit-tests/node/node-literal-utils/NodeLiteralUtils.spec.ts +++ b/test/unit-tests/node/node-literal-utils/NodeLiteralUtils.spec.ts @@ -58,9 +58,7 @@ describe('NodeLiteralUtils', () => { let statementNode: ESTree.Statement; before(() => { - statementNode = NodeFactory.expressionStatementNode( - literalNode - ); + statementNode = NodeFactory.expressionStatementNode(literalNode); literalNode.parentNode = statementNode; }); @@ -77,10 +75,7 @@ describe('NodeLiteralUtils', () => { let propertyNode: ESTree.Property; before(() => { - propertyNode = NodeFactory.propertyNode( - literalNode, - NodeFactory.literalNode(1) - ); + propertyNode = NodeFactory.propertyNode(literalNode, NodeFactory.literalNode(1)); literalNode.parentNode = propertyNode; }); @@ -96,11 +91,7 @@ describe('NodeLiteralUtils', () => { let propertyNode: ESTree.Property; before(() => { - propertyNode = NodeFactory.propertyNode( - literalNode, - NodeFactory.literalNode(1), - true - ); + propertyNode = NodeFactory.propertyNode(literalNode, NodeFactory.literalNode(1), true); literalNode.parentNode = propertyNode; }); @@ -116,10 +107,7 @@ describe('NodeLiteralUtils', () => { let propertyNode: ESTree.Property; before(() => { - propertyNode = NodeFactory.propertyNode( - NodeFactory.literalNode(1), - literalNode - ); + propertyNode = NodeFactory.propertyNode(NodeFactory.literalNode(1), literalNode); literalNode.parentNode = propertyNode; }); @@ -137,16 +125,16 @@ describe('NodeLiteralUtils', () => { let importDeclarationNode: ESTree.ImportDeclaration; before(() => { - importDeclarationNode = NodeFactory.importDeclarationNode( - [], - literalNode - ); + importDeclarationNode = NodeFactory.importDeclarationNode([], literalNode); literalNode.parentNode = importDeclarationNode; }); it('should return false for import declaration literal node', () => { - assert.equal(NodeLiteralUtils.isProhibitedLiteralNode(literalNode, importDeclarationNode), true); + assert.equal( + NodeLiteralUtils.isProhibitedLiteralNode(literalNode, importDeclarationNode), + true + ); }); }); }); @@ -158,16 +146,16 @@ describe('NodeLiteralUtils', () => { let exportNamedDeclarationNode: ESTree.ExportNamedDeclaration; before(() => { - exportNamedDeclarationNode = NodeFactory.exportNamedDeclarationNode( - [], - literalNode - ); + exportNamedDeclarationNode = NodeFactory.exportNamedDeclarationNode([], literalNode); literalNode.parentNode = exportNamedDeclarationNode; }); it('should return false for export named declaration literal node', () => { - assert.equal(NodeLiteralUtils.isProhibitedLiteralNode(literalNode, exportNamedDeclarationNode), true); + assert.equal( + NodeLiteralUtils.isProhibitedLiteralNode(literalNode, exportNamedDeclarationNode), + true + ); }); }); }); @@ -179,16 +167,16 @@ describe('NodeLiteralUtils', () => { let exportAllDeclarationNode: ESTree.ExportAllDeclaration; before(() => { - exportAllDeclarationNode = NodeFactory.exportAllDeclarationNode( - literalNode, - null - ); + exportAllDeclarationNode = NodeFactory.exportAllDeclarationNode(literalNode, null); literalNode.parentNode = exportAllDeclarationNode; }); it('should return false for export all declaration literal node', () => { - assert.equal(NodeLiteralUtils.isProhibitedLiteralNode(literalNode, exportAllDeclarationNode), true); + assert.equal( + NodeLiteralUtils.isProhibitedLiteralNode(literalNode, exportAllDeclarationNode), + true + ); }); }); }); @@ -201,13 +189,9 @@ describe('NodeLiteralUtils', () => { let statementNode: ESTree.Statement; before(() => { - statementNode = NodeFactory.expressionStatementNode( - literalNode - ); + statementNode = NodeFactory.expressionStatementNode(literalNode); - const blockStatementNode: ESTree.BlockStatement = NodeFactory.blockStatementNode([ - statementNode - ]); + const blockStatementNode: ESTree.BlockStatement = NodeFactory.blockStatementNode([statementNode]); statementNode.parentNode = blockStatementNode; literalNode.parentNode = statementNode; diff --git a/test/unit-tests/node/node-metadata/NodeMetadata.spec.ts b/test/unit-tests/node/node-metadata/NodeMetadata.spec.ts index b508077b..d806c8fc 100644 --- a/test/unit-tests/node/node-metadata/NodeMetadata.spec.ts +++ b/test/unit-tests/node/node-metadata/NodeMetadata.spec.ts @@ -21,7 +21,7 @@ describe('NodeMetadata', () => { NodeMetadata.set(node, { ignoredNode: true, stringArrayCallLiteralNode: true - }) + }); }); it('should set metadata to the node', () => { @@ -32,17 +32,16 @@ describe('NodeMetadata', () => { describe('get', () => { const expectedValue: boolean = true; - let node: ESTree.Literal, - value: boolean | undefined; + let node: ESTree.Literal, value: boolean | undefined; before(() => { node = NodeFactory.literalNode('foo'); node.metadata = {}; node.metadata.stringArrayCallLiteralNode = true; - value = NodeMetadata.get< - ESTree.LiteralNodeMetadata, + value = NodeMetadata.get( + node, 'stringArrayCallLiteralNode' - >(node, 'stringArrayCallLiteralNode'); + ); }); it('should get metadata value of the node', () => { @@ -53,8 +52,7 @@ describe('NodeMetadata', () => { describe('isEvalHostNode', () => { const expectedValue: boolean = true; - let node: ESTree.FunctionExpression, - value: boolean | undefined; + let node: ESTree.FunctionExpression, value: boolean | undefined; before(() => { node = NodeFactory.functionExpressionNode([], NodeFactory.blockStatementNode([])); @@ -71,8 +69,7 @@ describe('NodeMetadata', () => { describe('isForceTransformNode', () => { const expectedValue: boolean = true; - let node: ESTree.Identifier, - value: boolean | undefined; + let node: ESTree.Identifier, value: boolean | undefined; before(() => { node = NodeFactory.identifierNode('foo'); @@ -89,8 +86,7 @@ describe('NodeMetadata', () => { describe('isIgnoredNode', () => { const expectedValue: boolean = true; - let node: ESTree.Identifier, - value: boolean | undefined; + let node: ESTree.Identifier, value: boolean | undefined; before(() => { node = NodeFactory.identifierNode('foo'); @@ -107,8 +103,7 @@ describe('NodeMetadata', () => { describe('propertyKeyToRenameNode', () => { const expectedValue: boolean = true; - let node: ESTree.Identifier, - value: boolean | undefined; + let node: ESTree.Identifier, value: boolean | undefined; before(() => { node = NodeFactory.identifierNode('foo'); @@ -125,8 +120,7 @@ describe('NodeMetadata', () => { describe('isStringArrayCallLiteralNode', () => { const expectedValue: boolean = true; - let node: ESTree.Literal, - value: boolean | undefined; + let node: ESTree.Literal, value: boolean | undefined; before(() => { node = NodeFactory.literalNode('foo'); diff --git a/test/unit-tests/node/node-statement-utils/NodeStatementUtils.spec.ts b/test/unit-tests/node/node-statement-utils/NodeStatementUtils.spec.ts index 0cd09b00..5382ffe6 100644 --- a/test/unit-tests/node/node-statement-utils/NodeStatementUtils.spec.ts +++ b/test/unit-tests/node/node-statement-utils/NodeStatementUtils.spec.ts @@ -34,9 +34,7 @@ describe('NodeStatementUtils', () => { ifStatementBlockStatementNode2 ); - ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ - ifStatementNode2 - ]); + ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ifStatementNode2]); ifStatementNode1 = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), @@ -48,11 +46,13 @@ describe('NodeStatementUtils', () => { ifStatementNode1 ]); - functionDeclarationNode = NodeFactory.functionDeclarationNode('test', [], functionDeclarationBlockStatementNode); + functionDeclarationNode = NodeFactory.functionDeclarationNode( + 'test', + [], + functionDeclarationBlockStatementNode + ); - programNode = NodeFactory.programNode([ - functionDeclarationNode - ]); + programNode = NodeFactory.programNode([functionDeclarationNode]); programNode.parentNode = programNode; functionDeclarationNode.parentNode = programNode; @@ -74,31 +74,52 @@ describe('NodeStatementUtils', () => { }); it('should return parent node with statements node for `functionDeclaration blockStatement` node child node', () => { - assert.deepEqual(NodeStatementUtils.getParentNodeWithStatements(functionDeclarationBlockStatementNode), programNode); + assert.deepEqual( + NodeStatementUtils.getParentNodeWithStatements(functionDeclarationBlockStatementNode), + programNode + ); }); it('should return parent node with statements node for `expressionStatement` node #1 child node', () => { - assert.deepEqual(NodeStatementUtils.getParentNodeWithStatements(expressionStatementNode1), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodeWithStatements(expressionStatementNode1), + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `ifStatement` node child node', () => { - assert.deepEqual(NodeStatementUtils.getParentNodeWithStatements(ifStatementNode1), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodeWithStatements(ifStatementNode1), + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `ifStatement blockStatement` node #1 child node', () => { - assert.deepEqual(NodeStatementUtils.getParentNodeWithStatements(ifStatementBlockStatementNode1), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodeWithStatements(ifStatementBlockStatementNode1), + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `ifStatement blockStatement` node #2 child node', () => { - assert.deepEqual(NodeStatementUtils.getParentNodeWithStatements(ifStatementBlockStatementNode2), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodeWithStatements(ifStatementBlockStatementNode2), + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `expressionStatement` node #3 child node', () => { - assert.deepEqual(NodeStatementUtils.getParentNodeWithStatements(expressionStatementNode3), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodeWithStatements(expressionStatementNode3), + functionDeclarationBlockStatementNode + ); }); it('should throw a `ReferenceError` if node has no `parentNode` property', () => { - assert.throws(() => NodeStatementUtils.getParentNodeWithStatements(expressionStatementNode2), ReferenceError); + assert.throws( + () => NodeStatementUtils.getParentNodeWithStatements(expressionStatementNode2), + ReferenceError + ); }); }); @@ -129,9 +150,7 @@ describe('NodeStatementUtils', () => { ifStatementBlockStatementNode2 ); - ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ - ifStatementNode2 - ]); + ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ifStatementNode2]); ifStatementNode1 = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), @@ -143,11 +162,13 @@ describe('NodeStatementUtils', () => { ifStatementNode1 ]); - functionDeclarationNode = NodeFactory.functionDeclarationNode('test', [], functionDeclarationBlockStatementNode); + functionDeclarationNode = NodeFactory.functionDeclarationNode( + 'test', + [], + functionDeclarationBlockStatementNode + ); - programNode = NodeFactory.programNode([ - functionDeclarationNode - ]); + programNode = NodeFactory.programNode([functionDeclarationNode]); programNode.parentNode = programNode; functionDeclarationNode.parentNode = programNode; @@ -169,11 +190,17 @@ describe('NodeStatementUtils', () => { }); it('should return parent node with statements node for `functionDeclaration blockStatement` node child node #1', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(functionDeclarationBlockStatementNode)[0], programNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(functionDeclarationBlockStatementNode)[0], + programNode + ); }); it('should return parent node with statements node for `expressionStatement` node #1 child node #1', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(expressionStatementNode1)[0], functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(expressionStatementNode1)[0], + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `expressionStatement` node #1 child node #2', () => { @@ -181,7 +208,10 @@ describe('NodeStatementUtils', () => { }); it('should return parent node with statements node for `ifStatement` node child node #1', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(ifStatementNode1)[0], functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(ifStatementNode1)[0], + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `ifStatement` node child node #2', () => { @@ -189,23 +219,38 @@ describe('NodeStatementUtils', () => { }); it('should return parent node with statements node for `ifStatement blockStatement` node #1 child node #1', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode1)[0], functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode1)[0], + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `ifStatement blockStatement` node #1 child node #2', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode1)[1], programNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode1)[1], + programNode + ); }); it('should return parent node with statements node for `ifStatement blockStatement` node #2 child node #1', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode2)[0], functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode2)[0], + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `ifStatement blockStatement` node #1 child node #2', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode2)[1], programNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(ifStatementBlockStatementNode2)[1], + programNode + ); }); it('should return parent node with statements node for `expressionStatement` node #3 child node #1', () => { - assert.deepEqual(NodeStatementUtils.getParentNodesWithStatements(expressionStatementNode3)[0], functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getParentNodesWithStatements(expressionStatementNode3)[0], + functionDeclarationBlockStatementNode + ); }); it('should return parent node with statements node for `expressionStatement` node #3 child node #2', () => { @@ -213,26 +258,21 @@ describe('NodeStatementUtils', () => { }); it('should throw a `ReferenceError` if node has no `parentNode` property', () => { - assert.throws(() => NodeStatementUtils.getParentNodesWithStatements(expressionStatementNode2)[0], ReferenceError); + assert.throws( + () => NodeStatementUtils.getParentNodesWithStatements(expressionStatementNode2)[0], + ReferenceError + ); }); }); describe('getNextSiblingStatement', () => { describe('Variant #1: block statement node as scope node', () => { - let statementNode1: ESTree.Statement, - statementNode2: ESTree.Statement, - statementNode3: ESTree.Statement; + let statementNode1: ESTree.Statement, statementNode2: ESTree.Statement, statementNode3: ESTree.Statement; before(() => { - statementNode1 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('a') - ); - statementNode2 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('b') - ); - statementNode3 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('c') - ); + statementNode1 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('a')); + statementNode2 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('b')); + statementNode3 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('c')); const blockStatementNode: ESTree.BlockStatement = NodeFactory.blockStatementNode([ statementNode1, @@ -259,29 +299,18 @@ describe('NodeStatementUtils', () => { }); describe('Variant #2: switch case node as scope node', () => { - let statementNode1: ESTree.Statement, - statementNode2: ESTree.Statement, - statementNode3: ESTree.Statement; + let statementNode1: ESTree.Statement, statementNode2: ESTree.Statement, statementNode3: ESTree.Statement; before(() => { - statementNode1 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('a') - ); - statementNode2 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('b') - ); - statementNode3 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('c') - ); + statementNode1 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('a')); + statementNode2 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('b')); + statementNode3 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('c')); - const switchCaseNode: ESTree.SwitchCase = NodeFactory.switchCaseNode( - NodeFactory.literalNode(true), - [ - statementNode1, - statementNode2, - statementNode3 - ] - ); + const switchCaseNode: ESTree.SwitchCase = NodeFactory.switchCaseNode(NodeFactory.literalNode(true), [ + statementNode1, + statementNode2, + statementNode3 + ]); statementNode1.parentNode = switchCaseNode; statementNode2.parentNode = switchCaseNode; @@ -304,20 +333,12 @@ describe('NodeStatementUtils', () => { describe('getPreviousSiblingStatement', () => { describe('Variant #1: block statement node as scope node', () => { - let statementNode1: ESTree.Statement, - statementNode2: ESTree.Statement, - statementNode3: ESTree.Statement; + let statementNode1: ESTree.Statement, statementNode2: ESTree.Statement, statementNode3: ESTree.Statement; before(() => { - statementNode1 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('a') - ); - statementNode2 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('b') - ); - statementNode3 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('c') - ); + statementNode1 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('a')); + statementNode2 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('b')); + statementNode3 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('c')); const blockStatementNode: ESTree.BlockStatement = NodeFactory.blockStatementNode([ statementNode1, @@ -344,29 +365,18 @@ describe('NodeStatementUtils', () => { }); describe('Variant #2: switch case node as scope node', () => { - let statementNode1: ESTree.Statement, - statementNode2: ESTree.Statement, - statementNode3: ESTree.Statement; + let statementNode1: ESTree.Statement, statementNode2: ESTree.Statement, statementNode3: ESTree.Statement; before(() => { - statementNode1 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('a') - ); - statementNode2 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('b') - ); - statementNode3 = NodeFactory.expressionStatementNode( - NodeFactory.identifierNode('c') - ); + statementNode1 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('a')); + statementNode2 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('b')); + statementNode3 = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('c')); - const switchCaseNode: ESTree.SwitchCase = NodeFactory.switchCaseNode( - NodeFactory.literalNode(true), - [ - statementNode1, - statementNode2, - statementNode3 - ] - ); + const switchCaseNode: ESTree.SwitchCase = NodeFactory.switchCaseNode(NodeFactory.literalNode(true), [ + statementNode1, + statementNode2, + statementNode3 + ]); statementNode1.parentNode = switchCaseNode; statementNode2.parentNode = switchCaseNode; @@ -407,40 +417,30 @@ describe('NodeStatementUtils', () => { identifierNode4 = NodeFactory.identifierNode('foo'); identifierNode5 = NodeFactory.identifierNode('bar'); - assignmentExpression = NodeFactory.assignmentExpressionNode( - '=', - identifierNode4, - identifierNode5 - ); + assignmentExpression = NodeFactory.assignmentExpressionNode('=', identifierNode4, identifierNode5); - expressionStatement = NodeFactory.expressionStatementNode( - assignmentExpression - ); + expressionStatement = NodeFactory.expressionStatementNode(assignmentExpression); variableDeclarationNode = NodeFactory.variableDeclarationNode([ NodeFactory.variableDeclaratorNode( identifierNode1, - NodeFactory.binaryExpressionNode( - '+', - identifierNode2, - identifierNode3 - ) + NodeFactory.binaryExpressionNode('+', identifierNode2, identifierNode3) ) ]); - functionDeclarationBlockStatementNode = NodeFactory.blockStatementNode([ - variableDeclarationNode - ]); + functionDeclarationBlockStatementNode = NodeFactory.blockStatementNode([variableDeclarationNode]); - functionDeclarationNode = NodeFactory.functionDeclarationNode('test', [], functionDeclarationBlockStatementNode); + functionDeclarationNode = NodeFactory.functionDeclarationNode( + 'test', + [], + functionDeclarationBlockStatementNode + ); programNode = NodeFactory.programNode([ functionDeclarationNode, NodeFactory.ifStatementNode( NodeFactory.literalNode(true), - NodeFactory.blockStatementNode([ - expressionStatement - ]) + NodeFactory.blockStatementNode([expressionStatement]) ) ]); @@ -454,11 +454,17 @@ describe('NodeStatementUtils', () => { }); it('should return root statement in scope for `functionDeclaration` node #1', () => { - assert.deepEqual(NodeStatementUtils.getRootStatementOfNode(functionDeclarationNode), functionDeclarationNode); + assert.deepEqual( + NodeStatementUtils.getRootStatementOfNode(functionDeclarationNode), + functionDeclarationNode + ); }); it('should return root statement in scope for `functionDeclaration blockStatement` node #1', () => { - assert.deepEqual(NodeStatementUtils.getRootStatementOfNode(functionDeclarationBlockStatementNode), functionDeclarationNode); + assert.deepEqual( + NodeStatementUtils.getRootStatementOfNode(functionDeclarationBlockStatementNode), + functionDeclarationNode + ); }); it('should return root statement in scope for `identifier` node #1', () => { @@ -515,9 +521,7 @@ describe('NodeStatementUtils', () => { ifStatementBlockStatementNode2 = NodeFactory.blockStatementNode(); - ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ - ifStatementNode3 - ]); + ifStatementBlockStatementNode1 = NodeFactory.blockStatementNode([ifStatementNode3]); ifStatementNode2 = NodeFactory.ifStatementNode( NodeFactory.literalNode(true), @@ -529,19 +533,9 @@ describe('NodeStatementUtils', () => { ifStatementBlockStatementNode1 ); - switchCaseNode = NodeFactory.switchCaseNode( - NodeFactory.literalNode(1), - [ - ifStatementNode2 - ] - ); + switchCaseNode = NodeFactory.switchCaseNode(NodeFactory.literalNode(1), [ifStatementNode2]); - switchStatementNode = NodeFactory.switchStatementNode( - NodeFactory.literalNode(1), - [ - switchCaseNode - ] - ); + switchStatementNode = NodeFactory.switchStatementNode(NodeFactory.literalNode(1), [switchCaseNode]); functionDeclarationBlockStatementNode = NodeFactory.blockStatementNode([ expressionStatementNode1, @@ -549,11 +543,13 @@ describe('NodeStatementUtils', () => { switchStatementNode ]); - functionDeclarationNode = NodeFactory.functionDeclarationNode('test', [], functionDeclarationBlockStatementNode); + functionDeclarationNode = NodeFactory.functionDeclarationNode( + 'test', + [], + functionDeclarationBlockStatementNode + ); - programNode = NodeFactory.programNode([ - functionDeclarationNode - ]); + programNode = NodeFactory.programNode([functionDeclarationNode]); programNode.parentNode = programNode; functionDeclarationNode.parentNode = programNode; @@ -583,15 +579,24 @@ describe('NodeStatementUtils', () => { }); it('should return scope node for `expressionStatement` node #1 child node', () => { - assert.deepEqual(NodeStatementUtils.getScopeOfNode(expressionStatementNode1), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getScopeOfNode(expressionStatementNode1), + functionDeclarationBlockStatementNode + ); }); it('should return scope node for `ifStatement` node #1 child node', () => { - assert.deepEqual(NodeStatementUtils.getScopeOfNode(ifStatementNode1), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getScopeOfNode(ifStatementNode1), + functionDeclarationBlockStatementNode + ); }); it('should return scope node for `switchStatement` node child node', () => { - assert.deepEqual(NodeStatementUtils.getScopeOfNode(switchStatementNode), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getScopeOfNode(switchStatementNode), + functionDeclarationBlockStatementNode + ); }); it('should return scope node for `switchCase` node child node', () => { @@ -607,15 +612,24 @@ describe('NodeStatementUtils', () => { }); it('should return scope node for `ifStatement blockStatement` node #1 child node', () => { - assert.deepEqual(NodeStatementUtils.getScopeOfNode(ifStatementBlockStatementNode1), functionDeclarationBlockStatementNode); + assert.deepEqual( + NodeStatementUtils.getScopeOfNode(ifStatementBlockStatementNode1), + functionDeclarationBlockStatementNode + ); }); it('should return scope node for `ifStatement blockStatement` node #3 child node', () => { - assert.deepEqual(NodeStatementUtils.getScopeOfNode(ifStatementBlockStatementNode3), ifStatementBlockStatementNode1); + assert.deepEqual( + NodeStatementUtils.getScopeOfNode(ifStatementBlockStatementNode3), + ifStatementBlockStatementNode1 + ); }); it('should return scope node for `expressionStatement` node #3 child node', () => { - assert.deepEqual(NodeStatementUtils.getScopeOfNode(expressionStatementNode3), ifStatementBlockStatementNode3); + assert.deepEqual( + NodeStatementUtils.getScopeOfNode(expressionStatementNode3), + ifStatementBlockStatementNode3 + ); }); it('should throw a `ReferenceError` if node has no `parentNode` property', () => { diff --git a/test/unit-tests/node/node-utils/NodeUtils.spec.ts b/test/unit-tests/node/node-utils/NodeUtils.spec.ts index 16bdb719..a45fb7c2 100644 --- a/test/unit-tests/node/node-utils/NodeUtils.spec.ts +++ b/test/unit-tests/node/node-utils/NodeUtils.spec.ts @@ -11,8 +11,7 @@ import { NodeUtils } from '../../../../src/node/NodeUtils'; describe('NodeUtils', () => { describe('addXVerbatimPropertyTo', () => { - let literalNode: ESTree.Literal, - expectedLiteralNode: ESTree.Literal; + let literalNode: ESTree.Literal, expectedLiteralNode: ESTree.Literal; before(() => { literalNode = NodeFactory.literalNode('value'); @@ -30,13 +29,16 @@ describe('NodeUtils', () => { describe('clone', () => { describe('Variant #1: simple AST-tree', () => { - let programNode: ESTree.Program, - expectedProgramNode: ESTree.Program; + let programNode: ESTree.Program, expectedProgramNode: ESTree.Program; before(() => { // actual AST tree - const expressionStatementNode1: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('identifier')); - const expressionStatementNode2: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('identifier')); + const expressionStatementNode1: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( + NodeFactory.identifierNode('identifier') + ); + const expressionStatementNode2: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( + NodeFactory.identifierNode('identifier') + ); const ifStatementBlockStatementNode1: ESTree.BlockStatement = NodeFactory.blockStatementNode([ expressionStatementNode1, @@ -49,8 +51,12 @@ describe('NodeUtils', () => { ); // expected AST tree - const expressionStatementNode3: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('identifier')); - const expressionStatementNode4: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode(NodeFactory.identifierNode('identifier')); + const expressionStatementNode3: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( + NodeFactory.identifierNode('identifier') + ); + const expressionStatementNode4: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( + NodeFactory.identifierNode('identifier') + ); const ifStatementBlockStatementNode2: ESTree.BlockStatement = NodeFactory.blockStatementNode([ expressionStatementNode3, @@ -62,16 +68,8 @@ describe('NodeUtils', () => { ifStatementBlockStatementNode2 ); - programNode = NodeUtils.clone( - NodeFactory.programNode([ - ifStatementNode1 - ]) - ); - expectedProgramNode = NodeUtils.parentizeAst( - NodeFactory.programNode([ - ifStatementNode2 - ]) - ); + programNode = NodeUtils.clone(NodeFactory.programNode([ifStatementNode1])); + expectedProgramNode = NodeUtils.parentizeAst(NodeFactory.programNode([ifStatementNode2])); }); it('should clone given AST-tree', () => { @@ -80,8 +78,7 @@ describe('NodeUtils', () => { }); describe('Variant #2: array expression with `null` element', () => { - let programNode: ESTree.Program, - expectedProgramNode: ESTree.Program; + let programNode: ESTree.Program, expectedProgramNode: ESTree.Program; before(() => { // actual AST tree @@ -91,9 +88,8 @@ describe('NodeUtils', () => { null, NodeFactory.literalNode(4) ]); - const expressionStatementNode: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( - arrayExpressionNode - ); + const expressionStatementNode: ESTree.ExpressionStatement = + NodeFactory.expressionStatementNode(arrayExpressionNode); // expected AST tree const expectedArrayExpressionNode: ESTree.ArrayExpression = NodeFactory.arrayExpressionNode([ @@ -102,19 +98,12 @@ describe('NodeUtils', () => { null, NodeFactory.literalNode(4) ]); - const expectedExpressionStatementNode: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode( - expectedArrayExpressionNode - ); + const expectedExpressionStatementNode: ESTree.ExpressionStatement = + NodeFactory.expressionStatementNode(expectedArrayExpressionNode); - programNode = NodeUtils.clone( - NodeFactory.programNode([ - expressionStatementNode - ]) - ); + programNode = NodeUtils.clone(NodeFactory.programNode([expressionStatementNode])); expectedProgramNode = NodeUtils.parentizeAst( - NodeFactory.programNode([ - expectedExpressionStatementNode - ]) + NodeFactory.programNode([expectedExpressionStatementNode]) ); }); @@ -125,8 +114,7 @@ describe('NodeUtils', () => { }); describe('convertCodeToStructure', () => { - let structure: TStatement[], - expectedStructure: TStatement[]; + let structure: TStatement[], expectedStructure: TStatement[]; before(() => { const code: string = ` @@ -135,10 +123,13 @@ describe('NodeUtils', () => { const identifierNode: ESTree.Identifier = NodeFactory.identifierNode('abc'); const literalNode: ESTree.Literal = NodeFactory.literalNode('cde'); - const variableDeclaratorNode: ESTree.VariableDeclarator = NodeFactory - .variableDeclaratorNode(identifierNode, literalNode); - const variableDeclarationNode: ESTree.VariableDeclaration = NodeFactory - .variableDeclarationNode([variableDeclaratorNode]); + const variableDeclaratorNode: ESTree.VariableDeclarator = NodeFactory.variableDeclaratorNode( + identifierNode, + literalNode + ); + const variableDeclarationNode: ESTree.VariableDeclaration = NodeFactory.variableDeclarationNode([ + variableDeclaratorNode + ]); const programNode: ESTree.Program = NodeFactory.programNode([variableDeclarationNode]); programNode.parentNode = programNode; @@ -147,9 +138,7 @@ describe('NodeUtils', () => { identifierNode.parentNode = variableDeclaratorNode; literalNode.parentNode = variableDeclaratorNode; - structure = removeRangesFromStructure( - NodeUtils.convertCodeToStructure(code) - ); + structure = removeRangesFromStructure(NodeUtils.convertCodeToStructure(code)); expectedStructure = [variableDeclarationNode]; }); @@ -159,8 +148,7 @@ describe('NodeUtils', () => { }); describe('convertStructureToCode', () => { - let structure: ESTree.Node[], - expectedCode: string; + let structure: ESTree.Node[], expectedCode: string; before(() => { structure = [ @@ -173,7 +161,7 @@ describe('NodeUtils', () => { ]) ]) ]; - expectedCode = 'var abc = \'cde\';'; + expectedCode = "var abc = 'cde';"; }); it('should convert `ESTree.Node[]` structure to source code', () => { @@ -182,17 +170,18 @@ describe('NodeUtils', () => { }); describe('getUnaryExpressionArgumentNode', () => { - let expectedNode: ESTree.Literal, - unaryExpressionArgumentNode: ESTree.Node; + let expectedNode: ESTree.Literal, unaryExpressionArgumentNode: ESTree.Node; before(() => { const literalNode: ESTree.Literal = NodeFactory.literalNode('test'); const unaryExpressionNode2: ESTree.UnaryExpression = NodeFactory.unaryExpressionNode('!', literalNode); - const unaryExpressionNode1: ESTree.UnaryExpression = NodeFactory.unaryExpressionNode('!', unaryExpressionNode2); - const expressionStatementNode: ESTree.ExpressionStatement = NodeFactory.expressionStatementNode(unaryExpressionNode1); - const programNode: ESTree.Program = NodeFactory.programNode([ - expressionStatementNode - ]); + const unaryExpressionNode1: ESTree.UnaryExpression = NodeFactory.unaryExpressionNode( + '!', + unaryExpressionNode2 + ); + const expressionStatementNode: ESTree.ExpressionStatement = + NodeFactory.expressionStatementNode(unaryExpressionNode1); + const programNode: ESTree.Program = NodeFactory.programNode([expressionStatementNode]); programNode.parentNode = programNode; expressionStatementNode.parentNode = programNode; @@ -225,17 +214,12 @@ describe('NodeUtils', () => { expressionStatementNode2 ]); - ifStatementNode = NodeFactory.ifStatementNode( - NodeFactory.literalNode(true), - ifStatementBlockStatementNode - ); + ifStatementNode = NodeFactory.ifStatementNode(NodeFactory.literalNode(true), ifStatementBlockStatementNode); }); describe('Variant #1: parentize AST-tree with `ProgramNode` as root node', () => { beforeEach(() => { - programNode = NodeFactory.programNode([ - ifStatementNode - ]); + programNode = NodeFactory.programNode([ifStatementNode]); programNode = NodeUtils.parentizeAst(programNode); }); @@ -285,9 +269,7 @@ describe('NodeUtils', () => { describe('Variant #3: parentize AST-tree and keep root node parent node', () => { beforeEach(() => { - programNode = NodeFactory.programNode([ - ifStatementNode - ]); + programNode = NodeFactory.programNode([ifStatementNode]); ifStatementNode.parentNode = programNode; ifStatementNode = NodeUtils.parentizeAst(ifStatementNode); diff --git a/test/unit-tests/node/numerical-expression-data-to-node-converter/NumericalExpressionDataToNodeConverter.spec.ts b/test/unit-tests/node/numerical-expression-data-to-node-converter/NumericalExpressionDataToNodeConverter.spec.ts index a8a849a5..6b9f6916 100644 --- a/test/unit-tests/node/numerical-expression-data-to-node-converter/NumericalExpressionDataToNodeConverter.spec.ts +++ b/test/unit-tests/node/numerical-expression-data-to-node-converter/NumericalExpressionDataToNodeConverter.spec.ts @@ -12,9 +12,7 @@ import { NumericalExpressionDataToNodeConverter } from '../../../../src/node/Num describe('NumericalExpressionDataToNodeConverter', () => { describe('convertIntegerNumberData', () => { describe('Variant #1: base', () => { - const numberNumericalExpressionData: TNumberNumericalExpressionData = [ - 1, [-2, 3], 4 - ]; + const numberNumericalExpressionData: TNumberNumericalExpressionData = [1, [-2, 3], 4]; const expectedExpressionNode: ESTree.Expression = NodeFactory.binaryExpressionNode( '+', @@ -23,12 +21,9 @@ describe('NumericalExpressionDataToNodeConverter', () => { NodeFactory.literalNode(1), NodeFactory.binaryExpressionNode( '*', - NodeFactory.unaryExpressionNode( - '-', - NodeFactory.literalNode(2), - ), + NodeFactory.unaryExpressionNode('-', NodeFactory.literalNode(2)), NodeFactory.literalNode(3) - ), + ) ), NodeFactory.literalNode(4) ); @@ -43,10 +38,7 @@ describe('NumericalExpressionDataToNodeConverter', () => { return isPositiveNumber ? numberLiteralNode - : NodeFactory.unaryExpressionNode( - '-', - numberLiteralNode - ); + : NodeFactory.unaryExpressionNode('-', numberLiteralNode); } ); }); @@ -59,9 +51,7 @@ describe('NumericalExpressionDataToNodeConverter', () => { describe('convertFloatNumberData', () => { describe('Variant #1: base', () => { - const integerNumberNumericalExpressionData: TNumberNumericalExpressionData = [ - 1, [-2, 3], 4 - ]; + const integerNumberNumericalExpressionData: TNumberNumericalExpressionData = [1, [-2, 3], 4]; const decimalPart: number = 0.000000001; const expectedExpressionNode: ESTree.Expression = NodeFactory.binaryExpressionNode( @@ -73,12 +63,9 @@ describe('NumericalExpressionDataToNodeConverter', () => { NodeFactory.literalNode(1), NodeFactory.binaryExpressionNode( '*', - NodeFactory.unaryExpressionNode( - '-', - NodeFactory.literalNode(2), - ), + NodeFactory.unaryExpressionNode('-', NodeFactory.literalNode(2)), NodeFactory.literalNode(3) - ), + ) ), NodeFactory.literalNode(4) ), @@ -96,10 +83,7 @@ describe('NumericalExpressionDataToNodeConverter', () => { return isPositiveNumber ? numberLiteralNode - : NodeFactory.unaryExpressionNode( - '-', - numberLiteralNode - ); + : NodeFactory.unaryExpressionNode('-', numberLiteralNode); } ); }); diff --git a/test/unit-tests/options/ValidationErrorsFormatter.spec.ts b/test/unit-tests/options/ValidationErrorsFormatter.spec.ts index a7845c5c..8ecca25c 100644 --- a/test/unit-tests/options/ValidationErrorsFormatter.spec.ts +++ b/test/unit-tests/options/ValidationErrorsFormatter.spec.ts @@ -9,15 +9,17 @@ describe('ValidationErrorsFormatter', () => { describe('Variant #1: one constraint group with one constraint', () => { const constraintGroupRegExp: RegExp = /`foo` *errors:/; const constraintRegExp: RegExp = /(?: *-)+ *constraint *text/; - const validationErrors: ValidationError[] = [{ - target: {}, - property: 'foo', - value: null, - constraints: { - 'constraint1': '- constraint text' - }, - children: [] - }]; + const validationErrors: ValidationError[] = [ + { + target: {}, + property: 'foo', + value: null, + constraints: { + constraint1: '- constraint text' + }, + children: [] + } + ]; let validationError: string; @@ -38,16 +40,18 @@ describe('ValidationErrorsFormatter', () => { const constraintGroupRegExp: RegExp = /`foo` *errors:/; const constraintRegExp1: RegExp = /(?: *-)+ constraint *text *#1/; const constraintRegExp2: RegExp = /(?: *-)+ constraint *text *#2/; - const validationErrors: ValidationError[] = [{ - target: {}, - property: 'foo', - value: null, - constraints: { - 'constraint1': '- constraint text #1', - 'constraint2': '- constraint text #2' - }, - children: [] - }]; + const validationErrors: ValidationError[] = [ + { + target: {}, + property: 'foo', + value: null, + constraints: { + constraint1: '- constraint text #1', + constraint2: '- constraint text #2' + }, + children: [] + } + ]; let validationError: string; @@ -70,12 +74,14 @@ describe('ValidationErrorsFormatter', () => { describe('Variant #3: one constraint group without constraints', () => { const constraintGroupRegExp: RegExp = /`foo` *error/; - const validationErrors: ValidationError[] = [{ - target: {}, - property: 'foo', - value: null, - children: [] - }]; + const validationErrors: ValidationError[] = [ + { + target: {}, + property: 'foo', + value: null, + children: [] + } + ]; let validationError: string; @@ -89,30 +95,34 @@ describe('ValidationErrorsFormatter', () => { }); describe('Variant #4: two constraint groups', () => { - const regExpMatch: string = `` + + const regExpMatch: string = + `` + `\`foo\` *errors:\\n` + - `(?: *-)+ *constraint *group *#1 *text\\n+` + + `(?: *-)+ *constraint *group *#1 *text\\n+` + `\`bar\` *errors:\\n` + - `(?: *-)+ *constraint *group *#2 *text\\n+` + - ``; + `(?: *-)+ *constraint *group *#2 *text\\n+` + + ``; const regExp: RegExp = new RegExp(regExpMatch); - const validationErrors: ValidationError[] = [{ - target: {}, - property: 'foo', - value: null, - constraints: { - 'constraint': '- constraint group #1 text' + const validationErrors: ValidationError[] = [ + { + target: {}, + property: 'foo', + value: null, + constraints: { + constraint: '- constraint group #1 text' + }, + children: [] }, - children: [] - }, { - target: {}, - property: 'bar', - value: null, - constraints: { - 'constraint': '- constraint group #2 text' - }, - children: [] - }]; + { + target: {}, + property: 'bar', + value: null, + constraints: { + constraint: '- constraint group #2 text' + }, + children: [] + } + ]; let validationError: string; diff --git a/test/unit-tests/source-code/ObfuscationResult.spec.ts b/test/unit-tests/source-code/ObfuscationResult.spec.ts index da93d6ae..f25411cf 100644 --- a/test/unit-tests/source-code/ObfuscationResult.spec.ts +++ b/test/unit-tests/source-code/ObfuscationResult.spec.ts @@ -22,23 +22,17 @@ import { InversifyContainerFacade } from '../../../src/container/InversifyContai * @param {TInputOptions} options * @returns {IObfuscationResult} */ -function getObfuscationResult ( - rawObfuscatedCode: string, - options: TInputOptions -): IObfuscationResult { +function getObfuscationResult(rawObfuscatedCode: string, options: TInputOptions): IObfuscationResult { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); - inversifyContainerFacade.load( - '', - '', - { - ...DEFAULT_PRESET, - ...options - } - ); + inversifyContainerFacade.load('', '', { + ...DEFAULT_PRESET, + ...options + }); - const obfuscationResult: IObfuscationResult = inversifyContainerFacade - .get(ServiceIdentifiers.IObfuscationResult); + const obfuscationResult: IObfuscationResult = inversifyContainerFacade.get( + ServiceIdentifiers.IObfuscationResult + ); obfuscationResult.initialize(rawObfuscatedCode, ''); @@ -52,7 +46,7 @@ function getObfuscationResult ( * @param sourceMapFileName * @param sourceMapMode */ -function getSourceMapObfuscationResult ( +function getSourceMapObfuscationResult( rawObfuscatedCode: string, sourceMap: string, sourceMapBaseUrl: string, @@ -61,20 +55,17 @@ function getSourceMapObfuscationResult ( ): IObfuscationResult { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); - inversifyContainerFacade.load( - '', - '', - { - ...DEFAULT_PRESET, - sourceMap: true, - sourceMapBaseUrl, - sourceMapFileName, - sourceMapMode - } - ); + inversifyContainerFacade.load('', '', { + ...DEFAULT_PRESET, + sourceMap: true, + sourceMapBaseUrl, + sourceMapFileName, + sourceMapMode + }); - const obfuscationResult: IObfuscationResult = inversifyContainerFacade - .get(ServiceIdentifiers.IObfuscationResult); + const obfuscationResult: IObfuscationResult = inversifyContainerFacade.get( + ServiceIdentifiers.IObfuscationResult + ); obfuscationResult.initialize(rawObfuscatedCode, sourceMap); @@ -106,7 +97,7 @@ describe('ObfuscatedCode', () => { describe('getObfuscatedCode', () => { let obfuscatedCode: string; - describe('source map doest\'t exist', () => { + describe("source map doest't exist", () => { before(() => { obfuscatedCode = getSourceMapObfuscationResult( expectedObfuscatedCode, @@ -184,12 +175,9 @@ describe('ObfuscatedCode', () => { let options: IOptions; before(() => { - options = getObfuscationResult( - expectedObfuscatedCode, - { - seed - } - ).getOptions(); + options = getObfuscationResult(expectedObfuscatedCode, { + seed + }).getOptions(); }); it('should return options object', () => { diff --git a/test/unit-tests/storages/ArrayStorage.spec.ts b/test/unit-tests/storages/ArrayStorage.spec.ts index e22107d9..693b5645 100644 --- a/test/unit-tests/storages/ArrayStorage.spec.ts +++ b/test/unit-tests/storages/ArrayStorage.spec.ts @@ -9,12 +9,11 @@ import { IInversifyContainerFacade } from '../../../src/interfaces/container/IIn import { IOptions } from '../../../src/interfaces/options/IOptions'; import { IRandomGenerator } from '../../../src/interfaces/utils/IRandomGenerator'; - import { ArrayStorage } from '../../../src/storages/ArrayStorage'; import { InversifyContainerFacade } from '../../../src/container/InversifyContainerFacade'; -class ConcreteStorage extends ArrayStorage { - constructor () { +class ConcreteStorage extends ArrayStorage { + constructor() { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); @@ -29,8 +28,8 @@ class ConcreteStorage extends ArrayStorage { /** * @returns {IArrayStorage} */ -const getStorageInstance = (): IArrayStorage => { - const storage: IArrayStorage = new ConcreteStorage (); +const getStorageInstance = (): IArrayStorage => { + const storage: IArrayStorage = new ConcreteStorage(); storage.initialize(); @@ -41,7 +40,7 @@ describe('ArrayStorage', () => { const storageKey: number = 0; const storageValue: string = 'foo'; - let storage: IArrayStorage ; + let storage: IArrayStorage; describe('initialize', () => { const expectedError: ErrorConstructor = Error; @@ -53,7 +52,7 @@ describe('ArrayStorage', () => { testFunc = () => storage.set(storageKey, storageValue); }); - it('should throws an error when storage isn\'t initialized', () => { + it("should throws an error when storage isn't initialized", () => { assert.throws(testFunc, expectedError); }); }); @@ -109,7 +108,7 @@ describe('ArrayStorage', () => { }); }); - describe('Variant #2: value isn\'t exist', () => { + describe("Variant #2: value isn't exist", () => { const expectedValue: undefined = undefined; let value: string; @@ -144,7 +143,7 @@ describe('ArrayStorage', () => { }); }); - describe('Variant #2: value isn\'t exist', () => { + describe("Variant #2: value isn't exist", () => { const expectedError: ErrorConstructor = Error; let testFunc: () => void; @@ -221,7 +220,7 @@ describe('ArrayStorage', () => { storage = getStorageInstance(); storage.set(storageKey, object); - key = storage.getKeyOf({...object}); + key = storage.getKeyOf({ ...object }); }); it('should return `null` if objects in `set` and `get` are two different objects', () => { @@ -247,10 +246,7 @@ describe('ArrayStorage', () => { describe('delete', () => { describe('Variant #1: value exist', () => { - const expectedUpdatedStorage: string[] = [ - 'foo', - 'baz' - ]; + const expectedUpdatedStorage: string[] = ['foo', 'baz']; const expectedUpdatedStorageLength: number = 2; const expectedDeletedValue: string = 'bar'; @@ -282,12 +278,8 @@ describe('ArrayStorage', () => { }); }); - describe('Variant #2: value isn\'t exist', () => { - const expectedUpdatedStorage: string[] = [ - 'foo', - 'bar', - 'baz' - ]; + describe("Variant #2: value isn't exist", () => { + const expectedUpdatedStorage: string[] = ['foo', 'bar', 'baz']; const expectedUpdatedStorageLength: number = 3; const expectedDeletedValue: undefined = undefined; @@ -333,7 +325,7 @@ describe('ArrayStorage', () => { storage = getStorageInstance(); storage.set(storageKey, storageValue); - const secondStorage: IArrayStorage = getStorageInstance(); + const secondStorage: IArrayStorage = getStorageInstance(); secondStorage.set(secondStorageKey, secondStorageValue); storage.mergeWith(secondStorage, false); @@ -360,7 +352,7 @@ describe('ArrayStorage', () => { storage = getStorageInstance(); storage.set(storageKey, storageValue); - const secondStorage: IArrayStorage = getStorageInstance(); + const secondStorage: IArrayStorage = getStorageInstance(); expectedStorageId = secondStorage.getStorageId(); secondStorage.set(secondStorageKey, secondStorageValue); diff --git a/test/unit-tests/storages/MapStorage.spec.ts b/test/unit-tests/storages/MapStorage.spec.ts index 96e2a79c..94a8c938 100644 --- a/test/unit-tests/storages/MapStorage.spec.ts +++ b/test/unit-tests/storages/MapStorage.spec.ts @@ -14,8 +14,8 @@ import { IRandomGenerator } from '../../../src/interfaces/utils/IRandomGenerator import { InversifyContainerFacade } from '../../../src/container/InversifyContainerFacade'; import { MapStorage } from '../../../src/storages/MapStorage'; -class ConcreteStorage extends MapStorage { - constructor () { +class ConcreteStorage extends MapStorage { + constructor() { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); @@ -30,8 +30,8 @@ class ConcreteStorage extends MapStorage { /** * @returns {IMapStorage} */ -const getStorageInstance = (): IMapStorage => { - const storage: IMapStorage = new ConcreteStorage (); +const getStorageInstance = (): IMapStorage => { + const storage: IMapStorage = new ConcreteStorage(); storage.initialize(); @@ -42,7 +42,7 @@ describe('MapStorage', () => { const storageKey: string = 'foo'; const storageValue: string = 'bar'; - let storage: IMapStorage ; + let storage: IMapStorage; describe('initialize', () => { const expectedError: ErrorConstructor = Error; @@ -54,7 +54,7 @@ describe('MapStorage', () => { testFunc = () => storage.set(storageKey, storageValue); }); - it('should throws an error when storage isn\'t initialized', () => { + it("should throws an error when storage isn't initialized", () => { assert.throws(testFunc, expectedError); }); }); @@ -62,7 +62,7 @@ describe('MapStorage', () => { describe('getStorage', () => { const expectedInstanceOf: MapConstructor = Map; - let mapStorage: Map ; + let mapStorage: Map; before(() => { storage = getStorageInstance(); @@ -93,7 +93,7 @@ describe('MapStorage', () => { }); }); - describe('Variant #2: value isn\'t exist', () => { + describe("Variant #2: value isn't exist", () => { const expectedValue: undefined = undefined; let value: string; @@ -128,7 +128,7 @@ describe('MapStorage', () => { }); }); - describe('Variant #2: value isn\'t exist', () => { + describe("Variant #2: value isn't exist", () => { const expectedError: ErrorConstructor = Error; let testFunc: () => void; @@ -205,7 +205,7 @@ describe('MapStorage', () => { storage = getStorageInstance(); storage.set(storageKey, object); - key = storage.getKeyOf({...object}); + key = storage.getKeyOf({ ...object }); }); it('should return `null` if objects in `set` and `get` are two different objects', () => { @@ -251,7 +251,7 @@ describe('MapStorage', () => { }); }); - describe('Variant #2: item isn\'t presenting in storage', () => { + describe("Variant #2: item isn't presenting in storage", () => { const expectedItemExistence: boolean = false; let itemExistence: boolean; @@ -262,7 +262,7 @@ describe('MapStorage', () => { itemExistence = storage.has(storageKey); }); - it('should return `false` if item isn\'t presenting in storage', () => { + it("should return `false` if item isn't presenting in storage", () => { assert.equal(itemExistence, expectedItemExistence); }); }); @@ -298,7 +298,7 @@ describe('MapStorage', () => { storage = getStorageInstance(); storage.set(storageKey, storageValue); - const secondStorage: IMapStorage = getStorageInstance(); + const secondStorage: IMapStorage = getStorageInstance(); secondStorage.set(secondStorageKey, secondStorageValue); storage.mergeWith(secondStorage, false); diff --git a/test/unit-tests/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.spec.ts b/test/unit-tests/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.spec.ts index 2177b78d..7eedcedd 100644 --- a/test/unit-tests/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.spec.ts +++ b/test/unit-tests/storages/identifier-names-cache/GlobalIdentifierNamesCacheStorage.spec.ts @@ -23,11 +23,11 @@ const getStorageInstance = (options: Partial = DEFAULT_PRESET): IGl const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - const storage: IGlobalIdentifierNamesCacheStorage = new GlobalIdentifierNamesCacheStorage ( + const storage: IGlobalIdentifierNamesCacheStorage = new GlobalIdentifierNamesCacheStorage( inversifyContainerFacade.get(ServiceIdentifiers.IRandomGenerator), { ...DEFAULT_PRESET, - ...options as IOptions + ...(options as IOptions) } ); diff --git a/test/unit-tests/storages/identifier-names-cache/PropertyIdentifierNamesCacheStorage.spec.ts b/test/unit-tests/storages/identifier-names-cache/PropertyIdentifierNamesCacheStorage.spec.ts index 1e24553c..9b8e0d48 100644 --- a/test/unit-tests/storages/identifier-names-cache/PropertyIdentifierNamesCacheStorage.spec.ts +++ b/test/unit-tests/storages/identifier-names-cache/PropertyIdentifierNamesCacheStorage.spec.ts @@ -27,7 +27,7 @@ const getStorageInstance = (options: Partial = DEFAULT_PRESET): IPr inversifyContainerFacade.get(ServiceIdentifiers.IRandomGenerator), { ...DEFAULT_PRESET, - ...options as IOptions + ...(options as IOptions) } ); diff --git a/test/unit-tests/storages/string-array-transformers/literal-nodes-cache/LiteralNodesCacheStorage.spec.ts b/test/unit-tests/storages/string-array-transformers/literal-nodes-cache/LiteralNodesCacheStorage.spec.ts index 42dc9188..ef8d2b8f 100644 --- a/test/unit-tests/storages/string-array-transformers/literal-nodes-cache/LiteralNodesCacheStorage.spec.ts +++ b/test/unit-tests/storages/string-array-transformers/literal-nodes-cache/LiteralNodesCacheStorage.spec.ts @@ -28,7 +28,9 @@ const getStorageInstance = (options: TInputOptions = {}): ILiteralNodesCacheStor ...options }); - const storage: ILiteralNodesCacheStorage = inversifyContainerFacade.get(ServiceIdentifiers.ILiteralNodesCacheStorage); + const storage: ILiteralNodesCacheStorage = inversifyContainerFacade.get( + ServiceIdentifiers.ILiteralNodesCacheStorage + ); storage.initialize(); @@ -39,21 +41,18 @@ describe('LiteralNodesCacheStorage', () => { describe('buildKey', () => { const expectedCacheKey: string = 'foo-true'; - let cacheKey: string; + let cacheKey: string; before(() => { const literalNodesCacheStorage: ILiteralNodesCacheStorage = getStorageInstance(); - cacheKey = literalNodesCacheStorage.buildKey( - 'foo', - { - index: 1, - value: '_0x123abc', - encoding: StringArrayEncoding.Rc4, - encodedValue: 'encoded_value', - decodeKey: 'key' - } - ); + cacheKey = literalNodesCacheStorage.buildKey('foo', { + index: 1, + value: '_0x123abc', + encoding: StringArrayEncoding.Rc4, + encodedValue: 'encoded_value', + decodeKey: 'key' + }); }); it('should build a key for the storage', () => { @@ -62,7 +61,7 @@ describe('LiteralNodesCacheStorage', () => { }); describe('shouldUseCachedValue', () => { - const literalNode: ESTree.Literal = NodeFactory.literalNode('foo'); + const literalNode: ESTree.Literal = NodeFactory.literalNode('foo'); const key: string = 'key'; describe('Encoding is not `rc4` and `stringArrayWrappersCount` option is disabled', () => { @@ -77,16 +76,13 @@ describe('LiteralNodesCacheStorage', () => { literalNodesCacheStorage.set(key, literalNode); - result = literalNodesCacheStorage.shouldUseCachedValue( - key, - { - index: 1, - value: '_0x123abc', - encoding: StringArrayEncoding.Base64, - encodedValue: 'encoded_value', - decodeKey: 'key' - }, - ); + result = literalNodesCacheStorage.shouldUseCachedValue(key, { + index: 1, + value: '_0x123abc', + encoding: StringArrayEncoding.Base64, + encodedValue: 'encoded_value', + decodeKey: 'key' + }); }); it('should check if can use cached value', () => { @@ -95,7 +91,7 @@ describe('LiteralNodesCacheStorage', () => { }); describe('Encoding is `rc4` and `stringArrayWrappersCount` option is disabled', () => { - const expectedResult: boolean = false + const expectedResult: boolean = false; let result: boolean; @@ -106,16 +102,13 @@ describe('LiteralNodesCacheStorage', () => { literalNodesCacheStorage.set(key, literalNode); - result = literalNodesCacheStorage.shouldUseCachedValue( - key, - { - index: 1, - value: '_0x123abc', - encoding: StringArrayEncoding.Rc4, - encodedValue: 'encoded_value', - decodeKey: 'key' - }, - ); + result = literalNodesCacheStorage.shouldUseCachedValue(key, { + index: 1, + value: '_0x123abc', + encoding: StringArrayEncoding.Rc4, + encodedValue: 'encoded_value', + decodeKey: 'key' + }); }); it('should check if can use cached value', () => { @@ -137,16 +130,13 @@ describe('LiteralNodesCacheStorage', () => { literalNodesCacheStorage.set(key, literalNode); - result = literalNodesCacheStorage.shouldUseCachedValue( - key, - { - index: 1, - value: '_0x123abc', - encoding: StringArrayEncoding.Base64, - encodedValue: 'encoded_value', - decodeKey: 'key' - }, - ); + result = literalNodesCacheStorage.shouldUseCachedValue(key, { + index: 1, + value: '_0x123abc', + encoding: StringArrayEncoding.Base64, + encodedValue: 'encoded_value', + decodeKey: 'key' + }); }); it('should check if can use cached value', () => { diff --git a/test/unit-tests/storages/string-array-transformers/string-array/StringArrayStorage.spec.ts b/test/unit-tests/storages/string-array-transformers/string-array/StringArrayStorage.spec.ts index 9877d296..76a0b1a0 100644 --- a/test/unit-tests/storages/string-array-transformers/string-array/StringArrayStorage.spec.ts +++ b/test/unit-tests/storages/string-array-transformers/string-array/StringArrayStorage.spec.ts @@ -41,10 +41,7 @@ const getStringArrayStorageItemData = ( value: string, decodeKeys: string[] ): IStringArrayStorageItemData | undefined => { - (stringArrayStorage).rc4Keys = [ - 'foo', - ...decodeKeys - ]; + (stringArrayStorage).rc4Keys = ['foo', ...decodeKeys]; return stringArrayStorage.get(value); }; @@ -61,8 +58,10 @@ describe('StringArrayStorage', () => { }); for (let i = 0; i < samplesCount; i++) { - const {encodedValue: firstEncodedValue} = getStringArrayStorageItemData(stringArrayStorage, '_15', ['CRDL']) || {}; - const {encodedValue: secondEncodedValue} = getStringArrayStorageItemData(stringArrayStorage, '_12', ['q9mB']) || {}; + const { encodedValue: firstEncodedValue } = + getStringArrayStorageItemData(stringArrayStorage, '_15', ['CRDL']) || {}; + const { encodedValue: secondEncodedValue } = + getStringArrayStorageItemData(stringArrayStorage, '_12', ['q9mB']) || {}; if (firstEncodedValue === secondEncodedValue) { isCollisionHappened = true; @@ -83,25 +82,18 @@ describe('StringArrayStorage', () => { before(() => { const stringArrayStorage: IStringArrayStorage = getStorageInstance({ - stringArrayEncoding: [ - StringArrayEncoding.Base64, - StringArrayEncoding.Rc4 - ] + stringArrayEncoding: [StringArrayEncoding.Base64, StringArrayEncoding.Rc4] }); for (let i = 0; i < samplesCount; i++) { - const { - encodedValue: firstEncodedValue, - encoding: firstEncodedValueEncoding - } = getStringArrayStorageItemData(stringArrayStorage, 'zxL', ['&Jfx', '[lR4']) || {}; - const { - encodedValue: secondEncodedValue, - encoding: secondEncodedValueEncoding - } = getStringArrayStorageItemData(stringArrayStorage, 'omC', ['&Jfx', '[lR4']) || {}; + const { encodedValue: firstEncodedValue, encoding: firstEncodedValueEncoding } = + getStringArrayStorageItemData(stringArrayStorage, 'zxL', ['&Jfx', '[lR4']) || {}; + const { encodedValue: secondEncodedValue, encoding: secondEncodedValueEncoding } = + getStringArrayStorageItemData(stringArrayStorage, 'omC', ['&Jfx', '[lR4']) || {}; if ( - firstEncodedValue === secondEncodedValue - && firstEncodedValueEncoding === secondEncodedValueEncoding + firstEncodedValue === secondEncodedValue && + firstEncodedValueEncoding === secondEncodedValueEncoding ) { isCollisionHappened = true; break; diff --git a/test/unit-tests/storages/string-array-transformers/visited-lexical-scope-nodes-stack/VisitedLexicalScopeNodesStackStorage.spec.ts b/test/unit-tests/storages/string-array-transformers/visited-lexical-scope-nodes-stack/VisitedLexicalScopeNodesStackStorage.spec.ts index 8ce326c8..bea1a739 100644 --- a/test/unit-tests/storages/string-array-transformers/visited-lexical-scope-nodes-stack/VisitedLexicalScopeNodesStackStorage.spec.ts +++ b/test/unit-tests/storages/string-array-transformers/visited-lexical-scope-nodes-stack/VisitedLexicalScopeNodesStackStorage.spec.ts @@ -26,7 +26,9 @@ const getStorageInstance = (options: TInputOptions = {}): IVisitedLexicalScopeNo ...options }); - const storage: IVisitedLexicalScopeNodesStackStorage = inversifyContainerFacade.get(ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage); + const storage: IVisitedLexicalScopeNodesStackStorage = inversifyContainerFacade.get( + ServiceIdentifiers.IVisitedLexicalScopeNodesStackStorage + ); storage.initialize(); @@ -36,22 +38,16 @@ const getStorageInstance = (options: TInputOptions = {}): IVisitedLexicalScopeNo describe('VisitedLexicalScopeNodesStackStorage', () => { describe('getLastElement', () => { const firstElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('first') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('first')) ]); const secondElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('second') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('second')) ]); - const expectedLastElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('last') - ) + const expectedLastElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ + NodeFactory.expressionStatementNode(NodeFactory.literalNode('last')) ]); - let lastElement: TNodeWithLexicalScopeStatements | undefined; + let lastElement: TNodeWithLexicalScopeStatements | undefined; before(() => { const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = getStorageInstance(); @@ -70,25 +66,20 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { describe('getPenultimateElement', () => { describe('Variant #1: three array elements', () => { const firstElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('first') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('first')) ]); const expectedSecondElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('second') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('second')) ]); - const lastElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('last') - ) + const lastElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ + NodeFactory.expressionStatementNode(NodeFactory.literalNode('last')) ]); let penultimateElement: TNodeWithLexicalScopeStatements | undefined; before(() => { - const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = getStorageInstance(); + const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = + getStorageInstance(); visitedLexicalScopeNodesStackStorage.push(firstElement); visitedLexicalScopeNodesStackStorage.push(expectedSecondElement); @@ -104,15 +95,14 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { describe('Variant #2: one array element', () => { const expectedPenultimateElement: undefined = undefined; const firstElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('first') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('first')) ]); let penultimateElement: TNodeWithLexicalScopeStatements | undefined; before(() => { - const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = getStorageInstance(); + const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = + getStorageInstance(); visitedLexicalScopeNodesStackStorage.push(firstElement); penultimateElement = visitedLexicalScopeNodesStackStorage.getPenultimateElement(); @@ -129,7 +119,8 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { let penultimateElement: TNodeWithLexicalScopeStatements | undefined; before(() => { - const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = getStorageInstance(); + const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = + getStorageInstance(); penultimateElement = visitedLexicalScopeNodesStackStorage.getPenultimateElement(); }); @@ -142,19 +133,12 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { describe('push', () => { const firstElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('first') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('first')) ]); const secondElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('second') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('second')) ]); - const expectedStorage: TNodeWithLexicalScopeStatements[] = [ - firstElement, - secondElement - ]; + const expectedStorage: TNodeWithLexicalScopeStatements[] = [firstElement, secondElement]; let storage: TNodeWithLexicalScopeStatements[]; @@ -174,25 +158,20 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { describe('pop', () => { describe('Variant #1: few elements', () => { const firstElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('first') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('first')) ]); const secondElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('second') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('second')) ]); - const expectedStorage: TNodeWithLexicalScopeStatements[] = [ - firstElement - ]; + const expectedStorage: TNodeWithLexicalScopeStatements[] = [firstElement]; const expectedPoppedElement: TNodeWithLexicalScopeStatements = secondElement; let storage: TNodeWithLexicalScopeStatements[]; let poppedElement: TNodeWithLexicalScopeStatements | undefined; before(() => { - const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = getStorageInstance(); + const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = + getStorageInstance(); visitedLexicalScopeNodesStackStorage.push(firstElement); visitedLexicalScopeNodesStackStorage.push(secondElement); @@ -212,9 +191,7 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { describe('Variant #2: single element', () => { const firstElement: TNodeWithLexicalScopeStatements = NodeFactory.blockStatementNode([ - NodeFactory.expressionStatementNode( - NodeFactory.literalNode('first') - ) + NodeFactory.expressionStatementNode(NodeFactory.literalNode('first')) ]); const expectedStorage: TNodeWithLexicalScopeStatements[] = []; const expectedPoppedElement: TNodeWithLexicalScopeStatements = firstElement; @@ -223,7 +200,8 @@ describe('VisitedLexicalScopeNodesStackStorage', () => { let poppedElement: TNodeWithLexicalScopeStatements | undefined; before(() => { - const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = getStorageInstance(); + const visitedLexicalScopeNodesStackStorage: IVisitedLexicalScopeNodesStackStorage = + getStorageInstance(); visitedLexicalScopeNodesStackStorage.push(firstElement); diff --git a/test/unit-tests/utils/ArrayUtils.spec.ts b/test/unit-tests/utils/ArrayUtils.spec.ts index 0d8d1419..a62cc031 100644 --- a/test/unit-tests/utils/ArrayUtils.spec.ts +++ b/test/unit-tests/utils/ArrayUtils.spec.ts @@ -71,13 +71,7 @@ describe('ArrayUtils', () => { describe('range length more than 0', () => { const rangeLength: number = 5; - const expectedArray: string[] = [ - 'foo0', - 'foo1', - 'foo2', - 'foo3', - 'foo4', - ]; + const expectedArray: string[] = ['foo0', 'foo1', 'foo2', 'foo3', 'foo4']; let array: string[]; @@ -278,8 +272,7 @@ describe('ArrayUtils', () => { }); describe('rotate', () => { - let array: number[], - rotatedArray: number[]; + let array: number[], rotatedArray: number[]; beforeEach(() => { array = [1, 2, 3, 4, 5, 6]; @@ -306,7 +299,7 @@ describe('ArrayUtils', () => { rotatedArray = arrayUtils.rotate(array, rotateValue); }); - it('shouldn\'t rotate array', () => { + it("shouldn't rotate array", () => { assert.deepEqual(rotatedArray, expectedArray); }); }); diff --git a/test/unit-tests/utils/CryptUtils.spec.ts b/test/unit-tests/utils/CryptUtils.spec.ts index edc2cb60..a4364d59 100644 --- a/test/unit-tests/utils/CryptUtils.spec.ts +++ b/test/unit-tests/utils/CryptUtils.spec.ts @@ -21,33 +21,31 @@ describe('CryptUtils', () => { }); describe('btoa', () => { - describe('Variant #1: basic', () => { - const expectedEncodedString: string = 'c3RyaW5n'; - const expectedDecodedString: string = 'string'; + describe('Variant #1: basic', () => { + const expectedEncodedString: string = 'c3RyaW5n'; + const expectedDecodedString: string = 'string'; - let encodedString: string, - decodedString: string; + let encodedString: string, decodedString: string; - before(() => { - encodedString = cryptUtils.btoa('string'); - decodedString = atob(encodedString); - }); + before(() => { + encodedString = cryptUtils.btoa('string'); + decodedString = atob(encodedString); + }); - it('should create a base-64 encoded string from a given string', () => { - assert.equal(encodedString, expectedEncodedString); - }); + it('should create a base-64 encoded string from a given string', () => { + assert.equal(encodedString, expectedEncodedString); + }); - it('should create encoded string that can be successfully decoded', () => { - assert.equal(decodedString, expectedDecodedString); - }); - }); + it('should create encoded string that can be successfully decoded', () => { + assert.equal(decodedString, expectedDecodedString); + }); + }); describe('Variant #2: padding characters', () => { const expectedEncodedString: string = 'c3RyaQ=='; const expectedDecodedString: string = 'stri'; - let encodedString: string, - decodedString: string; + let encodedString: string, decodedString: string; before(() => { encodedString = cryptUtils.btoa('stri'); @@ -67,8 +65,7 @@ describe('CryptUtils', () => { const expectedEncodedString: string = '0YLQtdGB0YI='; const expectedDecodedString: string = 'тест'; - let encodedString: string, - decodedString: string; + let encodedString: string, decodedString: string; before(() => { encodedString = cryptUtils.btoa('тест'); @@ -89,16 +86,14 @@ describe('CryptUtils', () => { const originalString: string = 'example.com'; const hiddenStringLength: number = 30; - let hiddenString: string, - diffString: string; + let hiddenString: string, diffString: string; before(() => { [hiddenString, diffString] = cryptUtils.hideString(originalString, hiddenStringLength); }); describe('hidden string length check', () => { - let originalStringActualLength: number, - hiddenStringActualLength: number; + let originalStringActualLength: number, hiddenStringActualLength: number; before(() => { originalStringActualLength = originalString.length; @@ -129,8 +124,7 @@ describe('CryptUtils', () => { const string: string = 'test'; const key: string = 'key'; - let encodedString: string, - decodedString: string; + let encodedString: string, decodedString: string; before(() => { encodedString = cryptUtils.rc4(string, key); diff --git a/test/unit-tests/utils/CryptUtilsStringArray.spec.ts b/test/unit-tests/utils/CryptUtilsStringArray.spec.ts index 283b24f7..6b23fa6b 100644 --- a/test/unit-tests/utils/CryptUtilsStringArray.spec.ts +++ b/test/unit-tests/utils/CryptUtilsStringArray.spec.ts @@ -18,8 +18,9 @@ describe('CryptUtilsStringArray', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - cryptUtilsStringArray = inversifyContainerFacade - .get(ServiceIdentifiers.ICryptUtilsStringArray); + cryptUtilsStringArray = inversifyContainerFacade.get( + ServiceIdentifiers.ICryptUtilsStringArray + ); }); describe('btoa', () => { @@ -56,8 +57,7 @@ describe('CryptUtilsStringArray', () => { const string: string = 'test'; const key: string = 'key'; - let encodedString: string, - decodedString: string; + let encodedString: string, decodedString: string; before(() => { encodedString = cryptUtilsStringArray.rc4(string, key); diff --git a/test/unit-tests/utils/EscapeSequenceEncoder.spec.ts b/test/unit-tests/utils/EscapeSequenceEncoder.spec.ts index 3a553b9a..73624cc1 100644 --- a/test/unit-tests/utils/EscapeSequenceEncoder.spec.ts +++ b/test/unit-tests/utils/EscapeSequenceEncoder.spec.ts @@ -8,7 +8,6 @@ import { ServiceIdentifiers } from '../../../src/container/ServiceIdentifiers'; import { IInversifyContainerFacade } from '../../../src/interfaces/container/IInversifyContainerFacade'; import { IEscapeSequenceEncoder } from '../../../src/interfaces/utils/IEscapeSequenceEncoder'; - describe('EscapeSequenceEncoder', () => { describe('encode', () => { let escapeSequenceEncoder: IEscapeSequenceEncoder; @@ -17,8 +16,9 @@ describe('EscapeSequenceEncoder', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - escapeSequenceEncoder = inversifyContainerFacade - .get(ServiceIdentifiers.IEscapeSequenceEncoder); + escapeSequenceEncoder = inversifyContainerFacade.get( + ServiceIdentifiers.IEscapeSequenceEncoder + ); }); describe('Variant #1: default', () => { @@ -37,7 +37,7 @@ describe('EscapeSequenceEncoder', () => { }); describe('Variant #2: escape `escape sequences`', () => { - const string: string = 'abc\'\\r\\n'; + const string: string = "abc'\\r\\n"; const expectedString: string = 'abc\\x27\\x5cr\\x5cn'; let actualString: string; diff --git a/test/unit-tests/utils/LevelledTopologicalSorter.spec.ts b/test/unit-tests/utils/LevelledTopologicalSorter.spec.ts index f09a12c7..33bdd5a5 100644 --- a/test/unit-tests/utils/LevelledTopologicalSorter.spec.ts +++ b/test/unit-tests/utils/LevelledTopologicalSorter.spec.ts @@ -8,7 +8,6 @@ import { ServiceIdentifiers } from '../../../src/container/ServiceIdentifiers'; import { IInversifyContainerFacade } from '../../../src/interfaces/container/IInversifyContainerFacade'; import { ILevelledTopologicalSorter } from '../../../src/interfaces/utils/ILevelledTopologicalSorter'; - describe('EscapeSequenceEncoder', () => { describe('encode', () => { let levelledTopologicalSorter: ILevelledTopologicalSorter; @@ -17,8 +16,9 @@ describe('EscapeSequenceEncoder', () => { const inversifyContainerFacade: IInversifyContainerFacade = new InversifyContainerFacade(); inversifyContainerFacade.load('', '', {}); - levelledTopologicalSorter = inversifyContainerFacade - .get(ServiceIdentifiers.ILevelledTopologicalSorter); + levelledTopologicalSorter = inversifyContainerFacade.get( + ServiceIdentifiers.ILevelledTopologicalSorter + ); }); describe('Base sort', () => { @@ -33,14 +33,7 @@ describe('EscapeSequenceEncoder', () => { }); describe('Variant #1: Base linear sort', () => { - const expectedSortedItems: string[] = [ - 'F', - 'A', - 'C', - 'B', - 'D', - 'E', - ]; + const expectedSortedItems: string[] = ['F', 'A', 'C', 'B', 'D', 'E']; let sortedItems: string[]; @@ -54,11 +47,7 @@ describe('EscapeSequenceEncoder', () => { }); describe('Variant #2: Base sort with grouping', () => { - const expectedSortedItems: string[][] = [ - ['C', 'D', 'F'], - ['A', 'E'], - ['B'] - ]; + const expectedSortedItems: string[][] = [['C', 'D', 'F'], ['A', 'E'], ['B']]; let sortedItems: string[][]; @@ -83,14 +72,7 @@ describe('EscapeSequenceEncoder', () => { }); describe('Variant #1: Should sort items without relations', () => { - const expectedSortedItems: string[] = [ - 'A', - 'B', - 'C', - 'D', - 'E', - 'F' - ]; + const expectedSortedItems: string[] = ['A', 'B', 'C', 'D', 'E', 'F']; let sortedItems: string[]; @@ -104,9 +86,7 @@ describe('EscapeSequenceEncoder', () => { }); describe('Variant #2: Should sort items without relations with grouping', () => { - const expectedSortedItems: string[][] = [ - ['A', 'B', 'C', 'D', 'E', 'F'] - ]; + const expectedSortedItems: string[][] = [['A', 'B', 'C', 'D', 'E', 'F']]; let sortedItems: string[][]; diff --git a/test/unit-tests/utils/NumberUtils.spec.ts b/test/unit-tests/utils/NumberUtils.spec.ts index a87bdbe1..8f230f2a 100644 --- a/test/unit-tests/utils/NumberUtils.spec.ts +++ b/test/unit-tests/utils/NumberUtils.spec.ts @@ -334,7 +334,7 @@ describe('NumberUtils', function () { describe('Positive number', () => { describe('Variant #1: positive small safe integer', () => { const number: number = 100; - const expectedResult: boolean = false + const expectedResult: boolean = false; let result: boolean; @@ -349,7 +349,7 @@ describe('NumberUtils', function () { describe('Variant #2: positive big safe integer', () => { const number: number = Number.MAX_SAFE_INTEGER; - const expectedResult: boolean = false + const expectedResult: boolean = false; let result: boolean; @@ -364,7 +364,7 @@ describe('NumberUtils', function () { describe('Variant #3: positive unsafe integer', () => { const number: number = Number.MAX_SAFE_INTEGER + 1; - const expectedResult: boolean = true + const expectedResult: boolean = true; let result: boolean; @@ -381,7 +381,7 @@ describe('NumberUtils', function () { describe('Negative number', () => { describe('Variant #1: negative small safe integer', () => { const number: number = -100; - const expectedResult: boolean = false + const expectedResult: boolean = false; let result: boolean; @@ -396,7 +396,7 @@ describe('NumberUtils', function () { describe('Variant #2: negative big safe integer', () => { const number: number = Number.MIN_SAFE_INTEGER; - const expectedResult: boolean = false + const expectedResult: boolean = false; let result: boolean; @@ -411,7 +411,7 @@ describe('NumberUtils', function () { describe('Variant #3: negative unsafe integer', () => { const number: number = Number.MIN_SAFE_INTEGER - 1; - const expectedResult: boolean = true + const expectedResult: boolean = true; let result: boolean; @@ -444,10 +444,7 @@ describe('NumberUtils', function () { describe('Positive numbers', () => { describe('Variant #1: positive number `1`', () => { const number: number = 1; - const expectedFactors: number[] = [ - -1, - 1 - ]; + const expectedFactors: number[] = [-1, 1]; let factors: number[]; @@ -462,12 +459,7 @@ describe('NumberUtils', function () { describe('Variant #2: positive number `2`', () => { const number: number = 2; - const expectedFactors: number[] = [ - -2, - -1, - 1, - 2 - ]; + const expectedFactors: number[] = [-2, -1, 1, 2]; let factors: number[]; @@ -483,24 +475,7 @@ describe('NumberUtils', function () { describe('Variant #3: positive number `100`', () => { const number: number = 100; const expectedFactors: number[] = [ - -100, - -50, - -25, - -20, - -10, - -5, - -4, - -2, - -1, - 1, - 2, - 4, - 5, - 10, - 20, - 25, - 50, - 100 + -100, -50, -25, -20, -10, -5, -4, -2, -1, 1, 2, 4, 5, 10, 20, 25, 50, 100 ]; let factors: number[]; @@ -545,15 +520,12 @@ describe('NumberUtils', function () { assert.deepEqual(factors, expectedFactors); }); }); - }) + }); describe('Negative numbers', () => { describe('Variant #1: negative number `-1`', () => { const number: number = -1; - const expectedFactors: number[] = [ - -1, - 1 - ]; + const expectedFactors: number[] = [-1, 1]; let factors: number[]; @@ -568,12 +540,7 @@ describe('NumberUtils', function () { describe('Variant #2: negative number `-2`', () => { const number: number = -2; - const expectedFactors: number[] = [ - -2, - -1, - 1, - 2 - ]; + const expectedFactors: number[] = [-2, -1, 1, 2]; let factors: number[]; @@ -589,24 +556,7 @@ describe('NumberUtils', function () { describe('Variant #3: negative number `-100`', () => { const number: number = -100; const expectedFactors: number[] = [ - -100, - -50, - -25, - -20, - -10, - -5, - -4, - -2, - -1, - 1, - 2, - 4, - 5, - 10, - 20, - 25, - 50, - 100 + -100, -50, -25, -20, -10, -5, -4, -2, -1, 1, 2, 4, 5, 10, 20, 25, 50, 100 ]; let factors: number[]; @@ -651,7 +601,7 @@ describe('NumberUtils', function () { assert.deepEqual(factors, expectedFactors); }); }); - }) + }); describe('zero number', () => { const number: number = 0; @@ -665,6 +615,6 @@ describe('NumberUtils', function () { it('should throw an error', () => { assert.throw(testFunc, Error); }); - }) + }); }); }); diff --git a/test/unit-tests/utils/ObfuscatedCodeFileUtils.spec.ts b/test/unit-tests/utils/ObfuscatedCodeFileUtils.spec.ts index 29902bc4..5393a847 100644 --- a/test/unit-tests/utils/ObfuscatedCodeFileUtils.spec.ts +++ b/test/unit-tests/utils/ObfuscatedCodeFileUtils.spec.ts @@ -2,16 +2,16 @@ import { expect } from 'chai'; import { ObfuscatedCodeFileUtils } from '../../../src/cli/utils/ObfuscatedCodeFileUtils'; describe('ObfuscatedCodeFileUtils', () => { - let util: ObfuscatedCodeFileUtils; + let util: ObfuscatedCodeFileUtils; - beforeEach(() => { - util = new ObfuscatedCodeFileUtils('src/cli/', { - output: 'src/cli/dist', + beforeEach(() => { + util = new ObfuscatedCodeFileUtils('src/cli/', { + output: 'src/cli/dist' + }); }); - }); - it('should handle input path ending (or not ending) with forward slash', () => { - const result = util.getOutputCodePath('src/cli/app.js'); - expect(result).equals('src/cli/dist/app.js'); - }); + it('should handle input path ending (or not ending) with forward slash', () => { + const result = util.getOutputCodePath('src/cli/app.js'); + expect(result).equals('src/cli/dist/app.js'); + }); }); diff --git a/test/unit-tests/utils/RandomGenerator.spec.ts b/test/unit-tests/utils/RandomGenerator.spec.ts index 7671f67f..f2d3fe07 100644 --- a/test/unit-tests/utils/RandomGenerator.spec.ts +++ b/test/unit-tests/utils/RandomGenerator.spec.ts @@ -33,7 +33,11 @@ describe('RandomGenerator', () => { before(() => { for (let i = 0; i < samplesCount; i++) { - const randomInteger = randomGenerator.getRandomIntegerExcluding(minValue, maxValue, valuesToExclude); + const randomInteger = randomGenerator.getRandomIntegerExcluding( + minValue, + maxValue, + valuesToExclude + ); if (!expectedRandomIntegerValues.includes(randomInteger)) { isRandomIntegerInAllowedValuesRange = false; @@ -55,7 +59,7 @@ describe('RandomGenerator', () => { const delta: number = 0.15; - const expectedValueChance: number = 0.2 + const expectedValueChance: number = 0.2; let minValuesCount: number = 0; let maxValuesCount: number = 0; @@ -65,7 +69,11 @@ describe('RandomGenerator', () => { before(() => { for (let i = 0; i < samplesCount; i++) { - const randomInteger: number = randomGenerator.getRandomIntegerExcluding(minValue, maxValue, valuesToExclude); + const randomInteger: number = randomGenerator.getRandomIntegerExcluding( + minValue, + maxValue, + valuesToExclude + ); if (randomInteger === minValue) { minValuesCount += 1; diff --git a/test/unit-tests/utils/StringUtils.spec.ts b/test/unit-tests/utils/StringUtils.spec.ts index fa56eee8..21659e5f 100644 --- a/test/unit-tests/utils/StringUtils.spec.ts +++ b/test/unit-tests/utils/StringUtils.spec.ts @@ -7,12 +7,12 @@ describe('StringUtils', function () { describe('escapeJsString', () => { describe('Variant #1: single quotes', () => { - const expectedEscapedJsString: string = 'const foo = \\\'Hello World!\\\''; + const expectedEscapedJsString: string = "const foo = \\'Hello World!\\'"; let escapedJsString: string; before(() => { - escapedJsString = StringUtils.escapeJsString('const foo = \'Hello World!\''); + escapedJsString = StringUtils.escapeJsString("const foo = 'Hello World!'"); }); it('should escape js string', () => { diff --git a/test/unit-tests/utils/Utils.spec.ts b/test/unit-tests/utils/Utils.spec.ts index 7f570ba4..c72bb067 100644 --- a/test/unit-tests/utils/Utils.spec.ts +++ b/test/unit-tests/utils/Utils.spec.ts @@ -131,10 +131,7 @@ describe('Utils', () => { let identifiersPrefix: string; before(() => { - identifiersPrefix = Utils.getIdentifiersPrefixForMultipleSources( - 'foo', - 1 - ); + identifiersPrefix = Utils.getIdentifiersPrefixForMultipleSources('foo', 1); }); it('should return correct identifiers prefix', () => { @@ -148,10 +145,7 @@ describe('Utils', () => { let identifiersPrefix: string; before(() => { - identifiersPrefix = Utils.getIdentifiersPrefixForMultipleSources( - undefined, - 1 - ); + identifiersPrefix = Utils.getIdentifiersPrefixForMultipleSources(undefined, 1); }); it('should return correct identifiers prefix', () => { diff --git a/yarn.lock b/yarn.lock index 6c1be1ca..e74bdbc1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -487,6 +487,11 @@ resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.1.2.tgz#1cf95080bb7072fafaa3cb13b442fab4695c3893" integrity sha512-fdDH1LSGfZdTH2sxdpVMw31BanV28K/Gry0cVFxaNP77neJSkd82mM8ErPNYs9e+0O7SdHBLTDzDgwUuy18RnQ== +"@pkgr/core@^0.2.9": + version "0.2.9" + resolved "https://registry.yarnpkg.com/@pkgr/core/-/core-0.2.9.tgz#d229a7b7f9dac167a156992ef23c7f023653f53b" + integrity sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA== + "@rtsao/scc@^1.1.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@rtsao/scc/-/scc-1.1.0.tgz#927dd2fae9bc3361403ac2c7a00c32ddce9ad7e8" @@ -2151,6 +2156,11 @@ escape-string-regexp@^4.0.0: resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== +eslint-config-prettier@10.1.8: + version "10.1.8" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz#15734ce4af8c2778cc32f0b01b37b0b5cd1ecb97" + integrity sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w== + eslint-import-resolver-node@^0.3.9: version "0.3.9" resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz#d4eaac52b8a2e7c3cd1903eb00f7e053356118ac" @@ -2219,6 +2229,14 @@ eslint-plugin-prefer-arrow@1.2.3: resolved "https://registry.npmjs.org/eslint-plugin-prefer-arrow/-/eslint-plugin-prefer-arrow-1.2.3.tgz" integrity sha512-J9I5PKCOJretVuiZRGvPQxCbllxGAV/viI20JO3LYblAodofBxyMnZAJ+WGeClHgANnSJberTNoFWWjrWKBuXQ== +eslint-plugin-prettier@5.5.4: + version "5.5.4" + resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-5.5.4.tgz#9d61c4ea11de5af704d4edf108c82ccfa7f2e61c" + integrity sha512-swNtI95SToIz05YINMA6Ox5R057IMAmWZ26GqPxusAp1TZzj+IdY9tXNWWD3vkF/wEqydCONcwjTFpxybBqZsg== + dependencies: + prettier-linter-helpers "^1.0.0" + synckit "^0.11.7" + eslint-plugin-unicorn@56.0.1: version "56.0.1" resolved "https://registry.yarnpkg.com/eslint-plugin-unicorn/-/eslint-plugin-unicorn-56.0.1.tgz#d10a3df69ba885939075bdc95a65a0c872e940d4" @@ -2402,6 +2420,11 @@ fast-deep-equal@3.1.3, fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: resolved "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz" integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== +fast-diff@^1.1.2: + version "1.3.0" + resolved "https://registry.yarnpkg.com/fast-diff/-/fast-diff-1.3.0.tgz#ece407fa550a64d638536cd727e129c61616e0f0" + integrity sha512-VxPP4NqbUjj6MaAOafWeUn2cXWLcCtljklUtZf0Ind4XQ+QPtmA0b18zZy0jIQx+ExRVCR/ZQpBmik5lXshNsw== + fast-glob@^3.2.9: version "3.3.3" resolved "https://registry.yarnpkg.com/fast-glob/-/fast-glob-3.3.3.tgz#d06d585ce8dba90a16b0505c543c3ccfb3aeb818" @@ -4323,6 +4346,18 @@ prelude-ls@~1.1.2: resolved "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.1.2.tgz" integrity sha1-IZMqVJ9eUv/ZqCf1cOBL5iqX2lQ= +prettier-linter-helpers@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz#d23d41fe1375646de2d0104d3454a3008802cf7b" + integrity sha512-GbK2cP9nraSSUF9N2XwUwqfzlAFlMNYYl+ShE/V+H8a9uNl/oUqB1w2EL54Jh0OlyRSd8RfWYJ3coVS4TROP2w== + dependencies: + fast-diff "^1.1.2" + +prettier@3.6.2: + version "3.6.2" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.6.2.tgz#ccda02a1003ebbb2bfda6f83a074978f608b9393" + integrity sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ== + process-on-spawn@^1.0.0: version "1.0.0" resolved "https://registry.npmjs.org/process-on-spawn/-/process-on-spawn-1.0.0.tgz" @@ -5024,6 +5059,13 @@ supports-preserve-symlinks-flag@^1.0.0: resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== +synckit@^0.11.7: + version "0.11.11" + resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.11.11.tgz#c0b619cf258a97faa209155d9cd1699b5c998cb0" + integrity sha512-MeQTA1r0litLUf0Rp/iisCaL8761lKAZHaimlbGK4j0HysC4PLfqygQj9srcs0m2RdtDYnF8UuYyKpbjHYp7Jw== + dependencies: + "@pkgr/core" "^0.2.9" + synckit@^0.9.1: version "0.9.3" resolved "https://registry.yarnpkg.com/synckit/-/synckit-0.9.3.tgz#1cfd60d9e61f931e07fb7f56f474b5eb31b826a7"