/*
should.js - assertion library
Copyright(c) 2010-2013 TJ Holowaychuk <tj@vision-media.ca>
Copyright(c) 2013-2017 Denis Bardadym <bardadymchik@gmail.com>
MIT Licensed
182454
function matchingAssertions(should, Assertion) {
  var i = should.format;

  /**
   * Asserts if given object match `other` object, using some assumptions:
   * First object matched if they are equal,
   * If `other` is a regexp and given object is a string check on matching with regexp
   * If `other` is a regexp and given object is an array check if all elements matched regexp
   * If `other` is a regexp and given object is an object check values on matching regexp
   * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched
   * If `other` is an object check if the same keys matched with above rules
   * All other cases failed.
   *
   * Usually it is right idea to add pre type assertions, like `.String()` or `.Object()` to be sure assertions will do what you are expecting.
   * Object iteration happen by keys (properties with enumerable: true), thus some objects can cause small pain. Typical example is js
   * Error - it by default has 2 properties `name` and `message`, but they both non-enumerable. In this case make sure you specify checking props (see examples).
   *
   * @name match
   * @memberOf Assertion
   * @category assertion matching
   * @param {*} other Object to match
   * @param {string} [description] Optional message
   * @example
   * 'foobar'.should.match(/^foo/);
   * 'foobar'.should.not.match(/^bar/);
   *
   * ({ a: 'foo', c: 'barfoo' }).should.match(/foo$/);
   *
   * ['a', 'b', 'c'].should.match(/[a-z]/);
   *
   * (5).should.not.match(function(n) {
   *   return n < 0;
   * });
   * (5).should.not.match(function(it) {
   *    it.should.be.an.Array();
   * });
   * ({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should
   * .match({ a: 10, b: /c$/, c: function(it) {
   *    return it.should.have.property('d', 10);
   * }});
   *
   * [10, 'abc', { d: 10 }, 0].should
   * .match({ '0': 10, '1': /c$/, '2': function(it) {
   *    return it.should.have.property('d', 10);
   * }});
   *
   * var myString = 'abc';
   *
   * myString.should.be.a.String().and.match(/abc/);
   *
   * myString = {};
   *
   * myString.should.match(/abc/); //yes this will pass
   * //better to do
   * myString.should.be.an.Object().and.not.empty().and.match(/abc/);//fixed
   *
   * (new Error('boom')).should.match(/abc/);//passed because no keys
   * (new Error('boom')).should.not.match({ message: /abc/ });//check specified property
   */
  Assertion.add("match", function(other, description) {
    this.params = { operator: "to match " + i(other), message: description };

    if (eq(this.obj, other).length !== 0) {
      if (other instanceof RegExp) {
        // something - regex

        if (typeof this.obj == "string") {
          this.assert(other.exec(this.obj));
        } else if (null != this.obj && typeof this.obj == "object") {
          var notMatchedProps = [],
            matchedProps = [];
          forEach(
            this.obj,
            function(value, name) {
              if (other.exec(value)) {
                matchedProps.push(formatProp(name));
              } else {
                notMatchedProps.push(formatProp(name) + " (" + i(value) + ")");
              }
            },
            this
          );

          if (notMatchedProps.length) {
            this.params.operator += "\n    not matched properties: " + notMatchedProps.join(", ");
          }
          if (matchedProps.length) {
            this.params.operator += "\n    matched properties: " + matchedProps.join(", ");
          }

          this.assert(notMatchedProps.length === 0);
        } else {
          // should we try to convert to String and exec?
          this.assert(false);
        }
      } else if (typeof other == "function") {
        var res;

        res = other(this.obj);

        //if we throw exception ok - it is used .should inside
        if (typeof res == "boolean") {
          this.assert(res); // if it is just boolean function assert on it
        }
      } else if (typeof this.obj == "object" && this.obj != null && (isPlainObject(other) || Array.isArray(other))) {
        // try to match properties (for Object and Array)
        notMatchedProps = [];
        matchedProps = [];

        forEach(
          other,
          function(value, key) {
            try {
              should(this.obj)
                .have.property(key)
                .which.match(value);
              matchedProps.push(formatProp(key));
            } catch (e) {
              if (e instanceof should.AssertionError) {
                notMatchedProps.push(formatProp(key) + " (" + i(this.obj[key]) + ")");
              } else {
                throw e;
              }
            }
          },
          this
        );

        if (notMatchedProps.length) {
          this.params.operator += "\n    not matched properties: " + notMatchedProps.join(", ");
        }
        if (matchedProps.length) {
          this.params.operator += "\n    matched properties: " + matchedProps.join(", ");
        }

        this.assert(notMatchedProps.length === 0);
      } else {
        this.assert(false);
      }
    }
  });

  /**
   * Asserts if given object values or array elements all match `other` object, using some assumptions:
   * First object matched if they are equal,
   * If `other` is a regexp - matching with regexp
   * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched
   * All other cases check if this `other` equal to each element
   *
   * @name matchEach
   * @memberOf Assertion
   * @category assertion matching
   * @alias Assertion#matchEvery
   * @param {*} other Object to match
   * @param {string} [description] Optional message
   * @example
   * [ 'a', 'b', 'c'].should.matchEach(/\w+/);
   * [ 'a', 'a', 'a'].should.matchEach('a');
   *
   * [ 'a', 'a', 'a'].should.matchEach(function(value) { value.should.be.eql('a') });
   *
   * { a: 'a', b: 'a', c: 'a' }.should.matchEach(function(value) { value.should.be.eql('a') });
   */
  Assertion.add("matchEach", function(other, description) {
    this.params = {
      operator: "to match each " + i(other),
      message: description
    };

    forEach(
      this.obj,
      function(value) {
        should(value).match(other);
      },
      this
    );
  });

  /**
  * Asserts if any of given object values or array elements match `other` object, using some assumptions:
  * First object matched if they are equal,
  * If `other` is a regexp - matching with regexp
  * If `other` is a function check if this function throws AssertionError on given object or return false - it will be assumed as not matched
  * All other cases check if this `other` equal to each element
  *
  * @name matchAny
  * @memberOf Assertion
  * @category assertion matching
  * @param {*} other Object to match
  * @alias Assertion#matchSome
  * @param {string} [description] Optional message
  * @example
  * [ 'a', 'b', 'c'].should.matchAny(/\w+/);
  * [ 'a', 'b', 'c'].should.matchAny('a');
  *
  * [ 'a', 'b', 'c'].should.matchAny(function(value) { value.should.be.eql('a') });
  *
  * { a: 'a', b: 'b', c: 'c' }.should.matchAny(function(value) { value.should.be.eql('a') });
  */
  Assertion.add("matchAny", function(other, description) {
    this.params = {
      operator: "to match any " + i(other),
      message: description
    };

    this.assert(
      some(this.obj, function(value) {
        try {
          should(value).match(other);
          return true;
        } catch (e) {
          if (e instanceof should.AssertionError) {
            // Caught an AssertionError, return false to the iterator
            return false;
          }
          throw e;
        }
      })
    );
  });

  Assertion.alias("matchAny", "matchSome");
  Assertion.alias("matchEach", "matchEvery");
}
1329082
function assertEqualsDelta(msg, expected, actual, epsilon) {
	var args = this.argsWithOptionalMsg_(arguments, 4);
	jstestdriver.assertCount++;
	msg = args[0];
	expected = args[1];
	actual = args[2];
	epsilon = args[3];

	if (!compareDelta_(expected, actual, epsilon)) {
		this.fail(msg + 'expected ' + epsilon + ' within ' +
							this.prettyPrintEntity_(expected) +
							' but was ' + this.prettyPrintEntity_(actual) + '');
	}
	return true;
}
880180
function checkThatExecutableExists(next) {
        fs.exists(nodeCompiler.releasePath, function(exists) {
          if (!exists) {
            _log(
              'error',
              'The release executable has not been generated. ' +
                'This indicates a failure in the build process. ' +
                'There is likely additional information above.',
            );
            process.exit(1);
          } else {
            next();
          }
        });
      }
