Full Code of shapesecurity/unminify for AI

main 1a000607c53c cached
51 files
111.1 KB
33.1k tokens
114 symbols
1 requests
Download .txt
Repository: shapesecurity/unminify
Branch: main
Commit: 1a000607c53c
Files: 51
Total size: 111.1 KB

Directory structure:
gitextract_dhkidt2p/

├── .eslintrc.js
├── .github/
│   └── workflows/
│       └── check.yml
├── .gitignore
├── LICENSE
├── README.md
├── bin/
│   └── cli.js
├── package.json
├── src/
│   ├── cli.js
│   ├── helpers/
│   │   ├── codegen.js
│   │   ├── fn-contains-weirdness.js
│   │   ├── inlinable.js
│   │   └── parents.js
│   ├── index.js
│   ├── safety-levels.js
│   └── transforms/
│       ├── safe/
│       │   ├── cleanup-with-state.js
│       │   └── cleanup.js
│       ├── unsafe/
│       │   └── remove-unused.js
│       └── wildly-unsafe/
│           ├── inline.js
│           └── partial-evaluate.js
└── test/
    ├── snapshots-in/
    │   ├── computed-member-to-static.js
    │   ├── expand-expression-statement.js
    │   ├── expand-multiple-decl.js
    │   ├── expand-sequence.js
    │   ├── hoist-fns.js
    │   ├── if-and-seq.js
    │   ├── if-not.js
    │   ├── indexing.js
    │   ├── inline-arguments.js
    │   ├── inline-called-once.js
    │   ├── inline-constant-object-property.js
    │   ├── inline-function-as-conditional.js
    │   ├── inline-iife.js
    │   ├── inline-trivial-function.js
    │   ├── make-blocks.js
    │   ├── negate.js
    │   ├── no-trailing-return-void.js
    │   ├── partial-evaluate.js
    │   ├── remove-empty-statements.js
    │   ├── remove-empty-try.js
    │   ├── remove-unused-vars.js
    │   ├── return-and.js
    │   ├── return-conditional.js
    │   ├── return-void.js
    │   ├── shorthand-if.js
    │   ├── spread-block.js
    │   ├── statement-position-negation.js
    │   ├── un-yoda.js
    │   └── unhoist-var-decls.js
    ├── snapshots-out/
    │   └── test/
    │       ├── snapshots.js.md
    │       └── snapshots.js.snap
    └── snapshots.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .eslintrc.js
================================================
module.exports = {
  extends: 'eslint:recommended',
  env: {
    es6: true,
    node: true,
    browser: false,
  },
  parserOptions: {
    ecmaVersion: 2020,
    sourceType: 'module',
  },
  rules: {
    'arrow-parens': ['error', 'as-needed'],
    'array-bracket-spacing': ['error', 'never'],
    'brace-style': ['error', '1tbs'],
    'camelcase': 'error',
    'comma-dangle': ['error', 'always-multiline'],
    'comma-spacing': ['error', { before: false, after: true }],
    'comma-style': ['error', 'last'],
    'computed-property-spacing': ['error', 'never'],
    'consistent-return': 'error',
    'consistent-this': ['error', 'self'],
    'curly': ['error', 'multi-line'],
    'dot-notation': 'error',
    'eol-last': 'error',
    'eqeqeq': ['error', 'smart'],
    'guard-for-in': 'error',
    'indent': ['error', 2, { SwitchCase: 1, VariableDeclarator: { var: 2, let: 2, const: 3 } }],
    'key-spacing': ['error', { beforeColon: false, afterColon: true }],
    'keyword-spacing': 'error',
    // 'max-len': ['warn', 120],
    'no-alert': 'error',
    'no-caller': 'error',
    'no-catch-shadow': 'error',
    'no-console': 'warn',
    'no-else-return': 'error',
    'no-empty': ['error', { allowEmptyCatch: true }],
    'no-eval': 'error',
    'no-extend-native': 'error',
    'no-extra-bind': 'error',
    'no-extra-parens': 'warn',
    'no-fallthrough': 'error',
    'no-floating-decimal': 'error',
    'no-implied-eval': 'error',
    'no-inner-declarations': ['error', 'both'],
    'no-lonely-if': 'error',
    'no-loop-func': 'error',
    'no-mixed-spaces-and-tabs': 'error',
    'no-multi-spaces': 'error',
    'no-multiple-empty-lines': ['error', { max: 2 }],
    'no-negated-condition': 'error',
    'no-param-reassign': 'warn',
    'no-redeclare': 'error',
    'no-return-assign': 'error',
    'no-self-compare': 'error',
    'no-sequences': 'error',
    'no-shadow': ['error', { builtinGlobals: true }],
    'no-shadow-restricted-names': 'error',
    'no-spaced-func': 'error',
    'no-trailing-spaces': 'error',
    'no-undef': 'error',
    'no-undefined': 'error',
    'no-underscore-dangle': 'off',
    'no-unused-vars': ['error', { vars: 'all', args: 'after-used' }],
    'no-use-before-define': ['error', 'nofunc'],
    'no-useless-call': 'error',
    'no-useless-escape': 'error',
    'no-var': 'error',
    'no-warning-comments': 'off',
    'no-with': 'error',
    'object-curly-spacing': ['error', 'always'],
    'object-shorthand': ['error', 'always'],
    'prefer-arrow-callback': ['error'],
    'quotes': ['error', 'single'],
    'semi': ['error', 'always'],
    'semi-spacing': ['error', { before: false, after: true }],
    'space-before-blocks': 'error',
    'space-before-function-paren': ['error', { anonymous: 'always', named: 'never' }],
    'space-in-parens': 'error',
    'space-infix-ops': 'error',
    'space-unary-ops': 'error',
    'spaced-comment': ['warn', 'always', { block: { markers: ['!'], exceptions: ['*'] } }],
    'strict': 'off',
    'valid-jsdoc': 'warn',
    'wrap-iife': ['error', 'outside'],
    'yoda': ['error', 'never'],
  },
};



================================================
FILE: .github/workflows/check.yml
================================================
name: check

on:
  push:
    branches:
      - main
  pull_request:

jobs:
  pre:
    name: Prerequisites
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@v2
        with:
          fetch-depth: 0

      - name: Enforce CLA signature
        env:
          COMMIT_RANGE: ${{ github.event.pull_request.base.sha }}...${{ github.event.pull_request.head.sha }}
        run: curl https://raw.githubusercontent.com/shapesecurity/CLA/HEAD/cla-check.sh | bash

  check:
    needs: pre
    if: |
      !cancelled() && !failure()
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node: [18]

    name: Check - node ${{ matrix.node }}

    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup node
        uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node }}

      - name: Install dependencies
        run: npm ci

      - name: Lint
        run: npm run lint -- --quiet

      - name: Test
        run: npm test


================================================
FILE: .gitignore
================================================
node_modules


================================================
FILE: LICENSE
================================================

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!)  The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.


================================================
FILE: README.md
================================================
Unminify
========

A little project to undo several of the horrible things JavaScript build tools will do to JavaScript. In addition to undoing most minification, it reverses some of the stupider but surprisingly common "obfuscation" techniques used in the wild.

