Comments (4)
run #10297
from prettier-regression-testing.
prettier/prettier#10297 VS prettier/prettier@main
- babel/babel@b63be94
- vuejs/eslint-plugin-vue@cc9c140
- excalidraw/excalidraw@1973ae9
- prettier/prettier@2c1b8f6
- typescript-eslint/typescript-eslint@7b701a3
Diff (3727 lines)
diff --git ORI/babel/packages/babel-cli/test/index.js ALT/babel/packages/babel-cli/test/index.js
index 7cedb49e3..bd2f64c1b 100644
--- ORI/babel/packages/babel-cli/test/index.js
+++ ALT/babel/packages/babel-cli/test/index.js
@@ -52,19 +52,21 @@ const saveInFiles = function (files) {
};
const normalizeOutput = function (str, cwd) {
- let result = str
- .replace(/\(\d+ms\)/g, "(123ms)")
- .replace(new RegExp(escapeRegExp(cwd), "g"), "<CWD>")
- // (non-win32) /foo/babel/packages -> <CWD>/packages
- // (win32) C:\foo\babel\packages -> <CWD>\packages
- .replace(new RegExp(escapeRegExp(rootDir), "g"), "<ROOTDIR>");
+ let result =
+ str
+ .replace(/\(\d+ms\)/g, "(123ms)")
+ .replace(new RegExp(escapeRegExp(cwd), "g"), "<CWD>")
+ // (non-win32) /foo/babel/packages -> <CWD>/packages
+ // (win32) C:\foo\babel\packages -> <CWD>\packages
+ .replace(new RegExp(escapeRegExp(rootDir), "g"), "<ROOTDIR>");
if (process.platform === "win32") {
- result = result
- // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
- .replace(
- new RegExp(escapeRegExp(rootDir.replace(/\\/g, "\\\\")), "g"),
- "<ROOTDIR>",
- );
+ result =
+ result
+ // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
+ .replace(
+ new RegExp(escapeRegExp(rootDir.replace(/\\/g, "\\\\")), "g"),
+ "<ROOTDIR>",
+ );
}
return result;
};
diff --git ORI/babel/packages/babel-core/src/config/files/configuration.js ALT/babel/packages/babel-core/src/config/files/configuration.js
index 8a3bed914..19fcb9ed2 100644
--- ORI/babel/packages/babel-core/src/config/files/configuration.js
+++ ALT/babel/packages/babel-core/src/config/files/configuration.js
@@ -278,10 +278,11 @@ const readConfigJSON5 = makeStaticFileCache((filepath, content): ConfigFile => {
const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
const ignoreDir = path.dirname(filepath);
- const ignorePatterns = content
- .split("\n")
- .map<string>(line => line.replace(/#(.*?)$/, "").trim())
- .filter(line => !!line);
+ const ignorePatterns =
+ content
+ .split("\n")
+ .map<string>(line => line.replace(/#(.*?)$/, "").trim())
+ .filter(line => !!line);
for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
diff --git ORI/babel/packages/babel-core/src/config/full.js ALT/babel/packages/babel-core/src/config/full.js
index 75fbe293c..2efa73342 100644
--- ORI/babel/packages/babel-core/src/config/full.js
+++ ALT/babel/packages/babel-core/src/config/full.js
@@ -186,10 +186,11 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
})();
opts.plugins = passes[0];
- opts.presets = passes
- .slice(1)
- .filter(plugins => plugins.length > 0)
- .map(plugins => ({ plugins }));
+ opts.presets =
+ passes
+ .slice(1)
+ .filter(plugins => plugins.length > 0)
+ .map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
return {
diff --git ORI/babel/packages/babel-core/src/transformation/file/merge-map.js ALT/babel/packages/babel-core/src/transformation/file/merge-map.js
index 911867d96..70d64b276 100644
--- ORI/babel/packages/babel-core/src/transformation/file/merge-map.js
+++ ALT/babel/packages/babel-core/src/transformation/file/merge-map.js
@@ -242,19 +242,20 @@ function buildMappingData(map: SourceMap): ResolvedMappings {
sourceData.mappings.push({
original: obj,
- generated: consumer
- .allGeneratedPositionsFor({
- source: m.source,
- line: m.originalLine,
- column: m.originalColumn,
- })
- .map(item => ({
- line: item.line,
- columnStart: item.column,
- // source-map's lastColumn is inclusive, not exclusive, so we need
- // to add 1 to it.
- columnEnd: item.lastColumn + 1,
- })),
+ generated:
+ consumer
+ .allGeneratedPositionsFor({
+ source: m.source,
+ line: m.originalLine,
+ column: m.originalColumn,
+ })
+ .map(item => ({
+ line: item.line,
+ columnStart: item.column,
+ // source-map's lastColumn is inclusive, not exclusive, so we need
+ // to add 1 to it.
+ columnEnd: item.lastColumn + 1,
+ })),
});
},
null,
diff --git ORI/babel/packages/babel-helper-compilation-targets/src/index.js ALT/babel/packages/babel-helper-compilation-targets/src/index.js
index 4fff39876..3723a0435 100644
--- ORI/babel/packages/babel-helper-compilation-targets/src/index.js
+++ ALT/babel/packages/babel-helper-compilation-targets/src/index.js
@@ -160,9 +160,10 @@ export default function getTargets(
// These values OVERRIDE the `browsers` field.
if (inputTargets.esmodules) {
const supportsESModules = browserModulesData["es6.module"];
- browsers = Object.keys(supportsESModules)
- .map(browser => `${browser} ${supportsESModules[browser]}`)
- .join(", ");
+ browsers =
+ Object.keys(supportsESModules)
+ .map(browser => `${browser} ${supportsESModules[browser]}`)
+ .join(", ");
}
// Parse browsers target via browserslist
diff --git ORI/babel/packages/babel-helper-module-transforms/src/get-module-name.js ALT/babel/packages/babel-helper-module-transforms/src/get-module-name.js
index 0e4e81ad3..228aef281 100644
--- ORI/babel/packages/babel-helper-module-transforms/src/get-module-name.js
+++ ALT/babel/packages/babel-helper-module-transforms/src/get-module-name.js
@@ -33,11 +33,12 @@ export default function getModuleName(
const sourceRootReplacer =
sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
- moduleName += filenameRelative
- // remove sourceRoot from filename
- .replace(sourceRootReplacer, "")
- // remove extension
- .replace(/\.(\w*?)$/, "");
+ moduleName +=
+ filenameRelative
+ // remove sourceRoot from filename
+ .replace(sourceRootReplacer, "")
+ // remove extension
+ .replace(/\.(\w*?)$/, "");
}
// normalize path separators
diff --git ORI/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js ALT/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js
index 1b5116349..1fa64d029 100644
--- ORI/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js
+++ ALT/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js
@@ -325,23 +325,25 @@ function validateFile(actualCode, expectedLoc, expectedCode) {
function normalizeOutput(code) {
const projectRoot = path.resolve(__dirname, "../../../");
const cwdSymbol = "<CWD>";
- let result = code
- .trim()
- // (non-win32) /foo/babel/packages -> <CWD>/packages
- // (win32) C:\foo\babel\packages -> <CWD>\packages
- .replace(new RegExp(escapeRegExp(projectRoot), "g"), cwdSymbol);
+ let result =
+ code
+ .trim()
+ // (non-win32) /foo/babel/packages -> <CWD>/packages
+ // (win32) C:\foo\babel\packages -> <CWD>\packages
+ .replace(new RegExp(escapeRegExp(projectRoot), "g"), cwdSymbol);
if (process.platform === "win32") {
- result = result
- // C:/foo/babel/packages -> <CWD>/packages
- .replace(
- new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "/")), "g"),
- cwdSymbol,
- )
- // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
- .replace(
- new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "\\\\")), "g"),
- cwdSymbol,
- );
+ result =
+ result
+ // C:/foo/babel/packages -> <CWD>/packages
+ .replace(
+ new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "/")), "g"),
+ cwdSymbol,
+ )
+ // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
+ .replace(
+ new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "\\\\")), "g"),
+ cwdSymbol,
+ );
}
return result;
}
diff --git ORI/babel/packages/babel-helpers/src/index.js ALT/babel/packages/babel-helpers/src/index.js
index 067719614..1a6155c51 100644
--- ORI/babel/packages/babel-helpers/src/index.js
+++ ALT/babel/packages/babel-helpers/src/index.js
@@ -303,8 +303,9 @@ export function ensure(name: string, newFileClass?) {
loadHelper(name);
}
-export const list = Object.keys(helpers)
- .map(name => name.replace(/^_/, ""))
- .filter(name => name !== "__esModule");
+export const list =
+ Object.keys(helpers)
+ .map(name => name.replace(/^_/, ""))
+ .filter(name => name !== "__esModule");
export default get;
diff --git ORI/babel/packages/babel-highlight/src/index.js ALT/babel/packages/babel-highlight/src/index.js
index f2639a521..1a89ce0fd 100644
--- ORI/babel/packages/babel-highlight/src/index.js
+++ ALT/babel/packages/babel-highlight/src/index.js
@@ -204,10 +204,11 @@ function highlightTokens(defs: Object, text: string) {
for (const { type, value } of tokenize(text)) {
const colorize = defs[type];
if (colorize) {
- highlighted += value
- .split(NEWLINE)
- .map(str => colorize(str))
- .join("\n");
+ highlighted +=
+ value
+ .split(NEWLINE)
+ .map(str => colorize(str))
+ .join("\n");
} else {
highlighted += value;
}
diff --git ORI/babel/packages/babel-parser/src/parser/expression.js ALT/babel/packages/babel-parser/src/parser/expression.js
index b50aed34e..c9a06b149 100644
--- ORI/babel/packages/babel-parser/src/parser/expression.js
+++ ALT/babel/packages/babel-parser/src/parser/expression.js
@@ -1552,9 +1552,10 @@ export default class ExpressionParser extends LValParser {
}
}
elem.value = {
- raw: this.input
- .slice(this.state.start, this.state.end)
- .replace(/\r\n?/g, "\n"),
+ raw:
+ this.input
+ .slice(this.state.start, this.state.end)
+ .replace(/\r\n?/g, "\n"),
cooked: this.state.value,
};
this.next();
diff --git ORI/babel/packages/babel-parser/src/tokenizer/index.js ALT/babel/packages/babel-parser/src/tokenizer/index.js
index 7c119c7d1..2c23b7ae2 100644
--- ORI/babel/packages/babel-parser/src/tokenizer/index.js
+++ ALT/babel/packages/babel-parser/src/tokenizer/index.js
@@ -1381,9 +1381,10 @@ export default class Tokenizer extends ParserErrors {
default:
if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {
const codePos = this.state.pos - 1;
- const match = this.input
- .substr(this.state.pos - 1, 3)
- .match(/^[0-7]+/);
+ const match =
+ this.input
+ .substr(this.state.pos - 1, 3)
+ .match(/^[0-7]+/);
// This is never null, because of the if condition above.
/*:: invariant(match !== null) */
diff --git ORI/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js ALT/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js
index 387e2634c..c0741f2f8 100644
--- ORI/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js
+++ ALT/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js
@@ -394,9 +394,10 @@ export default declare((api, opts) => {
const declaration = path.get("declaration");
if (!declaration.isVariableDeclaration()) return;
- const hasRest = declaration
- .get("declarations")
- .some(path => hasObjectPatternRestElement(path.get("id")));
+ const hasRest =
+ declaration
+ .get("declarations")
+ .some(path => hasObjectPatternRestElement(path.get("id")));
if (!hasRest) return;
const specifiers = [];
diff --git ORI/babel/packages/babel-plugin-transform-flow-comments/src/index.js ALT/babel/packages/babel-plugin-transform-flow-comments/src/index.js
index db926052c..afa1486ad 100644
--- ORI/babel/packages/babel-plugin-transform-flow-comments/src/index.js
+++ ALT/babel/packages/babel-plugin-transform-flow-comments/src/index.js
@@ -68,10 +68,11 @@ export default declare(api => {
}
function generateComment(path, optional) {
- let comment = path
- .getSource()
- .replace(/\*-\//g, "*-ESCAPED/")
- .replace(/\*\//g, "*-/");
+ let comment =
+ path
+ .getSource()
+ .replace(/\*-\//g, "*-ESCAPED/")
+ .replace(/\*\//g, "*-/");
if (optional) comment = "?" + comment;
if (comment[0] !== ":") comment = ":: " + comment;
return comment;
diff --git ORI/babel/packages/babel-plugin-transform-modules-amd/src/index.js ALT/babel/packages/babel-plugin-transform-modules-amd/src/index.js
index 7ea2b150f..adb8d0e21 100644
--- ORI/babel/packages/babel-plugin-transform-modules-amd/src/index.js
+++ ALT/babel/packages/babel-plugin-transform-modules-amd/src/index.js
@@ -27,10 +27,11 @@ function injectWrapper(path, wrapper) {
path.node.directives = [];
path.node.body = [];
const amdWrapper = path.pushContainer("body", wrapper)[0];
- const amdFactory = amdWrapper
- .get("expression.arguments")
- .filter(arg => arg.isFunctionExpression())[0]
- .get("body");
+ const amdFactory =
+ amdWrapper
+ .get("expression.arguments")
+ .filter(arg => arg.isFunctionExpression())[0]
+ .get("body");
amdFactory.pushContainer("directives", directives);
amdFactory.pushContainer("body", body);
}
diff --git ORI/babel/packages/babel-plugin-transform-modules-umd/src/index.js ALT/babel/packages/babel-plugin-transform-modules-umd/src/index.js
index 0f85d5f9a..0752f4ad6 100644
--- ORI/babel/packages/babel-plugin-transform-modules-umd/src/index.js
+++ ALT/babel/packages/babel-plugin-transform-modules-umd/src/index.js
@@ -108,12 +108,13 @@ export default declare((api, options) => {
if (exactGlobals) {
const globalRef = browserGlobals[source];
if (globalRef) {
- memberExpression = globalRef
- .split(".")
- .reduce(
- (accum, curr) => t.memberExpression(accum, t.identifier(curr)),
- t.identifier("global"),
- );
+ memberExpression =
+ globalRef
+ .split(".")
+ .reduce(
+ (accum, curr) => t.memberExpression(accum, t.identifier(curr)),
+ t.identifier("global"),
+ );
} else {
memberExpression = t.memberExpression(
t.identifier("global"),
@@ -228,9 +229,10 @@ export default declare((api, options) => {
),
}),
])[0];
- const umdFactory = umdWrapper
- .get("expression.arguments")[1]
- .get("body");
+ const umdFactory =
+ umdWrapper
+ .get("expression.arguments")[1]
+ .get("body");
umdFactory.pushContainer("directives", directives);
umdFactory.pushContainer("body", body);
},
diff --git ORI/babel/packages/babel-plugin-transform-parameters/src/rest.js ALT/babel/packages/babel-plugin-transform-parameters/src/rest.js
index cfba76ce4..42db73bfe 100644
--- ORI/babel/packages/babel-plugin-transform-parameters/src/rest.js
+++ ALT/babel/packages/babel-plugin-transform-parameters/src/rest.js
@@ -349,9 +349,10 @@ export default function convertFunctionRest(path) {
if (state.deopted) {
node.body.body.unshift(loop);
} else {
- let target = path
- .getEarliestCommonAncestorFrom(state.references)
- .getStatementParent();
+ let target =
+ path
+ .getEarliestCommonAncestorFrom(state.references)
+ .getStatementParent();
// don't perform the allocation inside a loop
target.findParent(path => {
diff --git ORI/babel/packages/babel-preset-env/src/debug.js ALT/babel/packages/babel-preset-env/src/debug.js
index b91499e72..9a180a71e 100644
--- ORI/babel/packages/babel-preset-env/src/debug.js
+++ ALT/babel/packages/babel-preset-env/src/debug.js
@@ -18,10 +18,11 @@ export const logPluginOrPolyfill = (
) => {
const filteredList = getInclusionReasons(item, targetVersions, list);
- const formattedTargets = JSON.stringify(filteredList)
- .replace(/,/g, ", ")
- .replace(/^\{"/, '{ "')
- .replace(/"\}$/, '" }');
+ const formattedTargets =
+ JSON.stringify(filteredList)
+ .replace(/,/g, ", ")
+ .replace(/^\{"/, '{ "')
+ .replace(/"\}$/, '" }');
console.log(` ${item} ${formattedTargets}`);
};
diff --git ORI/babel/packages/babel-preset-env/src/index.js ALT/babel/packages/babel-preset-env/src/index.js
index 90384f610..eec73efbb 100644
--- ORI/babel/packages/babel-preset-env/src/index.js
+++ ALT/babel/packages/babel-preset-env/src/index.js
@@ -326,30 +326,31 @@ option \`forceAllTransforms: true\` instead.
});
const pluginUseBuiltIns = useBuiltIns !== false;
- const plugins = Array.from(pluginNames)
- .map(pluginName => {
- if (
- pluginName === "proposal-class-properties" ||
- pluginName === "proposal-private-methods" ||
- // This is not included in preset-env yet, but let's keep it here so we
- // don't forget about it in the future.
- pluginName === "proposal-private-property-in-object"
- ) {
+ const plugins =
+ Array.from(pluginNames)
+ .map(pluginName => {
+ if (
+ pluginName === "proposal-class-properties" ||
+ pluginName === "proposal-private-methods" ||
+ // This is not included in preset-env yet, but let's keep it here so we
+ // don't forget about it in the future.
+ pluginName === "proposal-private-property-in-object"
+ ) {
+ return [
+ getPlugin(pluginName),
+ {
+ loose: loose
+ ? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"
+ : "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error",
+ },
+ ];
+ }
return [
getPlugin(pluginName),
- {
- loose: loose
- ? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"
- : "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error",
- },
+ { spec, loose, useBuiltIns: pluginUseBuiltIns },
];
- }
- return [
- getPlugin(pluginName),
- { spec, loose, useBuiltIns: pluginUseBuiltIns },
- ];
- })
- .concat(polyfillPlugins);
+ })
+ .concat(polyfillPlugins);
if (debug) {
console.log("@babel/preset-env: `DEBUG` option");
diff --git ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js
index caa8de4cf..96c4a6a5b 100644
--- ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js
+++ ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js
@@ -23,10 +23,11 @@ function isBabelPolyfillSource(source) {
function isCoreJSSource(source) {
if (typeof source === "string") {
- source = source
- .replace(/\\/g, "/")
- .replace(/(\/(index)?)?(\.js)?$/i, "")
- .toLowerCase();
+ source =
+ source
+ .replace(/\\/g, "/")
+ .replace(/(\/(index)?)?(\.js)?$/i, "")
+ .toLowerCase();
}
return has(corejsEntries, source) && corejsEntries[source];
}
diff --git ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js
index 37370a9b6..77edfac37 100644
--- ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js
+++ ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js
@@ -32,12 +32,13 @@ const NO_DIRECT_POLYFILL_IMPORT = `
When setting \`useBuiltIns: 'usage'\`, polyfills are automatically imported when needed.
Please remove the direct import of \`core-js\` or use \`useBuiltIns: 'entry'\` instead.`;
-const corejs3PolyfillsWithoutProposals = Object.keys(corejs3Polyfills)
- .filter(name => !name.startsWith("esnext."))
- .reduce((memo, key) => {
- memo[key] = corejs3Polyfills[key];
- return memo;
- }, {});
+const corejs3PolyfillsWithoutProposals =
+ Object.keys(corejs3Polyfills)
+ .filter(name => !name.startsWith("esnext."))
+ .reduce((memo, key) => {
+ memo[key] = corejs3Polyfills[key];
+ return memo;
+ }, {});
const corejs3PolyfillsWithShippedProposals =
(corejs3ShippedProposalsList: string[]).reduce(
diff --git ORI/babel/packages/babel-traverse/test/evaluation.js ALT/babel/packages/babel-traverse/test/evaluation.js
index d90ab87ff..ff8625c01 100644
--- ORI/babel/packages/babel-traverse/test/evaluation.js
+++ ALT/babel/packages/babel-traverse/test/evaluation.js
@@ -107,12 +107,14 @@ describe("evaluation", function () {
const member_expr = getPath(
"var x = Math.min(2,Math.max(3,4));var y = Math.random();",
);
- const eval_member_expr = member_expr
- .get("body.0.declarations.0.init")
- .evaluate();
- const eval_invalid_call = member_expr
- .get("body.1.declarations.0.init")
- .evaluate();
+ const eval_member_expr =
+ member_expr
+ .get("body.0.declarations.0.init")
+ .evaluate();
+ const eval_invalid_call =
+ member_expr
+ .get("body.1.declarations.0.init")
+ .evaluate();
expect(eval_member_expr.value).toBe(2);
expect(eval_invalid_call.confident).toBe(false);
});
@@ -177,15 +179,18 @@ describe("evaluation", function () {
});
it("should deopt redefined primitives - undefined, NaN and Infinity", () => {
- const eval_undef = getPath("let undefined; undefined;")
- .get("body.1.expression")
- .evaluate();
- const eval_nan = getPath("let NaN; NaN;")
- .get("body.1.expression")
- .evaluate();
- const eval_inf = getPath("let Infinity; Infinity;")
- .get("body.1.expression")
- .evaluate();
+ const eval_undef =
+ getPath("let undefined; undefined;")
+ .get("body.1.expression")
+ .evaluate();
+ const eval_nan =
+ getPath("let NaN; NaN;")
+ .get("body.1.expression")
+ .evaluate();
+ const eval_inf =
+ getPath("let Infinity; Infinity;")
+ .get("body.1.expression")
+ .evaluate();
expect(eval_undef.confident).toBe(false);
expect(eval_nan.confident).toBe(false);
expect(eval_inf.confident).toBe(false);
diff --git ORI/babel/packages/babel-traverse/test/inference.js ALT/babel/packages/babel-traverse/test/inference.js
index dde8bd227..1d9d2614d 100644
--- ORI/babel/packages/babel-traverse/test/inference.js
+++ ALT/babel/packages/babel-traverse/test/inference.js
@@ -17,9 +17,10 @@ function getPath(code) {
describe("inference", function () {
describe("baseTypeStrictlyMatches", function () {
it("it should work with null", function () {
- const path = getPath("var x = null; x === null")
- .get("body")[1]
- .get("expression");
+ const path =
+ getPath("var x = null; x === null")
+ .get("body")[1]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
@@ -28,9 +29,10 @@ describe("inference", function () {
});
it("it should work with numbers", function () {
- const path = getPath("var x = 1; x === 2")
- .get("body")[1]
- .get("expression");
+ const path =
+ getPath("var x = 1; x === 2")
+ .get("body")[1]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
@@ -39,9 +41,10 @@ describe("inference", function () {
});
it("it should bail when type changes", function () {
- const path = getPath("var x = 1; if (foo) x = null;else x = 3; x === 2")
- .get("body")[2]
- .get("expression");
+ const path =
+ getPath("var x = 1; if (foo) x = null;else x = 3; x === 2")
+ .get("body")[2]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
@@ -51,9 +54,10 @@ describe("inference", function () {
});
it("it should differentiate between null and undefined", function () {
- const path = getPath("var x; x === null")
- .get("body")[1]
- .get("expression");
+ const path =
+ getPath("var x; x === null")
+ .get("body")[1]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
@@ -141,34 +145,38 @@ describe("inference", function () {
).toBeTruthy();
});
it("should infer Function from function", function () {
- const path = getPath("(function (): string {})")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(function (): string {})")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Function",
).toBeTruthy();
});
it("should infer call return type using function", function () {
- const path = getPath("(function (): string {})()")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(function (): string {})()")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(t.isStringTypeAnnotation(type)).toBeTruthy();
});
it("should infer call return type using async function", function () {
- const path = getPath("(async function (): string {})()")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(async function (): string {})()")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Promise",
).toBeTruthy();
});
it("should infer call return type using async generator function", function () {
- const path = getPath("(async function * (): string {})()")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(async function * (): string {})()")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator",
@@ -197,9 +205,10 @@ describe("inference", function () {
expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy();
});
it("should infer type of tagged template literal", function () {
- const path = getPath("(function (): RegExp {}) `hey`")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(function (): RegExp {}) `hey`")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "RegExp",
diff --git ORI/eslint-plugin-vue/docs/.vuepress/config.js ALT/eslint-plugin-vue/docs/.vuepress/config.js
index fb7719f..fdd16d2 100644
--- ORI/eslint-plugin-vue/docs/.vuepress/config.js
+++ ALT/eslint-plugin-vue/docs/.vuepress/config.js
@@ -60,21 +60,23 @@ const sidebarCategories = [
const categorizedRules = []
for (const { title, categoryIds } of sidebarCategories) {
- const categoryRules = rules
- .filter((rule) => rule.meta.docs.categories && !rule.meta.deprecated)
- .filter((rule) =>
- categoryIds.every((categoryId) =>
- rule.meta.docs.categories.includes(categoryId)
+ const categoryRules =
+ rules
+ .filter((rule) => rule.meta.docs.categories && !rule.meta.deprecated)
+ .filter((rule) =>
+ categoryIds.every((categoryId) =>
+ rule.meta.docs.categories.includes(categoryId)
+ )
)
- )
- const children = categoryRules
- .filter(({ ruleId }) => {
- const exists = categorizedRules.some(({ children }) =>
- children.some(([, alreadyRuleId]) => alreadyRuleId === ruleId)
- )
- return !exists
- })
- .map(({ ruleId, name }) => [`/rules/${name}`, ruleId])
+ const children =
+ categoryRules
+ .filter(({ ruleId }) => {
+ const exists = categorizedRules.some(({ children }) =>
+ children.some(([, alreadyRuleId]) => alreadyRuleId === ruleId)
+ )
+ return !exists
+ })
+ .map(({ ruleId, name }) => [`/rules/${name}`, ruleId])
if (children.length === 0) {
continue
diff --git ORI/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js ALT/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js
index 88cd9de..ebc9087 100644
--- ORI/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js
+++ ALT/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js
@@ -68,64 +68,65 @@ function getRuleInfo(ast) {
let exportsVarOverridden = false
let exportsIsFunction = false
- const exportNodes = ast.body
- .filter((statement) => statement.type === 'ExpressionStatement')
- .map((statement) => statement.expression)
- .filter((expression) => expression.type === 'AssignmentExpression')
- .filter((expression) => expression.left.type === 'MemberExpression')
- .reduce((currentExports, node) => {
- if (
- node.left.object.type === 'Identifier' &&
- node.left.object.name === 'module' &&
- node.left.property.type === 'Identifier' &&
- node.left.property.name === 'exports'
- ) {
- exportsVarOverridden = true
+ const exportNodes =
+ ast.body
+ .filter((statement) => statement.type === 'ExpressionStatement')
+ .map((statement) => statement.expression)
+ .filter((expression) => expression.type === 'AssignmentExpression')
+ .filter((expression) => expression.left.type === 'MemberExpression')
+ .reduce((currentExports, node) => {
+ if (
+ node.left.object.type === 'Identifier' &&
+ node.left.object.name === 'module' &&
+ node.left.property.type === 'Identifier' &&
+ node.left.property.name === 'exports'
+ ) {
+ exportsVarOverridden = true
- if (isNormalFunctionExpression(node.right)) {
- // Check `module.exports = function () {}`
+ if (isNormalFunctionExpression(node.right)) {
+ // Check `module.exports = function () {}`
- exportsIsFunction = true
- return { create: node.right, meta: null }
- } else if (node.right.type === 'ObjectExpression') {
- // Check `module.exports = { create: function () {}, meta: {} }`
+ exportsIsFunction = true
+ return { create: node.right, meta: null }
+ } else if (node.right.type === 'ObjectExpression') {
+ // Check `module.exports = { create: function () {}, meta: {} }`
- exportsIsFunction = false
- return node.right.properties.reduce((parsedProps, prop) => {
- const keyValue = getKeyName(prop)
- if (INTERESTING_KEYS.has(keyValue)) {
- parsedProps[keyValue] = prop.value
- }
- return parsedProps
- }, {})
- }
- return {}
- } else if (
- !exportsIsFunction &&
- node.left.object.type === 'MemberExpression' &&
- node.left.object.object.type === 'Identifier' &&
- node.left.object.object.name === 'module' &&
- node.left.object.property.type === 'Identifier' &&
- node.left.object.property.name === 'exports' &&
- node.left.property.type === 'Identifier' &&
- INTERESTING_KEYS.has(node.left.property.name)
- ) {
- // Check `module.exports.create = () => {}`
+ exportsIsFunction = false
+ return node.right.properties.reduce((parsedProps, prop) => {
+ const keyValue = getKeyName(prop)
+ if (INTERESTING_KEYS.has(keyValue)) {
+ parsedProps[keyValue] = prop.value
+ }
+ return parsedProps
+ }, {})
+ }
+ return {}
+ } else if (
+ !exportsIsFunction &&
+ node.left.object.type === 'MemberExpression' &&
+ node.left.object.object.type === 'Identifier' &&
+ node.left.object.object.name === 'module' &&
+ node.left.object.property.type === 'Identifier' &&
+ node.left.object.property.name === 'exports' &&
+ node.left.property.type === 'Identifier' &&
+ INTERESTING_KEYS.has(node.left.property.name)
+ ) {
+ // Check `module.exports.create = () => {}`
- currentExports[node.left.property.name] = node.right
- } else if (
- !exportsVarOverridden &&
- node.left.object.type === 'Identifier' &&
- node.left.object.name === 'exports' &&
- node.left.property.type === 'Identifier' &&
- INTERESTING_KEYS.has(node.left.property.name)
- ) {
- // Check `exports.create = () => {}`
+ currentExports[node.left.property.name] = node.right
+ } else if (
+ !exportsVarOverridden &&
+ node.left.object.type === 'Identifier' &&
+ node.left.object.name === 'exports' &&
+ node.left.property.type === 'Identifier' &&
+ INTERESTING_KEYS.has(node.left.property.name)
+ ) {
+ // Check `exports.create = () => {}`
- currentExports[node.left.property.name] = node.right
- }
- return currentExports
- }, {})
+ currentExports[node.left.property.name] = node.right
+ }
+ return currentExports
+ }, {})
return Object.prototype.hasOwnProperty.call(exportNodes, 'create')
? Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes)
diff --git ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js
index d215a27..b303b40 100644
--- ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js
+++ ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js
@@ -38,14 +38,15 @@ module.exports = {
return {}
}
const sourceCode = context.getSourceCode()
- const scriptElement = documentFragment.children
- .filter(utils.isVElement)
- .find(
- (element) =>
- element.name === 'script' &&
- element.range[0] <= sourceCode.ast.range[0] &&
- sourceCode.ast.range[1] <= element.range[1]
- )
+ const scriptElement =
+ documentFragment.children
+ .filter(utils.isVElement)
+ .find(
+ (element) =>
+ element.name === 'script' &&
+ element.range[0] <= sourceCode.ast.range[0] &&
+ sourceCode.ast.range[1] <= element.range[1]
+ )
if (!scriptElement) {
return {}
}
diff --git ORI/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js ALT/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js
index 786ecb9..eef0741 100644
--- ORI/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js
+++ ALT/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js
@@ -49,9 +49,10 @@ module.exports = {
return null
}
- const bindArgument = context
- .getSourceCode()
- .getText(node.key.argument)
+ const bindArgument =
+ context
+ .getSourceCode()
+ .getText(node.key.argument)
return fixer.replaceText(node.key, `v-model:${bindArgument}`)
}
})
diff --git ORI/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js ALT/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js
index f3ac473..8b578ab 100644
--- ORI/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js
+++ ALT/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js
@@ -75,20 +75,21 @@ module.exports = {
return {}
}
return utils.executeOnVue(context, (obj) => {
- const componentInstanceOptions = obj.properties
- .map((p) => {
- if (p.type === 'Property') {
- const name = utils.getStaticPropertyName(p)
- if (name != null) {
- return {
- name,
- key: p.key
+ const componentInstanceOptions =
+ obj.properties
+ .map((p) => {
+ if (p.type === 'Property') {
+ const name = utils.getStaticPropertyName(p)
+ if (name != null) {
+ return {
+ name,
+ key: p.key
+ }
}
}
- }
- return null
- })
- .filter(utils.isDef)
+ return null
+ })
+ .filter(utils.isDef)
if (!componentInstanceOptions.length) {
return
@@ -99,10 +100,11 @@ module.exports = {
if (candidateOptionSet.has(name)) {
return
}
- const potentialTypoList = candidateOptionList
- .map((o) => ({ option: o, distance: utils.editDistance(o, name) }))
- .filter(({ distance }) => distance <= threshold && distance > 0)
- .sort((a, b) => a.distance - b.distance)
+ const potentialTypoList =
+ candidateOptionList
+ .map((o) => ({ option: o, distance: utils.editDistance(o, name) }))
+ .filter(({ distance }) => distance <= threshold && distance > 0)
+ .sort((a, b) => a.distance - b.distance)
if (potentialTypoList.length) {
context.report({
node: id,
diff --git ORI/eslint-plugin-vue/lib/rules/no-unregistered-components.js ALT/eslint-plugin-vue/lib/rules/no-unregistered-components.js
index 6e6cb2a..5a3f29f 100644
--- ORI/eslint-plugin-vue/lib/rules/no-unregistered-components.js
+++ ALT/eslint-plugin-vue/lib/rules/no-unregistered-components.js
@@ -133,9 +133,10 @@ module.exports = {
)
// All registered components using kebab-case syntax
- const componentsRegisteredAsKebabCase = registeredComponents
- .filter(({ name }) => name === casing.kebabCase(name))
- .map(({ name }) => name)
+ const componentsRegisteredAsKebabCase =
+ registeredComponents
+ .filter(({ name }) => name === casing.kebabCase(name))
+ .map(({ name }) => name)
usedComponentNodes
.filter(({ name }) => {
diff --git ORI/eslint-plugin-vue/lib/rules/no-useless-mustaches.js ALT/eslint-plugin-vue/lib/rules/no-useless-mustaches.js
index 709617e..9021628 100644
--- ORI/eslint-plugin-vue/lib/rules/no-useless-mustaches.js
+++ ALT/eslint-plugin-vue/lib/rules/no-useless-mustaches.js
@@ -93,9 +93,10 @@ module.exports = {
}
const tokenStore = context.parserServices.getTemplateBodyTokenStore()
- const hasComment = tokenStore
- .getTokens(node, { includeComments: true })
- .some((t) => t.type === 'Block' || t.type === 'Line')
+ const hasComment =
+ tokenStore
+ .getTokens(node, { includeComments: true })
+ .some((t) => t.type === 'Block' || t.type === 'Line')
if (ignoreIncludesComment && hasComment) {
return
}
diff --git ORI/eslint-plugin-vue/lib/rules/no-useless-v-bind.js ALT/eslint-plugin-vue/lib/rules/no-useless-v-bind.js
index c2440da..fd934d7 100644
--- ORI/eslint-plugin-vue/lib/rules/no-useless-v-bind.js
+++ ALT/eslint-plugin-vue/lib/rules/no-useless-v-bind.js
@@ -76,9 +76,10 @@ module.exports = {
}
const tokenStore = context.parserServices.getTemplateBodyTokenStore()
- const hasComment = tokenStore
- .getTokens(value, { includeComments: true })
- .some((t) => t.type === 'Block' || t.type === 'Line')
+ const hasComment =
+ tokenStore
+ .getTokens(value, { includeComments: true })
+ .some((t) => t.type === 'Block' || t.type === 'Line')
if (ignoreIncludesComment && hasComment) {
return
}
@@ -134,9 +135,10 @@ module.exports = {
} else if (quoteChar === "'") {
attrValue = strValue.replace(SINGLE_QUOTES_RE, ''')
} else {
- attrValue = strValue
- .replace(DOUBLE_QUOTES_RE, '"')
- .replace(SINGLE_QUOTES_RE, ''')
+ attrValue =
+ strValue
+ .replace(DOUBLE_QUOTES_RE, '"')
+ .replace(SINGLE_QUOTES_RE, ''')
}
yield fixer.replaceText(expression, attrValue)
}
diff --git ORI/eslint-plugin-vue/lib/rules/order-in-components.js ALT/eslint-plugin-vue/lib/rules/order-in-components.js
index 5f33734..0681c85 100644
--- ORI/eslint-plugin-vue/lib/rules/order-in-components.js
+++ ALT/eslint-plugin-vue/lib/rules/order-in-components.js
@@ -271,13 +271,14 @@ module.exports = {
return
}
const propertiesAbove = properties.slice(0, i)
- const unorderedProperties = propertiesAbove
- .filter(
- (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
- )
- .sort((p1, p2) =>
- getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
- )
+ const unorderedProperties =
+ propertiesAbove
+ .filter(
+ (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
+ )
+ .sort((p1, p2) =>
+ getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
+ )
const firstUnorderedProperty = unorderedProperties[0]
@@ -294,15 +295,16 @@ module.exports = {
*fix(fixer) {
const propertyNode = property.node
const firstUnorderedPropertyNode = firstUnorderedProperty.node
- const hasSideEffectsPossibility = propertiesNodes
- .slice(
- propertiesNodes.indexOf(firstUnorderedPropertyNode),
- propertiesNodes.indexOf(propertyNode) + 1
- )
- .some(
- (property) =>
- !isNotSideEffectsNode(property, sourceCode.visitorKeys)
- )
+ const hasSideEffectsPossibility =
+ propertiesNodes
+ .slice(
+ propertiesNodes.indexOf(firstUnorderedPropertyNode),
+ propertiesNodes.indexOf(propertyNode) + 1
+ )
+ .some(
+ (property) =>
+ !isNotSideEffectsNode(property, sourceCode.visitorKeys)
+ )
if (hasSideEffectsPossibility) {
return
}
diff --git ORI/eslint-plugin-vue/lib/rules/require-default-prop.js ALT/eslint-plugin-vue/lib/rules/require-default-prop.js
index e0e29b6..cb70b3e 100644
--- ORI/eslint-plugin-vue/lib/rules/require-default-prop.js
+++ ALT/eslint-plugin-vue/lib/rules/require-default-prop.js
@@ -158,13 +158,14 @@ module.exports = {
// ----------------------------------------------------------------------
return utils.executeOnVue(context, (obj) => {
- const props = utils
- .getComponentProps(obj)
- .filter(
- (prop) =>
- prop.value &&
- !(prop.node.type === 'Property' && prop.node.shorthand)
- )
+ const props =
+ utils
+ .getComponentProps(obj)
+ .filter(
+ (prop) =>
+ prop.value &&
+ !(prop.node.type === 'Property' && prop.node.shorthand)
+ )
const propsWithoutDefault = findPropsWithoutDefaultValue(
/** @type {ComponentObjectProp[]} */ (props)
diff --git ORI/eslint-plugin-vue/lib/utils/indent-common.js ALT/eslint-plugin-vue/lib/utils/indent-common.js
index c4818b4..b947776 100644
--- ORI/eslint-plugin-vue/lib/utils/indent-common.js
+++ ALT/eslint-plugin-vue/lib/utils/indent-common.js
@@ -1878,12 +1878,14 @@ module.exports.defineVisitor = function create(
/** @param {TemplateLiteral} node */
TemplateLiteral(node) {
const firstToken = tokenStore.getFirstToken(node)
- const quasiTokens = node.quasis
- .slice(1)
- .map((n) => tokenStore.getFirstToken(n))
- const expressionToken = node.quasis
- .slice(0, -1)
- .map((n) => tokenStore.getTokenAfter(n))
+ const quasiTokens =
+ node.quasis
+ .slice(1)
+ .map((n) => tokenStore.getFirstToken(n))
+ const expressionToken =
+ node.quasis
+ .slice(0, -1)
+ .map((n) => tokenStore.getTokenAfter(n))
setOffset(quasiTokens, 0, firstToken)
setOffset(expressionToken, 1, firstToken)
diff --git ORI/eslint-plugin-vue/lib/utils/index.js ALT/eslint-plugin-vue/lib/utils/index.js
index 055ffb4..5e8d004 100644
--- ORI/eslint-plugin-vue/lib/utils/index.js
+++ ALT/eslint-plugin-vue/lib/utils/index.js
@@ -2033,9 +2033,10 @@ function getComponentComments(context) {
return tokens
}
const sourceCode = context.getSourceCode()
- tokens = sourceCode
- .getAllComments()
- .filter((comment) => /@vue\/component/g.test(comment.value))
+ tokens =
+ sourceCode
+ .getAllComments()
+ .filter((comment) => /@vue\/component/g.test(comment.value))
componentComments.set(context, tokens)
return tokens
}
diff --git ORI/eslint-plugin-vue/tests/lib/rules/html-indent.js ALT/eslint-plugin-vue/tests/lib/rules/html-indent.js
index 316eb92..5f705b8 100644
--- ORI/eslint-plugin-vue/tests/lib/rules/html-indent.js
+++ ALT/eslint-plugin-vue/tests/lib/rules/html-indent.js
@@ -50,36 +50,41 @@ function loadPatterns(additionalValid, additionalInvalid) {
}
return Object.assign(baseObj, { code, filename })
})
- const invalid = valid
- .map((pattern) => {
- const kind =
- (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
- const output = pattern.code
- const lines = output.split('\n').map((text, number) => ({
- number,
- text,
- indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
- }))
- const code = lines
- .map((line) => line.text.replace(/^[ \t]+/, ''))
- .join('\n')
- const errors = lines
- .map((line) =>
- line.indentSize === 0
- ? null
- : {
- message: `Expected indentation of ${line.indentSize} ${kind}${
- line.indentSize === 1 ? '' : 's'
- } but found 0 ${kind}s.`,
- line: line.number + 1
- }
- )
- .filter(Boolean)
+ const invalid =
+ valid
+ .map((pattern) => {
+ const kind =
+ (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
+ const output = pattern.code
+ const lines = output.split('\n').map((text, number) => ({
+ number,
+ text,
+ indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
+ }))
+ const code =
+ lines
+ .map((line) => line.text.replace(/^[ \t]+/, ''))
+ .join('\n')
+ const errors =
+ lines
+ .map((line) =>
+ line.indentSize === 0
+ ? null
+ : {
+ message: `Expected indentation of ${
+ line.indentSize
+ } ${kind}${
+ line.indentSize === 1 ? '' : 's'
+ } but found 0 ${kind}s.`,
+ line: line.number + 1
+ }
+ )
+ .filter(Boolean)
- return Object.assign({}, pattern, { code, output, errors })
- })
- .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
- .filter(Boolean)
+ return Object.assign({}, pattern, { code, output, errors })
+ })
+ .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
+ .filter(Boolean)
return {
valid: valid.concat(additionalValid),
@@ -94,13 +99,15 @@ function loadPatterns(additionalValid, additionalInvalid) {
*/
function unIndent(strings) {
const templateValue = strings[0]
- const lines = templateValue
- .replace(/^\n/, '')
- .replace(/\n\s*$/, '')
- .split('\n')
- const lineIndents = lines
- .filter((line) => line.trim())
- .map((line) => line.match(/ */)[0].length)
+ const lines =
+ templateValue
+ .replace(/^\n/, '')
+ .replace(/\n\s*$/, '')
+ .split('\n')
+ const lineIndents =
+ lines
+ .filter((line) => line.trim())
+ .map((line) => line.match(/ */)[0].length)
const minLineIndent = Math.min.apply(null, lineIndents)
return lines.map((line) => line.slice(minLineIndent)).join('\n')
diff --git ORI/eslint-plugin-vue/tests/lib/rules/script-indent.js ALT/eslint-plugin-vue/tests/lib/rules/script-indent.js
index 865e731..cbe90f2 100644
--- ORI/eslint-plugin-vue/tests/lib/rules/script-indent.js
+++ ALT/eslint-plugin-vue/tests/lib/rules/script-indent.js
@@ -51,36 +51,41 @@ function loadPatterns(additionalValid, additionalInvalid) {
}
return Object.assign(baseObj, { code, filename })
})
- const invalid = valid
- .map((pattern) => {
- const kind =
- (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
- const output = pattern.code
- const lines = output.split('\n').map((text, number) => ({
- number,
- text,
- indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
- }))
- const code = lines
- .map((line) => line.text.replace(/^[ \t]+/, ''))
- .join('\n')
- const errors = lines
- .map((line) =>
- line.indentSize === 0
- ? null
- : {
- message: `Expected indentation of ${line.indentSize} ${kind}${
- line.indentSize === 1 ? '' : 's'
- } but found 0 ${kind}s.`,
- line: line.number + 1
- }
- )
- .filter(Boolean)
+ const invalid =
+ valid
+ .map((pattern) => {
+ const kind =
+ (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
+ const output = pattern.code
+ const lines = output.split('\n').map((text, number) => ({
+ number,
+ text,
+ indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
+ }))
+ const code =
+ lines
+ .map((line) => line.text.replace(/^[ \t]+/, ''))
+ .join('\n')
+ const errors =
+ lines
+ .map((line) =>
+ line.indentSize === 0
+ ? null
+ : {
+ message: `Expected indentation of ${
+ line.indentSize
+ } ${kind}${
+ line.indentSize === 1 ? '' : 's'
+ } but found 0 ${kind}s.`,
+ line: line.number + 1
+ }
+ )
+ .filter(Boolean)
- return Object.assign({}, pattern, { code, output, errors })
- })
- .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
- .filter(Boolean)
+ return Object.assign({}, pattern, { code, output, errors })
+ })
+ .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
+ .filter(Boolean)
return {
valid: valid.concat(additionalValid),
@@ -95,13 +100,15 @@ function loadPatterns(additionalValid, additionalInvalid) {
*/
function unIndent(strings) {
const templateValue = strings[0]
- const lines = templateValue
- .replace(/^\n/, '')
- .replace(/\n\s*$/, '')
- .split('\n')
- const lineIndents = lines
- .filter((line) => line.trim())
- .map((line) => line.match(/ */)[0].length)
+ const lines =
+ templateValue
+ .replace(/^\n/, '')
+ .replace(/\n\s*$/, '')
+ .split('\n')
+ const lineIndents =
+ lines
+ .filter((line) => line.trim())
+ .map((line) => line.match(/ */)[0].length)
const minLineIndent = Math.min.apply(null, lineIndents)
return lines.map((line) => line.slice(minLineIndent)).join('\n')
diff --git ORI/eslint-plugin-vue/tests/lib/rules/this-in-template.js ALT/eslint-plugin-vue/tests/lib/rules/this-in-template.js
index 5f36b57..00b174a 100644
--- ORI/eslint-plugin-vue/tests/lib/rules/this-in-template.js
+++ ALT/eslint-plugin-vue/tests/lib/rules/this-in-template.js
@@ -185,41 +185,43 @@ function createInvalidTests(prefix, options, message, type) {
}
ruleTester.run('this-in-template', rule, {
- valid: ['', '<template></template>', '<template><div></div></template>']
- .concat(createValidTests('', []))
- .concat(createValidTests('', ['never']))
- .concat(createValidTests('this.', ['always']))
- .concat(createValidTests('this?.', ['always'])),
- invalid: []
- .concat(
- createInvalidTests(
- 'this.',
- [],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
- ),
- createInvalidTests(
- 'this?.',
- [],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
+ valid:
+ ['', '<template></template>', '<template><div></div></template>']
+ .concat(createValidTests('', []))
+ .concat(createValidTests('', ['never']))
+ .concat(createValidTests('this.', ['always']))
+ .concat(createValidTests('this?.', ['always'])),
+ invalid:
+ []
+ .concat(
+ createInvalidTests(
+ 'this.',
+ [],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ ),
+ createInvalidTests(
+ 'this?.',
+ [],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ )
)
- )
- .concat(
- createInvalidTests(
- 'this.',
- ['never'],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
- ),
- createInvalidTests(
- 'this?.',
- ['never'],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
+ .concat(
+ createInvalidTests(
+ 'this.',
+ ['never'],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ ),
+ createInvalidTests(
+ 'this?.',
+ ['never'],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ )
+ )
+ .concat(
+ createInvalidTests('', ['always'], "Expected 'this'.", 'Identifier')
)
- )
- .concat(
- createInvalidTests('', ['always'], "Expected 'this'.", 'Identifier')
- )
})
diff --git ORI/eslint-plugin-vue/tests/lib/utils/vue-component.js ALT/eslint-plugin-vue/tests/lib/utils/vue-component.js
index 91da3d2..0845ea4 100644
--- ORI/eslint-plugin-vue/tests/lib/utils/vue-component.js
+++ ALT/eslint-plugin-vue/tests/lib/utils/vue-component.js
@@ -327,31 +327,33 @@ function invalidTests(ext) {
const ruleTester = new RuleTester()
ruleTester.run('vue-component', rule, {
- valid: [
- {
- filename: 'test.js',
- code: `export default { }`,
- parserOptions
- }
- ]
- .concat(validTests('js'))
- .concat(validTests('jsx'))
- .concat(validTests('vue')),
- invalid: [
- {
- filename: 'test.vue',
- code: `export default { }`,
- parserOptions,
- errors: [makeError(1)]
- },
- {
- filename: 'test.jsx',
- code: `export default { }`,
- parserOptions,
- errors: [makeError(1)]
- }
- ]
- .concat(invalidTests('js'))
- .concat(invalidTests('jsx'))
- .concat(invalidTests('vue'))
+ valid:
+ [
+ {
+ filename: 'test.js',
+ code: `export default { }`,
+ parserOptions
+ }
+ ]
+ .concat(validTests('js'))
+ .concat(validTests('jsx'))
+ .concat(validTests('vue')),
+ invalid:
+ [
+ {
+ filename: 'test.vue',
+ code: `export default { }`,
+ parserOptions,
+ errors: [makeError(1)]
+ },
+ {
+ filename: 'test.jsx',
+ code: `export default { }`,
+ parserOptions,
+ errors: [makeError(1)]
+ }
+ ]
+ .concat(invalidTests('js'))
+ .concat(invalidTests('jsx'))
+ .concat(invalidTests('vue'))
})
diff --git ORI/eslint-plugin-vue/tools/lib/categories.js ALT/eslint-plugin-vue/tools/lib/categories.js
index 9f7fd79..6f96b6f 100644
--- ORI/eslint-plugin-vue/tools/lib/categories.js
+++ ALT/eslint-plugin-vue/tools/lib/categories.js
@@ -75,12 +75,13 @@ for (const rule of rules) {
}
}
-module.exports = categoryIds
- .map((categoryId) => ({
- categoryId,
- title: categoryTitles[categoryId],
- rules: (categoryRules[categoryId] || []).filter(
- (rule) => !rule.meta.deprecated
- )
- }))
- .filter((category) => category.rules.length >= 1)
+module.exports =
+ categoryIds
+ .map((categoryId) => ({
+ categoryId,
+ title: categoryTitles[categoryId],
+ rules: (categoryRules[categoryId] || []).filter(
+ (rule) => !rule.meta.deprecated
+ )
+ }))
+ .filter((category) => category.rules.length >= 1)
diff --git ORI/eslint-plugin-vue/tools/lib/configs.js ALT/eslint-plugin-vue/tools/lib/configs.js
index 031f41e..14cc8c5 100644
--- ORI/eslint-plugin-vue/tools/lib/configs.js
+++ ALT/eslint-plugin-vue/tools/lib/configs.js
@@ -9,7 +9,8 @@ const fs = require('fs')
const path = require('path')
const ROOT = path.resolve(__dirname, '../../lib/configs')
-module.exports = fs
- .readdirSync(ROOT)
- .filter((file) => path.extname(file) === '.js')
- .map((file) => path.basename(file, '.js'))
+module.exports =
+ fs
+ .readdirSync(ROOT)
+ .filter((file) => path.extname(file) === '.js')
+ .map((file) => path.basename(file, '.js'))
diff --git ORI/eslint-plugin-vue/tools/lib/rules.js ALT/eslint-plugin-vue/tools/lib/rules.js
index 745c635..27f4be5 100644
--- ORI/eslint-plugin-vue/tools/lib/rules.js
+++ ALT/eslint-plugin-vue/tools/lib/rules.js
@@ -9,20 +9,21 @@ const fs = require('fs')
const path = require('path')
const ROOT = path.resolve(__dirname, '../../lib/rules')
-module.exports = fs
- .readdirSync(ROOT)
- .filter((file) => path.extname(file) === '.js')
- .map((file) => path.basename(file, '.js'))
- .map((name) => {
- const meta = { ...require(path.join(ROOT, name)).meta }
- if (meta.docs && !meta.docs.categories && meta.docs.category) {
- // for vue3 migration
- meta.docs = { ...meta.docs }
- meta.docs.categories = [meta.docs.category]
- }
- return {
- ruleId: `vue/${name}`,
- name,
- meta
- }
- })
+module.exports =
+ fs
+ .readdirSync(ROOT)
+ .filter((file) => path.extname(file) === '.js')
+ .map((file) => path.basename(file, '.js'))
+ .map((name) => {
+ const meta = { ...require(path.join(ROOT, name)).meta }
+ if (meta.docs && !meta.docs.categories && meta.docs.category) {
+ // for vue3 migration
+ meta.docs = { ...meta.docs }
+ meta.docs.categories = [meta.docs.category]
+ }
+ return {
+ ruleId: `vue/${name}`,
+ name,
+ meta
+ }
+ })
diff --git ORI/eslint-plugin-vue/tools/update-docs-rules-index.js ALT/eslint-plugin-vue/tools/update-docs-rules-index.js
index 6e9c0f0..cf7d66e 100644
--- ORI/eslint-plugin-vue/tools/update-docs-rules-index.js
+++ ALT/eslint-plugin-vue/tools/update-docs-rules-index.js
@@ -37,17 +37,19 @@ function toRuleRow(rule) {
function toDeprecatedRuleRow(rule) {
const link = `[${rule.ruleId}](./${rule.name}.md)`
const replacedRules = rule.meta.docs.replacedBy || []
- const replacedBy = replacedRules
- .map((name) => `[vue/${name}](./${name}.md)`)
- .join(', ')
+ const replacedBy =
+ replacedRules
+ .map((name) => `[vue/${name}](./${name}.md)`)
+ .join(', ')
return `| ${link} | ${replacedBy || '(no replacement)'} |`
}
// -----------------------------------------------------------------------------
-let rulesTableContent = categories
- .map(
- (category) => `
+let rulesTableContent =
+ categories
+ .map(
+ (category) => `
## ${category.title.vuepress}
Enforce all the rules in this category, as well as all higher priority rules, with:
@@ -62,8 +64,8 @@ Enforce all the rules in this category, as well as all higher priority rules, wi
|:--------|:------------|:---|
${category.rules.map(toRuleRow).join('\n')}
`
- )
- .join('')
+ )
+ .join('')
// -----------------------------------------------------------------------------
if (uncategorizedRules.length || uncategorizedExtensionRule.length) {
diff --git ORI/prettier/scripts/build/cache.js ALT/prettier/scripts/build/cache.js
index 8f7b5c961..5a40389b6 100644
--- ORI/prettier/scripts/build/cache.js
+++ ALT/prettier/scripts/build/cache.js
@@ -67,9 +67,10 @@ class Cache {
const bundle = await rollup(getRollupConfig(inputOptions));
const { output } = await bundle.generate(outputOptions);
- const modules = output
- .filter((mod) => !/\0/.test(mod.facadeModuleId))
- .map((mod) => [path.relative(ROOT, mod.facadeModuleId), mod.code]);
+ const modules =
+ output
+ .filter((mod) => !/\0/.test(mod.facadeModuleId))
+ .map((mod) => [path.relative(ROOT, mod.facadeModuleId), mod.code]);
for (const [id, code] of modules) {
newFiles.push(id);
diff --git ORI/prettier/scripts/draft-blog-post.js ALT/prettier/scripts/draft-blog-post.js
index eca419567..06997825b 100644
--- ORI/prettier/scripts/draft-blog-post.js
+++ ALT/prettier/scripts/draft-blog-post.js
@@ -51,9 +51,10 @@ const categoriesByDir = categories.reduce((result, category) => {
return result;
}, {});
-const dirs = fs
- .readdirSync(changelogUnreleasedDir, { withFileTypes: true })
- .filter((entry) => entry.isDirectory());
+const dirs =
+ fs
+ .readdirSync(changelogUnreleasedDir, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory());
for (const dir of dirs) {
const dirPath = path.join(changelogUnreleasedDir, dir.name);
@@ -63,20 +64,22 @@ for (const dir of dirs) {
throw new Error("Unknown category: " + dir.name);
}
- category.entries = fs
- .readdirSync(dirPath)
- .filter((fileName) => /^\d+\.md$/.test(fileName))
- .map((fileName) => {
- const [title, ...rest] = fs
- .readFileSync(path.join(dirPath, fileName), "utf8")
- .trim()
- .split("\n");
- return {
- breaking: title.includes("[BREAKING]"),
- highlight: title.includes("[HIGHLIGHT]"),
- content: [processTitle(title), ...rest].join("\n"),
- };
- });
+ category.entries =
+ fs
+ .readdirSync(dirPath)
+ .filter((fileName) => /^\d+\.md$/.test(fileName))
+ .map((fileName) => {
+ const [title, ...rest] =
+ fs
+ .readFileSync(path.join(dirPath, fileName), "utf8")
+ .trim()
+ .split("\n");
+ return {
+ breaking: title.includes("[BREAKING]"),
+ highlight: title.includes("[HIGHLIGHT]"),
+ content: [processTitle(title), ...rest].join("\n"),
+ };
+ });
}
rimraf.sync(postGlob);
diff --git ORI/prettier/scripts/release/release.js ALT/prettier/scripts/release/release.js
index f063191be..feacf9a1a 100644
--- ORI/prettier/scripts/release/release.js
+++ ALT/prettier/scripts/release/release.js
@@ -18,9 +18,10 @@ async function run() {
alias: { v: "version" },
});
- const previousVersion = execSync("git describe --tags --abbrev=0")
- .toString()
- .trim();
+ const previousVersion =
+ execSync("git describe --tags --abbrev=0")
+ .toString()
+ .trim();
if (semver.parse(previousVersion) === null) {
throw new Error(`Unexpected previousVersion: ${previousVersion}`);
diff --git ORI/prettier/src/cli/expand-patterns.js ALT/prettier/src/cli/expand-patterns.js
index b840ce723..f130df44d 100644
--- ORI/prettier/src/cli/expand-patterns.js
+++ ALT/prettier/src/cli/expand-patterns.js
@@ -55,9 +55,10 @@ function* expandPatternsInternal(context) {
const globOptions = {
dot: true,
- ignore: Object.entries(silentlyIgnoredDirs)
- .filter(([, ignored]) => ignored)
- .map(([dir]) => "**/" + dir),
+ ignore:
+ Object.entries(silentlyIgnoredDirs)
+ .filter(([, ignored]) => ignored)
+ .map(([dir]) => "**/" + dir),
};
let supportedFilesGlob;
diff --git ORI/prettier/src/cli/usage.js ALT/prettier/src/cli/usage.js
index 2685b3bc6..3ce552a82 100644
--- ORI/prettier/src/cli/usage.js
+++ ALT/prettier/src/cli/usage.js
@@ -140,11 +140,12 @@ function createUsage(context) {
];
const optionsUsage = allCategories.map((category) => {
- const categoryOptions = groupedOptions[category]
- .map((option) =>
- createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)
- )
- .join("\n");
+ const categoryOptions =
+ groupedOptions[category]
+ .map((option) =>
+ createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)
+ )
+ .join("\n");
return `${category} options:\n\n${indent(categoryOptions, 2)}`;
});
diff --git ORI/prettier/src/document/doc-printer.js ALT/prettier/src/document/doc-printer.js
index 5e2558f1a..3769f4f1a 100644
--- ORI/prettier/src/document/doc-printer.js
+++ ALT/prettier/src/document/doc-printer.js
@@ -546,9 +546,10 @@ function printDocToString(doc, options) {
cursorPlaceholderIndex + 1
);
const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
- const aroundCursor = out
- .slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex)
- .join("");
+ const aroundCursor =
+ out
+ .slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex)
+ .join("");
const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
return {
diff --git ORI/prettier/src/language-handlebars/printer-glimmer.js ALT/prettier/src/language-handlebars/printer-glimmer.js
index fccfa2dea..e0d17fde6 100644
--- ORI/prettier/src/language-handlebars/printer-glimmer.js
+++ ALT/prettier/src/language-handlebars/printer-glimmer.js
@@ -406,14 +406,15 @@ function print(path, options, print) {
function printStartingTag(path, print) {
const node = path.getValue();
- const attributesLike = ["attributes", "modifiers", "comments", "blockParams"]
- .filter((property) => isNonEmptyArray(node[property]))
- .map((property) => [
- line,
- property === "blockParams"
- ? printBlockParams(node)
- : join(line, path.map(print, property)),
- ]);
+ const attributesLike =
+ ["attributes", "modifiers", "comments", "blockParams"]
+ .filter((property) => isNonEmptyArray(node[property]))
+ .map((property) => [
+ line,
+ property === "blockParams"
+ ? printBlockParams(node)
+ : join(line, path.map(print, property)),
+ ]);
return [
"<",
diff --git ORI/prettier/src/language-html/parser-html.js ALT/prettier/src/language-html/parser-html.js
index 748c3cf7a..a407c41a9 100644
--- ORI/prettier/src/language-html/parser-html.js
+++ ALT/prettier/src/language-html/parser-html.js
@@ -196,9 +196,10 @@ function ngHtmlParser(
}
}
} else if (node instanceof Comment) {
- node.value = node.sourceSpan
- .toString()
- .slice("<!--".length, -"-->".length);
+ node.value =
+ node.sourceSpan
+ .toString()
+ .slice("<!--".length, -"-->".length);
} else if (node instanceof Text) {
node.value = node.sourceSpan.toString();
}
diff --git ORI/prettier/src/language-html/print-preprocess.js ALT/prettier/src/language-html/print-preprocess.js
index 600947b77..25d831b9e 100644
--- ORI/prettier/src/language-html/print-preprocess.js
+++ ALT/prettier/src/language-html/print-preprocess.js
@@ -327,60 +327,61 @@ function extractWhitespaces(ast /*, options*/) {
return node.clone({
isWhitespaceSensitive,
isIndentationSensitive,
- children: node.children
- // extract whitespace nodes
- .reduce((newChildren, child) => {
- if (child.type !== "text" || isWhitespaceSensitive) {
- return [...newChildren, child];
- }
-
- const localChildren = [];
-
- const { leadingWhitespace, text, trailingWhitespace } =
- getLeadingAndTrailingHtmlWhitespace(child.value);
-
- if (leadingWhitespace) {
- localChildren.push({ type: TYPE_WHITESPACE });
- }
-
- if (text) {
- localChildren.push({
- type: "text",
- value: text,
- sourceSpan: new ParseSourceSpan(
- child.sourceSpan.start.moveBy(leadingWhitespace.length),
- child.sourceSpan.end.moveBy(-trailingWhitespace.length)
- ),
- });
- }
-
- if (trailingWhitespace) {
- localChildren.push({ type: TYPE_WHITESPACE });
- }
-
- return [...newChildren, ...localChildren];
- }, [])
- // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
- .reduce((newChildren, child, i, children) => {
- if (child.type === TYPE_WHITESPACE) {
- return newChildren;
- }
-
- const hasLeadingSpaces =
- i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
- const hasTrailingSpaces =
- i !== children.length - 1 &&
- children[i + 1].type === TYPE_WHITESPACE;
-
- return [
- ...newChildren,
- {
- ...child,
- hasLeadingSpaces,
- hasTrailingSpaces,
- },
- ];
- }, []),
+ children:
+ node.children
+ // extract whitespace nodes
+ .reduce((newChildren, child) => {
+ if (child.type !== "text" || isWhitespaceSensitive) {
+ return [...newChildren, child];
+ }
+
+ const localChildren = [];
+
+ const { leadingWhitespace, text, trailingWhitespace } =
+ getLeadingAndTrailingHtmlWhitespace(child.value);
+
+ if (leadingWhitespace) {
+ localChildren.push({ type: TYPE_WHITESPACE });
+ }
+
+ if (text) {
+ localChildren.push({
+ type: "text",
+ value: text,
+ sourceSpan: new ParseSourceSpan(
+ child.sourceSpan.start.moveBy(leadingWhitespace.length),
+ child.sourceSpan.end.moveBy(-trailingWhitespace.length)
+ ),
+ });
+ }
+
+ if (trailingWhitespace) {
+ localChildren.push({ type: TYPE_WHITESPACE });
+ }
+
+ return [...newChildren, ...localChildren];
+ }, [])
+ // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
+ .reduce((newChildren, child, i, children) => {
+ if (child.type === TYPE_WHITESPACE) {
+ return newChildren;
+ }
+
+ const hasLeadingSpaces =
+ i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
+ const hasTrailingSpaces =
+ i !== children.length - 1 &&
+ children[i + 1].type === TYPE_WHITESPACE;
+
+ return [
+ ...newChildren,
+ {
+ ...child,
+ hasLeadingSpaces,
+ hasTrailingSpaces,
+ },
+ ];
+ }, []),
});
});
}
@@ -439,28 +440,32 @@ function addIsSpaceSensitive(ast, options) {
}
return node.clone({
- children: node.children
- .map((child) => ({
- ...child,
- isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(child, options),
- isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(
- child,
- options
- ),
- }))
- .map((child, index, children) => ({
- ...child,
- isLeadingSpaceSensitive:
- index === 0
- ? child.isLeadingSpaceSensitive
- : children[index - 1].isTrailingSpaceSensitive &&
- child.isLeadingSpaceSensitive,
- isTrailingSpaceSensitive:
- index === children.length - 1
- ? child.isTrailingSpaceSensitive
- : children[index + 1].isLeadingSpaceSensitive &&
- child.isTrailingSpaceSensitive,
- })),
+ children:
+ node.children
+ .map((child) => ({
+ ...child,
+ isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(
+ child,
+ options
+ ),
+ isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(
+ child,
+ options
+ ),
+ }))
+ .map((child, index, children) => ({
+ ...child,
+ isLeadingSpaceSensitive:
+ index === 0
+ ? child.isLeadingSpaceSensitive
+ : children[index - 1].isTrailingSpaceSensitive &&
+ child.isLeadingSpaceSensitive,
+ isTrailingSpaceSensitive:
+ index === children.length - 1
+ ? child.isTrailingSpaceSensitive
+ : children[index + 1].isLeadingSpaceSensitive &&
+ child.isTrailingSpaceSensitive,
+ })),
});
});
}
diff --git ORI/prettier/src/language-html/syntax-attribute.js ALT/prettier/src/language-html/syntax-attribute.js
index 3180ae3b2..e37ba122d 100644
--- ORI/prettier/src/language-html/syntax-attribute.js
+++ ALT/prettier/src/language-html/syntax-attribute.js
@@ -30,9 +30,10 @@ function printImgSrcset(value) {
const urls = srcset.map((src) => src.url);
const maxUrlLength = getMax(urls.map((url) => url.length));
- const descriptors = srcset
- .map((src) => src[key])
- .map((descriptor) => (descriptor ? descriptor.toString() : ""));
+ const descriptors =
+ srcset
+ .map((src) => src[key])
+ .map((descriptor) => (descriptor ? descriptor.toString() : ""));
const descriptorLeftLengths = descriptors.map((descriptor) => {
const index = descriptor.indexOf(".");
return index === -1 ? descriptor.length : index;
diff --git ORI/prettier/src/language-js/embed/html.js ALT/prettier/src/language-js/embed/html.js
index cb2e41306..4e0b11d02 100644
--- ORI/prettier/src/language-js/embed/html.js
+++ ALT/prettier/src/language-js/embed/html.js
@@ -19,13 +19,14 @@ function format(path, print, textToDoc, options, { parser }) {
const composePlaceholder = (index) =>
`PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
- const text = node.quasis
- .map((quasi, index, quasis) =>
- index === quasis.length - 1
- ? quasi.value.cooked
- : quasi.value.cooked + composePlaceholder(index)
- )
- .join("");
+ const text =
+ node.quasis
+ .map((quasi, index, quasis) =>
+ index === quasis.length - 1
+ ? quasi.value.cooked
+ : quasi.value.cooked + composePlaceholder(index)
+ )
+ .join("");
const expressionDocs = printTemplateExpressions(path, print);
if (expressionDocs.length === 0 && text.trim().length === 0) {
diff --git ORI/prettier/src/language-js/print/member-chain.js ALT/prettier/src/language-js/print/member-chain.js
index b12c6c191..baf115b34 100644
--- ORI/prettier/src/language-js/print/member-chain.js
+++ ALT/prettier/src/language-js/print/member-chain.js
@@ -360,9 +360,10 @@ function printMemberChain(path, options, print) {
printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)),
];
- const callExpressions = printedNodes
- .map(({ node }) => node)
- .filter(isCallOrOptionalCallExpression);
+ const callExpressions =
+ printedNodes
+ .map(({ node }) => node)
+ .filter(isCallOrOptionalCallExpression);
function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
const lastGroupNode = getLast(getLast(groups)).node;
diff --git ORI/prettier/src/language-js/print/object.js ALT/prettier/src/language-js/print/object.js
index c8ff9dc45..b1c3d3223 100644
--- ORI/prettier/src/language-js/print/object.js
+++ ALT/prettier/src/language-js/print/object.js
@@ -110,24 +110,25 @@ function printObject(path, options, print) {
/** @type {Doc[]} */
let separatorParts = [];
- const props = propsAndLoc
- .sort((a, b) => a.loc - b.loc)
- .map((prop) => {
- const result = [...separatorParts, group(prop.printed)];
- separatorParts = [separator, line];
- if (
- (prop.node.type === "TSPropertySignature" ||
- prop.node.type === "TSMethodSignature" ||
- prop.node.type === "TSConstructSignatureDeclaration") &&
- hasComment(prop.node, CommentCheckFlags.PrettierIgnore)
- ) {
- separatorParts.shift();
- }
- if (isNextLineEmpty(prop.node, options)) {
- separatorParts.push(hardline);
- }
- return result;
- });
+ const props =
+ propsAndLoc
+ .sort((a, b) => a.loc - b.loc)
+ .map((prop) => {
+ const result = [...separatorParts, group(prop.printed)];
+ separatorParts = [separator, line];
+ if (
+ (prop.node.type === "TSPropertySignature" ||
+ prop.node.type === "TSMethodSignature" ||
+ prop.node.type === "TSConstructSignatureDeclaration") &&
+ hasComment(prop.node, CommentCheckFlags.PrettierIgnore)
+ ) {
+ separatorParts.shift();
+ }
+ if (isNextLineEmpty(prop.node, options)) {
+ separatorParts.push(hardline);
+ }
+ return result;
+ });
if (n.inexact) {
let printed;
diff --git ORI/prettier/src/language-js/printer-estree.js ALT/prettier/src/language-js/printer-estree.js
index a2fc6dbd5..df8ef9578 100644
--- ORI/prettier/src/language-js/printer-estree.js
+++ ALT/prettier/src/language-js/printer-estree.js
@@ -1034,9 +1034,10 @@ function printPathNoParens(path, options, print, args) {
const commentStartIndex = options.originalText.lastIndexOf("/*", start);
const commentEndIndex = options.originalText.indexOf("*/", end);
if (commentStartIndex !== -1 && commentEndIndex !== -1) {
- const comment = options.originalText
- .slice(commentStartIndex + 2, commentEndIndex)
- .trim();
+ const comment =
+ options.originalText
+ .slice(commentStartIndex + 2, commentEndIndex)
+ .trim();
if (
comment.startsWith("::") &&
!comment.includes("/*") &&
diff --git ORI/prettier/src/language-markdown/clean.js ALT/prettier/src/language-markdown/clean.js
index 869eef9dd..fffd2e578 100644
--- ORI/prettier/src/language-markdown/clean.js
+++ ALT/prettier/src/language-markdown/clean.js
@@ -43,10 +43,11 @@ function clean(ast, newObj, parent) {
}
if (ast.type === "definition" || ast.type === "linkReference") {
- newObj.label = ast.label
- .trim()
- .replace(/[\t\n ]+/g, " ")
- .toLowerCase();
+ newObj.label =
+ ast.label
+ .trim()
+ .replace(/[\t\n ]+/g, " ")
+ .toLowerCase();
}
if (
diff --git ORI/prettier/src/language-markdown/constants.evaluate.js ALT/prettier/src/language-markdown/constants.evaluate.js
index 45c799f9e..024d46b41 100644
--- ORI/prettier/src/language-markdown/constants.evaluate.js
+++ ALT/prettier/src/language-markdown/constants.evaluate.js
@@ -22,9 +22,10 @@ const cjkPattern = `(?:${cjkRegex()
Block: ["Variation_Selectors", "Variation_Selectors_Supplement"],
}).toString()})?`;
-const kPattern = unicodeRegex({ Script: ["Hangul"] })
- .union(unicodeRegex({ Script_Extensions: ["Hangul"] }))
- .toString();
+const kPattern =
+ unicodeRegex({ Script: ["Hangul"] })
+ .union(unicodeRegex({ Script_Extensions: ["Hangul"] }))
+ .toString();
// http://spec.commonmark.org/0.25/#ascii-punctuation-character
const asciiPunctuationCharset =
diff --git ORI/prettier/src/language-markdown/parser-markdown.js ALT/prettier/src/language-markdown/parser-markdown.js
index 494b77977..d7120cfbe 100644
--- ORI/prettier/src/language-markdown/parser-markdown.js
+++ ALT/prettier/src/language-markdown/parser-markdown.js
@@ -26,19 +26,20 @@ const mdx = require("./mdx");
*/
function createParse({ isMDX }) {
return (text) => {
- const processor = unified()
- .use(remarkParse, {
- commonmark: true,
- ...(isMDX && { blocks: [mdx.BLOCKS_REGEX] }),
- })
- .use(footnotes)
- .use(frontMatter)
- .use(remarkMath)
- .use(isMDX ? mdx.esSyntax : identity)
- .use(liquid)
- .use(isMDX ? htmlToJsx : identity)
- .use(wikiLink)
- .use(looseItems);
+ const processor =
+ unified()
+ .use(remarkParse, {
+ commonmark: true,
+ ...(isMDX && { blocks: [mdx.BLOCKS_REGEX] }),
+ })
+ .use(footnotes)
+ .use(frontMatter)
+ .use(remarkMath)
+ .use(isMDX ? mdx.esSyntax : identity)
+ .use(liquid)
+ .use(isMDX ? htmlToJsx : identity)
+ .use(wikiLink)
+ .use(looseItems);
return processor.runSync(processor.parse(text));
};
}
diff --git ORI/prettier/src/language-markdown/printer-markdown.js ALT/prettier/src/language-markdown/printer-markdown.js
index 179132dc2..34b6c2eb8 100644
--- ORI/prettier/src/language-markdown/printer-markdown.js
+++ ALT/prettier/src/language-markdown/printer-markdown.js
@@ -96,22 +96,23 @@ function genericPrint(path, options, print) {
case "sentence":
return printChildren(path, options, print);
case "word": {
- let escapedValue = node.value
- .replace(/\*/g, "\\$&") // escape all `*`
- .replace(
- new RegExp(
- [
- `(^|${punctuationPattern})(_+)`,
- `(_+)(${punctuationPattern}|$)`,
- ].join("|"),
- "g"
- ),
- (_, text1, underscore1, underscore2, text2) =>
- (underscore1
- ? `${text1}${underscore1}`
- : `${underscore2}${text2}`
- ).replace(/_/g, "\\_")
- ); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
+ let escapedValue =
+ node.value
+ .replace(/\*/g, "\\$&") // escape all `*`
+ .replace(
+ new RegExp(
+ [
+ `(^|${punctuationPattern})(_+)`,
+ `(_+)(${punctuationPattern}|$)`,
+ ].join("|"),
+ "g"
+ ),
+ (_, text1, underscore1, underscore2, text2) =>
+ (underscore1
+ ? `${text1}${underscore1}`
+ : `${underscore2}${text2}`
+ ).replace(/_/g, "\\_")
+ ); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
const isFirstSentence = (node, name, index) =>
node.type === "sentence" && index === 0;
diff --git ORI/prettier/src/language-markdown/utils.js ALT/prettier/src/language-markdown/utils.js
index 4b7d2608e..926ca0f06 100644
--- ORI/prettier/src/language-markdown/utils.js
+++ ALT/prettier/src/language-markdown/utils.js
@@ -153,12 +153,13 @@ function splitText(text, options) {
}
function getOrderedListItemInfo(orderListItem, originalText) {
- const [, numberText, marker, leadingSpaces] = originalText
- .slice(
- orderListItem.position.start.offset,
- orderListItem.position.end.offset
- )
- .match(/^\s*(\d+)(\.|\))(\s*)/);
+ const [, numberText, marker, leadingSpaces] =
+ originalText
+ .slice(
+ orderListItem.position.start.offset,
+ orderListItem.position.end.offset
+ )
+ .match(/^\s*(\d+)(\.|\))(\s*)/);
return { numberText, marker, leadingSpaces };
}
diff --git ORI/prettier/src/language-yaml/utils.js ALT/prettier/src/language-yaml/utils.js
index 2151c65bc..fef001f74 100644
--- ORI/prettier/src/language-yaml/utils.js
+++ ALT/prettier/src/language-yaml/utils.js
@@ -193,17 +193,18 @@ function splitWithSingleSpace(text) {
}
function getFlowScalarLineContents(nodeType, content, options) {
- const rawLineContents = content
- .split("\n")
- .map((lineContent, index, lineContents) =>
- index === 0 && index === lineContents.length - 1
- ? lineContent
- : index !== 0 && index !== lineContents.length - 1
- ? lineContent.trim()
- : index === 0
- ? lineContent.trimEnd()
- : lineContent.trimStart()
- );
+ const rawLineContents =
+ content
+ .split("\n")
+ .map((lineContent, index, lineContents) =>
+ index === 0 && index === lineContents.length - 1
+ ? lineContent
+ : index !== 0 && index !== lineContents.length - 1
+ ? lineContent.trim()
+ : index === 0
+ ? lineContent.trimEnd()
+ : lineContent.trimStart()
+ );
if (options.proseWrap === "preserve") {
return rawLineContents.map((lineContent) =>
@@ -260,9 +261,10 @@ function getBlockValueLineContents(
)
: node.indent - 1 + parentIndent;
- const rawLineContents = content
- .split("\n")
- .map((lineContent) => lineContent.slice(leadingSpaceCount));
+ const rawLineContents =
+ content
+ .split("\n")
+ .map((lineContent) => lineContent.slice(leadingSpaceCount));
if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
return removeUnnecessaryTrailingNewlines(
diff --git ORI/prettier/src/main/options.js ALT/prettier/src/main/options.js
index a12b5bcad..fbd13b464 100644
--- ORI/prettier/src/main/options.js
+++ ALT/prettier/src/main/options.js
@@ -68,19 +68,20 @@ function normalize(options, opts = {}) {
const plugin = getPlugin(rawOptions);
rawOptions.printer = plugin.printers[rawOptions.astFormat];
- const pluginDefaults = supportOptions
- .filter(
- (optionInfo) =>
- optionInfo.pluginDefaults &&
- optionInfo.pluginDefaults[plugin.name] !== undefined
- )
- .reduce(
- (reduced, optionInfo) =>
- Object.assign(reduced, {
- [optionInfo.name]: optionInfo.pluginDefaults[plugin.name],
- }),
- {}
- );
+ const pluginDefaults =
+ supportOptions
+ .filter(
+ (optionInfo) =>
+ optionInfo.pluginDefaults &&
+ optionInfo.pluginDefaults[plugin.name] !== undefined
+ )
+ .reduce(
+ (reduced, optionInfo) =>
+ Object.assign(reduced, {
+ [optionInfo.name]: optionInfo.pluginDefaults[plugin.name],
+ }),
+ {}
+ );
const mixedDefaults = { ...defaults, ...pluginDefaults };
diff --git ORI/prettier/src/main/support.js ALT/prettier/src/main/support.js
index a6aa0d83f..37c9b567c 100644
--- ORI/prettier/src/main/support.js
+++ ALT/prettier/src/main/support.js
@@ -29,54 +29,57 @@ function getSupportInfo({
// we need to treat it as the normal one so as to test new features.
const version = currentVersion.split("-", 1)[0];
- const languages = plugins
- .reduce((all, plugin) => [...all, ...(plugin.languages || [])], [])
- .filter(filterSince);
+ const languages =
+ plugins
+ .reduce((all, plugin) => [...all, ...(plugin.languages || [])], [])
+ .filter(filterSince);
- const options = arrayify(
- Object.assign({}, ...plugins.map(({ options }) => options), coreOptions),
- "name"
- )
- .filter((option) => filterSince(option) && filterDeprecated(option))
- .sort((a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1))
- .map(mapInternal)
- .map((option) => {
- option = { ...option };
+ const options =
+ arrayify(
+ Object.assign({}, ...plugins.map(({ options }) => options), coreOptions),
+ "name"
+ )
+ .filter((option) => filterSince(option) && filterDeprecated(option))
+ .sort((a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1))
+ .map(mapInternal)
+ .map((option) => {
+ option = { ...option };
- if (Array.isArray(option.default)) {
- option.default =
- option.default.length === 1
- ? option.default[0].value
- : option.default
- .filter(filterSince)
- .sort((info1, info2) =>
- semver.compare(info2.since, info1.since)
- )[0].value;
- }
+ if (Array.isArray(option.default)) {
+ option.default =
+ option.default.length === 1
+ ? option.default[0].value
+ : option.default
+ .filter(filterSince)
+ .sort((info1, info2) =>
+ semver.compare(info2.since, info1.since)
+ )[0].value;
+ }
- if (Array.isArray(option.choices)) {
- option.choices = option.choices.filter(
- (option) => filterSince(option) && filterDeprecated(option)
- );
+ if (Array.isArray(option.choices)) {
+ option.choices = option.choices.filter(
+ (option) => filterSince(option) && filterDeprecated(option)
+ );
- if (option.name === "parser") {
- collectParsersFromLanguages(option, languages, plugins);
+ if (option.name === "parser") {
+ collectParsersFromLanguages(option, languages, plugins);
+ }
}
- }
- const pluginDefaults = plugins
- .filter(
- (plugin) =>
- plugin.defaultOptions &&
- plugin.defaultOptions[option.name] !== undefined
- )
- .reduce((reduced, plugin) => {
- reduced[plugin.name] = plugin.defaultOptions[option.name];
- return reduced;
- }, {});
+ const pluginDefaults =
+ plugins
+ .filter(
+ (plugin) =>
+ plugin.defaultOptions &&
+ plugin.defaultOptions[option.name] !== undefined
+ )
+ .reduce((reduced, plugin) => {
+ reduced[plugin.name] = plugin.defaultOptions[option.name];
+ return reduced;
+ }, {});
- return { ...option, pluginDefaults };
- });
+ return { ...option, pluginDefaults };
+ });
return { languages, options };
diff --git ORI/prettier/tests/js/bom/jsfmt.spec.js ALT/prettier/tests/js/bom/jsfmt.spec.js
index 851064803..6501e2f16 100644
--- ORI/prettier/tests/js/bom/jsfmt.spec.js
+++ ALT/prettier/tests/js/bom/jsfmt.spec.js
@@ -2,18 +2,19 @@ const fs = require("fs");
const path = require("path");
const fixtureDirectory = path.join(__dirname, "../eol");
-const snippets = fs
- .readdirSync(fixtureDirectory)
- .filter(
- (fileName) => fileName !== "__snapshots__" && fileName !== "jsfmt.spec.js"
- )
- .map((fileName) => {
- const file = path.join(fixtureDirectory, fileName);
- const code = "\uFEFF" + fs.readFileSync(file, "utf8");
- return {
- name: fileName,
- code,
- };
- });
+const snippets =
+ fs
+ .readdirSync(fixtureDirectory)
+ .filter(
+ (fileName) => fileName !== "__snapshots__" && fileName !== "jsfmt.spec.js"
+ )
+ .map((fileName) => {
+ const file = path.join(fixtureDirectory, fileName);
+ const code = "\uFEFF" + fs.readFileSync(file, "utf8");
+ return {
+ name: fileName,
+ code,
+ };
+ });
run_spec({ dirname: __dirname, snippets }, ["babel"]);
diff --git ORI/prettier/tests/misc/empty/jsfmt.spec.js ALT/prettier/tests/misc/empty/jsfmt.spec.js
index 349f87d36..da6569e51 100644
--- ORI/prettier/tests/misc/empty/jsfmt.spec.js
+++ ALT/prettier/tests/misc/empty/jsfmt.spec.js
@@ -1,8 +1,9 @@
-const parsers = require("prettier-local")
- .getSupportInfo()
- .options.find((option) => option.name === "parser")
- .choices.filter((choice) => !choice.deprecated)
- .map((choice) => choice.value);
+const parsers =
+ require("prettier-local")
+ .getSupportInfo()
+ .options.find((option) => option.name === "parser")
+ .choices.filter((choice) => !choice.deprecated)
+ .map((choice) => choice.value);
run_spec(
{
diff --git ORI/prettier/tests_config/require_standalone.js ALT/prettier/tests_config/require_standalone.js
index 310dbb4b6..2be1957ee 100644
--- ORI/prettier/tests_config/require_standalone.js
+++ ALT/prettier/tests_config/require_standalone.js
@@ -6,13 +6,14 @@ const globby = require("globby");
const sandbox = vm.createContext();
-const source = globby
- .sync(["standalone.js", "parser-*.js"], {
- cwd: process.env.PRETTIER_DIR,
- absolute: true,
- })
- .map((file) => fs.readFileSync(file, "utf8"))
- .join(";");
+const source =
+ globby
+ .sync(["standalone.js", "parser-*.js"], {
+ cwd: process.env.PRETTIER_DIR,
+ absolute: true,
+ })
+ .map((file) => fs.readFileSync(file, "utf8"))
+ .join(";");
vm.runInContext(source, sandbox);
diff --git ORI/prettier/tests_config/run_spec.js ALT/prettier/tests_config/run_spec.js
index 8bb577930..03fce5bb5 100644
--- ORI/prettier/tests_config/run_spec.js
+++ ALT/prettier/tests_config/run_spec.js
@@ -118,29 +118,30 @@ function runSpec(fixtures, parsers, options) {
};
});
- const files = fs
- .readdirSync(dirname, { withFileTypes: true })
- .map((file) => {
- const basename = file.name;
- const filename = path.join(dirname, basename);
- if (
- path.extname(basename) === ".snap" ||
- !file.isFile() ||
- basename[0] === "." ||
- basename === "jsfmt.spec.js"
- ) {
- return;
- }
+ const files =
+ fs
+ .readdirSync(dirname, { withFileTypes: true })
+ .map((file) => {
+ const basename = file.name;
+ const filename = path.join(dirname, basename);
+ if (
+ path.extname(basename) === ".snap" ||
+ !file.isFile() ||
+ basename[0] === "." ||
+ basename === "jsfmt.spec.js"
+ ) {
+ return;
+ }
- const text = fs.readFileSync(filename, "utf8");
+ const text = fs.readFileSync(filename, "utf8");
- return {
- name: basename,
- filename,
- code: text,
- };
- })
- .filter(Boolean);
+ return {
+ name: basename,
+ filename,
+ code: text,
+ };
+ })
+ .filter(Boolean);
// Make sure tests are in correct location
if (process.env.CHECK_TEST_PARSERS) {
@@ -399,13 +400,14 @@ const indexProperties = [
},
];
function replacePlaceholders(originalText, originalOptions) {
- const indexes = indexProperties
- .map(({ property, placeholder }) => {
- const value = originalText.indexOf(placeholder);
- return value === -1 ? undefined : { property, value, placeholder };
- })
- .filter(Boolean)
- .sort((a, b) => a.value - b.value);
+ const indexes =
+ indexProperties
+ .map(({ property, placeholder }) => {
+ const value = originalText.indexOf(placeholder);
+ return value === -1 ? undefined : { property, value, placeholder };
+ })
+ .filter(Boolean)
+ .sort((a, b) => a.value - b.value);
const options = { ...originalOptions };
let text = originalText;
diff --git ORI/prettier/tests_integration/__tests__/bundle.js ALT/prettier/tests_integration/__tests__/bundle.js
index 1a2f85bab..b6c984c55 100644
--- ORI/prettier/tests_integration/__tests__/bundle.js
+++ ALT/prettier/tests_integration/__tests__/bundle.js
@@ -13,15 +13,17 @@ const distDirectory = path.join(projectRoot, "dist");
describe("standalone", () => {
const standalone = require(path.join(distDirectory, "standalone.js"));
- const plugins = globby
- .sync(["parser-*.js"], { cwd: distDirectory, absolute: true })
- .map((file) => require(file));
+ const plugins =
+ globby
+ .sync(["parser-*.js"], { cwd: distDirectory, absolute: true })
+ .map((file) => require(file));
const esmStandalone = require(path.join(distDirectory, "esm/standalone.mjs"))
.default;
- const esmPlugins = globby
- .sync(["esm/parser-*.mjs"], { cwd: distDirectory, absolute: true })
- .map((file) => require(file).default);
+ const esmPlugins =
+ globby
+ .sync(["esm/parser-*.mjs"], { cwd: distDirectory, absolute: true })
+ .map((file) => require(file).default);
for (const parser of parserNames) {
test(parser, () => {
diff --git ORI/prettier/website/blog/2020-08-24-2.1.0.md ALT/prettier/website/blog/2020-08-24-2.1.0.md
index 215b2102c..78474a301 100644
--- ORI/prettier/website/blog/2020-08-24-2.1.0.md
+++ ALT/prettier/website/blog/2020-08-24-2.1.0.md
@@ -2163,11 +2163,12 @@ npm install --save-dev --save-exact prettier @prettier/plugin-php
```
```js
-const hasPhpParser = prettier
- .getSupportInfo()
- .options.find((option) => option.name === "parser")
- .choices.map((choice) => choice.value)
- .includes("php"); // false in Prettier 2.0, true in Prettier 2.1
+const hasPhpParser =
+ prettier
+ .getSupportInfo()
+ .options.find((option) => option.name === "parser")
+ .choices.map((choice) => choice.value)
+ .includes("php"); // false in Prettier 2.0, true in Prettier 2.1
```
#### Fix `prettier.getFileInfo()` ([#8548](https://github.com/prettier/prettier/pull/8548), [#8551](https://github.com/prettier/prettier/pull/8551), [#8585](https://github.com/prettier/prettier/pull/8585) by [@fisker](https://github.com/fisker))
diff --git ORI/prettier/website/pages/en/index.js ALT/prettier/website/pages/en/index.js
index 0a212f30d..5cbe57622 100755
--- ORI/prettier/website/pages/en/index.js
+++ ALT/prettier/website/pages/en/index.js
@@ -239,13 +239,14 @@ const EditorSupportSection = () => (
);
const UsersSection = ({ language }) => {
- const showcase = siteConfig.users
- .filter((user) => user.pinned)
- .map((user, i) => (
- <a key={i} className="growOnHover alignCenter" href={user.infoLink}>
- <img className="user" src={user.greyImage} title={user.caption} />
- </a>
- ));
+ const showcase =
+ siteConfig.users
+ .filter((user) => user.pinned)
+ .map((user, i) => (
+ <a key={i} className="growOnHover alignCenter" href={user.infoLink}>
+ <img className="user" src={user.greyImage} title={user.caption} />
+ </a>
+ ));
return (
<div className="usersSection productShowcaseSection">
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts
index 096deaff..8d9d6de9 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts
@@ -592,9 +592,10 @@ export default util.createRule<Options, MessageIds>({
);
// import Type , {...} from 'foo'
// ^^^^^ pick
- const defaultText = sourceCode.text
- .slice(defaultSpecifier.range[0], commaToken.range[0])
- .trim();
+ const defaultText =
+ sourceCode.text
+ .slice(defaultSpecifier.range[0], commaToken.range[0])
+ .trim();
yield fixer.insertTextBefore(
node,
`import type ${defaultText} from ${sourceCode.getText(
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts
index 08d72181..c9d94183 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts
@@ -99,9 +99,10 @@ export default util.createRule<Options, MessageIds>({
util.isNotOptionalChainPunctuator,
)!;
- const textBetweenTokens = text
- .slice(lastCalleeToken.range[1], openingParenToken.range[0])
- .replace(/\/\*.*?\*\//gu, '');
+ const textBetweenTokens =
+ text
+ .slice(lastCalleeToken.range[1], openingParenToken.range[0])
+ .replace(/\/\*.*?\*\//gu, '');
const hasWhitespace = /\s/u.test(textBetweenTokens);
const hasNewline =
hasWhitespace && util.LINEBREAK_MATCHER.test(textBetweenTokens);
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts
index 4775a1fe..02a704b0 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts
@@ -154,13 +154,14 @@ export default util.createRule<Options, MessageIds>({
methodNode,
...duplicatedKeyMethodNodes,
].sort((a, b) => (a.range[0] < b.range[0] ? -1 : 1));
- const typeString = methodNodes
- .map(node => {
- const params = getMethodParams(node);
- const returnType = getMethodReturnType(node);
- return `(${params} => ${returnType})`;
- })
- .join(' & ');
+ const typeString =
+ methodNodes
+ .map(node => {
+ const params = getMethodParams(node);
+ const returnType = getMethodReturnType(node);
+ return `(${params} => ${returnType})`;
+ })
+ .join(' & ');
const key = getMethodKey(methodNode);
const delimiter = getDelimiter(methodNode);
yield fixer.replaceText(
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
index c4e6e36b..b0e1386f 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
@@ -80,9 +80,10 @@ function normalizeOption(option: Selector): NormalizedSelector[] {
}
function parseOptions(context: Context): ParsedOptions {
- const normalizedOptions = context.options
- .map(opt => normalizeOption(opt))
- .reduce((acc, val) => acc.concat(val), []);
+ const normalizedOptions =
+ context.options
+ .map(opt => normalizeOption(opt))
+ .reduce((acc, val) => acc.concat(val), []);
return util.getEnumNames(Selectors).reduce((acc, k) => {
acc[k] = createValidator(k, context, normalizedOptions);
return acc;
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts
index a683933d..0297f62c 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts
@@ -28,46 +28,47 @@ function createValidator(
): (node: TSESTree.Identifier | TSESTree.Literal) => void {
// make sure the "highest priority" configs are checked first
const selectorType = Selectors[type];
- const configs = allConfigs
- // gather all of the applicable selectors
- .filter(
- c =>
- (c.selector & selectorType) !== 0 ||
- c.selector === MetaSelectors.default,
- )
- .sort((a, b) => {
- if (a.selector === b.selector) {
- // in the event of the same selector, order by modifier weight
- // sort descending - the type modifiers are "more important"
- return b.modifierWeight - a.modifierWeight;
- }
+ const configs =
+ allConfigs
+ // gather all of the applicable selectors
+ .filter(
+ c =>
+ (c.selector & selectorType) !== 0 ||
+ c.selector === MetaSelectors.default,
+ )
+ .sort((a, b) => {
+ if (a.selector === b.selector) {
+ // in the event of the same selector, order by modifier weight
+ // sort descending - the type modifiers are "more important"
+ return b.modifierWeight - a.modifierWeight;
+ }
- const aIsMeta = isMetaSelector(a.selector);
- const bIsMeta = isMetaSelector(b.selector);
+ const aIsMeta = isMetaSelector(a.selector);
+ const bIsMeta = isMetaSelector(b.selector);
- // non-meta selectors should go ahead of meta selectors
- if (aIsMeta && !bIsMeta) {
- return 1;
- }
- if (!aIsMeta && bIsMeta) {
- return -1;
- }
+ // non-meta selectors should go ahead of meta selectors
+ if (aIsMeta && !bIsMeta) {
+ return 1;
+ }
+ if (!aIsMeta && bIsMeta) {
+ return -1;
+ }
- const aIsMethodOrProperty = isMethodOrPropertySelector(a.selector);
- const bIsMethodOrProperty = isMethodOrPropertySelector(b.selector);
+ const aIsMethodOrProperty = isMethodOrPropertySelector(a.selector);
+ const bIsMethodOrProperty = isMethodOrPropertySelector(b.selector);
- // for backward compatibility, method and property have higher precedence than other meta selectors
- if (aIsMethodOrProperty && !bIsMethodOrProperty) {
- return -1;
- }
- if (!aIsMethodOrProperty && bIsMethodOrProperty) {
- return 1;
- }
+ // for backward compatibility, method and property have higher precedence than other meta selectors
+ if (aIsMethodOrProperty && !bIsMethodOrProperty) {
+ return -1;
+ }
+ if (!aIsMethodOrProperty && bIsMethodOrProperty) {
+ return 1;
+ }
- // both aren't meta selectors
- // sort descending - the meta selectors are "least important"
- return b.selector - a.selector;
- });
+ // both aren't meta selectors
+ // sort descending - the meta selectors are "least important"
+ return b.selector - a.selector;
+ });
return (
node: TSESTree.Identifier | TSESTree.Literal,
@@ -429,10 +430,11 @@ function isCorrectType(
const { esTreeNodeToTSNodeMap, program } = util.getParserServices(context);
const checker = program.getTypeChecker();
const tsNode = esTreeNodeToTSNodeMap.get(node);
- const type = checker
- .getTypeAtLocation(tsNode)
- // remove null and undefined from the type, as we don't care about it here
- .getNonNullableType();
+ const type =
+ checker
+ .getTypeAtLocation(tsNode)
+ // remove null and undefined from the type, as we don't care about it here
+ .getNonNullableType();
for (const allowedType of config.types) {
switch (allowedType) {
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts
index 16e31b62..91c6dc0c 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts
@@ -96,9 +96,10 @@ export default util.createRule<Options, MessageIds>({
const validators = parseOptions(context);
// getParserServices(context, false) -- dirty hack to work around the docs checker test...
- const compilerOptions = util
- .getParserServices(context, true)
- .program.getCompilerOptions();
+ const compilerOptions =
+ util
+ .getParserServices(context, true)
+ .program.getCompilerOptions();
function handleMember(
validator: ValidatorFunction | null,
node:
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts
index 0dff489e..3ef3fcbb 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts
@@ -102,9 +102,10 @@ export default util.createRule<[Options], MessageIds>({
// check whitelist
if (Array.isArray(allowInGenericTypeArguments)) {
const sourceCode = context.getSourceCode();
- const fullyQualifiedName = sourceCode
- .getText(node.parent.parent.typeName)
- .replace(/ /gu, '');
+ const fullyQualifiedName =
+ sourceCode
+ .getText(node.parent.parent.typeName)
+ .replace(/ /gu, '');
if (
!allowInGenericTypeArguments
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts
index 44d0178e..99153caa 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts
@@ -49,9 +49,10 @@ export default util.createRule<Options, MessageIds>({
}
const references = context.getScope().through;
- const unsafeRefs = references
- .filter(r => !isSafe(loopNode, r))
- .map(r => r.identifier.name);
+ const unsafeRefs =
+ references
+ .filter(r => !isSafe(loopNode, r))
+ .map(r => r.identifier.name);
if (unsafeRefs.length > 0) {
context.report({
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts
index 21456319..d6d58ade 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts
@@ -101,15 +101,16 @@ export default util.createRule<Options, MessageIds>({
}
}
- const identifiers = variable.identifiers
- .map(id => ({
- identifier: id,
- parent: id.parent!,
- }))
- // ignore function declarations because TS will treat them as an overload
- .filter(
- ({ parent }) => parent.type !== AST_NODE_TYPES.TSDeclareFunction,
- );
+ const identifiers =
+ variable.identifiers
+ .map(id => ({
+ identifier: id,
+ parent: id.parent!,
+ }))
+ // ignore function declarations because TS will treat them as an overload
+ .filter(
+ ({ parent }) => parent.type !== AST_NODE_TYPES.TSDeclareFunction,
+ );
if (options.ignoreDeclarationMerge && identifiers.length > 1) {
if (
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts
index d21b088d..cc5a0136 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts
@@ -146,9 +146,10 @@ export default createRule({
// Get the symbol of `indexOf` method.
const tsNode = services.esTreeNodeToTSNodeMap.get(node.property);
- const indexofMethodDeclarations = types
- .getSymbolAtLocation(tsNode)
- ?.getDeclarations();
+ const indexofMethodDeclarations =
+ types
+ .getSymbolAtLocation(tsNode)
+ ?.getDeclarations();
if (
indexofMethodDeclarations == null ||
indexofMethodDeclarations.length === 0
@@ -161,9 +162,10 @@ export default createRule({
for (const instanceofMethodDecl of indexofMethodDeclarations) {
const typeDecl = instanceofMethodDecl.parent;
const type = types.getTypeAtLocation(typeDecl);
- const includesMethodDecl = type
- .getProperty('includes')
- ?.getDeclarations();
+ const includesMethodDecl =
+ type
+ .getProperty('includes')
+ ?.getDeclarations();
if (
includesMethodDecl == null ||
!includesMethodDecl.some(includesMethodDecl =>
@@ -204,9 +206,10 @@ export default createRule({
const tsNode = services.esTreeNodeToTSNodeMap.get(argument);
const type = getConstrainedTypeAtLocation(types, tsNode);
- const includesMethodDecl = type
- .getProperty('includes')
- ?.getDeclarations();
+ const includesMethodDecl =
+ type
+ .getProperty('includes')
+ ?.getDeclarations();
if (includesMethodDecl == null) {
return;
}
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts
index 00888c8f..1bcb2f96 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts
@@ -99,9 +99,10 @@ export default util.createRule<Options, MessageIds>({
| TSESTree.FunctionExpression,
): void {
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
- const signatures = checker
- .getTypeAtLocation(originalNode)
- .getCallSignatures();
+ const signatures =
+ checker
+ .getTypeAtLocation(originalNode)
+ .getCallSignatures();
if (!signatures.length) {
return;
}
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts
index ff4a4d1a..e738a517 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts
@@ -210,11 +210,14 @@ export default util.createRule<Options, MessageIds>({
}
const fix: TSESLint.ReportFixFunction = fixer => {
- const sorted = expectedOrder
- .map(t => t.text)
- .join(
- node.type === AST_NODE_TYPES.TSIntersectionType ? ' & ' : ' | ',
- );
+ const sorted =
+ expectedOrder
+ .map(t => t.text)
+ .join(
+ node.type === AST_NODE_TYPES.TSIntersectionType
+ ? ' & '
+ : ' | ',
+ );
return fixer.replaceText(node, sorted);
};
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
index 8881473d..99d911d8 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
@@ -88,9 +88,10 @@ export default createRule({
);
}
- const fixString = missingCases
- .map(code => `${caseIndent}${code}`)
- .join('\n');
+ const fixString =
+ missingCases
+ .map(code => `${caseIndent}${code}`)
+ .join('\n');
if (lastCase) {
return fixer.insertTextAfter(lastCase, `\n${fixString}`);
@@ -141,13 +142,14 @@ export default createRule({
node: node.discriminant,
messageId: 'switchIsNotExhaustive',
data: {
- missingBranches: missingBranchTypes
- .map(missingType =>
- isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike)
- ? `typeof ${missingType.getSymbol()?.escapedName}`
- : checker.typeToString(missingType),
- )
- .join(' | '),
+ missingBranches:
+ missingBranchTypes
+ .map(missingType =>
+ isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike)
+ ? `typeof ${missingType.getSymbol()?.escapedName}`
+ : checker.typeToString(missingType),
+ )
+ .join(' | '),
},
suggest: [
{
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts
index 407d04c1..ffacd370 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts
@@ -81,23 +81,24 @@ const SUPPORTED_GLOBALS = [
'JSON',
'Intl',
] as const;
-const nativelyBoundMembers = SUPPORTED_GLOBALS.map(namespace => {
- if (!(namespace in global)) {
- // node.js might not have namespaces like Intl depending on compilation options
- // https://nodejs.org/api/intl.html#intl_options_for_building_node_js
- return [];
- }
- const object = global[namespace];
- return Object.getOwnPropertyNames(object)
- .filter(
- name =>
- !name.startsWith('_') &&
- typeof (object as Record<string, unknown>)[name] === 'function',
- )
- .map(name => `${namespace}.${name}`);
-})
- .reduce((arr, names) => arr.concat(names), [])
- .filter(name => !nativelyNotBoundMembers.has(name));
+const nativelyBoundMembers =
+ SUPPORTED_GLOBALS.map(namespace => {
+ if (!(namespace in global)) {
+ // node.js might not have namespaces like Intl depending on compilation options
+ // https://nodejs.org/api/intl.html#intl_options_for_building_node_js
+ return [];
+ }
+ const object = global[namespace];
+ return Object.getOwnPropertyNames(object)
+ .filter(
+ name =>
+ !name.startsWith('_') &&
+ typeof (object as Record<string, unknown>)[name] === 'function',
+ )
+ .map(name => `${namespace}.${name}`);
+ })
+ .reduce((arr, names) => arr.concat(names), [])
+ .filter(name => !nativelyNotBoundMembers.has(name));
const isNotImported = (
symbol: ts.Symbol,
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts ALT/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts
index 5e2f1054..4b4a25b2 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts
@@ -13,9 +13,10 @@ export function getTypeOfPropertyOfName(
// Symbolic names may differ in their escaped name compared to their human-readable name
// https://github.com/typescript-eslint/typescript-eslint/issues/2143
- const escapedProperty = type
- .getProperties()
- .find(property => property.escapedName === escapedName);
+ const escapedProperty =
+ type
+ .getProperties()
+ .find(property => property.escapedName === escapedName);
return escapedProperty
? checker.getDeclaredTypeOfSymbol(escapedProperty)
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts
index f8fc068a..ed879e52 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts
@@ -2,17 +2,18 @@ import rules from '../src/rules';
import plugin from '../src/index';
const RULE_NAME_PREFIX = '@typescript-eslint/';
-const EXTENSION_RULES = Object.entries(rules)
- .filter(([, rule]) => rule.meta.docs?.extendsBaseRule)
- .map(
- ([ruleName, rule]) =>
- [
- `${RULE_NAME_PREFIX}${ruleName}`,
- typeof rule.meta.docs?.extendsBaseRule === 'string'
- ? rule.meta.docs.extendsBaseRule
- : ruleName,
- ] as const,
- );
+const EXTENSION_RULES =
+ Object.entries(rules)
+ .filter(([, rule]) => rule.meta.docs?.extendsBaseRule)
+ .map(
+ ([ruleName, rule]) =>
+ [
+ `${RULE_NAME_PREFIX}${ruleName}`,
+ typeof rule.meta.docs?.extendsBaseRule === 'string'
+ ? rule.meta.docs.extendsBaseRule
+ : ruleName,
+ ] as const,
+ );
function entriesToObject<T = unknown>(value: [string, T][]): Record<string, T> {
return value.reduce<Record<string, T>>((accum, [k, v]) => {
@@ -49,9 +50,13 @@ describe('all.json config', () => {
plugin.configs.all.rules;
const configRules = filterRules(unfilteredConfigRules);
// note: exclude deprecated rules, this config is allowed to change between minor versions
- const ruleConfigs = Object.entries(rules)
- .filter(([, rule]) => !rule.meta.deprecated)
- .map<[string, string]>(([name]) => [`${RULE_NAME_PREFIX}${name}`, 'error']);
+ const ruleConfigs =
+ Object.entries(rules)
+ .filter(([, rule]) => !rule.meta.deprecated)
+ .map<[string, string]>(([name]) => [
+ `${RULE_NAME_PREFIX}${name}`,
+ 'error',
+ ]);
it('contains all of the rules, excluding the deprecated ones', () => {
expect(entriesToObject(ruleConfigs)).toEqual(entriesToObject(configRules));
@@ -65,16 +70,17 @@ describe('recommended.json config', () => {
plugin.configs.recommended.rules;
const configRules = filterRules(unfilteredConfigRules);
// note: include deprecated rules so that the config doesn't change between major bumps
- const ruleConfigs = Object.entries(rules)
- .filter(
- ([, rule]) =>
- rule.meta.docs?.recommended !== false &&
- rule.meta.docs?.requiresTypeChecking !== true,
- )
- .map<[string, string]>(([name, rule]) => [
- `${RULE_NAME_PREFIX}${name}`,
- rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
- ]);
+ const ruleConfigs =
+ Object.entries(rules)
+ .filter(
+ ([, rule]) =>
+ rule.meta.docs?.recommended !== false &&
+ rule.meta.docs?.requiresTypeChecking !== true,
+ )
+ .map<[string, string]>(([name, rule]) => [
+ `${RULE_NAME_PREFIX}${name}`,
+ rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
+ ]);
it("contains all recommended rules that don't require typechecking, excluding the deprecated ones", () => {
expect(entriesToObject(ruleConfigs)).toEqual(entriesToObject(configRules));
@@ -88,16 +94,17 @@ describe('recommended-requiring-type-checking.json config', () => {
plugin.configs['recommended-requiring-type-checking'].rules;
const configRules = filterRules(unfilteredConfigRules);
// note: include deprecated rules so that the config doesn't change between major bumps
- const ruleConfigs = Object.entries(rules)
- .filter(
- ([, rule]) =>
- rule.meta.docs?.recommended !== false &&
- rule.meta.docs?.requiresTypeChecking === true,
- )
- .map<[string, string]>(([name, rule]) => [
- `${RULE_NAME_PREFIX}${name}`,
- rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
- ]);
+ const ruleConfigs =
+ Object.entries(rules)
+ .filter(
+ ([, rule]) =>
+ rule.meta.docs?.recommended !== false &&
+ rule.meta.docs?.requiresTypeChecking === true,
+ )
+ .map<[string, string]>(([name, rule]) => [
+ `${RULE_NAME_PREFIX}${name}`,
+ rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
+ ]);
it('contains all recommended rules that require type checking, excluding the deprecated ones', () => {
expect(entriesToObject(ruleConfigs)).toEqual(entriesToObject(configRules));
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts
index d67ff887..230e312b 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts
@@ -41,13 +41,15 @@ function parseReadme(): {
describe('Validating rule docs', () => {
it('All rules must have a corresponding rule doc', () => {
- const files = fs
- .readdirSync(docsRoot)
- // this rule doc was left behind on purpose for legacy reasons
- .filter(rule => rule !== 'camelcase.md');
- const ruleFiles = Object.keys(rules)
- .map(rule => `${rule}.md`)
- .sort();
+ const files =
+ fs
+ .readdirSync(docsRoot)
+ // this rule doc was left behind on purpose for legacy reasons
+ .filter(rule => rule !== 'camelcase.md');
+ const ruleFiles =
+ Object.keys(rules)
+ .map(rule => `${rule}.md`)
+ .sort();
expect(files.sort()).toEqual(ruleFiles);
});
@@ -115,20 +117,22 @@ describe('Validating README.md', () => {
);
it('All non-deprecated base rules should have a row in the base rules table, and the table should be ordered alphabetically', () => {
- const baseRuleNames = baseRules
- .map(([ruleName]) => ruleName)
- .sort()
- .map(createRuleLink);
+ const baseRuleNames =
+ baseRules
+ .map(([ruleName]) => ruleName)
+ .sort()
+ .map(createRuleLink);
expect(rulesTables.base.cells.map(row => row[0])).toStrictEqual(
baseRuleNames,
);
});
it('All non-deprecated extension rules should have a row in the base rules table, and the table should be ordered alphabetically', () => {
- const extensionRuleNames = extensionRules
- .map(([ruleName]) => ruleName)
- .sort()
- .map(createRuleLink);
+ const extensionRuleNames =
+ extensionRules
+ .map(([ruleName]) => ruleName)
+ .sort()
+ .map(createRuleLink);
expect(rulesTables.extension.cells.map(row => row[0])).toStrictEqual(
extensionRuleNames,
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/index.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/index.test.ts
index 3cac8304..6ca70b85 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/index.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/index.test.ts
@@ -8,10 +8,13 @@ describe('eslint-plugin ("./src/index.ts")', () => {
const ruleKeys = Object.keys(rules);
const eslintPluginRuleKeys = Object.keys(eslintPlugin.rules);
- const configs = fs
- .readdirSync('./src/configs')
- .filter(file => ['.json', '.ts'].includes(path.extname(file).toLowerCase()))
- .map(file => path.basename(file, path.extname(file)));
+ const configs =
+ fs
+ .readdirSync('./src/configs')
+ .filter(file =>
+ ['.json', '.ts'].includes(path.extname(file).toLowerCase()),
+ )
+ .map(file => path.basename(file, path.extname(file)));
const eslintPluginConfigKeys = Object.keys(eslintPlugin.configs);
it('exports all available rules', () => {
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts
index 8296bf19..22d15332 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts
@@ -640,30 +640,31 @@ type Foo = string | {
// test the fixer by removing all the spaces
code: code.replace(new RegExp(indent, 'g'), ''),
output: code,
- errors: code
- .split('\n')
- .map<TSESLint.TestCaseError<MessageIds> | null>((line, lineNum) => {
- const indentCount = line.split(indent).length - 1;
- const spaceCount = indentCount * indent.length;
+ errors:
+ code
+ .split('\n')
+ .map<TSESLint.TestCaseError<MessageIds> | null>((line, lineNum) => {
+ const indentCount = line.split(indent).length - 1;
+ const spaceCount = indentCount * indent.length;
- if (indentCount < 1) {
- return null;
- }
+ if (indentCount < 1) {
+ return null;
+ }
- return {
- messageId: 'wrongIndentation',
- data: {
- expected: `${spaceCount} spaces`,
- actual: 0,
- },
- line: lineNum + 1,
- column: 1,
- };
- })
- .filter(
- (error): error is TSESLint.TestCaseError<MessageIds> =>
- error !== null,
- ),
+ return {
+ messageId: 'wrongIndentation',
+ data: {
+ expected: `${spaceCount} spaces`,
+ actual: 0,
+ },
+ line: lineNum + 1,
+ column: 1,
+ };
+ })
+ .filter(
+ (error): error is TSESLint.TestCaseError<MessageIds> =>
+ error !== null,
+ ),
};
if (invalid.errors.length > 0) {
invalidCases.push(invalid);
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts
index badfbc1c..cd868ac7 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts
@@ -19,13 +19,15 @@ type MessageIds = InferMessageIdsTypeFromRule<typeof rule>;
export function unIndent(strings: TemplateStringsArray): string {
const WHITESPACE_REGEX = / */u;
const templateValue = strings[0];
- const lines = templateValue
- .replace(/^\n/u, '')
- .replace(/\n\s*$/u, '')
- .split('\n');
- const lineIndents = lines
- .filter(line => line.trim())
- .map(line => WHITESPACE_REGEX.exec(line)![0].length);
+ const lines =
+ templateValue
+ .replace(/^\n/u, '')
+ .replace(/\n\s*$/u, '')
+ .split('\n');
+ const lineIndents =
+ lines
+ .filter(line => line.trim())
+ .map(line => WHITESPACE_REGEX.exec(line)![0].length);
const minLineIndent = Math.min(...lineIndents);
return lines.map(line => line.slice(minLineIndent)).join('\n');
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts
index c9160c05..1139ce3e 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts
@@ -4,9 +4,10 @@ import rules from '../../src/rules';
describe('./src/rules/index.ts', () => {
const ruleNames = Object.keys(rules).map(name => `${name}.ts`);
- const files = fs
- .readdirSync('./src/rules')
- .filter(file => file !== 'index.ts' && file.endsWith('.ts'));
+ const files =
+ fs
+ .readdirSync('./src/rules')
+ .filter(file => file !== 'index.ts' && file.endsWith('.ts'));
it('imports all available rule modules', () => {
expect(ruleNames).toEqual(expect.arrayContaining(files));
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts
index 9278420a..59ac6ffc 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts
@@ -269,10 +269,11 @@ ruleTester.run('prefer-readonly-parameter-types', rule, {
invalid: [
// arrays
...arrays.map<TSESLint.InvalidTestCase<MessageIds, Options>>(baseType => {
- const type = baseType
- .replace(/readonly /g, '')
- .replace(/Readonly<(.+?)>/g, '$1')
- .replace(/ReadonlyArray/g, 'Array');
+ const type =
+ baseType
+ .replace(/readonly /g, '')
+ .replace(/Readonly<(.+?)>/g, '$1')
+ .replace(/ReadonlyArray/g, 'Array');
return {
code: `function foo(arg: ${type}) {}`,
errors: [
diff --git ORI/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts ALT/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts
index ed84f286..1f6698f3 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts
@@ -161,16 +161,17 @@ console.log();
console.log(
'------------------------------ recommended.ts (should not require program) ------------------------------',
);
-const recommendedRules = ruleEntries
- .filter(entry => !!entry[1].meta.docs?.recommended)
- .reduce<LinterConfigRules>(
- (config, entry) =>
- reducer(config, entry, {
- filterDeprecated: false,
- filterRequiresTypeChecking: 'exclude',
- }),
- {},
- );
+const recommendedRules =
+ ruleEntries
+ .filter(entry => !!entry[1].meta.docs?.recommended)
+ .reduce<LinterConfigRules>(
+ (config, entry) =>
+ reducer(config, entry, {
+ filterDeprecated: false,
+ filterRequiresTypeChecking: 'exclude',
+ }),
+ {},
+ );
const recommendedConfig: LinterConfig = {
extends: EXTENDS,
rules: recommendedRules,
@@ -184,16 +185,17 @@ console.log();
console.log(
'--------------------------------- recommended-requiring-type-checking.ts ---------------------------------',
);
-const recommendedRulesRequiringProgram = ruleEntries
- .filter(entry => !!entry[1].meta.docs?.recommended)
- .reduce<LinterConfigRules>(
- (config, entry) =>
- reducer(config, entry, {
- filterDeprecated: false,
- filterRequiresTypeChecking: 'include',
- }),
- {},
- );
+const recommendedRulesRequiringProgram =
+ ruleEntries
+ .filter(entry => !!entry[1].meta.docs?.recommended)
+ .reduce<LinterConfigRules>(
+ (config, entry) =>
+ reducer(config, entry, {
+ filterDeprecated: false,
+ filterRequiresTypeChecking: 'include',
+ }),
+ {},
+ );
const recommendedRequiringTypeCheckingConfig: LinterConfig = {
extends: EXTENDS,
rules: recommendedRulesRequiringProgram,
diff --git ORI/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts ALT/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts
index cffe4006..809c9248 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts
@@ -105,16 +105,17 @@ const updateRulesList = (
].join('\n');
};
-const rulesDetails: RuleDetails[] = Object.entries(rules)
- .filter(([, rule]) => rule.meta.deprecated !== true)
- .map(([name, rule]) => ({
- name,
- description: rule.meta.docs?.description ?? '',
- recommended: !!rule.meta.docs?.recommended ?? false,
- fixable: !!rule.meta.fixable,
- requiresTypeChecking: rule.meta.docs?.requiresTypeChecking ?? false,
- extendsBaseRule: !!rule.meta.docs?.extendsBaseRule ?? false,
- }));
+const rulesDetails: RuleDetails[] =
+ Object.entries(rules)
+ .filter(([, rule]) => rule.meta.deprecated !== true)
+ .map(([name, rule]) => ({
+ name,
+ description: rule.meta.docs?.description ?? '',
+ recommended: !!rule.meta.docs?.recommended ?? false,
+ fixable: !!rule.meta.fixable,
+ requiresTypeChecking: rule.meta.docs?.requiresTypeChecking ?? false,
+ extendsBaseRule: !!rule.meta.docs?.extendsBaseRule ?? false,
+ }));
const baseRules = rulesDetails.filter(rule => !rule.extendsBaseRule);
const extensionRules = rulesDetails.filter(rule => rule.extendsBaseRule);
diff --git ORI/typescript-eslint/packages/parser/src/parser.ts ALT/typescript-eslint/packages/parser/src/parser.ts
index f304a837..cd6fd0d1 100644
--- ORI/typescript-eslint/packages/parser/src/parser.ts
+++ ALT/typescript-eslint/packages/parser/src/parser.ts
@@ -154,9 +154,10 @@ function parseForESLint(
compilerOptions.jsxFragmentFactory != null
) {
// in case the user has specified something like "preact.Fragment"
- const fragFactory = compilerOptions.jsxFragmentFactory
- .split('.')[0]
- .trim();
+ const fragFactory =
+ compilerOptions.jsxFragmentFactory
+ .split('.')[0]
+ .trim();
analyzeOptions.jsxFragmentName = fragFactory;
log(
'Resolved jsxFragmentName from program: %s',
diff --git ORI/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts ALT/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts
index 5255ed02..5f5a2295 100644
--- ORI/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts
+++ ALT/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts
@@ -12,24 +12,25 @@ const ONLY = [].join(path.sep);
const FIXTURES_DIR = path.resolve(__dirname, 'fixtures');
-const fixtures = glob
- .sync(`${FIXTURES_DIR}/**/*.{js,ts,jsx,tsx}`, {
- ignore: ['fixtures.test.ts'],
- })
- .map(absolute => {
- const relative = path.relative(FIXTURES_DIR, absolute);
- const { name, dir, ext } = path.parse(relative);
- const segments = dir.split(path.sep);
- const snapshotPath = path.join(FIXTURES_DIR, dir);
- return {
- absolute,
- name,
- ext,
- segments,
- snapshotPath,
- snapshotFile: path.join(snapshotPath, `${name}${ext}.shot`),
- };
- });
+const fixtures =
+ glob
+ .sync(`${FIXTURES_DIR}/**/*.{js,ts,jsx,tsx}`, {
+ ignore: ['fixtures.test.ts'],
+ })
+ .map(absolute => {
+ const relative = path.relative(FIXTURES_DIR, absolute);
+ const { name, dir, ext } = path.parse(relative);
+ const segments = dir.split(path.sep);
+ const snapshotPath = path.join(FIXTURES_DIR, dir);
+ return {
+ absolute,
+ name,
+ ext,
+ segments,
+ snapshotPath,
+ snapshotFile: path.join(snapshotPath, `${name}${ext}.shot`),
+ };
+ });
const FOUR_SLASH = /^\/\/\/\/[ ]+@(\w+)[ ]*=[ ]*(.+)$/;
const QUOTED_STRING = /^["'](.+?)['"]$/;
diff --git ORI/typescript-eslint/packages/typescript-estree/src/convert.ts ALT/typescript-eslint/packages/typescript-estree/src/convert.ts
index f5a6a230..8c0ecfc7 100644
--- ORI/typescript-eslint/packages/typescript-estree/src/convert.ts
+++ ALT/typescript-eslint/packages/typescript-estree/src/convert.ts
@@ -1953,12 +1953,13 @@ export class Converter {
case SyntaxKind.BigIntLiteral: {
const range = getRange(node, this.ast);
const rawValue = this.ast.text.slice(range[0], range[1]);
- const bigint = rawValue
- // remove suffix `n`
- .slice(0, -1)
- // `BigInt` doesn't accept numeric separator
- // and `bigint` property should not include numeric separator
- .replace(/_/g, '');
+ const bigint =
+ rawValue
+ // remove suffix `n`
+ .slice(0, -1)
+ // `BigInt` doesn't accept numeric separator
+ // and `bigint` property should not include numeric separator
+ .replace(/_/g, '');
const value = typeof BigInt !== 'undefined' ? BigInt(bigint) : null;
return this.createNode<TSESTree.BigIntLiteral>(node, {
type: AST_NODE_TYPES.Literal,
diff --git ORI/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts ALT/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts
index a3f007a0..599cfeed 100644
--- ORI/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts
+++ ALT/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts
@@ -289,12 +289,14 @@ function createWatchProgram(
// ensure process doesn't emit programs
watchCompilerHost.afterProgramCreate = (program): void => {
// report error if there are any errors in the config file
- const configFileDiagnostics = program
- .getConfigFileParsingDiagnostics()
- .filter(
- diag =>
- diag.category === ts.DiagnosticCategory.Error && diag.code !== 18003,
- );
+ const configFileDiagnostics =
+ program
+ .getConfigFileParsingDiagnostics()
+ .filter(
+ diag =>
+ diag.category === ts.DiagnosticCategory.Error &&
+ diag.code !== 18003,
+ );
if (configFileDiagnostics.length > 0) {
diagnosticReporter(configFileDiagnostics[0]);
}
diff --git ORI/typescript-eslint/packages/typescript-estree/src/parser.ts ALT/typescript-eslint/packages/typescript-estree/src/parser.ts
index dd765eb5..4e118007 100644
--- ORI/typescript-eslint/packages/typescript-estree/src/parser.ts
+++ ALT/typescript-eslint/packages/typescript-estree/src/parser.ts
@@ -264,17 +264,16 @@ function applyParserOptionsToExtra(options: TSESTreeOptions): void {
// NOTE - ensureAbsolutePath relies upon having the correct tsconfigRootDir in extra
extra.filePath = ensureAbsolutePath(extra.filePath, extra);
- const projectFolderIgnoreList = (
- options.projectFolderIgnoreList ?? ['**/node_modules/**']
- )
- .reduce<string[]>((acc, folder) => {
- if (typeof folder === 'string') {
- acc.push(folder);
- }
- return acc;
- }, [])
- // prefix with a ! for not match glob
- .map(folder => (folder.startsWith('!') ? folder : `!${folder}`));
+ const projectFolderIgnoreList =
+ (options.projectFolderIgnoreList ?? ['**/node_modules/**'])
+ .reduce<string[]>((acc, folder) => {
+ if (typeof folder === 'string') {
+ acc.push(folder);
+ }
+ return acc;
+ }, [])
+ // prefix with a ! for not match glob
+ .map(folder => (folder.startsWith('!') ? folder : `!${folder}`));
// NOTE - prepareAndTransformProjects relies upon having the correct tsconfigRootDir in extra
extra.projects = prepareAndTransformProjects(
options.project,
diff --git ORI/typescript-eslint/tools/generate-contributors.ts ALT/typescript-eslint/tools/generate-contributors.ts
index 6bb908b3..fb6dc4df 100644
--- ORI/typescript-eslint/tools/generate-contributors.ts
+++ ALT/typescript-eslint/tools/generate-contributors.ts
@@ -83,19 +83,20 @@ async function main(): Promise<void> {
}),
);
- const contributors = users
- // remove ignored users
- .filter(u => !IGNORED_USERS.has(u.login))
- // fetch the in-depth information for each user
- .map<AllContributorsUser>(usr => {
- return {
- login: usr.login,
- name: usr.name || usr.login,
- avatar_url: usr.avatar_url,
- profile: usr.html_url,
- contributions: [],
- };
- });
+ const contributors =
+ users
+ // remove ignored users
+ .filter(u => !IGNORED_USERS.has(u.login))
+ // fetch the in-depth information for each user
+ .map<AllContributorsUser>(usr => {
+ return {
+ login: usr.login,
+ name: usr.name || usr.login,
+ avatar_url: usr.avatar_url,
+ profile: usr.html_url,
+ contributions: [],
+ };
+ });
// build + write the .all-contributorsrc
const allContributorsConfig = {
from prettier-regression-testing.
run #10297
from prettier-regression-testing.
prettier/prettier#10297 VS prettier/prettier@main
- babel/babel@b63be94
- vuejs/eslint-plugin-vue@cc9c140
- excalidraw/excalidraw@1973ae9
- prettier/prettier@2c1b8f6
- typescript-eslint/typescript-eslint@7b701a3
- vega/vega-lite@e89e9e6
Diff (3915 lines)
diff --git ORI/babel/packages/babel-cli/test/index.js ALT/babel/packages/babel-cli/test/index.js
index 7cedb49e3..bd2f64c1b 100644
--- ORI/babel/packages/babel-cli/test/index.js
+++ ALT/babel/packages/babel-cli/test/index.js
@@ -52,19 +52,21 @@ const saveInFiles = function (files) {
};
const normalizeOutput = function (str, cwd) {
- let result = str
- .replace(/\(\d+ms\)/g, "(123ms)")
- .replace(new RegExp(escapeRegExp(cwd), "g"), "<CWD>")
- // (non-win32) /foo/babel/packages -> <CWD>/packages
- // (win32) C:\foo\babel\packages -> <CWD>\packages
- .replace(new RegExp(escapeRegExp(rootDir), "g"), "<ROOTDIR>");
+ let result =
+ str
+ .replace(/\(\d+ms\)/g, "(123ms)")
+ .replace(new RegExp(escapeRegExp(cwd), "g"), "<CWD>")
+ // (non-win32) /foo/babel/packages -> <CWD>/packages
+ // (win32) C:\foo\babel\packages -> <CWD>\packages
+ .replace(new RegExp(escapeRegExp(rootDir), "g"), "<ROOTDIR>");
if (process.platform === "win32") {
- result = result
- // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
- .replace(
- new RegExp(escapeRegExp(rootDir.replace(/\\/g, "\\\\")), "g"),
- "<ROOTDIR>",
- );
+ result =
+ result
+ // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
+ .replace(
+ new RegExp(escapeRegExp(rootDir.replace(/\\/g, "\\\\")), "g"),
+ "<ROOTDIR>",
+ );
}
return result;
};
diff --git ORI/babel/packages/babel-core/src/config/files/configuration.js ALT/babel/packages/babel-core/src/config/files/configuration.js
index 8a3bed914..19fcb9ed2 100644
--- ORI/babel/packages/babel-core/src/config/files/configuration.js
+++ ALT/babel/packages/babel-core/src/config/files/configuration.js
@@ -278,10 +278,11 @@ const readConfigJSON5 = makeStaticFileCache((filepath, content): ConfigFile => {
const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
const ignoreDir = path.dirname(filepath);
- const ignorePatterns = content
- .split("\n")
- .map<string>(line => line.replace(/#(.*?)$/, "").trim())
- .filter(line => !!line);
+ const ignorePatterns =
+ content
+ .split("\n")
+ .map<string>(line => line.replace(/#(.*?)$/, "").trim())
+ .filter(line => !!line);
for (const pattern of ignorePatterns) {
if (pattern[0] === "!") {
diff --git ORI/babel/packages/babel-core/src/config/full.js ALT/babel/packages/babel-core/src/config/full.js
index 75fbe293c..2efa73342 100644
--- ORI/babel/packages/babel-core/src/config/full.js
+++ ALT/babel/packages/babel-core/src/config/full.js
@@ -186,10 +186,11 @@ export default gensync<[any], ResolvedConfig | null>(function* loadFullConfig(
})();
opts.plugins = passes[0];
- opts.presets = passes
- .slice(1)
- .filter(plugins => plugins.length > 0)
- .map(plugins => ({ plugins }));
+ opts.presets =
+ passes
+ .slice(1)
+ .filter(plugins => plugins.length > 0)
+ .map(plugins => ({ plugins }));
opts.passPerPreset = opts.presets.length > 0;
return {
diff --git ORI/babel/packages/babel-core/src/transformation/file/merge-map.js ALT/babel/packages/babel-core/src/transformation/file/merge-map.js
index 911867d96..70d64b276 100644
--- ORI/babel/packages/babel-core/src/transformation/file/merge-map.js
+++ ALT/babel/packages/babel-core/src/transformation/file/merge-map.js
@@ -242,19 +242,20 @@ function buildMappingData(map: SourceMap): ResolvedMappings {
sourceData.mappings.push({
original: obj,
- generated: consumer
- .allGeneratedPositionsFor({
- source: m.source,
- line: m.originalLine,
- column: m.originalColumn,
- })
- .map(item => ({
- line: item.line,
- columnStart: item.column,
- // source-map's lastColumn is inclusive, not exclusive, so we need
- // to add 1 to it.
- columnEnd: item.lastColumn + 1,
- })),
+ generated:
+ consumer
+ .allGeneratedPositionsFor({
+ source: m.source,
+ line: m.originalLine,
+ column: m.originalColumn,
+ })
+ .map(item => ({
+ line: item.line,
+ columnStart: item.column,
+ // source-map's lastColumn is inclusive, not exclusive, so we need
+ // to add 1 to it.
+ columnEnd: item.lastColumn + 1,
+ })),
});
},
null,
diff --git ORI/babel/packages/babel-helper-compilation-targets/src/index.js ALT/babel/packages/babel-helper-compilation-targets/src/index.js
index 4fff39876..3723a0435 100644
--- ORI/babel/packages/babel-helper-compilation-targets/src/index.js
+++ ALT/babel/packages/babel-helper-compilation-targets/src/index.js
@@ -160,9 +160,10 @@ export default function getTargets(
// These values OVERRIDE the `browsers` field.
if (inputTargets.esmodules) {
const supportsESModules = browserModulesData["es6.module"];
- browsers = Object.keys(supportsESModules)
- .map(browser => `${browser} ${supportsESModules[browser]}`)
- .join(", ");
+ browsers =
+ Object.keys(supportsESModules)
+ .map(browser => `${browser} ${supportsESModules[browser]}`)
+ .join(", ");
}
// Parse browsers target via browserslist
diff --git ORI/babel/packages/babel-helper-module-transforms/src/get-module-name.js ALT/babel/packages/babel-helper-module-transforms/src/get-module-name.js
index 0e4e81ad3..228aef281 100644
--- ORI/babel/packages/babel-helper-module-transforms/src/get-module-name.js
+++ ALT/babel/packages/babel-helper-module-transforms/src/get-module-name.js
@@ -33,11 +33,12 @@ export default function getModuleName(
const sourceRootReplacer =
sourceRoot != null ? new RegExp("^" + sourceRoot + "/?") : "";
- moduleName += filenameRelative
- // remove sourceRoot from filename
- .replace(sourceRootReplacer, "")
- // remove extension
- .replace(/\.(\w*?)$/, "");
+ moduleName +=
+ filenameRelative
+ // remove sourceRoot from filename
+ .replace(sourceRootReplacer, "")
+ // remove extension
+ .replace(/\.(\w*?)$/, "");
}
// normalize path separators
diff --git ORI/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js ALT/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js
index 1b5116349..1fa64d029 100644
--- ORI/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js
+++ ALT/babel/packages/babel-helper-transform-fixture-test-runner/src/index.js
@@ -325,23 +325,25 @@ function validateFile(actualCode, expectedLoc, expectedCode) {
function normalizeOutput(code) {
const projectRoot = path.resolve(__dirname, "../../../");
const cwdSymbol = "<CWD>";
- let result = code
- .trim()
- // (non-win32) /foo/babel/packages -> <CWD>/packages
- // (win32) C:\foo\babel\packages -> <CWD>\packages
- .replace(new RegExp(escapeRegExp(projectRoot), "g"), cwdSymbol);
+ let result =
+ code
+ .trim()
+ // (non-win32) /foo/babel/packages -> <CWD>/packages
+ // (win32) C:\foo\babel\packages -> <CWD>\packages
+ .replace(new RegExp(escapeRegExp(projectRoot), "g"), cwdSymbol);
if (process.platform === "win32") {
- result = result
- // C:/foo/babel/packages -> <CWD>/packages
- .replace(
- new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "/")), "g"),
- cwdSymbol,
- )
- // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
- .replace(
- new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "\\\\")), "g"),
- cwdSymbol,
- );
+ result =
+ result
+ // C:/foo/babel/packages -> <CWD>/packages
+ .replace(
+ new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "/")), "g"),
+ cwdSymbol,
+ )
+ // C:\\foo\\babel\\packages -> <CWD>\\packages (in js string literal)
+ .replace(
+ new RegExp(escapeRegExp(projectRoot.replace(/\\/g, "\\\\")), "g"),
+ cwdSymbol,
+ );
}
return result;
}
diff --git ORI/babel/packages/babel-helpers/src/index.js ALT/babel/packages/babel-helpers/src/index.js
index 067719614..1a6155c51 100644
--- ORI/babel/packages/babel-helpers/src/index.js
+++ ALT/babel/packages/babel-helpers/src/index.js
@@ -303,8 +303,9 @@ export function ensure(name: string, newFileClass?) {
loadHelper(name);
}
-export const list = Object.keys(helpers)
- .map(name => name.replace(/^_/, ""))
- .filter(name => name !== "__esModule");
+export const list =
+ Object.keys(helpers)
+ .map(name => name.replace(/^_/, ""))
+ .filter(name => name !== "__esModule");
export default get;
diff --git ORI/babel/packages/babel-highlight/src/index.js ALT/babel/packages/babel-highlight/src/index.js
index f2639a521..1a89ce0fd 100644
--- ORI/babel/packages/babel-highlight/src/index.js
+++ ALT/babel/packages/babel-highlight/src/index.js
@@ -204,10 +204,11 @@ function highlightTokens(defs: Object, text: string) {
for (const { type, value } of tokenize(text)) {
const colorize = defs[type];
if (colorize) {
- highlighted += value
- .split(NEWLINE)
- .map(str => colorize(str))
- .join("\n");
+ highlighted +=
+ value
+ .split(NEWLINE)
+ .map(str => colorize(str))
+ .join("\n");
} else {
highlighted += value;
}
diff --git ORI/babel/packages/babel-parser/src/parser/expression.js ALT/babel/packages/babel-parser/src/parser/expression.js
index b50aed34e..c9a06b149 100644
--- ORI/babel/packages/babel-parser/src/parser/expression.js
+++ ALT/babel/packages/babel-parser/src/parser/expression.js
@@ -1552,9 +1552,10 @@ export default class ExpressionParser extends LValParser {
}
}
elem.value = {
- raw: this.input
- .slice(this.state.start, this.state.end)
- .replace(/\r\n?/g, "\n"),
+ raw:
+ this.input
+ .slice(this.state.start, this.state.end)
+ .replace(/\r\n?/g, "\n"),
cooked: this.state.value,
};
this.next();
diff --git ORI/babel/packages/babel-parser/src/tokenizer/index.js ALT/babel/packages/babel-parser/src/tokenizer/index.js
index 7c119c7d1..2c23b7ae2 100644
--- ORI/babel/packages/babel-parser/src/tokenizer/index.js
+++ ALT/babel/packages/babel-parser/src/tokenizer/index.js
@@ -1381,9 +1381,10 @@ export default class Tokenizer extends ParserErrors {
default:
if (ch >= charCodes.digit0 && ch <= charCodes.digit7) {
const codePos = this.state.pos - 1;
- const match = this.input
- .substr(this.state.pos - 1, 3)
- .match(/^[0-7]+/);
+ const match =
+ this.input
+ .substr(this.state.pos - 1, 3)
+ .match(/^[0-7]+/);
// This is never null, because of the if condition above.
/*:: invariant(match !== null) */
diff --git ORI/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js ALT/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js
index 387e2634c..c0741f2f8 100644
--- ORI/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js
+++ ALT/babel/packages/babel-plugin-proposal-object-rest-spread/src/index.js
@@ -394,9 +394,10 @@ export default declare((api, opts) => {
const declaration = path.get("declaration");
if (!declaration.isVariableDeclaration()) return;
- const hasRest = declaration
- .get("declarations")
- .some(path => hasObjectPatternRestElement(path.get("id")));
+ const hasRest =
+ declaration
+ .get("declarations")
+ .some(path => hasObjectPatternRestElement(path.get("id")));
if (!hasRest) return;
const specifiers = [];
diff --git ORI/babel/packages/babel-plugin-transform-flow-comments/src/index.js ALT/babel/packages/babel-plugin-transform-flow-comments/src/index.js
index db926052c..afa1486ad 100644
--- ORI/babel/packages/babel-plugin-transform-flow-comments/src/index.js
+++ ALT/babel/packages/babel-plugin-transform-flow-comments/src/index.js
@@ -68,10 +68,11 @@ export default declare(api => {
}
function generateComment(path, optional) {
- let comment = path
- .getSource()
- .replace(/\*-\//g, "*-ESCAPED/")
- .replace(/\*\//g, "*-/");
+ let comment =
+ path
+ .getSource()
+ .replace(/\*-\//g, "*-ESCAPED/")
+ .replace(/\*\//g, "*-/");
if (optional) comment = "?" + comment;
if (comment[0] !== ":") comment = ":: " + comment;
return comment;
diff --git ORI/babel/packages/babel-plugin-transform-modules-amd/src/index.js ALT/babel/packages/babel-plugin-transform-modules-amd/src/index.js
index 7ea2b150f..adb8d0e21 100644
--- ORI/babel/packages/babel-plugin-transform-modules-amd/src/index.js
+++ ALT/babel/packages/babel-plugin-transform-modules-amd/src/index.js
@@ -27,10 +27,11 @@ function injectWrapper(path, wrapper) {
path.node.directives = [];
path.node.body = [];
const amdWrapper = path.pushContainer("body", wrapper)[0];
- const amdFactory = amdWrapper
- .get("expression.arguments")
- .filter(arg => arg.isFunctionExpression())[0]
- .get("body");
+ const amdFactory =
+ amdWrapper
+ .get("expression.arguments")
+ .filter(arg => arg.isFunctionExpression())[0]
+ .get("body");
amdFactory.pushContainer("directives", directives);
amdFactory.pushContainer("body", body);
}
diff --git ORI/babel/packages/babel-plugin-transform-modules-umd/src/index.js ALT/babel/packages/babel-plugin-transform-modules-umd/src/index.js
index 0f85d5f9a..0752f4ad6 100644
--- ORI/babel/packages/babel-plugin-transform-modules-umd/src/index.js
+++ ALT/babel/packages/babel-plugin-transform-modules-umd/src/index.js
@@ -108,12 +108,13 @@ export default declare((api, options) => {
if (exactGlobals) {
const globalRef = browserGlobals[source];
if (globalRef) {
- memberExpression = globalRef
- .split(".")
- .reduce(
- (accum, curr) => t.memberExpression(accum, t.identifier(curr)),
- t.identifier("global"),
- );
+ memberExpression =
+ globalRef
+ .split(".")
+ .reduce(
+ (accum, curr) => t.memberExpression(accum, t.identifier(curr)),
+ t.identifier("global"),
+ );
} else {
memberExpression = t.memberExpression(
t.identifier("global"),
@@ -228,9 +229,10 @@ export default declare((api, options) => {
),
}),
])[0];
- const umdFactory = umdWrapper
- .get("expression.arguments")[1]
- .get("body");
+ const umdFactory =
+ umdWrapper
+ .get("expression.arguments")[1]
+ .get("body");
umdFactory.pushContainer("directives", directives);
umdFactory.pushContainer("body", body);
},
diff --git ORI/babel/packages/babel-plugin-transform-parameters/src/rest.js ALT/babel/packages/babel-plugin-transform-parameters/src/rest.js
index cfba76ce4..42db73bfe 100644
--- ORI/babel/packages/babel-plugin-transform-parameters/src/rest.js
+++ ALT/babel/packages/babel-plugin-transform-parameters/src/rest.js
@@ -349,9 +349,10 @@ export default function convertFunctionRest(path) {
if (state.deopted) {
node.body.body.unshift(loop);
} else {
- let target = path
- .getEarliestCommonAncestorFrom(state.references)
- .getStatementParent();
+ let target =
+ path
+ .getEarliestCommonAncestorFrom(state.references)
+ .getStatementParent();
// don't perform the allocation inside a loop
target.findParent(path => {
diff --git ORI/babel/packages/babel-preset-env/src/debug.js ALT/babel/packages/babel-preset-env/src/debug.js
index b91499e72..9a180a71e 100644
--- ORI/babel/packages/babel-preset-env/src/debug.js
+++ ALT/babel/packages/babel-preset-env/src/debug.js
@@ -18,10 +18,11 @@ export const logPluginOrPolyfill = (
) => {
const filteredList = getInclusionReasons(item, targetVersions, list);
- const formattedTargets = JSON.stringify(filteredList)
- .replace(/,/g, ", ")
- .replace(/^\{"/, '{ "')
- .replace(/"\}$/, '" }');
+ const formattedTargets =
+ JSON.stringify(filteredList)
+ .replace(/,/g, ", ")
+ .replace(/^\{"/, '{ "')
+ .replace(/"\}$/, '" }');
console.log(` ${item} ${formattedTargets}`);
};
diff --git ORI/babel/packages/babel-preset-env/src/index.js ALT/babel/packages/babel-preset-env/src/index.js
index 90384f610..eec73efbb 100644
--- ORI/babel/packages/babel-preset-env/src/index.js
+++ ALT/babel/packages/babel-preset-env/src/index.js
@@ -326,30 +326,31 @@ option \`forceAllTransforms: true\` instead.
});
const pluginUseBuiltIns = useBuiltIns !== false;
- const plugins = Array.from(pluginNames)
- .map(pluginName => {
- if (
- pluginName === "proposal-class-properties" ||
- pluginName === "proposal-private-methods" ||
- // This is not included in preset-env yet, but let's keep it here so we
- // don't forget about it in the future.
- pluginName === "proposal-private-property-in-object"
- ) {
+ const plugins =
+ Array.from(pluginNames)
+ .map(pluginName => {
+ if (
+ pluginName === "proposal-class-properties" ||
+ pluginName === "proposal-private-methods" ||
+ // This is not included in preset-env yet, but let's keep it here so we
+ // don't forget about it in the future.
+ pluginName === "proposal-private-property-in-object"
+ ) {
+ return [
+ getPlugin(pluginName),
+ {
+ loose: loose
+ ? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"
+ : "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error",
+ },
+ ];
+ }
return [
getPlugin(pluginName),
- {
- loose: loose
- ? "#__internal__@babel/preset-env__prefer-true-but-false-is-ok-if-it-prevents-an-error"
- : "#__internal__@babel/preset-env__prefer-false-but-true-is-ok-if-it-prevents-an-error",
- },
+ { spec, loose, useBuiltIns: pluginUseBuiltIns },
];
- }
- return [
- getPlugin(pluginName),
- { spec, loose, useBuiltIns: pluginUseBuiltIns },
- ];
- })
- .concat(polyfillPlugins);
+ })
+ .concat(polyfillPlugins);
if (debug) {
console.log("@babel/preset-env: `DEBUG` option");
diff --git ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js
index caa8de4cf..96c4a6a5b 100644
--- ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js
+++ ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/entry-plugin.js
@@ -23,10 +23,11 @@ function isBabelPolyfillSource(source) {
function isCoreJSSource(source) {
if (typeof source === "string") {
- source = source
- .replace(/\\/g, "/")
- .replace(/(\/(index)?)?(\.js)?$/i, "")
- .toLowerCase();
+ source =
+ source
+ .replace(/\\/g, "/")
+ .replace(/(\/(index)?)?(\.js)?$/i, "")
+ .toLowerCase();
}
return has(corejsEntries, source) && corejsEntries[source];
}
diff --git ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js
index 37370a9b6..77edfac37 100644
--- ORI/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js
+++ ALT/babel/packages/babel-preset-env/src/polyfills/corejs3/usage-plugin.js
@@ -32,12 +32,13 @@ const NO_DIRECT_POLYFILL_IMPORT = `
When setting \`useBuiltIns: 'usage'\`, polyfills are automatically imported when needed.
Please remove the direct import of \`core-js\` or use \`useBuiltIns: 'entry'\` instead.`;
-const corejs3PolyfillsWithoutProposals = Object.keys(corejs3Polyfills)
- .filter(name => !name.startsWith("esnext."))
- .reduce((memo, key) => {
- memo[key] = corejs3Polyfills[key];
- return memo;
- }, {});
+const corejs3PolyfillsWithoutProposals =
+ Object.keys(corejs3Polyfills)
+ .filter(name => !name.startsWith("esnext."))
+ .reduce((memo, key) => {
+ memo[key] = corejs3Polyfills[key];
+ return memo;
+ }, {});
const corejs3PolyfillsWithShippedProposals =
(corejs3ShippedProposalsList: string[]).reduce(
diff --git ORI/babel/packages/babel-traverse/test/evaluation.js ALT/babel/packages/babel-traverse/test/evaluation.js
index d90ab87ff..ff8625c01 100644
--- ORI/babel/packages/babel-traverse/test/evaluation.js
+++ ALT/babel/packages/babel-traverse/test/evaluation.js
@@ -107,12 +107,14 @@ describe("evaluation", function () {
const member_expr = getPath(
"var x = Math.min(2,Math.max(3,4));var y = Math.random();",
);
- const eval_member_expr = member_expr
- .get("body.0.declarations.0.init")
- .evaluate();
- const eval_invalid_call = member_expr
- .get("body.1.declarations.0.init")
- .evaluate();
+ const eval_member_expr =
+ member_expr
+ .get("body.0.declarations.0.init")
+ .evaluate();
+ const eval_invalid_call =
+ member_expr
+ .get("body.1.declarations.0.init")
+ .evaluate();
expect(eval_member_expr.value).toBe(2);
expect(eval_invalid_call.confident).toBe(false);
});
@@ -177,15 +179,18 @@ describe("evaluation", function () {
});
it("should deopt redefined primitives - undefined, NaN and Infinity", () => {
- const eval_undef = getPath("let undefined; undefined;")
- .get("body.1.expression")
- .evaluate();
- const eval_nan = getPath("let NaN; NaN;")
- .get("body.1.expression")
- .evaluate();
- const eval_inf = getPath("let Infinity; Infinity;")
- .get("body.1.expression")
- .evaluate();
+ const eval_undef =
+ getPath("let undefined; undefined;")
+ .get("body.1.expression")
+ .evaluate();
+ const eval_nan =
+ getPath("let NaN; NaN;")
+ .get("body.1.expression")
+ .evaluate();
+ const eval_inf =
+ getPath("let Infinity; Infinity;")
+ .get("body.1.expression")
+ .evaluate();
expect(eval_undef.confident).toBe(false);
expect(eval_nan.confident).toBe(false);
expect(eval_inf.confident).toBe(false);
diff --git ORI/babel/packages/babel-traverse/test/inference.js ALT/babel/packages/babel-traverse/test/inference.js
index dde8bd227..1d9d2614d 100644
--- ORI/babel/packages/babel-traverse/test/inference.js
+++ ALT/babel/packages/babel-traverse/test/inference.js
@@ -17,9 +17,10 @@ function getPath(code) {
describe("inference", function () {
describe("baseTypeStrictlyMatches", function () {
it("it should work with null", function () {
- const path = getPath("var x = null; x === null")
- .get("body")[1]
- .get("expression");
+ const path =
+ getPath("var x = null; x === null")
+ .get("body")[1]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
@@ -28,9 +29,10 @@ describe("inference", function () {
});
it("it should work with numbers", function () {
- const path = getPath("var x = 1; x === 2")
- .get("body")[1]
- .get("expression");
+ const path =
+ getPath("var x = 1; x === 2")
+ .get("body")[1]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
@@ -39,9 +41,10 @@ describe("inference", function () {
});
it("it should bail when type changes", function () {
- const path = getPath("var x = 1; if (foo) x = null;else x = 3; x === 2")
- .get("body")[2]
- .get("expression");
+ const path =
+ getPath("var x = 1; if (foo) x = null;else x = 3; x === 2")
+ .get("body")[2]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
@@ -51,9 +54,10 @@ describe("inference", function () {
});
it("it should differentiate between null and undefined", function () {
- const path = getPath("var x; x === null")
- .get("body")[1]
- .get("expression");
+ const path =
+ getPath("var x; x === null")
+ .get("body")[1]
+ .get("expression");
const left = path.get("left");
const right = path.get("right");
const strictMatch = left.baseTypeStrictlyMatches(right);
@@ -141,34 +145,38 @@ describe("inference", function () {
).toBeTruthy();
});
it("should infer Function from function", function () {
- const path = getPath("(function (): string {})")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(function (): string {})")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Function",
).toBeTruthy();
});
it("should infer call return type using function", function () {
- const path = getPath("(function (): string {})()")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(function (): string {})()")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(t.isStringTypeAnnotation(type)).toBeTruthy();
});
it("should infer call return type using async function", function () {
- const path = getPath("(async function (): string {})()")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(async function (): string {})()")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "Promise",
).toBeTruthy();
});
it("should infer call return type using async generator function", function () {
- const path = getPath("(async function * (): string {})()")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(async function * (): string {})()")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "AsyncIterator",
@@ -197,9 +205,10 @@ describe("inference", function () {
expect(t.isNumberTypeAnnotation(type.types[1])).toBeTruthy();
});
it("should infer type of tagged template literal", function () {
- const path = getPath("(function (): RegExp {}) `hey`")
- .get("body")[0]
- .get("expression");
+ const path =
+ getPath("(function (): RegExp {}) `hey`")
+ .get("body")[0]
+ .get("expression");
const type = path.getTypeAnnotation();
expect(
t.isGenericTypeAnnotation(type) && type.id.name === "RegExp",
diff --git ORI/eslint-plugin-vue/docs/.vuepress/config.js ALT/eslint-plugin-vue/docs/.vuepress/config.js
index fb7719f..fdd16d2 100644
--- ORI/eslint-plugin-vue/docs/.vuepress/config.js
+++ ALT/eslint-plugin-vue/docs/.vuepress/config.js
@@ -60,21 +60,23 @@ const sidebarCategories = [
const categorizedRules = []
for (const { title, categoryIds } of sidebarCategories) {
- const categoryRules = rules
- .filter((rule) => rule.meta.docs.categories && !rule.meta.deprecated)
- .filter((rule) =>
- categoryIds.every((categoryId) =>
- rule.meta.docs.categories.includes(categoryId)
+ const categoryRules =
+ rules
+ .filter((rule) => rule.meta.docs.categories && !rule.meta.deprecated)
+ .filter((rule) =>
+ categoryIds.every((categoryId) =>
+ rule.meta.docs.categories.includes(categoryId)
+ )
)
- )
- const children = categoryRules
- .filter(({ ruleId }) => {
- const exists = categorizedRules.some(({ children }) =>
- children.some(([, alreadyRuleId]) => alreadyRuleId === ruleId)
- )
- return !exists
- })
- .map(({ ruleId, name }) => [`/rules/${name}`, ruleId])
+ const children =
+ categoryRules
+ .filter(({ ruleId }) => {
+ const exists = categorizedRules.some(({ children }) =>
+ children.some(([, alreadyRuleId]) => alreadyRuleId === ruleId)
+ )
+ return !exists
+ })
+ .map(({ ruleId, name }) => [`/rules/${name}`, ruleId])
if (children.length === 0) {
continue
diff --git ORI/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js ALT/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js
index 88cd9de..ebc9087 100644
--- ORI/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js
+++ ALT/eslint-plugin-vue/eslint-internal-rules/require-meta-docs-url.js
@@ -68,64 +68,65 @@ function getRuleInfo(ast) {
let exportsVarOverridden = false
let exportsIsFunction = false
- const exportNodes = ast.body
- .filter((statement) => statement.type === 'ExpressionStatement')
- .map((statement) => statement.expression)
- .filter((expression) => expression.type === 'AssignmentExpression')
- .filter((expression) => expression.left.type === 'MemberExpression')
- .reduce((currentExports, node) => {
- if (
- node.left.object.type === 'Identifier' &&
- node.left.object.name === 'module' &&
- node.left.property.type === 'Identifier' &&
- node.left.property.name === 'exports'
- ) {
- exportsVarOverridden = true
+ const exportNodes =
+ ast.body
+ .filter((statement) => statement.type === 'ExpressionStatement')
+ .map((statement) => statement.expression)
+ .filter((expression) => expression.type === 'AssignmentExpression')
+ .filter((expression) => expression.left.type === 'MemberExpression')
+ .reduce((currentExports, node) => {
+ if (
+ node.left.object.type === 'Identifier' &&
+ node.left.object.name === 'module' &&
+ node.left.property.type === 'Identifier' &&
+ node.left.property.name === 'exports'
+ ) {
+ exportsVarOverridden = true
- if (isNormalFunctionExpression(node.right)) {
- // Check `module.exports = function () {}`
+ if (isNormalFunctionExpression(node.right)) {
+ // Check `module.exports = function () {}`
- exportsIsFunction = true
- return { create: node.right, meta: null }
- } else if (node.right.type === 'ObjectExpression') {
- // Check `module.exports = { create: function () {}, meta: {} }`
+ exportsIsFunction = true
+ return { create: node.right, meta: null }
+ } else if (node.right.type === 'ObjectExpression') {
+ // Check `module.exports = { create: function () {}, meta: {} }`
- exportsIsFunction = false
- return node.right.properties.reduce((parsedProps, prop) => {
- const keyValue = getKeyName(prop)
- if (INTERESTING_KEYS.has(keyValue)) {
- parsedProps[keyValue] = prop.value
- }
- return parsedProps
- }, {})
- }
- return {}
- } else if (
- !exportsIsFunction &&
- node.left.object.type === 'MemberExpression' &&
- node.left.object.object.type === 'Identifier' &&
- node.left.object.object.name === 'module' &&
- node.left.object.property.type === 'Identifier' &&
- node.left.object.property.name === 'exports' &&
- node.left.property.type === 'Identifier' &&
- INTERESTING_KEYS.has(node.left.property.name)
- ) {
- // Check `module.exports.create = () => {}`
+ exportsIsFunction = false
+ return node.right.properties.reduce((parsedProps, prop) => {
+ const keyValue = getKeyName(prop)
+ if (INTERESTING_KEYS.has(keyValue)) {
+ parsedProps[keyValue] = prop.value
+ }
+ return parsedProps
+ }, {})
+ }
+ return {}
+ } else if (
+ !exportsIsFunction &&
+ node.left.object.type === 'MemberExpression' &&
+ node.left.object.object.type === 'Identifier' &&
+ node.left.object.object.name === 'module' &&
+ node.left.object.property.type === 'Identifier' &&
+ node.left.object.property.name === 'exports' &&
+ node.left.property.type === 'Identifier' &&
+ INTERESTING_KEYS.has(node.left.property.name)
+ ) {
+ // Check `module.exports.create = () => {}`
- currentExports[node.left.property.name] = node.right
- } else if (
- !exportsVarOverridden &&
- node.left.object.type === 'Identifier' &&
- node.left.object.name === 'exports' &&
- node.left.property.type === 'Identifier' &&
- INTERESTING_KEYS.has(node.left.property.name)
- ) {
- // Check `exports.create = () => {}`
+ currentExports[node.left.property.name] = node.right
+ } else if (
+ !exportsVarOverridden &&
+ node.left.object.type === 'Identifier' &&
+ node.left.object.name === 'exports' &&
+ node.left.property.type === 'Identifier' &&
+ INTERESTING_KEYS.has(node.left.property.name)
+ ) {
+ // Check `exports.create = () => {}`
- currentExports[node.left.property.name] = node.right
- }
- return currentExports
- }, {})
+ currentExports[node.left.property.name] = node.right
+ }
+ return currentExports
+ }, {})
return Object.prototype.hasOwnProperty.call(exportNodes, 'create')
? Object.assign({ isNewStyle: !exportsIsFunction, meta: null }, exportNodes)
diff --git ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js
index d215a27..b303b40 100644
--- ORI/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js
+++ ALT/eslint-plugin-vue/lib/rules/experimental-script-setup-vars.js
@@ -38,14 +38,15 @@ module.exports = {
return {}
}
const sourceCode = context.getSourceCode()
- const scriptElement = documentFragment.children
- .filter(utils.isVElement)
- .find(
- (element) =>
- element.name === 'script' &&
- element.range[0] <= sourceCode.ast.range[0] &&
- sourceCode.ast.range[1] <= element.range[1]
- )
+ const scriptElement =
+ documentFragment.children
+ .filter(utils.isVElement)
+ .find(
+ (element) =>
+ element.name === 'script' &&
+ element.range[0] <= sourceCode.ast.range[0] &&
+ sourceCode.ast.range[1] <= element.range[1]
+ )
if (!scriptElement) {
return {}
}
diff --git ORI/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js ALT/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js
index 786ecb9..eef0741 100644
--- ORI/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js
+++ ALT/eslint-plugin-vue/lib/rules/no-deprecated-v-bind-sync.js
@@ -49,9 +49,10 @@ module.exports = {
return null
}
- const bindArgument = context
- .getSourceCode()
- .getText(node.key.argument)
+ const bindArgument =
+ context
+ .getSourceCode()
+ .getText(node.key.argument)
return fixer.replaceText(node.key, `v-model:${bindArgument}`)
}
})
diff --git ORI/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js ALT/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js
index f3ac473..8b578ab 100644
--- ORI/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js
+++ ALT/eslint-plugin-vue/lib/rules/no-potential-component-option-typo.js
@@ -75,20 +75,21 @@ module.exports = {
return {}
}
return utils.executeOnVue(context, (obj) => {
- const componentInstanceOptions = obj.properties
- .map((p) => {
- if (p.type === 'Property') {
- const name = utils.getStaticPropertyName(p)
- if (name != null) {
- return {
- name,
- key: p.key
+ const componentInstanceOptions =
+ obj.properties
+ .map((p) => {
+ if (p.type === 'Property') {
+ const name = utils.getStaticPropertyName(p)
+ if (name != null) {
+ return {
+ name,
+ key: p.key
+ }
}
}
- }
- return null
- })
- .filter(utils.isDef)
+ return null
+ })
+ .filter(utils.isDef)
if (!componentInstanceOptions.length) {
return
@@ -99,10 +100,11 @@ module.exports = {
if (candidateOptionSet.has(name)) {
return
}
- const potentialTypoList = candidateOptionList
- .map((o) => ({ option: o, distance: utils.editDistance(o, name) }))
- .filter(({ distance }) => distance <= threshold && distance > 0)
- .sort((a, b) => a.distance - b.distance)
+ const potentialTypoList =
+ candidateOptionList
+ .map((o) => ({ option: o, distance: utils.editDistance(o, name) }))
+ .filter(({ distance }) => distance <= threshold && distance > 0)
+ .sort((a, b) => a.distance - b.distance)
if (potentialTypoList.length) {
context.report({
node: id,
diff --git ORI/eslint-plugin-vue/lib/rules/no-unregistered-components.js ALT/eslint-plugin-vue/lib/rules/no-unregistered-components.js
index 6e6cb2a..5a3f29f 100644
--- ORI/eslint-plugin-vue/lib/rules/no-unregistered-components.js
+++ ALT/eslint-plugin-vue/lib/rules/no-unregistered-components.js
@@ -133,9 +133,10 @@ module.exports = {
)
// All registered components using kebab-case syntax
- const componentsRegisteredAsKebabCase = registeredComponents
- .filter(({ name }) => name === casing.kebabCase(name))
- .map(({ name }) => name)
+ const componentsRegisteredAsKebabCase =
+ registeredComponents
+ .filter(({ name }) => name === casing.kebabCase(name))
+ .map(({ name }) => name)
usedComponentNodes
.filter(({ name }) => {
diff --git ORI/eslint-plugin-vue/lib/rules/no-useless-mustaches.js ALT/eslint-plugin-vue/lib/rules/no-useless-mustaches.js
index 709617e..9021628 100644
--- ORI/eslint-plugin-vue/lib/rules/no-useless-mustaches.js
+++ ALT/eslint-plugin-vue/lib/rules/no-useless-mustaches.js
@@ -93,9 +93,10 @@ module.exports = {
}
const tokenStore = context.parserServices.getTemplateBodyTokenStore()
- const hasComment = tokenStore
- .getTokens(node, { includeComments: true })
- .some((t) => t.type === 'Block' || t.type === 'Line')
+ const hasComment =
+ tokenStore
+ .getTokens(node, { includeComments: true })
+ .some((t) => t.type === 'Block' || t.type === 'Line')
if (ignoreIncludesComment && hasComment) {
return
}
diff --git ORI/eslint-plugin-vue/lib/rules/no-useless-v-bind.js ALT/eslint-plugin-vue/lib/rules/no-useless-v-bind.js
index c2440da..fd934d7 100644
--- ORI/eslint-plugin-vue/lib/rules/no-useless-v-bind.js
+++ ALT/eslint-plugin-vue/lib/rules/no-useless-v-bind.js
@@ -76,9 +76,10 @@ module.exports = {
}
const tokenStore = context.parserServices.getTemplateBodyTokenStore()
- const hasComment = tokenStore
- .getTokens(value, { includeComments: true })
- .some((t) => t.type === 'Block' || t.type === 'Line')
+ const hasComment =
+ tokenStore
+ .getTokens(value, { includeComments: true })
+ .some((t) => t.type === 'Block' || t.type === 'Line')
if (ignoreIncludesComment && hasComment) {
return
}
@@ -134,9 +135,10 @@ module.exports = {
} else if (quoteChar === "'") {
attrValue = strValue.replace(SINGLE_QUOTES_RE, ''')
} else {
- attrValue = strValue
- .replace(DOUBLE_QUOTES_RE, '"')
- .replace(SINGLE_QUOTES_RE, ''')
+ attrValue =
+ strValue
+ .replace(DOUBLE_QUOTES_RE, '"')
+ .replace(SINGLE_QUOTES_RE, ''')
}
yield fixer.replaceText(expression, attrValue)
}
diff --git ORI/eslint-plugin-vue/lib/rules/order-in-components.js ALT/eslint-plugin-vue/lib/rules/order-in-components.js
index 5f33734..0681c85 100644
--- ORI/eslint-plugin-vue/lib/rules/order-in-components.js
+++ ALT/eslint-plugin-vue/lib/rules/order-in-components.js
@@ -271,13 +271,14 @@ module.exports = {
return
}
const propertiesAbove = properties.slice(0, i)
- const unorderedProperties = propertiesAbove
- .filter(
- (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
- )
- .sort((p1, p2) =>
- getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
- )
+ const unorderedProperties =
+ propertiesAbove
+ .filter(
+ (p) => getOrderPosition(p.name) > getOrderPosition(property.name)
+ )
+ .sort((p1, p2) =>
+ getOrderPosition(p1.name) > getOrderPosition(p2.name) ? 1 : -1
+ )
const firstUnorderedProperty = unorderedProperties[0]
@@ -294,15 +295,16 @@ module.exports = {
*fix(fixer) {
const propertyNode = property.node
const firstUnorderedPropertyNode = firstUnorderedProperty.node
- const hasSideEffectsPossibility = propertiesNodes
- .slice(
- propertiesNodes.indexOf(firstUnorderedPropertyNode),
- propertiesNodes.indexOf(propertyNode) + 1
- )
- .some(
- (property) =>
- !isNotSideEffectsNode(property, sourceCode.visitorKeys)
- )
+ const hasSideEffectsPossibility =
+ propertiesNodes
+ .slice(
+ propertiesNodes.indexOf(firstUnorderedPropertyNode),
+ propertiesNodes.indexOf(propertyNode) + 1
+ )
+ .some(
+ (property) =>
+ !isNotSideEffectsNode(property, sourceCode.visitorKeys)
+ )
if (hasSideEffectsPossibility) {
return
}
diff --git ORI/eslint-plugin-vue/lib/rules/require-default-prop.js ALT/eslint-plugin-vue/lib/rules/require-default-prop.js
index e0e29b6..cb70b3e 100644
--- ORI/eslint-plugin-vue/lib/rules/require-default-prop.js
+++ ALT/eslint-plugin-vue/lib/rules/require-default-prop.js
@@ -158,13 +158,14 @@ module.exports = {
// ----------------------------------------------------------------------
return utils.executeOnVue(context, (obj) => {
- const props = utils
- .getComponentProps(obj)
- .filter(
- (prop) =>
- prop.value &&
- !(prop.node.type === 'Property' && prop.node.shorthand)
- )
+ const props =
+ utils
+ .getComponentProps(obj)
+ .filter(
+ (prop) =>
+ prop.value &&
+ !(prop.node.type === 'Property' && prop.node.shorthand)
+ )
const propsWithoutDefault = findPropsWithoutDefaultValue(
/** @type {ComponentObjectProp[]} */ (props)
diff --git ORI/eslint-plugin-vue/lib/utils/indent-common.js ALT/eslint-plugin-vue/lib/utils/indent-common.js
index c4818b4..b947776 100644
--- ORI/eslint-plugin-vue/lib/utils/indent-common.js
+++ ALT/eslint-plugin-vue/lib/utils/indent-common.js
@@ -1878,12 +1878,14 @@ module.exports.defineVisitor = function create(
/** @param {TemplateLiteral} node */
TemplateLiteral(node) {
const firstToken = tokenStore.getFirstToken(node)
- const quasiTokens = node.quasis
- .slice(1)
- .map((n) => tokenStore.getFirstToken(n))
- const expressionToken = node.quasis
- .slice(0, -1)
- .map((n) => tokenStore.getTokenAfter(n))
+ const quasiTokens =
+ node.quasis
+ .slice(1)
+ .map((n) => tokenStore.getFirstToken(n))
+ const expressionToken =
+ node.quasis
+ .slice(0, -1)
+ .map((n) => tokenStore.getTokenAfter(n))
setOffset(quasiTokens, 0, firstToken)
setOffset(expressionToken, 1, firstToken)
diff --git ORI/eslint-plugin-vue/lib/utils/index.js ALT/eslint-plugin-vue/lib/utils/index.js
index 055ffb4..5e8d004 100644
--- ORI/eslint-plugin-vue/lib/utils/index.js
+++ ALT/eslint-plugin-vue/lib/utils/index.js
@@ -2033,9 +2033,10 @@ function getComponentComments(context) {
return tokens
}
const sourceCode = context.getSourceCode()
- tokens = sourceCode
- .getAllComments()
- .filter((comment) => /@vue\/component/g.test(comment.value))
+ tokens =
+ sourceCode
+ .getAllComments()
+ .filter((comment) => /@vue\/component/g.test(comment.value))
componentComments.set(context, tokens)
return tokens
}
diff --git ORI/eslint-plugin-vue/tests/lib/rules/html-indent.js ALT/eslint-plugin-vue/tests/lib/rules/html-indent.js
index 316eb92..5f705b8 100644
--- ORI/eslint-plugin-vue/tests/lib/rules/html-indent.js
+++ ALT/eslint-plugin-vue/tests/lib/rules/html-indent.js
@@ -50,36 +50,41 @@ function loadPatterns(additionalValid, additionalInvalid) {
}
return Object.assign(baseObj, { code, filename })
})
- const invalid = valid
- .map((pattern) => {
- const kind =
- (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
- const output = pattern.code
- const lines = output.split('\n').map((text, number) => ({
- number,
- text,
- indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
- }))
- const code = lines
- .map((line) => line.text.replace(/^[ \t]+/, ''))
- .join('\n')
- const errors = lines
- .map((line) =>
- line.indentSize === 0
- ? null
- : {
- message: `Expected indentation of ${line.indentSize} ${kind}${
- line.indentSize === 1 ? '' : 's'
- } but found 0 ${kind}s.`,
- line: line.number + 1
- }
- )
- .filter(Boolean)
+ const invalid =
+ valid
+ .map((pattern) => {
+ const kind =
+ (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
+ const output = pattern.code
+ const lines = output.split('\n').map((text, number) => ({
+ number,
+ text,
+ indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
+ }))
+ const code =
+ lines
+ .map((line) => line.text.replace(/^[ \t]+/, ''))
+ .join('\n')
+ const errors =
+ lines
+ .map((line) =>
+ line.indentSize === 0
+ ? null
+ : {
+ message: `Expected indentation of ${
+ line.indentSize
+ } ${kind}${
+ line.indentSize === 1 ? '' : 's'
+ } but found 0 ${kind}s.`,
+ line: line.number + 1
+ }
+ )
+ .filter(Boolean)
- return Object.assign({}, pattern, { code, output, errors })
- })
- .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
- .filter(Boolean)
+ return Object.assign({}, pattern, { code, output, errors })
+ })
+ .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
+ .filter(Boolean)
return {
valid: valid.concat(additionalValid),
@@ -94,13 +99,15 @@ function loadPatterns(additionalValid, additionalInvalid) {
*/
function unIndent(strings) {
const templateValue = strings[0]
- const lines = templateValue
- .replace(/^\n/, '')
- .replace(/\n\s*$/, '')
- .split('\n')
- const lineIndents = lines
- .filter((line) => line.trim())
- .map((line) => line.match(/ */)[0].length)
+ const lines =
+ templateValue
+ .replace(/^\n/, '')
+ .replace(/\n\s*$/, '')
+ .split('\n')
+ const lineIndents =
+ lines
+ .filter((line) => line.trim())
+ .map((line) => line.match(/ */)[0].length)
const minLineIndent = Math.min.apply(null, lineIndents)
return lines.map((line) => line.slice(minLineIndent)).join('\n')
diff --git ORI/eslint-plugin-vue/tests/lib/rules/script-indent.js ALT/eslint-plugin-vue/tests/lib/rules/script-indent.js
index 865e731..cbe90f2 100644
--- ORI/eslint-plugin-vue/tests/lib/rules/script-indent.js
+++ ALT/eslint-plugin-vue/tests/lib/rules/script-indent.js
@@ -51,36 +51,41 @@ function loadPatterns(additionalValid, additionalInvalid) {
}
return Object.assign(baseObj, { code, filename })
})
- const invalid = valid
- .map((pattern) => {
- const kind =
- (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
- const output = pattern.code
- const lines = output.split('\n').map((text, number) => ({
- number,
- text,
- indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
- }))
- const code = lines
- .map((line) => line.text.replace(/^[ \t]+/, ''))
- .join('\n')
- const errors = lines
- .map((line) =>
- line.indentSize === 0
- ? null
- : {
- message: `Expected indentation of ${line.indentSize} ${kind}${
- line.indentSize === 1 ? '' : 's'
- } but found 0 ${kind}s.`,
- line: line.number + 1
- }
- )
- .filter(Boolean)
+ const invalid =
+ valid
+ .map((pattern) => {
+ const kind =
+ (pattern.options && pattern.options[0]) === 'tab' ? 'tab' : 'space'
+ const output = pattern.code
+ const lines = output.split('\n').map((text, number) => ({
+ number,
+ text,
+ indentSize: (/^[ \t]+/.exec(text) || [''])[0].length
+ }))
+ const code =
+ lines
+ .map((line) => line.text.replace(/^[ \t]+/, ''))
+ .join('\n')
+ const errors =
+ lines
+ .map((line) =>
+ line.indentSize === 0
+ ? null
+ : {
+ message: `Expected indentation of ${
+ line.indentSize
+ } ${kind}${
+ line.indentSize === 1 ? '' : 's'
+ } but found 0 ${kind}s.`,
+ line: line.number + 1
+ }
+ )
+ .filter(Boolean)
- return Object.assign({}, pattern, { code, output, errors })
- })
- .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
- .filter(Boolean)
+ return Object.assign({}, pattern, { code, output, errors })
+ })
+ .filter((invalid) => invalid.errors.length > 0) // Empty errors cannot be verified with eslint 7.3.
+ .filter(Boolean)
return {
valid: valid.concat(additionalValid),
@@ -95,13 +100,15 @@ function loadPatterns(additionalValid, additionalInvalid) {
*/
function unIndent(strings) {
const templateValue = strings[0]
- const lines = templateValue
- .replace(/^\n/, '')
- .replace(/\n\s*$/, '')
- .split('\n')
- const lineIndents = lines
- .filter((line) => line.trim())
- .map((line) => line.match(/ */)[0].length)
+ const lines =
+ templateValue
+ .replace(/^\n/, '')
+ .replace(/\n\s*$/, '')
+ .split('\n')
+ const lineIndents =
+ lines
+ .filter((line) => line.trim())
+ .map((line) => line.match(/ */)[0].length)
const minLineIndent = Math.min.apply(null, lineIndents)
return lines.map((line) => line.slice(minLineIndent)).join('\n')
diff --git ORI/eslint-plugin-vue/tests/lib/rules/this-in-template.js ALT/eslint-plugin-vue/tests/lib/rules/this-in-template.js
index 5f36b57..00b174a 100644
--- ORI/eslint-plugin-vue/tests/lib/rules/this-in-template.js
+++ ALT/eslint-plugin-vue/tests/lib/rules/this-in-template.js
@@ -185,41 +185,43 @@ function createInvalidTests(prefix, options, message, type) {
}
ruleTester.run('this-in-template', rule, {
- valid: ['', '<template></template>', '<template><div></div></template>']
- .concat(createValidTests('', []))
- .concat(createValidTests('', ['never']))
- .concat(createValidTests('this.', ['always']))
- .concat(createValidTests('this?.', ['always'])),
- invalid: []
- .concat(
- createInvalidTests(
- 'this.',
- [],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
- ),
- createInvalidTests(
- 'this?.',
- [],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
+ valid:
+ ['', '<template></template>', '<template><div></div></template>']
+ .concat(createValidTests('', []))
+ .concat(createValidTests('', ['never']))
+ .concat(createValidTests('this.', ['always']))
+ .concat(createValidTests('this?.', ['always'])),
+ invalid:
+ []
+ .concat(
+ createInvalidTests(
+ 'this.',
+ [],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ ),
+ createInvalidTests(
+ 'this?.',
+ [],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ )
)
- )
- .concat(
- createInvalidTests(
- 'this.',
- ['never'],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
- ),
- createInvalidTests(
- 'this?.',
- ['never'],
- "Unexpected usage of 'this'.",
- 'ThisExpression'
+ .concat(
+ createInvalidTests(
+ 'this.',
+ ['never'],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ ),
+ createInvalidTests(
+ 'this?.',
+ ['never'],
+ "Unexpected usage of 'this'.",
+ 'ThisExpression'
+ )
+ )
+ .concat(
+ createInvalidTests('', ['always'], "Expected 'this'.", 'Identifier')
)
- )
- .concat(
- createInvalidTests('', ['always'], "Expected 'this'.", 'Identifier')
- )
})
diff --git ORI/eslint-plugin-vue/tests/lib/utils/vue-component.js ALT/eslint-plugin-vue/tests/lib/utils/vue-component.js
index 91da3d2..0845ea4 100644
--- ORI/eslint-plugin-vue/tests/lib/utils/vue-component.js
+++ ALT/eslint-plugin-vue/tests/lib/utils/vue-component.js
@@ -327,31 +327,33 @@ function invalidTests(ext) {
const ruleTester = new RuleTester()
ruleTester.run('vue-component', rule, {
- valid: [
- {
- filename: 'test.js',
- code: `export default { }`,
- parserOptions
- }
- ]
- .concat(validTests('js'))
- .concat(validTests('jsx'))
- .concat(validTests('vue')),
- invalid: [
- {
- filename: 'test.vue',
- code: `export default { }`,
- parserOptions,
- errors: [makeError(1)]
- },
- {
- filename: 'test.jsx',
- code: `export default { }`,
- parserOptions,
- errors: [makeError(1)]
- }
- ]
- .concat(invalidTests('js'))
- .concat(invalidTests('jsx'))
- .concat(invalidTests('vue'))
+ valid:
+ [
+ {
+ filename: 'test.js',
+ code: `export default { }`,
+ parserOptions
+ }
+ ]
+ .concat(validTests('js'))
+ .concat(validTests('jsx'))
+ .concat(validTests('vue')),
+ invalid:
+ [
+ {
+ filename: 'test.vue',
+ code: `export default { }`,
+ parserOptions,
+ errors: [makeError(1)]
+ },
+ {
+ filename: 'test.jsx',
+ code: `export default { }`,
+ parserOptions,
+ errors: [makeError(1)]
+ }
+ ]
+ .concat(invalidTests('js'))
+ .concat(invalidTests('jsx'))
+ .concat(invalidTests('vue'))
})
diff --git ORI/eslint-plugin-vue/tools/lib/categories.js ALT/eslint-plugin-vue/tools/lib/categories.js
index 9f7fd79..6f96b6f 100644
--- ORI/eslint-plugin-vue/tools/lib/categories.js
+++ ALT/eslint-plugin-vue/tools/lib/categories.js
@@ -75,12 +75,13 @@ for (const rule of rules) {
}
}
-module.exports = categoryIds
- .map((categoryId) => ({
- categoryId,
- title: categoryTitles[categoryId],
- rules: (categoryRules[categoryId] || []).filter(
- (rule) => !rule.meta.deprecated
- )
- }))
- .filter((category) => category.rules.length >= 1)
+module.exports =
+ categoryIds
+ .map((categoryId) => ({
+ categoryId,
+ title: categoryTitles[categoryId],
+ rules: (categoryRules[categoryId] || []).filter(
+ (rule) => !rule.meta.deprecated
+ )
+ }))
+ .filter((category) => category.rules.length >= 1)
diff --git ORI/eslint-plugin-vue/tools/lib/configs.js ALT/eslint-plugin-vue/tools/lib/configs.js
index 031f41e..14cc8c5 100644
--- ORI/eslint-plugin-vue/tools/lib/configs.js
+++ ALT/eslint-plugin-vue/tools/lib/configs.js
@@ -9,7 +9,8 @@ const fs = require('fs')
const path = require('path')
const ROOT = path.resolve(__dirname, '../../lib/configs')
-module.exports = fs
- .readdirSync(ROOT)
- .filter((file) => path.extname(file) === '.js')
- .map((file) => path.basename(file, '.js'))
+module.exports =
+ fs
+ .readdirSync(ROOT)
+ .filter((file) => path.extname(file) === '.js')
+ .map((file) => path.basename(file, '.js'))
diff --git ORI/eslint-plugin-vue/tools/lib/rules.js ALT/eslint-plugin-vue/tools/lib/rules.js
index 745c635..27f4be5 100644
--- ORI/eslint-plugin-vue/tools/lib/rules.js
+++ ALT/eslint-plugin-vue/tools/lib/rules.js
@@ -9,20 +9,21 @@ const fs = require('fs')
const path = require('path')
const ROOT = path.resolve(__dirname, '../../lib/rules')
-module.exports = fs
- .readdirSync(ROOT)
- .filter((file) => path.extname(file) === '.js')
- .map((file) => path.basename(file, '.js'))
- .map((name) => {
- const meta = { ...require(path.join(ROOT, name)).meta }
- if (meta.docs && !meta.docs.categories && meta.docs.category) {
- // for vue3 migration
- meta.docs = { ...meta.docs }
- meta.docs.categories = [meta.docs.category]
- }
- return {
- ruleId: `vue/${name}`,
- name,
- meta
- }
- })
+module.exports =
+ fs
+ .readdirSync(ROOT)
+ .filter((file) => path.extname(file) === '.js')
+ .map((file) => path.basename(file, '.js'))
+ .map((name) => {
+ const meta = { ...require(path.join(ROOT, name)).meta }
+ if (meta.docs && !meta.docs.categories && meta.docs.category) {
+ // for vue3 migration
+ meta.docs = { ...meta.docs }
+ meta.docs.categories = [meta.docs.category]
+ }
+ return {
+ ruleId: `vue/${name}`,
+ name,
+ meta
+ }
+ })
diff --git ORI/eslint-plugin-vue/tools/update-docs-rules-index.js ALT/eslint-plugin-vue/tools/update-docs-rules-index.js
index 6e9c0f0..cf7d66e 100644
--- ORI/eslint-plugin-vue/tools/update-docs-rules-index.js
+++ ALT/eslint-plugin-vue/tools/update-docs-rules-index.js
@@ -37,17 +37,19 @@ function toRuleRow(rule) {
function toDeprecatedRuleRow(rule) {
const link = `[${rule.ruleId}](./${rule.name}.md)`
const replacedRules = rule.meta.docs.replacedBy || []
- const replacedBy = replacedRules
- .map((name) => `[vue/${name}](./${name}.md)`)
- .join(', ')
+ const replacedBy =
+ replacedRules
+ .map((name) => `[vue/${name}](./${name}.md)`)
+ .join(', ')
return `| ${link} | ${replacedBy || '(no replacement)'} |`
}
// -----------------------------------------------------------------------------
-let rulesTableContent = categories
- .map(
- (category) => `
+let rulesTableContent =
+ categories
+ .map(
+ (category) => `
## ${category.title.vuepress}
Enforce all the rules in this category, as well as all higher priority rules, with:
@@ -62,8 +64,8 @@ Enforce all the rules in this category, as well as all higher priority rules, wi
|:--------|:------------|:---|
${category.rules.map(toRuleRow).join('\n')}
`
- )
- .join('')
+ )
+ .join('')
// -----------------------------------------------------------------------------
if (uncategorizedRules.length || uncategorizedExtensionRule.length) {
diff --git ORI/prettier/scripts/build/cache.js ALT/prettier/scripts/build/cache.js
index 8f7b5c961..5a40389b6 100644
--- ORI/prettier/scripts/build/cache.js
+++ ALT/prettier/scripts/build/cache.js
@@ -67,9 +67,10 @@ class Cache {
const bundle = await rollup(getRollupConfig(inputOptions));
const { output } = await bundle.generate(outputOptions);
- const modules = output
- .filter((mod) => !/\0/.test(mod.facadeModuleId))
- .map((mod) => [path.relative(ROOT, mod.facadeModuleId), mod.code]);
+ const modules =
+ output
+ .filter((mod) => !/\0/.test(mod.facadeModuleId))
+ .map((mod) => [path.relative(ROOT, mod.facadeModuleId), mod.code]);
for (const [id, code] of modules) {
newFiles.push(id);
diff --git ORI/prettier/scripts/draft-blog-post.js ALT/prettier/scripts/draft-blog-post.js
index eca419567..06997825b 100644
--- ORI/prettier/scripts/draft-blog-post.js
+++ ALT/prettier/scripts/draft-blog-post.js
@@ -51,9 +51,10 @@ const categoriesByDir = categories.reduce((result, category) => {
return result;
}, {});
-const dirs = fs
- .readdirSync(changelogUnreleasedDir, { withFileTypes: true })
- .filter((entry) => entry.isDirectory());
+const dirs =
+ fs
+ .readdirSync(changelogUnreleasedDir, { withFileTypes: true })
+ .filter((entry) => entry.isDirectory());
for (const dir of dirs) {
const dirPath = path.join(changelogUnreleasedDir, dir.name);
@@ -63,20 +64,22 @@ for (const dir of dirs) {
throw new Error("Unknown category: " + dir.name);
}
- category.entries = fs
- .readdirSync(dirPath)
- .filter((fileName) => /^\d+\.md$/.test(fileName))
- .map((fileName) => {
- const [title, ...rest] = fs
- .readFileSync(path.join(dirPath, fileName), "utf8")
- .trim()
- .split("\n");
- return {
- breaking: title.includes("[BREAKING]"),
- highlight: title.includes("[HIGHLIGHT]"),
- content: [processTitle(title), ...rest].join("\n"),
- };
- });
+ category.entries =
+ fs
+ .readdirSync(dirPath)
+ .filter((fileName) => /^\d+\.md$/.test(fileName))
+ .map((fileName) => {
+ const [title, ...rest] =
+ fs
+ .readFileSync(path.join(dirPath, fileName), "utf8")
+ .trim()
+ .split("\n");
+ return {
+ breaking: title.includes("[BREAKING]"),
+ highlight: title.includes("[HIGHLIGHT]"),
+ content: [processTitle(title), ...rest].join("\n"),
+ };
+ });
}
rimraf.sync(postGlob);
diff --git ORI/prettier/scripts/release/release.js ALT/prettier/scripts/release/release.js
index f063191be..feacf9a1a 100644
--- ORI/prettier/scripts/release/release.js
+++ ALT/prettier/scripts/release/release.js
@@ -18,9 +18,10 @@ async function run() {
alias: { v: "version" },
});
- const previousVersion = execSync("git describe --tags --abbrev=0")
- .toString()
- .trim();
+ const previousVersion =
+ execSync("git describe --tags --abbrev=0")
+ .toString()
+ .trim();
if (semver.parse(previousVersion) === null) {
throw new Error(`Unexpected previousVersion: ${previousVersion}`);
diff --git ORI/prettier/src/cli/expand-patterns.js ALT/prettier/src/cli/expand-patterns.js
index b840ce723..f130df44d 100644
--- ORI/prettier/src/cli/expand-patterns.js
+++ ALT/prettier/src/cli/expand-patterns.js
@@ -55,9 +55,10 @@ function* expandPatternsInternal(context) {
const globOptions = {
dot: true,
- ignore: Object.entries(silentlyIgnoredDirs)
- .filter(([, ignored]) => ignored)
- .map(([dir]) => "**/" + dir),
+ ignore:
+ Object.entries(silentlyIgnoredDirs)
+ .filter(([, ignored]) => ignored)
+ .map(([dir]) => "**/" + dir),
};
let supportedFilesGlob;
diff --git ORI/prettier/src/cli/usage.js ALT/prettier/src/cli/usage.js
index 2685b3bc6..3ce552a82 100644
--- ORI/prettier/src/cli/usage.js
+++ ALT/prettier/src/cli/usage.js
@@ -140,11 +140,12 @@ function createUsage(context) {
];
const optionsUsage = allCategories.map((category) => {
- const categoryOptions = groupedOptions[category]
- .map((option) =>
- createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)
- )
- .join("\n");
+ const categoryOptions =
+ groupedOptions[category]
+ .map((option) =>
+ createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)
+ )
+ .join("\n");
return `${category} options:\n\n${indent(categoryOptions, 2)}`;
});
diff --git ORI/prettier/src/document/doc-printer.js ALT/prettier/src/document/doc-printer.js
index 5e2558f1a..3769f4f1a 100644
--- ORI/prettier/src/document/doc-printer.js
+++ ALT/prettier/src/document/doc-printer.js
@@ -546,9 +546,10 @@ function printDocToString(doc, options) {
cursorPlaceholderIndex + 1
);
const beforeCursor = out.slice(0, cursorPlaceholderIndex).join("");
- const aroundCursor = out
- .slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex)
- .join("");
+ const aroundCursor =
+ out
+ .slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex)
+ .join("");
const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join("");
return {
diff --git ORI/prettier/src/language-handlebars/printer-glimmer.js ALT/prettier/src/language-handlebars/printer-glimmer.js
index fccfa2dea..e0d17fde6 100644
--- ORI/prettier/src/language-handlebars/printer-glimmer.js
+++ ALT/prettier/src/language-handlebars/printer-glimmer.js
@@ -406,14 +406,15 @@ function print(path, options, print) {
function printStartingTag(path, print) {
const node = path.getValue();
- const attributesLike = ["attributes", "modifiers", "comments", "blockParams"]
- .filter((property) => isNonEmptyArray(node[property]))
- .map((property) => [
- line,
- property === "blockParams"
- ? printBlockParams(node)
- : join(line, path.map(print, property)),
- ]);
+ const attributesLike =
+ ["attributes", "modifiers", "comments", "blockParams"]
+ .filter((property) => isNonEmptyArray(node[property]))
+ .map((property) => [
+ line,
+ property === "blockParams"
+ ? printBlockParams(node)
+ : join(line, path.map(print, property)),
+ ]);
return [
"<",
diff --git ORI/prettier/src/language-html/parser-html.js ALT/prettier/src/language-html/parser-html.js
index 748c3cf7a..a407c41a9 100644
--- ORI/prettier/src/language-html/parser-html.js
+++ ALT/prettier/src/language-html/parser-html.js
@@ -196,9 +196,10 @@ function ngHtmlParser(
}
}
} else if (node instanceof Comment) {
- node.value = node.sourceSpan
- .toString()
- .slice("<!--".length, -"-->".length);
+ node.value =
+ node.sourceSpan
+ .toString()
+ .slice("<!--".length, -"-->".length);
} else if (node instanceof Text) {
node.value = node.sourceSpan.toString();
}
diff --git ORI/prettier/src/language-html/print-preprocess.js ALT/prettier/src/language-html/print-preprocess.js
index 600947b77..25d831b9e 100644
--- ORI/prettier/src/language-html/print-preprocess.js
+++ ALT/prettier/src/language-html/print-preprocess.js
@@ -327,60 +327,61 @@ function extractWhitespaces(ast /*, options*/) {
return node.clone({
isWhitespaceSensitive,
isIndentationSensitive,
- children: node.children
- // extract whitespace nodes
- .reduce((newChildren, child) => {
- if (child.type !== "text" || isWhitespaceSensitive) {
- return [...newChildren, child];
- }
-
- const localChildren = [];
-
- const { leadingWhitespace, text, trailingWhitespace } =
- getLeadingAndTrailingHtmlWhitespace(child.value);
-
- if (leadingWhitespace) {
- localChildren.push({ type: TYPE_WHITESPACE });
- }
-
- if (text) {
- localChildren.push({
- type: "text",
- value: text,
- sourceSpan: new ParseSourceSpan(
- child.sourceSpan.start.moveBy(leadingWhitespace.length),
- child.sourceSpan.end.moveBy(-trailingWhitespace.length)
- ),
- });
- }
-
- if (trailingWhitespace) {
- localChildren.push({ type: TYPE_WHITESPACE });
- }
-
- return [...newChildren, ...localChildren];
- }, [])
- // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
- .reduce((newChildren, child, i, children) => {
- if (child.type === TYPE_WHITESPACE) {
- return newChildren;
- }
-
- const hasLeadingSpaces =
- i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
- const hasTrailingSpaces =
- i !== children.length - 1 &&
- children[i + 1].type === TYPE_WHITESPACE;
-
- return [
- ...newChildren,
- {
- ...child,
- hasLeadingSpaces,
- hasTrailingSpaces,
- },
- ];
- }, []),
+ children:
+ node.children
+ // extract whitespace nodes
+ .reduce((newChildren, child) => {
+ if (child.type !== "text" || isWhitespaceSensitive) {
+ return [...newChildren, child];
+ }
+
+ const localChildren = [];
+
+ const { leadingWhitespace, text, trailingWhitespace } =
+ getLeadingAndTrailingHtmlWhitespace(child.value);
+
+ if (leadingWhitespace) {
+ localChildren.push({ type: TYPE_WHITESPACE });
+ }
+
+ if (text) {
+ localChildren.push({
+ type: "text",
+ value: text,
+ sourceSpan: new ParseSourceSpan(
+ child.sourceSpan.start.moveBy(leadingWhitespace.length),
+ child.sourceSpan.end.moveBy(-trailingWhitespace.length)
+ ),
+ });
+ }
+
+ if (trailingWhitespace) {
+ localChildren.push({ type: TYPE_WHITESPACE });
+ }
+
+ return [...newChildren, ...localChildren];
+ }, [])
+ // set hasLeadingSpaces/hasTrailingSpaces and filter whitespace nodes
+ .reduce((newChildren, child, i, children) => {
+ if (child.type === TYPE_WHITESPACE) {
+ return newChildren;
+ }
+
+ const hasLeadingSpaces =
+ i !== 0 && children[i - 1].type === TYPE_WHITESPACE;
+ const hasTrailingSpaces =
+ i !== children.length - 1 &&
+ children[i + 1].type === TYPE_WHITESPACE;
+
+ return [
+ ...newChildren,
+ {
+ ...child,
+ hasLeadingSpaces,
+ hasTrailingSpaces,
+ },
+ ];
+ }, []),
});
});
}
@@ -439,28 +440,32 @@ function addIsSpaceSensitive(ast, options) {
}
return node.clone({
- children: node.children
- .map((child) => ({
- ...child,
- isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(child, options),
- isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(
- child,
- options
- ),
- }))
- .map((child, index, children) => ({
- ...child,
- isLeadingSpaceSensitive:
- index === 0
- ? child.isLeadingSpaceSensitive
- : children[index - 1].isTrailingSpaceSensitive &&
- child.isLeadingSpaceSensitive,
- isTrailingSpaceSensitive:
- index === children.length - 1
- ? child.isTrailingSpaceSensitive
- : children[index + 1].isLeadingSpaceSensitive &&
- child.isTrailingSpaceSensitive,
- })),
+ children:
+ node.children
+ .map((child) => ({
+ ...child,
+ isLeadingSpaceSensitive: isLeadingSpaceSensitiveNode(
+ child,
+ options
+ ),
+ isTrailingSpaceSensitive: isTrailingSpaceSensitiveNode(
+ child,
+ options
+ ),
+ }))
+ .map((child, index, children) => ({
+ ...child,
+ isLeadingSpaceSensitive:
+ index === 0
+ ? child.isLeadingSpaceSensitive
+ : children[index - 1].isTrailingSpaceSensitive &&
+ child.isLeadingSpaceSensitive,
+ isTrailingSpaceSensitive:
+ index === children.length - 1
+ ? child.isTrailingSpaceSensitive
+ : children[index + 1].isLeadingSpaceSensitive &&
+ child.isTrailingSpaceSensitive,
+ })),
});
});
}
diff --git ORI/prettier/src/language-html/syntax-attribute.js ALT/prettier/src/language-html/syntax-attribute.js
index 3180ae3b2..e37ba122d 100644
--- ORI/prettier/src/language-html/syntax-attribute.js
+++ ALT/prettier/src/language-html/syntax-attribute.js
@@ -30,9 +30,10 @@ function printImgSrcset(value) {
const urls = srcset.map((src) => src.url);
const maxUrlLength = getMax(urls.map((url) => url.length));
- const descriptors = srcset
- .map((src) => src[key])
- .map((descriptor) => (descriptor ? descriptor.toString() : ""));
+ const descriptors =
+ srcset
+ .map((src) => src[key])
+ .map((descriptor) => (descriptor ? descriptor.toString() : ""));
const descriptorLeftLengths = descriptors.map((descriptor) => {
const index = descriptor.indexOf(".");
return index === -1 ? descriptor.length : index;
diff --git ORI/prettier/src/language-js/embed/html.js ALT/prettier/src/language-js/embed/html.js
index cb2e41306..4e0b11d02 100644
--- ORI/prettier/src/language-js/embed/html.js
+++ ALT/prettier/src/language-js/embed/html.js
@@ -19,13 +19,14 @@ function format(path, print, textToDoc, options, { parser }) {
const composePlaceholder = (index) =>
`PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`;
- const text = node.quasis
- .map((quasi, index, quasis) =>
- index === quasis.length - 1
- ? quasi.value.cooked
- : quasi.value.cooked + composePlaceholder(index)
- )
- .join("");
+ const text =
+ node.quasis
+ .map((quasi, index, quasis) =>
+ index === quasis.length - 1
+ ? quasi.value.cooked
+ : quasi.value.cooked + composePlaceholder(index)
+ )
+ .join("");
const expressionDocs = printTemplateExpressions(path, print);
if (expressionDocs.length === 0 && text.trim().length === 0) {
diff --git ORI/prettier/src/language-js/print/member-chain.js ALT/prettier/src/language-js/print/member-chain.js
index b12c6c191..baf115b34 100644
--- ORI/prettier/src/language-js/print/member-chain.js
+++ ALT/prettier/src/language-js/print/member-chain.js
@@ -360,9 +360,10 @@ function printMemberChain(path, options, print) {
printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)),
];
- const callExpressions = printedNodes
- .map(({ node }) => node)
- .filter(isCallOrOptionalCallExpression);
+ const callExpressions =
+ printedNodes
+ .map(({ node }) => node)
+ .filter(isCallOrOptionalCallExpression);
function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() {
const lastGroupNode = getLast(getLast(groups)).node;
diff --git ORI/prettier/src/language-js/print/object.js ALT/prettier/src/language-js/print/object.js
index c8ff9dc45..b1c3d3223 100644
--- ORI/prettier/src/language-js/print/object.js
+++ ALT/prettier/src/language-js/print/object.js
@@ -110,24 +110,25 @@ function printObject(path, options, print) {
/** @type {Doc[]} */
let separatorParts = [];
- const props = propsAndLoc
- .sort((a, b) => a.loc - b.loc)
- .map((prop) => {
- const result = [...separatorParts, group(prop.printed)];
- separatorParts = [separator, line];
- if (
- (prop.node.type === "TSPropertySignature" ||
- prop.node.type === "TSMethodSignature" ||
- prop.node.type === "TSConstructSignatureDeclaration") &&
- hasComment(prop.node, CommentCheckFlags.PrettierIgnore)
- ) {
- separatorParts.shift();
- }
- if (isNextLineEmpty(prop.node, options)) {
- separatorParts.push(hardline);
- }
- return result;
- });
+ const props =
+ propsAndLoc
+ .sort((a, b) => a.loc - b.loc)
+ .map((prop) => {
+ const result = [...separatorParts, group(prop.printed)];
+ separatorParts = [separator, line];
+ if (
+ (prop.node.type === "TSPropertySignature" ||
+ prop.node.type === "TSMethodSignature" ||
+ prop.node.type === "TSConstructSignatureDeclaration") &&
+ hasComment(prop.node, CommentCheckFlags.PrettierIgnore)
+ ) {
+ separatorParts.shift();
+ }
+ if (isNextLineEmpty(prop.node, options)) {
+ separatorParts.push(hardline);
+ }
+ return result;
+ });
if (n.inexact) {
let printed;
diff --git ORI/prettier/src/language-js/printer-estree.js ALT/prettier/src/language-js/printer-estree.js
index a2fc6dbd5..df8ef9578 100644
--- ORI/prettier/src/language-js/printer-estree.js
+++ ALT/prettier/src/language-js/printer-estree.js
@@ -1034,9 +1034,10 @@ function printPathNoParens(path, options, print, args) {
const commentStartIndex = options.originalText.lastIndexOf("/*", start);
const commentEndIndex = options.originalText.indexOf("*/", end);
if (commentStartIndex !== -1 && commentEndIndex !== -1) {
- const comment = options.originalText
- .slice(commentStartIndex + 2, commentEndIndex)
- .trim();
+ const comment =
+ options.originalText
+ .slice(commentStartIndex + 2, commentEndIndex)
+ .trim();
if (
comment.startsWith("::") &&
!comment.includes("/*") &&
diff --git ORI/prettier/src/language-markdown/clean.js ALT/prettier/src/language-markdown/clean.js
index 869eef9dd..fffd2e578 100644
--- ORI/prettier/src/language-markdown/clean.js
+++ ALT/prettier/src/language-markdown/clean.js
@@ -43,10 +43,11 @@ function clean(ast, newObj, parent) {
}
if (ast.type === "definition" || ast.type === "linkReference") {
- newObj.label = ast.label
- .trim()
- .replace(/[\t\n ]+/g, " ")
- .toLowerCase();
+ newObj.label =
+ ast.label
+ .trim()
+ .replace(/[\t\n ]+/g, " ")
+ .toLowerCase();
}
if (
diff --git ORI/prettier/src/language-markdown/constants.evaluate.js ALT/prettier/src/language-markdown/constants.evaluate.js
index 45c799f9e..024d46b41 100644
--- ORI/prettier/src/language-markdown/constants.evaluate.js
+++ ALT/prettier/src/language-markdown/constants.evaluate.js
@@ -22,9 +22,10 @@ const cjkPattern = `(?:${cjkRegex()
Block: ["Variation_Selectors", "Variation_Selectors_Supplement"],
}).toString()})?`;
-const kPattern = unicodeRegex({ Script: ["Hangul"] })
- .union(unicodeRegex({ Script_Extensions: ["Hangul"] }))
- .toString();
+const kPattern =
+ unicodeRegex({ Script: ["Hangul"] })
+ .union(unicodeRegex({ Script_Extensions: ["Hangul"] }))
+ .toString();
// http://spec.commonmark.org/0.25/#ascii-punctuation-character
const asciiPunctuationCharset =
diff --git ORI/prettier/src/language-markdown/parser-markdown.js ALT/prettier/src/language-markdown/parser-markdown.js
index 494b77977..d7120cfbe 100644
--- ORI/prettier/src/language-markdown/parser-markdown.js
+++ ALT/prettier/src/language-markdown/parser-markdown.js
@@ -26,19 +26,20 @@ const mdx = require("./mdx");
*/
function createParse({ isMDX }) {
return (text) => {
- const processor = unified()
- .use(remarkParse, {
- commonmark: true,
- ...(isMDX && { blocks: [mdx.BLOCKS_REGEX] }),
- })
- .use(footnotes)
- .use(frontMatter)
- .use(remarkMath)
- .use(isMDX ? mdx.esSyntax : identity)
- .use(liquid)
- .use(isMDX ? htmlToJsx : identity)
- .use(wikiLink)
- .use(looseItems);
+ const processor =
+ unified()
+ .use(remarkParse, {
+ commonmark: true,
+ ...(isMDX && { blocks: [mdx.BLOCKS_REGEX] }),
+ })
+ .use(footnotes)
+ .use(frontMatter)
+ .use(remarkMath)
+ .use(isMDX ? mdx.esSyntax : identity)
+ .use(liquid)
+ .use(isMDX ? htmlToJsx : identity)
+ .use(wikiLink)
+ .use(looseItems);
return processor.runSync(processor.parse(text));
};
}
diff --git ORI/prettier/src/language-markdown/printer-markdown.js ALT/prettier/src/language-markdown/printer-markdown.js
index 179132dc2..34b6c2eb8 100644
--- ORI/prettier/src/language-markdown/printer-markdown.js
+++ ALT/prettier/src/language-markdown/printer-markdown.js
@@ -96,22 +96,23 @@ function genericPrint(path, options, print) {
case "sentence":
return printChildren(path, options, print);
case "word": {
- let escapedValue = node.value
- .replace(/\*/g, "\\$&") // escape all `*`
- .replace(
- new RegExp(
- [
- `(^|${punctuationPattern})(_+)`,
- `(_+)(${punctuationPattern}|$)`,
- ].join("|"),
- "g"
- ),
- (_, text1, underscore1, underscore2, text2) =>
- (underscore1
- ? `${text1}${underscore1}`
- : `${underscore2}${text2}`
- ).replace(/_/g, "\\_")
- ); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
+ let escapedValue =
+ node.value
+ .replace(/\*/g, "\\$&") // escape all `*`
+ .replace(
+ new RegExp(
+ [
+ `(^|${punctuationPattern})(_+)`,
+ `(_+)(${punctuationPattern}|$)`,
+ ].join("|"),
+ "g"
+ ),
+ (_, text1, underscore1, underscore2, text2) =>
+ (underscore1
+ ? `${text1}${underscore1}`
+ : `${underscore2}${text2}`
+ ).replace(/_/g, "\\_")
+ ); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis
const isFirstSentence = (node, name, index) =>
node.type === "sentence" && index === 0;
diff --git ORI/prettier/src/language-markdown/utils.js ALT/prettier/src/language-markdown/utils.js
index 4b7d2608e..926ca0f06 100644
--- ORI/prettier/src/language-markdown/utils.js
+++ ALT/prettier/src/language-markdown/utils.js
@@ -153,12 +153,13 @@ function splitText(text, options) {
}
function getOrderedListItemInfo(orderListItem, originalText) {
- const [, numberText, marker, leadingSpaces] = originalText
- .slice(
- orderListItem.position.start.offset,
- orderListItem.position.end.offset
- )
- .match(/^\s*(\d+)(\.|\))(\s*)/);
+ const [, numberText, marker, leadingSpaces] =
+ originalText
+ .slice(
+ orderListItem.position.start.offset,
+ orderListItem.position.end.offset
+ )
+ .match(/^\s*(\d+)(\.|\))(\s*)/);
return { numberText, marker, leadingSpaces };
}
diff --git ORI/prettier/src/language-yaml/utils.js ALT/prettier/src/language-yaml/utils.js
index 2151c65bc..fef001f74 100644
--- ORI/prettier/src/language-yaml/utils.js
+++ ALT/prettier/src/language-yaml/utils.js
@@ -193,17 +193,18 @@ function splitWithSingleSpace(text) {
}
function getFlowScalarLineContents(nodeType, content, options) {
- const rawLineContents = content
- .split("\n")
- .map((lineContent, index, lineContents) =>
- index === 0 && index === lineContents.length - 1
- ? lineContent
- : index !== 0 && index !== lineContents.length - 1
- ? lineContent.trim()
- : index === 0
- ? lineContent.trimEnd()
- : lineContent.trimStart()
- );
+ const rawLineContents =
+ content
+ .split("\n")
+ .map((lineContent, index, lineContents) =>
+ index === 0 && index === lineContents.length - 1
+ ? lineContent
+ : index !== 0 && index !== lineContents.length - 1
+ ? lineContent.trim()
+ : index === 0
+ ? lineContent.trimEnd()
+ : lineContent.trimStart()
+ );
if (options.proseWrap === "preserve") {
return rawLineContents.map((lineContent) =>
@@ -260,9 +261,10 @@ function getBlockValueLineContents(
)
: node.indent - 1 + parentIndent;
- const rawLineContents = content
- .split("\n")
- .map((lineContent) => lineContent.slice(leadingSpaceCount));
+ const rawLineContents =
+ content
+ .split("\n")
+ .map((lineContent) => lineContent.slice(leadingSpaceCount));
if (options.proseWrap === "preserve" || node.type === "blockLiteral") {
return removeUnnecessaryTrailingNewlines(
diff --git ORI/prettier/src/main/options.js ALT/prettier/src/main/options.js
index a12b5bcad..fbd13b464 100644
--- ORI/prettier/src/main/options.js
+++ ALT/prettier/src/main/options.js
@@ -68,19 +68,20 @@ function normalize(options, opts = {}) {
const plugin = getPlugin(rawOptions);
rawOptions.printer = plugin.printers[rawOptions.astFormat];
- const pluginDefaults = supportOptions
- .filter(
- (optionInfo) =>
- optionInfo.pluginDefaults &&
- optionInfo.pluginDefaults[plugin.name] !== undefined
- )
- .reduce(
- (reduced, optionInfo) =>
- Object.assign(reduced, {
- [optionInfo.name]: optionInfo.pluginDefaults[plugin.name],
- }),
- {}
- );
+ const pluginDefaults =
+ supportOptions
+ .filter(
+ (optionInfo) =>
+ optionInfo.pluginDefaults &&
+ optionInfo.pluginDefaults[plugin.name] !== undefined
+ )
+ .reduce(
+ (reduced, optionInfo) =>
+ Object.assign(reduced, {
+ [optionInfo.name]: optionInfo.pluginDefaults[plugin.name],
+ }),
+ {}
+ );
const mixedDefaults = { ...defaults, ...pluginDefaults };
diff --git ORI/prettier/src/main/support.js ALT/prettier/src/main/support.js
index a6aa0d83f..37c9b567c 100644
--- ORI/prettier/src/main/support.js
+++ ALT/prettier/src/main/support.js
@@ -29,54 +29,57 @@ function getSupportInfo({
// we need to treat it as the normal one so as to test new features.
const version = currentVersion.split("-", 1)[0];
- const languages = plugins
- .reduce((all, plugin) => [...all, ...(plugin.languages || [])], [])
- .filter(filterSince);
+ const languages =
+ plugins
+ .reduce((all, plugin) => [...all, ...(plugin.languages || [])], [])
+ .filter(filterSince);
- const options = arrayify(
- Object.assign({}, ...plugins.map(({ options }) => options), coreOptions),
- "name"
- )
- .filter((option) => filterSince(option) && filterDeprecated(option))
- .sort((a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1))
- .map(mapInternal)
- .map((option) => {
- option = { ...option };
+ const options =
+ arrayify(
+ Object.assign({}, ...plugins.map(({ options }) => options), coreOptions),
+ "name"
+ )
+ .filter((option) => filterSince(option) && filterDeprecated(option))
+ .sort((a, b) => (a.name === b.name ? 0 : a.name < b.name ? -1 : 1))
+ .map(mapInternal)
+ .map((option) => {
+ option = { ...option };
- if (Array.isArray(option.default)) {
- option.default =
- option.default.length === 1
- ? option.default[0].value
- : option.default
- .filter(filterSince)
- .sort((info1, info2) =>
- semver.compare(info2.since, info1.since)
- )[0].value;
- }
+ if (Array.isArray(option.default)) {
+ option.default =
+ option.default.length === 1
+ ? option.default[0].value
+ : option.default
+ .filter(filterSince)
+ .sort((info1, info2) =>
+ semver.compare(info2.since, info1.since)
+ )[0].value;
+ }
- if (Array.isArray(option.choices)) {
- option.choices = option.choices.filter(
- (option) => filterSince(option) && filterDeprecated(option)
- );
+ if (Array.isArray(option.choices)) {
+ option.choices = option.choices.filter(
+ (option) => filterSince(option) && filterDeprecated(option)
+ );
- if (option.name === "parser") {
- collectParsersFromLanguages(option, languages, plugins);
+ if (option.name === "parser") {
+ collectParsersFromLanguages(option, languages, plugins);
+ }
}
- }
- const pluginDefaults = plugins
- .filter(
- (plugin) =>
- plugin.defaultOptions &&
- plugin.defaultOptions[option.name] !== undefined
- )
- .reduce((reduced, plugin) => {
- reduced[plugin.name] = plugin.defaultOptions[option.name];
- return reduced;
- }, {});
+ const pluginDefaults =
+ plugins
+ .filter(
+ (plugin) =>
+ plugin.defaultOptions &&
+ plugin.defaultOptions[option.name] !== undefined
+ )
+ .reduce((reduced, plugin) => {
+ reduced[plugin.name] = plugin.defaultOptions[option.name];
+ return reduced;
+ }, {});
- return { ...option, pluginDefaults };
- });
+ return { ...option, pluginDefaults };
+ });
return { languages, options };
diff --git ORI/prettier/tests/js/bom/jsfmt.spec.js ALT/prettier/tests/js/bom/jsfmt.spec.js
index 851064803..6501e2f16 100644
--- ORI/prettier/tests/js/bom/jsfmt.spec.js
+++ ALT/prettier/tests/js/bom/jsfmt.spec.js
@@ -2,18 +2,19 @@ const fs = require("fs");
const path = require("path");
const fixtureDirectory = path.join(__dirname, "../eol");
-const snippets = fs
- .readdirSync(fixtureDirectory)
- .filter(
- (fileName) => fileName !== "__snapshots__" && fileName !== "jsfmt.spec.js"
- )
- .map((fileName) => {
- const file = path.join(fixtureDirectory, fileName);
- const code = "\uFEFF" + fs.readFileSync(file, "utf8");
- return {
- name: fileName,
- code,
- };
- });
+const snippets =
+ fs
+ .readdirSync(fixtureDirectory)
+ .filter(
+ (fileName) => fileName !== "__snapshots__" && fileName !== "jsfmt.spec.js"
+ )
+ .map((fileName) => {
+ const file = path.join(fixtureDirectory, fileName);
+ const code = "\uFEFF" + fs.readFileSync(file, "utf8");
+ return {
+ name: fileName,
+ code,
+ };
+ });
run_spec({ dirname: __dirname, snippets }, ["babel"]);
diff --git ORI/prettier/tests/misc/empty/jsfmt.spec.js ALT/prettier/tests/misc/empty/jsfmt.spec.js
index 349f87d36..da6569e51 100644
--- ORI/prettier/tests/misc/empty/jsfmt.spec.js
+++ ALT/prettier/tests/misc/empty/jsfmt.spec.js
@@ -1,8 +1,9 @@
-const parsers = require("prettier-local")
- .getSupportInfo()
- .options.find((option) => option.name === "parser")
- .choices.filter((choice) => !choice.deprecated)
- .map((choice) => choice.value);
+const parsers =
+ require("prettier-local")
+ .getSupportInfo()
+ .options.find((option) => option.name === "parser")
+ .choices.filter((choice) => !choice.deprecated)
+ .map((choice) => choice.value);
run_spec(
{
diff --git ORI/prettier/tests_config/require_standalone.js ALT/prettier/tests_config/require_standalone.js
index 310dbb4b6..2be1957ee 100644
--- ORI/prettier/tests_config/require_standalone.js
+++ ALT/prettier/tests_config/require_standalone.js
@@ -6,13 +6,14 @@ const globby = require("globby");
const sandbox = vm.createContext();
-const source = globby
- .sync(["standalone.js", "parser-*.js"], {
- cwd: process.env.PRETTIER_DIR,
- absolute: true,
- })
- .map((file) => fs.readFileSync(file, "utf8"))
- .join(";");
+const source =
+ globby
+ .sync(["standalone.js", "parser-*.js"], {
+ cwd: process.env.PRETTIER_DIR,
+ absolute: true,
+ })
+ .map((file) => fs.readFileSync(file, "utf8"))
+ .join(";");
vm.runInContext(source, sandbox);
diff --git ORI/prettier/tests_config/run_spec.js ALT/prettier/tests_config/run_spec.js
index 8bb577930..03fce5bb5 100644
--- ORI/prettier/tests_config/run_spec.js
+++ ALT/prettier/tests_config/run_spec.js
@@ -118,29 +118,30 @@ function runSpec(fixtures, parsers, options) {
};
});
- const files = fs
- .readdirSync(dirname, { withFileTypes: true })
- .map((file) => {
- const basename = file.name;
- const filename = path.join(dirname, basename);
- if (
- path.extname(basename) === ".snap" ||
- !file.isFile() ||
- basename[0] === "." ||
- basename === "jsfmt.spec.js"
- ) {
- return;
- }
+ const files =
+ fs
+ .readdirSync(dirname, { withFileTypes: true })
+ .map((file) => {
+ const basename = file.name;
+ const filename = path.join(dirname, basename);
+ if (
+ path.extname(basename) === ".snap" ||
+ !file.isFile() ||
+ basename[0] === "." ||
+ basename === "jsfmt.spec.js"
+ ) {
+ return;
+ }
- const text = fs.readFileSync(filename, "utf8");
+ const text = fs.readFileSync(filename, "utf8");
- return {
- name: basename,
- filename,
- code: text,
- };
- })
- .filter(Boolean);
+ return {
+ name: basename,
+ filename,
+ code: text,
+ };
+ })
+ .filter(Boolean);
// Make sure tests are in correct location
if (process.env.CHECK_TEST_PARSERS) {
@@ -399,13 +400,14 @@ const indexProperties = [
},
];
function replacePlaceholders(originalText, originalOptions) {
- const indexes = indexProperties
- .map(({ property, placeholder }) => {
- const value = originalText.indexOf(placeholder);
- return value === -1 ? undefined : { property, value, placeholder };
- })
- .filter(Boolean)
- .sort((a, b) => a.value - b.value);
+ const indexes =
+ indexProperties
+ .map(({ property, placeholder }) => {
+ const value = originalText.indexOf(placeholder);
+ return value === -1 ? undefined : { property, value, placeholder };
+ })
+ .filter(Boolean)
+ .sort((a, b) => a.value - b.value);
const options = { ...originalOptions };
let text = originalText;
diff --git ORI/prettier/tests_integration/__tests__/bundle.js ALT/prettier/tests_integration/__tests__/bundle.js
index 1a2f85bab..b6c984c55 100644
--- ORI/prettier/tests_integration/__tests__/bundle.js
+++ ALT/prettier/tests_integration/__tests__/bundle.js
@@ -13,15 +13,17 @@ const distDirectory = path.join(projectRoot, "dist");
describe("standalone", () => {
const standalone = require(path.join(distDirectory, "standalone.js"));
- const plugins = globby
- .sync(["parser-*.js"], { cwd: distDirectory, absolute: true })
- .map((file) => require(file));
+ const plugins =
+ globby
+ .sync(["parser-*.js"], { cwd: distDirectory, absolute: true })
+ .map((file) => require(file));
const esmStandalone = require(path.join(distDirectory, "esm/standalone.mjs"))
.default;
- const esmPlugins = globby
- .sync(["esm/parser-*.mjs"], { cwd: distDirectory, absolute: true })
- .map((file) => require(file).default);
+ const esmPlugins =
+ globby
+ .sync(["esm/parser-*.mjs"], { cwd: distDirectory, absolute: true })
+ .map((file) => require(file).default);
for (const parser of parserNames) {
test(parser, () => {
diff --git ORI/prettier/website/blog/2020-08-24-2.1.0.md ALT/prettier/website/blog/2020-08-24-2.1.0.md
index 215b2102c..78474a301 100644
--- ORI/prettier/website/blog/2020-08-24-2.1.0.md
+++ ALT/prettier/website/blog/2020-08-24-2.1.0.md
@@ -2163,11 +2163,12 @@ npm install --save-dev --save-exact prettier @prettier/plugin-php
```
```js
-const hasPhpParser = prettier
- .getSupportInfo()
- .options.find((option) => option.name === "parser")
- .choices.map((choice) => choice.value)
- .includes("php"); // false in Prettier 2.0, true in Prettier 2.1
+const hasPhpParser =
+ prettier
+ .getSupportInfo()
+ .options.find((option) => option.name === "parser")
+ .choices.map((choice) => choice.value)
+ .includes("php"); // false in Prettier 2.0, true in Prettier 2.1
```
#### Fix `prettier.getFileInfo()` ([#8548](https://github.com/prettier/prettier/pull/8548), [#8551](https://github.com/prettier/prettier/pull/8551), [#8585](https://github.com/prettier/prettier/pull/8585) by [@fisker](https://github.com/fisker))
diff --git ORI/prettier/website/pages/en/index.js ALT/prettier/website/pages/en/index.js
index 0a212f30d..5cbe57622 100755
--- ORI/prettier/website/pages/en/index.js
+++ ALT/prettier/website/pages/en/index.js
@@ -239,13 +239,14 @@ const EditorSupportSection = () => (
);
const UsersSection = ({ language }) => {
- const showcase = siteConfig.users
- .filter((user) => user.pinned)
- .map((user, i) => (
- <a key={i} className="growOnHover alignCenter" href={user.infoLink}>
- <img className="user" src={user.greyImage} title={user.caption} />
- </a>
- ));
+ const showcase =
+ siteConfig.users
+ .filter((user) => user.pinned)
+ .map((user, i) => (
+ <a key={i} className="growOnHover alignCenter" href={user.infoLink}>
+ <img className="user" src={user.greyImage} title={user.caption} />
+ </a>
+ ));
return (
<div className="usersSection productShowcaseSection">
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts
index 096deaff..8d9d6de9 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/consistent-type-imports.ts
@@ -592,9 +592,10 @@ export default util.createRule<Options, MessageIds>({
);
// import Type , {...} from 'foo'
// ^^^^^ pick
- const defaultText = sourceCode.text
- .slice(defaultSpecifier.range[0], commaToken.range[0])
- .trim();
+ const defaultText =
+ sourceCode.text
+ .slice(defaultSpecifier.range[0], commaToken.range[0])
+ .trim();
yield fixer.insertTextBefore(
node,
`import type ${defaultText} from ${sourceCode.getText(
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts
index 08d72181..c9d94183 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/func-call-spacing.ts
@@ -99,9 +99,10 @@ export default util.createRule<Options, MessageIds>({
util.isNotOptionalChainPunctuator,
)!;
- const textBetweenTokens = text
- .slice(lastCalleeToken.range[1], openingParenToken.range[0])
- .replace(/\/\*.*?\*\//gu, '');
+ const textBetweenTokens =
+ text
+ .slice(lastCalleeToken.range[1], openingParenToken.range[0])
+ .replace(/\/\*.*?\*\//gu, '');
const hasWhitespace = /\s/u.test(textBetweenTokens);
const hasNewline =
hasWhitespace && util.LINEBREAK_MATCHER.test(textBetweenTokens);
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts
index 4775a1fe..02a704b0 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/method-signature-style.ts
@@ -154,13 +154,14 @@ export default util.createRule<Options, MessageIds>({
methodNode,
...duplicatedKeyMethodNodes,
].sort((a, b) => (a.range[0] < b.range[0] ? -1 : 1));
- const typeString = methodNodes
- .map(node => {
- const params = getMethodParams(node);
- const returnType = getMethodReturnType(node);
- return `(${params} => ${returnType})`;
- })
- .join(' & ');
+ const typeString =
+ methodNodes
+ .map(node => {
+ const params = getMethodParams(node);
+ const returnType = getMethodReturnType(node);
+ return `(${params} => ${returnType})`;
+ })
+ .join(' & ');
const key = getMethodKey(methodNode);
const delimiter = getDelimiter(methodNode);
yield fixer.replaceText(
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
index c4e6e36b..b0e1386f 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/parse-options.ts
@@ -80,9 +80,10 @@ function normalizeOption(option: Selector): NormalizedSelector[] {
}
function parseOptions(context: Context): ParsedOptions {
- const normalizedOptions = context.options
- .map(opt => normalizeOption(opt))
- .reduce((acc, val) => acc.concat(val), []);
+ const normalizedOptions =
+ context.options
+ .map(opt => normalizeOption(opt))
+ .reduce((acc, val) => acc.concat(val), []);
return util.getEnumNames(Selectors).reduce((acc, k) => {
acc[k] = createValidator(k, context, normalizedOptions);
return acc;
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts
index a683933d..0297f62c 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention-utils/validator.ts
@@ -28,46 +28,47 @@ function createValidator(
): (node: TSESTree.Identifier | TSESTree.Literal) => void {
// make sure the "highest priority" configs are checked first
const selectorType = Selectors[type];
- const configs = allConfigs
- // gather all of the applicable selectors
- .filter(
- c =>
- (c.selector & selectorType) !== 0 ||
- c.selector === MetaSelectors.default,
- )
- .sort((a, b) => {
- if (a.selector === b.selector) {
- // in the event of the same selector, order by modifier weight
- // sort descending - the type modifiers are "more important"
- return b.modifierWeight - a.modifierWeight;
- }
+ const configs =
+ allConfigs
+ // gather all of the applicable selectors
+ .filter(
+ c =>
+ (c.selector & selectorType) !== 0 ||
+ c.selector === MetaSelectors.default,
+ )
+ .sort((a, b) => {
+ if (a.selector === b.selector) {
+ // in the event of the same selector, order by modifier weight
+ // sort descending - the type modifiers are "more important"
+ return b.modifierWeight - a.modifierWeight;
+ }
- const aIsMeta = isMetaSelector(a.selector);
- const bIsMeta = isMetaSelector(b.selector);
+ const aIsMeta = isMetaSelector(a.selector);
+ const bIsMeta = isMetaSelector(b.selector);
- // non-meta selectors should go ahead of meta selectors
- if (aIsMeta && !bIsMeta) {
- return 1;
- }
- if (!aIsMeta && bIsMeta) {
- return -1;
- }
+ // non-meta selectors should go ahead of meta selectors
+ if (aIsMeta && !bIsMeta) {
+ return 1;
+ }
+ if (!aIsMeta && bIsMeta) {
+ return -1;
+ }
- const aIsMethodOrProperty = isMethodOrPropertySelector(a.selector);
- const bIsMethodOrProperty = isMethodOrPropertySelector(b.selector);
+ const aIsMethodOrProperty = isMethodOrPropertySelector(a.selector);
+ const bIsMethodOrProperty = isMethodOrPropertySelector(b.selector);
- // for backward compatibility, method and property have higher precedence than other meta selectors
- if (aIsMethodOrProperty && !bIsMethodOrProperty) {
- return -1;
- }
- if (!aIsMethodOrProperty && bIsMethodOrProperty) {
- return 1;
- }
+ // for backward compatibility, method and property have higher precedence than other meta selectors
+ if (aIsMethodOrProperty && !bIsMethodOrProperty) {
+ return -1;
+ }
+ if (!aIsMethodOrProperty && bIsMethodOrProperty) {
+ return 1;
+ }
- // both aren't meta selectors
- // sort descending - the meta selectors are "least important"
- return b.selector - a.selector;
- });
+ // both aren't meta selectors
+ // sort descending - the meta selectors are "least important"
+ return b.selector - a.selector;
+ });
return (
node: TSESTree.Identifier | TSESTree.Literal,
@@ -429,10 +430,11 @@ function isCorrectType(
const { esTreeNodeToTSNodeMap, program } = util.getParserServices(context);
const checker = program.getTypeChecker();
const tsNode = esTreeNodeToTSNodeMap.get(node);
- const type = checker
- .getTypeAtLocation(tsNode)
- // remove null and undefined from the type, as we don't care about it here
- .getNonNullableType();
+ const type =
+ checker
+ .getTypeAtLocation(tsNode)
+ // remove null and undefined from the type, as we don't care about it here
+ .getNonNullableType();
for (const allowedType of config.types) {
switch (allowedType) {
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts
index 16e31b62..91c6dc0c 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/naming-convention.ts
@@ -96,9 +96,10 @@ export default util.createRule<Options, MessageIds>({
const validators = parseOptions(context);
// getParserServices(context, false) -- dirty hack to work around the docs checker test...
- const compilerOptions = util
- .getParserServices(context, true)
- .program.getCompilerOptions();
+ const compilerOptions =
+ util
+ .getParserServices(context, true)
+ .program.getCompilerOptions();
function handleMember(
validator: ValidatorFunction | null,
node:
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts
index 0dff489e..3ef3fcbb 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-invalid-void-type.ts
@@ -102,9 +102,10 @@ export default util.createRule<[Options], MessageIds>({
// check whitelist
if (Array.isArray(allowInGenericTypeArguments)) {
const sourceCode = context.getSourceCode();
- const fullyQualifiedName = sourceCode
- .getText(node.parent.parent.typeName)
- .replace(/ /gu, '');
+ const fullyQualifiedName =
+ sourceCode
+ .getText(node.parent.parent.typeName)
+ .replace(/ /gu, '');
if (
!allowInGenericTypeArguments
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts
index 44d0178e..99153caa 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-loop-func.ts
@@ -49,9 +49,10 @@ export default util.createRule<Options, MessageIds>({
}
const references = context.getScope().through;
- const unsafeRefs = references
- .filter(r => !isSafe(loopNode, r))
- .map(r => r.identifier.name);
+ const unsafeRefs =
+ references
+ .filter(r => !isSafe(loopNode, r))
+ .map(r => r.identifier.name);
if (unsafeRefs.length > 0) {
context.report({
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts
index 21456319..d6d58ade 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/no-redeclare.ts
@@ -101,15 +101,16 @@ export default util.createRule<Options, MessageIds>({
}
}
- const identifiers = variable.identifiers
- .map(id => ({
- identifier: id,
- parent: id.parent!,
- }))
- // ignore function declarations because TS will treat them as an overload
- .filter(
- ({ parent }) => parent.type !== AST_NODE_TYPES.TSDeclareFunction,
- );
+ const identifiers =
+ variable.identifiers
+ .map(id => ({
+ identifier: id,
+ parent: id.parent!,
+ }))
+ // ignore function declarations because TS will treat them as an overload
+ .filter(
+ ({ parent }) => parent.type !== AST_NODE_TYPES.TSDeclareFunction,
+ );
if (options.ignoreDeclarationMerge && identifiers.length > 1) {
if (
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts
index d21b088d..cc5a0136 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/prefer-includes.ts
@@ -146,9 +146,10 @@ export default createRule({
// Get the symbol of `indexOf` method.
const tsNode = services.esTreeNodeToTSNodeMap.get(node.property);
- const indexofMethodDeclarations = types
- .getSymbolAtLocation(tsNode)
- ?.getDeclarations();
+ const indexofMethodDeclarations =
+ types
+ .getSymbolAtLocation(tsNode)
+ ?.getDeclarations();
if (
indexofMethodDeclarations == null ||
indexofMethodDeclarations.length === 0
@@ -161,9 +162,10 @@ export default createRule({
for (const instanceofMethodDecl of indexofMethodDeclarations) {
const typeDecl = instanceofMethodDecl.parent;
const type = types.getTypeAtLocation(typeDecl);
- const includesMethodDecl = type
- .getProperty('includes')
- ?.getDeclarations();
+ const includesMethodDecl =
+ type
+ .getProperty('includes')
+ ?.getDeclarations();
if (
includesMethodDecl == null ||
!includesMethodDecl.some(includesMethodDecl =>
@@ -204,9 +206,10 @@ export default createRule({
const tsNode = services.esTreeNodeToTSNodeMap.get(argument);
const type = getConstrainedTypeAtLocation(types, tsNode);
- const includesMethodDecl = type
- .getProperty('includes')
- ?.getDeclarations();
+ const includesMethodDecl =
+ type
+ .getProperty('includes')
+ ?.getDeclarations();
if (includesMethodDecl == null) {
return;
}
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts
index 00888c8f..1bcb2f96 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/promise-function-async.ts
@@ -99,9 +99,10 @@ export default util.createRule<Options, MessageIds>({
| TSESTree.FunctionExpression,
): void {
const originalNode = parserServices.esTreeNodeToTSNodeMap.get(node);
- const signatures = checker
- .getTypeAtLocation(originalNode)
- .getCallSignatures();
+ const signatures =
+ checker
+ .getTypeAtLocation(originalNode)
+ .getCallSignatures();
if (!signatures.length) {
return;
}
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts
index ff4a4d1a..e738a517 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/sort-type-union-intersection-members.ts
@@ -210,11 +210,14 @@ export default util.createRule<Options, MessageIds>({
}
const fix: TSESLint.ReportFixFunction = fixer => {
- const sorted = expectedOrder
- .map(t => t.text)
- .join(
- node.type === AST_NODE_TYPES.TSIntersectionType ? ' & ' : ' | ',
- );
+ const sorted =
+ expectedOrder
+ .map(t => t.text)
+ .join(
+ node.type === AST_NODE_TYPES.TSIntersectionType
+ ? ' & '
+ : ' | ',
+ );
return fixer.replaceText(node, sorted);
};
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
index 8881473d..99d911d8 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/switch-exhaustiveness-check.ts
@@ -88,9 +88,10 @@ export default createRule({
);
}
- const fixString = missingCases
- .map(code => `${caseIndent}${code}`)
- .join('\n');
+ const fixString =
+ missingCases
+ .map(code => `${caseIndent}${code}`)
+ .join('\n');
if (lastCase) {
return fixer.insertTextAfter(lastCase, `\n${fixString}`);
@@ -141,13 +142,14 @@ export default createRule({
node: node.discriminant,
messageId: 'switchIsNotExhaustive',
data: {
- missingBranches: missingBranchTypes
- .map(missingType =>
- isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike)
- ? `typeof ${missingType.getSymbol()?.escapedName}`
- : checker.typeToString(missingType),
- )
- .join(' | '),
+ missingBranches:
+ missingBranchTypes
+ .map(missingType =>
+ isTypeFlagSet(missingType, ts.TypeFlags.ESSymbolLike)
+ ? `typeof ${missingType.getSymbol()?.escapedName}`
+ : checker.typeToString(missingType),
+ )
+ .join(' | '),
},
suggest: [
{
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts ALT/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts
index 407d04c1..ffacd370 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/rules/unbound-method.ts
@@ -81,23 +81,24 @@ const SUPPORTED_GLOBALS = [
'JSON',
'Intl',
] as const;
-const nativelyBoundMembers = SUPPORTED_GLOBALS.map(namespace => {
- if (!(namespace in global)) {
- // node.js might not have namespaces like Intl depending on compilation options
- // https://nodejs.org/api/intl.html#intl_options_for_building_node_js
- return [];
- }
- const object = global[namespace];
- return Object.getOwnPropertyNames(object)
- .filter(
- name =>
- !name.startsWith('_') &&
- typeof (object as Record<string, unknown>)[name] === 'function',
- )
- .map(name => `${namespace}.${name}`);
-})
- .reduce((arr, names) => arr.concat(names), [])
- .filter(name => !nativelyNotBoundMembers.has(name));
+const nativelyBoundMembers =
+ SUPPORTED_GLOBALS.map(namespace => {
+ if (!(namespace in global)) {
+ // node.js might not have namespaces like Intl depending on compilation options
+ // https://nodejs.org/api/intl.html#intl_options_for_building_node_js
+ return [];
+ }
+ const object = global[namespace];
+ return Object.getOwnPropertyNames(object)
+ .filter(
+ name =>
+ !name.startsWith('_') &&
+ typeof (object as Record<string, unknown>)[name] === 'function',
+ )
+ .map(name => `${namespace}.${name}`);
+ })
+ .reduce((arr, names) => arr.concat(names), [])
+ .filter(name => !nativelyNotBoundMembers.has(name));
const isNotImported = (
symbol: ts.Symbol,
diff --git ORI/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts ALT/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts
index 5e2f1054..4b4a25b2 100644
--- ORI/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/src/util/propertyTypes.ts
@@ -13,9 +13,10 @@ export function getTypeOfPropertyOfName(
// Symbolic names may differ in their escaped name compared to their human-readable name
// https://github.com/typescript-eslint/typescript-eslint/issues/2143
- const escapedProperty = type
- .getProperties()
- .find(property => property.escapedName === escapedName);
+ const escapedProperty =
+ type
+ .getProperties()
+ .find(property => property.escapedName === escapedName);
return escapedProperty
? checker.getDeclaredTypeOfSymbol(escapedProperty)
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts
index f8fc068a..ed879e52 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/configs.test.ts
@@ -2,17 +2,18 @@ import rules from '../src/rules';
import plugin from '../src/index';
const RULE_NAME_PREFIX = '@typescript-eslint/';
-const EXTENSION_RULES = Object.entries(rules)
- .filter(([, rule]) => rule.meta.docs?.extendsBaseRule)
- .map(
- ([ruleName, rule]) =>
- [
- `${RULE_NAME_PREFIX}${ruleName}`,
- typeof rule.meta.docs?.extendsBaseRule === 'string'
- ? rule.meta.docs.extendsBaseRule
- : ruleName,
- ] as const,
- );
+const EXTENSION_RULES =
+ Object.entries(rules)
+ .filter(([, rule]) => rule.meta.docs?.extendsBaseRule)
+ .map(
+ ([ruleName, rule]) =>
+ [
+ `${RULE_NAME_PREFIX}${ruleName}`,
+ typeof rule.meta.docs?.extendsBaseRule === 'string'
+ ? rule.meta.docs.extendsBaseRule
+ : ruleName,
+ ] as const,
+ );
function entriesToObject<T = unknown>(value: [string, T][]): Record<string, T> {
return value.reduce<Record<string, T>>((accum, [k, v]) => {
@@ -49,9 +50,13 @@ describe('all.json config', () => {
plugin.configs.all.rules;
const configRules = filterRules(unfilteredConfigRules);
// note: exclude deprecated rules, this config is allowed to change between minor versions
- const ruleConfigs = Object.entries(rules)
- .filter(([, rule]) => !rule.meta.deprecated)
- .map<[string, string]>(([name]) => [`${RULE_NAME_PREFIX}${name}`, 'error']);
+ const ruleConfigs =
+ Object.entries(rules)
+ .filter(([, rule]) => !rule.meta.deprecated)
+ .map<[string, string]>(([name]) => [
+ `${RULE_NAME_PREFIX}${name}`,
+ 'error',
+ ]);
it('contains all of the rules, excluding the deprecated ones', () => {
expect(entriesToObject(ruleConfigs)).toEqual(entriesToObject(configRules));
@@ -65,16 +70,17 @@ describe('recommended.json config', () => {
plugin.configs.recommended.rules;
const configRules = filterRules(unfilteredConfigRules);
// note: include deprecated rules so that the config doesn't change between major bumps
- const ruleConfigs = Object.entries(rules)
- .filter(
- ([, rule]) =>
- rule.meta.docs?.recommended !== false &&
- rule.meta.docs?.requiresTypeChecking !== true,
- )
- .map<[string, string]>(([name, rule]) => [
- `${RULE_NAME_PREFIX}${name}`,
- rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
- ]);
+ const ruleConfigs =
+ Object.entries(rules)
+ .filter(
+ ([, rule]) =>
+ rule.meta.docs?.recommended !== false &&
+ rule.meta.docs?.requiresTypeChecking !== true,
+ )
+ .map<[string, string]>(([name, rule]) => [
+ `${RULE_NAME_PREFIX}${name}`,
+ rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
+ ]);
it("contains all recommended rules that don't require typechecking, excluding the deprecated ones", () => {
expect(entriesToObject(ruleConfigs)).toEqual(entriesToObject(configRules));
@@ -88,16 +94,17 @@ describe('recommended-requiring-type-checking.json config', () => {
plugin.configs['recommended-requiring-type-checking'].rules;
const configRules = filterRules(unfilteredConfigRules);
// note: include deprecated rules so that the config doesn't change between major bumps
- const ruleConfigs = Object.entries(rules)
- .filter(
- ([, rule]) =>
- rule.meta.docs?.recommended !== false &&
- rule.meta.docs?.requiresTypeChecking === true,
- )
- .map<[string, string]>(([name, rule]) => [
- `${RULE_NAME_PREFIX}${name}`,
- rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
- ]);
+ const ruleConfigs =
+ Object.entries(rules)
+ .filter(
+ ([, rule]) =>
+ rule.meta.docs?.recommended !== false &&
+ rule.meta.docs?.requiresTypeChecking === true,
+ )
+ .map<[string, string]>(([name, rule]) => [
+ `${RULE_NAME_PREFIX}${name}`,
+ rule.meta.docs?.recommended ? rule.meta.docs.recommended : 'off',
+ ]);
it('contains all recommended rules that require type checking, excluding the deprecated ones', () => {
expect(entriesToObject(ruleConfigs)).toEqual(entriesToObject(configRules));
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts
index d67ff887..230e312b 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/docs.test.ts
@@ -41,13 +41,15 @@ function parseReadme(): {
describe('Validating rule docs', () => {
it('All rules must have a corresponding rule doc', () => {
- const files = fs
- .readdirSync(docsRoot)
- // this rule doc was left behind on purpose for legacy reasons
- .filter(rule => rule !== 'camelcase.md');
- const ruleFiles = Object.keys(rules)
- .map(rule => `${rule}.md`)
- .sort();
+ const files =
+ fs
+ .readdirSync(docsRoot)
+ // this rule doc was left behind on purpose for legacy reasons
+ .filter(rule => rule !== 'camelcase.md');
+ const ruleFiles =
+ Object.keys(rules)
+ .map(rule => `${rule}.md`)
+ .sort();
expect(files.sort()).toEqual(ruleFiles);
});
@@ -115,20 +117,22 @@ describe('Validating README.md', () => {
);
it('All non-deprecated base rules should have a row in the base rules table, and the table should be ordered alphabetically', () => {
- const baseRuleNames = baseRules
- .map(([ruleName]) => ruleName)
- .sort()
- .map(createRuleLink);
+ const baseRuleNames =
+ baseRules
+ .map(([ruleName]) => ruleName)
+ .sort()
+ .map(createRuleLink);
expect(rulesTables.base.cells.map(row => row[0])).toStrictEqual(
baseRuleNames,
);
});
it('All non-deprecated extension rules should have a row in the base rules table, and the table should be ordered alphabetically', () => {
- const extensionRuleNames = extensionRules
- .map(([ruleName]) => ruleName)
- .sort()
- .map(createRuleLink);
+ const extensionRuleNames =
+ extensionRules
+ .map(([ruleName]) => ruleName)
+ .sort()
+ .map(createRuleLink);
expect(rulesTables.extension.cells.map(row => row[0])).toStrictEqual(
extensionRuleNames,
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/index.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/index.test.ts
index 3cac8304..6ca70b85 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/index.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/index.test.ts
@@ -8,10 +8,13 @@ describe('eslint-plugin ("./src/index.ts")', () => {
const ruleKeys = Object.keys(rules);
const eslintPluginRuleKeys = Object.keys(eslintPlugin.rules);
- const configs = fs
- .readdirSync('./src/configs')
- .filter(file => ['.json', '.ts'].includes(path.extname(file).toLowerCase()))
- .map(file => path.basename(file, path.extname(file)));
+ const configs =
+ fs
+ .readdirSync('./src/configs')
+ .filter(file =>
+ ['.json', '.ts'].includes(path.extname(file).toLowerCase()),
+ )
+ .map(file => path.basename(file, path.extname(file)));
const eslintPluginConfigKeys = Object.keys(eslintPlugin.configs);
it('exports all available rules', () => {
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts
index 8296bf19..22d15332 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/indent.test.ts
@@ -640,30 +640,31 @@ type Foo = string | {
// test the fixer by removing all the spaces
code: code.replace(new RegExp(indent, 'g'), ''),
output: code,
- errors: code
- .split('\n')
- .map<TSESLint.TestCaseError<MessageIds> | null>((line, lineNum) => {
- const indentCount = line.split(indent).length - 1;
- const spaceCount = indentCount * indent.length;
+ errors:
+ code
+ .split('\n')
+ .map<TSESLint.TestCaseError<MessageIds> | null>((line, lineNum) => {
+ const indentCount = line.split(indent).length - 1;
+ const spaceCount = indentCount * indent.length;
- if (indentCount < 1) {
- return null;
- }
+ if (indentCount < 1) {
+ return null;
+ }
- return {
- messageId: 'wrongIndentation',
- data: {
- expected: `${spaceCount} spaces`,
- actual: 0,
- },
- line: lineNum + 1,
- column: 1,
- };
- })
- .filter(
- (error): error is TSESLint.TestCaseError<MessageIds> =>
- error !== null,
- ),
+ return {
+ messageId: 'wrongIndentation',
+ data: {
+ expected: `${spaceCount} spaces`,
+ actual: 0,
+ },
+ line: lineNum + 1,
+ column: 1,
+ };
+ })
+ .filter(
+ (error): error is TSESLint.TestCaseError<MessageIds> =>
+ error !== null,
+ ),
};
if (invalid.errors.length > 0) {
invalidCases.push(invalid);
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts
index badfbc1c..cd868ac7 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/indent/utils.ts
@@ -19,13 +19,15 @@ type MessageIds = InferMessageIdsTypeFromRule<typeof rule>;
export function unIndent(strings: TemplateStringsArray): string {
const WHITESPACE_REGEX = / */u;
const templateValue = strings[0];
- const lines = templateValue
- .replace(/^\n/u, '')
- .replace(/\n\s*$/u, '')
- .split('\n');
- const lineIndents = lines
- .filter(line => line.trim())
- .map(line => WHITESPACE_REGEX.exec(line)![0].length);
+ const lines =
+ templateValue
+ .replace(/^\n/u, '')
+ .replace(/\n\s*$/u, '')
+ .split('\n');
+ const lineIndents =
+ lines
+ .filter(line => line.trim())
+ .map(line => WHITESPACE_REGEX.exec(line)![0].length);
const minLineIndent = Math.min(...lineIndents);
return lines.map(line => line.slice(minLineIndent)).join('\n');
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts
index c9160c05..1139ce3e 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/index.test.ts
@@ -4,9 +4,10 @@ import rules from '../../src/rules';
describe('./src/rules/index.ts', () => {
const ruleNames = Object.keys(rules).map(name => `${name}.ts`);
- const files = fs
- .readdirSync('./src/rules')
- .filter(file => file !== 'index.ts' && file.endsWith('.ts'));
+ const files =
+ fs
+ .readdirSync('./src/rules')
+ .filter(file => file !== 'index.ts' && file.endsWith('.ts'));
it('imports all available rule modules', () => {
expect(ruleNames).toEqual(expect.arrayContaining(files));
diff --git ORI/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts ALT/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts
index 9278420a..59ac6ffc 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tests/rules/prefer-readonly-parameter-types.test.ts
@@ -269,10 +269,11 @@ ruleTester.run('prefer-readonly-parameter-types', rule, {
invalid: [
// arrays
...arrays.map<TSESLint.InvalidTestCase<MessageIds, Options>>(baseType => {
- const type = baseType
- .replace(/readonly /g, '')
- .replace(/Readonly<(.+?)>/g, '$1')
- .replace(/ReadonlyArray/g, 'Array');
+ const type =
+ baseType
+ .replace(/readonly /g, '')
+ .replace(/Readonly<(.+?)>/g, '$1')
+ .replace(/ReadonlyArray/g, 'Array');
return {
code: `function foo(arg: ${type}) {}`,
errors: [
diff --git ORI/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts ALT/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts
index ed84f286..1f6698f3 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tools/generate-configs.ts
@@ -161,16 +161,17 @@ console.log();
console.log(
'------------------------------ recommended.ts (should not require program) ------------------------------',
);
-const recommendedRules = ruleEntries
- .filter(entry => !!entry[1].meta.docs?.recommended)
- .reduce<LinterConfigRules>(
- (config, entry) =>
- reducer(config, entry, {
- filterDeprecated: false,
- filterRequiresTypeChecking: 'exclude',
- }),
- {},
- );
+const recommendedRules =
+ ruleEntries
+ .filter(entry => !!entry[1].meta.docs?.recommended)
+ .reduce<LinterConfigRules>(
+ (config, entry) =>
+ reducer(config, entry, {
+ filterDeprecated: false,
+ filterRequiresTypeChecking: 'exclude',
+ }),
+ {},
+ );
const recommendedConfig: LinterConfig = {
extends: EXTENDS,
rules: recommendedRules,
@@ -184,16 +185,17 @@ console.log();
console.log(
'--------------------------------- recommended-requiring-type-checking.ts ---------------------------------',
);
-const recommendedRulesRequiringProgram = ruleEntries
- .filter(entry => !!entry[1].meta.docs?.recommended)
- .reduce<LinterConfigRules>(
- (config, entry) =>
- reducer(config, entry, {
- filterDeprecated: false,
- filterRequiresTypeChecking: 'include',
- }),
- {},
- );
+const recommendedRulesRequiringProgram =
+ ruleEntries
+ .filter(entry => !!entry[1].meta.docs?.recommended)
+ .reduce<LinterConfigRules>(
+ (config, entry) =>
+ reducer(config, entry, {
+ filterDeprecated: false,
+ filterRequiresTypeChecking: 'include',
+ }),
+ {},
+ );
const recommendedRequiringTypeCheckingConfig: LinterConfig = {
extends: EXTENDS,
rules: recommendedRulesRequiringProgram,
diff --git ORI/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts ALT/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts
index cffe4006..809c9248 100644
--- ORI/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts
+++ ALT/typescript-eslint/packages/eslint-plugin/tools/generate-rules-lists.ts
@@ -105,16 +105,17 @@ const updateRulesList = (
].join('\n');
};
-const rulesDetails: RuleDetails[] = Object.entries(rules)
- .filter(([, rule]) => rule.meta.deprecated !== true)
- .map(([name, rule]) => ({
- name,
- description: rule.meta.docs?.description ?? '',
- recommended: !!rule.meta.docs?.recommended ?? false,
- fixable: !!rule.meta.fixable,
- requiresTypeChecking: rule.meta.docs?.requiresTypeChecking ?? false,
- extendsBaseRule: !!rule.meta.docs?.extendsBaseRule ?? false,
- }));
+const rulesDetails: RuleDetails[] =
+ Object.entries(rules)
+ .filter(([, rule]) => rule.meta.deprecated !== true)
+ .map(([name, rule]) => ({
+ name,
+ description: rule.meta.docs?.description ?? '',
+ recommended: !!rule.meta.docs?.recommended ?? false,
+ fixable: !!rule.meta.fixable,
+ requiresTypeChecking: rule.meta.docs?.requiresTypeChecking ?? false,
+ extendsBaseRule: !!rule.meta.docs?.extendsBaseRule ?? false,
+ }));
const baseRules = rulesDetails.filter(rule => !rule.extendsBaseRule);
const extensionRules = rulesDetails.filter(rule => rule.extendsBaseRule);
diff --git ORI/typescript-eslint/packages/parser/src/parser.ts ALT/typescript-eslint/packages/parser/src/parser.ts
index f304a837..cd6fd0d1 100644
--- ORI/typescript-eslint/packages/parser/src/parser.ts
+++ ALT/typescript-eslint/packages/parser/src/parser.ts
@@ -154,9 +154,10 @@ function parseForESLint(
compilerOptions.jsxFragmentFactory != null
) {
// in case the user has specified something like "preact.Fragment"
- const fragFactory = compilerOptions.jsxFragmentFactory
- .split('.')[0]
- .trim();
+ const fragFactory =
+ compilerOptions.jsxFragmentFactory
+ .split('.')[0]
+ .trim();
analyzeOptions.jsxFragmentName = fragFactory;
log(
'Resolved jsxFragmentName from program: %s',
diff --git ORI/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts ALT/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts
index 5255ed02..5f5a2295 100644
--- ORI/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts
+++ ALT/typescript-eslint/packages/scope-manager/tests/fixtures.test.ts
@@ -12,24 +12,25 @@ const ONLY = [].join(path.sep);
const FIXTURES_DIR = path.resolve(__dirname, 'fixtures');
-const fixtures = glob
- .sync(`${FIXTURES_DIR}/**/*.{js,ts,jsx,tsx}`, {
- ignore: ['fixtures.test.ts'],
- })
- .map(absolute => {
- const relative = path.relative(FIXTURES_DIR, absolute);
- const { name, dir, ext } = path.parse(relative);
- const segments = dir.split(path.sep);
- const snapshotPath = path.join(FIXTURES_DIR, dir);
- return {
- absolute,
- name,
- ext,
- segments,
- snapshotPath,
- snapshotFile: path.join(snapshotPath, `${name}${ext}.shot`),
- };
- });
+const fixtures =
+ glob
+ .sync(`${FIXTURES_DIR}/**/*.{js,ts,jsx,tsx}`, {
+ ignore: ['fixtures.test.ts'],
+ })
+ .map(absolute => {
+ const relative = path.relative(FIXTURES_DIR, absolute);
+ const { name, dir, ext } = path.parse(relative);
+ const segments = dir.split(path.sep);
+ const snapshotPath = path.join(FIXTURES_DIR, dir);
+ return {
+ absolute,
+ name,
+ ext,
+ segments,
+ snapshotPath,
+ snapshotFile: path.join(snapshotPath, `${name}${ext}.shot`),
+ };
+ });
const FOUR_SLASH = /^\/\/\/\/[ ]+@(\w+)[ ]*=[ ]*(.+)$/;
const QUOTED_STRING = /^["'](.+?)['"]$/;
diff --git ORI/typescript-eslint/packages/typescript-estree/src/convert.ts ALT/typescript-eslint/packages/typescript-estree/src/convert.ts
index f5a6a230..8c0ecfc7 100644
--- ORI/typescript-eslint/packages/typescript-estree/src/convert.ts
+++ ALT/typescript-eslint/packages/typescript-estree/src/convert.ts
@@ -1953,12 +1953,13 @@ export class Converter {
case SyntaxKind.BigIntLiteral: {
const range = getRange(node, this.ast);
const rawValue = this.ast.text.slice(range[0], range[1]);
- const bigint = rawValue
- // remove suffix `n`
- .slice(0, -1)
- // `BigInt` doesn't accept numeric separator
- // and `bigint` property should not include numeric separator
- .replace(/_/g, '');
+ const bigint =
+ rawValue
+ // remove suffix `n`
+ .slice(0, -1)
+ // `BigInt` doesn't accept numeric separator
+ // and `bigint` property should not include numeric separator
+ .replace(/_/g, '');
const value = typeof BigInt !== 'undefined' ? BigInt(bigint) : null;
return this.createNode<TSESTree.BigIntLiteral>(node, {
type: AST_NODE_TYPES.Literal,
diff --git ORI/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts ALT/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts
index a3f007a0..599cfeed 100644
--- ORI/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts
+++ ALT/typescript-eslint/packages/typescript-estree/src/create-program/createWatchProgram.ts
@@ -289,12 +289,14 @@ function createWatchProgram(
// ensure process doesn't emit programs
watchCompilerHost.afterProgramCreate = (program): void => {
// report error if there are any errors in the config file
- const configFileDiagnostics = program
- .getConfigFileParsingDiagnostics()
- .filter(
- diag =>
- diag.category === ts.DiagnosticCategory.Error && diag.code !== 18003,
- );
+ const configFileDiagnostics =
+ program
+ .getConfigFileParsingDiagnostics()
+ .filter(
+ diag =>
+ diag.category === ts.DiagnosticCategory.Error &&
+ diag.code !== 18003,
+ );
if (configFileDiagnostics.length > 0) {
diagnosticReporter(configFileDiagnostics[0]);
}
diff --git ORI/typescript-eslint/packages/typescript-estree/src/parser.ts ALT/typescript-eslint/packages/typescript-estree/src/parser.ts
index dd765eb5..4e118007 100644
--- ORI/typescript-eslint/packages/typescript-estree/src/parser.ts
+++ ALT/typescript-eslint/packages/typescript-estree/src/parser.ts
@@ -264,17 +264,16 @@ function applyParserOptionsToExtra(options: TSESTreeOptions): void {
// NOTE - ensureAbsolutePath relies upon having the correct tsconfigRootDir in extra
extra.filePath = ensureAbsolutePath(extra.filePath, extra);
- const projectFolderIgnoreList = (
- options.projectFolderIgnoreList ?? ['**/node_modules/**']
- )
- .reduce<string[]>((acc, folder) => {
- if (typeof folder === 'string') {
- acc.push(folder);
- }
- return acc;
- }, [])
- // prefix with a ! for not match glob
- .map(folder => (folder.startsWith('!') ? folder : `!${folder}`));
+ const projectFolderIgnoreList =
+ (options.projectFolderIgnoreList ?? ['**/node_modules/**'])
+ .reduce<string[]>((acc, folder) => {
+ if (typeof folder === 'string') {
+ acc.push(folder);
+ }
+ return acc;
+ }, [])
+ // prefix with a ! for not match glob
+ .map(folder => (folder.startsWith('!') ? folder : `!${folder}`));
// NOTE - prepareAndTransformProjects relies upon having the correct tsconfigRootDir in extra
extra.projects = prepareAndTransformProjects(
options.project,
diff --git ORI/typescript-eslint/tools/generate-contributors.ts ALT/typescript-eslint/tools/generate-contributors.ts
index 6bb908b3..fb6dc4df 100644
--- ORI/typescript-eslint/tools/generate-contributors.ts
+++ ALT/typescript-eslint/tools/generate-contributors.ts
@@ -83,19 +83,20 @@ async function main(): Promise<void> {
}),
);
- const contributors = users
- // remove ignored users
- .filter(u => !IGNORED_USERS.has(u.login))
- // fetch the in-depth information for each user
- .map<AllContributorsUser>(usr => {
- return {
- login: usr.login,
- name: usr.name || usr.login,
- avatar_url: usr.avatar_url,
- profile: usr.html_url,
- contributions: [],
- };
- });
+ const contributors =
+ users
+ // remove ignored users
+ .filter(u => !IGNORED_USERS.has(u.login))
+ // fetch the in-depth information for each user
+ .map<AllContributorsUser>(usr => {
+ return {
+ login: usr.login,
+ name: usr.name || usr.login,
+ avatar_url: usr.avatar_url,
+ profile: usr.html_url,
+ contributions: [],
+ };
+ });
// build + write the .all-contributorsrc
const allContributorsConfig = {
diff --git ORI/vega-lite/site/static/index.ts ALT/vega-lite/site/static/index.ts
index 951282330..92458d643 100644
--- ORI/vega-lite/site/static/index.ts
+++ ALT/vega-lite/site/static/index.ts
@@ -60,12 +60,13 @@ function renderExample($target: Selection<any, any, any, any>, specText: string,
const textClean = specText.replace(/(\s)+"(\$schema|description)": ".*?",/g, '');
if (!figureOnly) {
- const code = $target
- .append('pre')
- .attr('class', 'example-code')
- .append('code')
- .attr('class', 'json')
- .text(textClean);
+ const code =
+ $target
+ .append('pre')
+ .attr('class', 'example-code')
+ .append('code')
+ .attr('class', 'json')
+ .text(textClean);
hljs.highlightBlock(code.node() as any);
}
@@ -142,11 +143,12 @@ window['buildSpecOpts'] = (id: string, baseName: string) => {
const prefixSel = select(`select[name=${id}]`);
const inputsSel = selectAll(`input[name=${id}]:checked`);
const prefix = prefixSel.empty() ? id : prefixSel.property('value');
- const values = inputsSel
- .nodes()
- .map((n: any) => n.value)
- .sort()
- .join('_');
+ const values =
+ inputsSel
+ .nodes()
+ .map((n: any) => n.value)
+ .sort()
+ .join('_');
const newName = baseName + prefix + (values ? `_${values}` : '');
if (oldName !== newName) {
window['changeSpec'](id, newName);
diff --git ORI/vega-lite/site/static/streaming.ts ALT/vega-lite/site/static/streaming.ts
index ff4806aa2..af282d915 100644
--- ORI/vega-lite/site/static/streaming.ts
+++ ALT/vega-lite/site/static/streaming.ts
@@ -42,10 +42,11 @@ export function runStreamingExample(eleId: string) {
let minimumX = -100;
window.setInterval(() => {
minimumX++;
- const changeSet = view
- .changeset()
- .insert(valueGenerator())
- .remove((t: {x: number}) => t.x < minimumX);
+ const changeSet =
+ view
+ .changeset()
+ .insert(valueGenerator())
+ .remove((t: {x: number}) => t.x < minimumX);
view.change('table', changeSet).run();
}, 1000);
}
diff --git ORI/vega-lite/src/compile/legend/assemble.ts ALT/vega-lite/src/compile/legend/assemble.ts
index 3732dac59..d675e3ae0 100644
--- ORI/vega-lite/src/compile/legend/assemble.ts
+++ ALT/vega-lite/src/compile/legend/assemble.ts
@@ -40,10 +40,11 @@ export function assembleLegends(model: Model): VgLegend[] {
}
}
- const legends = vals(legendByDomain)
- .flat()
- .map(l => assembleLegend(l, model.config))
- .filter(l => l !== undefined);
+ const legends =
+ vals(legendByDomain)
+ .flat()
+ .map(l => assembleLegend(l, model.config))
+ .filter(l => l !== undefined);
return legends;
}
diff --git ORI/vega-lite/src/compile/mark/encode/aria.ts ALT/vega-lite/src/compile/mark/encode/aria.ts
index dac62f19e..c210e2563 100644
--- ORI/vega-lite/src/compile/mark/encode/aria.ts
+++ ALT/vega-lite/src/compile/mark/encode/aria.ts
@@ -69,9 +69,10 @@ export function description(model: UnitModel) {
return {
description: {
- signal: entries(data)
- .map(([key, value], index) => `"${index > 0 ? '; ' : ''}${key}: " + (${value})`)
- .join(' + ')
+ signal:
+ entries(data)
+ .map(([key, value], index) => `"${index > 0 ? '; ' : ''}${key}: " + (${value})`)
+ .join(' + ')
}
};
}
diff --git ORI/vega-lite/src/compile/selection/interval.ts ALT/vega-lite/src/compile/selection/interval.ts
index 7dd7b69b1..f104ea560 100644
--- ORI/vega-lite/src/compile/selection/interval.ts
+++ ALT/vega-lite/src/compile/selection/interval.ts
@@ -139,9 +139,10 @@ const interval: SelectionCompiler<'interval'> = {
const vgStroke = keys(stroke).reduce((def, k) => {
def[k] = [
{
- test: [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`]
- .filter(t => t)
- .join(' && '),
+ test:
+ [x !== undefined && `${xvname}[0] !== ${xvname}[1]`, y !== undefined && `${yvname}[0] !== ${yvname}[1]`]
+ .filter(t => t)
+ .join(' && '),
value: stroke[k]
},
{value: null}
diff --git ORI/vega-lite/src/compile/selection/legends.ts ALT/vega-lite/src/compile/selection/legends.ts
index d24822243..fe4a25f61 100644
--- ORI/vega-lite/src/compile/selection/legends.ts
+++ ALT/vega-lite/src/compile/selection/legends.ts
@@ -62,10 +62,11 @@ const legendBindings: SelectionCompiler<'point'> = {
const hasSignal = signals.filter(s => s.name === sgName);
if (hasSignal.length === 0) {
- const events = stream.merge
- .map(markName(`${prefix}_symbols`))
- .concat(stream.merge.map(markName(`${prefix}_labels`)))
- .concat(stream.merge.map(markName(`${prefix}_entries`)));
+ const events =
+ stream.merge
+ .map(markName(`${prefix}_symbols`))
+ .concat(stream.merge.map(markName(`${prefix}_labels`)))
+ .concat(stream.merge.map(markName(`${prefix}_entries`)));
signals.unshift({
name: sgName,
diff --git ORI/vega-lite/src/compile/selection/point.ts ALT/vega-lite/src/compile/selection/point.ts
index 384ac50fa..8c25479d8 100644
--- ORI/vega-lite/src/compile/selection/point.ts
+++ ALT/vega-lite/src/compile/selection/point.ts
@@ -11,16 +11,17 @@ const point: SelectionCompiler<'point'> = {
const fieldsSg = name + TUPLE_FIELDS;
const project = selCmpt.project;
const datum = '(item().isVoronoi ? datum.datum : datum)';
- const values = project.items
- .map(p => {
- const fieldDef = model.fieldDef(p.channel);
- // Binned fields should capture extents, for a range test against the raw field.
- return fieldDef && fieldDef.bin
- ? `[${datum}[${stringValue(model.vgField(p.channel, {}))}], ` +
- `${datum}[${stringValue(model.vgField(p.channel, {binSuffix: 'end'}))}]]`
- : `${datum}[${stringValue(p.field)}]`;
- })
- .join(', ');
+ const values =
+ project.items
+ .map(p => {
+ const fieldDef = model.fieldDef(p.channel);
+ // Binned fields should capture extents, for a range test against the raw field.
+ return fieldDef && fieldDef.bin
+ ? `[${datum}[${stringValue(model.vgField(p.channel, {}))}], ` +
+ `${datum}[${stringValue(model.vgField(p.channel, {binSuffix: 'end'}))}]]`
+ : `${datum}[${stringValue(p.field)}]`;
+ })
+ .join(', ');
// Only add a discrete selection to the store if a datum is present _and_
// the interaction isn't occurring on a group mark. This guards against
diff --git ORI/vega-lite/src/normalize/repeater.ts ALT/vega-lite/src/normalize/repeater.ts
index 4034174bb..c832e2b73 100644
--- ORI/vega-lite/src/normalize/repeater.ts
+++ ALT/vega-lite/src/normalize/repeater.ts
@@ -145,9 +145,10 @@ function replaceRepeaterInMapping(
if (isArray(channelDef)) {
// array cannot have condition
- out[channel] = (channelDef as ChannelDef<Field>[]) // somehow we need to cast it here
- .map(cd => replaceRepeaterInChannelDef(cd, repeater))
- .filter(cd => cd);
+ out[channel] =
+ (channelDef as ChannelDef<Field>[]) // somehow we need to cast it here
+ .map(cd => replaceRepeaterInChannelDef(cd, repeater))
+ .filter(cd => cd);
} else {
const cd = replaceRepeaterInChannelDef(channelDef, repeater);
if (cd !== undefined) {
from prettier-regression-testing.
Related Issues (20)
- for 12087 HOT 24
- For 12260 HOT 2
- v3 HOT 23
- for 12349 HOT 5
- For #12359 and #12362 HOT 8
- Regression testing for 2.6 HOT 3
- For 12563 HOT 6
- 2.7 HOT 2
- compact multiline imports HOT 8
- for 13532 (Fix unstable embedded template literals) HOT 4
- misc tests HOT 38
- for 11103 (Break multiline parenthesized logical expression) HOT 8
- for 13621 (Fix template literal indention) HOT 4
- for 13735 (Print `ChainExpression`) HOT 8
- v2.8.0 HOT 5
- 2.8.1 HOT 2
- Misc tests HOT 52
- v3 HOT 23
- 15447 HOT 26
- 3.1 HOT 34
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from prettier-regression-testing.