Plucked directly from old Babel Core https://github.com/babel/babel/commit/0df0c696a93889f029982bf36d34346a039b1920
482004
function regexify(val) {
  if (!val) return new RegExp;
  if (Array.isArray(val)) val = val.join("|");
  if (isString(val)) return new RegExp(val || "");
  if (isRegExp(val)) return val;
  throw new TypeError("illegal type for regexify");
}
276886
function fixBadRegex(grammar) {
	const scopeResolution = grammar.repository['scope-resolution'];
	if (scopeResolution) {
		const match = scopeResolution.patterns[0].match;
		if (match === '(?i)([a-z_\\x{7f}-\\x{7fffffff}\\\\][a-z0-9_\\x{7f}-\\x{7fffffff}\\\\]*)(?=\\s*::)') {
			scopeResolution.patterns[0].match = '([A-Za-z_\\x{7f}-\\x{7fffffff}\\\\][A-Za-z0-9_\\x{7f}-\\x{7fffffff}\\\\]*)(?=\\s*::)';
			return;
		}
	}

	throw new Error(`fixBadRegex callback couldn't patch the regex. It may be obsolete`);
}
170527
function compileGraphQLTag(
  t: $FlowFixMe,
  path: Object,
  state: BabelState,
  ast: DocumentNode,
): void {
  if (ast.definitions.length !== 1) {
    throw new Error(
      'BabelPluginRelay: Expected exactly one definition per graphql tag.',
    );
  }
  const definition = ast.definitions[0];
  if (
    definition.kind !== 'FragmentDefinition' &&
    definition.kind !== 'OperationDefinition'
  ) {
    throw new Error(
      'BabelPluginRelay: Expected a fragment, mutation, query, or ' +
        'subscription, got `' +
        definition.kind +
        '`.',
    );
  }
  return replaceMemoized(t, path, createAST(t, state, path, definition));
}
844304
function getBabelConfig(env) {
  var babelrcPath = path.join(__dirname, '.babelrc')
  var babelrc = JSON.parse(fs.readFileSync(babelrcPath))
  babelrc.presets = resolve(
    babelrc.presets.map(preset => 'babel-preset-' + preset)
  )
  if (!babelrc.plugins) babelrc.plugins = []
  return babelrc
}
1147733
function makeLexer() {
  const mooLexer = moo.compile(tokens);

  return {
    current: null,
    lines: [],
    get line() {
      return mooLexer.line;
    },
    get col() {
      return mooLexer.col;
    },
    save() {
      return mooLexer.save();
    },
    reset(chunk, info) {
      this.lines = chunk.split('\n');
      return mooLexer.reset(chunk, info);
    },
    next() {
      // It's a cruel and unusual punishment to implement comments with nearly
      let token = mooLexer.next();
      // Drop all comment tokens found
      while (token && token.type === 'comment') {
        token = mooLexer.next();
      }
      this.current = token;
      return this.current;
    },
    formatError(token) {
      return mooLexer.formatError(token);
    },
    has(name) {
      return mooLexer.has(name);
    },
  };
}
724160
function reconstitute(original, translated) {
    (0, _babelTraverse2.default)(original, {
        noScope: true,
        JSXElement: function JSXElement(_ref) {
            var node = _ref.node;

            (0, _ast.convertNamespacedNameToIdAttribute)(node);
        }
    });
    var sanitized = (0, _validation.sanitizedAttributesOf)(original);
    (0, _babelTraverse2.default)(translated, {
        JSXElement: function JSXElement(_ref2) {
            var node = _ref2.node;

            if ((0, _ast.isElementMarker)(node)) {
                (0, _validation.validateMessage)(node);
                node.openingElement.name.name = 'span';
                node.closingElement.name.name = 'span';
            }
            (0, _ast.convertNamespacedNameToIdAttribute)(node);
            var id = (0, _ast.idOrComponentName)(node);
            if (id && sanitized[id]) {
                sanitized[id].forEach(function (a) {
                    node.openingElement.attributes.push(a);
                });
            }
            (0, _ast.removeIdAttribute)(node);
        }
    });
    return translated;
}
17410
function extract(
  pattern /* : string */,
  babelPlugins /* : Array<string> */ = []
) /* : string */ {
  const srcPaths = glob.sync(pattern, { absolute: true });
  const relativeSrcPaths = glob.sync(pattern);
  const contents = srcPaths.map(p => fs.readFileSync(p, 'utf-8'));
  const reqBabelPlugins = babelPlugins.map(b =>
    require.resolve(`babel-plugin-${b}`)
  );
  const messages = contents
    .map(content =>
      babel.transform(content, {
        presets: [require.resolve('babel-preset-react-app')],
        plugins: [
          require.resolve('babel-plugin-react-intl'),
          ...reqBabelPlugins,
        ],
        babelrc: false,
      })
    )
    .map(R.path(['metadata', 'react-intl', 'messages']));

  const result = R.zipWith(
    (m, r) => m.map(R.assoc('filepath', r)),
    messages,
    relativeSrcPaths
  )
    .filter(R.complement(R.isEmpty))
    .reduce(R.concat, []);

  return result;
}
979761
function (options, overrides) {
    let resolved = null;

    if (typeof options === 'string') { //we've been give a path to a project dir or babelrc
      let babelrcPath;
      const stats = fs.statSync(options);
      if (stats.isDirectory()) {
        babelrcPath = path.join(options, '.babelrc');
      } else if (stats.isFile()) {
        babelrcPath = options;
      }

      if (babelrcPath) {
        try {
          const babelOptions = JSON.parse(fs.readFileSync(babelrcPath));
          resolved = resolveOptions(babelOptions);
        } catch (e) {
          console.log(e);
        }
      }

    } else if (typeof options === 'object') {
      resolved = resolveOptions(options);
    }

    if (resolved) {
      Object.keys(overrides).forEach(function (key) {
        resolved[key] = overrides[key];
      });
      return resolved;
    }

    return null;
  }
