tools: update ESLint to 7.0.0-rc.0

PR-URL: https://github.com/nodejs/node/pull/33062
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
himself65 authored and Michaël Zasso committed 2020-05-13 17:52:53 +02:00
1 parent d08be9c8ca
commit 1c010b41a1
127 files changed
+11468 -9632

No files matched your search

+7 -7
View File
@@ -214,6 +214,11 @@ The people who review and implement new features.
<img src="https://github.com/aladdin-add.png?s=75" width="75" height="75"><br />
薛定谔的猫
</a>
</td><td align="center" valign="top" width="11%">
<a href="https://github.com/mdjermanovic">
<img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br />
Milos Djermanovic
</a>
</td></tr></tbody></table>
@@ -233,11 +238,6 @@ Pig Fang
<img src="https://github.com/yeonjuan.png?s=75" width="75" height="75"><br />
YeonJuan
</a>
</td><td align="center" valign="top" width="11%">
<a href="https://github.com/mdjermanovic">
<img src="https://github.com/mdjermanovic.png?s=75" width="75" height="75"><br />
Milos Djermanovic
</a>
</td></tr></tbody></table>
@@ -250,9 +250,9 @@ The following companies, organizations, and individuals support ESLint's ongoing
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
<h3>Gold Sponsors</h3>
<p><a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/eeb91aa/logo.png" alt="Shopify" height="96"></a> <a href="http://engineering.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://magiclab.co/?utm_source=eslint"><img src="https://images.opencollective.com/magiclab/bbf6345/logo.png" alt="MagicLab" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.shopify.com"><img src="https://images.opencollective.com/shopify/eeb91aa/logo.png" alt="Shopify" height="96"></a> <a href="https://www.salesforce.com"><img src="https://images.opencollective.com/salesforce/ca8f997/logo.png" alt="Salesforce" height="96"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://www.ampproject.org/"><img src="https://images.opencollective.com/amp/c8a3b25/logo.png" alt="AMP Project" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://www.kasinot.fi"><img src="https://images.opencollective.com/kasinot-fi/e09aa2e/logo.png" alt="Kasinot.fi" height="32"></a> <a href="https://www.pelisivut.com"><img src="https://images.opencollective.com/pelisivut/04f08f2/logo.png" alt="Pelisivut" height="32"></a> <a href="https://www.nettikasinot.org"><img src="https://images.opencollective.com/nettikasinot-org/bbd887f/logo.png" alt="Nettikasinot.org" height="32"></a> <a href="https://www.bonus.com.de/freispiele"><img src="https://images.opencollective.com/bonusfinder-deutschland/646169e/logo.png" alt="BonusFinder Deutschland" height="32"></a> <a href="https://medium.com/@niksundin/best-web-design-companies-1872e445775f"><img src="https://images.opencollective.com/top-web-design-agencies/d92d747/logo.png" alt="Top Web Design Agencies" height="32"></a> <a href="https://www.bugsnag.com/platforms?utm_source=Open Collective&utm_medium=Website&utm_content=open-source&utm_campaign=2019-community&utm_term="><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/0b37d14/logo.png" alt="Free Icons by Icons8" height="32"></a> <a href="https://uxplanet.org/top-ui-ux-design-agencies-user-experience-firms-8c54697e290"><img src="https://images.opencollective.com/ui-ux-design-agencies/cae5dfe/logo.png" alt="UI UX Design Agencies" height="32"></a> <a href="https://clay.global"><img src="https://images.opencollective.com/clayglobal/2468f34/logo.png" alt="clay" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a></p>
<p><a href="https://www.casinotop.com/"><img src="https://images.opencollective.com/casinotop-com/10fd95b/logo.png" alt="CasinoTop.com" height="32"></a> <a href="https://www.casinotopp.net/"><img src="https://images.opencollective.com/casino-topp/1dd399a/logo.png" alt="Casino Topp" height="32"></a> <a href="https://writersperhour.com/urgent-essay-writing-service"><img src="https://images.opencollective.com/writersperhour/5787d4b/logo.png" alt="Writers Per Hour" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://cooltechzone.com/netflix-vpn"><img src="https://images.opencollective.com/vpn-netflix/4850160/logo.png" alt="vpn netflix" height="32"></a> <a href="https://www.kasinot.fi"><img src="https://images.opencollective.com/kasinot-fi/e09aa2e/logo.png" alt="Kasinot.fi" height="32"></a> <a href="https://www.pelisivut.com"><img src="https://images.opencollective.com/pelisivut/04f08f2/logo.png" alt="Pelisivut" height="32"></a> <a href="https://www.nettikasinot.org"><img src="https://images.opencollective.com/nettikasinot-org/bbd887f/logo.png" alt="Nettikasinot.org" height="32"></a> <a href="https://www.bonus.com.de/freispiele"><img src="https://images.opencollective.com/bonusfinder-deutschland/646169e/logo.png" alt="BonusFinder Deutschland" height="32"></a> <a href="https://medium.com/@niksundin/best-web-design-companies-1872e445775f"><img src="https://images.opencollective.com/top-web-design-agencies/d92d747/logo.png" alt="Top Web Design Agencies" height="32"></a> <a href="https://www.bugsnag.com/platforms?utm_source=Open Collective&utm_medium=Website&utm_content=open-source&utm_campaign=2019-community&utm_term="><img src="https://images.opencollective.com/bugsnag-stability-monitoring/c2cef36/logo.png" alt="Bugsnag Stability Monitoring" height="32"></a> <a href="https://mixpanel.com"><img src="https://images.opencollective.com/mixpanel/cd682f7/logo.png" alt="Mixpanel" height="32"></a> <a href="https://www.vpsserver.com"><img src="https://images.opencollective.com/vpsservercom/logo.png" alt="VPS Server" height="32"></a> <a href="https://icons8.com"><img src="https://images.opencollective.com/icons8/0b37d14/logo.png" alt="Free Icons by Icons8" height="32"></a> <a href="https://uxplanet.org/top-ui-ux-design-agencies-user-experience-firms-8c54697e290"><img src="https://images.opencollective.com/ui-ux-design-agencies/cae5dfe/logo.png" alt="UI UX Design Agencies" height="32"></a> <a href="https://clay.global"><img src="https://images.opencollective.com/clayglobal/2468f34/logo.png" alt="clay" height="32"></a> <a href="https://discordapp.com"><img src="https://images.opencollective.com/discordapp/7e3d9a9/logo.png" alt="Discord" height="32"></a> <a href="https://themeisle.com"><img src="https://images.opencollective.com/themeisle/d5592fe/logo.png" alt="ThemeIsle" height="32"></a> <a href="https://tekhattan.com"><img src="https://images.opencollective.com/tekhattan/bc73c28/logo.png" alt="TekHattan" height="32"></a> <a href="https://www.marfeel.com/"><img src="https://images.opencollective.com/marfeel/4b88e30/logo.png" alt="Marfeel" height="32"></a> <a href="http://www.firesticktricks.com"><img src="https://images.opencollective.com/fire-stick-tricks/b8fbe2c/logo.png" alt="Fire Stick Tricks" height="32"></a></p>
<!--sponsorsend-->
## <a name="technology-sponsors"></a>Technology Sponsors
+117 -79
View File
@@ -12,97 +12,135 @@
// to use V8's code cache to speed up instantiation time
require("v8-compile-cache");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const useStdIn = process.argv.includes("--stdin"),
init = process.argv.includes("--init"),
debug = process.argv.includes("--debug");
// must do this initialization *before* other requires in order to work
if (debug) {
if (process.argv.includes("--debug")) {
require("debug").enable("eslint:*,-eslint:code-path");
}
//------------------------------------------------------------------------------
// Requirements
// Helpers
//------------------------------------------------------------------------------
// now we can safely include the other modules that use debug
const path = require("path"),
fs = require("fs"),
cli = require("../lib/cli");
/**
* Read data from stdin til the end.
*
* Note: See
* - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin
* - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io
* - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html
* - https://github.com/nodejs/node/issues/7439 (historical)
*
* On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems
* to read 4096 bytes before blocking and never drains to read further data.
*
* The investigation on the Emacs thread indicates:
*
* > Emacs on MS-Windows uses pipes to communicate with subprocesses; a
* > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than
* > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for
* > the subprocess to read its end of the pipe, at which time Emacs will
* > write the rest of the stuff.
* @returns {Promise<string>} The read text.
*/
function readStdin() {
return new Promise((resolve, reject) => {
let content = "";
let chunk = "";
process.stdin
.setEncoding("utf8")
.on("readable", () => {
while ((chunk = process.stdin.read()) !== null) {
content += chunk;
}
})
.on("end", () => resolve(content))
.on("error", reject);
});
}
/**
* Get the error message of a given value.
* @param {any} error The value to get.
* @returns {string} The error message.
*/
function getErrorMessage(error) {
// Lazy loading because those are used only if error happened.
const fs = require("fs");
const path = require("path");
const util = require("util");
const lodash = require("lodash");
// Foolproof -- thirdparty module might throw non-object.
if (typeof error !== "object" || error === null) {
return String(error);
}
// Use templates if `error.messageTemplate` is present.
if (typeof error.messageTemplate === "string") {
try {
const templateFilePath = path.resolve(
__dirname,
`../messages/${error.messageTemplate}.txt`
);
// Use sync API because Node.js should exit at this tick.
const templateText = fs.readFileSync(templateFilePath, "utf-8");
const template = lodash.template(templateText);
return template(error.messageData || {});
} catch {
// Ignore template error then fallback to use `error.stack`.
}
}
// Use the stacktrace if it's an error object.
if (typeof error.stack === "string") {
return error.stack;
}
// Otherwise, dump the object.
return util.format("%o", error);
}
/**
* Catch and report unexpected error.
* @param {any} error The thrown error object.
* @returns {void}
*/
function onFatalError(error) {
process.exitCode = 2;
const { version } = require("../package.json");
const message = getErrorMessage(error);
console.error(`
Oops! Something went wrong! :(
ESLint: ${version}
${message}`);
}
//------------------------------------------------------------------------------
// Execution
//------------------------------------------------------------------------------
process.once("uncaughtException", err => {
(async function main() {
process.on("uncaughtException", onFatalError);
process.on("unhandledRejection", onFatalError);
// lazy load
const lodash = require("lodash");
if (typeof err.messageTemplate === "string" && err.messageTemplate.length > 0) {
const template = lodash.template(fs.readFileSync(path.resolve(__dirname, `../messages/${err.messageTemplate}.txt`), "utf-8"));
const pkg = require("../package.json");
console.error("\nOops! Something went wrong! :(");
console.error(`\nESLint: ${pkg.version}.\n\n${template(err.messageData || {})}`);
} else {
console.error(err.stack);
// Call the config initializer if `--init` is present.
if (process.argv.includes("--init")) {
await require("../lib/init/config-initializer").initializeConfig();
return;
}
process.exitCode = 2;
});
if (useStdIn) {
/*
* Note: See
* - https://github.com/nodejs/node/blob/master/doc/api/process.md#processstdin
* - https://github.com/nodejs/node/blob/master/doc/api/process.md#a-note-on-process-io
* - https://lists.gnu.org/archive/html/bug-gnu-emacs/2016-01/msg00419.html
* - https://github.com/nodejs/node/issues/7439 (historical)
*
* On Windows using `fs.readFileSync(STDIN_FILE_DESCRIPTOR, "utf8")` seems
* to read 4096 bytes before blocking and never drains to read further data.
*
* The investigation on the Emacs thread indicates:
*
* > Emacs on MS-Windows uses pipes to communicate with subprocesses; a
* > pipe on Windows has a 4K buffer. So as soon as Emacs writes more than
* > 4096 bytes to the pipe, the pipe becomes full, and Emacs then waits for
* > the subprocess to read its end of the pipe, at which time Emacs will
* > write the rest of the stuff.
*
* Using the nodejs code example for reading from stdin.
*/
let contents = "",
chunk = "";
process.stdin.setEncoding("utf8");
process.stdin.on("readable", () => {
// Use a loop to make sure we read all available data.
while ((chunk = process.stdin.read()) !== null) {
contents += chunk;
}
});
process.stdin.on("end", () => {
process.exitCode = cli.execute(process.argv, contents, "utf8");
});
} else if (init) {
const configInit = require("../lib/init/config-initializer");
configInit.initializeConfig().then(() => {
process.exitCode = 0;
}).catch(err => {
process.exitCode = 1;
console.error(err.message);
console.error(err.stack);
});
} else {
process.exitCode = cli.execute(process.argv);
}
// Otherwise, call the CLI.
process.exitCode = await require("../lib/cli").execute(
process.argv,
process.argv.includes("--stdin") ? await readStdin() : null
);
}()).catch(onFatalError);
+2
View File
@@ -6,6 +6,7 @@
"use strict";
const { CLIEngine } = require("./cli-engine");
const { ESLint } = require("./eslint");
const { Linter } = require("./linter");
const { RuleTester } = require("./rule-tester");
const { SourceCode } = require("./source-code");
@@ -13,6 +14,7 @@ const { SourceCode } = require("./source-code");
module.exports = {
Linter,
CLIEngine,
ESLint,
RuleTester,
SourceCode
};
@@ -279,6 +279,18 @@ class CascadingConfigArrayFactory {
);
}
/**
* Set the config data to override all configs.
* Require to call `clearCache()` method after this method is called.
* @param {ConfigData} configData The config data to override all configs.
* @returns {void}
*/
setOverrideConfig(configData) {
const slots = internalSlotsMap.get(this);
slots.cliConfigData = configData;
}
/**
* Clear config cache.
* @returns {void}
+51 -46
View File
@@ -39,6 +39,7 @@ const validFixTypes = new Set(["problem", "suggestion", "layout"]);
// For VSCode IntelliSense
/** @typedef {import("../shared/types").ConfigData} ConfigData */
/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
/** @typedef {import("../shared/types").LintMessage} LintMessage */
/** @typedef {import("../shared/types").ParserOptions} ParserOptions */
/** @typedef {import("../shared/types").Plugin} Plugin */
@@ -50,29 +51,29 @@ const validFixTypes = new Set(["problem", "suggestion", "layout"]);
/**
* The options to configure a CLI engine with.
* @typedef {Object} CLIEngineOptions
* @property {boolean} allowInlineConfig Enable or disable inline configuration comments.
* @property {ConfigData} baseConfig Base config object, extended by all configs used with this CLIEngine instance
* @property {boolean} cache Enable result caching.
* @property {string} cacheLocation The cache file to use instead of .eslintcache.
* @property {string} configFile The configuration file to use.
* @property {string} cwd The value to use for the current working directory.
* @property {string[]} envs An array of environments to load.
* @property {string[]|null} extensions An array of file extensions to check.
* @property {boolean|Function} fix Execute in autofix mode. If a function, should return a boolean.
* @property {string[]} fixTypes Array of rule types to apply fixes for.
* @property {string[]} globals An array of global variables to declare.
* @property {boolean} ignore False disables use of .eslintignore.
* @property {string} ignorePath The ignore file to use instead of .eslintignore.
* @property {string|string[]} ignorePattern One or more glob patterns to ignore.
* @property {boolean} useEslintrc False disables looking for .eslintrc
* @property {string} parser The name of the parser to use.
* @property {ParserOptions} parserOptions An object of parserOption settings to use.
* @property {string[]} plugins An array of plugins to load.
* @property {Record<string,RuleConf>} rules An object of rules to use.
* @property {string[]} rulePaths An array of directories to load custom rules from.
* @property {boolean} reportUnusedDisableDirectives `true` adds reports for unused eslint-disable directives
* @property {boolean} globInputPaths Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
* @property {string} resolvePluginsRelativeTo The folder where plugins should be resolved from, defaulting to the CWD
* @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
* @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this CLIEngine instance
* @property {boolean} [cache] Enable result caching.
* @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
* @property {string} [configFile] The configuration file to use.
* @property {string} [cwd] The value to use for the current working directory.
* @property {string[]} [envs] An array of environments to load.
* @property {string[]|null} [extensions] An array of file extensions to check.
* @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
* @property {string[]} [fixTypes] Array of rule types to apply fixes for.
* @property {string[]} [globals] An array of global variables to declare.
* @property {boolean} [ignore] False disables use of .eslintignore.
* @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
* @property {string|string[]} [ignorePattern] One or more glob patterns to ignore.
* @property {boolean} [useEslintrc] False disables looking for .eslintrc
* @property {string} [parser] The name of the parser to use.
* @property {ParserOptions} [parserOptions] An object of parserOption settings to use.
* @property {string[]} [plugins] An array of plugins to load.
* @property {Record<string,RuleConf>} [rules] An object of rules to use.
* @property {string[]} [rulePaths] An array of directories to load custom rules from.
* @property {boolean} [reportUnusedDisableDirectives] `true` adds reports for unused eslint-disable directives
* @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
* @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD
*/
/**
@@ -88,13 +89,6 @@ const validFixTypes = new Set(["problem", "suggestion", "layout"]);
* @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/
/**
* Linting results.
* @typedef {Object} LintReport
@@ -821,16 +815,22 @@ class CLIEngine {
lintResultCache.reconcile();
}
// Collect used deprecated rules.
const usedDeprecatedRules = Array.from(
iterateRuleDeprecationWarnings(lastConfigArrays)
);
debug(`Linting complete in: ${Date.now() - startTime}ms`);
let usedDeprecatedRules;
return {
results,
...calculateStatsPerRun(results),
usedDeprecatedRules
// Initialize it lazily because CLI and `ESLint` API don't use it.
get usedDeprecatedRules() {
if (!usedDeprecatedRules) {
usedDeprecatedRules = Array.from(
iterateRuleDeprecationWarnings(lastConfigArrays)
);
}
return usedDeprecatedRules;
}
};
}
@@ -858,9 +858,9 @@ class CLIEngine {
const startTime = Date.now();
const resolvedFilename = filename && path.resolve(cwd, filename);
// Clear the last used config arrays.
lastConfigArrays.length = 0;
if (resolvedFilename && this.isPathIgnored(resolvedFilename)) {
if (warnIgnored) {
results.push(createIgnoreResult(resolvedFilename, cwd));
@@ -892,16 +892,22 @@ class CLIEngine {
}));
}
// Collect used deprecated rules.
const usedDeprecatedRules = Array.from(
iterateRuleDeprecationWarnings(lastConfigArrays)
);
debug(`Linting complete in: ${Date.now() - startTime}ms`);
let usedDeprecatedRules;
return {
results,
...calculateStatsPerRun(results),
usedDeprecatedRules
// Initialize it lazily because CLI and `ESLint` API don't use it.
get usedDeprecatedRules() {
if (!usedDeprecatedRules) {
usedDeprecatedRules = Array.from(
iterateRuleDeprecationWarnings(lastConfigArrays)
);
}
return usedDeprecatedRules;
}
};
}
@@ -955,11 +961,10 @@ class CLIEngine {
}
/**
* Returns the formatter representing the given format or null if no formatter
* with the given name can be found.
* Returns the formatter representing the given format or null if the `format` is not a string.
* @param {string} [format] The name of the format to load or the path to a
* custom formatter.
* @returns {Function} The formatter function or null if not found.
* @returns {(Function|null)} The formatter function or null if the `format` is not a string.
*/
getFormatter(format) {
+2 -2
View File
@@ -817,7 +817,7 @@ class ConfigArrayFactory {
if (configData) {
return this._normalizeConfigData(configData, {
...ctx,
filePath: plugin.filePath,
filePath: plugin.filePath || ctx.filePath,
name: `${ctx.name} » plugin:${plugin.id}/${configName}`
});
}
@@ -978,7 +978,7 @@ class ConfigArrayFactory {
if (plugin) {
return new ConfigDependency({
definition: normalizePlugin(plugin),
filePath: ctx.filePath,
filePath: "", // It's unknown where the plugin came from.
id,
importerName: ctx.name,
importerPath: ctx.filePath
+1 -1
View File
@@ -107,7 +107,7 @@ function getMatchedIndices(elements, filePath) {
for (let i = elements.length - 1; i >= 0; --i) {
const element = elements[i];
if (!element.criteria || element.criteria.test(filePath)) {
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
indices.push(i);
}
}
+7 -1
View File
@@ -71,7 +71,13 @@ function getCommonAncestorPath(sourcePaths) {
}
}
return result || path.sep;
let resolvedResult = result || path.sep;
// if Windows common ancestor is root of drive must have trailing slash to be absolute.
if (resolvedResult && resolvedResult.endsWith(":") && process.platform === "win32") {
resolvedResult += path.sep;
}
return resolvedResult;
}
/**
+188 -102
View File
@@ -17,105 +17,176 @@
const fs = require("fs"),
path = require("path"),
{ CLIEngine } = require("./cli-engine"),
options = require("./options"),
{ promisify } = require("util"),
{ ESLint } = require("./eslint"),
CLIOptions = require("./options"),
log = require("./shared/logging"),
RuntimeInfo = require("./shared/runtime-info");
const debug = require("debug")("eslint:cli");
//------------------------------------------------------------------------------
// Types
//------------------------------------------------------------------------------
/** @typedef {import("./eslint/eslint").ESLintOptions} ESLintOptions */
/** @typedef {import("./eslint/eslint").LintMessage} LintMessage */
/** @typedef {import("./eslint/eslint").LintResult} LintResult */
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const mkdir = promisify(fs.mkdir);
const stat = promisify(fs.stat);
const writeFile = promisify(fs.writeFile);
/**
* Predicate function for whether or not to apply fixes in quiet mode.
* If a message is a warning, do not apply a fix.
* @param {LintResult} lintResult The lint result.
* @param {LintMessage} message The lint result.
* @returns {boolean} True if the lint message is an error (and thus should be
* autofixed), false otherwise.
*/
function quietFixPredicate(lintResult) {
return lintResult.severity === 2;
function quietFixPredicate(message) {
return message.severity === 2;
}
/**
* Translates the CLI options into the options expected by the CLIEngine.
* @param {Object} cliOptions The CLI options to translate.
* @returns {CLIEngineOptions} The options object for the CLIEngine.
* @returns {ESLintOptions} The options object for the CLIEngine.
* @private
*/
function translateOptions(cliOptions) {
function translateOptions({
cache,
cacheFile,
cacheLocation,
config,
env,
errorOnUnmatchedPattern,
eslintrc,
ext,
fix,
fixDryRun,
fixType,
global,
ignore,
ignorePath,
ignorePattern,
inlineConfig,
parser,
parserOptions,
plugin,
quiet,
reportUnusedDisableDirectives,
resolvePluginsRelativeTo,
rule,
rulesdir
}) {
return {
envs: cliOptions.env,
extensions: cliOptions.ext,
rules: cliOptions.rule,
plugins: cliOptions.plugin,
globals: cliOptions.global,
ignore: cliOptions.ignore,
ignorePath: cliOptions.ignorePath,
ignorePattern: cliOptions.ignorePattern,
configFile: cliOptions.config,
rulePaths: cliOptions.rulesdir,
useEslintrc: cliOptions.eslintrc,
parser: cliOptions.parser,
parserOptions: cliOptions.parserOptions,
cache: cliOptions.cache,
cacheFile: cliOptions.cacheFile,
cacheLocation: cliOptions.cacheLocation,
fix: (cliOptions.fix || cliOptions.fixDryRun) && (cliOptions.quiet ? quietFixPredicate : true),
fixTypes: cliOptions.fixType,
allowInlineConfig: cliOptions.inlineConfig,
reportUnusedDisableDirectives: cliOptions.reportUnusedDisableDirectives,
resolvePluginsRelativeTo: cliOptions.resolvePluginsRelativeTo,
errorOnUnmatchedPattern: cliOptions.errorOnUnmatchedPattern
allowInlineConfig: inlineConfig,
cache,
cacheLocation: cacheLocation || cacheFile,
errorOnUnmatchedPattern,
extensions: ext,
fix: (fix || fixDryRun) && (quiet ? quietFixPredicate : true),
fixTypes: fixType,
ignore,
ignorePath,
overrideConfig: {
env: env && env.reduce((obj, name) => {
obj[name] = true;
return obj;
}, {}),
globals: global && global.reduce((obj, name) => {
if (name.endsWith(":true")) {
obj[name.slice(0, -5)] = "writable";
} else {
obj[name] = "readonly";
}
return obj;
}, {}),
ignorePatterns: ignorePattern,
parser,
parserOptions,
plugins: plugin,
rules: rule
},
overrideConfigFile: config,
reportUnusedDisableDirectives: reportUnusedDisableDirectives ? "error" : void 0,
resolvePluginsRelativeTo,
rulePaths: rulesdir,
useEslintrc: eslintrc
};
}
/**
* Count error messages.
* @param {LintResult[]} results The lint results.
* @returns {{errorCount:number;warningCount:number}} The number of error messages.
*/
function countErrors(results) {
let errorCount = 0;
let warningCount = 0;
for (const result of results) {
errorCount += result.errorCount;
warningCount += result.warningCount;
}
return { errorCount, warningCount };
}
/**
* Check if a given file path is a directory or not.
* @param {string} filePath The path to a file to check.
* @returns {Promise<boolean>} `true` if the given path is a directory.
*/
async function isDirectory(filePath) {
try {
return (await stat(filePath)).isDirectory();
} catch (error) {
if (error.code === "ENOENT" || error.code === "ENOTDIR") {
return false;
}
throw error;
}
}
/**
* Outputs the results of the linting.
* @param {CLIEngine} engine The CLIEngine to use.
* @param {ESLint} engine The ESLint instance to use.
* @param {LintResult[]} results The results to print.
* @param {string} format The name of the formatter to use or the path to the formatter.
* @param {string} outputFile The path for the output file.
* @returns {boolean} True if the printing succeeds, false if not.
* @returns {Promise<boolean>} True if the printing succeeds, false if not.
* @private
*/
function printResults(engine, results, format, outputFile) {
async function printResults(engine, results, format, outputFile) {
let formatter;
let rulesMeta;
try {
formatter = engine.getFormatter(format);
formatter = await engine.loadFormatter(format);
} catch (e) {
log.error(e.message);
return false;
}
const output = formatter(results, {
get rulesMeta() {
if (!rulesMeta) {
rulesMeta = {};
for (const [ruleId, rule] of engine.getRules()) {
rulesMeta[ruleId] = rule.meta;
}
}
return rulesMeta;
}
});
const output = formatter.format(results);
if (output) {
if (outputFile) {
const filePath = path.resolve(process.cwd(), outputFile);
if (fs.existsSync(filePath) && fs.statSync(filePath).isDirectory()) {
if (await isDirectory(filePath)) {
log.error("Cannot write to output file path, it is a directory: %s", outputFile);
return false;
}
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, output);
await mkdir(path.dirname(filePath), { recursive: true });
await writeFile(filePath, output);
} catch (ex) {
log.error("There was a problem writing the output file:\n%s", ex);
return false;
@@ -126,7 +197,6 @@ function printResults(engine, results, format, outputFile) {
}
return true;
}
//------------------------------------------------------------------------------
@@ -143,28 +213,33 @@ const cli = {
* Executes the CLI based on an array of arguments that is passed in.
* @param {string|Array|Object} args The arguments to process.
* @param {string} [text] The text to lint (used for TTY).
* @returns {int} The exit code for the operation.
* @returns {Promise<number>} The exit code for the operation.
*/
execute(args, text) {
async execute(args, text) {
if (Array.isArray(args)) {
debug("CLI args: %o", args.slice(2));
}
let currentOptions;
let options;
try {
currentOptions = options.parse(args);
options = CLIOptions.parse(args);
} catch (error) {
log.error(error.message);
return 2;
}
const files = currentOptions._;
const files = options._;
const useStdin = typeof text === "string";
if (currentOptions.version) {
if (options.help) {
log.info(CLIOptions.generateHelp());
return 0;
}
if (options.version) {
log.info(RuntimeInfo.version());
} else if (currentOptions.envInfo) {
return 0;
}
if (options.envInfo) {
try {
log.info(RuntimeInfo.environment());
return 0;
@@ -172,7 +247,9 @@ const cli = {
log.error(err.message);
return 2;
}
} else if (currentOptions.printConfig) {
}
if (options.printConfig) {
if (files.length) {
log.error("The --print-config option must be used with exactly one file name.");
return 2;
@@ -182,58 +259,67 @@ const cli = {
return 2;
}
const engine = new CLIEngine(translateOptions(currentOptions));
const fileConfig = engine.getConfigForFile(currentOptions.printConfig);
const engine = new ESLint(translateOptions(options));
const fileConfig =
await engine.calculateConfigForFile(options.printConfig);
log.info(JSON.stringify(fileConfig, null, " "));
return 0;
} else if (currentOptions.help || (!files.length && !useStdin)) {
log.info(options.generateHelp());
} else {
debug(`Running on ${useStdin ? "text" : "files"}`);
}
if (currentOptions.fix && currentOptions.fixDryRun) {
log.error("The --fix option and the --fix-dry-run option cannot be used together.");
return 2;
}
if (useStdin && currentOptions.fix) {
log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
return 2;
}
if (currentOptions.fixType && !currentOptions.fix && !currentOptions.fixDryRun) {
log.error("The --fix-type option requires either --fix or --fix-dry-run.");
return 2;
}
const engine = new CLIEngine(translateOptions(currentOptions));
const report = useStdin ? engine.executeOnText(text, currentOptions.stdinFilename, true) : engine.executeOnFiles(files);
if (currentOptions.fix) {
debug("Fix mode enabled - applying fixes");
CLIEngine.outputFixes(report);
}
if (currentOptions.quiet) {
debug("Quiet mode enabled - filtering out warnings");
report.results = CLIEngine.getErrorResults(report.results);
}
if (printResults(engine, report.results, currentOptions.format, currentOptions.outputFile)) {
const tooManyWarnings = currentOptions.maxWarnings >= 0 && report.warningCount > currentOptions.maxWarnings;
if (!report.errorCount && tooManyWarnings) {
log.error("ESLint found too many warnings (maximum: %s).", currentOptions.maxWarnings);
}
return (report.errorCount || tooManyWarnings) ? 1 : 0;
}
debug(`Running on ${useStdin ? "text" : "files"}`);
if (options.fix && options.fixDryRun) {
log.error("The --fix option and the --fix-dry-run option cannot be used together.");
return 2;
}
if (useStdin && options.fix) {
log.error("The --fix option is not available for piped-in code; use --fix-dry-run instead.");
return 2;
}
if (options.fixType && !options.fix && !options.fixDryRun) {
log.error("The --fix-type option requires either --fix or --fix-dry-run.");
return 2;
}
return 0;
const engine = new ESLint(translateOptions(options));
let results;
if (useStdin) {
results = await engine.lintText(text, {
filePath: options.stdinFilename,
warnIgnored: true
});
} else {
results = await engine.lintFiles(files);
}
if (options.fix) {
debug("Fix mode enabled - applying fixes");
await ESLint.outputFixes(results);
}
if (options.quiet) {
debug("Quiet mode enabled - filtering out warnings");
results = ESLint.getErrorResults(results);
}
if (await printResults(engine, results, options.format, options.outputFile)) {
const { errorCount, warningCount } = countErrors(results);
const tooManyWarnings =
options.maxWarnings >= 0 && warningCount > options.maxWarnings;
if (!errorCount && tooManyWarnings) {
log.error(
"ESLint found too many warnings (maximum: %s).",
options.maxWarnings
);
}
return (errorCount || tooManyWarnings) ? 1 : 0;
}
return 2;
}
};
+656
View File
@@ -0,0 +1,656 @@
/**
* @fileoverview Main API Class
* @author Kai Cataldo
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const path = require("path");
const fs = require("fs");
const { promisify } = require("util");
const { CLIEngine, getCLIEngineInternalSlots } = require("../cli-engine/cli-engine");
const BuiltinRules = require("../rules");
const { getRuleSeverity } = require("../shared/config-ops");
const { version } = require("../../package.json");
//------------------------------------------------------------------------------
// Typedefs
//------------------------------------------------------------------------------
/** @typedef {import("../cli-engine/cli-engine").LintReport} CLIEngineLintReport */
/** @typedef {import("../shared/types").DeprecatedRuleInfo} DeprecatedRuleInfo */
/** @typedef {import("../shared/types").ConfigData} ConfigData */
/** @typedef {import("../shared/types").LintMessage} LintMessage */
/** @typedef {import("../shared/types").Plugin} Plugin */
/** @typedef {import("../shared/types").Rule} Rule */
/** @typedef {import("./load-formatter").Formatter} Formatter */
/**
* The options with which to configure the ESLint instance.
* @typedef {Object} ESLintOptions
* @property {boolean} [allowInlineConfig] Enable or disable inline configuration comments.
* @property {ConfigData} [baseConfig] Base config object, extended by all configs used with this instance
* @property {boolean} [cache] Enable result caching.
* @property {string} [cacheLocation] The cache file to use instead of .eslintcache.
* @property {string} [cwd] The value to use for the current working directory.
* @property {boolean} [errorOnUnmatchedPattern] If `false` then `ESLint#lintFiles()` doesn't throw even if no target files found. Defaults to `true`.
* @property {string[]} [extensions] An array of file extensions to check.
* @property {boolean|Function} [fix] Execute in autofix mode. If a function, should return a boolean.
* @property {string[]} [fixTypes] Array of rule types to apply fixes for.
* @property {boolean} [globInputPaths] Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
* @property {boolean} [ignore] False disables use of .eslintignore.
* @property {string} [ignorePath] The ignore file to use instead of .eslintignore.
* @property {ConfigData} [overrideConfig] Override config object, overrides all configs used with this instance
* @property {string} [overrideConfigFile] The configuration file to use.
* @property {Record<string,Plugin>} [plugins] An array of plugin implementations.
* @property {"error" | "warn" | "off"} [reportUnusedDisableDirectives] the severity to report unused eslint-disable directives.
* @property {string} [resolvePluginsRelativeTo] The folder where plugins should be resolved from, defaulting to the CWD.
* @property {string[]} [rulePaths] An array of directories to load custom rules from.
* @property {boolean} [useEslintrc] False disables looking for .eslintrc.* files.
*/
/**
* A rules metadata object.
* @typedef {Object} RulesMeta
* @property {string} id The plugin ID.
* @property {Object} definition The plugin definition.
*/
/**
* A linting result.
* @typedef {Object} LintResult
* @property {string} filePath The path to the file that was linted.
* @property {LintMessage[]} messages All of the messages for the result.
* @property {number} errorCount Number of errors for the result.
* @property {number} warningCount Number of warnings for the result.
* @property {number} fixableErrorCount Number of fixable errors for the result.
* @property {number} fixableWarningCount Number of fixable warnings for the result.
* @property {string} [source] The source code of the file that was linted.
* @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
* @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules.
*/
/**
* Private members for the `ESLint` instance.
* @typedef {Object} ESLintPrivateMembers
* @property {CLIEngine} cliEngine The wrapped CLIEngine instance.
* @property {ESLintOptions} options The options used to instantiate the ESLint instance.
*/
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const writeFile = promisify(fs.writeFile);
/**
* The map with which to store private class members.
* @type {WeakMap<ESLint, ESLintPrivateMembers>}
*/
const privateMembersMap = new WeakMap();
/**
* Check if a given value is a non-empty string or not.
* @param {any} x The value to check.
* @returns {boolean} `true` if `x` is a non-empty string.
*/
function isNonEmptyString(x) {
return typeof x === "string" && x.trim() !== "";
}
/**
* Check if a given value is an array of non-empty stringss or not.
* @param {any} x The value to check.
* @returns {boolean} `true` if `x` is an array of non-empty stringss.
*/
function isArrayOfNonEmptyString(x) {
return Array.isArray(x) && x.every(isNonEmptyString);
}
/**
* Check if a given value is a valid fix type or not.
* @param {any} x The value to check.
* @returns {boolean} `true` if `x` is valid fix type.
*/
function isFixType(x) {
return x === "problem" || x === "suggestion" || x === "layout";
}
/**
* Check if a given value is an array of fix types or not.
* @param {any} x The value to check.
* @returns {boolean} `true` if `x` is an array of fix types.
*/
function isFixTypeArray(x) {
return Array.isArray(x) && x.every(isFixType);
}
/**
* The error for invalid options.
*/
class ESLintInvalidOptionsError extends Error {
constructor(messages) {
super(`Invalid Options:\n- ${messages.join("\n- ")}`);
this.code = "ESLINT_INVALID_OPTIONS";
Error.captureStackTrace(this, ESLintInvalidOptionsError);
}
}
/**
* Validates and normalizes options for the wrapped CLIEngine instance.
* @param {ESLintOptions} options The options to process.
* @returns {ESLintOptions} The normalized options.
*/
function processOptions({
allowInlineConfig = true, // ← we cannot use `overrideConfig.noInlineConfig` instead because `allowInlineConfig` has side-effect that suppress warnings that show inline configs are ignored.
baseConfig = null,
cache = false,
cacheLocation = ".eslintcache",
cwd = process.cwd(),
errorOnUnmatchedPattern = true,
extensions = null, // ← should be null by default because if it's an array then it suppresses RFC20 feature.
fix = false,
fixTypes = null, // ← should be null by default because if it's an array then it suppresses rules that don't have the `meta.type` property.
globInputPaths = true,
ignore = true,
ignorePath = null, // ← should be null by default because if it's a string then it may throw ENOENT.
overrideConfig = null,
overrideConfigFile = null,
plugins = {},
reportUnusedDisableDirectives = null, // ← should be null by default because if it's a string then it overrides the 'reportUnusedDisableDirectives' setting in config files. And we cannot use `overrideConfig.reportUnusedDisableDirectives` instead because we cannot configure the `error` severity with that.
resolvePluginsRelativeTo = null, // ← should be null by default because if it's a string then it suppresses RFC47 feature.
rulePaths = [],
useEslintrc = true,
...unknownOptions
}) {
const errors = [];
const unknownOptionKeys = Object.keys(unknownOptions);
if (unknownOptionKeys.length >= 1) {
errors.push(`Unknown options: ${unknownOptionKeys.join(", ")}`);
if (unknownOptionKeys.includes("cacheFile")) {
errors.push("'cacheFile' has been removed. Please use the 'cacheLocation' option instead.");
}
if (unknownOptionKeys.includes("configFile")) {
errors.push("'configFile' has been removed. Please use the 'overrideConfigFile' option instead.");
}
if (unknownOptionKeys.includes("envs")) {
errors.push("'envs' has been removed. Please use the 'overrideConfig.env' option instead.");
}
if (unknownOptionKeys.includes("globals")) {
errors.push("'globals' has been removed. Please use the 'overrideConfig.globals' option instead.");
}
if (unknownOptionKeys.includes("ignorePattern")) {
errors.push("'ignorePattern' has been removed. Please use the 'overrideConfig.ignorePatterns' option instead.");
}
if (unknownOptionKeys.includes("parser")) {
errors.push("'parser' has been removed. Please use the 'overrideConfig.parser' option instead.");
}
if (unknownOptionKeys.includes("parserOptions")) {
errors.push("'parserOptions' has been removed. Please use the 'overrideConfig.parserOptions' option instead.");
}
if (unknownOptionKeys.includes("rules")) {
errors.push("'rules' has been removed. Please use the 'overrideConfig.rules' option instead.");
}
}
if (typeof allowInlineConfig !== "boolean") {
errors.push("'allowInlineConfig' must be a boolean.");
}
if (typeof baseConfig !== "object") {
errors.push("'baseConfig' must be an object or null.");
}
if (typeof cache !== "boolean") {
errors.push("'cache' must be a boolean.");
}
if (!isNonEmptyString(cacheLocation)) {
errors.push("'cacheLocation' must be a non-empty string.");
}
if (!isNonEmptyString(cwd) || !path.isAbsolute(cwd)) {
errors.push("'cwd' must be an absolute path.");
}
if (typeof errorOnUnmatchedPattern !== "boolean") {
errors.push("'errorOnUnmatchedPattern' must be a boolean.");
}
if (!isArrayOfNonEmptyString(extensions) && extensions !== null) {
errors.push("'extensions' must be an array of non-empty strings or null.");
}
if (typeof fix !== "boolean" && typeof fix !== "function") {
errors.push("'fix' must be a boolean or a function.");
}
if (fixTypes !== null && !isFixTypeArray(fixTypes)) {
errors.push("'fixTypes' must be an array of any of \"problem\", \"suggestion\", and \"layout\".");
}
if (typeof globInputPaths !== "boolean") {
errors.push("'globInputPaths' must be a boolean.");
}
if (typeof ignore !== "boolean") {
errors.push("'ignore' must be a boolean.");
}
if (!isNonEmptyString(ignorePath) && ignorePath !== null) {
errors.push("'ignorePath' must be a non-empty string or null.");
}
if (typeof overrideConfig !== "object") {
errors.push("'overrideConfig' must be an object or null.");
}
if (!isNonEmptyString(overrideConfigFile) && overrideConfigFile !== null) {
errors.push("'overrideConfigFile' must be a non-empty string or null.");
}
if (typeof plugins !== "object") {
errors.push("'plugins' must be an object or null.");
} else if (plugins !== null && Object.keys(plugins).includes("")) {
errors.push("'plugins' must not include an empty string.");
}
if (Array.isArray(plugins)) {
errors.push("'plugins' doesn't add plugins to configuration to load. Please use the 'overrideConfig.plugins' option instead.");
}
if (
reportUnusedDisableDirectives !== "error" &&
reportUnusedDisableDirectives !== "warn" &&
reportUnusedDisableDirectives !== "off" &&
reportUnusedDisableDirectives !== null
) {
errors.push("'reportUnusedDisableDirectives' must be any of \"error\", \"warn\", \"off\", and null.");
}
if (
!isNonEmptyString(resolvePluginsRelativeTo) &&
resolvePluginsRelativeTo !== null
) {
errors.push("'resolvePluginsRelativeTo' must be a non-empty string or null.");
}
if (!isArrayOfNonEmptyString(rulePaths)) {
errors.push("'rulePaths' must be an array of non-empty strings.");
}
if (typeof useEslintrc !== "boolean") {
errors.push("'useElintrc' must be a boolean.");
}
if (errors.length > 0) {
throw new ESLintInvalidOptionsError(errors);
}
return {
allowInlineConfig,
baseConfig,
cache,
cacheLocation,
configFile: overrideConfigFile,
cwd,
errorOnUnmatchedPattern,
extensions,
fix,
fixTypes,
globInputPaths,
ignore,
ignorePath,
reportUnusedDisableDirectives,
resolvePluginsRelativeTo,
rulePaths,
useEslintrc
};
}
/**
* Check if a value has one or more properties and that value is not undefined.
* @param {any} obj The value to check.
* @returns {boolean} `true` if `obj` has one or more properties that that value is not undefined.
*/
function hasDefinedProperty(obj) {
if (typeof obj === "object" && obj !== null) {
for (const key in obj) {
if (typeof obj[key] !== "undefined") {
return true;
}
}
}
return false;
}
/**
* Create rulesMeta object.
* @param {Map<string,Rule>} rules a map of rules from which to generate the object.
* @returns {Object} metadata for all enabled rules.
*/
function createRulesMeta(rules) {
return Array.from(rules).reduce((retVal, [id, rule]) => {
retVal[id] = rule.meta;
return retVal;
}, {});
}
/** @type {WeakMap<ExtractedConfig, DeprecatedRuleInfo[]>} */
const usedDeprecatedRulesCache = new WeakMap();
/**
* Create used deprecated rule list.
* @param {CLIEngine} cliEngine The CLIEngine instance.
* @param {string} maybeFilePath The absolute path to a lint target file or `"<text>"`.
* @returns {DeprecatedRuleInfo[]} The used deprecated rule list.
*/
function getOrFindUsedDeprecatedRules(cliEngine, maybeFilePath) {
const {
configArrayFactory,
options: { cwd }
} = getCLIEngineInternalSlots(cliEngine);
const filePath = path.isAbsolute(maybeFilePath)
? maybeFilePath
: path.join(cwd, "__placeholder__.js");
const configArray = configArrayFactory.getConfigArrayForFile(filePath);
const config = configArray.extractConfig(filePath);
// Most files use the same config, so cache it.
if (!usedDeprecatedRulesCache.has(config)) {
const pluginRules = configArray.pluginRules;
const retv = [];
for (const [ruleId, ruleConf] of Object.entries(config.rules)) {
if (getRuleSeverity(ruleConf) === 0) {
continue;
}
const rule = pluginRules.get(ruleId) || BuiltinRules.get(ruleId);
const meta = rule && rule.meta;
if (meta && meta.deprecated) {
retv.push({ ruleId, replacedBy: meta.replacedBy || [] });
}
}
usedDeprecatedRulesCache.set(config, Object.freeze(retv));
}
return usedDeprecatedRulesCache.get(config);
}
/**
* Processes the linting results generated by a CLIEngine linting report to
* match the ESLint class's API.
* @param {CLIEngine} cliEngine The CLIEngine instance.
* @param {CLIEngineLintReport} report The CLIEngine linting report to process.
* @returns {LintResult[]} The processed linting results.
*/
function processCLIEngineLintReport(cliEngine, { results }) {
const descriptor = {
configurable: true,
enumerable: true,
get() {
return getOrFindUsedDeprecatedRules(cliEngine, this.filePath);
}
};
for (const result of results) {
Object.defineProperty(result, "usedDeprecatedRules", descriptor);
}
return results;
}
/**
* An Array.prototype.sort() compatible compare function to order results by their file path.
* @param {LintResult} a The first lint result.
* @param {LintResult} b The second lint result.
* @returns {number} An integer representing the order in which the two results should occur.
*/
function compareResultsByFilePath(a, b) {
if (a.filePath < b.filePath) {
return -1;
}
if (a.filePath > b.filePath) {
return 1;
}
return 0;
}
class ESLint {
/**
* Creates a new instance of the main ESLint API.
* @param {ESLintOptions} options The options for this instance.
*/
constructor(options = {}) {
const processedOptions = processOptions(options);
const cliEngine = new CLIEngine(processedOptions);
const {
additionalPluginPool,
configArrayFactory,
lastConfigArrays
} = getCLIEngineInternalSlots(cliEngine);
let updated = false;
/*
* Address `plugins` to add plugin implementations.
* Operate the `additionalPluginPool` internal slot directly to avoid
* using `addPlugin(id, plugin)` method that resets cache everytime.
*/
if (options.plugins) {
for (const [id, plugin] of Object.entries(options.plugins)) {
additionalPluginPool.set(id, plugin);
updated = true;
}
}
/*
* Address `overrideConfig` to set override config.
* Operate the `configArrayFactory` internal slot directly because this
* functionality doesn't exist as the public API of CLIEngine.
*/
if (hasDefinedProperty(options.overrideConfig)) {
configArrayFactory.setOverrideConfig(options.overrideConfig);
updated = true;
}
// Update caches.
if (updated) {
configArrayFactory.clearCache();
lastConfigArrays[0] = configArrayFactory.getConfigArrayForFile();
}
// Initialize private properties.
privateMembersMap.set(this, {
cliEngine,
options: processedOptions
});
}
/**
* The version text.
* @type {string}
*/
static get version() {
return version;
}
/**
* Outputs fixes from the given results to files.
* @param {LintResult[]} results The lint results.
* @returns {Promise<void>} Returns a promise that is used to track side effects.
*/
static async outputFixes(results) {
if (!Array.isArray(results)) {
throw new Error("'results' must be an array");
}
await Promise.all(
results
.filter(result => {
if (typeof result !== "object" || result === null) {
throw new Error("'results' must include only objects");
}
return (
typeof result.output === "string" &&
path.isAbsolute(result.filePath)
);
})
.map(r => writeFile(r.filePath, r.output))
);
}
/**
* Returns results that only contains errors.
* @param {LintResult[]} results The results to filter.
* @returns {LintResult[]} The filtered results.
*/
static getErrorResults(results) {
return CLIEngine.getErrorResults(results);
}
/**
* Executes the current configuration on an array of file and directory names.
* @param {string[]} patterns An array of file and directory names.
* @returns {Promise<LintResult[]>} The results of linting the file patterns given.
*/
async lintFiles(patterns) {
if (!isNonEmptyString(patterns) && !isArrayOfNonEmptyString(patterns)) {
throw new Error("'patterns' must be a non-empty string or an array of non-empty strings");
}
const { cliEngine } = privateMembersMap.get(this);
return processCLIEngineLintReport(
cliEngine,
cliEngine.executeOnFiles(patterns)
);
}
/**
* Executes the current configuration on text.
* @param {string} code A string of JavaScript code to lint.
* @param {Object} [options] The options.
* @param {string} [options.filePath] The path to the file of the source code.
* @param {boolean} [options.warnIgnored] When set to true, warn if given filePath is an ignored path.
* @returns {Promise<LintResult[]>} The results of linting the string of code given.
*/
async lintText(code, options = {}) {
if (typeof code !== "string") {
throw new Error("'code' must be a string");
}
if (typeof options !== "object") {
throw new Error("'options' must be an object, null, or undefined");
}
const {
filePath,
warnIgnored = false,
...unknownOptions
} = options || {};
for (const key of Object.keys(unknownOptions)) {
throw new Error(`'options' must not include the unknown option '${key}'`);
}
if (filePath !== void 0 && !isNonEmptyString(filePath)) {
throw new Error("'options.filePath' must be a non-empty string or undefined");
}
if (typeof warnIgnored !== "boolean") {
throw new Error("'options.warnIgnored' must be a boolean or undefined");
}
const { cliEngine } = privateMembersMap.get(this);
return processCLIEngineLintReport(
cliEngine,
cliEngine.executeOnText(code, filePath, warnIgnored)
);
}
/**
* Returns the formatter representing the given formatter name.
* @param {string} [name] The name of the formattter to load.
* The following values are allowed:
* - `undefined` ... Load `stylish` builtin formatter.
* - A builtin formatter name ... Load the builtin formatter.
* - A thirdparty formatter name:
* - `foo` → `eslint-formatter-foo`
* - `@foo` → `@foo/eslint-formatter`
* - `@foo/bar` → `@foo/eslint-formatter-bar`
* - A file path ... Load the file.
* @returns {Promise<Formatter>} A promise resolving to the formatter object.
* This promise will be rejected if the given formatter was not found or not
* a function.
*/
async loadFormatter(name = "stylish") {
if (typeof name !== "string") {
throw new Error("'name' must be a string");
}
const { cliEngine } = privateMembersMap.get(this);
const formatter = cliEngine.getFormatter(name);
if (typeof formatter !== "function") {
throw new Error(`Formatter must be a function, but got a ${typeof formatter}.`);
}
return {
/**
* The main formatter method.
* @param {LintResults[]} results The lint results to format.
* @returns {string} The formatted lint results.
*/
format(results) {
let rulesMeta = null;
results.sort(compareResultsByFilePath);
return formatter(results, {
get rulesMeta() {
if (!rulesMeta) {
rulesMeta = createRulesMeta(cliEngine.getRules());
}
return rulesMeta;
}
});
}
};
}
/**
* Returns a configuration object for the given file based on the CLI options.
* This is the same logic used by the ESLint CLI executable to determine
* configuration for each file it processes.
* @param {string} filePath The path of the file to retrieve a config object for.
* @returns {Promise<ConfigData>} A configuration object for the file.
*/
async calculateConfigForFile(filePath) {
if (!isNonEmptyString(filePath)) {
throw new Error("'filePath' must be a non-empty string");
}
const { cliEngine } = privateMembersMap.get(this);
return cliEngine.getConfigForFile(filePath);
}
/**
* Checks if a given path is ignored by ESLint.
* @param {string} filePath The path of the file to check.
* @returns {Promise<boolean>} Whether or not the given path is ignored.
*/
async isPathIgnored(filePath) {
if (!isNonEmptyString(filePath)) {
throw new Error("'filePath' must be a non-empty string");
}
const { cliEngine } = privateMembersMap.get(this);
return cliEngine.isPathIgnored(filePath);
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
ESLint,
/**
* Get the private class members of a given ESLint instance for tests.
* @param {ESLint} instance The ESLint instance to get.
* @returns {ESLintPrivateMembers} The instance's private class members.
*/
getESLintPrivateMembers(instance) {
return privateMembersMap.get(instance);
}
};
+7
View File
@@ -0,0 +1,7 @@
"use strict";
const { ESLint } = require("./eslint");
module.exports = {
ESLint
};
+4 -4
View File
@@ -301,7 +301,7 @@ class Registry {
ruleSetIdx += 1;
if (cb) {
cb(totalFilesLinting); // eslint-disable-line callback-return
cb(totalFilesLinting); // eslint-disable-line node/callback-return
}
});
@@ -316,10 +316,10 @@ class Registry {
/**
* Extract rule configuration into eslint:recommended where possible.
*
* This will return a new config with `"extends": "eslint:recommended"` and
* This will return a new config with `["extends": [ ..., "eslint:recommended"]` and
* only the rules which have configurations different from the recommended config.
* @param {Object} config config object
* @returns {Object} config object using `"extends": "eslint:recommended"`
* @returns {Object} config object using `"extends": ["eslint:recommended"]`
*/
function extendFromRecommended(config) {
const newConfig = Object.assign({}, config);
@@ -333,7 +333,7 @@ function extendFromRecommended(config) {
delete newConfig.rules[ruleId];
}
});
newConfig.extends = RECOMMENDED_CONFIG_NAME;
newConfig.extends.unshift(RECOMMENDED_CONFIG_NAME);
return newConfig;
}
+2 -4
View File
@@ -15,6 +15,7 @@ const util = require("util"),
inquirer = require("inquirer"),
ProgressBar = require("progress"),
semver = require("semver"),
espree = require("espree"),
recConfig = require("../../conf/eslint-recommended"),
ConfigOps = require("../shared/config-ops"),
log = require("../shared/logging"),
@@ -31,8 +32,6 @@ const debug = require("debug")("eslint:config-initializer");
// Private
//------------------------------------------------------------------------------
const DEFAULT_ECMA_VERSION = 2018;
/* istanbul ignore next: hard to test fs function */
/**
* Create .eslintrc file in the current working directory
@@ -265,8 +264,7 @@ function processAnswers(answers) {
extends: []
};
// set the latest ECMAScript version
config.parserOptions.ecmaVersion = DEFAULT_ECMA_VERSION;
config.parserOptions.ecmaVersion = espree.latestEcmaVersion;
config.env.es6 = true;
config.globals = {
Atomics: "readonly",
+2 -2
View File
@@ -23,7 +23,7 @@ const { CLIEngine } = require("../cli-engine");
* TODO1: Expose the API that enumerates target files.
* TODO2: Extract the creation logic of `SourceCode` from `Linter` class.
*/
const { getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); // eslint-disable-line no-restricted-modules
const { getCLIEngineInternalSlots } = require("../cli-engine/cli-engine"); // eslint-disable-line node/no-restricted-require
const debug = require("debug")("eslint:source-code-utils");
@@ -97,7 +97,7 @@ function getSourceCodeOfFiles(patterns, options, callback) {
sourceCodes[filename] = sourceCode;
}
if (callback) {
callback(filenames.length); // eslint-disable-line callback-return
callback(filenames.length); // eslint-disable-line node/callback-return
}
});
-1
View File
@@ -46,7 +46,6 @@ module.exports = optionator({
{
option: "ext",
type: "[String]",
default: ".js",
description: "Specify JavaScript file extensions"
},
{
+6 -1
View File
@@ -563,7 +563,12 @@ class RuleTester {
output = SourceCodeFixer.applyFixes(code, messages).output;
const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
assert(!errorMessageInFix, `A fatal parsing error occurred in autofix: ${errorMessageInFix && errorMessageInFix.message}`);
assert(!errorMessageInFix, [
"A fatal parsing error occurred in autofix.",
`Error: ${errorMessageInFix && errorMessageInFix.message}`,
"Autofix output:",
output
].join("\n"));
} else {
output = code;
}
+3 -18
View File
@@ -29,22 +29,6 @@ function isReachable(segment) {
return segment.reachable;
}
/**
* Gets a readable location.
*
* - FunctionExpression -> the function name or `function` keyword.
* - ArrowFunctionExpression -> `=>` token.
* @param {ASTNode} node A function node to get.
* @param {SourceCode} sourceCode A source code to get tokens.
* @returns {ASTNode|Token} The node or the token of a location.
*/
function getLocation(node, sourceCode) {
if (node.type === "ArrowFunctionExpression") {
return sourceCode.getTokenBefore(node.body);
}
return node.id || node;
}
/**
* Checks a given node is a MemberExpression node which has the specified name's
* property.
@@ -179,6 +163,7 @@ module.exports = {
create(context) {
const options = context.options[0] || { allowImplicit: false, checkForEach: false };
const sourceCode = context.getSourceCode();
let funcInfo = {
arrayMethodName: null,
@@ -217,12 +202,12 @@ module.exports = {
}
if (messageId) {
let name = astUtils.getFunctionNameWithKind(funcInfo.node);
let name = astUtils.getFunctionNameWithKind(node);
name = messageId === "expectedNoReturnValue" ? lodash.upperFirst(name) : name;
context.report({
node,
loc: getLocation(node, context.getSourceCode()).loc.start,
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
messageId,
data: { name }
});
+4
View File
@@ -10,6 +10,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/callback-return"],
type: "suggestion",
docs: {
+3 -8
View File
@@ -146,10 +146,7 @@ module.exports = {
// lone comma
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.start.column
},
loc: commaToken.loc,
messageId: "unexpectedLineBeforeAndAfterComma",
fix: getFixerFunction(styleType, previousItemToken, commaToken, currentItemToken)
});
@@ -158,6 +155,7 @@ module.exports = {
context.report({
node: reportItem,
loc: commaToken.loc,
messageId: "expectedCommaFirst",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
@@ -166,10 +164,7 @@ module.exports = {
context.report({
node: reportItem,
loc: {
line: commaToken.loc.end.line,
column: commaToken.loc.end.column
},
loc: commaToken.loc,
messageId: "expectedCommaLast",
fix: getFixerFunction(style, previousItemToken, commaToken, currentItemToken)
});
+4 -3
View File
@@ -63,7 +63,8 @@ module.exports = {
},
messages: {
unexpected: "Unexpected newline between function name and paren.",
unexpectedWhitespace: "Unexpected whitespace between function name and paren.",
unexpectedNewline: "Unexpected newline between function name and paren.",
missing: "Missing space between function name and paren."
}
},
@@ -116,7 +117,7 @@ module.exports = {
context.report({
node,
loc: leftToken.loc.start,
messageId: "unexpected",
messageId: "unexpectedWhitespace",
fix(fixer) {
/*
@@ -143,7 +144,7 @@ module.exports = {
context.report({
node,
loc: leftToken.loc.start,
messageId: "unexpected",
messageId: "unexpectedNewline",
fix(fixer) {
return fixer.replaceTextRange([leftToken.range[1], rightToken.range[0]], " ");
}
+2 -12
View File
@@ -25,17 +25,6 @@ function isReachable(segment) {
return segment.reachable;
}
/**
* Gets a readable location.
*
* - FunctionExpression -> the function name or `function` keyword.
* @param {ASTNode} node A function node to get.
* @returns {ASTNode|Token} The node or the token of a location.
*/
function getId(node) {
return node.id || node;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
@@ -75,6 +64,7 @@ module.exports = {
create(context) {
const options = context.options[0] || { allowImplicit: false };
const sourceCode = context.getSourceCode();
let funcInfo = {
upper: null,
@@ -99,7 +89,7 @@ module.exports = {
) {
context.report({
node,
loc: getId(node).loc.start,
loc: astUtils.getFunctionHeadLoc(node, sourceCode),
messageId: funcInfo.hasReturn ? "expectedAlways" : "expected",
data: {
name: astUtils.getFunctionNameWithKind(funcInfo.node)
+4
View File
@@ -48,6 +48,10 @@ function isShadowed(scope, node) {
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/global-require"],
type: "suggestion",
docs: {
+4
View File
@@ -11,6 +11,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/handle-callback-err"],
type: "suggestion",
docs: {
+1 -1
View File
@@ -45,7 +45,7 @@ function isSingleLine(node) {
/**
* Checks whether the properties on a single line.
* @param {ASTNode[]} properties List of Property AST nodes.
* @returns {boolean} True if all properies is on a single line.
* @returns {boolean} True if all properties is on a single line.
*/
function isSingleLineProperties(properties) {
const [firstProp] = properties,
+1 -1
View File
@@ -235,7 +235,7 @@ module.exports = {
callee = callee.property;
}
context.report({ node, loc: callee.loc.start, messageId });
context.report({ node, loc: callee.loc, messageId });
}
//--------------------------------------------------------------------------
+6 -3
View File
@@ -90,16 +90,19 @@ module.exports = {
}
if (depth > ignoreChainWithDepth && astUtils.isTokenOnSameLine(callee.object, callee.property)) {
const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken);
context.report({
node: callee.property,
loc: callee.property.loc.start,
loc: {
start: firstTokenAfterObject.loc.start,
end: callee.loc.end
},
messageId: "expected",
data: {
callee: getPropertyText(callee)
},
fix(fixer) {
const firstTokenAfterObject = sourceCode.getTokenAfter(callee.object, astUtils.isNotClosingParenToken);
return fixer.insertTextBefore(firstTokenAfterObject, "\n");
}
});
+4
View File
@@ -10,6 +10,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-deprecated-api"],
type: "problem",
docs: {
+1 -1
View File
@@ -151,7 +151,7 @@ module.exports = {
) {
context.report({
node,
loc: node.body.loc.start,
loc: node.body.loc,
messageId: "unexpected",
data: { name }
});
+5 -1
View File
@@ -560,7 +560,11 @@ module.exports = {
tokensToIgnore.add(secondToken);
}
if (hasExcessParens(node)) {
const hasExtraParens = node.parent.type === "ExportDefaultDeclaration"
? hasExcessParensWithPrecedence(node, PRECEDENCE_OF_ASSIGNMENT_EXPR)
: hasExcessParens(node);
if (hasExtraParens) {
report(node);
}
}
+30 -38
View File
@@ -5,10 +5,19 @@
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
const validParent = new Set(["Program", "ExportNamedDeclaration", "ExportDefaultDeclaration"]);
const validBlockStatementParent = new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
module.exports = {
meta: {
type: "problem",
@@ -33,54 +42,37 @@ module.exports = {
create(context) {
/**
* Find the nearest Program or Function ancestor node.
* @returns {Object} Ancestor's type and distance from node.
*/
function nearestBody() {
const ancestors = context.getAncestors();
let ancestor = ancestors.pop(),
generation = 1;
while (ancestor && ["Program", "FunctionDeclaration",
"FunctionExpression", "ArrowFunctionExpression"
].indexOf(ancestor.type) < 0) {
generation += 1;
ancestor = ancestors.pop();
}
return {
// Type of containing ancestor
type: ancestor.type,
// Separation between ancestor and node
distance: generation
};
}
/**
* Ensure that a given node is at a program or function body's root.
* @param {ASTNode} node Declaration node to check.
* @returns {void}
*/
function check(node) {
const body = nearestBody(),
valid = ((body.type === "Program" && body.distance === 1) ||
body.distance === 2);
const parent = node.parent;
if (!valid) {
context.report({
node,
messageId: "moveDeclToRoot",
data: {
type: (node.type === "FunctionDeclaration" ? "function" : "variable"),
body: (body.type === "Program" ? "program" : "function body")
}
});
if (
parent.type === "BlockStatement" && validBlockStatementParent.has(parent.parent.type)
) {
return;
}
if (validParent.has(parent.type)) {
return;
}
const upperFunction = astUtils.getUpperFunction(parent);
context.report({
node,
messageId: "moveDeclToRoot",
data: {
type: (node.type === "FunctionDeclaration" ? "function" : "variable"),
body: (upperFunction === null ? "program" : "function body")
}
});
}
return {
FunctionDeclaration: check,
+1 -1
View File
@@ -49,7 +49,7 @@ module.exports = {
}
/**
* Checks for any ocurrence of a BlockStatement in a place where lists of statements can appear
* Checks for any occurrence of a BlockStatement in a place where lists of statements can appear
* @param {ASTNode} node The node to check
* @returns {boolean} True if the node is a lone block.
*/
+4
View File
@@ -11,6 +11,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-mixed-requires"],
type: "suggestion",
docs: {
+15 -3
View File
@@ -5,6 +5,12 @@
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
@@ -28,10 +34,17 @@ module.exports = {
},
create(context) {
return {
NewExpression(node) {
const variable = astUtils.getVariableByName(
context.getScope(),
node.callee.name
);
if (variable && variable.identifiers.length > 0) {
return;
}
if (node.callee.name === "Object") {
context.report({
node,
@@ -40,6 +53,5 @@ module.exports = {
}
}
};
}
};
+4
View File
@@ -11,6 +11,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-new-require"],
type: "suggestion",
docs: {
+4
View File
@@ -10,6 +10,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-path-concat"],
type: "suggestion",
docs: {
+4
View File
@@ -10,6 +10,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-process-env"],
type: "suggestion",
docs: {
+4
View File
@@ -10,6 +10,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-process-exit"],
type: "suggestion",
docs: {
+4
View File
@@ -40,6 +40,10 @@ const arrayOfStringsOrObjects = {
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-restricted-require"],
type: "suggestion",
docs: {
+4
View File
@@ -13,6 +13,10 @@
module.exports = {
meta: {
deprecated: true,
replacedBy: ["node/no-sync"],
type: "suggestion",
docs: {
+22 -12
View File
@@ -53,7 +53,11 @@ module.exports = {
const nodeExpressionEnd = sourceCode.getTokenBefore(openParen);
if (openParen.loc.start.line !== nodeExpressionEnd.loc.end.line) {
context.report({ node, loc: openParen.loc.start, messageId, data: { char: openParen.value } });
context.report({
node,
loc: openParen.loc,
messageId
});
}
}
@@ -71,18 +75,24 @@ module.exports = {
},
TaggedTemplateExpression(node) {
if (node.tag.loc.end.line === node.quasi.loc.start.line) {
return;
const { quasi } = node;
// handles common tags, parenthesized tags, and typescript's generic type arguments
const tokenBefore = sourceCode.getTokenBefore(quasi);
if (tokenBefore.loc.end.line !== quasi.loc.start.line) {
context.report({
node,
loc: {
start: quasi.loc.start,
end: {
line: quasi.loc.start.line,
column: quasi.loc.start.column + 1
}
},
messageId: "taggedTemplate"
});
}
// handle generics type parameters on template tags
const tokenBefore = sourceCode.getTokenBefore(node.quasi);
if (tokenBefore.loc.end.line === node.quasi.loc.start.line) {
return;
}
context.report({ node, loc: node.loc.start, messageId: "taggedTemplate" });
},
CallExpression(node) {
+1 -1
View File
@@ -105,7 +105,7 @@ module.exports = {
context.report({
node,
loc: operatorToken.loc.start,
loc: operatorToken.loc,
messageId: "unexpectedConcat"
});
}
+5 -2
View File
@@ -127,7 +127,10 @@ module.exports = {
if (hasSpacing && functionConfig === "never") {
context.report({
node,
loc: leftToken.loc.end,
loc: {
start: leftToken.loc.end,
end: rightToken.loc.start
},
messageId: "unexpectedSpace",
fix(fixer) {
const comments = sourceCode.getCommentsBefore(rightToken);
@@ -145,7 +148,7 @@ module.exports = {
} else if (!hasSpacing && functionConfig === "always") {
context.report({
node,
loc: leftToken.loc.end,
loc: rightToken.loc,
messageId: "missingSpace",
fix: fixer => fixer.insertTextAfter(leftToken, " ")
});
+101 -51
View File
@@ -20,7 +20,7 @@ const astUtils = require("./utils/ast-utils");
* @returns {boolean} Whether or not it is a comparison operator.
*/
function isComparisonOperator(operator) {
return (/^(==|===|!=|!==|<|>|<=|>=)$/u).test(operator);
return /^(==|===|!=|!==|<|>|<=|>=)$/u.test(operator);
}
/**
@@ -29,7 +29,7 @@ function isComparisonOperator(operator) {
* @returns {boolean} Whether or not it is an equality operator.
*/
function isEqualityOperator(operator) {
return (/^(==|===)$/u).test(operator);
return /^(==|===)$/u.test(operator);
}
/**
@@ -50,10 +50,12 @@ function isRangeTestOperator(operator) {
* real literal and should be treated as such.
*/
function isNegativeNumericLiteral(node) {
return (node.type === "UnaryExpression" &&
return (
node.type === "UnaryExpression" &&
node.operator === "-" &&
node.prefix &&
astUtils.isNumericLiteral(node.argument));
astUtils.isNumericLiteral(node.argument)
);
}
/**
@@ -71,25 +73,21 @@ function isStaticTemplateLiteral(node) {
* @returns {boolean} True if the node should be treated as a single Literal node.
*/
function looksLikeLiteral(node) {
return isNegativeNumericLiteral(node) ||
isStaticTemplateLiteral(node);
return isNegativeNumericLiteral(node) || isStaticTemplateLiteral(node);
}
/**
* Attempts to derive a Literal node from nodes that are treated like literals.
* @param {ASTNode} node Node to normalize.
* @param {number} [defaultValue] The default value to be returned if the node
* is not a Literal.
* @returns {ASTNode} One of the following options.
* 1. The original node if the node is already a Literal
* 2. A normalized Literal node with the negative number as the value if the
* node represents a negative number literal.
* 3. A normalized Literal node with the string as the value if the node is
* a Template Literal without expression.
* 4. The Literal node which has the `defaultValue` argument if it exists.
* 5. Otherwise `null`.
* 4. Otherwise `null`.
*/
function getNormalizedLiteral(node, defaultValue) {
function getNormalizedLiteral(node) {
if (node.type === "Literal") {
return node;
}
@@ -110,14 +108,6 @@ function getNormalizedLiteral(node, defaultValue) {
};
}
if (defaultValue) {
return {
type: "Literal",
value: defaultValue,
raw: String(defaultValue)
};
}
return null;
}
@@ -183,7 +173,7 @@ module.exports = {
type: "suggestion",
docs: {
description: "require or disallow \"Yoda\" conditions",
description: 'require or disallow "Yoda" conditions',
category: "Best Practices",
recommended: false,
url: "https://eslint.org/docs/rules/yoda"
@@ -211,16 +201,19 @@ module.exports = {
fixable: "code",
messages: {
expected: "Expected literal to be on the {{expectedSide}} side of {{operator}}."
expected:
"Expected literal to be on the {{expectedSide}} side of {{operator}}."
}
},
create(context) {
// Default to "never" (!always) if no option
const always = (context.options[0] === "always");
const exceptRange = (context.options[1] && context.options[1].exceptRange);
const onlyEquality = (context.options[1] && context.options[1].onlyEquality);
const always = context.options[0] === "always";
const exceptRange =
context.options[1] && context.options[1].exceptRange;
const onlyEquality =
context.options[1] && context.options[1].onlyEquality;
const sourceCode = context.getSourceCode();
@@ -243,13 +236,23 @@ module.exports = {
* @returns {boolean} Whether node is a "between" range test.
*/
function isBetweenTest() {
let leftLiteral, rightLiteral;
if (node.operator === "&&" && same(left.right, right.left)) {
const leftLiteral = getNormalizedLiteral(left.left);
const rightLiteral = getNormalizedLiteral(right.right);
return (node.operator === "&&" &&
(leftLiteral = getNormalizedLiteral(left.left)) &&
(rightLiteral = getNormalizedLiteral(right.right, Number.POSITIVE_INFINITY)) &&
leftLiteral.value <= rightLiteral.value &&
same(left.right, right.left));
if (leftLiteral === null && rightLiteral === null) {
return false;
}
if (rightLiteral === null || leftLiteral === null) {
return true;
}
if (leftLiteral.value <= rightLiteral.value) {
return true;
}
}
return false;
}
/**
@@ -257,13 +260,24 @@ module.exports = {
* @returns {boolean} Whether node is an "outside" range test.
*/
function isOutsideTest() {
let leftLiteral, rightLiteral;
if (node.operator === "||" && same(left.left, right.right)) {
const leftLiteral = getNormalizedLiteral(left.right);
const rightLiteral = getNormalizedLiteral(right.left);
return (node.operator === "||" &&
(leftLiteral = getNormalizedLiteral(left.right, Number.NEGATIVE_INFINITY)) &&
(rightLiteral = getNormalizedLiteral(right.left)) &&
leftLiteral.value <= rightLiteral.value &&
same(left.left, right.right));
if (leftLiteral === null && rightLiteral === null) {
return false;
}
if (rightLiteral === null || leftLiteral === null) {
return true;
}
if (leftLiteral.value <= rightLiteral.value) {
return true;
}
}
return false;
}
/**
@@ -276,13 +290,15 @@ module.exports = {
return astUtils.isParenthesised(sourceCode, node);
}
return (node.type === "LogicalExpression" &&
return (
node.type === "LogicalExpression" &&
left.type === "BinaryExpression" &&
right.type === "BinaryExpression" &&
isRangeTestOperator(left.operator) &&
isRangeTestOperator(right.operator) &&
(isBetweenTest() || isOutsideTest()) &&
isParenWrapped());
isParenWrapped()
);
}
const OPERATOR_FLIP_MAP = {
@@ -303,21 +319,52 @@ module.exports = {
*/
function getFlippedString(node) {
const tokenBefore = sourceCode.getTokenBefore(node);
const operatorToken = sourceCode.getFirstTokenBetween(node.left, node.right, token => token.value === node.operator);
const textBeforeOperator = sourceCode.getText().slice(sourceCode.getTokenBefore(operatorToken).range[1], operatorToken.range[0]);
const textAfterOperator = sourceCode.getText().slice(operatorToken.range[1], sourceCode.getTokenAfter(operatorToken).range[0]);
const leftText = sourceCode.getText().slice(node.range[0], sourceCode.getTokenBefore(operatorToken).range[1]);
const operatorToken = sourceCode.getFirstTokenBetween(
node.left,
node.right,
token => token.value === node.operator
);
const textBeforeOperator = sourceCode
.getText()
.slice(
sourceCode.getTokenBefore(operatorToken).range[1],
operatorToken.range[0]
);
const textAfterOperator = sourceCode
.getText()
.slice(
operatorToken.range[1],
sourceCode.getTokenAfter(operatorToken).range[0]
);
const leftText = sourceCode
.getText()
.slice(
node.range[0],
sourceCode.getTokenBefore(operatorToken).range[1]
);
const firstRightToken = sourceCode.getTokenAfter(operatorToken);
const rightText = sourceCode.getText().slice(firstRightToken.range[0], node.range[1]);
const rightText = sourceCode
.getText()
.slice(firstRightToken.range[0], node.range[1]);
let prefix = "";
if (tokenBefore && tokenBefore.range[1] === node.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken)) {
if (
tokenBefore &&
tokenBefore.range[1] === node.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, firstRightToken)
) {
prefix = " ";
}
return prefix + rightText + textBeforeOperator + OPERATOR_FLIP_MAP[operatorToken.value] + textAfterOperator + leftText;
return (
prefix +
rightText +
textBeforeOperator +
OPERATOR_FLIP_MAP[operatorToken.value] +
textAfterOperator +
leftText
);
}
//--------------------------------------------------------------------------
@@ -331,8 +378,12 @@ module.exports = {
// If `expectedLiteral` is not a literal, and `expectedNonLiteral` is a literal, raise an error.
if (
(expectedNonLiteral.type === "Literal" || looksLikeLiteral(expectedNonLiteral)) &&
!(expectedLiteral.type === "Literal" || looksLikeLiteral(expectedLiteral)) &&
(expectedNonLiteral.type === "Literal" ||
looksLikeLiteral(expectedNonLiteral)) &&
!(
expectedLiteral.type === "Literal" ||
looksLikeLiteral(expectedLiteral)
) &&
!(!isEqualityOperator(node.operator) && onlyEquality) &&
isComparisonOperator(node.operator) &&
!(exceptRange && isRangeTest(context.getAncestors().pop()))
@@ -344,12 +395,11 @@ module.exports = {
operator: node.operator,
expectedSide: always ? "left" : "right"
},
fix: fixer => fixer.replaceText(node, getFlippedString(node))
fix: fixer =>
fixer.replaceText(node, getFlippedString(node))
});
}
}
};
}
};
+1
View File
@@ -11,6 +11,7 @@ const Module = require("module");
* `Module.createRequire` is added in v12.2.0. It supports URL as well.
* We only support the case where the argument is a filepath, not a URL.
*/
// eslint-disable-next-line node/no-unsupported-features/node-builtins, node/no-deprecated-api
const createRequire = Module.createRequire || Module.createRequireFromPath;
module.exports = {
+7
View File
@@ -141,3 +141,10 @@ module.exports = {};
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Function | Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
*/
@@ -73,5 +73,5 @@ function isIdentifierName(name) {
}
}
return true;
return !isFirst;
}
@@ -7,7 +7,7 @@
"unicode-13.0.0": "^0.8.0"
},
"exports": "./lib/index.js",
"gitHead": "8d5e422be27251cfaadf8dd2536b31b4a5024b02",
"gitHead": "5b97e77e030cf3853a147fdff81844ea4026219d",
"license": "MIT",
"main": "./lib/index.js",
"name": "@babel/helper-validator-identifier",
@@ -18,5 +18,5 @@
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-validator-identifier"
},
"version": "7.9.0"
"version": "7.9.5"
}
+44 -3
View File
@@ -8,8 +8,49 @@ The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/
[![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv)
[![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv)
[![Coverage Status](https://coveralls.io/repos/epoberezkin/ajv/badge.svg?branch=master&service=github)](https://coveralls.io/github/epoberezkin/ajv?branch=master)
[![Greenkeeper badge](https://badges.greenkeeper.io/epoberezkin/ajv.svg)](https://greenkeeper.io/)
[![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv)
[![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin)
## Please [sponsor Ajv](https://github.com/sponsors/epoberezkin)
Dear Ajv users! ❤️
I ask you to support the development of Ajv with donations. 🙏
Since 2015 Ajv has become widely used, thanks to your help and contributions:
- **90** contributors 🏗
- **5,000** dependent npm packages ⚙️
- **7,000** github stars, from GitHub users [all over the world](https://www.google.com/maps/d/u/0/viewer?mid=1MGRV8ciFUGIbO1l0EKFWNJGYE7iSkDxP&ll=-3.81666561775622e-14%2C4.821737100000007&z=2) ⭐️
- **5,000,000** dependent repositories on GitHub 🚀
- **120,000,000** npm downloads per month! 💯
Your donations will fund futher development - small and large improvements, support of the next versions of JSON Schema specification, and, possibly, the code should be migrated to TypeScript to make it more maintainable.
I will greatly appreciate anything you can help with to make it happen:
- a **personal** donation - from $2 ☕️
- your **company** donation - from $10 🍔
- a **sponsorship** to get promoted on Ajv or related packages - from $50 💰
- an **introduction** to a sponsor who would benefit from the promotion on Ajv page 🤝
| Please [make donations via my GitHub sponsors page](https://github.com/sponsors/epoberezkin)<br>‼️ **GitHub will DOUBLE them** ‼️ |
|---|
#### Open Collective sponsors
<a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a>
<a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a>
<a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a>
## Using version 6
@@ -273,7 +314,7 @@ The following formats are implemented for string validation with "format" keywor
__Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here.
There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, `email`, and `hostname`. See [Options](#options) for details.
There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details.
You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method.
@@ -1340,7 +1381,7 @@ If you have published a useful plugin please submit a PR to add it to the next s
- [ajv-keywords](https://github.com/epoberezkin/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.)
- [ajv-merge-patch](https://github.com/epoberezkin/ajv-merge-patch) - plugin with keywords $merge and $patch
- [ajv-pack](https://github.com/epoberezkin/ajv-pack) - produces a compact module exporting validation functions
- [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`).
## Some packages using Ajv
+2 -2
View File
@@ -1,3 +1,3 @@
/* ajv 6.12.0: Another JSON Schema Validator */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}}(function(){return function o(i,n,l){function c(r,e){if(!n[r]){if(!i[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(u)return u(r,!0);var a=new Error("Cannot find module '"+r+"'");throw a.code="MODULE_NOT_FOUND",a}var s=n[r]={exports:{}};i[r][0].call(s.exports,function(e){return c(i[r][1][e]||e)},s,s.exports,o,i,n,l)}return n[r].exports}for(var u="function"==typeof require&&require,e=0;e<l.length;e++)c(l[e]);return c}({1:[function(e,r,t){"use strict";var a=r.exports=function(){this._cache={}};a.prototype.put=function(e,r){this._cache[e]=r},a.prototype.get=function(e){return this._cache[e]},a.prototype.del=function(e){delete this._cache[e]},a.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){"use strict";var s=e("./error_classes").MissingRef;r.exports=function t(r,i,a){var n=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof i&&(a=i,i=void 0);var e=l(r).then(function(){var e=n._addSchema(r,void 0,i);return e.validate||c(e)});a&&e.then(function(e){a(null,e)},a);return e;function l(e){var r=e.$schema;return r&&!n.getSchema(r)?t.call(n,{$ref:r},!0):Promise.resolve()}function c(o){try{return n._compile(o)}catch(e){if(e instanceof s)return r(e);throw e}function r(e){var r=e.missingSchema;if(s(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");var t=n._loadingSchemas[r];return t||(t=n._loadingSchemas[r]=n._opts.loadSchema(r)).then(a,a),t.then(function(e){if(!s(r))return l(e).then(function(){s(r)||n.addSchema(e,r,void 0,i)})}).then(function(){return c(o)});function a(){delete n._loadingSchemas[r]}function s(e){return n._refs[e]||n._schemas[e]}}}}},{"./error_classes":3}],3:[function(e,r,t){"use strict";var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){"use strict";var a=e("./util"),o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,l=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,c=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[Line truncated
/* ajv 6.12.2: Another JSON Schema Validator */
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Ajv=e()}}(function(){return function o(i,n,l){function c(r,e){if(!n[r]){if(!i[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(u)return u(r,!0);var a=new Error("Cannot find module '"+r+"'");throw a.code="MODULE_NOT_FOUND",a}var s=n[r]={exports:{}};i[r][0].call(s.exports,function(e){return c(i[r][1][e]||e)},s,s.exports,o,i,n,l)}return n[r].exports}for(var u="function"==typeof require&&require,e=0;e<l.length;e++)c(l[e]);return c}({1:[function(e,r,t){"use strict";var a=r.exports=function(){this._cache={}};a.prototype.put=function(e,r){this._cache[e]=r},a.prototype.get=function(e){return this._cache[e]},a.prototype.del=function(e){delete this._cache[e]},a.prototype.clear=function(){this._cache={}}},{}],2:[function(e,r,t){"use strict";var a=e("./error_classes").MissingRef;function s(r,n,t){var l=this;if("function"!=typeof this._opts.loadSchema)throw new Error("options.loadSchema should be a function");"function"==typeof n&&(t=n,n=void 0);var e=c(r).then(function(){var e=l._addSchema(r,void 0,n);return e.validate||function o(i){try{return l._compile(i)}catch(e){if(e instanceof a)return r(e);throw e}function r(e){var r=e.missingSchema;if(s(r))throw new Error("Schema "+r+" is loaded but "+e.missingRef+" cannot be resolved");var t=l._loadingSchemas[r];return t||(t=l._loadingSchemas[r]=l._opts.loadSchema(r)).then(a,a),t.then(function(e){if(!s(r))return c(e).then(function(){s(r)||l.addSchema(e,r,void 0,n)})}).then(function(){return o(i)});function a(){delete l._loadingSchemas[r]}function s(e){return l._refs[e]||l._schemas[e]}}}(e)});return t&&e.then(function(e){t(null,e)},t),e;function c(e){var r=e.$schema;return r&&!l.getSchema(r)?s.call(l,{$ref:r},!0):Promise.resolve()}}r.exports=s},{"./error_classes":3}],3:[function(e,r,t){"use strict";var a=e("./resolve");function s(e,r,t){this.message=t||s.message(e,r),this.missingRef=a.url(e,r),this.missingSchema=a.normalizeId(a.fullPath(this.missingRef))}function o(e){return e.prototype=Object.create(Error.prototype),e.prototype.constructor=e}r.exports={Validation:o(function(e){this.message="validation failed",this.errors=e,this.ajv=this.validation=!0}),MissingRef:o(s)},s.message=function(e,r){return"can't resolve reference "+r+" from id "+e}},{"./resolve":6}],4:[function(e,r,t){"use strict";var a=e("./util"),o=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31],n=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,s=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,l=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,c=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,u=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[Line truncated
//# sourceMappingURL=ajv.min.js.map
+8 -4
View File
@@ -6,6 +6,10 @@
"url": "https://github.com/epoberezkin/ajv/issues"
},
"bundleDependencies": false,
"collective": {
"type": "opencollective",
"url": "https://opencollective.com/ajv"
},
"dependencies": {
"fast-deep-equal": "^3.1.1",
"fast-json-stable-stringify": "^2.0.0",
@@ -30,10 +34,10 @@
"js-beautify": "^1.7.3",
"jshint": "^2.10.2",
"json-schema-test": "^2.0.0",
"karma": "^4.0.1",
"karma": "^5.0.0",
"karma-chrome-launcher": "^3.0.0",
"karma-mocha": "^1.1.1",
"karma-sauce-launcher": "^2.0.0",
"karma-mocha": "^2.0.0",
"karma-sauce-launcher": "^4.1.3",
"mocha": "^7.0.1",
"nyc": "^15.0.0",
"pre-commit": "^1.1.1",
@@ -98,5 +102,5 @@
},
"tonicExampleFilename": ".tonic_example.js",
"typings": "lib/ajv.d.ts",
"version": "6.12.0"
"version": "6.12.2"
}
+11 -6
View File
@@ -12,21 +12,22 @@
"devDependencies": {
"ava": "^2.4.0",
"coveralls": "^3.0.7",
"execa": "^3.2.0",
"execa": "^4.0.0",
"import-fresh": "^3.1.0",
"matcha": "^0.7.0",
"nyc": "^14.1.1",
"nyc": "^15.0.0",
"resolve-from": "^5.0.0",
"tsd": "^0.7.4",
"xo": "^0.25.3"
"xo": "^0.28.2"
},
"engines": {
"node": ">=8"
"node": ">=10"
},
"files": [
"source",
"index.d.ts"
],
"funding": "https://github.com/chalk/chalk?sponsor=1",
"homepage": "https://github.com/chalk/chalk#readme",
"keywords": [
"color",
@@ -62,11 +63,15 @@
"bench": "matcha benchmark.js",
"test": "xo && nyc ava && tsd"
},
"version": "3.0.0",
"version": "4.0.0",
"xo": {
"rules": {
"unicorn/prefer-string-slice": "off",
"unicorn/prefer-includes": "off"
"unicorn/prefer-includes": "off",
"@typescript-eslint/member-ordering": "off",
"no-redeclare": "off",
"unicorn/string-content": "off",
"unicorn/better-regex": "off"
}
}
}
+2 -14
View File
@@ -9,11 +9,10 @@
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg)
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](http://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
## Highlights
- Expressive API
@@ -24,8 +23,7 @@
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~46,000 packages](https://www.npmjs.com/browse/depended/chalk) as of October 1, 2019
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
## Install
@@ -33,7 +31,6 @@
$ npm install chalk
```
## Usage
```js
@@ -107,7 +104,6 @@ console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
@@ -149,7 +145,6 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
## Styles
### Modifiers
@@ -202,7 +197,6 @@ Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=
- `bgCyanBright`
- `bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](http://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
@@ -232,7 +226,6 @@ Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
@@ -262,24 +255,20 @@ The following color models can be used:
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Windows
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## chalk for enterprise
Available as part of the Tidelift Subscription.
The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
@@ -297,7 +286,6 @@ The maintainers of chalk and thousands of other packages are working with Tideli
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
+4 -15
View File
@@ -17,7 +17,7 @@ const levelMapping = [
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level > 3 || options.level < 0) {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error('The `level` option should be an integer from 0 to 3');
}
@@ -28,6 +28,7 @@ const applyOptions = (object, options = {}) => {
class ChalkClass {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
@@ -139,9 +140,9 @@ const createBuilder = (self, _styler, _isEmpty) => {
return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
};
// `__proto__` is used because we must return a function, but there is
// We alter the prototype because we must return a function, but there is
// no way to create a function with a different prototype
builder.__proto__ = proto; // eslint-disable-line no-proto
Object.setPrototypeOf(builder, proto);
builder._generator = self;
builder._styler = _styler;
@@ -218,16 +219,4 @@ chalk.supportsColor = stdoutColor;
chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
chalk.stderr.supportsColor = stderrColor;
// For TypeScript
chalk.Level = {
None: 0,
Basic: 1,
Ansi256: 2,
TrueColor: 3,
0: 'None',
1: 'Basic',
2: 'Ansi256',
3: 'TrueColor'
};
module.exports = chalk;
+3 -3
View File
@@ -2,7 +2,7 @@
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = new Map([
['n', '\n'],
@@ -126,8 +126,8 @@ module.exports = (chalk, temporary) => {
chunks.push(chunk.join(''));
if (styles.length > 0) {
const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMsg);
const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMessage);
}
return chunks.join('');
+23 -23
View File
@@ -11,15 +11,15 @@ function normalizeOpts(options) {
if (!options) {
return defaultOpts;
} else {
Object.keys(defaultOpts).forEach(function (key) {
if (!options[key]) {
options[key] = defaultOpts[key];
}
});
return options;
}
Object.keys(defaultOpts).forEach(function (key) {
if (!options[key]) {
options[key] = defaultOpts[key];
}
});
return options;
}
function cliWidth(options) {
@@ -27,23 +27,23 @@ function cliWidth(options) {
if (opts.output.getWindowSize) {
return opts.output.getWindowSize()[0] || opts.defaultWidth;
} else {
if (opts.tty.getWindowSize) {
return opts.tty.getWindowSize()[1] || opts.defaultWidth;
} else {
if (opts.output.columns) {
return opts.output.columns;
} else {
if (process.env.CLI_WIDTH) {
var width = parseInt(process.env.CLI_WIDTH, 10);
}
if (!isNaN(width) && width !== 0) {
return width;
}
}
}
if (opts.tty.getWindowSize) {
return opts.tty.getWindowSize()[1] || opts.defaultWidth;
}
return opts.defaultWidth;
if (opts.output.columns) {
return opts.output.columns;
}
if (process.env.CLI_WIDTH) {
var width = parseInt(process.env.CLI_WIDTH, 10);
if (!isNaN(width) && width !== 0) {
return width;
}
}
return opts.defaultWidth;
};
+8 -10
View File
@@ -1,7 +1,7 @@
{
"author": {
"name": "Ilya Radchenko",
"email": "ilya@burstcreations.com"
"email": "knownasilya@gmail.com"
},
"bugs": {
"url": "https://github.com/knownasilya/cli-width/issues"
@@ -10,12 +10,11 @@
"deprecated": false,
"description": "Get stdout window width, with two fallbacks, tty and then a default.",
"devDependencies": {
"coveralls": "^2.11.4",
"isparta": "^3.0.4",
"rimraf": "^2.4.3",
"standard-version": "^4.2.0",
"tap-spec": "^4.1.0",
"tape": "^3.4.0"
"coveralls": "^3.0.11",
"nyc": "^15.0.1",
"standard-version": "^7.1.0",
"tap-spec": "^5.0.0",
"tape": "^4.13.2"
},
"homepage": "https://github.com/knownasilya/cli-width",
"license": "ISC",
@@ -26,11 +25,10 @@
"url": "git+ssh://git@github.com/knownasilya/cli-width.git"
},
"scripts": {
"coverage": "isparta cover test/*.js | tspec",
"coverage": "nyc node test | tspec",
"coveralls": "npm run coverage -s && coveralls < coverage/lcov.info",
"postcoveralls": "rimraf ./coverage",
"release": "standard-version",
"test": "node test | tspec"
},
"version": "2.2.0"
"version": "2.2.1"
}
+4 -4
View File
@@ -3,10 +3,10 @@
[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url]
[npm-url]:https://npmjs.org/package/cross-spawn
[downloads-image]:http://img.shields.io/npm/dm/cross-spawn.svg
[npm-image]:http://img.shields.io/npm/v/cross-spawn.svg
[downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg
[npm-image]:https://img.shields.io/npm/v/cross-spawn.svg
[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn
[travis-image]:http://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg
[travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg
[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn
@@ -93,4 +93,4 @@ Remember to always test your code on Windows!
## License
Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php).
Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php).
@@ -8,7 +8,7 @@ function resolveCommandAttempt(parsed, withoutPathExt) {
const cwd = process.cwd();
const hasCustomCwd = parsed.options.cwd != null;
// Worker threads do not have process.chdir()
const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined;
const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
// If a custom `cwd` was specified, we need to change the process cwd
// because `which` will do stat calls but does not support a custom cwd
+2 -6
View File
@@ -72,14 +72,10 @@
},
"scripts": {
"lint": "eslint .",
"postrelease": "git push --follow-tags origin HEAD && npm publish",
"prerelease": "npm t && npm run lint",
"release": "standard-version",
"test": "jest --env node --coverage"
},
"standard-version": {
"scripts": {
"posttag": "git push --follow-tags origin master"
}
},
"version": "7.0.1"
"version": "7.0.2"
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,2 +1,2 @@
"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function e(e,t){return e(t={exports:{}},t.exports),t.exports}var t=e((function(e,t){!function e(t){var r,n,s,o,a,i;function l(e){var t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],n[t]="object"==typeof r&&null!==r?l(r):r);return n}function u(e,t){this.parent=e,this.key=t}function c(e,t,r,n){this.node=e,this.path=t,this.wrap=r,this.ref=n}function p(){}function f(e){return null!=e&&("object"==typeof e&&"string"==typeof e.type)}function h(e,t){return(e===r.ObjectExpression||e===r.ObjectPattern)&&"properties"===t}function d(e,t){return(new p).traverse(e,t)}function x(e,t){var r;return r=function(e,t){var r,n,s,o;for(n=e.length,s=0;n;)t(e[o=s+(r=n>>>1)])?n=r:(s=o+1,n-=r+1);return s}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},s={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["local"],ImportNamespaceSpecifier:["local"],ImportSpecifier:["imported","local"],Literal:[],LabeledStatement:["label","bodLine truncated
function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var r=[],n=!0,o=!1,a=void 0;try{for(var s,i=e[Symbol.iterator]();!(n=(s=i.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw a}}return r}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(r):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function a(e,t){return e(t={exports:{}},t.exports),t.exports}var s=a((function(e,t){!function e(t){var r,n,o,a,s,i;function l(e){var t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],n[t]="object"==typeof r&&null!==r?l(r):r);return n}function u(e,t){this.parent=e,this.key=t}function c(e,t,r,n){this.node=e,this.path=t,this.wrap=r,this.ref=n}function p(){}function f(e){return null!=e&&("object"==typeof e&&"string"==typeof e.type)}function h(e,t){return(e===r.ObjectExpression||e===r.ObjectPattern)&&"properties"===t}function d(e,t){for(var r=e.length-1;r>=0;--r)if(e[r].node===t)return!0;return!1}function y(e,t){return(new p).traverse(e,t)}function m(e,t){var r;return r=function(e,t){var r,n,o,a;for(n=e.length,o=0;n;)t(e[a=o+(r=n>>>1)])?n=r:(o=a+1,n-=r+1);return o}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariablLine truncated
//# sourceMappingURL=esquery.esm.min.js.map
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,2 +1,2 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).esquery=t()}(this,(function(){"use strict";"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function e(e,t){return e(t={exports:{}},t.exports),t.exports}var t=e((function(e,t){!function e(t){var r,n,s,o,a,i;function l(e){var t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],n[t]="object"==typeof r&&null!==r?l(r):r);return n}function u(e,t){this.parent=e,this.key=t}function c(e,t,r,n){this.node=e,this.path=t,this.wrap=r,this.ref=n}function p(){}function f(e){return null!=e&&("object"==typeof e&&"string"==typeof e.type)}function h(e,t){return(e===r.ObjectExpression||e===r.ObjectPattern)&&"properties"===t}function d(e,t){return(new p).traverse(e,t)}function x(e,t){var r;return r=function(e,t){var r,n,s,o;for(n=e.length,s=0;n;)t(e[o=s+(r=n>>>1)])?n=r:(s=o+1,n-=r+1);return s}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"},s={AssignmentExpression:["left","right"],AssignmentPattern:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","body"],AwaitExpression:["argument"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","superClass","body"],ClassExpression:["id","superClass","body"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportAllDeclaration:["source"],ExportDefaultDeclaration:["declaration"],ExportNamedDeclaration:["declaration","specifiers","source"],ExportSpecifier:["exported","local"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","body"],FunctionExpression:["id","params","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportExpression:["source"Line truncated
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).esquery=t()}(this,(function(){"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(e)))return;var r=[],n=!0,o=!1,a=void 0;try{for(var s,i=e[Symbol.iterator]();!(n=(s=i.next()).done)&&(r.push(s.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw a}}return r}(e,t)||n(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function r(e){return function(e){if(Array.isArray(e))return o(e)}(e)||function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}(e)||n(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function n(e,t){if(e){if("string"==typeof e)return o(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(r):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?o(e,t):void 0}}function o(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function a(e,t){return e(t={exports:{}},t.exports),t.exports}var s=a((function(e,t){!function e(t){var r,n,o,a,s,i;function l(e){var t,r,n={};for(t in e)e.hasOwnProperty(t)&&(r=e[t],n[t]="object"==typeof r&&null!==r?l(r):r);return n}function u(e,t){this.parent=e,this.key=t}function c(e,t,r,n){this.node=e,this.path=t,this.wrap=r,this.ref=n}function f(){}function p(e){return null!=e&&("object"==typeof e&&"string"==typeof e.type)}function h(e,t){return(e===r.ObjectExpression||e===r.ObjectPattern)&&"properties"===t}function d(e,t){for(var r=e.length-1;r>=0;--r)if(e[r].node===t)return!0;return!1}function y(e,t){return(new f).traverse(e,t)}function m(e,t){var r;return r=function(e,t){var r,n,o,a;for(n=e.length,o=0;n;)t(e[a=o+(r=n>>>1)])?n=r:(o=a+1,n-=r+1);return o}(t,(function(t){return t.range[0]>e.range[0]})),e.extendedRange=[e.range[0],e.range[1]],r!==t.length&&(e.extendedRange[1]=t[r].range[0]),(r-=1)>=0&&(e.extendedRange[0]=t[r].range[1]),e}return r={AssignmentExpression:"AssignmentExpression",AssignmentPattern:"AssignmentPattern",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportAllDeclaration:"ExportAllDeclaration",ExportDefaultDeclaration:"ExportDefaultDeclaration",ExportNamedDeclaration:"ExportNamedDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportExpression:"ImportExpression",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MetaProperty:"MetaProperty",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",RestElement:"RestElement",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",Super:"Super",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",Line truncated
//# sourceMappingURL=esquery.min.js.map
@@ -389,6 +389,15 @@
return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key;
}
function candidateExistsInLeaveList(leavelist, candidate) {
for (var i = leavelist.length - 1; i >= 0; --i) {
if (leavelist[i].node === candidate) {
return true;
}
}
return false;
}
Controller.prototype.traverse = function traverse(root, visitor) {
var worklist,
leavelist,
@@ -469,6 +478,11 @@
if (!candidate[current2]) {
continue;
}
if (candidateExistsInLeaveList(leavelist, candidate[current2])) {
continue;
}
if (isProperty(nodeType, candidates[current])) {
element = new Element(candidate[current2], [key, current2], 'Property', null);
} else if (isNode(candidate[current2])) {
@@ -479,6 +493,10 @@
worklist.push(element);
}
} else if (isNode(candidate)) {
if (candidateExistsInLeaveList(leavelist, candidate)) {
continue;
}
worklist.push(new Element(candidate, key, null, null));
}
}
@@ -41,5 +41,5 @@
"test": "npm run-script lint && npm run-script unit-test",
"unit-test": "mocha --compilers js:babel-register"
},
"version": "5.0.0"
"version": "5.1.0"
}
+14 -10
View File
@@ -9,26 +9,30 @@
"bundleDependencies": false,
"contributors": [],
"dependencies": {
"estraverse": "^5.0.0"
"estraverse": "^5.1.0"
},
"deprecated": false,
"description": "A query library for ECMAScript AST using a CSS selector like query language.",
"devDependencies": {
"@rollup/plugin-commonjs": "^11.0.2",
"@babel/core": "^7.9.0",
"@babel/preset-env": "^7.9.5",
"@babel/register": "^7.9.0",
"@rollup/plugin-commonjs": "^11.1.0",
"@rollup/plugin-json": "^4.0.2",
"@rollup/plugin-node-resolve": "^7.1.1",
"@rollup/plugin-node-resolve": "^7.1.3",
"babel-plugin-transform-es2017-object-entries": "0.0.5",
"chai": "^4.2.0",
"eslint": "^6.8.0",
"esm": "^3.2.25",
"esprima": "~4.0.1",
"mocha": "^7.1.1",
"nyc": "^15.0.0",
"nyc": "^15.0.1",
"pegjs": "~0.10.0",
"rollup": "^1.32.0",
"rollup-plugin-terser": "^5.2.0"
"rollup": "^1.32.1",
"rollup-plugin-babel": "^4.4.0",
"rollup-plugin-terser": "^5.3.0"
},
"engines": {
"node": ">=8.0"
"node": ">=0.10"
},
"files": [
"dist/*.js",
@@ -72,10 +76,10 @@
"build:browser": "rollup -c",
"build:parser": "rm parser.js && pegjs --cache --format umd -o \"parser.js\" \"grammar.pegjs\"",
"lint": "eslint .",
"mocha": "mocha --require chai/register-assert --require esm tests",
"mocha": "mocha --require chai/register-assert --require @babel/register tests",
"prepublishOnly": "npm run build && npm test",
"test": "nyc npm run mocha && npm run lint",
"test:ci": "npm run mocha"
},
"version": "1.2.0"
"version": "1.3.1"
}
+13
View File
@@ -4,6 +4,10 @@
A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson).
```js
npm i flatted
```
Usable via [CDN](https://unpkg.com/flatted) or as regular module.
```js
@@ -20,6 +24,15 @@ a.push(a);
stringify(a); // [["1","0"],{"a":"0"}]
```
## Flatted VS JSON
As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`.
The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity.
Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected.
### New in V1: Exact same JSON API
* Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects.
-2
View File
@@ -46,8 +46,6 @@ var Flatted = (function (Primitive, primitive) {
if (firstRun) {
firstRun = !firstRun;
return value;
// this was invoking twice each root object
// return i < 1 ? value : $.call(this, key, value);
}
var after = $.call(this, key, value);
switch (typeof after) {
-2
View File
@@ -46,8 +46,6 @@ var Flatted = (function (Primitive, primitive) {
if (firstRun) {
firstRun = !firstRun;
return value;
// this was invoking twice each root object
// return i < 1 ? value : $.call(this, key, value);
}
var after = $.call(this, key, value);
switch (typeof after) {
-2
View File
@@ -46,8 +46,6 @@ var Flatted = (function (Primitive, primitive) {
if (firstRun) {
firstRun = !firstRun;
return value;
// this was invoking twice each root object
// return i < 1 ? value : $.call(this, key, value);
}
var after = $.call(this, key, value);
switch (typeof after) {
+9 -9
View File
@@ -9,12 +9,12 @@
"deprecated": false,
"description": "A super light and fast circular JSON parser.",
"devDependencies": {
"circular-json": "latest",
"circular-json-es6": "latest",
"coveralls": "latest",
"istanbul": "latest",
"jsan": "latest",
"uglify-js": "latest"
"circular-json": "^0.5.9",
"circular-json-es6": "^2.0.2",
"coveralls": "^3.0.11",
"jsan": "^3.1.13",
"nyc": "^15.0.0",
"uglify-js": "^3.8.1"
},
"homepage": "https://github.com/WebReflection/flatted#readme",
"keywords": [
@@ -36,13 +36,13 @@
"bench": "node test/bench.js",
"build": "npm run cjs && npm test && npm run esm && npm run min && npm run size",
"cjs": "cp index.js cjs/index.js; echo 'module.exports = Flatted;' >> cjs/index.js",
"coveralls": "cat ./coverage/lcov.info | coveralls",
"coveralls": "nyc report --reporter=text-lcov | coveralls",
"esm": "cp index.js esm/index.js; echo 'export default Flatted;' >> esm/index.js; echo 'export var parse = Flatted.parse;' >> esm/index.js; echo 'export var stringify = Flatted.stringify;' >> esm/index.js",
"min": "echo '/*! (c) 2018, Andrea Giammarchi, (ISC) */'>min.js && uglifyjs index.js --support-ie8 -c -m >> min.js",
"size": "cat index.js | wc -c;cat min.js | wc -c;gzip -c9 min.js | wc -c;cat min.js | brotli | wc -c",
"test": "istanbul cover test/index.js"
"test": "nyc node test/index.js"
},
"types": "types.d.ts",
"unpkg": "min.js",
"version": "2.0.1"
"version": "2.0.2"
}
+1
View File
@@ -1,4 +1,5 @@
module.exports = isPromise;
module.exports.default = isPromise;
function isPromise(obj) {
return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
+11 -3
View File
@@ -9,9 +9,16 @@
"deprecated": false,
"description": "Test whether an object looks like a promises-a+ promise",
"devDependencies": {
"better-assert": "~0.1.0",
"mocha": "~1.7.4"
"better-assert": "^1.0.2",
"mocha": "^7.1.1"
},
"exports": {
"import": "index.mjs",
"require": "index.js"
},
"files": [
"index.js"
],
"homepage": "https://github.com/then/is-promise#readme",
"license": "MIT",
"main": "index.js",
@@ -23,5 +30,6 @@
"scripts": {
"test": "mocha -R spec"
},
"version": "2.1.0"
"type": "module",
"version": "2.2.0"
}
+8 -4
View File
@@ -1,12 +1,15 @@
<a href="http://promises-aplus.github.com/promises-spec"><img src="http://promises-aplus.github.com/promises-spec/assets/logo-small.png" align="right" /></a>
<a href="https://promisesaplus.com/"><img src="https://promisesaplus.com/assets/logo-small.png" align="right" /></a>
# is-promise
Test whether an object looks like a promises-a+ promise
[![Build Status](https://img.shields.io/travis/then/is-promise/master.svg)](https://travis-ci.org/then/is-promise)
[![Dependency Status](https://img.shields.io/gemnasium/then/is-promise.svg)](https://gemnasium.com/then/is-promise)
[![Dependency Status](https://img.shields.io/david/then/is-promise.svg)](https://david-dm.org/then/is-promise)
[![NPM version](https://img.shields.io/npm/v/is-promise.svg)](https://www.npmjs.org/package/is-promise)
## Installation
$ npm install is-promise
@@ -15,9 +18,10 @@ You can also use it client side via npm.
## API
```javascript
var isPromise = require('is-promise');
```typescript
import isPromise from 'is-promise';
isPromise(Promise.resolve());//=>true
isPromise({then:function () {...}});//=>true
isPromise(null);//=>false
isPromise({});//=>false
+1 -1
View File
@@ -2,7 +2,7 @@
__Light ECMAScript (JavaScript) Value Notation__
Levn is a library which allows you to parse a string into a JavaScript value based on an expected type. It is meant for short amounts of human entered data (eg. config files, command line arguments).
Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.3.0.
Levn aims to concisely describe JavaScript values in text, and allow for the extraction and validation of those values. Levn uses [type-check](https://github.com/gkz/type-check) for its type format, and to validate the results. MIT license. Version 0.4.1.
__How is this different than JSON?__ levn is meant to be written by humans only, is (due to the previous point) much more concise, can be validated against supplied types, has regex and date literals, and can easily be extended with custom types. On the other hand, it is probably slower and thus less efficient at transporting large amounts of data, which is fine since this is not its purpose.
+34 -5
View File
@@ -1,4 +1,4 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
@@ -162,21 +162,45 @@
}, options);
},
String: function(it){
var that;
var replace, that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
replace = function(value, quote){
return value.replace(/\\([^u]|u[0-9a-fA-F]{4})/g, function(all, escaped){
switch (escaped[0]) {
case quote:
return quote;
case '\\':
return '\\';
case 'b':
return '\b';
case 'f':
return '\f';
case 'n':
return '\n';
case 'r':
return '\r';
case 't':
return '\t';
case 'u':
return JSON.parse("\"" + all + "\"");
default:
return escaped;
}
});
};
if (that = it.match(/^'([\s\S]*)'$/)) {
return {
type: 'Just',
value: that[1].replace(/\\'/g, "'")
value: replace(that[1], "'")
};
} else if (that = it.match(/^"([\s\S]*)"$/)) {
return {
type: 'Just',
value: that[1].replace(/\\"/g, '"')
value: replace(that[1], '"')
};
} else {
return {
@@ -294,5 +318,10 @@
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = typesCast;
module.exports = function(node, types, options){
if (!options.explicit && types.length === 1 && types[0].type === 'String') {
return node;
}
return typesCast(node, types, options);
};
}).call(this);
-285
View File
@@ -1,285 +0,0 @@
// Generated by LiveScript 1.2.0
(function(){
var parsedTypeCheck, types, toString$ = {}.toString;
parsedTypeCheck = require('type-check').parsedTypeCheck;
types = {
'*': function(it){
switch (toString$.call(it).slice(8, -1)) {
case 'Array':
return coerceType(it, {
type: 'Array'
});
case 'Object':
return coerceType(it, {
type: 'Object'
});
default:
return {
type: 'Just',
value: coerceTypes(it, [
{
type: 'Undefined'
}, {
type: 'Null'
}, {
type: 'NaN'
}, {
type: 'Boolean'
}, {
type: 'Number'
}, {
type: 'Date'
}, {
type: 'RegExp'
}, {
type: 'Array'
}, {
type: 'Object'
}, {
type: 'String'
}
], {
explicit: true
})
};
}
},
Undefined: function(it){
if (it === 'undefined' || it === void 8) {
return {
type: 'Just',
value: void 8
};
} else {
return {
type: 'Nothing'
};
}
},
Null: function(it){
if (it === 'null') {
return {
type: 'Just',
value: null
};
} else {
return {
type: 'Nothing'
};
}
},
NaN: function(it){
if (it === 'NaN') {
return {
type: 'Just',
value: NaN
};
} else {
return {
type: 'Nothing'
};
}
},
Boolean: function(it){
if (it === 'true') {
return {
type: 'Just',
value: true
};
} else if (it === 'false') {
return {
type: 'Just',
value: false
};
} else {
return {
type: 'Nothing'
};
}
},
Number: function(it){
return {
type: 'Just',
value: +it
};
},
Int: function(it){
return {
type: 'Just',
value: parseInt(it)
};
},
Float: function(it){
return {
type: 'Just',
value: parseFloat(it)
};
},
Date: function(value, options){
var that;
if (that = /^\#(.*)\#$/.exec(value)) {
return {
type: 'Just',
value: new Date(+that[1] || that[1])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new Date(+value || value)
};
}
},
RegExp: function(value, options){
var that;
if (that = /^\/(.*)\/([gimy]*)$/.exec(value)) {
return {
type: 'Just',
value: new RegExp(that[1], that[2])
};
} else if (options.explicit) {
return {
type: 'Nothing'
};
} else {
return {
type: 'Just',
value: new RegExp(value)
};
}
},
Array: function(it){
return coerceArray(it, {
of: [{
type: '*'
}]
});
},
Object: function(it){
return coerceFields(it, {
of: {}
});
},
String: function(it){
var that;
if (toString$.call(it).slice(8, -1) !== 'String') {
return {
type: 'Nothing'
};
}
if (that = it.match(/^'(.*)'$/)) {
return {
type: 'Just',
value: that[1]
};
} else if (that = it.match(/^"(.*)"$/)) {
return {
type: 'Just',
value: that[1]
};
} else {
return {
type: 'Just',
value: it
};
}
}
};
function coerceArray(node, type){
var typeOf, element;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = node).length; i$ < len$; ++i$) {
element = ref$[i$];
results$.push(coerceTypes(element, typeOf));
}
return results$;
}())
};
}
function coerceTuple(node, type){
var result, i$, ref$, len$, i, types, that;
if (toString$.call(node).slice(8, -1) !== 'Array') {
return {
type: 'Nothing'
};
}
result = [];
for (i$ = 0, len$ = (ref$ = type.of).length; i$ < len$; ++i$) {
i = i$;
types = ref$[i$];
if (that = coerceTypes(node[i], types)) {
result.push(that);
}
}
return {
type: 'Just',
value: result
};
}
function coerceFields(node, type){
var typeOf, key, value;
if (toString$.call(node).slice(8, -1) !== 'Object') {
return {
type: 'Nothing'
};
}
typeOf = type.of;
return {
type: 'Just',
value: (function(){
var ref$, results$ = {};
for (key in ref$ = node) {
value = ref$[key];
results$[key] = coerceTypes(value, typeOf[key] || [{
type: '*'
}]);
}
return results$;
}())
};
}
function coerceType(node, typeObj, options){
var type, structure, coerceFunc;
type = typeObj.type, structure = typeObj.structure;
if (type) {
coerceFunc = types[type];
return coerceFunc(node, options);
} else {
switch (structure) {
case 'array':
return coerceArray(node, typeObj);
case 'tuple':
return coerceTuple(node, typeObj);
case 'fields':
return coerceFields(node, typeObj);
}
}
}
function coerceTypes(node, types, options){
var i$, len$, type, ref$, valueType, value;
for (i$ = 0, len$ = types.length; i$ < len$; ++i$) {
type = types[i$];
ref$ = coerceType(node, type, options), valueType = ref$.type, value = ref$.value;
if (valueType === 'Nothing') {
continue;
}
if (parsedTypeCheck([type], value)) {
return value;
}
}
throw new Error("Value " + JSON.stringify(node) + " does not type check against " + JSON.stringify(types) + ".");
}
module.exports = coerceTypes;
}).call(this);
+2 -2
View File
@@ -1,10 +1,10 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
(function(){
var parseString, cast, parseType, VERSION, parsedTypeParse, parse;
parseString = require('./parse-string');
cast = require('./cast');
parseType = require('type-check').parseType;
VERSION = '0.3.0';
VERSION = '0.4.1';
parsedTypeParse = function(parsedType, string, options){
options == null && (options = {});
options.explicit == null && (options.explicit = false);
+2 -2
View File
@@ -1,4 +1,4 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
@@ -100,7 +100,7 @@
var tokens, node;
options == null && (options = {});
if (!options.explicit && types.length === 1 && types[0].type === 'String') {
return "'" + string.replace(/\\'/g, "\\\\'") + "'";
return string;
}
tokens = reject(not$, string.split(tokenRegex));
node = consumeTopLevel(tokens, types, options);
-102
View File
@@ -1,102 +0,0 @@
// Generated by LiveScript 1.2.0
(function(){
var reject, special, tokenRegex;
reject = require('prelude-ls').reject;
function consumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
} else {
throw new Error("Expected '" + op + "', but got '" + tokens[0] + "' instead in " + JSON.stringify(tokens) + ".");
}
}
function maybeConsumeOp(tokens, op){
if (tokens[0] === op) {
return tokens.shift();
}
}
function consumeList(tokens, delimiters, hasDelimiters){
var result;
if (hasDelimiters) {
consumeOp(tokens, delimiters[0]);
}
result = [];
while (tokens.length && tokens[0] !== delimiters[1]) {
result.push(consumeElement(tokens));
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, delimiters[1]);
}
return result;
}
function consumeArray(tokens, hasDelimiters){
return consumeList(tokens, ['[', ']'], hasDelimiters);
}
function consumeTuple(tokens, hasDelimiters){
return consumeList(tokens, ['(', ')'], hasDelimiters);
}
function consumeFields(tokens, hasDelimiters){
var result, key;
if (hasDelimiters) {
consumeOp(tokens, '{');
}
result = {};
while (tokens.length && (!hasDelimiters || tokens[0] !== '}')) {
key = tokens.shift();
consumeOp(tokens, ':');
result[key] = consumeElement(tokens);
maybeConsumeOp(tokens, ',');
}
if (hasDelimiters) {
consumeOp(tokens, '}');
}
return result;
}
function consumeElement(tokens){
switch (tokens[0]) {
case '[':
return consumeArray(tokens, true);
case '(':
return consumeTuple(tokens, true);
case '{':
return consumeFields(tokens, true);
default:
return tokens.shift();
}
}
function consumeTopLevel(tokens, types){
var ref$, type, structure, origTokens, result, finalResult, x$, y$;
ref$ = types[0], type = ref$.type, structure = ref$.structure;
origTokens = tokens.concat();
if (types.length === 1 && (structure || (type === 'Array' || type === 'Object'))) {
result = structure === 'array' || type === 'Array'
? consumeArray(tokens, tokens[0] === '[')
: structure === 'tuple'
? consumeTuple(tokens, tokens[0] === '(')
: consumeFields(tokens, tokens[0] === '{');
finalResult = tokens.length ? consumeElement(structure === 'array' || type === 'Array'
? (x$ = origTokens, x$.unshift('['), x$.push(']'), x$)
: (y$ = origTokens, y$.unshift('('), y$.push(')'), y$)) : result;
} else {
finalResult = consumeElement(tokens);
}
if (tokens.length && origTokens.length) {
throw new Error("Unable to parse " + JSON.stringify(origTokens) + " of type " + JSON.stringify(types) + ".");
} else {
return finalResult;
}
}
special = /\[\]\(\)}{:,/.source;
tokenRegex = RegExp('("(?:[^"]|\\\\")*")|(\'(?:[^\']|\\\\\')*\')|(#.*#)|(/(?:\\\\/|[^/])*/[gimy]*)|([' + special + '])|([^\\s' + special + ']+)|\\s*');
module.exports = function(string, types){
var tokens, node;
tokens = reject(function(it){
return !it || /^\s+$/.test(it);
}, string.split(tokenRegex));
node = consumeTopLevel(tokens, types);
if (!node) {
throw new Error("Error parsing '" + string + "'.");
}
return node;
};
}).call(this);
+5 -6
View File
@@ -8,15 +8,14 @@
},
"bundleDependencies": false,
"dependencies": {
"prelude-ls": "~1.1.2",
"type-check": "~0.3.2"
"prelude-ls": "^1.2.1",
"type-check": "~0.4.0"
},
"deprecated": false,
"description": "Light ECMAScript (JavaScript) Value Notation - human written, concise, typed, flexible",
"devDependencies": {
"istanbul": "~0.4.1",
"livescript": "~1.4.0",
"mocha": "~2.3.4"
"livescript": "^1.6.0",
"mocha": "^7.1.1"
},
"engines": {
"node": ">= 0.8.0"
@@ -50,5 +49,5 @@
"scripts": {
"test": "make test"
},
"version": "0.3.0"
"version": "0.4.1"
}
+2 -2
View File
@@ -17,7 +17,7 @@ function mkdirP (p, opts, f, made) {
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
mode = _0777
}
if (!made) made = null;
@@ -62,7 +62,7 @@ mkdirP.sync = function sync (p, opts, made) {
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
mode = _0777
}
if (!made) made = null;
+2 -2
View File
@@ -14,7 +14,7 @@
"dependencies": {
"minimist": "^1.2.5"
},
"deprecated": "Legacy versions of mkdirp are no longer supported. Please update to mkdirp 1.x. (Note that the API surface has changed to use Promises in 1.x.)",
"deprecated": false,
"description": "Recursively mkdir, like `mkdir -p`",
"devDependencies": {
"mock-fs": "^3.7.0",
@@ -42,5 +42,5 @@
"scripts": {
"test": "tap test/*.js"
},
"version": "0.5.4"
"version": "0.5.5"
}
+2 -2
View File
@@ -37,7 +37,7 @@ Create a new directory and any necessary subdirectories at `dir` with octal
permission string `opts.mode`. If `opts` is a non-object, it will be treated as
the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.
If `opts.mode` isn't specified, it defaults to `0777`.
`cb(err, made)` fires with the error or the first directory `made`
that had to be created, if any.
@@ -52,7 +52,7 @@ Synchronously create a new directory and any necessary subdirectories at `dir`
with octal permission string `opts.mode`. If `opts` is a non-object, it will be
treated as the `opts.mode`.
If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.
If `opts.mode` isn't specified, it defaults to `0777`.
Returns the first directory that had to be created, if any.
+1 -1
View File
@@ -23,7 +23,7 @@ Other helpful features include reformatting the help text based on the size of t
## About
Optionator uses [type-check](https://github.com/gkz/type-check) and [levn](https://github.com/gkz/levn) behind the scenes to cast and verify input according the specified types.
MIT license. Version 0.8.3
MIT license. Version 0.9.1
npm install optionator
+1 -1
View File
@@ -1,7 +1,7 @@
// Generated by LiveScript 1.6.0
(function(){
var VERSION, ref$, id, map, compact, any, groupBy, partition, chars, isItNaN, keys, Obj, camelize, deepIs, closestString, nameToRaw, dasherize, naturalJoin, generateHelp, generateHelpForOption, parsedTypeCheck, parseType, parseLevn, camelizeKeys, parseString, main, toString$ = {}.toString, slice$ = [].slice, arrayFrom$ = Array.from || function(x){return slice$.call(x);};
VERSION = '0.8.3';
VERSION = '0.9.1';
ref$ = require('prelude-ls'), id = ref$.id, map = ref$.map, compact = ref$.compact, any = ref$.any, groupBy = ref$.groupBy, partition = ref$.partition, chars = ref$.chars, isItNaN = ref$.isItNaN, keys = ref$.keys, Obj = ref$.Obj, camelize = ref$.camelize;
deepIs = require('deep-is');
ref$ = require('./util'), closestString = ref$.closestString, nameToRaw = ref$.nameToRaw, dasherize = ref$.dasherize, naturalJoin = ref$.naturalJoin;
+9 -10
View File
@@ -8,19 +8,18 @@
},
"bundleDependencies": false,
"dependencies": {
"deep-is": "~0.1.3",
"fast-levenshtein": "~2.0.6",
"levn": "~0.3.0",
"prelude-ls": "~1.1.2",
"type-check": "~0.3.2",
"word-wrap": "~1.2.3"
"deep-is": "^0.1.3",
"fast-levenshtein": "^2.0.6",
"levn": "^0.4.1",
"prelude-ls": "^1.2.1",
"type-check": "^0.4.0",
"word-wrap": "^1.2.3"
},
"deprecated": false,
"description": "option parsing and help generation",
"devDependencies": {
"istanbul": "~0.4.5",
"livescript": "~1.6.0",
"mocha": "~6.2.2"
"livescript": "^1.6.0",
"mocha": "^7.1.1"
},
"engines": {
"node": ">= 0.8.0"
@@ -47,5 +46,5 @@
"scripts": {
"test": "make test"
},
"version": "0.8.3"
"version": "0.9.1"
}
+8 -4
View File
@@ -1,5 +1,5 @@
// Generated by LiveScript 1.4.0
var apply, curry, flip, fix, over, memoize, slice$ = [].slice, toString$ = {}.toString;
// Generated by LiveScript 1.6.0
var apply, curry, flip, fix, over, memoize, toString$ = {}.toString;
apply = curry$(function(f, list){
return f.apply(null, list);
});
@@ -27,8 +27,12 @@ memoize = function(f){
var memo;
memo = {};
return function(){
var args, key, arg;
args = slice$.call(arguments);
var args, res$, i$, to$, key, arg;
res$ = [];
for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) {
res$.push(arguments[i$]);
}
args = res$;
key = (function(){
var i$, ref$, len$, results$ = [];
for (i$ = 0, len$ = (ref$ = args).length; i$ < len$; ++i$) {
+42 -12
View File
@@ -1,5 +1,5 @@
// Generated by LiveScript 1.4.0
var each, map, compact, filter, reject, partition, find, head, first, tail, last, initial, empty, reverse, unique, uniqueBy, fold, foldl, fold1, foldl1, foldr, foldr1, unfoldr, concat, concatMap, flatten, difference, intersection, union, countBy, groupBy, andList, orList, any, all, sort, sortWith, sortBy, sum, product, mean, average, maximum, minimum, maximumBy, minimumBy, scan, scanl, scan1, scanl1, scanr, scanr1, slice, take, drop, splitAt, takeWhile, dropWhile, span, breakList, zip, zipWith, zipAll, zipAllWith, at, elemIndex, elemIndices, findIndex, findIndices, toString$ = {}.toString, slice$ = [].slice;
// Generated by LiveScript 1.6.0
var each, map, compact, filter, reject, remove, partition, find, head, first, tail, last, initial, empty, reverse, unique, uniqueBy, fold, foldl, fold1, foldl1, foldr, foldr1, unfoldr, concat, concatMap, flatten, difference, intersection, union, countBy, groupBy, andList, orList, any, all, sort, sortWith, sortBy, sum, product, mean, average, maximum, minimum, maximumBy, minimumBy, scan, scanl, scan1, scanl1, scanr, scanr1, slice, take, drop, splitAt, takeWhile, dropWhile, span, breakList, zip, zipWith, zipAll, zipAllWith, at, elemIndex, elemIndices, findIndex, findIndices, toString$ = {}.toString;
each = curry$(function(f, xs){
var i$, len$, x;
for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
@@ -46,6 +46,15 @@ reject = curry$(function(f, xs){
}
return results$;
});
remove = curry$(function(el, xs){
var i, x$;
i = elemIndex(el, xs);
x$ = xs.slice();
if (i != null) {
x$.splice(i, 1);
}
return x$;
});
partition = curry$(function(f, xs){
var passed, failed, i$, len$, x;
passed = [];
@@ -176,8 +185,12 @@ flatten = function(xs){
}()));
};
difference = function(xs){
var yss, results, i$, len$, x, j$, len1$, ys;
yss = slice$.call(arguments, 1);
var yss, res$, i$, to$, results, len$, x, j$, len1$, ys;
res$ = [];
for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) {
res$.push(arguments[i$]);
}
yss = res$;
results = [];
outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
@@ -192,8 +205,12 @@ difference = function(xs){
return results;
};
intersection = function(xs){
var yss, results, i$, len$, x, j$, len1$, ys;
yss = slice$.call(arguments, 1);
var yss, res$, i$, to$, results, len$, x, j$, len1$, ys;
res$ = [];
for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) {
res$.push(arguments[i$]);
}
yss = res$;
results = [];
outer: for (i$ = 0, len$ = xs.length; i$ < len$; ++i$) {
x = xs[i$];
@@ -208,8 +225,12 @@ intersection = function(xs){
return results;
};
union = function(){
var xss, results, i$, len$, xs, j$, len1$, x;
xss = slice$.call(arguments);
var xss, res$, i$, to$, results, len$, xs, j$, len1$, x;
res$ = [];
for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) {
res$.push(arguments[i$]);
}
xss = res$;
results = [];
for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
xs = xss[i$];
@@ -494,8 +515,12 @@ zipWith = curry$(function(f, xs, ys){
return result;
});
zipAll = function(){
var xss, minLength, i$, len$, xs, ref$, i, lresult$, j$, results$ = [];
xss = slice$.call(arguments);
var xss, res$, i$, to$, minLength, len$, xs, ref$, i, lresult$, j$, results$ = [];
res$ = [];
for (i$ = 0, to$ = arguments.length; i$ < to$; ++i$) {
res$.push(arguments[i$]);
}
xss = res$;
minLength = undefined;
for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
xs = xss[i$];
@@ -513,8 +538,12 @@ zipAll = function(){
return results$;
};
zipAllWith = function(f){
var xss, minLength, i$, len$, xs, ref$, i, results$ = [];
xss = slice$.call(arguments, 1);
var xss, res$, i$, to$, minLength, len$, xs, ref$, i, results$ = [];
res$ = [];
for (i$ = 1, to$ = arguments.length; i$ < to$; ++i$) {
res$.push(arguments[i$]);
}
xss = res$;
minLength = undefined;
for (i$ = 0, len$ = xss.length; i$ < len$; ++i$) {
xs = xss[i$];
@@ -589,6 +618,7 @@ module.exports = {
filter: filter,
compact: compact,
reject: reject,
remove: remove,
partition: partition,
find: find,
head: head,
+2 -2
View File
@@ -1,4 +1,4 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
var max, min, negate, abs, signum, quot, rem, div, mod, recip, pi, tau, exp, sqrt, ln, pow, sin, tan, cos, asin, acos, atan, atan2, truncate, round, ceiling, floor, isItNaN, even, odd, gcd, lcm;
max = curry$(function(x$, y$){
return x$ > y$ ? x$ : y$;
@@ -30,7 +30,7 @@ div = curry$(function(x, y){
});
mod = curry$(function(x$, y$){
var ref$;
return (((x$) % (ref$ = y$) + ref$) % ref$);
return ((x$) % (ref$ = y$) + ref$) % ref$;
});
recip = (function(it){
return 1 / it;
+1 -1
View File
@@ -1,4 +1,4 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
var values, keys, pairsToObj, objToPairs, listsToObj, objToLists, empty, each, map, compact, filter, reject, partition, find;
values = function(object){
var i$, x, results$ = [];
+1 -1
View File
@@ -1,4 +1,4 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
var split, join, lines, unlines, words, unwords, chars, unchars, reverse, repeat, capitalize, camelize, dasherize;
split = curry$(function(sep, str){
return str.split(sep);
+2 -2
View File
@@ -1,4 +1,4 @@
// Generated by LiveScript 1.4.0
// Generated by LiveScript 1.6.0
var Func, List, Obj, Str, Num, id, isType, replicate, prelude, toString$ = {}.toString;
Func = require('./Func.js');
List = require('./List.js');
@@ -161,7 +161,7 @@ prelude.even = Num.even;
prelude.odd = Num.odd;
prelude.gcd = Num.gcd;
prelude.lcm = Num.lcm;
prelude.VERSION = '1.1.2';
prelude.VERSION = '1.2.1';
module.exports = prelude;
function curry$(f, bound){
var context,
+7 -13
View File
@@ -10,12 +10,11 @@
"deprecated": false,
"description": "prelude.ls is a functionally oriented utility library. It is powerful and flexible. Almost all of its functions are curried. It is written in, and is the recommended base library for, LiveScript.",
"devDependencies": {
"browserify": "~3.24.13",
"istanbul": "~0.2.4",
"livescript": "~1.4.0",
"mocha": "~2.2.4",
"sinon": "~1.10.2",
"uglify-js": "~2.4.12"
"browserify": "^16.5.1",
"livescript": "^1.6.0",
"mocha": "^7.1.1",
"sinon": "~8.0.1",
"uglify-js": "^3.8.1"
},
"engines": {
"node": ">= 0.8.0"
@@ -40,12 +39,7 @@
"object",
"string"
],
"licenses": [
{
"type": "MIT",
"url": "https://raw.github.com/gkz/prelude-ls/master/LICENSE"
}
],
"license": "MIT",
"main": "lib/",
"name": "prelude-ls",
"repository": {
@@ -55,5 +49,5 @@
"scripts": {
"test": "make test"
},
"version": "1.1.2"
"version": "1.2.1"
}
+465 -769
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -36,6 +36,7 @@
"files": [
"index.*"
],
"funding": "https://github.com/sponsors/mysticatea",
"homepage": "https://github.com/mysticatea/regexpp#readme",
"keywords": [
"regexp",
@@ -82,7 +83,7 @@
"update:unicode:ids": "ts-node scripts/update-unicode-ids.ts",
"update:unicode:props": "ts-node scripts/update-unicode-properties.ts",
"version": "npm run -s build",
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions .ts --watch --growl"
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl"
},
"version": "3.0.0"
"version": "3.1.0"
}
+19 -17
View File
@@ -1,6 +1,4 @@
<img src="doc/asset/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
======================================
# <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
[![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x)
[![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs)
@@ -22,9 +20,8 @@ Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Exten
- [Code of Conduct](CODE_OF_CONDUCT.md)
- [Contribution Guidelines](CONTRIBUTING.md)
- [Maintainer Guidelines](doc/maintainer-guidelines.md)
- [Creating Operators](doc/operator-creation.md)
- [API Documentation (WIP)](https://rxjs.dev/)
- [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md)
- [API Documentation](https://rxjs.dev/)
## Versions In This Repository
@@ -45,14 +42,16 @@ npm install rxjs
It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`.
```js
import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';
```ts
import { range } from "rxjs";
import { map, filter } from "rxjs/operators";
range(1, 200).pipe(
filter(x => x % 2 === 1),
map(x => x + x)
).subscribe(x => console.log(x));
range(1, 200)
.pipe(
filter(x => x % 2 === 1),
map(x => x + x)
)
.subscribe(x => console.log(x));
```
Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information.
@@ -89,10 +88,12 @@ The global namespace for rxjs is `rxjs`:
const { range } = rxjs;
const { map, filter } = rxjs.operators;
range(1, 200).pipe(
filter(x => x % 2 === 1),
map(x => x + x)
).subscribe(x => console.log(x));
range(1, 200)
.pipe(
filter(x => x % 2 === 1),
map(x => x + x)
)
.subscribe(x => console.log(x));
```
## Goals
@@ -116,6 +117,7 @@ Run `npm run build_perf` or `npm run perf` to run the performance tests with `pr
Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator.
## Adding documentation
We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app).
## Generating PNG marble diagrams
+19 -17
View File
@@ -1,6 +1,4 @@
<img src="doc/asset/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
======================================
# <img src="docs_app/assets/Rx_Logo_S.png" alt="RxJS Logo" width="86" height="86"> RxJS: Reactive Extensions For JavaScript
[![CircleCI](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x.svg?style=svg)](https://circleci.com/gh/ReactiveX/rxjs/tree/6.x)
[![npm version](https://badge.fury.io/js/%40reactivex%2Frxjs.svg)](http://badge.fury.io/js/%40reactivex%2Frxjs)
@@ -22,9 +20,8 @@ Reactive Extensions Library for JavaScript. This is a rewrite of [Reactive-Exten
- [Code of Conduct](CODE_OF_CONDUCT.md)
- [Contribution Guidelines](CONTRIBUTING.md)
- [Maintainer Guidelines](doc/maintainer-guidelines.md)
- [Creating Operators](doc/operator-creation.md)
- [API Documentation (WIP)](https://rxjs.dev/)
- [Maintainer Guidelines](doc_app/content/maintainer-guidelines.md)
- [API Documentation](https://rxjs.dev/)
## Versions In This Repository
@@ -45,14 +42,16 @@ npm install rxjs
It's recommended to pull in the Observable creation methods you need directly from `'rxjs'` as shown below with `range`. And you can pull in any operator you need from one spot, under `'rxjs/operators'`.
```js
import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';
```ts
import { range } from "rxjs";
import { map, filter } from "rxjs/operators";
range(1, 200).pipe(
filter(x => x % 2 === 1),
map(x => x + x)
).subscribe(x => console.log(x));
range(1, 200)
.pipe(
filter(x => x % 2 === 1),
map(x => x + x)
)
.subscribe(x => console.log(x));
```
Here, we're using the built-in `pipe` method on Observables to combine operators. See [pipeable operators](https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md) for more information.
@@ -89,10 +88,12 @@ The global namespace for rxjs is `rxjs`:
const { range } = rxjs;
const { map, filter } = rxjs.operators;
range(1, 200).pipe(
filter(x => x % 2 === 1),
map(x => x + x)
).subscribe(x => console.log(x));
range(1, 200)
.pipe(
filter(x => x % 2 === 1),
map(x => x + x)
)
.subscribe(x => console.log(x));
```
## Goals
@@ -116,6 +117,7 @@ Run `npm run build_perf` or `npm run perf` to run the performance tests with `pr
Run `npm run perf_micro [operator]` to run micro performance test benchmarking operator.
## Adding documentation
We appreciate all contributions to the documentation of any type. All of the information needed to get the docs app up and running locally as well as how to contribute can be found in the [documentation directory](./docs_app).
## Generating PNG marble diagrams
@@ -1,31 +1,41 @@
import { Observable } from '../../Observable';
import { Subscription } from '../../Subscription';
export function fromFetch(input, init) {
return new Observable(subscriber => {
const controller = new AbortController();
const signal = controller.signal;
let outerSignalHandler;
let abortable = true;
let unsubscribed = false;
const subscription = new Subscription();
subscription.add(() => {
unsubscribed = true;
if (abortable) {
controller.abort();
}
});
let perSubscriberInit;
if (init) {
if (init.signal) {
if (init.signal.aborted) {
controller.abort();
}
else {
outerSignalHandler = () => {
const outerSignal = init.signal;
const outerSignalHandler = () => {
if (!signal.aborted) {
controller.abort();
}
};
init.signal.addEventListener('abort', outerSignalHandler);
outerSignal.addEventListener('abort', outerSignalHandler);
subscription.add(() => outerSignal.removeEventListener('abort', outerSignalHandler));
}
}
init = Object.assign({}, init, { signal });
perSubscriberInit = Object.assign({}, init, { signal });
}
else {
init = { signal };
perSubscriberInit = { signal };
}
fetch(input, init).then(response => {
fetch(input, perSubscriberInit).then(response => {
abortable = false;
subscriber.next(response);
subscriber.complete();
@@ -35,12 +45,7 @@ export function fromFetch(input, init) {
subscriber.error(err);
}
});
return () => {
unsubscribed = true;
if (abortable) {
controller.abort();
}
};
return subscription;
});
}
//# sourceMappingURL=fetch.js.map
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff. Show more