688963
function fileExists(fileName) {
  return new BbPromise((resolve) => {
    fs.exists(fileName, (exists) => resolve(exists));
  });
}
24961
function assertDeprecations(object, path, properties) {
  let errors = [];

  (properties || []).forEach(({ property, use }) => {
    if (get(object, property, undefined) !== undefined) {
      errors = [
        ...errors,
        {
          path,
          id: object.id,
          error: `${object.type} is using the '${property}' property. It's deprecated and will be removed.${use ? ` Use '${use}' instead` : ''}.`,
        },
      ];
    }
  });

  return errors;
}
63880
function AssertionError (options) {
  options = options || {};
  this.message = options.message;
  this.actual = options.actual;
  this.expected = options.expected;
  this.operator = options.operator;
  this.showDiff = options.showDiff;

  if (options.stackStartFunction && Error.captureStackTrace) {
    var stackStartFunction = options.stackStartFunction;
    Error.captureStackTrace(this, stackStartFunction);
  }
}
358663
function verifyPackageTree() {
  const depsToCheck = [
    // These are packages most likely to break in practice.
    // See https://github.com/echo008/xmi/issues/1795 for reasons why.
    // I have not included Babel here because plugins typically don't import Babel (so it's not affected).
    'babel-eslint',
    'babel-jest',
    'babel-loader',
    'eslint',
    'jest',
    'webpack',
    'webpack-dev-server',
  ];
  // Inlined from semver-regex, MIT license.
  // Don't want to make this a dependency after ejecting.
  const getSemverRegex = () =>
    /\bv?(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[\da-z-]+(?:\.[\da-z-]+)*)?(?:\+[\da-z-]+(?:\.[\da-z-]+)*)?\b/gi;
  const ownPackageJson = require('../../package.json');
  const expectedVersionsByDep = {};
  // Gather wanted deps
  depsToCheck.forEach(dep => {
    const expectedVersion = ownPackageJson.dependencies[dep];
    if (!expectedVersion) {
      throw new Error('This dependency list is outdated, fix it.');
    }
    if (!getSemverRegex().test(expectedVersion)) {
      throw new Error(
        `The ${dep} package should be pinned, instead got version ${expectedVersion}.`
      );
    }
    expectedVersionsByDep[dep] = expectedVersion;
  });
  // Verify we don't have other versions up the tree
  let currentDir = __dirname;
  // eslint-disable-next-line no-constant-condition
  while (true) {
    const previousDir = currentDir;
    currentDir = path.resolve(currentDir, '..');
    if (currentDir === previousDir) {
      // We've reached the root.
      break;
    }
    const maybeNodeModules = path.resolve(currentDir, 'node_modules');
    if (!fs.existsSync(maybeNodeModules)) {
      continue;
    }
    depsToCheck.forEach(dep => {
      const maybeDep = path.resolve(maybeNodeModules, dep);
      if (!fs.existsSync(maybeDep)) {
        return;
      }
      const maybeDepPackageJson = path.resolve(maybeDep, 'package.json');
      if (!fs.existsSync(maybeDepPackageJson)) {
        return;
      }
      const depPackageJson = JSON.parse(
        fs.readFileSync(maybeDepPackageJson, 'utf8')
      );
      const expectedVersion = expectedVersionsByDep[dep];
      if (depPackageJson.version !== expectedVersion) {
        console.error(
          chalk.red(
            `\nThere might be a problem with the project dependency tree.\n` +
              `It is likely ${chalk.bold(
                'not'
              )} a bug in Create React App, but something you need to fix locally.\n\n`
          ) +
            `The ${chalk.bold(
              ownPackageJson.name
            )} package provided by Create React App requires a dependency:\n\n` +
            chalk.green(
              `  "${chalk.bold(dep)}": "${chalk.bold(expectedVersion)}"\n\n`
            ) +
            `Don't try to install it manually: your package manager does it automatically.\n` +
            `However, a different version of ${chalk.bold(
              dep
            )} was detected higher up in the tree:\n\n` +
            `  ${chalk.bold(chalk.red(maybeDep))} (version: ${chalk.bold(
              chalk.red(depPackageJson.version)
            )}) \n\n` +
            `Manually installing incompatible versions is known to cause hard-to-debug issues.\n\n` +
            chalk.red(
              `If prefer to ignore this check, add ${chalk.bold(
                'SKIP_PREFLIGHT_CHECK=true'
              )} to an ${chalk.bold('.env')} file in your project.\n` +
                `That will permanently disable this message but you might encounter other issues.\n\n`
            ) +
            `To ${chalk.green(
              'fix'
            )} the dependency tree, try following the steps below in the exact order:\n\n` +
            `  ${chalk.cyan('1.')} Delete ${chalk.bold(
              'package-lock.json'
            )} (${chalk.underline('not')} ${chalk.bold(
              'package.json'
            )}!) and/or ${chalk.bold('yarn.lock')} in your project folder.\n` +
            `  ${chalk.cyan('2.')} Delete ${chalk.bold(
              'node_modules'
            )} in your project folder.\n` +
            `  ${chalk.cyan('3.')} Remove "${chalk.bold(
              dep
            )}" from ${chalk.bold('dependencies')} and/or ${chalk.bold(
              'devDependencies'
            )} in the ${chalk.bold(
              'package.json'
            )} file in your project folder.\n` +
            `  ${chalk.cyan('4.')} Run ${chalk.bold(
              'npm install'
            )} or ${chalk.bold(
              'yarn'
            )}, depending on the package manager you use.\n\n` +
            `In most cases, this should be enough to fix the problem.\n` +
            `If this has not helped, there are a few other things you can try:\n\n` +
            `  ${chalk.cyan('5.')} If you used ${chalk.bold(
              'npm'
            )}, install ${chalk.bold(
              'yarn'
            )} (http://yarnpkg.com/) and repeat the above steps with it instead.\n` +
            `     This may help because npm has known issues with package hoisting which may get resolved in future versions.\n\n` +
            `  ${chalk.cyan('6.')} Check if ${chalk.bold(
              maybeDep
            )} is outside your project directory.\n` +
            `     For example, you might have accidentally installed something in your home folder.\n\n` +
            `  ${chalk.cyan('7.')} Try running ${chalk.bold(
              `npm ls ${dep}`
            )} in your project folder.\n` +
            `     This will tell you which ${chalk.underline(
              'other'
            )} package (apart from the expected ${chalk.bold(
              ownPackageJson.name
            )}) installed ${chalk.bold(dep)}.\n\n` +
            `If nothing else helps, add ${chalk.bold(
              'SKIP_PREFLIGHT_CHECK=true'
            )} to an ${chalk.bold('.env')} file in your project.\n` +
            `That would permanently disable this preflight check in case you want to proceed anyway.\n\n` +
            chalk.cyan(
              `P.S. We know this message is long but please read the steps above :-) We hope you find them helpful!\n`
            )
        );
        process.exit(1);
      }
    });
  }
}
1072228
function verify(parts, asPrefix) {
	const has = arrayHas(parts);

	if (has('only') + has('skip') + has('todo') > 1) {
		return false;
	}

	const beforeAfterCount = has('before') + has('beforeEach') + has('after') + has('afterEach');

	if (beforeAfterCount > 1) {
		return false;
	}

	if (beforeAfterCount === 1) {
		if (has('only')) {
			return false;
		}
	}

	if (has('always')) {
		// `always` can only be used with `after` or `afterEach`.
		// Without it can still be a valid prefix
		if (has('after') || has('afterEach')) {
			return true;
		}

		if (!verify(parts.concat(['after']), false) && !verify(parts.concat(['afterEach']), false)) {
			// If `after` nor `afterEach` cannot be added to this prefix,
			// `always` is not allowed here.
			return false;
		}

		// Only allowed as a prefix
		return asPrefix;
	}

	return true;
}
305038
function moduleExistsAtPath(modPath) {
	for (var i = 0; i < CODE_EXTENSIONS.length; i += 1) {
		var fileName = 'index' + CODE_EXTENSIONS[i];
		var filePath = path.join(modPath, fileName);

		if (fs.existsSync(filePath)) {
			return true;
		}
	}

	return false;
}
1345637
function ruleSync(filePath) {
  var ruleId = path.basename(filePath)
  var result = {}
  var tests = {}
  var description
  var code
  var tags
  var name

  ruleId = ruleId.slice('remark-lint-'.length)
  code = fs.readFileSync(path.join(filePath, 'index.js'), 'utf-8')
  tags = dox.parseComments(code)[0].tags
  description = find(tags, 'fileoverview')
  name = find(tags, 'module')

  /* istanbul ignore if */
  if (name !== ruleId) {
    throw new Error(ruleId + ' has an invalid `@module`: ' + name)
  }

  /* istanbul ignore if */
  if (!description) {
    throw new Error(ruleId + ' is missing a `@fileoverview`')
  }

  description = strip(description)

  result.ruleId = ruleId
  result.description = trim(description)
  result.tests = tests
  result.filePath = filePath

  find
    .all(tags, 'example')
    .map(strip)
    .forEach(check)

  return result

  function check(example) {
    var lines = example.split('\n')
    var value = strip(lines.slice(1).join('\n'))
    var info
    var setting
    var context
    var name

    try {
      info = JSON.parse(lines[0])
    } catch (error) {
      /* istanbul ignore next */
      throw new Error(
        'Could not parse example in ' + ruleId + ':\n' + error.stack
      )
    }

    setting = JSON.stringify(info.setting || true)
    context = tests[setting]
    name = info.name

    if (!context) {
      context = []
      tests[setting] = context
    }

    if (!info.label) {
      context[name] = {
        config: info.config || {},
        setting: setting,
        input: value,
        output: []
      }

      return
    }

    /* istanbul ignore if */
    if (info.label !== 'input' && info.label !== 'output') {
      throw new Error(
        'Expected `input` or `ouput` for `label` in ' +
          ruleId +
          ', not `' +
          info.label +
          '`'
      )
    }

    if (!context[name]) {
      context[name] = {config: info.config || {}}
    }

    context[name].setting = setting

    if (info.label === 'output') {
      value = value.split('\n')
    }

    context[name][info.label] = value
  }
}
619952
function(obj){
        console.warn('should.contain() is deprecated, use should.include()');
        this.obj.should.be.an.instanceof(Array);
        this.assert(
            ~this.obj.indexOf(obj)
            , function(){ return 'expected ' + this.inspect + ' to contain ' + i(obj) }
            , function(){ return 'expected ' + this.inspect + ' to not contain ' + i(obj) });
        return this;
    }