It may amuse you to try it on, say, [this random bit of JavaScript I found](https://secure2.homedepot.com/_bm/async.js).

## Installation

```
npm install -g unminify
```

or use it without installing via `npx` (available since `npm` 5.2.0)

```
npx unminify [...args]
```

## CLI Usage

```
unminify /path/to/file.js
```

* `--safety` may be given to enable/disable transformations based on the user's required safety guarantees. Refer to the [safety levels](#safety-levels) documentation for more details. The value of `--safety` may be one of
  * `useless`
  * `safe` (default)
  * `mostly-safe`
  * `unsafe`
  * `wildly-unsafe`
* `--additional-transform` may be given zero or more times, each followed by a path to a module providing an AST transform; the function signals that the transformation was not applied by returning its input

## API Usage

```js
let { unminifySource } = require('unminify');
let sourceText = '/* a minified/"obfuscated" JavaScript program */';
console.log(unminify(sourceText));

// or, with options
console.log(unminifySource(sourceText, {
  safety: unminify.safetyLevels.UNSAFE,
  additionalTransforms: [function(ast) { /* ... */ }],
}));
```

If you already have a Shift tree then you can use `unminifyTree` to avoid the codegen & reparse cost.

```js
let { parseScript } = require('shift-parser');
let { unminifyTree } = require('unminify');

let sourceText = '/* a minified/"obfuscated" JavaScript program */';

let tree = parseScript(sourceText);
let unminifiedTree = unminifyTree(tree);
```

## Safety Levels

* "safe to the point of uselessness":
  * safe for ALL programs ("programs" don't have early errors)
* "safe": "safe to the point of uselessness" except
  * Function.prototype.toString
  * function name/arity
  * Annex B
  * direct eval
* "mostly safe": "safe" except
  * side effecting getters/setters on the global object
  * sealed global object
  * non-writable/non-configurable properties on the global object
  * top-level var decls make global properties
* "unsafe": "mostly safe" except
  * non-spec built-in global properties or native proto properties
* "wildly unsafe":
  * no guarantees but it'll probably work most of the time

## License

    Copyright 2017 Shape Security, Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.


================================================
FILE: bin/cli.js
================================================
#!/usr/bin/env node
require('../src/cli');


================================================
FILE: package.json
================================================
{
  "name": "unminify",
  "version": "2.0.0",
  "author": "Kevin Gibbons <kevin@shapesecurity.com>",
  "description": "reverse many of the transformations applied by minifiers and naïve obfuscators",
  "license": "Apache-2.0",
  "repository": {
    "type": "git",
    "url": "https://github.com/shapesecurity/unminify"
  },
  "main": "src/index.js",
  "files": [
    "src",
    "bin"
  ],
  "bin": "bin/cli.js",
  "scripts": {
    "test": "ava --fail-fast --verbose",
    "update-snapshots": "ava --update-snapshots",
    "lint": "eslint src bin",
    "build": "exit 0"
  },
  "ava": {
    "files": [
      "test/**/*.js",
      "!test/snapshots-*/**/*.js"
    ],
    "snapshotDir": "test/snapshots-out",
    "failFast": true,
    "failWithoutAssertions": false
  },
  "dependencies": {
    "command-line-args": "5.2.1",
    "esutils": "2.0.3",
    "prettier": "2.6.2",
    "shift-ast": "7.0.0",
    "shift-codegen": "8.0.0",
    "shift-parser": "8.0.0",
    "shift-reducer": "7.0.0",
    "shift-scope": "6.0.0",
    "shift-spec": "2019.0.0"
  },
  "devDependencies": {
    "ava": "4.2.0",
    "eslint": "8.15.0"
  }
}


================================================
FILE: src/cli.js
================================================
'use strict';
/* eslint-disable no-console */

const fs = require('fs');
const args = require('command-line-args')([
  { name: 'file', type: String, defaultOption: true },
  { name: 'safety', type: String, defaultValue: 'safe' },
  { name: 'additional-transform', type: String, multiple: true, defaultValue: [] },
]);
const prettier = require('prettier');
const deobfuscate = require('../');
const safetyLevels = require('./safety-levels');
const safetyLevelMap = {
  __proto__: null,
  useless: safetyLevels.USELESS,
  safe: safetyLevels.SAFE,
  'mostly-safe': safetyLevels.MOSTLY_SAFE,
  unsafe: safetyLevels.UNSAFE,
  'wildly-unsafe': safetyLevels.WILDLY_UNSAFE,
};

function format(src) {
  return prettier.format(src, { parser: 'babel', singleQuote: true, trailingComma: 'es5' });
}

if (!args.file) {
  throw new Error('Missing required input file parameter');
}
if (!(args.safety in safetyLevelMap)) {
  throw new Error(`Safety level must be one of ${JSON.stringify(Object.keys(safetyLevelMap))}`);
}

const src = fs.readFileSync(args.file, 'utf-8');
const safety = safetyLevelMap[args.safety];
const additionalTransforms = args['additional-transform'].map(a => require(a));

console.log(format(deobfuscate(src, { additionalTransforms, safety })).trim());


================================================
FILE: src/helpers/codegen.js
================================================
'use strict';

const codegen = require('shift-codegen');

class FormattedCodeGenWithStrs extends codegen.FormattedCodeGen {
  reduceLiteralStringExpression(node) {
    const s = super.reduceLiteralStringExpression(node);
    let out = '';
    for (let i = 0; i < s.token.length; ++i) {
      const code = s.token.codePointAt(i);
      if (code >= 0x20 && code <= 0x7E) {
        out += s.token.charAt(i);
      } else if (code > 0xFFFF) {
        ++i;
        out += '\\u{' + code.toString(16).toUpperCase() + '}';
      } else if (code > 0xFF) {
        let hex = code.toString(16).toUpperCase();
        out += '\\u' + '0000'.slice(hex.length) + hex;
      } else if (code === 0) {
        out += '\\0';
      } else {
        let hex = code.toString(16).toUpperCase();
        out += '\\x' + '00'.slice(hex.length) + hex;
      }
    }
    s.token = out;
    return s;
  }
}

module.exports = function (tree) {
  return codegen.default(tree, new FormattedCodeGenWithStrs);
};


================================================
FILE: src/helpers/fn-contains-weirdness.js
================================================
'use strict';

// TODO short-curcuiting, memoization

const reducer = require('shift-reducer');

class ContainsWeirdness extends reducer.MonoidalReducer {
  constructor() {
    super({ empty: () => false, concat(b) {
      return this || b;
    } });
  }

  reduceThisExpression() {
    return true;
  }

  reduceFunctionExpression() {
    return false;
  }

  reduceFunctionDeclaration() {
    return false;
  }

  reduceIdentifierExpression(node) {
    return node.name === 'arguments';
  }

  // TODO many other cases
}
ContainsWeirdness.INSTANCE = new ContainsWeirdness;

module.exports.functionContainsWeirdness = function (fn) {
  return reducer.default(ContainsWeirdness.INSTANCE, fn.params) || reducer.default(ContainsWeirdness.INSTANCE, fn.body);
};

module.exports.expressionContainsWeirdness = function (expr) {
  return reducer.default(ContainsWeirdness.INSTANCE, expr);
};


================================================
FILE: src/helpers/inlinable.js
================================================
module.exports = [
  'LiteralNumericExpression',
  'LiteralStringExpression',
  'LiteralNullExpression',
  'LiteralBooleanExpression',
];


================================================
FILE: src/helpers/parents.js
================================================
'use strict';

// Give a map from a node to its parents.

const reducer = require('shift-reducer');
const spec = require('shift-spec');


class ParentFinder {
  constructor() {
    this.parents = new WeakMap;
  }
}

// eslint-disable-next-line guard-for-in
for (const typeName in spec) {
  const type = spec[typeName];
  const fields = type.fields.filter(f => f.name !== 'type');
  ParentFinder.prototype['reduce' + typeName] = function (node) {
    for (const field of fields) {
      if (node[field.name] === null || typeof node[field.name] !== 'object') continue;
      if (Array.isArray(node[field.name])) {
        node[field.name].filter(c => c !== null).forEach(c => {
          this.parents.set(c, node);
        });
      } else {
        this.parents.set(node[field.name], node);
      }
    }
  };
}

ParentFinder.prototype.originalReduceScript = ParentFinder.prototype.reduceScript;
ParentFinder.prototype.originalReduceModule = ParentFinder.prototype.reduceModule;
ParentFinder.prototype.reduceScript = function (node) {
  this.originalReduceScript(node);
  this.parents.set(node, null);
  return this.parents;
};
ParentFinder.prototype.reduceModule = function (node) {
  this.originalReduceModule(node);
  this.parents.set(node, null);
  return this.parents;
};

module.exports = ast => reducer.default(new ParentFinder, ast);


================================================
FILE: src/index.js
================================================
'use strict';

const parser = require('shift-parser');
const codegen = require('./helpers/codegen');
const safetyLevels = require('./safety-levels');

const TRANSFORMATIONS = {
  [safetyLevels.USELESS]: [],
  [safetyLevels.SAFE]: [
    require('./transforms/safe/cleanup'),
    require('./transforms/safe/cleanup-with-state'),
  ],
  [safetyLevels.MOSTLY_SAFE]: [],
  [safetyLevels.UNSAFE]: [
    require('./transforms/unsafe/remove-unused'),
  ],
  [safetyLevels.WILDLY_UNSAFE]: [
    require('./transforms/wildly-unsafe/inline'),
    require('./transforms/wildly-unsafe/partial-evaluate'),
  ],
};

function unminifySource(src, options) {
  let tree = parser.parseScript(src);
  return codegen(unminifyTree(tree, options));
}

function unminifyTree(tree, { safety = safetyLevels.SAFE, additionalTransforms = [] } = {}) {
  let transformations = [];
  for (let i = 0; i <= safety; ++i) {
    transformations.push(...TRANSFORMATIONS[i]);
  }
  transformations.push(...additionalTransforms);

  let lastTree = tree;
  // cap at 100 on general principles, but theoretically `while (true)` should be ok
  for (let i = 0; i < 100; ++i) {
    let newTree = lastTree;
    for (let transformation of transformations) {
      newTree = transformation(newTree);
    }
    if (newTree === lastTree) break;
    lastTree = newTree;
  }

  return lastTree;
}

module.exports = unminifySource;
module.exports.unminifySource = unminifySource;
module.exports.unminifyTree = unminifyTree;
module.exports.safetyLevels = safetyLevels;


================================================
FILE: src/safety-levels.js
================================================
module.exports = {
  __proto__: null,
  USELESS: 0,
  SAFE: 1,
  MOSTLY_SAFE: 2,
  UNSAFE: 3,
  WILDLY_UNSAFE: 4,
};


================================================
FILE: src/transforms/safe/cleanup-with-state.js
================================================
'use strict';

const reducer = require('shift-reducer');
const shiftScope = require('shift-scope');
const Shift = require('shift-ast/checked');

const getParents = require('../../helpers/parents');
const { functionContainsWeirdness, expressionContainsWeirdness } = require('../../helpers/fn-contains-weirdness');

// TODO rename this to something better expressing "transform for simpler static analysis"
module.exports = function cleanupWithState(ast) {
  const parents = getParents(ast);
  const globalScope = shiftScope.default(ast);
  const lookup = new shiftScope.ScopeLookup(globalScope);

  function findScopeForNode(node, scope = globalScope) {
    // TODO this should live elsewhere
    if (scope.astNode === node) return scope;
    for (let child of scope.children) {
      const r = findScopeForNode(node, child);
      if (r !== null) return r;
    }
    return null;
  }

  function unhoistVarDeclarations(statements) {
    const out = [];
    const toRemove = new WeakSet;
    const toBecomeDecl = new WeakMap; // ExpressionStatement -> list of other expression statements to remove from this set
    let touched = false;
    for (let statement of statements) {
      if (statement.type === 'VariableDeclarationStatement' && statement.declaration.kind === 'var' && statement.declaration.declarators.length === 1 && statement.declaration.declarators[0].init === null) {
        const vs = lookup.lookup(statement.declaration.declarators[0].binding);
        if (vs != null && vs.length === 1) {
          const v = vs[0];
          const simpleWrites = v.references
            .filter(r => r.accessibility.isWrite && !r.accessibility.isRead)
            .map(r => parents.get(r.node))
            .filter(n => n.type === 'AssignmentExpression')
            .map(n => [n, parents.get(n)])
            .filter(([n, p]) => p.type === 'ExpressionStatement' || p.type === 'ForStatement' && p.init === n)
            .map(([, p]) => p);
          const declParent = parents.get(statement);
          const isSameParent = n => {
            const parent = parents.get(n);
            if (parent === declParent) {
              return true;
            }
            const gp = parents.get(parent);
            if (gp != null && gp.type === 'ForStatement' && gp.init === parent) {
              return true;
            }
            return false;
          };
          if (simpleWrites.length > 0 && simpleWrites.every(isSameParent)) {
            touched = true;
            toRemove.add(statement);
            simpleWrites.forEach(s => toBecomeDecl.set(s, simpleWrites));
          }
        }
      }
    }

    if (!touched) {
      return statements;
    }

    for (let statement of statements) {
      if (toRemove.has(statement)) continue;
      if (toBecomeDecl.has(statement)) {
        if (statement.type === 'ExpressionStatement') {
          const declaration = new Shift.VariableDeclaration({ kind: 'var', declarators: [new Shift.VariableDeclarator({
            binding: new Shift.BindingIdentifier({ name: statement.expression.binding.name }),
            init: statement.expression.expression,
          })] });
          out.push(new Shift.VariableDeclarationStatement({ declaration }));
        } else if (statement.type === 'ForStatement') {
          const declaration = new Shift.VariableDeclaration({ kind: 'var', declarators: [new Shift.VariableDeclarator({
            binding: new Shift.BindingIdentifier({ name: statement.init.binding.name }),
            init: statement.init.expression,
          })] });
          out.push(new Shift.ForStatement({ init: declaration, test: statement.test, update: statement.update, body: statement.body }));
        } else {
          throw new Error('unreachable');
        }
        toBecomeDecl.get(statement).forEach(s => toBecomeDecl.delete(s));
        continue;
      }
      out.push(statement);
    }

    return out;
  }

  class CleanupWithState extends reducer.LazyCloneReducer {
    reduceFunctionBody(node, { directives, statements }) {
      // move declarations to first initialization, as long as all writes are in the same statement list as the declaration
      return super.reduceFunctionBody(node, { directives, statements: unhoistVarDeclarations(statements) });
    }

    reduceCallExpression(node, { callee, arguments: _arguments }) {
      // Turn (function(a){ ... })(b) into (function(){ var a = b; ... })()
      // Note: not safe if the function contains a direct `eval` which references `arguments` or an argument contains a direct `eval` which references `arguments` or `this`.
      if (callee.type === 'FunctionExpression' && !callee.isGenerator && !functionContainsWeirdness(callee)) {
        if (_arguments.length > 0 && _arguments.every(a => a.type !== 'SpreadElement' && !expressionContainsWeirdness(a)) && callee.params.rest === null && callee.params.items.every(p => p.type === 'BindingIdentifier')) {
          const names = [].concat(...node.arguments.map(collectNames)); // TODO avoid
          const fnScope = findScopeForNode(node.callee);
          if (fnScope && !names.some(n => fnScope.variables.has(n))) {
            // the scope check is to avoid shadowing something in the arguments
            const newInit = [];
            let i = 0;
            for (; i < callee.params.items.length; ++i) {
              newInit.push(new Shift.VariableDeclarationStatement({ declaration: new Shift.VariableDeclaration({
                kind: 'var',
                declarators: [
                  new Shift.VariableDeclarator({ binding: callee.params.items[i], init: _arguments[i] || null }),
                ],
              }) }));
            }
            for (; i < _arguments.length; ++i) {
              newInit.push(new Shift.ExpressionStatement({ expression: _arguments[i] }));
            }
            const fn = new Shift.FunctionExpression({ name: callee.name, isGenerator: false, isAsync: false, params: new Shift.FormalParameters({ items: [], rest: null }), body: new Shift.FunctionBody({
              directives: [],
              statements: newInit.concat(callee.body.statements),
            }) });
            return new Shift.CallExpression({ callee: fn, arguments: [] });
          }
        }
      }
      return super.reduceCallExpression(node, { callee, arguments: _arguments });
    }
  }


  class NameCollector extends reducer.MonoidalReducer {
    constructor() {
      super({ empty: () => [], concat: (a, b) => a.concat(b) });
    }

    reduceIdentifierExpression(node) {
      return [node.name];
    }

    reduceAssignmentTargetIdentifier(node) {
      return [node.name];
    }

    reduceBindingIdentifier(node) {
      return [node.name];
    }

    reduceFunctionExpression(node, state) { // TODO it would be nice for this to be thunked
      const scope = findScopeForNode(node);
      if (scope !== null) {
        return [...scope.through.keys()];
      }
      return super.reduceFunctionExpression(node, state); // better than nothing
    }

    /*
      Maybe this is a thing which should be exposed by the scope analyzer? through references for individual nodes, not just scopes?
    */
  }

  function collectNames(node) {
    return reducer.default(new NameCollector, node);
  }


  return reducer.default(new CleanupWithState, ast);
};


================================================
FILE: src/transforms/safe/cleanup.js
================================================
'use strict';

/* eslint-disable no-param-reassign */
// Basically de-uglify-js

const reducer = require('shift-reducer');
const Shift = require('shift-ast/checked');

const inlinable = require('../../helpers/inlinable');
const { functionContainsWeirdness } = require('../../helpers/fn-contains-weirdness');

const esutils = require('esutils');


// TODO convert switches to if/else

function makeBlock(statement) {
  return new Shift.BlockStatement({ block: new Shift.Block({ statements: [statement] }) });
}

function negate(expr, isBooleanContext, requireResult = true) {
  if (expr.type === 'LiteralBooleanExpression') {
    return new Shift.LiteralBooleanExpression({ value: !expr.value });
  } else if (expr.type === 'LiteralNumericExpression') {
    return new Shift.LiteralBooleanExpression({ value: !expr.value });
  } else if (expr.type === 'ArrayExpression' && expr.elements.length === 0) {
    return new Shift.LiteralBooleanExpression({ value: false });
  } else if (expr.type === 'ObjectExpression' && expr.properties.length === 0) {
    return new Shift.LiteralBooleanExpression({ value: false });
  } else if (expr.type === 'BinaryExpression') {
    if (expr.operator === '&&') {
      return new Shift.BinaryExpression({ left: negate(expr.left, isBooleanContext), operator: '||', right: negate(expr.right, isBooleanContext) });
    } else if (expr.operator === '||') {
      return new Shift.BinaryExpression({ left: negate(expr.left, isBooleanContext), operator: '&&', right: negate(expr.right, isBooleanContext) });
    } else if (expr.operator === '==') {
      return new Shift.BinaryExpression({ left: expr.left, operator: '!=', right: expr.right });
    } else if (expr.operator === '===') {
      return new Shift.BinaryExpression({ left: expr.left, operator: '!==', right: expr.right });
    } else if (expr.operator === '!=') {
      return new Shift.BinaryExpression({ left: expr.left, operator: '==', right: expr.right });
    } else if (expr.operator === '!==') {
      return new Shift.BinaryExpression({ left: expr.left, operator: '===', right: expr.right });
    }
  } else if (expr.type === 'UnaryExpression' && expr.operator === '!' && isBooleanContext) {
    return { ...expr.operand };
  }
  if (!requireResult) {
    return null;
  }
  return new Shift.UnaryExpression({ operator: '!', operand: expr });
}

function isConstant(node) {
  return inlinable.includes(node.type)
    || node.type === 'UnaryExpression' && inlinable.includes(node.operand.type);
}

function isSequence(expr) {
  return expr != null && expr.type === 'BinaryExpression' && expr.operator === ',';
}

// NB: only for use with associative operators
function binExprToExprs(expr) {
  const operator = expr.operator;
  return [...binExprToExprsHelper(expr.left, operator), ...binExprToExprsHelper(expr.right, operator)];
}

function binExprToExprsHelper(expr, operator) {
  if (expr.type === 'BinaryExpression' && expr.operator === operator) {
    return [...binExprToExprsHelper(expr.left, operator), ...binExprToExprsHelper(expr.right, operator)];
  }
  return [expr];
}

function declaratorsToDeclarationStatements(kind, declarators) {
  return declarators.map(d => new Shift.VariableDeclarationStatement({ declaration: new Shift.VariableDeclaration({ kind, declarators: [d] }) }));
}


class OnlyReturnUndefined extends reducer.LazyCloneReducer { // TODO this would be better thunked.
  reduceFunctionBody(node) {
    return node;
  }

  reduceReturnStatement(node, { expression }) {
    if (expression === null || expression.type === 'UnaryExpression' && expression.operator === 'void') {
      return node;
    }
    if (expression.type === 'UnaryExpression' && expression.operator === 'void') {
      return node;
    }
    const undef = new Shift.UnaryExpression({ operator: 'void', operand: expression });
    return new Shift.ReturnStatement({ expression: undef });
  }
}
const onlyReturnUndefined = new OnlyReturnUndefined;

function makeReturnsUndefined(fnBody) {
  const fixed = fnBody.statements.map(s => reducer.default(onlyReturnUndefined, s));
  if (arrayEquals(fixed, fnBody.statements)) {
    return fnBody;
  }
  return new Shift.FunctionBody({ directives: fnBody.directives, statements: fixed });
}

let booleanBinOps = ['==', '!=', '===', '!==', '<', '<=', '>', '>=', 'in', 'instanceof'];
function returnsBoolean(expr) {
  return expr.type === 'LiteralBooleanExpression'
    || expr.type === 'UnaryExpression' && expr.operator === '!'
    || expr.type === 'BinaryExpression' && booleanBinOps.includes(expr.operator)
    || expr.type === 'BinaryExpression' && (expr.operator === '&&' || expr.operator === '||') && returnsBoolean(expr.left) && returnsBoolean(expr.right)
    || expr.type === 'BinaryExpression' && expr.operator === ',' && returnsBoolean(expr.right)
    || expr.type === 'ConditionalExpression' && returnsBoolean(expr.consequent) && returnsBoolean(expr.alternate);
}

/*
This function takes an expression like

  a && (b, c, d) && e

and returns an object with three properties:

- prefix, a conjunction of all the clauses before the sequence expression, or `null` if there are none
- seqs, a list of all expressions in the sequence expression save the last
- suffix, a conjuction of the last item in the sequence expression with all the clauses after the sequence expression

If the expression is not a conjunction of clauses at least one of which is a sequence, returns `null`.

If `isBooleanContext` is true, it will additionally require that each clause in the prefix returns a boolean.

In this example, assuming `isBooleanContext` is false, it would return
{
  prefix: a
  seqs: [b, c]
  suffix: d && e
}
*/
function extractSequenceFromConjunction(expr, isBooleanContext) {
  if (expr.type !== 'BinaryExpression' || expr.operator !== '&&') {
    return null;
  }
  const clauses = binExprToExprs(expr);
  for (let i = 0; i < clauses.length; ++i) {
    if (isSequence(clauses[i])) {
      const seqs = binExprToExprs(clauses[i]);
      const last = seqs.pop();
      return {
        prefix: i === 0 ? null : clauses.slice(0, i).reduce((acc, e) => new Shift.BinaryExpression({ left: acc, operator: '&&', right: e })),
        seqs,
        suffix: clauses.slice(i + 1).reduce((acc, e) => new Shift.BinaryExpression({ left: acc, operator: '&&', right: e }), last),
      };
    }
    if (!isBooleanContext && !returnsBoolean(clauses[i])) {
      break;
    }
  }
  return null;
}

function fixStatementList(statements) {
  // strip empty statements
  // turn sequence expressions in statement position into multiple statements
  // turn variable declarations with multiple declarators into multiple statements
  // for (var a, b, c;;); -> var a; var b; for (var c;;);
  const o = [];
  for (const s of statements) {
    switch (s.type) {
      case 'EmptyStatement':
        break;
      case 'TryCatchStatement':
        if (s.body.statements.length === 0) {
          o.push(new Shift.IfStatement({ test: new Shift.LiteralBooleanExpression({ value: false }), consequent: new Shift.BlockStatement({ block: s.catchClause.body }), alternate: null }));
        } else {
          o.push(s);
        }
        break;
      case 'ExpressionStatement':
        if (isSequence(s.expression)) {
          o.push(...binExprToExprs(s.expression).map(e => new Shift.ExpressionStatement({ expression: e })));
        } else if (inlinable.includes(s.expression.type) || s.expression.type === 'ThisExpression' || s.expression.type === 'FunctionExpression') { // TODO local IdentifierExpressions
          continue;
        } else if (s.expression.type === 'UnaryExpression' && s.expression.operator === 'void') {
          if (inlinable.includes(s.expression.operand.type)) {
            continue;
          }
          o.push(new Shift.ExpressionStatement({ expression: s.expression.operand }));
        } else {
          o.push(s);
        }
        break;
      case 'ThrowStatement':
        if (isSequence(s.expression)) {
          const exprs = binExprToExprs(s.expression);
          const last = exprs.pop();
          o.push(...exprs.map(e => new Shift.ExpressionStatement({ expression: e })));
          o.push(new Shift.ThrowStatement({ expression: last }));
        } else {
          o.push(s);
        }
        break;
      case 'ReturnStatement':
        if (s.expression === null) {
          o.push(s);
        } else if (isSequence(s.expression)) {
          const exprs = binExprToExprs(s.expression);
          const last = exprs.pop();
          o.push(...exprs.map(e => new Shift.ExpressionStatement({ expression: e })));
          o.push(new Shift.ReturnStatement({ expression: last }));
        } else if (s.expression.type === 'ConditionalExpression') {
          const consequent = new Shift.ReturnStatement({ expression: s.expression.consequent });
          const alternate = new Shift.ReturnStatement({ expression: s.expression.alternate });
          o.push(new Shift.IfStatement({ test: s.expression.test, consequent, alternate }));
        } else if (s.expression.type === 'BinaryExpression' && s.expression.operator === '&&') {
          const extracted = extractSequenceFromConjunction(s.expression, false);
          if (extracted === null) {
            o.push(s);
          } else {
            const { prefix, seqs, suffix } = extracted;
            if (prefix !== null) {
              o.push(new Shift.IfStatement({
                test: negate(prefix, true),
                consequent: new Shift.BlockStatement({ block: new Shift.Block({ statements: [new Shift.ReturnStatement({ expression: new Shift.LiteralBooleanExpression({ value: false }) })] }) }),
                alternate: null,
              }));
            }
            o.push(...seqs.map(e => new Shift.ExpressionStatement({ expression: e })));
            o.push(new Shift.ReturnStatement({ expression: suffix }));
          }
        } else if (s.expression.type === 'UnaryExpression' && s.expression.operator === 'void') {
          o.push(new Shift.ExpressionStatement({ expression: s.expression.operand }));
          o.push(new Shift.ReturnStatement({ expression: null }));
        } else {
          o.push(s);
        }
        // TODO: elsewhere, remove statements after returns (while preserving hoisted declarations)
        break;
      case 'BlockStatement':
        if (s.block.statements.every(x => x.type !== 'FunctionDeclaration' && (x.type !== 'VariableDeclarationStatement' || x.declaration.kind === 'var'))) {
          o.push(...s.block.statements);
        } else {
          o.push(s);
        }
        break;
      case 'IfStatement':
        if (isSequence(s.test)) {
          const exprs = binExprToExprs(s.test);
          const last = exprs.pop();
          o.push(...exprs.map(e => new Shift.ExpressionStatement({ expression: e })));
          o.push(new Shift.IfStatement({ test: last, consequent: s.consequent, alternate: s.alternate }));
        } else if (s.test.type === 'BinaryExpression' && s.test.operator === '&&' && s.alternate == null) {
          const extracted = extractSequenceFromConjunction(s.test, true);
          if (extracted === null) {
            o.push(s);
          } else {
            const { prefix, seqs, suffix } = extracted;
            let newStatements = seqs.map(e => new Shift.ExpressionStatement({ expression: e }));
            newStatements.push(new Shift.IfStatement({
              test: suffix,
              consequent: s.consequent,
              alternate: null,
            }));
            if (prefix === null) {
              o.push(...newStatements);
            } else {
              o.push(new Shift.IfStatement({
                test: prefix,
                consequent: new Shift.BlockStatement({ block: new Shift.Block({ statements: newStatements }) }),
                alternate: null,
              }));
            }
          }
        } else {
          o.push(s);
        }
        break;
      case 'VariableDeclarationStatement':
        if (s.declaration.declarators.length > 1) {
          o.push(...declaratorsToDeclarationStatements(s.declaration.kind, s.declaration.declarators));
        } else if (isSequence(s.declaration.declarators[0].init)) {
          let originalDeclarator = s.declaration.declarators[0];
          // Yes, these steps could be combined, but /shrug
          const exprs = binExprToExprs(originalDeclarator.init);
          const last = exprs.pop();
          o.push(...exprs.map(e => new Shift.ExpressionStatement({ expression: e })));
          const declarator = new Shift.VariableDeclarator({ binding: originalDeclarator.binding, init: last });
          const declaration = new Shift.VariableDeclaration({ kind: s.declaration.kind, declarators: [declarator] });
          o.push(new Shift.VariableDeclarationStatement({ declaration }));
        } else {
          o.push(s);
        }
        break;
      case 'ForStatement':
        if (s.init != null) {
          if (s.init.type === 'VariableDeclaration' && s.init.declarators.length > 1) {
            const declarators = [...s.init.declarators];
            const finalDeclarator = declarators.pop();
            const newDeclaration = new Shift.VariableDeclaration({ kind: s.init.kind, declarators: [finalDeclarator] });
            o.push(...declaratorsToDeclarationStatements(s.init.kind, declarators));
            o.push(new Shift.ForStatement({ init: newDeclaration, test: s.test, update: s.update, body: s.body }));
          } else if (isSequence(s.init)) {
            const exprs = binExprToExprs(s.init);
            const last = exprs.pop();
            o.push(...exprs.map(e => new Shift.ExpressionStatement({ expression: e })));
            o.push(new Shift.ForStatement({ init: last, test: s.test, update: s.update, body: s.body }));
          } else {
            o.push(s);
          }
        }
        break;
      default:
        o.push(s);
    }
  }

  if (arrayEquals(o, statements)) {
    return statements;
  }
  return o;
}


function arrayEquals(a, b) {
  return a.length === b.length && a.every((v, i) => v === b[i]);
}

function hoistFunctionDeclarations(statements) {
  const decls = [];
  const nonDecls = [];
  for (const statement of statements) {
    if (statement.type === 'FunctionDeclaration') {
      decls.push(statement);
    } else {
      nonDecls.push(statement);
    }
  }
  const o = decls.concat(nonDecls);
  if (arrayEquals(o, statements)) {
    return statements;
  }
  return o;
}

class Cleanup extends reducer.LazyCloneReducer {
  reduceBlock(node, { statements }) {
    return super.reduceBlock(node, { statements: fixStatementList(statements) });
  }

  reduceSwitchCase(node, { test, consequent }) {
    return super.reduceSwitchCase(node, { test, consequent: fixStatementList(consequent) });
  }

  reduceSwitchDefault(node, { consequent }) {
    return super.reduceSwitchDefault(node, { consequent: fixStatementList(consequent) });
  }

  reduceFunctionBody(node, { directives, statements }) {
    statements = hoistFunctionDeclarations(fixStatementList(statements));
    if (directives.length === 0 && statements.length === 1 && (statements[0].type === 'ExpressionStatement' || statements[0].type === 'ReturnStatement') && statements[0].expression != null && statements[0].expression.type === 'CallExpression' && statements[0].expression.arguments.length === 0) {
      const callee = statements[0].expression.callee;
      if (callee.type === 'FunctionExpression' && callee.name === null && callee.params.items.length === 0 && callee.params.rest === null && !functionContainsWeirdness(callee)) {
        return statements[0].type === 'ExpressionStatement' ? makeReturnsUndefined(callee.body) : callee.body;
      }
    }
    if (statements.length > 0 && statements[statements.length - 1].type === 'ReturnStatement' && statements[statements.length - 1].expression == null) {
      statements = statements.slice(0, -1);
    }
    return super.reduceFunctionBody(node, { directives, statements });
  }

  reduceScript(node, { directives, statements }) {
    return super.reduceScript(node, { directives, statements: fixStatementList(statements) });
  }

  reduceUnaryExpression(node, { operand }) {
    if (node.operator === '!') {
      const negated = negate(operand, false, false);
      if (negated) {
        return negated;
      }
    }
    return super.reduceUnaryExpression(node, { operand });
  }

  reduceBinaryExpression(node, { left, right }) {
    // 1 == a -> a == 1
    if (['==', '===', '!=', '!=='].includes(node.operator) && isConstant(left) && !isConstant(right)) {
      return new Shift.BinaryExpression({ left: right, operator: node.operator, right: left });
    }
    if (node.operator === ',' && inlinable.includes(left.type)) {
      return right;
    }
    return super.reduceBinaryExpression(node, { left, right });
  }

  reduceExpressionStatement(node, { expression }) {
    if (expression.type === 'ConditionalExpression') {
      return new Shift.IfStatement({ test: expression.test, consequent: new Shift.ExpressionStatement({ expression: expression.consequent }), alternate: new Shift.ExpressionStatement({ expression: expression.alternate }) });
    } else if (expression.type === 'BinaryExpression' && expression.operator === '&&') {
      return new Shift.IfStatement({ test: expression.left, consequent: new Shift.ExpressionStatement({ expression: expression.right }), alternate: null });
    } else if (expression.type === 'BinaryExpression' && expression.operator === '||') {
      return new Shift.IfStatement({ test: new Shift.UnaryExpression({ operator: '!', operand: expression.left }), consequent: new Shift.ExpressionStatement({ expression: expression.right }), alternate: null });
    } else if (expression.type === 'UnaryExpression' && expression.operator === '!') {
      return new Shift.ExpressionStatement({ expression: expression.operand });
    }
    return super.reduceExpressionStatement(node, { expression });
  }

  reduceIfStatement(node, { test, consequent, alternate }) {
    if (test.type === 'UnaryExpression' && test.operator === '!') {
      test = negate(test.operand, true, false) || test;
    }
    if (test.type === 'BinaryExpression' && (test.operator === '!=' || test.operator === '!==') && alternate != null) {
      test = negate(test, true);
      [consequent, alternate] = [alternate, consequent];
    }
    if (consequent.type !== 'BlockStatement') {
      consequent = makeBlock(consequent);
    }
    if (alternate != null) {
      if (alternate.type !== 'BlockStatement' && alternate.type !== 'IfStatement') {
        alternate = makeBlock(alternate);
      } else if (alternate.type === 'BlockStatement' && alternate.block.statements.length === 1 && alternate.block.statements[0].type === 'IfStatement') {
        alternate = alternate.block.statements[0];
      }
      if (alternate.type === 'BlockStatement' && alternate.block.statements.length === 0) {
        alternate = null;
      }
    }
    return super.reduceIfStatement(node, { test, consequent, alternate });
  }

  reduceConditionalExpression(node, { test, consequent, alternate }) {
    if (test.type === 'UnaryExpression' && test.operator === '!') {
      test = negate(test.operand, true, false) || test;
    }
    return super.reduceConditionalExpression(node, { test, consequent, alternate });
  }

  reduceForStatement(node, { init, test, update, body }) {
    if (body.type !== 'BlockStatement') {
      body = makeBlock(body);
    }
    if (init == null && test != null && update == null) {
      return new Shift.WhileStatement({ test, body });
    }
    return super.reduceForStatement(node, { init, test, update, body });
  }

  reduceForInStatement(node, { left, right, body }) {
    if (body.type !== 'BlockStatement') {
      body = makeBlock(body);
    }
    return super.reduceForInStatement(node, { left, right, body });
  }

  reduceForOfStatement(node, { left, right, body }) {
    if (body.type !== 'BlockStatement') {
      body = makeBlock(body);
    }
    return super.reduceForOfStatement(node, { left, right, body });
  }

  reduceWhileStatement(node, { test, body }) {
    if (body.type !== 'BlockStatement') {
      body = makeBlock(body);
    }
    return super.reduceWhileStatement(node, { test, body });
  }

  reduceDoWhileStatement(node, { body, test }) {
    if (body.type !== 'BlockStatement') {
      body = makeBlock(body);
    }
    return super.reduceDoWhileStatement(node, { body, test });
  }

  reduceComputedMemberAssignmentTarget(node, { object, expression }) {
    if (expression.type === 'LiteralStringExpression' && esutils.keyword.isIdentifierNameES6(expression.value)) {
      return new Shift.StaticMemberAssignmentTarget({ object, property: expression.value });
    }
    return super.reduceComputedMemberAssignmentTarget(node, { object, expression });
  }

  reduceComputedMemberExpression(node, { object, expression }) {
    if (expression.type === 'LiteralStringExpression' && esutils.keyword.isIdentifierNameES6(expression.value)) {
      return new Shift.StaticMemberExpression({ object, property: expression.value });
    }
    return super.reduceComputedMemberExpression(node, { object, expression });
  }

  reduceCallExpression(node, { callee, arguments: _arguments }) {
    if (callee.type === 'FunctionExpression' && !callee.isGenerator && !functionContainsWeirdness(callee)) {
      if (_arguments.length === 0 && callee.params.rest === null && callee.params.items.length === 0 && callee.body.directives.length === 0 && callee.body.statements.length <= 1) {
        // turn iifes with very simple bodies into expressions with no calls
        if (callee.body.statements.length === 0) {
          return new Shift.UnaryExpression({ operator: 'void', operand: new Shift.LiteralNullExpression });
        }
        const statement = callee.body.statements[0];
        if (statement.type === 'ReturnStatement') {
          return statement.expression;
        }
        if (statement.type === 'ExpressionStatement') {
          return new Shift.BinaryExpression({ left: statement.expression, operator: ',', right: new Shift.UnaryExpression({ operator: 'void', operand: new Shift.LiteralNullExpression }) }); // `(expr, void 0)`
        }
      }
    }
    return super.reduceCallExpression(node, { callee, arguments: _arguments });
  }
}


const cleaner = new Cleanup;

module.exports = function cleanup(ast) {
  return reducer.default(cleaner, ast);
};


================================================
FILE: src/transforms/unsafe/remove-unused.js
================================================
'use strict';

// Remove unused variables and object properties which are initialized to constants.

const scope = require('shift-scope');
const reducer = require('shift-reducer');
const Shift = require('shift-ast/checked');

const getParents = require('../../helpers/parents');
const inlinable = require('../../helpers/inlinable');


function isOnlyWritten(node, parents, lookup) {
  if (node.type !== 'AssignmentTargetIdentifier') {
    return false;
  }
  const vs = lookup.lookup(node);
  if (vs.length === 1 && lookup.scope.variableList.indexOf(vs[0]) === -1) {
    const reads = vs[0].references.filter(r => r.accessibility.isRead);

    return reads.length === 0 || reads.every(r => {
      if (!r.accessibility.isWrite) {
        return false;
      }
      const parent = parents.get(r.node);
      if (parent == null || !(parent.type === 'CompoundAssignmentExpression' || parent.type === 'UpdateExpression')) {
        return false;
      }

      const gp = parents.get(parent);
      return gp.type === 'ExpressionStatement';
    });
  }
  return false;
}

module.exports = function removeUnused(ast) {
  const globalScope = scope.default(ast);
  const lookup = new scope.ScopeLookup(globalScope);
  const parents = getParents(ast);

  class RemoveUnused extends reducer.LazyCloneReducer {
    reduceVariableDeclarationStatement(node, { declaration }) {
      // This strips declarations of variables initialized to constants if those variables are never referred to.
      const declarators = declaration.declarators.filter((d, i) => {
        const oldD = node.declaration.declarators[i];
        if (d.binding.type !== 'BindingIdentifier' || d.init == null || !(
          inlinable.includes(d.init.type)
          || d.init.type === 'FunctionExpression'
          || d.init.type === 'ObjectExpression' && d.init.properties.length === 0
          || d.init.type === 'ArrayExpression' && d.init.elements.every(e => inlinable.includes(e.type))
        )) return true;
        const v = lookup.lookup(oldD.binding)[0];
        if (v.declarations.length !== 1 || lookup.scope.variableList.includes(v)) return true;
        return v.references.length !== 1;
      });
      if (declarators.length === 0) {
        return new Shift.EmptyStatement;
      } else if (declarators.length === 1) {
        const binding = declarators[0].binding;
        if (binding.type === 'BindingIdentifier') {
          const v = lookup.lookup(binding)[0];
          if (v.references.every(ref => ref.node === binding) && !lookup.scope.variableList.includes(v)) {
            if (declarators[0].init === null) {
              return new Shift.EmptyStatement;
            }
            return new Shift.ExpressionStatement({ expression: declarators[0].init });
          }
        }
      }

      if (declarators.length === declaration.declarators.length) {
        return super.reduceVariableDeclarationStatement(node, { declaration });
      }

      return new Shift.VariableDeclarationStatement({ declaration: new Shift.VariableDeclaration({ kind: declaration.kind, declarators }) });
    }

    reduceVariableDeclarator(node, { binding, init }) {
      // This strips properties from object literals used to initialize variables provided that
      // a.) no one ever refers to that variable except to read a static property of it,
      // b.) no one ever tries to read that property, and
      // c.) the object contains only data properties.
      // TODO make this safe by asserting that all properties ever referred to are present on the object (so they never go up to Object.prototype)
      if (init !== null && init.type === 'ObjectExpression' && init.properties.every(p => p.type === 'DataProperty')) {
        const v = lookup.lookup(node.binding)[0];
        const referencedNames = new Set;
        if (v.references.every(r => {
          if (r.node === node.binding) return true; // We don't care about the declaration itself.
          const parent = parents.get(r.node);
          if (parent.type !== 'StaticMemberExpression') return false;
          referencedNames.add(parent.property);
          return true;
        })) {
          const properties = init.properties.filter(p => {
            return !(inlinable.includes(p.expression.type) || p.expression.type === 'FunctionExpression') || p.name.type !== 'StaticPropertyName' || referencedNames.has(p.name.value);
          });
          if (properties.length === init.properties.length) {
            return super.reduceVariableDeclarator(node, { binding, init });
          }
          const obj = new Shift.ObjectExpression({ properties });
          return new Shift.VariableDeclarator({ binding, init: obj });
        }
      }
      return super.reduceVariableDeclarator(node, { binding, init });
    }

    reduceAssignmentExpression(node, { binding, expression }) {
      if (isOnlyWritten(node.binding, parents, lookup)) {
        return expression;
      }
      return super.reduceAssignmentExpression(node, { binding, expression });
    }

    reduceCompoundAssignmentExpression(node, { binding, expression }) {
      if (isOnlyWritten(node.binding, parents, lookup)) {
        return expression;
      }
      return super.reduceCompoundAssignmentExpression(node, { binding, expression });
    }
  }

  return reducer.default(new RemoveUnused, ast);
};


================================================
FILE: src/transforms/wildly-unsafe/inline.js
================================================
'use strict';

// Inline constant primitive variables, constant primitive object properties, and constant object properties which are particularly trivial functions.

const shiftScope = require('shift-scope');
const reducer = require('shift-reducer');
const Shift = require('shift-ast/checked');

const getParents = require('../../helpers/parents');
const inlinable = require('../../helpers/inlinable');


module.exports = function inline(ast) {

  const globalScope = shiftScope.default(ast);
  const lookup = new shiftScope.ScopeLookup(globalScope);
  const parents = getParents(ast);

  function findScopeForNode(node, scope = globalScope) {
    // TODO this should live elsewhere
    if (scope.astNode === node) return scope;
    for (let child of scope.children) {
      const r = findScopeForNode(node, child);
      if (r !== null) return r;
    }
    return null;
  }

  function isConstantInitializedVariable(v) {
    if (!isConstantVariable(v)) {
      return false;
    }
    const parent = parents.get(v.declarations[0].node);
    if (parent.type !== 'VariableDeclarator') {
      return false;
    }
    return parent.init !== null;
  }

  function isConstantVariable(v) {
    // TODO this also needs to check that use-before-def is impossible
    if (v.declarations.length !== 1) return false;
    const binding = v.declarations[0].node;
    const parent = parents.get(binding);
    if (parent.type !== 'VariableDeclarator' && parent.type !== 'FormalParameters') return false;
    if (v.references.some(r => r.accessibility.isWrite && r.node !== binding)) return false;
    return true;
  }

  function getConstantObjectVariableObject(_var) {
    // TODO for this to be actually correct we'd also need to check that none of the properties of the object are functions binding 'this'
    if (!isConstantInitializedVariable(_var)) return null;
    const binding = _var.declarations[0].node;
    const parent = parents.get(binding);
    if (parent.init == null) return null;
    if (parent.init.type === 'ObjectExpression' || parent.init.type === 'ArrayExpression') {
      if (_var.references.some(r => {
        const rparent = parents.get(r.node);
        return rparent.type === 'StaticMemberAssignmentTarget' || rparent.type === 'ComputedMemberAssignmentTarget' && rparent.object === r.node;
      })) return null;
      const obj = parent.init;

      if (obj.type === 'ObjectExpression') {
        return new Map(obj.properties.filter(p => p.type === 'DataProperty' && p.name.type === 'StaticPropertyName').map(p => [p.name.value, p.expression])); // TODO could include methods, in principle
      } else if (obj.type === 'ArrayExpression') {
        return new Map(obj.elements.map((v, i) => [i, v]));
      }
      throw 'not reached;';

    } else {
      return null;
    }
  }

  function findStatementParent(node) {
    while (!/Statement/.test(node.type) && node.type !== 'FunctionDeclaration') {
      // eslint-disable-next-line no-param-reassign
      node = parents.get(node);
    }
    return node;
  }


  function getInlining(node) {
    const vars = lookup.lookup(node);
    if (vars.length !== 1) return null;
    const v = vars[0];
    if (!isConstantInitializedVariable(v)) return null;
    const init = parents.get(v.declarations[0].node).init;
    if (init.type === 'IdentifierExpression') {
      const indirectVars = lookup.lookup(init);
      if (indirectVars.length === 1 && isConstantVariable(indirectVars[0])) {
        return new Shift.IdentifierExpression(init);
      }
    }
    if (!inlinable.includes(init.type)) return null;

    return { ...init };
  }


  function getTriviallyInlineableFunction(f, arglen) {
    if (f.type !== 'FunctionExpression') return null;
    if (f.params.items.length !== arglen) return null;
    if (f.body.directives.length > 0) return null;
    if (f.body.statements.length !== 1) return null;
    if (f.body.statements[0].type !== 'ReturnStatement') return null;
    if (f.body.statements[0].expression.type !== 'BinaryExpression') return null;
    const expr = f.body.statements[0].expression;

    if (arglen === 2) {
      if (expr.left.type !== 'IdentifierExpression' || lookup.lookup(expr.left)[0] !== lookup.lookup(f.params.items[0])[0]) return null;
      if (expr.right.type !== 'IdentifierExpression' || lookup.lookup(expr.right)[0] !== lookup.lookup(f.params.items[1])[0]) return null;
      return (left, right) => new Shift.BinaryExpression({ left, operator: expr.operator, right });
    } else if (arglen === 3) {
      if (expr.left.type !== 'BinaryExpression') return null;
      const expr2 = expr.left;
      if (expr2.left.type !== 'IdentifierExpression' || lookup.lookup(expr2.left)[0] !== lookup.lookup(f.params.items[0])[0]) return null;
      if (expr2.right.type !== 'IdentifierExpression' || lookup.lookup(expr2.right)[0] !== lookup.lookup(f.params.items[1])[0]) return null;
      if (expr.right.type !== 'IdentifierExpression' || lookup.lookup(expr.right)[0] !== lookup.lookup(f.params.items[2])[0]) return null;

      return (a, b, right) => new Shift.BinaryExpression({ left: new Shift.BinaryExpression({ left: a, operator: expr2.operator, right: b }), operator: expr.operator, right });
    }
    return null;
  }

  class InliningReducer extends reducer.LazyCloneReducer {
    reduceExpressionStatement(node, { expression }) {
      if (expression.type === 'IdentifierExpression') {
        return new Shift.EmptyStatement;
      }
      return super.reduceExpressionStatement(node, { expression });
    }

    reduceCallExpression(node, { callee, arguments: _arguments }) {
      if (callee.type === 'StaticMemberExpression' && callee.object.type === 'IdentifierExpression' && (_arguments.length === 2 || _arguments.length === 3)) {
        const vs = lookup.lookup(node.callee.object);
        if (vs.length === 1) {
          const obj = getConstantObjectVariableObject(vs[0]);
          if (obj !== null && obj.has(callee.property)) {
            const val = obj.get(callee.property);
            const replacer = getTriviallyInlineableFunction(val, _arguments.length);
            if (replacer !== null) {
              return replacer(..._arguments);
            }
          }
        }
      } else if (callee.type === 'IdentifierExpression') {
        const vs = lookup.lookup(node.callee);
        if (vs.length === 1 && isConstantInitializedVariable(vs[0]) && lookup.scope.variableList.indexOf(vs[0]) === -1) {
          const v = vs[0];
          const decl = parents.get(v.declarations[0].node);
          if (decl.init.type === 'FunctionExpression') {
            const f = decl.init;
            let scope = findScopeForNode(f);
            if (scope !== null && scope.through.size === 0) {

              // This is to handle specifically `var x = function (foo) { if (foo == 'bar') { return a; } else { return b; } }; y = x('bar'); z = x('baz'); w = x();`
              if (f.params.items.length === 1 && _arguments.length <= 1) {
                const pv = lookup.lookup(f.params.items[0])[0];
                if (pv.references.length === 1 && f.body.statements.length === 1 && f.body.statements[0].type === 'IfStatement') {
                  const consequent = f.body.statements[0].consequent;
                  const alternate = f.body.statements[0].alternate;
                  if (consequent.type === 'BlockStatement' && consequent.block.statements.length === 1 && consequent.block.statements[0].type === 'ReturnStatement' && alternate.type === 'BlockStatement' && alternate.block.statements.length === 1 && alternate.block.statements[0].type === 'ReturnStatement') {
                    const test = f.body.statements[0].test;
                    if (test.type === 'BinaryExpression' && test.operator.slice(0, 2) === '==' && test.left.type === 'IdentifierExpression' && lookup.lookup(test.left)[0] === pv && inlinable.includes(test.right.type)) {
                      const conditional = new Shift.ConditionalExpression({ test: { ...test }, consequent: consequent.block.statements[0].expression, alternate: alternate.block.statements[0].expression });
                      if (_arguments.length === 1) {
                        conditional.test.left = _arguments[0];
                      } else {
                        conditional.test.left = new Shift.UnaryExpression({ operator: 'void', operand: new Shift.LiteralNumericExpression({ value: 0 }) });
                      }
                      return conditional;
                    }
                  }
                }
              }
            }

            if (v.references.length === 2) {
              // inline functions which are only called once
              const p1 = findStatementParent(v.references[0].node);
              const p2 = findStatementParent(v.references[0].node);
              if (scope.through.size === 0 || parents.get(p1) === parents.get(p2)) {
                // This ensures any through references get resolved the same after inlining
                return new Shift.CallExpression({ callee: reducer.default(new reducer.CloneReducer, f), arguments: _arguments });
              }
            }
          }
        }
      }
      return super.reduceCallExpression(node, { callee, arguments: _arguments });
    }

    reduceIdentifierExpression(node) {
      const inlining = getInlining(node);
      if (inlining !== null) return inlining;
      return super.reduceIdentifierExpression(node);
    }

    reduceComputedMemberExpression(node, { object, expression }) {
      if (node.object.type === 'IdentifierExpression' && expression.type === 'LiteralNumericExpression') {
        const vs = lookup.lookup(node.object);
        if (vs.length === 1) {
          const obj = getConstantObjectVariableObject(vs[0]);
          if (obj !== null && obj.has(expression.value)) {
            const val = obj.get(expression.value);
            if (inlinable.includes(val.type)) {
              return new Shift[val.type](val);
            }
          }
        }
      }
      return super.reduceComputedMemberExpression(node, { object, expression });// new Shift.ComputedMemberExpression({object, expression});
    }

    reduceStaticMemberExpression(node, { object }) {
      if (node.object.type === 'IdentifierExpression') {
        const vs = lookup.lookup(node.object);
        if (vs.length === 1) {
          const obj = getConstantObjectVariableObject(vs[0]);
          if (obj !== null && obj.has(node.property)) {
            const val = obj.get(node.property);
            if (inlinable.includes(val.type)) {
              return { ...val };
            }
          }
        }
      }
      return super.reduceStaticMemberExpression(node, { object });
    }
  }

  return reducer.default(new InliningReducer, ast);
};


================================================
FILE: src/transforms/wildly-unsafe/partial-evaluate.js
================================================
'use strict';

const reducer = require('shift-reducer');
const Shift = require('shift-ast/checked');
const shiftScope = require('shift-scope');

const getParents = require('../../helpers/parents');

const none = {};

function constantToNode(c) {
  switch (typeof c) {
    case 'undefined':
      return new Shift.UnaryExpression({ operator: 'void', operand: new Shift.LiteralNumericExpression({ value: 0 }) });
    case 'number':
      return new Shift.LiteralNumericExpression({ value: c });
    case 'string':
      return new Shift.LiteralStringExpression({ value: c });
    case 'boolean':
      return new Shift.LiteralBooleanExpression({ value: c });
    case 'object':
      if (Array.isArray(c)) {
        const elements = c.map(constantToNode);
        return new Shift.ArrayExpression({ elements });
      }
      // falls through
    default:
      throw new Error('cannot handle ' + typeof c);
  }
}

const globalFunctions = {
  decodeURI,
  decodeURIComponent,
  unescape,
  parseInt,
  parseFloat,
};

const isNonMutatingArrayMethod = p => ['slice', 'forEach', 'map', 'filter', 'reduce', 'indexOf'].includes(p);

module.exports = function partialEvaluate(ast) {

  const parents = getParents(ast);
  const globalScope = shiftScope.default(ast);
  const lookup = new shiftScope.ScopeLookup(globalScope);

  function getStaticInit(node) {
    // This is unsafe in that it assumes no use-before-def
    const vs = lookup.lookup(node);
    if (vs && vs.length === 1) {
      const v = vs[0];
      if (v.declarations.length === 1) {
        const binding = v.declarations[0].node;
        const parent = parents.get(binding);
        if (parent.type === 'VariableDeclarator' && parent.init !== null && v.references.every(r => !(r.accessibility.isWrite && r.node !== binding))) {
          return { initNode: parent.init, variable: v };
        }
      }
    }
    return { initNode: null };
  }

  function evaluateToNode(node) {
    const value = evaluate(node);
    if (value !== none && (typeof value !== 'object' || value === null) && typeof value !== 'function') {
      const rv = constantToNode(value);
      if (rv.type === 'UnaryExpression' && rv.type === node.type && rv.operator === 'void' && rv.operator === node.operator && rv.operand.type === 'LiteralNumericExpression' && rv.operand.type === node.operand.type && rv.operand.value === node.operand.value) {
        return node;
      }
      return rv;
    }
    return node;
  }


  const seen = new WeakMap;
  function evaluate(node) {
    if (seen.has(node)) {
      return seen.get(node);
    }
    seen.set(node, none);
    const out = evaluateCore(node);
    if (out !== none) {
      seen.set(node, out);
    }
    return out;
  }
  function evaluateCore(node) {
    switch (node.type) {
      case 'ArrayExpression': {
        const evaluated = node.elements.map(e => e === null ? void 0 : evaluate(e));
        if (evaluated.every(v => v !== none)) {
          return evaluated;
        }
        break;
      }
      case 'LiteralNumericExpression':
      case 'LiteralStringExpression':
      case 'LiteralBooleanExpression':
        return node.value;
      case 'LiteralRegExpExpression':
        // Not actually safe, since regexps have identity
        if (!node.global && !node.ignoreCase && !node.multiLine && !node.sticky && !node.unicode) {
          return new RegExp(node.pattern);
        }
        break;
      case 'UnaryExpression': {
        const operand = evaluate(node.operand);
        if (operand !== none) {
          switch (node.operator) {
            case '+':
              return +operand;
            case 'void':
              return void 0;
            case '-':
              return -operand;
            case '!':
              return !operand;
            case '~':
              return ~operand;
            case 'typeof':
              return typeof operand;
            default:
              throw new Error('useful unary operator: ' + node.operator + ' ' + operand);
          }
        }
        break;
      }
      case 'BinaryExpression': {
        const left = evaluate(node.left);
        const right = evaluate(node.right);
        if (left !== none && right !== none) {
          switch (node.operator) {
            case '===':
              return left === right;
            case '!==':
              return left !== right;
            case '==':
              // eslint-disable-next-line eqeqeq
              return left == right;
            case '!=':
              // eslint-disable-next-line eqeqeq
              return left != right;
            case '>':
              return left > right;
            case '<':
              return left < right;
            case '>=':
              return left >= right;
            case '<=':
              return left <= right;
            case '+':
              return left + right;
            case '-':
              return left - right;
            case '*':
              return left * right;
            case '/':
              return left / right;
            case '%':
              return left % right;
            case '||':
              return left || right;
            case '&&':
              return left && right;
            case '<<':
              return left << right;
            case '>>':
              return left >> right;
            case '>>>':
              return left >>> right;
            case '|':
              return left | right;
            case '&':
              return left & right;
            case '^':
              return left ^ right;
            case 'in':
              // If this happens, something may have gone wrong.
              break;
            default:
              throw new Error('useful binary operator: ' + node.operator + ' ' + left + ' ' + right);
          }
        }
        break;
      }
      case 'IdentifierExpression': {
        if (node.name in globalFunctions) {
          const vs = lookup.lookup(node);
          if (vs.length === 1) {
            const refs = vs[0].references;
            if (vs[0].declarations.length === 0 && !refs.some(r => r.accessibility.isWrite)) {
              return globalFunctions[node.name];
            }
          }
        }

        // TODO this isn't actually safe, for several reasons
        const { initNode, variable } = getStaticInit(node);
        if (initNode !== null) {
          const val = evaluate(initNode);
          if (val !== none) {
            if (Array.isArray(val)) {
              for (let r of variable.references) {
                let p = parents.get(r.node);
                if (p.type === 'StaticMemberExpression') {
                  if (!(isNonMutatingArrayMethod(p.property) || p.property === 'length')) {
                    return none;
                  }
                } else if (p.type === 'StaticMemberAssignmentTarget' || p.type === 'ComputedMemberAssignmentTarget') {
                  return none;
                } else if (p.type === 'ComputedMemberExpression') {
                  const gp = parents.get(p);
                  if (gp.type === 'CallExpression' && gp.callee === p) {
                    return none;
                  }
                }
              }
            }
            return val;
          }
        }
        break;
      }
      case 'CallExpression': {
        // TODO factor these cases better
        const argVals = node.arguments.map(evaluate);
        if (argVals.every(v => v !== none)) {
          if (node.callee.type === 'StaticMemberExpression') {

            // TODO factor this and similar cases out to something else
            if (node.callee.object.type === 'IdentifierExpression' && node.callee.object.name === 'String' && node.callee.property === 'fromCharCode' && node.arguments.length === 1 && node.arguments[0].type === 'LiteralNumericExpression') {
              return String.fromCharCode(node.arguments[0].value);
            }


            const objVal = evaluate(node.callee.object);
            if (objVal !== none) {
              if (typeof objVal !== 'object') {
                if (typeof objVal !== 'function') {
                  return objVal[node.callee.property](...argVals);
                }
              } else if (Array.isArray(objVal) && isNonMutatingArrayMethod(node.callee.property)) {
                return objVal[node.callee.property](...argVals);
              }
            }
          }

          const calleeVal = evaluate(node.callee);
          if (typeof calleeVal === 'function') {
            let c = calleeVal(...argVals);
            return c;
          }
        }
        break;
      }
      case 'StaticMemberExpression': {
        if (node.property === 'length' && node.object.type === 'ArrayExpression') {
          return node.object.elements.length;
        }
        return evaluateStaticProperty(node.object, node.property);
      }
    }
    return none;
  }

  function evaluateStaticProperty(object, property) {
    // TODO this has a lot of overlap with inline.js
    // this interacts poorly with getters
    const objVal = evaluate(object);
    if (objVal !== none && typeof objVal !== 'object' && typeof objVal !== 'function') {
      if (property in Object(objVal)) {
        return objVal[property];
      }
      return none;
    }
    if (object.type === 'IdentifierExpression') {
      const { initNode, variable } = getStaticInit(object); // TODO this is not sufficient; we also need to check it doesn't leak
      if (initNode !== null) {
        const leaks = variable.references.some(r => {
          if (r.accessibility.isRead) {
            const parent = parents.get(r.node);
            return parent.type !== 'StaticMemberExpression' && parent.type !== 'ComputedMemberAssignmentTarget' && parent.type !== 'StaticMemberAssignmentTarget' && parent.type !== 'ComputedMemberAssignmentTarget';
          }
          return false;
        });
        if (!leaks && (initNode.type === 'FunctionExpression' || initNode.type === 'ObjectExpression' && initNode.properties.every(p => p.type === 'DataProperty' && p.name.type === 'StaticPropertyName'))) {
          const hasComputedWrite = variable.references.some(r => {
            const parent = parents.get(r.node);
            return parent.type === 'ComputedMemberAssignmentTarget' && parent.object === r.node;
          });
          if (!hasComputedWrite) {
            const hasProperty = initNode.type === 'ObjectExpression' && initNode.properties.filter(p => p.name.value === property).length === 1;
            const propertyWrites = variable.references.filter(r => {
              const parent = parents.get(r.node);
              return parent.type === 'StaticMemberAssignmentTarget' && parent.property === property;
            });
            if (!hasProperty && propertyWrites.length === 1) {
              const gp = parents.get(parents.get(propertyWrites[0].node));
              if (gp.type === 'AssignmentExpression') {
                return evaluate(gp.expression);
              }
            } else if (hasProperty && propertyWrites.length === 0) {
              for (let p of initNode.properties) {
                if (p.name.value === property) {
                  return evaluate(p.expression);
                }
              }
            }
          }
        }
      }
    }
    return none;
  }

  class Evaluate extends reducer.LazyCloneReducer {
    reduceUnaryExpression(node, { operand }) {
      return evaluateToNode(super.reduceUnaryExpression(node, { operand }));
    }

    reduceBinaryExpression(node, { left, right }) {
      return evaluateToNode(super.reduceBinaryExpression(node, { left, right }));
    }

    reduceCallExpression(node, { callee, arguments: _arguments }) {
      return evaluateToNode(super.reduceCallExpression(node, { callee, arguments: _arguments }));
    }

    reduceStaticMemberExpression(node, { object }) {
      return evaluateToNode(super.reduceStaticMemberExpression(node, { object }));
    }

    reduceIdentifierExpression(node) {
      return evaluateToNode(node);
    }

    reduceComputedMemberExpression(node, { object, expression }) {
      const clone = super.reduceComputedMemberExpression(node, { object, expression });
      const parent = parents.get(node);
      if (parent.type !== 'CallExpression' || parent.callee !== node) {
        if (object.type === 'ArrayExpression' || object.type === 'LiteralStringExpression') {
          const isArray = object.type === 'ArrayExpression';
          const index = evaluate(expression);
          if (index !== none) {
            if (index === 'length') {
              return constantToNode((isArray ? object.elements : object.value).length);
            }
            const coerced = +('' + index);
            if (!Number.isNaN(coerced) && Math.floor(coerced) === coerced && coerced.toString() === '' + index) {
              if (coerced >= (isArray ? object.elements : object.value).length) {
                return constantToNode(void 0);
              }
              return isArray ? object.elements[index] : constantToNode(object.value[index]);
            }
          }
        }
      }
      return clone;
    }

    reduceConditionalExpression(node, { test, consequent, alternate }) {
      const clone = super.reduceConditionalExpression(node, { test, consequent, alternate });
      const testValue = evaluate(clone.test);
      if (testValue !== none) {
        return testValue ? consequent : alternate;
      }
      return clone;
    }

    reduceIfStatement(node, { test, consequent, alternate }) {
      // Note: this needs to pull var declarations out of the untaken branch
      const clone = super.reduceIfStatement(node, { test, consequent, alternate });
      const testValue = evaluate(clone.test);
      if (testValue !== none) {
        if (testValue) {
          return consequent;
        }
        if (alternate === null) {
          return new Shift.EmptyStatement;
        }
        return alternate;


      }
      return clone;
    }
  }

  return reducer.default(new Evaluate, ast);
};


================================================
FILE: test/snapshots-in/computed-member-to-static.js
================================================
a['b'];
a['b'] = 0;
a[0];
a['0'];

================================================
FILE: test/snapshots-in/expand-expression-statement.js
================================================
foo(), this, void bar(), void 0, new baz;

================================================
FILE: test/snapshots-in/expand-multiple-decl.js
================================================
function f(){
  var a = foo(), b = bar();
  for (var c = foo(), d = bar(); false;);
  return a + b + c + d;
}

================================================
FILE: test/snapshots-in/expand-sequence.js
================================================
if(a(), b()) {
  c();
}
function f(){
  var a = (b(), c);
  return d(), a;
}
throw f(), g;
for((a(), b()); false;);

================================================
FILE: test/snapshots-in/hoist-fns.js
================================================
function f(){
  foo();
  function bar(){}
  return bar;
}

================================================
FILE: test/snapshots-in/if-and-seq.js
================================================
if (a && (b, c) && d) {
  foo();
}

if ((b, c) && d) {
  foo();
}

if (a && (b, c)) {
  foo();
}


================================================
FILE: test/snapshots-in/if-not.js
================================================
if (a !== b) {
  foo();
} else {
  bar();
}

================================================
FILE: test/snapshots-in/indexing.js
================================================
[0][0]();
f([0, 1, 2][1]);
f('abcd'[2]);
f('' + [][0]);
f('abcd'[5]);
f([0, 1, 2].length);
f('abcd'.length);
f([].map);


================================================
FILE: test/snapshots-in/inline-arguments.js
================================================
(function(a, b){ return a + b; })(foo(), bar(), baz());
(function(a, b, c){ return a + b + c; })(foo(), bar());

================================================
FILE: test/snapshots-in/inline-called-once.js
================================================
function f() {
  var x = function(a){ return a + foo(); }
  return x(a);
}

================================================
FILE: test/snapshots-in/inline-constant-object-property.js
================================================
var x = {
  a: 0,
};
y = x.a;


================================================
FILE: test/snapshots-in/inline-function-as-conditional.js
================================================
function f(){

  var x = function (foo) { if (foo == 'bar') return 'a'; else return 'b'; };
  var y = x(a);
  var z = x(b);
  var w = x();
  return y + z + w;
}


================================================
FILE: test/snapshots-in/inline-iife.js
================================================
function f () {
  (function() {
    foo();
  })();

  x = function(){ return 0; }();
  x = function(){ foo(); }();
}


================================================
FILE: test/snapshots-in/inline-trivial-function.js
================================================
function f(){
  var x = {
    p: function (a, b, c) {
      return a + b + c;
    },
  };

  console.log(x.p(foo(), bar(), baz()));  
}


================================================
FILE: test/snapshots-in/make-blocks.js
================================================
if (foo()) bar();
for(;;) bar();
while (0) bar();
for (a in b) bar();
do bar(); while (0);
for (a of b) bar();

================================================
FILE: test/snapshots-in/negate.js
================================================
f(!false);
f(!0);
f(![]);
f(!(a && b));
f(!(a == b));
if (!!a) foo();


================================================
FILE: test/snapshots-in/no-trailing-return-void.js
================================================
function f(){
  foo();
  return;
}

================================================
FILE: test/snapshots-in/partial-evaluate.js
================================================
function f(){
  var a = 1;
  return a + 2 + ['d', 'e'];
}

================================================
FILE: test/snapshots-in/remove-empty-statements.js
================================================
;;


================================================
FILE: test/snapshots-in/remove-empty-try.js
================================================
try{}catch(e){var x;}

================================================
FILE: test/snapshots-in/remove-unused-vars.js
================================================
var x = 0;
function f(){
  var x = foo();
}

================================================
FILE: test/snapshots-in/return-and.js
================================================
function f(){
  return (a = 0, b, c) && d && e;
}

function g(){
  return !a && b === 0 && (c = 0, d, e) && f && g;
}

function h(){
  return !a && b === 0 && (c = 0, d, e);
}

function i(){
  return a && (b, c);
}


================================================
FILE: test/snapshots-in/return-conditional.js
================================================
function f(){
  return foo() ? 0 : 1;
}

================================================
FILE: test/snapshots-in/return-void.js
================================================
function f(){
  if (foo()) {
    return void bar();
  }
}

================================================
FILE: test/snapshots-in/shorthand-if.js
================================================
a ? b() : c();
a && b();
a || c();


================================================
FILE: test/snapshots-in/spread-block.js
================================================
{
  foo();
  {
    bar();
    baz();
  }
  quux();
}


================================================
FILE: test/snapshots-in/statement-position-negation.js
================================================
!d();

================================================
FILE: test/snapshots-in/un-yoda.js
================================================
0 === b;


================================================
FILE: test/snapshots-in/unhoist-var-decls.js
================================================
function f(){
  var a;
  b();
  a = b();
  return a;
}

================================================
FILE: test/snapshots-out/test/snapshots.js.md
================================================
# Snapshot report for `test/snapshots.js`

The actual snapshot is saved in `snapshots.js.snap`.

Generated by [AVA](https://avajs.dev).

## USELESS snapshot: computed-member-to-static.js

> Snapshot 1

    `a['b'];␊
    a['b'] = 0;␊
    a[0];␊
    a['0'];␊
    `

## SAFE snapshot: computed-member-to-static.js

> Snapshot 1

    `a.b;␊
    a.b = 0;␊
    a[0];␊
    a['0'];␊
    `

## MOSTLY_SAFE snapshot: computed-member-to-static.js

> Snapshot 1

    `a.b;␊
    a.b = 0;␊
    a[0];␊
    a['0'];␊
    `

## UNSAFE snapshot: computed-member-to-static.js

> Snapshot 1

    `a.b;␊
    a.b = 0;␊
    a[0];␊
    a['0'];␊
    `

## WILDLY_UNSAFE snapshot: computed-member-to-static.js

> Snapshot 1

    `a.b;␊
    a.b = 0;␊
    a[0];␊
    a['0'];␊
    `

## USELESS snapshot: expand-expression-statement.js

> Snapshot 1

    `foo(), this, void bar(), void 0, new baz();␊
    `

## SAFE snapshot: expand-expression-statement.js

> Snapshot 1

    `foo();␊
    bar();␊
    new baz();␊
    `

## MOSTLY_SAFE snapshot: expand-expression-statement.js

> Snapshot 1

    `foo();␊
    bar();␊
    new baz();␊
    `

## UNSAFE snapshot: expand-expression-statement.js

> Snapshot 1

    `foo();␊
    bar();␊
    new baz();␊
    `

## WILDLY_UNSAFE snapshot: expand-expression-statement.js

> Snapshot 1

    `foo();␊
    bar();␊
    new baz();␊
    `

## USELESS snapshot: expand-multiple-decl.js

> Snapshot 1

    `function f() {␊
      var a = foo(),␊
        b = bar();␊
      for (var c = foo(), d = bar(); false; );␊
      return a + b + c + d;␊
    }␊
    `

## SAFE snapshot: expand-multiple-decl.js

> Snapshot 1

    `function f() {␊
      var a = foo();␊
      var b = bar();␊
      var c = foo();␊
      for (var d = bar(); false; ) {}␊
      return a + b + c + d;␊
    }␊
    `

## MOSTLY_SAFE snapshot: expand-multiple-decl.js

> Snapshot 1

    `function f() {␊
      var a = foo();␊
      var b = bar();␊
      var c = foo();␊
      for (var d = bar(); false; ) {}␊
      return a + b + c + d;␊
    }␊
    `

## UNSAFE snapshot: expand-multiple-decl.js

> Snapshot 1

    `function f() {␊
      var a = foo();␊
      var b = bar();␊
      var c = foo();␊
      for (var d = bar(); false; ) {}␊
      return a + b + c + d;␊
    }␊
    `

## WILDLY_UNSAFE snapshot: expand-multiple-decl.js

> Snapshot 1

    `function f() {␊
      var a = foo();␊
      var b = bar();␊
      var c = foo();␊
      for (var d = bar(); false; ) {}␊
      return a + b + c + d;␊
    }␊
    `

## USELESS snapshot: expand-sequence.js

> Snapshot 1

    `if ((a(), b())) {␊
      c();␊
    }␊
    function f() {␊
      var a = (b(), c);␊
      return d(), a;␊
    }␊
    throw (f(), g);␊
    for (a(), b(); false; );␊
    `

## SAFE snapshot: expand-sequence.js

> Snapshot 1

    `a();␊
    if (b()) {␊
      c();␊
    }␊
    function f() {␊
      b();␊
      var a = c;␊
      d();␊
      return a;␊
    }␊
    f();␊
    throw g;␊
    a();␊
    for (b(); false; ) {}␊
    `

## MOSTLY_SAFE snapshot: expand-sequence.js

> Snapshot 1

    `a();␊
    if (b()) {␊
      c();␊
    }␊
    function f() {␊
      b();␊
      var a = c;␊
      d();␊
      return a;␊
    }␊
    f();␊
    throw g;␊
    a();␊
    for (b(); false; ) {}␊
    `

## UNSAFE snapshot: expand-sequence.js

> Snapshot 1

    `a();␊
    if (b()) {␊
      c();␊
    }␊
    function f() {␊
      b();␊
      var a = c;␊
      d();␊
      return a;␊
    }␊
    f();␊
    throw g;␊
    a();␊
    for (b(); false; ) {}␊
    `

## WILDLY_UNSAFE snapshot: expand-sequence.js

> Snapshot 1

    `a();␊
    if (b()) {␊
      c();␊
    }␊
    function f() {␊
      b();␊
      var a = c;␊
      d();␊
      return a;␊
    }␊
    f();␊
    throw g;␊
    a();␊
    for (b(); false; ) {}␊
    `

## USELESS snapshot: hoist-fns.js

> Snapshot 1

    `function f() {␊
      foo();␊
      function bar() {}␊
      return bar;␊
    }␊
    `

## SAFE snapshot: hoist-fns.js

> Snapshot 1

    `function f() {␊
      function bar() {}␊
      foo();␊
      return bar;␊
    }␊
    `

## MOSTLY_SAFE snapshot: hoist-fns.js

> Snapshot 1

    `function f() {␊
      function bar() {}␊
      foo();␊
      return bar;␊
    }␊
    `

## UNSAFE snapshot: hoist-fns.js

> Snapshot 1

    `function f() {␊
      function bar() {}␊
      foo();␊
      return bar;␊
    }␊
    `

## WILDLY_UNSAFE snapshot: hoist-fns.js

> Snapshot 1

    `function f() {␊
      function bar() {}␊
      foo();␊
      return bar;␊
    }␊
    `

## USELESS snapshot: if-and-seq.js

> Snapshot 1

    `if (a && (b, c) && d) {␊
      foo();␊
    }␊
    if ((b, c) && d) {␊
      foo();␊
    }␊
    if (a && (b, c)) {␊
      foo();␊
    }␊
    `

## SAFE snapshot: if-and-seq.js

> Snapshot 1

    `if (a) {␊
      b;␊
      if (c && d) {␊
        foo();␊
      }␊
    }␊
    b;␊
    if (c && d) {␊
      foo();␊
    }␊
    if (a) {␊
      b;␊
      if (c) {␊
        foo();␊
      }␊
    }␊
    `

## MOSTLY_SAFE snapshot: if-and-seq.js

> Snapshot 1

    `if (a) {␊
      b;␊
      if (c && d) {␊
        foo();␊
      }␊
    }␊
    b;␊
    if (c && d) {␊
      foo();␊
    }␊
    if (a) {␊
      b;␊
      if (c) {␊
        foo();␊
      }␊
    }␊
    `

## UNSAFE snapshot: if-and-seq.js

> Snapshot 1

    `if (a) {␊
      b;␊
      if (c && d) {␊
        foo();␊
      }␊
    }␊
    b;␊
    if (c && d) {␊
      foo();␊
    }␊
    if (a) {␊
      b;␊
      if (c) {␊
        foo();␊
      }␊
    }␊
    `

## WILDLY_UNSAFE snapshot: if-and-seq.js

> Snapshot 1

    `if (a) {␊
      if (c && d) {␊
        foo();␊
      }␊
    }␊
    if (c && d) {␊
      foo();␊
    }␊
    if (a) {␊
      if (c) {␊
        foo();␊
      }␊
    }␊
    `

## USELESS snapshot: if-not.js

> Snapshot 1

    `if (a !== b) {␊
      foo();␊
    } else {␊
      bar();␊
    }␊
    `

## SAFE snapshot: if-not.js

> Snapshot 1

    `if (a === b) {␊
      bar();␊
    } else {␊
      foo();␊
    }␊
    `

## MOSTLY_SAFE snapshot: if-not.js

> Snapshot 1

    `if (a === b) {␊
      bar();␊
    } else {␊
      foo();␊
    }␊
    `

## UNSAFE snapshot: if-not.js

> Snapshot 1

    `if (a === b) {␊
      bar();␊
    } else {␊
      foo();␊
    }␊
    `

## WILDLY_UNSAFE snapshot: if-not.js

> Snapshot 1

    `if (a === b) {␊
      bar();␊
    } else {␊
      foo();␊
    }␊
    `

## USELESS snapshot: indexing.js

> Snapshot 1

    `[0][0]();␊
    f([0, 1, 2][1]);␊
    f('abcd'[2]);␊
    f('' + [][0]);␊
    f('abcd'[5]);␊
    f([0, 1, 2].length);␊
    f('abcd'.length);␊
    f([].map);␊
    `

## SAFE snapshot: indexing.js

> Snapshot 1

    `[0][0]();␊
    f([0, 1, 2][1]);␊
    f('abcd'[2]);␊
    f('' + [][0]);␊
    f('abcd'[5]);␊
    f([0, 1, 2].length);␊
    f('abcd'.length);␊
    f([].map);␊
    `

## MOSTLY_SAFE snapshot: indexing.js

> Snapshot 1

    `[0][0]();␊
    f([0, 1, 2][1]);␊
    f('abcd'[2]);␊
    f('' + [][0]);␊
    f('abcd'[5]);␊
    f([0, 1, 2].length);␊
    f('abcd'.length);␊
    f([].map);␊
    `

## UNSAFE snapshot: indexing.js

> Snapshot 1

    `[0][0]();␊
    f([0, 1, 2][1]);␊
    f('abcd'[2]);␊
    f('' + [][0]);␊
    f('abcd'[5]);␊
    f([0, 1, 2].length);␊
    f('abcd'.length);␊
    f([].map);␊
    `

## WILDLY_UNSAFE snapshot: indexing.js

> Snapshot 1

    `[0][0]();␊
    f(1);␊
    f('c');␊
    f('undefined');␊
    f(void 0);␊
    f(3);␊
    f(4);␊
    f([].map);␊
    `

## USELESS snapshot: inline-arguments.js

> Snapshot 1

    `(function (a, b) {␊
      return a + b;␊
    })(foo(), bar(), baz());␊
    (function (a, b, c) {␊
      return a + b + c;␊
    })(foo(), bar());␊
    `

## SAFE snapshot: inline-arguments.js

> Snapshot 1

    `(function () {␊
      var a = foo();␊
      var b = bar();␊
      baz();␊
      return a + b;␊
    })();␊
    (function () {␊
      var a = foo();␊
      var b = bar();␊
      var c;␊
      return a + b + c;␊
    })();␊
    `

## MOSTLY_SAFE snapshot: inline-arguments.js

> Snapshot 1

    `(function () {␊
      var a = foo();␊
      var b = bar();␊
      baz();␊
      return a + b;␊
    })();␊
    (function () {␊
      var a = foo();␊
      var b = bar();␊
      var c;␊
      return a + b + c;␊
    })();␊
    `

## UNSAFE snapshot: inline-arguments.js

> Snapshot 1

    `(function () {␊
      var a = foo();␊
      var b = bar();␊
      baz();␊
      return a + b;␊
    })();␊
    (function () {␊
      var a = foo();␊
      var b = bar();␊
      var c;␊
      return a + b + c;␊
    })();␊
    `

## WILDLY_UNSAFE snapshot: inline-arguments.js

> Snapshot 1

    `(function () {␊
      var a = foo();␊
      var b = bar();␊
      baz();␊
      return a + b;␊
    })();␊
    (function () {␊
      var a = foo();␊
      var b = bar();␊
      var c;␊
      return a + b + c;␊
    })();␊
    `

## USELESS snapshot: inline-called-once.js

> Snapshot 1

    `function f() {␊
      var x = function (a) {␊
        return a + foo();␊
      };␊
      return x(a);␊
    }␊
    `

## SAFE snapshot: inline-called-once.js

> Snapshot 1

    `function f() {␊
      var x = function (a) {␊
        return a + foo();␊
      };␊
      return x(a);␊
    }␊
    `

## MOSTLY_SAFE snapshot: inline-called-once.js

> Snapshot 1

    `function f() {␊
      var x = function (a) {␊
        return a + foo();␊
      };␊
      return x(a);␊
    }␊
    `

## UNSAFE snapshot: inline-called-once.js

> Snapshot 1

    `function f() {␊
      var x = function (a) {␊
        return a + foo();␊
      };␊
      return x(a);␊
    }␊
    `

## WILDLY_UNSAFE snapshot: inline-called-once.js

> Snapshot 1

    `function f() {␊
      return (function (a) {␊
        return a + foo();␊
      })(a);␊
    }␊
    `

## USELESS snapshot: inline-constant-object-property.js

> Snapshot 1

    `var x = { a: 0 };␊
    y = x.a;␊
    `

## SAFE snapshot: inline-constant-object-property.js

> Snapshot 1

    `var x = { a: 0 };␊
    y = x.a;␊
    `

## MOSTLY_SAFE snapshot: inline-constant-object-property.js

> Snapshot 1

    `var x = { a: 0 };␊
    y = x.a;␊
    `

## UNSAFE snapshot: inline-constant-object-property.js

> Snapshot 1

    `var x = { a: 0 };␊
    y = x.a;␊
    `

## WILDLY_UNSAFE snapshot: inline-constant-object-property.js

> Snapshot 1

    `var x = {};␊
    y = 0;␊
    `

## USELESS snapshot: inline-function-as-conditional.js

> Snapshot 1

    `function f() {␊
      var x = function (foo) {␊
        if (foo == 'bar') return 'a';␊
        else return 'b';␊
      };␊
      var y = x(a);␊
      var z = x(b);␊
      var w = x();␊
      return y + z + w;␊
    }␊
    `

## SAFE snapshot: inline-function-as-conditional.js

> Snapshot 1

    `function f() {␊
      var x = function (foo) {␊
        if (foo == 'bar') {␊
          return 'a';␊
        } else {␊
          return 'b';␊
        }␊
      };␊
      var y = x(a);␊
      var z = x(b);␊
      var w = x();␊
      return y + z + w;␊
    }␊
    `

## MOSTLY_SAFE snapshot: inline-function-as-conditional.js

> Snapshot 1

    `function f() {␊
      var x = function (foo) {␊
        if (foo == 'bar') {␊
          return 'a';␊
        } else {␊
          return 'b';␊
        }␊
      };␊
      var y = x(a);␊
      var z = x(b);␊
      var w = x();␊
      return y + z + w;␊
    }␊
    `

## UNSAFE snapshot: inline-function-as-conditional.js

> Snapshot 1

    `function f() {␊
      var x = function (foo) {␊
        if (foo == 'bar') {␊
          return 'a';␊
        } else {␊
          return 'b';␊
        }␊
      };␊
      var y = x(a);␊
      var z = x(b);␊
      var w = x();␊
      return y + z + w;␊
    }␊
    `

## WILDLY_UNSAFE snapshot: inline-function-as-conditional.js

> Snapshot 1

    `function f() {␊
      var y = a == 'bar' ? 'a' : 'b';␊
      var z = b == 'bar' ? 'a' : 'b';␊
      return y + z + 'b';␊
    }␊
    `

## USELESS snapshot: inline-iife.js

> Snapshot 1

    `function f() {␊
      (function () {␊
        foo();␊
      })();␊
      x = (function () {␊
        return 0;␊
      })();␊
      x = (function () {␊
        foo();␊
      })();␊
    }␊
    `

## SAFE snapshot: inline-iife.js

> Snapshot 1

    `function f() {␊
      foo();␊
      x = 0;␊
      x = (foo(), void null);␊
    }␊
    `

## MOSTLY_SAFE snapshot: inline-iife.js

> Snapshot 1

    `function f() {␊
      foo();␊
      x = 0;␊
      x = (foo(), void null);␊
    }␊
    `

## UNSAFE snapshot: inline-iife.js

> Snapshot 1

    `function f() {␊
      foo();␊
      x = 0;␊
      x = (foo(), void null);␊
    }␊
    `

## WILDLY_UNSAFE snapshot: inline-iife.js

> Snapshot 1

    `function f() {␊
      foo();␊
      x = 0;␊
      x = (foo(), void null);␊
    }␊
    `

## USELESS snapshot: inline-trivial-function.js

> Snapshot 1

    `function f() {␊
      var x = {␊
        p: function (a, b, c) {␊
          return a + b + c;␊
        },␊
      };␊
      console.log(x.p(foo(), bar(), baz()));␊
    }␊
    `

## SAFE snapshot: inline-trivial-function.js

> Snapshot 1

    `function f() {␊
      var x = {␊
        p: function (a, b, c) {␊
          return a + b + c;␊
        },␊
      };␊
      console.log(x.p(foo(), bar(), baz()));␊
    }␊
    `

## MOSTLY_SAFE snapshot: inline-trivial-function.js

> Snapshot 1

    `function f() {␊
      var x = {␊
        p: function (a, b, c) {␊
          return a + b + c;␊
        },␊
      };␊
      console.log(x.p(foo(), bar(), baz()));␊
    }␊
    `

## UNSAFE snapshot: inline-trivial-function.js

> Snapshot 1

    `function f() {␊
      var x = {␊
        p: function (a, b, c) {␊
          return a + b + c;␊
        },␊
      };␊
      console.log(x.p(foo(), bar(), baz()));␊
    }␊
    `

## WILDLY_UNSAFE snapshot: inline-trivial-function.js

> Snapshot 1

    `function f() {␊
      console.log(foo() + bar() + baz());␊
    }␊
    `

## USELESS snapshot: make-blocks.js

> Snapshot 1

    `if (foo()) bar();␊
    for (;;) bar();␊
    while (0) bar();␊
    for (a in b) bar();␊
    do bar();␊
    while (0);␊
    for (a of b) bar();␊
    `

## SAFE snapshot: make-blocks.js

> Snapshot 1

    `if (foo()) {␊
      bar();␊
    }␊
    while (0) {␊
      bar();␊
    }␊
    for (a in b) {␊
      bar();␊
    }␊
    do {␊
      bar();␊
    } while (0);␊
    for (a of b) {␊
      bar();␊
    }␊
    `

## MOSTLY_SAFE snapshot: make-blocks.js

> Snapshot 1

    `if (foo()) {␊
      bar();␊
    }␊
    while (0) {␊
      bar();␊
    }␊
    for (a in b) {␊
      bar();␊
    }␊
    do {␊
      bar();␊
    } while (0);␊
    for (a of b) {␊
      bar();␊
    }␊
    `

## UNSAFE snapshot: make-blocks.js

> Snapshot 1

    `if (foo()) {␊
      bar();␊
    }␊
    while (0) {␊
      bar();␊
    }␊
    for (a in b) {␊
      bar();␊
    }␊
    do {␊
      bar();␊
    } while (0);␊
    for (a of b) {␊
      bar();␊
    }␊
    `

## WILDLY_UNSAFE snapshot: make-blocks.js

> Snapshot 1

    `if (foo()) {␊
      bar();␊
    }␊
    while (0) {␊
      bar();␊
    }␊
    for (a in b) {␊
      bar();␊
    }␊
    do {␊
      bar();␊
    } while (0);␊
    for (a of b) {␊
      bar();␊
    }␊
    `

## USELESS snapshot: negate.js

> Snapshot 1

    `f(!false);␊
    f(!0);␊
    f(![]);␊
    f(!(a && b));␊
    f(!(a == b));␊
    if (!!a) foo();␊
    `

## SAFE snapshot: negate.js

> Snapshot 1

    `f(true);␊
    f(true);␊
    f(false);␊
    f(!a || !b);␊
    f(a != b);␊
    if (a) {␊
      foo();␊
    }␊
    `

## MOSTLY_SAFE snapshot: negate.js

> Snapshot 1

    `f(true);␊
    f(true);␊
    f(false);␊
    f(!a || !b);␊
    f(a != b);␊
    if (a) {␊
      foo();␊
    }␊
    `

## UNSAFE snapshot: negate.js

> Snapshot 1

    `f(true);␊
    f(true);␊
    f(false);␊
    f(!a || !b);␊
    f(a != b);␊
    if (a) {␊
      foo();␊
    }␊
    `

## WILDLY_UNSAFE snapshot: negate.js

> Snapshot 1

    `f(true);␊
    f(true);␊
    f(false);␊
    f(!a || !b);␊
    f(a != b);␊
    if (a) {␊
      foo();␊
    }␊
    `

## USELESS snapshot: no-trailing-return-void.js

> Snapshot 1

    `function f() {␊
      foo();␊
      return;␊
    }␊
    `

## SAFE snapshot: no-trailing-return-void.js

> Snapshot 1

    `function f() {␊
      foo();␊
    }␊
    `

## MOSTLY_SAFE snapshot: no-trailing-return-void.js

> Snapshot 1

    `function f() {␊
      foo();␊
    }␊
    `

## UNSAFE snapshot: no-trailing-return-void.js

> Snapshot 1

    `function f() {␊
      foo();␊
    }␊
    `

## WILDLY_UNSAFE snapshot: no-trailing-return-void.js

> Snapshot 1

    `function f() {␊
      foo();␊
    }␊
    `

## USELESS snapshot: partial-evaluate.js

> Snapshot 1

    `function f() {␊
      var a = 1;␊
      return a + 2 + ['d', 'e'];␊
    }␊
    `

## SAFE snapshot: partial-evaluate.js

> Snapshot 1

    `function f() {␊
      var a = 1;␊
      return a + 2 + ['d', 'e'];␊
    }␊
    `

## MOSTLY_SAFE snapshot: partial-evaluate.js

> Snapshot 1

    `function f() {␊
      var a = 1;␊
      return a + 2 + ['d', 'e'];␊
    }␊
    `

## UNSAFE snapshot: partial-evaluate.js

> Snapshot 1

    `function f() {␊
      var a = 1;␊
      return a + 2 + ['d', 'e'];␊
    }␊
    `

## WILDLY_UNSAFE snapshot: partial-evaluate.js

> Snapshot 1

    `function f() {␊
      return '3d,e';␊
    }␊
    `

## USELESS snapshot: remove-empty-statements.js

> Snapshot 1

    ''

## SAFE snapshot: remove-empty-statements.js

> Snapshot 1

    ''

## MOSTLY_SAFE snapshot: remove-empty-statements.js

> Snapshot 1

    ''

## UNSAFE snapshot: remove-empty-statements.js

> Snapshot 1

    ''

## WILDLY_UNSAFE snapshot: remove-empty-statements.js

> Snapshot 1

    ''

## USELESS snapshot: remove-empty-try.js

> Snapshot 1

    `try {␊
    } catch (e) {␊
      var x;␊
    }␊
    `

## SAFE snapshot: remove-empty-try.js

> Snapshot 1

    `if (false) {␊
      var x;␊
    }␊
    `

## MOSTLY_SAFE snapshot: remove-empty-try.js

> Snapshot 1

    `if (false) {␊
      var x;␊
    }␊
    `

## UNSAFE snapshot: remove-empty-try.js

> Snapshot 1

    `if (false) {␊
      var x;␊
    }␊
    `

## WILDLY_UNSAFE snapshot: remove-empty-try.js

> Snapshot 1

    ''

## USELESS snapshot: remove-unused-vars.js

> Snapshot 1

    `var x = 0;␊
    function f() {␊
      var x = foo();␊
    }␊
    `

## SAFE snapshot: remove-unused-vars.js

> Snapshot 1

    `var x = 0;␊
    function f() {␊
      var x = foo();␊
    }␊
    `

## MOSTLY_SAFE snapshot: remove-unused-vars.js

> Snapshot 1

    `var x = 0;␊
    function f() {␊
      var x = foo();␊
    }␊
    `

## UNSAFE snapshot: remove-unused-vars.js

> Snapshot 1

    `var x = 0;␊
    function f() {␊
      foo();␊
    }␊
    `

## WILDLY_UNSAFE snapshot: remove-unused-vars.js

> Snapshot 1

    `var x = 0;␊
    function f() {␊
      foo();␊
    }␊
    `

## USELESS snapshot: return-and.js

> Snapshot 1

    `function f() {␊
      return ((a = 0), b, c) && d && e;␊
    }␊
    function g() {␊
      return !a && b === 0 && ((c = 0), d, e) && f && g;␊
    }␊
    function h() {␊
      return !a && b === 0 && ((c = 0), d, e);␊
    }␊
    function i() {␊
      return a && (b, c);␊
    }␊
    `

## SAFE snapshot: return-and.js

> Snapshot 1

    `function f() {␊
      a = 0;␊
      b;␊
      return c && d && e;␊
    }␊
    function g() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      d;␊
      return e && f && g;␊
    }␊
    function h() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      d;␊
      return e;␊
    }␊
    function i() {␊
      return a && (b, c);␊
    }␊
    `

## MOSTLY_SAFE snapshot: return-and.js

> Snapshot 1

    `function f() {␊
      a = 0;␊
      b;␊
      return c && d && e;␊
    }␊
    function g() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      d;␊
      return e && f && g;␊
    }␊
    function h() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      d;␊
      return e;␊
    }␊
    function i() {␊
      return a && (b, c);␊
    }␊
    `

## UNSAFE snapshot: return-and.js

> Snapshot 1

    `function f() {␊
      a = 0;␊
      b;␊
      return c && d && e;␊
    }␊
    function g() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      d;␊
      return e && f && g;␊
    }␊
    function h() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      d;␊
      return e;␊
    }␊
    function i() {␊
      return a && (b, c);␊
    }␊
    `

## WILDLY_UNSAFE snapshot: return-and.js

> Snapshot 1

    `function f() {␊
      a = 0;␊
      return c && d && e;␊
    }␊
    function g() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      return e && f && g;␊
    }␊
    function h() {␊
      if (a || b !== 0) {␊
        return false;␊
      }␊
      c = 0;␊
      return e;␊
    }␊
    function i() {␊
      return a && (b, c);␊
    }␊
    `

## USELESS snapshot: return-conditional.js

> Snapshot 1

    `function f() {␊
      return foo() ? 0 : 1;␊
    }␊
    `

## SAFE snapshot: return-conditional.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        return 0;␊
      } else {␊
        return 1;␊
      }␊
    }␊
    `

## MOSTLY_SAFE snapshot: return-conditional.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        return 0;␊
      } else {␊
        return 1;␊
      }␊
    }␊
    `

## UNSAFE snapshot: return-conditional.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        return 0;␊
      } else {␊
        return 1;␊
      }␊
    }␊
    `

## WILDLY_UNSAFE snapshot: return-conditional.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        return 0;␊
      } else {␊
        return 1;␊
      }␊
    }␊
    `

