summaryrefslogtreecommitdiff
path: root/node_modules/babel-plugin-minify-dead-code-elimination/lib/remove-use-strict.js
blob: eb4cbe3a6b95f20449c029499fdff461065cd9d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
"use strict";

module.exports = removeUseStrict;
const newIssueUrl = "https://github.com/babel/minify/issues/new";
const useStrict = "use strict";
/**
 * Remove redundant use strict
 * If the parent has a "use strict" directive, it is not required in
 * the children
 *
 * @param {NodePath} block BlockStatement
 */

function removeUseStrict(block) {
  if (!block.isBlockStatement()) {
    throw new Error(`Received ${block.type}. Expected BlockStatement. ` + `Please report at ${newIssueUrl}`);
  }

  const useStricts = getUseStrictDirectives(block); // early exit

  if (useStricts.length < 1) return; // only keep the first use strict

  if (useStricts.length > 1) {
    for (let i = 1; i < useStricts.length; i++) {
      useStricts[i].remove();
    }
  } // check if parent has an use strict


  if (hasStrictParent(block)) {
    useStricts[0].remove();
  }
}

function hasStrictParent(path) {
  return path.findParent(parent => parent.isBlockStatement() && isStrict(parent));
}

function isStrict(block) {
  return getUseStrictDirectives(block).length > 0;
}

function getUseStrictDirectives(block) {
  var dir = block.get("directives");
  return Array.isArray(dir) ? dir.filter(function (directive) {
    return directive.node.value.value === useStrict;
  }) : [];
}