Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

2.5 KB
Raw Blame
"use strict";

/**
 * Some settings and code related to Mocha's handling of Node.js/V8 flags.
 * @private
 * @module
 */

const inspector = require("node:inspector");
const nodeFlags = process.allowedNodeEnvironmentFlags;
const {
  isMochaFlag,
  stripLeadingDashes,
} = require("./run-option-metadata.cjs");
const { unparseNodeFlags } = require("./unparse-args.js");

/**
 * These flags are considered "debug" flags.
 * @see {@link impliesNoTimeouts}
 * @private
 */
const debugFlags = new Set(["inspect", "inspect-brk"]);

/**
 * Mocha has historical support for various `node` and V8 flags which might not
 * appear in `process.allowedNodeEnvironmentFlags`.
 * These include:
 *   - `--preserve-symlinks`
 *   - `--harmony-*`
 *   - `--gc-global`
 *   - `--trace-*`
 *   - `--es-staging`
 *   - `--use-strict`
 *   - `--v8-*` (but *not* `--v8-options`)
 * @summary Whether or not to pass a flag along to the `node` executable.
 * @param {string} flag - Flag to test
 * @param {boolean} [bareword=true] - If `false`, we expect `flag` to have one or two leading dashes.
 * @returns {boolean} If the flag is considered a "Node" flag.
 * @private
 */
function isNodeFlag(flag, bareword = true) {
  if (!bareword) {
    // check if the flag begins with dashes; if not, not a node flag.
    if (!/^--?/.test(flag)) {
      return false;
    }
    // strip the leading dashes to match against subsequent checks
    flag = stripLeadingDashes(flag);
  }
  return (
    // check actual node flags from `process.allowedNodeEnvironmentFlags`,
    // then historical support for various V8 and non-`NODE_OPTIONS` flags
    // and also any V8 flags with `--v8-` prefix
    (!isMochaFlag(flag) && nodeFlags && nodeFlags.has(flag)) ||
    debugFlags.has(flag) ||
    /(?:preserve-symlinks(?:-main)?|harmony(?:[_-]|$)|(?:trace[_-].+$)|gc[_-]global$|es[_-]staging$|use[_-]strict$|v8[_-](?!options).+?$)/.test(
      flag,
    )
  );
}

/**
 * Returns `true` if the flag is a "debug-like" flag.  These require timeouts
 * to be suppressed, or pausing the debugger on breakpoints will cause test failures.
 * @param {string} flag - Flag to test
 * @returns {boolean}
 * @private
 */
function impliesNoTimeouts(flag) {
  return debugFlags.has(flag);
}

/**
 * Returns `true` if the Node.js inspector is active.
 * @returns {boolean}
 * @private
 */
function isInspectorActive() {
  return inspector.url() !== undefined;
}

exports.isNodeFlag = isNodeFlag;
exports.impliesNoTimeouts = impliesNoTimeouts;
exports.isInspectorActive = isInspectorActive;
exports.unparseNodeFlags = unparseNodeFlags;