## USELESS snapshot: return-void.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        return void bar();␊
      }␊
    }␊
    `

## SAFE snapshot: return-void.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        bar();␊
        return;␊
      }␊
    }␊
    `

## MOSTLY_SAFE snapshot: return-void.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        bar();␊
        return;␊
      }␊
    }␊
    `

## UNSAFE snapshot: return-void.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        bar();␊
        return;␊
      }␊
    }␊
    `

## WILDLY_UNSAFE snapshot: return-void.js

> Snapshot 1

    `function f() {␊
      if (foo()) {␊
        bar();␊
        return;␊
      }␊
    }␊
    `

## USELESS snapshot: shorthand-if.js

> Snapshot 1

    `a ? b() : c();␊
    a && b();␊
    a || c();␊
    `

## SAFE snapshot: shorthand-if.js

> Snapshot 1

    `if (a) {␊
      b();␊
    } else {␊
      c();␊
    }␊
    if (a) {␊
      b();␊
    }␊
    if (!a) {␊
      c();␊
    }␊
    `

## MOSTLY_SAFE snapshot: shorthand-if.js

> Snapshot 1

    `if (a) {␊
      b();␊
    } else {␊
      c();␊
    }␊
    if (a) {␊
      b();␊
    }␊
    if (!a) {␊
      c();␊
    }␊
    `