793208
function createBitbucketEnterpriseCommitLink () {
  const pkg = require(process.cwd() + '/package')
  const repository = pkg.repository.url

  return function (commit) {
    const commitStr = commit.substring(0,8)
    return repository ?
      `[${commitStr}](${repository}/commits/${commitStr})` :
      commitStr
  }
}
1209274
function procES6(src, base, dest = '', handle_error = false, min = false) {
    const babelOptions = requireJSON.parse(fs.readFileSync('./.babelrc', 'utf8'));
    let bo = Object.assign(babelOptions);
    let bplg = bo.plugins || (bo.plugins = []);
    bplg.push("external-helpers");
    bo.exclude = "node_modules/**";

    let plugins = [
        // require('rollup-plugin-strip')(),
        require('rollup-plugin-babel')(bo),
    ];

    if ( min ) {
        plugins.push(require('rollup-plugin-uglify')({
            output: {
                comments: function(node, comment) {
                    let { value, type } = comment;
                    // multiline comment
                    if (type === "comment2") {
                        return /@preserve|@license|@cc_on/i.test(value);
                    }
                },
            },
        }));
    }

    let s = gulp.src(src, { base })
        .pipe($.sourcemaps.init({loadMaps:true}))
        // .pipe($.babel(babelOptions))

        .pipe($.betterRollup({ plugins }, 'umd'))
        // .pipe($.rename((fn)=>{fn.basename = path.basename(fn.basename, '.es')}))
    ;
    if ( handle_error ) {
        handle_stream_error(s);
    }
    if ( min ) {
        s = s.pipe($.rename({extname: '.min.js'}));
    }
    s = s.pipe($.sourcemaps.write('.'));
    if ( dest ) {
        s = s.pipe(gulp.dest(dest));
    }
    return s;
}
160341
function parseRELEASES(content) {
    return _.chain(stripBom(content))
        .replace('\r\n', '\n')
        .split('\n')
        .map(function(line) {
            var parts = releaseRe.exec(line);
            if (!parts) return null;

            var filename = parts[2];
            var isDelta = filename.indexOf('-full.nupkg') == -1;

            var filenameParts = filename
                .replace(".nupkg", "")
                .replace("-delta", "")
                .replace("-full", "")
                .split(/\.|-/)
                .reverse();

            var version = _.chain(filenameParts)
                .filter(function(x) {
                    return /^\d+$/.exec(x);
                })
                .reverse()
                .value()
                .join('.');

            return {
                sha: parts[1],
                filename: filename,
                size: Number(parts[3]),
                isDelta: isDelta,
                version: version,
                semver: toSemver(version)
            };
        })
        .compact()
        .value();
}
1233609
function getCleanTargets() {
    var directDeps = targets.map(function (pattern) {
            return '*/' + pattern;
        }),

        indirectDeps = targets.map(function (pattern) {
            return '**/node_modules/*/' + pattern;
        });

    return directDeps.concat(indirectDeps);
}
1322759
function patch(node, languages) {
    var data = node.data || {};
    var primary = languages[0][0];

    data.language = primary === 'und' ? null : primary;
    data.languages = languages;

    node.data = data;
}
489016
function getTransformMacroExpressions(babelTemplate) {
  return {
    visitor: {
        StringLiteral(path) {
            const node = path.node;
            if (!node.macro) {
                // This has nothing to do with macros but it's necessary to prevent
                // Babel from escaping Unicode strings. See #784
                if (typeof node.value === "string") {
                    node.extra = {
                        raw: JSON.stringify(node.value),
                        rawValue: node.value,
                    };
                }
                return;
            }

            const DOLLAR_REGEX = /\$\d+/g;
            const buildArgs = {};
            const originalMacro = node.value;
            let macro = originalMacro;

            try {
                // Check if there are more placeholders than args, this may happen
                // if null optional arguments have been removed.
                let m = null;
                const placeholders = [];
                const args = node.args || [];

                // tslint:disable-next-line:no-conditional-assignment
                while (m = DOLLAR_REGEX.exec(macro)) {
                    placeholders.push(parseInt(m[0].substr(1), 10));
                }

                if (placeholders.length > 0) {
                    const max = placeholders.reduce((x, y) => Math.max(x, y));
                    // If there're actually more args than placeholders (e.g `$0($1...)`), use the args length
                    const argsLength = Math.max(max + 1, args.length);
                    for (let i = 0; i < argsLength; i++) {
                        buildArgs["$" + String(i)] =
                            args[i] == null
                                ? { type: "NullLiteral" }
                                : args[i];
                    }
                }

                macro = macro
                    // Macro transformations, see http://fable.io/docs/interacting.html#emit-attribute
                    .replace(/\$(\d+)\.\.\./, (_, i) => {
                        const rep = [];
                        for (let j = parseInt(i, 10); j < args.length; j++) {
                            rep.push("$" + j);
                        }
                        return rep.join(",");
                    })
                    .replace(/\{\{\s*\$(\d+)\s*\?(.*?)\:(.*?)\}\}/g, (_, g1, g2, g3) => {
                        const i = parseInt(g1, 10);
                        return typeof args[i] === "object" && args[i].value ? g2 : g3;
                    })
                    .replace(/\{\{([^\}]*\$(\d+).*?)\}\}/g, (_, g1, g2) => {
                        const i = parseInt(g2, 10);
                        return typeof args[i] === "object" && args[i].type !== "NullLiteral" ? g1 : "";
                    })
                    .replace(/\$(\d+)!/, (_, i) => {
                        const arg = args[parseInt(i, 10)]
                        return typeof arg === "object" && arg.type === "StringLiteral" ? arg.value : "";
                    });

                // Babel 7 throws error if there're unused arguments, remove them
                const actualArgs = [];
                const buildArgKeys = Object.keys(buildArgs);

                // tslint:disable-next-line:no-conditional-assignment
                while (m = DOLLAR_REGEX.exec(macro)) {
                    actualArgs.push(m[0]);
                }
                for (const key of buildArgKeys) {
                    if (actualArgs.indexOf(key) < 0) {
                        delete buildArgs[key];
                    }
                }

                // console.log("MACRO 1", originalMacro);
                // console.log("MACRO 2", macro);
                // console.log("MACRO ARGS", buildArgs);

                const builtMacro = babelTemplate(macro, {
                    placeholderPattern: /^\$\d+$/,
                })(buildArgs);

                if (builtMacro != null) {
                    path.replaceWithMultiple(builtMacro);
                } else {
                    // Apparently if the macro is just a string, babel-template will fail
                    path.replaceWith({
                        type: "StringLiteral",
                        value: JSON.parse(macro),
                    });
                }
            } catch (err) {
                throw new Error(
                    "BABEL ERROR: Failed to parse macro: " + originalMacro + " -> " + macro + "\n" +
                    "MACRO ARGUMENTS: " + Object.keys(buildArgs).join() + "\n" +
                    err.message);
            }
        },
    },
  };
}
162207
function extract(npmignore) {
  if (npmignore == null) {
    throw new Error('npmignore expects a string.');
  }

  var lines = split(npmignore);
  var len = lines.length;
  var npmignored = false;
  var git = [];
  var npm = [];
  var i = 0;

  while (i < len) {
    var line = lines[i++];
    if (re.test(line)) {
      npmignored = true;
    }

    if (npmignored) {
      npm.push(line);
    } else {
      git.push(line);
    }
  }

  return npm;
}
272142
function patchMakeErrFromCode() {
  const func = errors.makeErrFromCode;
  function makeErrFromCodeHook() {
    const err = func.apply(null, arguments);
    patchErrorBody(err, {});
    return err;
  }
  errors.makeErrFromCode = makeErrFromCodeHook;

  // Deprecated.
  // See https://github.com/restify/errors/blob/master/lib/index.js#L126
  errors.codeToHttpError = makeErrFromCodeHook;
}
1243267
function applyPatch (oldStr, uniDiff) {
  var diffstr = uniDiff.split('\n');
  var diff = [];
  var remEOFNL = false,
      addEOFNL = false;

  // i = 4 in order to skip diff headers.
  for (var i = 4; i < diffstr.length; i++) {
    if(diffstr[i][0] === '@') {
      var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
      diff.unshift({
        start:meh[3],
        oldlength:meh[2],
        oldlines:[],
        newlength:meh[4],
        newlines:[]
      });
    } else if(diffstr[i][0] === '+') {
      diff[0].newlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '-') {
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === ' ') {
      diff[0].newlines.push(diffstr[i].substr(1));
      diff[0].oldlines.push(diffstr[i].substr(1));
    } else if(diffstr[i][0] === '\\') {
      if (diffstr[i-1][0] === '+') {
        remEOFNL = true;
      } else if(diffstr[i-1][0] === '-') {
        addEOFNL = true;
      }
    }
  }

  var str = oldStr.split('\n');
  for (i = diff.length - 1; i >= 0; i--) {
    var d = diff[i];
    for (var j = 0; j < d.oldlength; j++) {
      if(str[d.start-1+j] !== d.oldlines[j]) {
        return false;
      }
    }
    Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
  }

  if (remEOFNL) {
    while (!str[str.length-1]) {
      str.pop();
    }
  } else if (addEOFNL) {
    str.push('');
  }
  return str.join('\n');
}