1222158
function componentExists(componentPath) {
  const existsInExtensions = fs.existsSync(path.resolve(EXTENSIONS_PATH, componentPath));
  const existsInWidgets = fs.existsSync(path.resolve(themes.getPath(), 'widgets', componentPath));

  return !(!existsInExtensions && !existsInWidgets);
}
278836
function checkInclude3(i) {
  const start = i;
  let l;

  if (l = checkAtkeyword(i)) i += l;
  else return 0;

  if (tokens[start + 1].value !== 'include') return 0;

  if (l = checkSC(i)) i += l;
  else return 0;

  if (l = checkIdentOrInterpolation(i)) i += l;
  else return 0;

  if (l = checkSC(i)) i += l;

  if (l = checkArguments(i)) i += l;
  else return 0;

  return i - start;
}
276836
function AssertionError(actual, expected, phrase, base) {
  this.name = 'AssertionError';
  this.actual = actual;
  this.expected = expected;
  this.message = 'expected ' + objectDisplay(actual) + ' ' +
      phrase + ' ' +
    objectDisplay(expected);

  if (typeof actual === 'object' || typeof expected === 'object') {
    this.showDiff = true;
  }

  Error.captureStackTrace(this, base);
}
250726
function() {
            var assert = this;

            // Backwards compatibility fix.
            // Allows the direct use of global exported assertions and QUnit.assert.*
            // Although, it's use is not recommended as it can leak assertions
            // to other tests from async tests, because we only get a reference to the current test,
            // not exactly the test where assertion were intended to be called.
            if ( !QUnit.config.current ) {
                throw new Error( "assertion outside test context, in " + sourceFromStacktrace( 2 ) );
            }
            if ( !( assert instanceof Assert ) ) {
                assert = QUnit.config.current.assert;
            }
            return assert.test.push.apply( assert.test, arguments );
        }
722475
function checkPhantomjsVersion(phantomPath) {
  console.log('Found PhantomJS at', phantomPath, '...verifying')
  return kew.nfcall(cp.execFile, phantomPath, ['--version']).then(function (stdout) {
    var version = stdout.trim()
    if (helper.version == version) {
      return true
    } else {
      console.log('PhantomJS detected, but wrong version', stdout.trim(), '@', phantomPath + '.')
      return false
    }
  }).fail(function (err) {
    console.error('Error verifying phantomjs, continuing', err)
    return false
  })
}
277231
function _verifySignature(signature, value) {
        if (value === undefined) {
            console.assert(signature.optional === true, "Missing argument: " + signature.name);
        }
        return true;
    }