## UNSAFE snapshot: shorthand-if.js

> Snapshot 1

    `if (a) {␊
      b();␊
    } else {␊
      c();␊
    }␊
    if (a) {␊
      b();␊
    }␊
    if (!a) {␊
      c();␊
    }␊
    `

## WILDLY_UNSAFE snapshot: shorthand-if.js

> Snapshot 1

    `if (a) {␊
      b();␊
    } else {␊
      c();␊
    }␊
    if (a) {␊
      b();␊
    }␊
    if (!a) {␊
      c();␊
    }␊
    `

## USELESS snapshot: spread-block.js

> Snapshot 1

    `{␊
      foo();␊
      {␊
        bar();␊
        baz();␊
      }␊
      quux();␊
    }␊
    `

## SAFE snapshot: spread-block.js

> Snapshot 1

    `foo();␊
    bar();␊
    baz();␊
    quux();␊
    `

## MOSTLY_SAFE snapshot: spread-block.js

> Snapshot 1

    `foo();␊
    bar();␊
    baz();␊
    quux();␊
    `

## UNSAFE snapshot: spread-block.js

> Snapshot 1

    `foo();␊
    bar();␊
    baz();␊
    quux();␊
    `

## WILDLY_UNSAFE snapshot: spread-block.js

> Snapshot 1

    `foo();␊
    bar();␊
    baz();␊
    quux();␊
    `

## USELESS snapshot: statement-position-negation.js

> Snapshot 1

    `!d();␊
    `

## SAFE snapshot: statement-position-negation.js

> Snapshot 1

    `d();␊
    `

## MOSTLY_SAFE snapshot: statement-position-negation.js

> Snapshot 1

    `d();␊
    `

## UNSAFE snapshot: statement-position-negation.js

> Snapshot 1

    `d();␊
    `

## WILDLY_UNSAFE snapshot: statement-position-negation.js

> Snapshot 1

    `d();␊
    `

## USELESS snapshot: un-yoda.js

> Snapshot 1

    `0 === b;␊
    `

## SAFE snapshot: un-yoda.js

> Snapshot 1

    `b === 0;␊
    `

## MOSTLY_SAFE snapshot: un-yoda.js

> Snapshot 1

    `b === 0;␊
    `

## UNSAFE snapshot: un-yoda.js

> Snapshot 1

    `b === 0;␊
    `

## WILDLY_UNSAFE snapshot: un-yoda.js

> Snapshot 1

    `b === 0;␊
    `

## USELESS snapshot: unhoist-var-decls.js

> Snapshot 1

    `function f() {␊
      var a;␊
      b();␊
      a = b();␊
      return a;␊
    }␊
    `

## SAFE snapshot: unhoist-var-decls.js

> Snapshot 1

    `function f() {␊
      b();␊
      var a = b();␊
      return a;␊
    }␊
    `

## MOSTLY_SAFE snapshot: unhoist-var-decls.js

> Snapshot 1

    `function f() {␊
      b();␊
      var a = b();␊
      return a;␊
    }␊
    `

## UNSAFE snapshot: unhoist-var-decls.js

> Snapshot 1

    `function f() {␊
      b();␊
      var a = b();␊
      return a;␊
    }␊
    `

## WILDLY_UNSAFE snapshot: unhoist-var-decls.js

> Snapshot 1

    `function f() {␊
      b();␊
      var a = b();␊
      return a;␊
    }␊
    `


================================================
FILE: test/snapshots.js
================================================
const fs = require('fs');
const test = require('ava');
const prettier = require('prettier');
const unminify = require('../');

const SNAPSHOTS_DIR = `${__dirname}/snapshots-in`;
const files = fs.readdirSync(SNAPSHOTS_DIR)

function format(src) {
  return prettier.format(src, { parser: 'babel', singleQuote: true, trailingComma: 'all' });
}

files.forEach(file => {
  let sourceText = fs.readFileSync(`${SNAPSHOTS_DIR}/${file}`, 'utf-8');

  Object.keys(unminify.safetyLevels).forEach(safetyLevel => {
    test(`${safetyLevel} snapshot: ${file}`, async t => {
      t.snapshot(format(unminify(sourceText, { safety: unminify.safetyLevels[safetyLevel] })));
    });
  });
});
Download .txt
gitextract_dhkidt2p/

├── .eslintrc.js
├── .github/
│   └── workflows/
│       └── check.yml
├── .gitignore
├── LICENSE
├── README.md
├── bin/
│   └── cli.js
├── package.json
├── src/
│   ├── cli.js
│   ├── helpers/
│   │   ├── codegen.js
│   │   ├── fn-contains-weirdness.js
│   │   ├── inlinable.js
│   │   └── parents.js
│   ├── index.js
│   ├── safety-levels.js
│   └── transforms/
│       ├── safe/
│       │   ├── cleanup-with-state.js
│       │   └── cleanup.js
│       ├── unsafe/
│       │   └── remove-unused.js
│       └── wildly-unsafe/
│           ├── inline.js
│           └── partial-evaluate.js
└── test/
    ├── snapshots-in/
    │   ├── computed-member-to-static.js
    │   ├── expand-expression-statement.js
    │   ├── expand-multiple-decl.js
    │   ├── expand-sequence.js
    │   ├── hoist-fns.js
    │   ├── if-and-seq.js
    │   ├── if-not.js
    │   ├── indexing.js
    │   ├── inline-arguments.js
    │   ├── inline-called-once.js
    │   ├── inline-constant-object-property.js
    │   ├── inline-function-as-conditional.js
    │   ├── inline-iife.js
    │   ├── inline-trivial-function.js
    │   ├── make-blocks.js
    │   ├── negate.js
    │   ├── no-trailing-return-void.js
    │   ├── partial-evaluate.js
    │   ├── remove-empty-statements.js
    │   ├── remove-empty-try.js
    │   ├── remove-unused-vars.js
    │   ├── return-and.js
    │   ├── return-conditional.js
    │   ├── return-void.js
    │   ├── shorthand-if.js
    │   ├── spread-block.js
    │   ├── statement-position-negation.js
    │   ├── un-yoda.js
    │   └── unhoist-var-decls.js
    ├── snapshots-out/
    │   └── test/
    │       ├── snapshots.js.md
    │       └── snapshots.js.snap
    └── snapshots.js
Download .txt
SYMBOL INDEX (114 symbols across 25 files)

FILE: src/cli.js
  function format (line 22) | function format(src) {

FILE: src/helpers/codegen.js
  class FormattedCodeGenWithStrs (line 5) | class FormattedCodeGenWithStrs extends codegen.FormattedCodeGen {
    method reduceLiteralStringExpression (line 6) | reduceLiteralStringExpression(node) {

FILE: src/helpers/fn-contains-weirdness.js
  class ContainsWeirdness (line 7) | class ContainsWeirdness extends reducer.MonoidalReducer {
    method constructor (line 8) | constructor() {
    method reduceThisExpression (line 14) | reduceThisExpression() {
    method reduceFunctionExpression (line 18) | reduceFunctionExpression() {
    method reduceFunctionDeclaration (line 22) | reduceFunctionDeclaration() {
    method reduceIdentifierExpression (line 26) | reduceIdentifierExpression(node) {

FILE: src/helpers/parents.js
  class ParentFinder (line 9) | class ParentFinder {
    method constructor (line 10) | constructor() {

FILE: src/index.js
  constant TRANSFORMATIONS (line 7) | const TRANSFORMATIONS = {
  function unminifySource (line 23) | function unminifySource(src, options) {
  function unminifyTree (line 28) | function unminifyTree(tree, { safety = safetyLevels.SAFE, additionalTran...

FILE: src/transforms/safe/cleanup-with-state.js
  function findScopeForNode (line 16) | function findScopeForNode(node, scope = globalScope) {
  function unhoistVarDeclarations (line 26) | function unhoistVarDeclarations(statements) {
  class CleanupWithState (line 95) | class CleanupWithState extends reducer.LazyCloneReducer {
    method reduceFunctionBody (line 96) | reduceFunctionBody(node, { directives, statements }) {
    method reduceCallExpression (line 101) | reduceCallExpression(node, { callee, arguments: _arguments }) {
  class NameCollector (line 136) | class NameCollector extends reducer.MonoidalReducer {
    method constructor (line 137) | constructor() {
    method reduceIdentifierExpression (line 141) | reduceIdentifierExpression(node) {
    method reduceAssignmentTargetIdentifier (line 145) | reduceAssignmentTargetIdentifier(node) {
    method reduceBindingIdentifier (line 149) | reduceBindingIdentifier(node) {
    method reduceFunctionExpression (line 153) | reduceFunctionExpression(node, state) { // TODO it would be nice for t...
  function collectNames (line 166) | function collectNames(node) {

FILE: src/transforms/safe/cleanup.js
  function makeBlock (line 17) | function makeBlock(statement) {
  function negate (line 21) | function negate(expr, isBooleanContext, requireResult = true) {
  function isConstant (line 53) | function isConstant(node) {
  function isSequence (line 58) | function isSequence(expr) {
  function binExprToExprs (line 63) | function binExprToExprs(expr) {
  function binExprToExprsHelper (line 68) | function binExprToExprsHelper(expr, operator) {
  function declaratorsToDeclarationStatements (line 75) | function declaratorsToDeclarationStatements(kind, declarators) {
  class OnlyReturnUndefined (line 80) | class OnlyReturnUndefined extends reducer.LazyCloneReducer { // TODO thi...
    method reduceFunctionBody (line 81) | reduceFunctionBody(node) {
    method reduceReturnStatement (line 85) | reduceReturnStatement(node, { expression }) {
  function makeReturnsUndefined (line 98) | function makeReturnsUndefined(fnBody) {
  function returnsBoolean (line 107) | function returnsBoolean(expr) {
  function extractSequenceFromConjunction (line 138) | function extractSequenceFromConjunction(expr, isBooleanContext) {
  function fixStatementList (line 160) | function fixStatementList(statements) {
  function arrayEquals (line 322) | function arrayEquals(a, b) {
  function hoistFunctionDeclarations (line 326) | function hoistFunctionDeclarations(statements) {
  class Cleanup (line 343) | class Cleanup extends reducer.LazyCloneReducer {
    method reduceBlock (line 344) | reduceBlock(node, { statements }) {
    method reduceSwitchCase (line 348) | reduceSwitchCase(node, { test, consequent }) {
    method reduceSwitchDefault (line 352) | reduceSwitchDefault(node, { consequent }) {
    method reduceFunctionBody (line 356) | reduceFunctionBody(node, { directives, statements }) {
    method reduceScript (line 370) | reduceScript(node, { directives, statements }) {
    method reduceUnaryExpression (line 374) | reduceUnaryExpression(node, { operand }) {
    method reduceBinaryExpression (line 384) | reduceBinaryExpression(node, { left, right }) {
    method reduceExpressionStatement (line 395) | reduceExpressionStatement(node, { expression }) {
    method reduceIfStatement (line 408) | reduceIfStatement(node, { test, consequent, alternate }) {
    method reduceConditionalExpression (line 432) | reduceConditionalExpression(node, { test, consequent, alternate }) {
    method reduceForStatement (line 439) | reduceForStatement(node, { init, test, update, body }) {
    method reduceForInStatement (line 449) | reduceForInStatement(node, { left, right, body }) {
    method reduceForOfStatement (line 456) | reduceForOfStatement(node, { left, right, body }) {
    method reduceWhileStatement (line 463) | reduceWhileStatement(node, { test, body }) {
    method reduceDoWhileStatement (line 470) | reduceDoWhileStatement(node, { body, test }) {
    method reduceComputedMemberAssignmentTarget (line 477) | reduceComputedMemberAssignmentTarget(node, { object, expression }) {
    method reduceComputedMemberExpression (line 484) | reduceComputedMemberExpression(node, { object, expression }) {
    method reduceCallExpression (line 491) | reduceCallExpression(node, { callee, arguments: _arguments }) {

FILE: src/transforms/unsafe/remove-unused.js
  function isOnlyWritten (line 13) | function isOnlyWritten(node, parents, lookup) {
  class RemoveUnused (line 42) | class RemoveUnused extends reducer.LazyCloneReducer {
    method reduceVariableDeclarationStatement (line 43) | reduceVariableDeclarationStatement(node, { declaration }) {
    method reduceVariableDeclarator (line 79) | reduceVariableDeclarator(node, { binding, init }) {
    method reduceAssignmentExpression (line 108) | reduceAssignmentExpression(node, { binding, expression }) {
    method reduceCompoundAssignmentExpression (line 115) | reduceCompoundAssignmentExpression(node, { binding, expression }) {

FILE: src/transforms/wildly-unsafe/inline.js
  function findScopeForNode (line 19) | function findScopeForNode(node, scope = globalScope) {
  function isConstantInitializedVariable (line 29) | function isConstantInitializedVariable(v) {
  function isConstantVariable (line 40) | function isConstantVariable(v) {
  function getConstantObjectVariableObject (line 50) | function getConstantObjectVariableObject(_var) {
  function findStatementParent (line 75) | function findStatementParent(node) {
  function getInlining (line 84) | function getInlining(node) {
  function getTriviallyInlineableFunction (line 102) | function getTriviallyInlineableFunction(f, arglen) {
  class InliningReducer (line 127) | class InliningReducer extends reducer.LazyCloneReducer {
    method reduceExpressionStatement (line 128) | reduceExpressionStatement(node, { expression }) {
    method reduceCallExpression (line 135) | reduceCallExpression(node, { callee, arguments: _arguments }) {
    method reduceIdentifierExpression (line 195) | reduceIdentifierExpression(node) {
    method reduceComputedMemberExpression (line 201) | reduceComputedMemberExpression(node, { object, expression }) {
    method reduceStaticMemberExpression (line 217) | reduceStaticMemberExpression(node, { object }) {

FILE: src/transforms/wildly-unsafe/partial-evaluate.js
  function constantToNode (line 11) | function constantToNode(c) {
  function getStaticInit (line 48) | function getStaticInit(node) {
  function evaluateToNode (line 64) | function evaluateToNode(node) {
  function evaluate (line 78) | function evaluate(node) {
  function evaluateCore (line 89) | function evaluateCore(node) {
  function evaluateStaticProperty (line 268) | function evaluateStaticProperty(object, property) {
  class Evaluate (line 318) | class Evaluate extends reducer.LazyCloneReducer {
    method reduceUnaryExpression (line 319) | reduceUnaryExpression(node, { operand }) {
    method reduceBinaryExpression (line 323) | reduceBinaryExpression(node, { left, right }) {
    method reduceCallExpression (line 327) | reduceCallExpression(node, { callee, arguments: _arguments }) {
    method reduceStaticMemberExpression (line 331) | reduceStaticMemberExpression(node, { object }) {
    method reduceIdentifierExpression (line 335) | reduceIdentifierExpression(node) {
    method reduceComputedMemberExpression (line 339) | reduceComputedMemberExpression(node, { object, expression }) {
    method reduceConditionalExpression (line 363) | reduceConditionalExpression(node, { test, consequent, alternate }) {
    method reduceIfStatement (line 372) | reduceIfStatement(node, { test, consequent, alternate }) {

FILE: test/snapshots-in/expand-multiple-decl.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/expand-sequence.js
  function f (line 4) | function f(){

FILE: test/snapshots-in/hoist-fns.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/inline-called-once.js
  function f (line 1) | function f() {

FILE: test/snapshots-in/inline-function-as-conditional.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/inline-iife.js
  function f (line 1) | function f () {

FILE: test/snapshots-in/inline-trivial-function.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/no-trailing-return-void.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/partial-evaluate.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/remove-unused-vars.js
  function f (line 2) | function f(){

FILE: test/snapshots-in/return-and.js
  function f (line 1) | function f(){
  function g (line 5) | function g(){
  function h (line 9) | function h(){
  function i (line 13) | function i(){

FILE: test/snapshots-in/return-conditional.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/return-void.js
  function f (line 1) | function f(){

FILE: test/snapshots-in/unhoist-var-decls.js
  function f (line 1) | function f(){

FILE: test/snapshots.js
  constant SNAPSHOTS_DIR (line 6) | const SNAPSHOTS_DIR = `${__dirname}/snapshots-in`;
  function format (line 9) | function format(src) {
Condensed preview — 51 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (123K chars).
[
  {
    "path": ".eslintrc.js",
    "chars": 3088,
    "preview": "module.exports = {\n  extends: 'eslint:recommended',\n  env: {\n    es6: true,\n    node: true,\n    browser: false,\n  },\n  p"
  },
  {
    "path": ".github/workflows/check.yml",
    "chars": 1069,
    "preview": "name: check\n\non:\n  push:\n    branches:\n      - main\n  pull_request:\n\njobs:\n  pre:\n    name: Prerequisites\n    if: github"
  },
  {
    "path": ".gitignore",
    "chars": 13,
    "preview": "node_modules\n"
  },
  {
    "path": "LICENSE",
    "chars": 11358,
    "preview": "\n                                 Apache License\n                           Version 2.0, January 2004\n                  "
  },
  {
    "path": "README.md",
    "chars": 3067,
    "preview": "Unminify\n========\n\nA little project to undo several of the horrible things JavaScript build tools will do to JavaScript."
  },
  {
    "path": "bin/cli.js",
    "chars": 43,
    "preview": "#!/usr/bin/env node\nrequire('../src/cli');\n"
  },
  {
    "path": "package.json",
    "chars": 1119,
    "preview": "{\n  \"name\": \"unminify\",\n  \"version\": \"2.0.0\",\n  \"author\": \"Kevin Gibbons <kevin@shapesecurity.com>\",\n  \"description\": \"r"
  },
  {
    "path": "src/cli.js",
    "chars": 1263,
    "preview": "'use strict';\n/* eslint-disable no-console */\n\nconst fs = require('fs');\nconst args = require('command-line-args')([\n  {"
  },
  {
    "path": "src/helpers/codegen.js",
    "chars": 979,
    "preview": "'use strict';\n\nconst codegen = require('shift-codegen');\n\nclass FormattedCodeGenWithStrs extends codegen.FormattedCodeGe"
  },
  {
    "path": "src/helpers/fn-contains-weirdness.js",
    "chars": 886,
    "preview": "'use strict';\n\n// TODO short-curcuiting, memoization\n\nconst reducer = require('shift-reducer');\n\nclass ContainsWeirdness"
  },
  {
    "path": "src/helpers/inlinable.js",
    "chars": 138,
    "preview": "module.exports = [\n  'LiteralNumericExpression',\n  'LiteralStringExpression',\n  'LiteralNullExpression',\n  'LiteralBoole"
  },
  {
    "path": "src/helpers/parents.js",
    "chars": 1341,
    "preview": "'use strict';\n\n// Give a map from a node to its parents.\n\nconst reducer = require('shift-reducer');\nconst spec = require"
  },
  {
    "path": "src/index.js",
    "chars": 1516,
    "preview": "'use strict';\n\nconst parser = require('shift-parser');\nconst codegen = require('./helpers/codegen');\nconst safetyLevels "
  },
  {
    "path": "src/safety-levels.js",
    "chars": 117,
    "preview": "module.exports = {\n  __proto__: null,\n  USELESS: 0,\n  SAFE: 1,\n  MOSTLY_SAFE: 2,\n  UNSAFE: 3,\n  WILDLY_UNSAFE: 4,\n};\n"
  },
  {
    "path": "src/transforms/safe/cleanup-with-state.js",
    "chars": 7302,
    "preview": "'use strict';\n\nconst reducer = require('shift-reducer');\nconst shiftScope = require('shift-scope');\nconst Shift = requir"
  },
  {
    "path": "src/transforms/safe/cleanup.js",
    "chars": 22438,
    "preview": "'use strict';\n\n/* eslint-disable no-param-reassign */\n// Basically de-uglify-js\n\nconst reducer = require('shift-reducer'"
  },
  {
    "path": "src/transforms/unsafe/remove-unused.js",
    "chars": 5333,
    "preview": "'use strict';\n\n// Remove unused variables and object properties which are initialized to constants.\n\nconst scope = requi"
  },
  {
    "path": "src/transforms/wildly-unsafe/inline.js",
    "chars": 10755,
    "preview": "'use strict';\n\n// Inline constant primitive variables, constant primitive object properties, and constant object propert"
  },
  {
    "path": "src/transforms/wildly-unsafe/partial-evaluate.js",
    "chars": 14051,
    "preview": "'use strict';\n\nconst reducer = require('shift-reducer');\nconst Shift = require('shift-ast/checked');\nconst shiftScope = "
  },
  {
    "path": "test/snapshots-in/computed-member-to-static.js",
    "chars": 33,
    "preview": "a['b'];\na['b'] = 0;\na[0];\na['0'];"
  },
  {
    "path": "test/snapshots-in/expand-expression-statement.js",
    "chars": 41,
    "preview": "foo(), this, void bar(), void 0, new baz;"
  },
  {
    "path": "test/snapshots-in/expand-multiple-decl.js",
    "chars": 109,
    "preview": "function f(){\n  var a = foo(), b = bar();\n  for (var c = foo(), d = bar(); false;);\n  return a + b + c + d;\n}"
  },
  {
    "path": "test/snapshots-in/expand-sequence.js",
    "chars": 115,
    "preview": "if(a(), b()) {\n  c();\n}\nfunction f(){\n  var a = (b(), c);\n  return d(), a;\n}\nthrow f(), g;\nfor((a(), b()); false;);"
  },
  {
    "path": "test/snapshots-in/hoist-fns.js",
    "chars": 57,
    "preview": "function f(){\n  foo();\n  function bar(){}\n  return bar;\n}"
  },
  {
    "path": "test/snapshots-in/if-and-seq.js",
    "chars": 97,
    "preview": "if (a && (b, c) && d) {\n  foo();\n}\n\nif ((b, c) && d) {\n  foo();\n}\n\nif (a && (b, c)) {\n  foo();\n}\n"
  },
  {
    "path": "test/snapshots-in/if-not.js",
    "chars": 43,
    "preview": "if (a !== b) {\n  foo();\n} else {\n  bar();\n}"
  },
  {
    "path": "test/snapshots-in/indexing.js",
    "chars": 120,
    "preview": "[0][0]();\nf([0, 1, 2][1]);\nf('abcd'[2]);\nf('' + [][0]);\nf('abcd'[5]);\nf([0, 1, 2].length);\nf('abcd'.length);\nf([].map);\n"
  },
  {
    "path": "test/snapshots-in/inline-arguments.js",
    "chars": 111,
    "preview": "(function(a, b){ return a + b; })(foo(), bar(), baz());\n(function(a, b, c){ return a + b + c; })(foo(), bar());"
  },
  {
    "path": "test/snapshots-in/inline-called-once.js",
    "chars": 74,
    "preview": "function f() {\n  var x = function(a){ return a + foo(); }\n  return x(a);\n}"
  },
  {
    "path": "test/snapshots-in/inline-constant-object-property.js",
    "chars": 30,
    "preview": "var x = {\n  a: 0,\n};\ny = x.a;\n"
  },
  {
    "path": "test/snapshots-in/inline-function-as-conditional.js",
    "chars": 161,
    "preview": "function f(){\n\n  var x = function (foo) { if (foo == 'bar') return 'a'; else return 'b'; };\n  var y = x(a);\n  var z = x("
  },
  {
    "path": "test/snapshots-in/inline-iife.js",
    "chars": 117,
    "preview": "function f () {\n  (function() {\n    foo();\n  })();\n\n  x = function(){ return 0; }();\n  x = function(){ foo(); }();\n}\n"
  },
  {
    "path": "test/snapshots-in/inline-trivial-function.js",
    "chars": 136,
    "preview": "function f(){\n  var x = {\n    p: function (a, b, c) {\n      return a + b + c;\n    },\n  };\n\n  console.log(x.p(foo(), bar("
  },
  {
    "path": "test/snapshots-in/make-blocks.js",
    "chars": 110,
    "preview": "if (foo()) bar();\nfor(;;) bar();\nwhile (0) bar();\nfor (a in b) bar();\ndo bar(); while (0);\nfor (a of b) bar();"
  },
  {
    "path": "test/snapshots-in/negate.js",
    "chars": 70,
    "preview": "f(!false);\nf(!0);\nf(![]);\nf(!(a && b));\nf(!(a == b));\nif (!!a) foo();\n"
  },
  {
    "path": "test/snapshots-in/no-trailing-return-void.js",
    "chars": 34,
    "preview": "function f(){\n  foo();\n  return;\n}"
  },
  {
    "path": "test/snapshots-in/partial-evaluate.js",
    "chars": 57,
    "preview": "function f(){\n  var a = 1;\n  return a + 2 + ['d', 'e'];\n}"
  },
  {
    "path": "test/snapshots-in/remove-empty-statements.js",
    "chars": 3,
    "preview": ";;\n"
  },
  {
    "path": "test/snapshots-in/remove-empty-try.js",
    "chars": 21,
    "preview": "try{}catch(e){var x;}"
  },
  {
    "path": "test/snapshots-in/remove-unused-vars.js",
    "chars": 43,
    "preview": "var x = 0;\nfunction f(){\n  var x = foo();\n}"
  },
  {
    "path": "test/snapshots-in/return-and.js",
    "chars": 215,
    "preview": "function f(){\n  return (a = 0, b, c) && d && e;\n}\n\nfunction g(){\n  return !a && b === 0 && (c = 0, d, e) && f && g;\n}\n\nf"
  },
  {
    "path": "test/snapshots-in/return-conditional.js",
    "chars": 39,
    "preview": "function f(){\n  return foo() ? 0 : 1;\n}"
  },
  {
    "path": "test/snapshots-in/return-void.js",
    "chars": 57,
    "preview": "function f(){\n  if (foo()) {\n    return void bar();\n  }\n}"
  },
  {
    "path": "test/snapshots-in/shorthand-if.js",
    "chars": 35,
    "preview": "a ? b() : c();\na && b();\na || c();\n"
  },
  {
    "path": "test/snapshots-in/spread-block.js",
    "chars": 53,
    "preview": "{\n  foo();\n  {\n    bar();\n    baz();\n  }\n  quux();\n}\n"
  },
  {
    "path": "test/snapshots-in/statement-position-negation.js",
    "chars": 5,
    "preview": "!d();"
  },
  {
    "path": "test/snapshots-in/un-yoda.js",
    "chars": 9,
    "preview": "0 === b;\n"
  },
  {
    "path": "test/snapshots-in/unhoist-var-decls.js",
    "chars": 54,
    "preview": "function f(){\n  var a;\n  b();\n  a = b();\n  return a;\n}"
  },
  {
    "path": "test/snapshots-out/test/snapshots.js.md",
    "chars": 25152,
    "preview": "# Snapshot report for `test/snapshots.js`\n\nThe actual snapshot is saved in `snapshots.js.snap`.\n\nGenerated by [AVA](http"
  },
  {
    "path": "test/snapshots.js",
    "chars": 674,
    "preview": "const fs = require('fs');\nconst test = require('ava');\nconst prettier = require('prettier');\nconst unminify = require('."
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the shapesecurity/unminify GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 51 files (111.1 KB), approximately 33.1k tokens, and a symbol index with 114 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!