Commit 4806fefb authored by Rosanny Sihombing's avatar Rosanny Sihombing
Browse files

Merge branch 'cherry-pick-5b932c11' into 'testing'

MLAB-677: Update required modules

See merge request !169
parents b807a4c1 d7204587
Pipeline #6896 passed with stage
in 5 seconds
...@@ -939,7 +939,7 @@ function classAccessorProperty(key, value = null, typeAnnotation = null, decorat ...@@ -939,7 +939,7 @@ function classAccessorProperty(key, value = null, typeAnnotation = null, decorat
}); });
} }
function classPrivateProperty(key, value = null, decorators = null, _static = false) { function classPrivateProperty(key, value = null, decorators = null, _static) {
return (0, _validateNode.default)({ return (0, _validateNode.default)({
type: "ClassPrivateProperty", type: "ClassPrivateProperty",
key, key,
......
...@@ -9,12 +9,8 @@ var _generated = require("../generated"); ...@@ -9,12 +9,8 @@ var _generated = require("../generated");
var _removeTypeDuplicates = require("../../modifications/typescript/removeTypeDuplicates"); var _removeTypeDuplicates = require("../../modifications/typescript/removeTypeDuplicates");
var _index = require("../../validators/generated/index");
function createTSUnionType(typeAnnotations) { function createTSUnionType(typeAnnotations) {
const types = typeAnnotations.map(type => { const types = typeAnnotations.map(type => type.typeAnnotation);
return (0, _index.isTSTypeAnnotation)(type) ? type.typeAnnotation : type;
});
const flattened = (0, _removeTypeDuplicates.default)(types); const flattened = (0, _removeTypeDuplicates.default)(types);
if (flattened.length === 1) { if (flattened.length === 1) {
......
...@@ -278,8 +278,7 @@ defineType("ForStatement", { ...@@ -278,8 +278,7 @@ defineType("ForStatement", {
} }
} }
}); });
const functionCommon = {
const functionCommon = () => ({
params: { params: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Identifier", "Pattern", "RestElement"))) validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Identifier", "Pattern", "RestElement")))
}, },
...@@ -289,11 +288,9 @@ const functionCommon = () => ({ ...@@ -289,11 +288,9 @@ const functionCommon = () => ({
async: { async: {
default: false default: false
} }
}); };
exports.functionCommon = functionCommon; exports.functionCommon = functionCommon;
const functionTypeAnnotationCommon = {
const functionTypeAnnotationCommon = () => ({
returnType: { returnType: {
validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true optional: true
...@@ -302,11 +299,9 @@ const functionTypeAnnotationCommon = () => ({ ...@@ -302,11 +299,9 @@ const functionTypeAnnotationCommon = () => ({
validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"), validate: (0, _utils.assertNodeType)("TypeParameterDeclaration", "TSTypeParameterDeclaration", "Noop"),
optional: true optional: true
} }
}); };
exports.functionTypeAnnotationCommon = functionTypeAnnotationCommon; exports.functionTypeAnnotationCommon = functionTypeAnnotationCommon;
const functionDeclarationCommon = Object.assign({}, functionCommon, {
const functionDeclarationCommon = () => Object.assign({}, functionCommon(), {
declare: { declare: {
validate: (0, _utils.assertValueType)("boolean"), validate: (0, _utils.assertValueType)("boolean"),
optional: true optional: true
...@@ -316,12 +311,11 @@ const functionDeclarationCommon = () => Object.assign({}, functionCommon(), { ...@@ -316,12 +311,11 @@ const functionDeclarationCommon = () => Object.assign({}, functionCommon(), {
optional: true optional: true
} }
}); });
exports.functionDeclarationCommon = functionDeclarationCommon; exports.functionDeclarationCommon = functionDeclarationCommon;
defineType("FunctionDeclaration", { defineType("FunctionDeclaration", {
builder: ["id", "params", "body", "generator", "async"], builder: ["id", "params", "body", "generator", "async"],
visitor: ["id", "params", "body", "returnType", "typeParameters"], visitor: ["id", "params", "body", "returnType", "typeParameters"],
fields: Object.assign({}, functionDeclarationCommon(), functionTypeAnnotationCommon(), { fields: Object.assign({}, functionDeclarationCommon, functionTypeAnnotationCommon, {
body: { body: {
validate: (0, _utils.assertNodeType)("BlockStatement") validate: (0, _utils.assertNodeType)("BlockStatement")
}, },
...@@ -344,7 +338,7 @@ defineType("FunctionDeclaration", { ...@@ -344,7 +338,7 @@ defineType("FunctionDeclaration", {
defineType("FunctionExpression", { defineType("FunctionExpression", {
inherits: "FunctionDeclaration", inherits: "FunctionDeclaration",
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"],
fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, {
id: { id: {
validate: (0, _utils.assertNodeType)("Identifier"), validate: (0, _utils.assertNodeType)("Identifier"),
optional: true optional: true
...@@ -358,24 +352,21 @@ defineType("FunctionExpression", { ...@@ -358,24 +352,21 @@ defineType("FunctionExpression", {
} }
}) })
}); });
const patternLikeCommon = {
const patternLikeCommon = () => ({
typeAnnotation: { typeAnnotation: {
validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"), validate: (0, _utils.assertNodeType)("TypeAnnotation", "TSTypeAnnotation", "Noop"),
optional: true optional: true
}, },
decorators: { decorators: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator")))
optional: true
} }
}); };
exports.patternLikeCommon = patternLikeCommon; exports.patternLikeCommon = patternLikeCommon;
defineType("Identifier", { defineType("Identifier", {
builder: ["name"], builder: ["name"],
visitor: ["typeAnnotation", "decorators"], visitor: ["typeAnnotation", "decorators"],
aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"], aliases: ["Expression", "PatternLike", "LVal", "TSEntityName"],
fields: Object.assign({}, patternLikeCommon(), { fields: Object.assign({}, patternLikeCommon, {
name: { name: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) { validate: (0, _utils.chain)((0, _utils.assertValueType)("string"), Object.assign(function (node, key, val) {
if (!process.env.BABEL_TYPES_8_BREAKING) return; if (!process.env.BABEL_TYPES_8_BREAKING) return;
...@@ -596,7 +587,7 @@ defineType("ObjectExpression", { ...@@ -596,7 +587,7 @@ defineType("ObjectExpression", {
}); });
defineType("ObjectMethod", { defineType("ObjectMethod", {
builder: ["kind", "key", "params", "body", "computed", "generator", "async"], builder: ["kind", "key", "params", "body", "computed", "generator", "async"],
fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, {
kind: Object.assign({ kind: Object.assign({
validate: (0, _utils.assertOneOf)("method", "get", "set") validate: (0, _utils.assertOneOf)("method", "get", "set")
}, !process.env.BABEL_TYPES_8_BREAKING ? { }, !process.env.BABEL_TYPES_8_BREAKING ? {
...@@ -607,7 +598,7 @@ defineType("ObjectMethod", { ...@@ -607,7 +598,7 @@ defineType("ObjectMethod", {
}, },
key: { key: {
validate: function () { validate: function () {
const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"); const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral");
const computed = (0, _utils.assertNodeType)("Expression"); const computed = (0, _utils.assertNodeType)("Expression");
const validator = function (node, key, val) { const validator = function (node, key, val) {
...@@ -615,7 +606,7 @@ defineType("ObjectMethod", { ...@@ -615,7 +606,7 @@ defineType("ObjectMethod", {
validator(node, key, val); validator(node, key, val);
}; };
validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral"]; validator.oneOfNodeTypes = ["Expression", "Identifier", "StringLiteral", "NumericLiteral"];
return validator; return validator;
}() }()
}, },
...@@ -692,7 +683,7 @@ defineType("RestElement", { ...@@ -692,7 +683,7 @@ defineType("RestElement", {
builder: ["argument"], builder: ["argument"],
aliases: ["LVal", "PatternLike"], aliases: ["LVal", "PatternLike"],
deprecatedAlias: "RestProperty", deprecatedAlias: "RestProperty",
fields: Object.assign({}, patternLikeCommon(), { fields: Object.assign({}, patternLikeCommon, {
argument: { argument: {
validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern", "MemberExpression", "TSAsExpression", "TSTypeAssertion", "TSNonNullExpression") validate: !process.env.BABEL_TYPES_8_BREAKING ? (0, _utils.assertNodeType)("LVal") : (0, _utils.assertNodeType)("Identifier", "ArrayPattern", "ObjectPattern", "MemberExpression", "TSAsExpression", "TSTypeAssertion", "TSNonNullExpression")
}, },
...@@ -919,7 +910,7 @@ defineType("AssignmentPattern", { ...@@ -919,7 +910,7 @@ defineType("AssignmentPattern", {
visitor: ["left", "right", "decorators"], visitor: ["left", "right", "decorators"],
builder: ["left", "right"], builder: ["left", "right"],
aliases: ["Pattern", "PatternLike", "LVal"], aliases: ["Pattern", "PatternLike", "LVal"],
fields: Object.assign({}, patternLikeCommon(), { fields: Object.assign({}, patternLikeCommon, {
left: { left: {
validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern", "MemberExpression", "TSAsExpression", "TSTypeAssertion", "TSNonNullExpression") validate: (0, _utils.assertNodeType)("Identifier", "ObjectPattern", "ArrayPattern", "MemberExpression", "TSAsExpression", "TSTypeAssertion", "TSNonNullExpression")
}, },
...@@ -936,7 +927,7 @@ defineType("ArrayPattern", { ...@@ -936,7 +927,7 @@ defineType("ArrayPattern", {
visitor: ["elements", "typeAnnotation"], visitor: ["elements", "typeAnnotation"],
builder: ["elements"], builder: ["elements"],
aliases: ["Pattern", "PatternLike", "LVal"], aliases: ["Pattern", "PatternLike", "LVal"],
fields: Object.assign({}, patternLikeCommon(), { fields: Object.assign({}, patternLikeCommon, {
elements: { elements: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "PatternLike"))) validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeOrValueType)("null", "PatternLike")))
}, },
...@@ -954,7 +945,7 @@ defineType("ArrowFunctionExpression", { ...@@ -954,7 +945,7 @@ defineType("ArrowFunctionExpression", {
builder: ["params", "body", "async"], builder: ["params", "body", "async"],
visitor: ["params", "body", "returnType", "typeParameters"], visitor: ["params", "body", "returnType", "typeParameters"],
aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"], aliases: ["Scopable", "Function", "BlockParent", "FunctionParent", "Expression", "Pureish"],
fields: Object.assign({}, functionCommon(), functionTypeAnnotationCommon(), { fields: Object.assign({}, functionCommon, functionTypeAnnotationCommon, {
expression: { expression: {
validate: (0, _utils.assertValueType)("boolean") validate: (0, _utils.assertValueType)("boolean")
}, },
...@@ -1276,8 +1267,7 @@ defineType("MetaProperty", { ...@@ -1276,8 +1267,7 @@ defineType("MetaProperty", {
} }
} }
}); });
const classMethodOrPropertyCommon = {
const classMethodOrPropertyCommon = () => ({
abstract: { abstract: {
validate: (0, _utils.assertValueType)("boolean"), validate: (0, _utils.assertValueType)("boolean"),
optional: true optional: true
...@@ -1307,13 +1297,11 @@ const classMethodOrPropertyCommon = () => ({ ...@@ -1307,13 +1297,11 @@ const classMethodOrPropertyCommon = () => ({
const validator = node.computed ? computed : normal; const validator = node.computed ? computed : normal;
validator(node, key, val); validator(node, key, val);
}; };
}(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "Expression")) }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "Expression"))
} }
}); };
exports.classMethodOrPropertyCommon = classMethodOrPropertyCommon; exports.classMethodOrPropertyCommon = classMethodOrPropertyCommon;
const classMethodOrDeclareMethodCommon = Object.assign({}, functionCommon, classMethodOrPropertyCommon, {
const classMethodOrDeclareMethodCommon = () => Object.assign({}, functionCommon(), classMethodOrPropertyCommon(), {
params: { params: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Identifier", "Pattern", "RestElement", "TSParameterProperty"))) validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Identifier", "Pattern", "RestElement", "TSParameterProperty")))
}, },
...@@ -1330,13 +1318,12 @@ const classMethodOrDeclareMethodCommon = () => Object.assign({}, functionCommon( ...@@ -1330,13 +1318,12 @@ const classMethodOrDeclareMethodCommon = () => Object.assign({}, functionCommon(
optional: true optional: true
} }
}); });
exports.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon; exports.classMethodOrDeclareMethodCommon = classMethodOrDeclareMethodCommon;
defineType("ClassMethod", { defineType("ClassMethod", {
aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"], aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method"],
builder: ["kind", "key", "params", "body", "computed", "static", "generator", "async"], builder: ["kind", "key", "params", "body", "computed", "static", "generator", "async"],
visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"],
fields: Object.assign({}, classMethodOrDeclareMethodCommon(), functionTypeAnnotationCommon(), { fields: Object.assign({}, classMethodOrDeclareMethodCommon, functionTypeAnnotationCommon, {
body: { body: {
validate: (0, _utils.assertNodeType)("BlockStatement") validate: (0, _utils.assertNodeType)("BlockStatement")
} }
...@@ -1346,7 +1333,7 @@ defineType("ObjectPattern", { ...@@ -1346,7 +1333,7 @@ defineType("ObjectPattern", {
visitor: ["properties", "typeAnnotation", "decorators"], visitor: ["properties", "typeAnnotation", "decorators"],
builder: ["properties"], builder: ["properties"],
aliases: ["Pattern", "PatternLike", "LVal"], aliases: ["Pattern", "PatternLike", "LVal"],
fields: Object.assign({}, patternLikeCommon(), { fields: Object.assign({}, patternLikeCommon, {
properties: { properties: {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("RestElement", "ObjectProperty"))) validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("RestElement", "ObjectProperty")))
} }
...@@ -1528,7 +1515,7 @@ defineType("ClassProperty", { ...@@ -1528,7 +1515,7 @@ defineType("ClassProperty", {
visitor: ["key", "value", "typeAnnotation", "decorators"], visitor: ["key", "value", "typeAnnotation", "decorators"],
builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"],
aliases: ["Property"], aliases: ["Property"],
fields: Object.assign({}, classMethodOrPropertyCommon(), { fields: Object.assign({}, classMethodOrPropertyCommon, {
value: { value: {
validate: (0, _utils.assertNodeType)("Expression"), validate: (0, _utils.assertNodeType)("Expression"),
optional: true optional: true
...@@ -1563,16 +1550,16 @@ defineType("ClassAccessorProperty", { ...@@ -1563,16 +1550,16 @@ defineType("ClassAccessorProperty", {
visitor: ["key", "value", "typeAnnotation", "decorators"], visitor: ["key", "value", "typeAnnotation", "decorators"],
builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"], builder: ["key", "value", "typeAnnotation", "decorators", "computed", "static"],
aliases: ["Property", "Accessor"], aliases: ["Property", "Accessor"],
fields: Object.assign({}, classMethodOrPropertyCommon(), { fields: Object.assign({}, classMethodOrPropertyCommon, {
key: { key: {
validate: (0, _utils.chain)(function () { validate: (0, _utils.chain)(function () {
const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "PrivateName"); const normal = (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "PrivateName");
const computed = (0, _utils.assertNodeType)("Expression"); const computed = (0, _utils.assertNodeType)("Expression");
return function (node, key, val) { return function (node, key, val) {
const validator = node.computed ? computed : normal; const validator = node.computed ? computed : normal;
validator(node, key, val); validator(node, key, val);
}; };
}(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "BigIntLiteral", "Expression", "PrivateName")) }(), (0, _utils.assertNodeType)("Identifier", "StringLiteral", "NumericLiteral", "Expression", "PrivateName"))
}, },
value: { value: {
validate: (0, _utils.assertNodeType)("Expression"), validate: (0, _utils.assertNodeType)("Expression"),
...@@ -1624,10 +1611,6 @@ defineType("ClassPrivateProperty", { ...@@ -1624,10 +1611,6 @@ defineType("ClassPrivateProperty", {
validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))), validate: (0, _utils.chain)((0, _utils.assertValueType)("array"), (0, _utils.assertEach)((0, _utils.assertNodeType)("Decorator"))),
optional: true optional: true
}, },
static: {
validate: (0, _utils.assertValueType)("boolean"),
default: false
},
readonly: { readonly: {
validate: (0, _utils.assertValueType)("boolean"), validate: (0, _utils.assertValueType)("boolean"),
optional: true optional: true
...@@ -1646,11 +1629,7 @@ defineType("ClassPrivateMethod", { ...@@ -1646,11 +1629,7 @@ defineType("ClassPrivateMethod", {
builder: ["kind", "key", "params", "body", "static"], builder: ["kind", "key", "params", "body", "static"],
visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"], visitor: ["key", "params", "body", "decorators", "returnType", "typeParameters"],
aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method", "Private"], aliases: ["Function", "Scopable", "BlockParent", "FunctionParent", "Method", "Private"],
fields: Object.assign({}, classMethodOrDeclareMethodCommon(), functionTypeAnnotationCommon(), { fields: Object.assign({}, classMethodOrDeclareMethodCommon, functionTypeAnnotationCommon, {
kind: {
validate: (0, _utils.assertOneOf)("get", "set", "method"),
default: "method"
},
key: { key: {
validate: (0, _utils.assertNodeType)("PrivateName") validate: (0, _utils.assertNodeType)("PrivateName")
}, },
......
...@@ -8,8 +8,7 @@ var _is = require("../validators/is"); ...@@ -8,8 +8,7 @@ var _is = require("../validators/is");
const defineType = (0, _utils.defineAliasedType)("TypeScript"); const defineType = (0, _utils.defineAliasedType)("TypeScript");
const bool = (0, _utils.assertValueType)("boolean"); const bool = (0, _utils.assertValueType)("boolean");
const tSFunctionTypeAnnotationCommon = {
const tSFunctionTypeAnnotationCommon = () => ({
returnType: { returnType: {
validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"), validate: (0, _utils.assertNodeType)("TSTypeAnnotation", "Noop"),
optional: true optional: true
...@@ -18,8 +17,7 @@ const tSFunctionTypeAnnotationCommon = () => ({ ...@@ -18,8 +17,7 @@ const tSFunctionTypeAnnotationCommon = () => ({
validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"), validate: (0, _utils.assertNodeType)("TSTypeParameterDeclaration", "Noop"),
optional: true optional: true
} }
}); };
defineType("TSParameterProperty", { defineType("TSParameterProperty", {
aliases: ["LVal"], aliases: ["LVal"],
visitor: ["parameter"], visitor: ["parameter"],
...@@ -48,11 +46,11 @@ defineType("TSParameterProperty", { ...@@ -48,11 +46,11 @@ defineType("TSParameterProperty", {
defineType("TSDeclareFunction", { defineType("TSDeclareFunction", {
aliases: ["Statement", "Declaration"], aliases: ["Statement", "Declaration"],
visitor: ["id", "typeParameters", "params", "returnType"], visitor: ["id", "typeParameters", "params", "returnType"],
fields: Object.assign({}, (0, _core.functionDeclarationCommon)(), tSFunctionTypeAnnotationCommon()) fields: Object.assign({}, _core.functionDeclarationCommon, tSFunctionTypeAnnotationCommon)
}); });
defineType("TSDeclareMethod", { defineType("TSDeclareMethod", {
visitor: ["decorators", "key", "typeParameters", "params", "returnType"], visitor: ["decorators", "key", "typeParameters", "params", "returnType"],
fields: Object.assign({}, (0, _core.classMethodOrDeclareMethodCommon)(), tSFunctionTypeAnnotationCommon()) fields: Object.assign({}, _core.classMethodOrDeclareMethodCommon, tSFunctionTypeAnnotationCommon)
}); });
defineType("TSQualifiedName", { defineType("TSQualifiedName", {
aliases: ["TSEntityName"], aliases: ["TSEntityName"],
...@@ -62,33 +60,27 @@ defineType("TSQualifiedName", { ...@@ -62,33 +60,27 @@ defineType("TSQualifiedName", {
right: (0, _utils.validateType)("Identifier") right: (0, _utils.validateType)("Identifier")
} }
}); });
const signatureDeclarationCommon = {
const signatureDeclarationCommon = () => ({
typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"), typeParameters: (0, _utils.validateOptionalType)("TSTypeParameterDeclaration"),
["parameters"]: (0, _utils.validateArrayOfType)(["Identifier", "RestElement"]), ["parameters"]: (0, _utils.validateArrayOfType)(["Identifier", "RestElement"]),
["typeAnnotation"]: (0, _utils.validateOptionalType)("TSTypeAnnotation") ["typeAnnotation"]: (0, _utils.validateOptionalType)("TSTypeAnnotation")
}); };
const callConstructSignatureDeclaration = { const callConstructSignatureDeclaration = {
aliases: ["TSTypeElement"], aliases: ["TSTypeElement"],
visitor: ["typeParameters", "parameters", "typeAnnotation"], visitor: ["typeParameters", "parameters", "typeAnnotation"],
fields: signatureDeclarationCommon() fields: signatureDeclarationCommon
}; };
defineType("TSCallSignatureDeclaration", callConstructSignatureDeclaration); defineType("TSCallSignatureDeclaration", callConstructSignatureDeclaration);
defineType("TSConstructSignatureDeclaration", callConstructSignatureDeclaration); defineType("TSConstructSignatureDeclaration", callConstructSignatureDeclaration);
const namedTypeElementCommon = {
const namedTypeElementCommon = () => ({
key: (0, _utils.validateType)("Expression"), key: (0, _utils.validateType)("Expression"),
computed: { computed: (0, _utils.validate)(bool),
default: false
},
optional: (0, _utils.validateOptional)(bool) optional: (0, _utils.validateOptional)(bool)
}); };
defineType("TSPropertySignature", { defineType("TSPropertySignature", {
aliases: ["TSTypeElement"], aliases: ["TSTypeElement"],
visitor: ["key", "typeAnnotation", "initializer"], visitor: ["key", "typeAnnotation", "initializer"],
fields: Object.assign({}, namedTypeElementCommon(), { fields: Object.assign({}, namedTypeElementCommon, {
readonly: (0, _utils.validateOptional)(bool), readonly: (0, _utils.validateOptional)(bool),
typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"), typeAnnotation: (0, _utils.validateOptionalType)("TSTypeAnnotation"),
initializer: (0, _utils.validateOptionalType)("Expression"), initializer: (0, _utils.validateOptionalType)("Expression"),
...@@ -100,7 +92,7 @@ defineType("TSPropertySignature", { ...@@ -100,7 +92,7 @@ defineType("TSPropertySignature", {
defineType("TSMethodSignature", { defineType("TSMethodSignature", {
aliases: ["TSTypeElement"], aliases: ["TSTypeElement"],
visitor: ["key", "typeParameters", "parameters", "typeAnnotation"], visitor: ["key", "typeParameters", "parameters", "typeAnnotation"],
fields: Object.assign({}, signatureDeclarationCommon(), namedTypeElementCommon(), { fields: Object.assign({}, signatureDeclarationCommon, namedTypeElementCommon, {
kind: { kind: {
validate: (0, _utils.assertOneOf)("method", "get", "set") validate: (0, _utils.assertOneOf)("method", "get", "set")
} }
...@@ -136,10 +128,10 @@ const fnOrCtrBase = { ...@@ -136,10 +128,10 @@ const fnOrCtrBase = {
visitor: ["typeParameters", "parameters", "typeAnnotation"] visitor: ["typeParameters", "parameters", "typeAnnotation"]
}; };
defineType("TSFunctionType", Object.assign({}, fnOrCtrBase, { defineType("TSFunctionType", Object.assign({}, fnOrCtrBase, {
fields: signatureDeclarationCommon() fields: signatureDeclarationCommon
})); }));
defineType("TSConstructorType", Object.assign({}, fnOrCtrBase, { defineType("TSConstructorType", Object.assign({}, fnOrCtrBase, {
fields: Object.assign({}, signatureDeclarationCommon(), { fields: Object.assign({}, signatureDeclarationCommon, {
abstract: (0, _utils.validateOptional)(bool) abstract: (0, _utils.validateOptional)(bool)
}) })
})); }));
......
...@@ -269,7 +269,7 @@ export interface ObjectExpression extends BaseNode { ...@@ -269,7 +269,7 @@ export interface ObjectExpression extends BaseNode {
export interface ObjectMethod extends BaseNode { export interface ObjectMethod extends BaseNode {
type: "ObjectMethod"; type: "ObjectMethod";
kind: "method" | "get" | "set"; kind: "method" | "get" | "set";
key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral; key: Expression | Identifier | StringLiteral | NumericLiteral;
params: Array<Identifier | Pattern | RestElement>; params: Array<Identifier | Pattern | RestElement>;
body: BlockStatement; body: BlockStatement;
computed: boolean; computed: boolean;
...@@ -510,7 +510,7 @@ export interface MetaProperty extends BaseNode { ...@@ -510,7 +510,7 @@ export interface MetaProperty extends BaseNode {
export interface ClassMethod extends BaseNode { export interface ClassMethod extends BaseNode {
type: "ClassMethod"; type: "ClassMethod";
kind: "get" | "set" | "method" | "constructor"; kind: "get" | "set" | "method" | "constructor";
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression; key: Identifier | StringLiteral | NumericLiteral | Expression;
params: Array<Identifier | Pattern | RestElement | TSParameterProperty>; params: Array<Identifier | Pattern | RestElement | TSParameterProperty>;
body: BlockStatement; body: BlockStatement;
computed: boolean; computed: boolean;
...@@ -606,7 +606,7 @@ export interface OptionalCallExpression extends BaseNode { ...@@ -606,7 +606,7 @@ export interface OptionalCallExpression extends BaseNode {
export interface ClassProperty extends BaseNode { export interface ClassProperty extends BaseNode {
type: "ClassProperty"; type: "ClassProperty";
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression; key: Identifier | StringLiteral | NumericLiteral | Expression;
value: Expression | null; value: Expression | null;
typeAnnotation: TypeAnnotation | TSTypeAnnotation | Noop | null; typeAnnotation: TypeAnnotation | TSTypeAnnotation | Noop | null;
decorators: Array<Decorator> | null; decorators: Array<Decorator> | null;
...@@ -624,7 +624,7 @@ export interface ClassProperty extends BaseNode { ...@@ -624,7 +624,7 @@ export interface ClassProperty extends BaseNode {
export interface ClassAccessorProperty extends BaseNode { export interface ClassAccessorProperty extends BaseNode {
type: "ClassAccessorProperty"; type: "ClassAccessorProperty";
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression | PrivateName; key: Identifier | StringLiteral | NumericLiteral | Expression | PrivateName;
value: Expression | null; value: Expression | null;
typeAnnotation: TypeAnnotation | TSTypeAnnotation | Noop | null; typeAnnotation: TypeAnnotation | TSTypeAnnotation | Noop | null;
decorators: Array<Decorator> | null; decorators: Array<Decorator> | null;
...@@ -645,7 +645,7 @@ export interface ClassPrivateProperty extends BaseNode { ...@@ -645,7 +645,7 @@ export interface ClassPrivateProperty extends BaseNode {
key: PrivateName; key: PrivateName;
value: Expression | null; value: Expression | null;
decorators: Array<Decorator> | null; decorators: Array<Decorator> | null;
static: boolean; static: any;
definite: boolean | null; definite: boolean | null;
readonly: boolean | null; readonly: boolean | null;
typeAnnotation: TypeAnnotation | TSTypeAnnotation | Noop | null; typeAnnotation: TypeAnnotation | TSTypeAnnotation | Noop | null;
...@@ -654,7 +654,7 @@ export interface ClassPrivateProperty extends BaseNode { ...@@ -654,7 +654,7 @@ export interface ClassPrivateProperty extends BaseNode {
export interface ClassPrivateMethod extends BaseNode { export interface ClassPrivateMethod extends BaseNode {
type: "ClassPrivateMethod"; type: "ClassPrivateMethod";
kind: "get" | "set" | "method"; kind: "get" | "set" | "method" | "constructor";
key: PrivateName; key: PrivateName;
params: Array<Identifier | Pattern | RestElement | TSParameterProperty>; params: Array<Identifier | Pattern | RestElement | TSParameterProperty>;
body: BlockStatement; body: BlockStatement;
...@@ -1268,7 +1268,7 @@ export interface TSDeclareFunction extends BaseNode { ...@@ -1268,7 +1268,7 @@ export interface TSDeclareFunction extends BaseNode {
export interface TSDeclareMethod extends BaseNode { export interface TSDeclareMethod extends BaseNode {
type: "TSDeclareMethod"; type: "TSDeclareMethod";
decorators: Array<Decorator> | null; decorators: Array<Decorator> | null;
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression; key: Identifier | StringLiteral | NumericLiteral | Expression;
typeParameters: TSTypeParameterDeclaration | Noop | null; typeParameters: TSTypeParameterDeclaration | Noop | null;
params: Array<Identifier | Pattern | RestElement | TSParameterProperty>; params: Array<Identifier | Pattern | RestElement | TSParameterProperty>;
returnType: TSTypeAnnotation | Noop | null; returnType: TSTypeAnnotation | Noop | null;
...@@ -1309,7 +1309,7 @@ export interface TSPropertySignature extends BaseNode { ...@@ -1309,7 +1309,7 @@ export interface TSPropertySignature extends BaseNode {
key: Expression; key: Expression;
typeAnnotation: TSTypeAnnotation | null; typeAnnotation: TSTypeAnnotation | null;
initializer: Expression | null; initializer: Expression | null;
computed: boolean; computed: boolean | null;
kind: "get" | "set"; kind: "get" | "set";
optional: boolean | null; optional: boolean | null;
readonly: boolean | null; readonly: boolean | null;
...@@ -1321,7 +1321,7 @@ export interface TSMethodSignature extends BaseNode { ...@@ -1321,7 +1321,7 @@ export interface TSMethodSignature extends BaseNode {
typeParameters: TSTypeParameterDeclaration | null; typeParameters: TSTypeParameterDeclaration | null;
parameters: Array<Identifier | RestElement>; parameters: Array<Identifier | RestElement>;
typeAnnotation: TSTypeAnnotation | null; typeAnnotation: TSTypeAnnotation | null;
computed: boolean; computed: boolean | null;
kind: "method" | "get" | "set"; kind: "method" | "get" | "set";
optional: boolean | null; optional: boolean | null;
} }
...@@ -1799,7 +1799,7 @@ export function memberExpression(object: Expression, property: Expression | Iden ...@@ -1799,7 +1799,7 @@ export function memberExpression(object: Expression, property: Expression | Iden
export function newExpression(callee: Expression | V8IntrinsicIdentifier, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>): NewExpression; export function newExpression(callee: Expression | V8IntrinsicIdentifier, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>): NewExpression;
export function program(body: Array<Statement>, directives?: Array<Directive>, sourceType?: "script" | "module", interpreter?: InterpreterDirective | null): Program; export function program(body: Array<Statement>, directives?: Array<Directive>, sourceType?: "script" | "module", interpreter?: InterpreterDirective | null): Program;
export function objectExpression(properties: Array<ObjectMethod | ObjectProperty | SpreadElement>): ObjectExpression; export function objectExpression(properties: Array<ObjectMethod | ObjectProperty | SpreadElement>): ObjectExpression;
export function objectMethod(kind: "method" | "get" | "set" | undefined, key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral, params: Array<Identifier | Pattern | RestElement>, body: BlockStatement, computed?: boolean, generator?: boolean, async?: boolean): ObjectMethod; export function objectMethod(kind: "method" | "get" | "set" | undefined, key: Expression | Identifier | StringLiteral | NumericLiteral, params: Array<Identifier | Pattern | RestElement>, body: BlockStatement, computed?: boolean, generator?: boolean, async?: boolean): ObjectMethod;
export function objectProperty(key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral | DecimalLiteral | PrivateName, value: Expression | PatternLike, computed?: boolean, shorthand?: boolean, decorators?: Array<Decorator> | null): ObjectProperty; export function objectProperty(key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral | DecimalLiteral | PrivateName, value: Expression | PatternLike, computed?: boolean, shorthand?: boolean, decorators?: Array<Decorator> | null): ObjectProperty;
export function restElement(argument: LVal): RestElement; export function restElement(argument: LVal): RestElement;
export function returnStatement(argument?: Expression | null): ReturnStatement; export function returnStatement(argument?: Expression | null): ReturnStatement;
...@@ -1832,7 +1832,7 @@ export function importDefaultSpecifier(local: Identifier): ImportDefaultSpecifie ...@@ -1832,7 +1832,7 @@ export function importDefaultSpecifier(local: Identifier): ImportDefaultSpecifie
export function importNamespaceSpecifier(local: Identifier): ImportNamespaceSpecifier; export function importNamespaceSpecifier(local: Identifier): ImportNamespaceSpecifier;
export function importSpecifier(local: Identifier, imported: Identifier | StringLiteral): ImportSpecifier; export function importSpecifier(local: Identifier, imported: Identifier | StringLiteral): ImportSpecifier;
export function metaProperty(meta: Identifier, property: Identifier): MetaProperty; export function metaProperty(meta: Identifier, property: Identifier): MetaProperty;
export function classMethod(kind: "get" | "set" | "method" | "constructor" | undefined, key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, computed?: boolean, _static?: boolean, generator?: boolean, async?: boolean): ClassMethod; export function classMethod(kind: "get" | "set" | "method" | "constructor" | undefined, key: Identifier | StringLiteral | NumericLiteral | Expression, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, computed?: boolean, _static?: boolean, generator?: boolean, async?: boolean): ClassMethod;
export function objectPattern(properties: Array<RestElement | ObjectProperty>): ObjectPattern; export function objectPattern(properties: Array<RestElement | ObjectProperty>): ObjectPattern;
export function spreadElement(argument: Expression): SpreadElement; export function spreadElement(argument: Expression): SpreadElement;
declare function _super(): Super; declare function _super(): Super;
...@@ -1848,10 +1848,10 @@ export function bigIntLiteral(value: string): BigIntLiteral; ...@@ -1848,10 +1848,10 @@ export function bigIntLiteral(value: string): BigIntLiteral;
export function exportNamespaceSpecifier(exported: Identifier): ExportNamespaceSpecifier; export function exportNamespaceSpecifier(exported: Identifier): ExportNamespaceSpecifier;
export function optionalMemberExpression(object: Expression, property: Expression | Identifier, computed: boolean | undefined, optional: boolean): OptionalMemberExpression; export function optionalMemberExpression(object: Expression, property: Expression | Identifier, computed: boolean | undefined, optional: boolean): OptionalMemberExpression;
export function optionalCallExpression(callee: Expression, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>, optional: boolean): OptionalCallExpression; export function optionalCallExpression(callee: Expression, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>, optional: boolean): OptionalCallExpression;
export function classProperty(key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassProperty; export function classProperty(key: Identifier | StringLiteral | NumericLiteral | Expression, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassProperty;
export function classAccessorProperty(key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression | PrivateName, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassAccessorProperty; export function classAccessorProperty(key: Identifier | StringLiteral | NumericLiteral | Expression | PrivateName, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassAccessorProperty;
export function classPrivateProperty(key: PrivateName, value?: Expression | null, decorators?: Array<Decorator> | null, _static?: boolean): ClassPrivateProperty; export function classPrivateProperty(key: PrivateName, value: Expression | null | undefined, decorators: Array<Decorator> | null | undefined, _static: any): ClassPrivateProperty;
export function classPrivateMethod(kind: "get" | "set" | "method" | undefined, key: PrivateName, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, _static?: boolean): ClassPrivateMethod; export function classPrivateMethod(kind: "get" | "set" | "method" | "constructor" | undefined, key: PrivateName, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, _static?: boolean): ClassPrivateMethod;
export function privateName(id: Identifier): PrivateName; export function privateName(id: Identifier): PrivateName;
export function staticBlock(body: Array<Statement>): StaticBlock; export function staticBlock(body: Array<Statement>): StaticBlock;
export function anyTypeAnnotation(): AnyTypeAnnotation; export function anyTypeAnnotation(): AnyTypeAnnotation;
...@@ -1953,7 +1953,7 @@ export function pipelineBareFunction(callee: Expression): PipelineBareFunction; ...@@ -1953,7 +1953,7 @@ export function pipelineBareFunction(callee: Expression): PipelineBareFunction;
export function pipelinePrimaryTopicReference(): PipelinePrimaryTopicReference; export function pipelinePrimaryTopicReference(): PipelinePrimaryTopicReference;
export function tsParameterProperty(parameter: Identifier | AssignmentPattern): TSParameterProperty; export function tsParameterProperty(parameter: Identifier | AssignmentPattern): TSParameterProperty;
export function tsDeclareFunction(id: Identifier | null | undefined, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareFunction; export function tsDeclareFunction(id: Identifier | null | undefined, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareFunction;
export function tsDeclareMethod(decorators: Array<Decorator> | null | undefined, key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareMethod; export function tsDeclareMethod(decorators: Array<Decorator> | null | undefined, key: Identifier | StringLiteral | NumericLiteral | Expression, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareMethod;
export function tsQualifiedName(left: TSEntityName, right: Identifier): TSQualifiedName; export function tsQualifiedName(left: TSEntityName, right: Identifier): TSQualifiedName;
export function tsCallSignatureDeclaration(typeParameters: TSTypeParameterDeclaration | null | undefined, parameters: Array<Identifier | RestElement>, typeAnnotation?: TSTypeAnnotation | null): TSCallSignatureDeclaration; export function tsCallSignatureDeclaration(typeParameters: TSTypeParameterDeclaration | null | undefined, parameters: Array<Identifier | RestElement>, typeAnnotation?: TSTypeAnnotation | null): TSCallSignatureDeclaration;
export function tsConstructSignatureDeclaration(typeParameters: TSTypeParameterDeclaration | null | undefined, parameters: Array<Identifier | RestElement>, typeAnnotation?: TSTypeAnnotation | null): TSConstructSignatureDeclaration; export function tsConstructSignatureDeclaration(typeParameters: TSTypeParameterDeclaration | null | undefined, parameters: Array<Identifier | RestElement>, typeAnnotation?: TSTypeAnnotation | null): TSConstructSignatureDeclaration;
......
...@@ -135,8 +135,8 @@ interface FunctionDeclaration extends BaseNode { ...@@ -135,8 +135,8 @@ interface FunctionDeclaration extends BaseNode {
id?: Identifier | null; id?: Identifier | null;
params: Array<Identifier | Pattern | RestElement>; params: Array<Identifier | Pattern | RestElement>;
body: BlockStatement; body: BlockStatement;
generator: boolean; generator?: boolean;
async: boolean; async?: boolean;
declare?: boolean | null; declare?: boolean | null;
predicate?: DeclaredPredicate | InferredPredicate | null; predicate?: DeclaredPredicate | InferredPredicate | null;
returnType?: TypeAnnotation | TSTypeAnnotation | Noop | null; returnType?: TypeAnnotation | TSTypeAnnotation | Noop | null;
...@@ -147,8 +147,8 @@ interface FunctionExpression extends BaseNode { ...@@ -147,8 +147,8 @@ interface FunctionExpression extends BaseNode {
id?: Identifier | null; id?: Identifier | null;
params: Array<Identifier | Pattern | RestElement>; params: Array<Identifier | Pattern | RestElement>;
body: BlockStatement; body: BlockStatement;
generator: boolean; generator?: boolean;
async: boolean; async?: boolean;
predicate?: DeclaredPredicate | InferredPredicate | null; predicate?: DeclaredPredicate | InferredPredicate | null;
returnType?: TypeAnnotation | TSTypeAnnotation | Noop | null; returnType?: TypeAnnotation | TSTypeAnnotation | Noop | null;
typeParameters?: TypeParameterDeclaration | TSTypeParameterDeclaration | Noop | null; typeParameters?: TypeParameterDeclaration | TSTypeParameterDeclaration | Noop | null;
...@@ -242,12 +242,12 @@ interface ObjectExpression extends BaseNode { ...@@ -242,12 +242,12 @@ interface ObjectExpression extends BaseNode {
interface ObjectMethod extends BaseNode { interface ObjectMethod extends BaseNode {
type: "ObjectMethod"; type: "ObjectMethod";
kind: "method" | "get" | "set"; kind: "method" | "get" | "set";
key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral; key: Expression | Identifier | StringLiteral | NumericLiteral;
params: Array<Identifier | Pattern | RestElement>; params: Array<Identifier | Pattern | RestElement>;
body: BlockStatement; body: BlockStatement;
computed: boolean; computed: boolean;
generator: boolean; generator?: boolean;
async: boolean; async?: boolean;
decorators?: Array<Decorator> | null; decorators?: Array<Decorator> | null;
returnType?: TypeAnnotation | TSTypeAnnotation | Noop | null; returnType?: TypeAnnotation | TSTypeAnnotation | Noop | null;
typeParameters?: TypeParameterDeclaration | TSTypeParameterDeclaration | Noop | null; typeParameters?: TypeParameterDeclaration | TSTypeParameterDeclaration | Noop | null;
...@@ -364,7 +364,7 @@ interface ArrowFunctionExpression extends BaseNode { ...@@ -364,7 +364,7 @@ interface ArrowFunctionExpression extends BaseNode {
type: "ArrowFunctionExpression"; type: "ArrowFunctionExpression";
params: Array<Identifier | Pattern | RestElement>; params: Array<Identifier | Pattern | RestElement>;
body: BlockStatement | Expression; body: BlockStatement | Expression;
async: boolean; async?: boolean;
expression: boolean; expression: boolean;
generator?: boolean; generator?: boolean;
predicate?: DeclaredPredicate | InferredPredicate | null; predicate?: DeclaredPredicate | InferredPredicate | null;
...@@ -459,14 +459,14 @@ interface MetaProperty extends BaseNode { ...@@ -459,14 +459,14 @@ interface MetaProperty extends BaseNode {
} }
interface ClassMethod extends BaseNode { interface ClassMethod extends BaseNode {
type: "ClassMethod"; type: "ClassMethod";
kind: "get" | "set" | "method" | "constructor"; kind?: "get" | "set" | "method" | "constructor";
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression; key: Identifier | StringLiteral | NumericLiteral | Expression;
params: Array<Identifier | Pattern | RestElement | TSParameterProperty>; params: Array<Identifier | Pattern | RestElement | TSParameterProperty>;
body: BlockStatement; body: BlockStatement;
computed: boolean; computed?: boolean;
static: boolean; static?: boolean;
generator: boolean; generator?: boolean;
async: boolean; async?: boolean;
abstract?: boolean | null; abstract?: boolean | null;
access?: "public" | "private" | "protected" | null; access?: "public" | "private" | "protected" | null;
accessibility?: "public" | "private" | "protected" | null; accessibility?: "public" | "private" | "protected" | null;
...@@ -552,12 +552,12 @@ interface OptionalCallExpression extends BaseNode { ...@@ -552,12 +552,12 @@ interface OptionalCallExpression extends BaseNode {
} }
interface ClassProperty extends BaseNode { interface ClassProperty extends BaseNode {
type: "ClassProperty"; type: "ClassProperty";
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression; key: Identifier | StringLiteral | NumericLiteral | Expression;
value?: Expression | null; value?: Expression | null;
typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null; typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null;
decorators?: Array<Decorator> | null; decorators?: Array<Decorator> | null;
computed: boolean; computed?: boolean;
static: boolean; static?: boolean;
abstract?: boolean | null; abstract?: boolean | null;
accessibility?: "public" | "private" | "protected" | null; accessibility?: "public" | "private" | "protected" | null;
declare?: boolean | null; declare?: boolean | null;
...@@ -569,12 +569,12 @@ interface ClassProperty extends BaseNode { ...@@ -569,12 +569,12 @@ interface ClassProperty extends BaseNode {
} }
interface ClassAccessorProperty extends BaseNode { interface ClassAccessorProperty extends BaseNode {
type: "ClassAccessorProperty"; type: "ClassAccessorProperty";
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression | PrivateName; key: Identifier | StringLiteral | NumericLiteral | Expression | PrivateName;
value?: Expression | null; value?: Expression | null;
typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null; typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null;
decorators?: Array<Decorator> | null; decorators?: Array<Decorator> | null;
computed: boolean; computed?: boolean;
static: boolean; static?: boolean;
abstract?: boolean | null; abstract?: boolean | null;
accessibility?: "public" | "private" | "protected" | null; accessibility?: "public" | "private" | "protected" | null;
declare?: boolean | null; declare?: boolean | null;
...@@ -589,7 +589,7 @@ interface ClassPrivateProperty extends BaseNode { ...@@ -589,7 +589,7 @@ interface ClassPrivateProperty extends BaseNode {
key: PrivateName; key: PrivateName;
value?: Expression | null; value?: Expression | null;
decorators?: Array<Decorator> | null; decorators?: Array<Decorator> | null;
static: boolean; static: any;
definite?: boolean | null; definite?: boolean | null;
readonly?: boolean | null; readonly?: boolean | null;
typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null; typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null;
...@@ -597,11 +597,11 @@ interface ClassPrivateProperty extends BaseNode { ...@@ -597,11 +597,11 @@ interface ClassPrivateProperty extends BaseNode {
} }
interface ClassPrivateMethod extends BaseNode { interface ClassPrivateMethod extends BaseNode {
type: "ClassPrivateMethod"; type: "ClassPrivateMethod";
kind: "get" | "set" | "method"; kind?: "get" | "set" | "method" | "constructor";
key: PrivateName; key: PrivateName;
params: Array<Identifier | Pattern | RestElement | TSParameterProperty>; params: Array<Identifier | Pattern | RestElement | TSParameterProperty>;
body: BlockStatement; body: BlockStatement;
static: boolean; static?: boolean;
abstract?: boolean | null; abstract?: boolean | null;
access?: "public" | "private" | "protected" | null; access?: "public" | "private" | "protected" | null;
accessibility?: "public" | "private" | "protected" | null; accessibility?: "public" | "private" | "protected" | null;
...@@ -1109,7 +1109,7 @@ interface TSDeclareFunction extends BaseNode { ...@@ -1109,7 +1109,7 @@ interface TSDeclareFunction extends BaseNode {
interface TSDeclareMethod extends BaseNode { interface TSDeclareMethod extends BaseNode {
type: "TSDeclareMethod"; type: "TSDeclareMethod";
decorators?: Array<Decorator> | null; decorators?: Array<Decorator> | null;
key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression; key: Identifier | StringLiteral | NumericLiteral | Expression;
typeParameters?: TSTypeParameterDeclaration | Noop | null; typeParameters?: TSTypeParameterDeclaration | Noop | null;
params: Array<Identifier | Pattern | RestElement | TSParameterProperty>; params: Array<Identifier | Pattern | RestElement | TSParameterProperty>;
returnType?: TSTypeAnnotation | Noop | null; returnType?: TSTypeAnnotation | Noop | null;
...@@ -1146,7 +1146,7 @@ interface TSPropertySignature extends BaseNode { ...@@ -1146,7 +1146,7 @@ interface TSPropertySignature extends BaseNode {
key: Expression; key: Expression;
typeAnnotation?: TSTypeAnnotation | null; typeAnnotation?: TSTypeAnnotation | null;
initializer?: Expression | null; initializer?: Expression | null;
computed?: boolean; computed?: boolean | null;
kind: "get" | "set"; kind: "get" | "set";
optional?: boolean | null; optional?: boolean | null;
readonly?: boolean | null; readonly?: boolean | null;
...@@ -1157,7 +1157,7 @@ interface TSMethodSignature extends BaseNode { ...@@ -1157,7 +1157,7 @@ interface TSMethodSignature extends BaseNode {
typeParameters?: TSTypeParameterDeclaration | null; typeParameters?: TSTypeParameterDeclaration | null;
parameters: Array<Identifier | RestElement>; parameters: Array<Identifier | RestElement>;
typeAnnotation?: TSTypeAnnotation | null; typeAnnotation?: TSTypeAnnotation | null;
computed?: boolean; computed?: boolean | null;
kind: "method" | "get" | "set"; kind: "method" | "get" | "set";
optional?: boolean | null; optional?: boolean | null;
} }
...@@ -1855,7 +1855,7 @@ declare function createFlowUnionType<T extends FlowType>(types: [T] | Array<T>): ...@@ -1855,7 +1855,7 @@ declare function createFlowUnionType<T extends FlowType>(types: [T] | Array<T>):
* Takes an array of `types` and flattens them, removing duplicates and * Takes an array of `types` and flattens them, removing duplicates and
* returns a `UnionTypeAnnotation` node containing them. * returns a `UnionTypeAnnotation` node containing them.
*/ */
declare function createTSUnionType(typeAnnotations: Array<TSTypeAnnotation | TSType>): TSType; declare function createTSUnionType(typeAnnotations: Array<TSTypeAnnotation>): TSType;
declare function arrayExpression(elements?: Array<null | Expression | SpreadElement>): ArrayExpression; declare function arrayExpression(elements?: Array<null | Expression | SpreadElement>): ArrayExpression;
declare function assignmentExpression(operator: string, left: LVal, right: Expression): AssignmentExpression; declare function assignmentExpression(operator: string, left: LVal, right: Expression): AssignmentExpression;
...@@ -1891,7 +1891,7 @@ declare function memberExpression(object: Expression, property: Expression | Ide ...@@ -1891,7 +1891,7 @@ declare function memberExpression(object: Expression, property: Expression | Ide
declare function newExpression(callee: Expression | V8IntrinsicIdentifier, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>): NewExpression; declare function newExpression(callee: Expression | V8IntrinsicIdentifier, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>): NewExpression;
declare function program(body: Array<Statement>, directives?: Array<Directive>, sourceType?: "script" | "module", interpreter?: InterpreterDirective | null): Program; declare function program(body: Array<Statement>, directives?: Array<Directive>, sourceType?: "script" | "module", interpreter?: InterpreterDirective | null): Program;
declare function objectExpression(properties: Array<ObjectMethod | ObjectProperty | SpreadElement>): ObjectExpression; declare function objectExpression(properties: Array<ObjectMethod | ObjectProperty | SpreadElement>): ObjectExpression;
declare function objectMethod(kind: "method" | "get" | "set" | undefined, key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral, params: Array<Identifier | Pattern | RestElement>, body: BlockStatement, computed?: boolean, generator?: boolean, async?: boolean): ObjectMethod; declare function objectMethod(kind: "method" | "get" | "set" | undefined, key: Expression | Identifier | StringLiteral | NumericLiteral, params: Array<Identifier | Pattern | RestElement>, body: BlockStatement, computed?: boolean, generator?: boolean, async?: boolean): ObjectMethod;
declare function objectProperty(key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral | DecimalLiteral | PrivateName, value: Expression | PatternLike, computed?: boolean, shorthand?: boolean, decorators?: Array<Decorator> | null): ObjectProperty; declare function objectProperty(key: Expression | Identifier | StringLiteral | NumericLiteral | BigIntLiteral | DecimalLiteral | PrivateName, value: Expression | PatternLike, computed?: boolean, shorthand?: boolean, decorators?: Array<Decorator> | null): ObjectProperty;
declare function restElement(argument: LVal): RestElement; declare function restElement(argument: LVal): RestElement;
declare function returnStatement(argument?: Expression | null): ReturnStatement; declare function returnStatement(argument?: Expression | null): ReturnStatement;
...@@ -1924,7 +1924,7 @@ declare function importDefaultSpecifier(local: Identifier): ImportDefaultSpecifi ...@@ -1924,7 +1924,7 @@ declare function importDefaultSpecifier(local: Identifier): ImportDefaultSpecifi
declare function importNamespaceSpecifier(local: Identifier): ImportNamespaceSpecifier; declare function importNamespaceSpecifier(local: Identifier): ImportNamespaceSpecifier;
declare function importSpecifier(local: Identifier, imported: Identifier | StringLiteral): ImportSpecifier; declare function importSpecifier(local: Identifier, imported: Identifier | StringLiteral): ImportSpecifier;
declare function metaProperty(meta: Identifier, property: Identifier): MetaProperty; declare function metaProperty(meta: Identifier, property: Identifier): MetaProperty;
declare function classMethod(kind: "get" | "set" | "method" | "constructor" | undefined, key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, computed?: boolean, _static?: boolean, generator?: boolean, async?: boolean): ClassMethod; declare function classMethod(kind: "get" | "set" | "method" | "constructor" | undefined, key: Identifier | StringLiteral | NumericLiteral | Expression, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, computed?: boolean, _static?: boolean, generator?: boolean, async?: boolean): ClassMethod;
declare function objectPattern(properties: Array<RestElement | ObjectProperty>): ObjectPattern; declare function objectPattern(properties: Array<RestElement | ObjectProperty>): ObjectPattern;
declare function spreadElement(argument: Expression): SpreadElement; declare function spreadElement(argument: Expression): SpreadElement;
declare function _super(): Super; declare function _super(): Super;
...@@ -1943,10 +1943,10 @@ declare function bigIntLiteral(value: string): BigIntLiteral; ...@@ -1943,10 +1943,10 @@ declare function bigIntLiteral(value: string): BigIntLiteral;
declare function exportNamespaceSpecifier(exported: Identifier): ExportNamespaceSpecifier; declare function exportNamespaceSpecifier(exported: Identifier): ExportNamespaceSpecifier;
declare function optionalMemberExpression(object: Expression, property: Expression | Identifier, computed: boolean | undefined, optional: boolean): OptionalMemberExpression; declare function optionalMemberExpression(object: Expression, property: Expression | Identifier, computed: boolean | undefined, optional: boolean): OptionalMemberExpression;
declare function optionalCallExpression(callee: Expression, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>, optional: boolean): OptionalCallExpression; declare function optionalCallExpression(callee: Expression, _arguments: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>, optional: boolean): OptionalCallExpression;
declare function classProperty(key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassProperty; declare function classProperty(key: Identifier | StringLiteral | NumericLiteral | Expression, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassProperty;
declare function classAccessorProperty(key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression | PrivateName, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassAccessorProperty; declare function classAccessorProperty(key: Identifier | StringLiteral | NumericLiteral | Expression | PrivateName, value?: Expression | null, typeAnnotation?: TypeAnnotation | TSTypeAnnotation | Noop | null, decorators?: Array<Decorator> | null, computed?: boolean, _static?: boolean): ClassAccessorProperty;
declare function classPrivateProperty(key: PrivateName, value?: Expression | null, decorators?: Array<Decorator> | null, _static?: boolean): ClassPrivateProperty; declare function classPrivateProperty(key: PrivateName, value: Expression | null | undefined, decorators: Array<Decorator> | null | undefined, _static: any): ClassPrivateProperty;
declare function classPrivateMethod(kind: "get" | "set" | "method" | undefined, key: PrivateName, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, _static?: boolean): ClassPrivateMethod; declare function classPrivateMethod(kind: "get" | "set" | "method" | "constructor" | undefined, key: PrivateName, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, body: BlockStatement, _static?: boolean): ClassPrivateMethod;
declare function privateName(id: Identifier): PrivateName; declare function privateName(id: Identifier): PrivateName;
declare function staticBlock(body: Array<Statement>): StaticBlock; declare function staticBlock(body: Array<Statement>): StaticBlock;
declare function anyTypeAnnotation(): AnyTypeAnnotation; declare function anyTypeAnnotation(): AnyTypeAnnotation;
...@@ -2065,7 +2065,7 @@ declare function tsParameterProperty(parameter: Identifier | AssignmentPattern): ...@@ -2065,7 +2065,7 @@ declare function tsParameterProperty(parameter: Identifier | AssignmentPattern):
declare function tsDeclareFunction(id: Identifier | null | undefined, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareFunction; declare function tsDeclareFunction(id: Identifier | null | undefined, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareFunction;
declare function tsDeclareMethod(decorators: Array<Decorator> | null | undefined, key: Identifier | StringLiteral | NumericLiteral | BigIntLiteral | Expression, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareMethod; declare function tsDeclareMethod(decorators: Array<Decorator> | null | undefined, key: Identifier | StringLiteral | NumericLiteral | Expression, typeParameters: TSTypeParameterDeclaration | Noop | null | undefined, params: Array<Identifier | Pattern | RestElement | TSParameterProperty>, returnType?: TSTypeAnnotation | Noop | null): TSDeclareMethod;
declare function tsQualifiedName(left: TSEntityName, right: Identifier): TSQualifiedName; declare function tsQualifiedName(left: TSEntityName, right: Identifier): TSQualifiedName;
......
...@@ -263,7 +263,7 @@ declare class BabelNodeObjectExpression extends BabelNode { ...@@ -263,7 +263,7 @@ declare class BabelNodeObjectExpression extends BabelNode {
declare class BabelNodeObjectMethod extends BabelNode { declare class BabelNodeObjectMethod extends BabelNode {
type: "ObjectMethod"; type: "ObjectMethod";
kind?: "method" | "get" | "set"; kind?: "method" | "get" | "set";
key: BabelNodeExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral; key: BabelNodeExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral;
params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement>; params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement>;
body: BabelNodeBlockStatement; body: BabelNodeBlockStatement;
computed?: boolean; computed?: boolean;
...@@ -501,7 +501,7 @@ declare class BabelNodeMetaProperty extends BabelNode { ...@@ -501,7 +501,7 @@ declare class BabelNodeMetaProperty extends BabelNode {
declare class BabelNodeClassMethod extends BabelNode { declare class BabelNodeClassMethod extends BabelNode {
type: "ClassMethod"; type: "ClassMethod";
kind?: "get" | "set" | "method" | "constructor"; kind?: "get" | "set" | "method" | "constructor";
key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression; key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression;
params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>; params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>;
body: BabelNodeBlockStatement; body: BabelNodeBlockStatement;
computed?: boolean; computed?: boolean;
...@@ -596,7 +596,7 @@ declare class BabelNodeOptionalCallExpression extends BabelNode { ...@@ -596,7 +596,7 @@ declare class BabelNodeOptionalCallExpression extends BabelNode {
declare class BabelNodeClassProperty extends BabelNode { declare class BabelNodeClassProperty extends BabelNode {
type: "ClassProperty"; type: "ClassProperty";
key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression; key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression;
value?: BabelNodeExpression; value?: BabelNodeExpression;
typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop; typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
decorators?: Array<BabelNodeDecorator>; decorators?: Array<BabelNodeDecorator>;
...@@ -613,7 +613,7 @@ declare class BabelNodeClassProperty extends BabelNode { ...@@ -613,7 +613,7 @@ declare class BabelNodeClassProperty extends BabelNode {
declare class BabelNodeClassAccessorProperty extends BabelNode { declare class BabelNodeClassAccessorProperty extends BabelNode {
type: "ClassAccessorProperty"; type: "ClassAccessorProperty";
key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression | BabelNodePrivateName; key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression | BabelNodePrivateName;
value?: BabelNodeExpression; value?: BabelNodeExpression;
typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop; typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop;
decorators?: Array<BabelNodeDecorator>; decorators?: Array<BabelNodeDecorator>;
...@@ -641,7 +641,7 @@ declare class BabelNodeClassPrivateProperty extends BabelNode { ...@@ -641,7 +641,7 @@ declare class BabelNodeClassPrivateProperty extends BabelNode {
declare class BabelNodeClassPrivateMethod extends BabelNode { declare class BabelNodeClassPrivateMethod extends BabelNode {
type: "ClassPrivateMethod"; type: "ClassPrivateMethod";
kind?: "get" | "set" | "method"; kind?: "get" | "set" | "method" | "constructor";
key: BabelNodePrivateName; key: BabelNodePrivateName;
params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>; params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>;
body: BabelNodeBlockStatement; body: BabelNodeBlockStatement;
...@@ -1240,7 +1240,7 @@ declare class BabelNodeTSDeclareFunction extends BabelNode { ...@@ -1240,7 +1240,7 @@ declare class BabelNodeTSDeclareFunction extends BabelNode {
declare class BabelNodeTSDeclareMethod extends BabelNode { declare class BabelNodeTSDeclareMethod extends BabelNode {
type: "TSDeclareMethod"; type: "TSDeclareMethod";
decorators?: Array<BabelNodeDecorator>; decorators?: Array<BabelNodeDecorator>;
key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression; key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression;
typeParameters?: BabelNodeTSTypeParameterDeclaration | BabelNodeNoop; typeParameters?: BabelNodeTSTypeParameterDeclaration | BabelNodeNoop;
params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>; params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>;
returnType?: BabelNodeTSTypeAnnotation | BabelNodeNoop; returnType?: BabelNodeTSTypeAnnotation | BabelNodeNoop;
...@@ -1694,7 +1694,7 @@ declare module "@babel/types" { ...@@ -1694,7 +1694,7 @@ declare module "@babel/types" {
declare export function newExpression(callee: BabelNodeExpression | BabelNodeV8IntrinsicIdentifier, _arguments: Array<BabelNodeExpression | BabelNodeSpreadElement | BabelNodeJSXNamespacedName | BabelNodeArgumentPlaceholder>): BabelNodeNewExpression; declare export function newExpression(callee: BabelNodeExpression | BabelNodeV8IntrinsicIdentifier, _arguments: Array<BabelNodeExpression | BabelNodeSpreadElement | BabelNodeJSXNamespacedName | BabelNodeArgumentPlaceholder>): BabelNodeNewExpression;
declare export function program(body: Array<BabelNodeStatement>, directives?: Array<BabelNodeDirective>, sourceType?: "script" | "module", interpreter?: BabelNodeInterpreterDirective): BabelNodeProgram; declare export function program(body: Array<BabelNodeStatement>, directives?: Array<BabelNodeDirective>, sourceType?: "script" | "module", interpreter?: BabelNodeInterpreterDirective): BabelNodeProgram;
declare export function objectExpression(properties: Array<BabelNodeObjectMethod | BabelNodeObjectProperty | BabelNodeSpreadElement>): BabelNodeObjectExpression; declare export function objectExpression(properties: Array<BabelNodeObjectMethod | BabelNodeObjectProperty | BabelNodeSpreadElement>): BabelNodeObjectExpression;
declare export function objectMethod(kind?: "method" | "get" | "set", key: BabelNodeExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement>, body: BabelNodeBlockStatement, computed?: boolean, generator?: boolean, async?: boolean): BabelNodeObjectMethod; declare export function objectMethod(kind?: "method" | "get" | "set", key: BabelNodeExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement>, body: BabelNodeBlockStatement, computed?: boolean, generator?: boolean, async?: boolean): BabelNodeObjectMethod;
declare export function objectProperty(key: BabelNodeExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeDecimalLiteral | BabelNodePrivateName, value: BabelNodeExpression | BabelNodePatternLike, computed?: boolean, shorthand?: boolean, decorators?: Array<BabelNodeDecorator>): BabelNodeObjectProperty; declare export function objectProperty(key: BabelNodeExpression | BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeDecimalLiteral | BabelNodePrivateName, value: BabelNodeExpression | BabelNodePatternLike, computed?: boolean, shorthand?: boolean, decorators?: Array<BabelNodeDecorator>): BabelNodeObjectProperty;
declare export function restElement(argument: BabelNodeLVal): BabelNodeRestElement; declare export function restElement(argument: BabelNodeLVal): BabelNodeRestElement;
declare export function returnStatement(argument?: BabelNodeExpression): BabelNodeReturnStatement; declare export function returnStatement(argument?: BabelNodeExpression): BabelNodeReturnStatement;
...@@ -1727,7 +1727,7 @@ declare module "@babel/types" { ...@@ -1727,7 +1727,7 @@ declare module "@babel/types" {
declare export function importNamespaceSpecifier(local: BabelNodeIdentifier): BabelNodeImportNamespaceSpecifier; declare export function importNamespaceSpecifier(local: BabelNodeIdentifier): BabelNodeImportNamespaceSpecifier;
declare export function importSpecifier(local: BabelNodeIdentifier, imported: BabelNodeIdentifier | BabelNodeStringLiteral): BabelNodeImportSpecifier; declare export function importSpecifier(local: BabelNodeIdentifier, imported: BabelNodeIdentifier | BabelNodeStringLiteral): BabelNodeImportSpecifier;
declare export function metaProperty(meta: BabelNodeIdentifier, property: BabelNodeIdentifier): BabelNodeMetaProperty; declare export function metaProperty(meta: BabelNodeIdentifier, property: BabelNodeIdentifier): BabelNodeMetaProperty;
declare export function classMethod(kind?: "get" | "set" | "method" | "constructor", key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>, body: BabelNodeBlockStatement, computed?: boolean, _static?: boolean, generator?: boolean, async?: boolean): BabelNodeClassMethod; declare export function classMethod(kind?: "get" | "set" | "method" | "constructor", key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>, body: BabelNodeBlockStatement, computed?: boolean, _static?: boolean, generator?: boolean, async?: boolean): BabelNodeClassMethod;
declare export function objectPattern(properties: Array<BabelNodeRestElement | BabelNodeObjectProperty>): BabelNodeObjectPattern; declare export function objectPattern(properties: Array<BabelNodeRestElement | BabelNodeObjectProperty>): BabelNodeObjectPattern;
declare export function spreadElement(argument: BabelNodeExpression): BabelNodeSpreadElement; declare export function spreadElement(argument: BabelNodeExpression): BabelNodeSpreadElement;
declare function _super(): BabelNodeSuper; declare function _super(): BabelNodeSuper;
...@@ -1743,10 +1743,10 @@ declare module "@babel/types" { ...@@ -1743,10 +1743,10 @@ declare module "@babel/types" {
declare export function exportNamespaceSpecifier(exported: BabelNodeIdentifier): BabelNodeExportNamespaceSpecifier; declare export function exportNamespaceSpecifier(exported: BabelNodeIdentifier): BabelNodeExportNamespaceSpecifier;
declare export function optionalMemberExpression(object: BabelNodeExpression, property: BabelNodeExpression | BabelNodeIdentifier, computed?: boolean, optional: boolean): BabelNodeOptionalMemberExpression; declare export function optionalMemberExpression(object: BabelNodeExpression, property: BabelNodeExpression | BabelNodeIdentifier, computed?: boolean, optional: boolean): BabelNodeOptionalMemberExpression;
declare export function optionalCallExpression(callee: BabelNodeExpression, _arguments: Array<BabelNodeExpression | BabelNodeSpreadElement | BabelNodeJSXNamespacedName | BabelNodeArgumentPlaceholder>, optional: boolean): BabelNodeOptionalCallExpression; declare export function optionalCallExpression(callee: BabelNodeExpression, _arguments: Array<BabelNodeExpression | BabelNodeSpreadElement | BabelNodeJSXNamespacedName | BabelNodeArgumentPlaceholder>, optional: boolean): BabelNodeOptionalCallExpression;
declare export function classProperty(key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression, value?: BabelNodeExpression, typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, decorators?: Array<BabelNodeDecorator>, computed?: boolean, _static?: boolean): BabelNodeClassProperty; declare export function classProperty(key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression, value?: BabelNodeExpression, typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, decorators?: Array<BabelNodeDecorator>, computed?: boolean, _static?: boolean): BabelNodeClassProperty;
declare export function classAccessorProperty(key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression | BabelNodePrivateName, value?: BabelNodeExpression, typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, decorators?: Array<BabelNodeDecorator>, computed?: boolean, _static?: boolean): BabelNodeClassAccessorProperty; declare export function classAccessorProperty(key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression | BabelNodePrivateName, value?: BabelNodeExpression, typeAnnotation?: BabelNodeTypeAnnotation | BabelNodeTSTypeAnnotation | BabelNodeNoop, decorators?: Array<BabelNodeDecorator>, computed?: boolean, _static?: boolean): BabelNodeClassAccessorProperty;
declare export function classPrivateProperty(key: BabelNodePrivateName, value?: BabelNodeExpression, decorators?: Array<BabelNodeDecorator>, _static?: boolean): BabelNodeClassPrivateProperty; declare export function classPrivateProperty(key: BabelNodePrivateName, value?: BabelNodeExpression, decorators?: Array<BabelNodeDecorator>, _static: any): BabelNodeClassPrivateProperty;
declare export function classPrivateMethod(kind?: "get" | "set" | "method", key: BabelNodePrivateName, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>, body: BabelNodeBlockStatement, _static?: boolean): BabelNodeClassPrivateMethod; declare export function classPrivateMethod(kind?: "get" | "set" | "method" | "constructor", key: BabelNodePrivateName, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>, body: BabelNodeBlockStatement, _static?: boolean): BabelNodeClassPrivateMethod;
declare export function privateName(id: BabelNodeIdentifier): BabelNodePrivateName; declare export function privateName(id: BabelNodeIdentifier): BabelNodePrivateName;
declare export function staticBlock(body: Array<BabelNodeStatement>): BabelNodeStaticBlock; declare export function staticBlock(body: Array<BabelNodeStatement>): BabelNodeStaticBlock;
declare export function anyTypeAnnotation(): BabelNodeAnyTypeAnnotation; declare export function anyTypeAnnotation(): BabelNodeAnyTypeAnnotation;
...@@ -1848,7 +1848,7 @@ declare module "@babel/types" { ...@@ -1848,7 +1848,7 @@ declare module "@babel/types" {
declare export function pipelinePrimaryTopicReference(): BabelNodePipelinePrimaryTopicReference; declare export function pipelinePrimaryTopicReference(): BabelNodePipelinePrimaryTopicReference;
declare export function tsParameterProperty(parameter: BabelNodeIdentifier | BabelNodeAssignmentPattern): BabelNodeTSParameterProperty; declare export function tsParameterProperty(parameter: BabelNodeIdentifier | BabelNodeAssignmentPattern): BabelNodeTSParameterProperty;
declare export function tsDeclareFunction(id?: BabelNodeIdentifier, typeParameters?: BabelNodeTSTypeParameterDeclaration | BabelNodeNoop, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement>, returnType?: BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeTSDeclareFunction; declare export function tsDeclareFunction(id?: BabelNodeIdentifier, typeParameters?: BabelNodeTSTypeParameterDeclaration | BabelNodeNoop, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement>, returnType?: BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeTSDeclareFunction;
declare export function tsDeclareMethod(decorators?: Array<BabelNodeDecorator>, key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeBigIntLiteral | BabelNodeExpression, typeParameters?: BabelNodeTSTypeParameterDeclaration | BabelNodeNoop, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>, returnType?: BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeTSDeclareMethod; declare export function tsDeclareMethod(decorators?: Array<BabelNodeDecorator>, key: BabelNodeIdentifier | BabelNodeStringLiteral | BabelNodeNumericLiteral | BabelNodeExpression, typeParameters?: BabelNodeTSTypeParameterDeclaration | BabelNodeNoop, params: Array<BabelNodeIdentifier | BabelNodePattern | BabelNodeRestElement | BabelNodeTSParameterProperty>, returnType?: BabelNodeTSTypeAnnotation | BabelNodeNoop): BabelNodeTSDeclareMethod;
declare export function tsQualifiedName(left: BabelNodeTSEntityName, right: BabelNodeIdentifier): BabelNodeTSQualifiedName; declare export function tsQualifiedName(left: BabelNodeTSEntityName, right: BabelNodeIdentifier): BabelNodeTSQualifiedName;
declare export function tsCallSignatureDeclaration(typeParameters?: BabelNodeTSTypeParameterDeclaration, parameters: Array<BabelNodeIdentifier | BabelNodeRestElement>, typeAnnotation?: BabelNodeTSTypeAnnotation): BabelNodeTSCallSignatureDeclaration; declare export function tsCallSignatureDeclaration(typeParameters?: BabelNodeTSTypeParameterDeclaration, parameters: Array<BabelNodeIdentifier | BabelNodeRestElement>, typeAnnotation?: BabelNodeTSTypeAnnotation): BabelNodeTSCallSignatureDeclaration;
declare export function tsConstructSignatureDeclaration(typeParameters?: BabelNodeTSTypeParameterDeclaration, parameters: Array<BabelNodeIdentifier | BabelNodeRestElement>, typeAnnotation?: BabelNodeTSTypeAnnotation): BabelNodeTSConstructSignatureDeclaration; declare export function tsConstructSignatureDeclaration(typeParameters?: BabelNodeTSTypeParameterDeclaration, parameters: Array<BabelNodeIdentifier | BabelNodeRestElement>, typeAnnotation?: BabelNodeTSTypeAnnotation): BabelNodeTSConstructSignatureDeclaration;
......
...@@ -12,8 +12,8 @@ function getQualifiedName(node) { ...@@ -12,8 +12,8 @@ function getQualifiedName(node) {
} }
function removeTypeDuplicates(nodes) { function removeTypeDuplicates(nodes) {
const generics = new Map(); const generics = {};
const bases = new Map(); const bases = {};
const typeGroups = new Set(); const typeGroups = new Set();
const types = []; const types = [];
...@@ -30,7 +30,7 @@ function removeTypeDuplicates(nodes) { ...@@ -30,7 +30,7 @@ function removeTypeDuplicates(nodes) {
} }
if ((0, _generated.isFlowBaseAnnotation)(node)) { if ((0, _generated.isFlowBaseAnnotation)(node)) {
bases.set(node.type, node); bases[node.type] = node;
continue; continue;
} }
...@@ -46,8 +46,8 @@ function removeTypeDuplicates(nodes) { ...@@ -46,8 +46,8 @@ function removeTypeDuplicates(nodes) {
if ((0, _generated.isGenericTypeAnnotation)(node)) { if ((0, _generated.isGenericTypeAnnotation)(node)) {
const name = getQualifiedName(node.id); const name = getQualifiedName(node.id);
if (generics.has(name)) { if (generics[name]) {
let existing = generics.get(name); let existing = generics[name];
if (existing.typeParameters) { if (existing.typeParameters) {
if (node.typeParameters) { if (node.typeParameters) {
...@@ -57,7 +57,7 @@ function removeTypeDuplicates(nodes) { ...@@ -57,7 +57,7 @@ function removeTypeDuplicates(nodes) {
existing = node.typeParameters; existing = node.typeParameters;
} }
} else { } else {
generics.set(name, node); generics[name] = node;
} }
continue; continue;
...@@ -66,12 +66,12 @@ function removeTypeDuplicates(nodes) { ...@@ -66,12 +66,12 @@ function removeTypeDuplicates(nodes) {
types.push(node); types.push(node);
} }
for (const [, baseType] of bases) { for (const type of Object.keys(bases)) {
types.push(baseType); types.push(bases[type]);
} }
for (const [, genericName] of generics) { for (const name of Object.keys(generics)) {
types.push(genericName); types.push(generics[name]);
} }
return types; return types;
......
...@@ -7,13 +7,9 @@ exports.default = removeTypeDuplicates; ...@@ -7,13 +7,9 @@ exports.default = removeTypeDuplicates;
var _generated = require("../../validators/generated"); var _generated = require("../../validators/generated");
function getQualifiedName(node) {
return (0, _generated.isIdentifier)(node) ? node.name : `${node.right.name}.${getQualifiedName(node.left)}`;
}
function removeTypeDuplicates(nodes) { function removeTypeDuplicates(nodes) {
const generics = new Map(); const generics = {};
const bases = new Map(); const bases = {};
const typeGroups = new Set(); const typeGroups = new Set();
const types = []; const types = [];
...@@ -30,7 +26,7 @@ function removeTypeDuplicates(nodes) { ...@@ -30,7 +26,7 @@ function removeTypeDuplicates(nodes) {
} }
if ((0, _generated.isTSBaseType)(node)) { if ((0, _generated.isTSBaseType)(node)) {
bases.set(node.type, node); bases[node.type] = node;
continue; continue;
} }
...@@ -43,35 +39,15 @@ function removeTypeDuplicates(nodes) { ...@@ -43,35 +39,15 @@ function removeTypeDuplicates(nodes) {
continue; continue;
} }
if ((0, _generated.isTSTypeReference)(node) && node.typeParameters) {
const name = getQualifiedName(node.typeName);
if (generics.has(name)) {
let existing = generics.get(name);
if (existing.typeParameters) {
if (node.typeParameters) {
existing.typeParameters.params = removeTypeDuplicates(existing.typeParameters.params.concat(node.typeParameters.params));
}
} else {
existing = node.typeParameters;
}
} else {
generics.set(name, node);
}
continue;
}
types.push(node); types.push(node);
} }
for (const [, baseType] of bases) { for (const type of Object.keys(bases)) {
types.push(baseType); types.push(bases[type]);
} }
for (const [, genericName] of generics) { for (const name of Object.keys(generics)) {
types.push(genericName); types.push(generics[name]);
} }
return types; return types;
......
{ {
"name": "@babel/types", "name": "@babel/types",
"version": "7.18.8", "version": "7.18.7",
"description": "Babel Types is a Lodash-esque utility library for AST nodes", "description": "Babel Types is a Lodash-esque utility library for AST nodes",
"author": "The Babel Team (https://babel.dev/team)", "author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-types", "homepage": "https://babel.dev/docs/en/next/babel-types",
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
}, },
"devDependencies": { "devDependencies": {
"@babel/generator": "^7.18.7", "@babel/generator": "^7.18.7",
"@babel/parser": "^7.18.8", "@babel/parser": "^7.18.6",
"chalk": "^4.1.0", "chalk": "^4.1.0",
"glob": "^7.1.7" "glob": "^7.1.7"
}, },
......
v0.4.3 - July 17, 2021
* [`ce78027`](https://github.com/eslint/eslintrc/commit/ce78027f6a319a29fdf0b78ac1e7071373acffc4) Fix: ensure config files are files (#42) (Tom Jenkinson)
* [`95b1c9b`](https://github.com/eslint/eslintrc/commit/95b1c9b30267479a75cd07768f8f9e9cfa63c105) Chore: pin fs-teardown@0.1.1 (#45) (Milos Djermanovic)
* [`593fbe3`](https://github.com/eslint/eslintrc/commit/593fbe3c2c1c5f723f71810963ed21a56caed4c1) Chore: fix failing test (#44) (Tom Jenkinson)
v0.4.2 - June 4, 2021
* [`cc79a4d`](https://github.com/eslint/eslintrc/commit/cc79a4db45a2ca0236a846ed8eba28eea07d4db5) Upgrade: update globals to version 13.6 (#32) (Rouven Weßling)
v0.4.1 - May 7, 2021
* [`aa38ef4`](https://github.com/eslint/eslintrc/commit/aa38ef40c3123f8f534c7f9b0b7c306f5f011dce) Fix: Properly export module resolver (#34) (Richie Bendall)
* [`62ea4bd`](https://github.com/eslint/eslintrc/commit/62ea4bd74b78fbeff12ffb21f1f978817601d4d1) Build: add node v16 (#33) (薛定谔的猫)
* [`7c43d77`](https://github.com/eslint/eslintrc/commit/7c43d7784e39cf0b7b102af64f703cade11252bb) Chore: add tests for built-in rules config schema validation (fixes #15) (#31) (Milos Djermanovic)
* [`d8ea601`](https://github.com/eslint/eslintrc/commit/d8ea601ecb4b9f81cdc332b012b6b1bbc984366c) Chore: Test on Node 15.x (#30) (Milos Djermanovic)
* [`0b2f80d`](https://github.com/eslint/eslintrc/commit/0b2f80d6f6b33e4c5e168b08468867653f726754) Chore: lint test files (#18) (Milos Djermanovic)
v0.4.0 - February 27, 2021
* [`d9a527b`](https://github.com/eslint/eslintrc/commit/d9a527bdb16af46a28d37fa9022131149970a438) New: Implement DotCompat class (#20) (Nicholas C. Zakas)
* [`dac76c0`](https://github.com/eslint/eslintrc/commit/dac76c035a9ab9d315050f688867373966aab288) Chore: Replace usage of lodash with cache set (#29) (Tim van der Lippe)
* [`3ae2d77`](https://github.com/eslint/eslintrc/commit/3ae2d770cb810c026de817e6861e25dac111da9f) Update: add AggregateError global to es2021 environment (#28) (Milos Djermanovic)
v0.3.0 - January 15, 2021
* [`5184490`](https://github.com/eslint/eslintrc/commit/51844902bc4132f264f05a0614f2cdeb89290f68) Upgrade: lodash@4.17.20 (#24) (Milos Djermanovic)
* [`f1179c5`](https://github.com/eslint/eslintrc/commit/f1179c587ae09fabb5c3402598363cfcec2494f7) Update: Implement missing functionality from ESLint port (fixes #12) (#23) (Nicholas C. Zakas)
v0.2.2 - December 5, 2020
* [`1746840`](https://github.com/eslint/eslintrc/commit/17468407c1baf05747cb261c91f7f7b7c2a82422) Fix: include loadRules in internalSlotsMap cache (#19) (Henry Q. Dineen)
* [`f30bb49`](https://github.com/eslint/eslintrc/commit/f30bb4935aaf3f4c1b268490da495a59647e58d8) Chore: Test fixes for CascadingConfigArrayFactory (#17) (Nicholas C. Zakas)
* [`4440df8`](https://github.com/eslint/eslintrc/commit/4440df8237a127e15cbde5c697353e1224f12ec1) Chore: Fix config-array tests (#16) (Nicholas C. Zakas)
* [`7890e02`](https://github.com/eslint/eslintrc/commit/7890e027df530a0fb53bcf5751c8c7a008b2a494) Chore: Test fixes for config-array-factory.js (#13) (Nicholas C. Zakas)
v0.2.1 - October 26, 2020
* [`8b202ff`](https://github.com/eslint/eslintrc/commit/8b202ff866a39efdaad6394fde9f88372afbfca8) Fix: validate schema for built-in rules (#14) (Milos Djermanovic)
* [`04f3cae`](https://github.com/eslint/eslintrc/commit/04f3cae17fe07b2fd0b74fd3e88482b3094e75e3) Fix: cache compiled config schema (#9) (Milos Djermanovic)
v0.2.0 - October 16, 2020
* [`cb12255`](https://github.com/eslint/eslintrc/commit/cb12255b85390e932e1942e479c2c97310149390) Update: Allow eslint:all and eslint:recommended paths to be passed in (#11) (Nicholas C. Zakas)
* [`a75bacd`](https://github.com/eslint/eslintrc/commit/a75bacd9a743a7bbcdb8c59e5d4f9de3dc8b0f20) Chore: use GitHub Actions (#10) (Milos Djermanovic)
v0.1.3 - September 1, 2020
* [`8647a61`](https://github.com/eslint/eslintrc/commit/8647a61991fe121f923d33e96232475209b78210) Fix: version number and eslint-release version (refs #6) (Nicholas C. Zakas)
MIT License
Copyright (c) 2020 ESLint
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# ESLintRC Library
This repository contains the legacy ESLintRC configuration file format for ESLint.
**Note:** This package is not intended for use outside of the ESLint ecosystem. It is ESLint-specific and not intended for use in other programs.
## Installation
You can install the package as follows:
```
npm install @eslint/eslintrc --save-dev
# or
yarn add @eslint/eslintrc -D
```
## Future Usage
**Note:** This package is not intended for public use at this time. The following is an example of how it will be used in the future.
The primary class in this package is `FlatCompat`, which is a utility to translate ESLintRC-style configs into flat configs. Here's how you use it inside of your `eslint.config.js` file:
```js
import { FlatCompat } from "@eslint/eslintrc";
const compat = new FlatCompat();
export default [
// mimic ESLintRC-style extends
compat.extends("standard", "example"),
// mimic environments
compat.env({
es2020: true,
node: true
}),
// mimic plugins
compat.plugins("airbnb", "react"),
// translate an entire config
compat.config({
plugins: ["airbnb", "react"],
extends: "standard",
env: {
es2020: true,
node: true
},
rules: {
semi: "error"
}
})
];
```
## License
MIT License
/**
* @fileoverview Defines a schema for configs.
* @author Sylvan Mably
*/
"use strict";
const baseConfigProperties = {
$schema: { type: "string" },
env: { type: "object" },
extends: { $ref: "#/definitions/stringOrStrings" },
globals: { type: "object" },
overrides: {
type: "array",
items: { $ref: "#/definitions/overrideConfig" },
additionalItems: false
},
parser: { type: ["string", "null"] },
parserOptions: { type: "object" },
plugins: { type: "array" },
processor: { type: "string" },
rules: { type: "object" },
settings: { type: "object" },
noInlineConfig: { type: "boolean" },
reportUnusedDisableDirectives: { type: "boolean" },
ecmaFeatures: { type: "object" } // deprecated; logs a warning when used
};
const configSchema = {
definitions: {
stringOrStrings: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false
}
]
},
stringOrStringsRequired: {
oneOf: [
{ type: "string" },
{
type: "array",
items: { type: "string" },
additionalItems: false,
minItems: 1
}
]
},
// Config at top-level.
objectConfig: {
type: "object",
properties: {
root: { type: "boolean" },
ignorePatterns: { $ref: "#/definitions/stringOrStrings" },
...baseConfigProperties
},
additionalProperties: false
},
// Config in `overrides`.
overrideConfig: {
type: "object",
properties: {
excludedFiles: { $ref: "#/definitions/stringOrStrings" },
files: { $ref: "#/definitions/stringOrStringsRequired" },
...baseConfigProperties
},
required: ["files"],
additionalProperties: false
}
},
$ref: "#/definitions/objectConfig"
};
module.exports = configSchema;
/**
* @fileoverview Defines environment settings and globals.
* @author Elan Shanker
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const globals = require("globals");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Get the object that has difference.
* @param {Record<string,boolean>} current The newer object.
* @param {Record<string,boolean>} prev The older object.
* @returns {Record<string,boolean>} The difference object.
*/
function getDiff(current, prev) {
const retv = {};
for (const [key, value] of Object.entries(current)) {
if (!Object.hasOwnProperty.call(prev, key)) {
retv[key] = value;
}
}
return retv;
}
const newGlobals2015 = getDiff(globals.es2015, globals.es5); // 19 variables such as Promise, Map, ...
const newGlobals2017 = {
Atomics: false,
SharedArrayBuffer: false
};
const newGlobals2020 = {
BigInt: false,
BigInt64Array: false,
BigUint64Array: false,
globalThis: false
};
const newGlobals2021 = {
AggregateError: false,
FinalizationRegistry: false,
WeakRef: false
};
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/** @type {Map<string, import("../lib/shared/types").Environment>} */
module.exports = new Map(Object.entries({
// Language
builtin: {
globals: globals.es5
},
es6: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2015: {
globals: newGlobals2015,
parserOptions: {
ecmaVersion: 6
}
},
es2017: {
globals: { ...newGlobals2015, ...newGlobals2017 },
parserOptions: {
ecmaVersion: 8
}
},
es2020: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020 },
parserOptions: {
ecmaVersion: 11
}
},
es2021: {
globals: { ...newGlobals2015, ...newGlobals2017, ...newGlobals2020, ...newGlobals2021 },
parserOptions: {
ecmaVersion: 12
}
},
// Platforms
browser: {
globals: globals.browser
},
node: {
globals: globals.node,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
"shared-node-browser": {
globals: globals["shared-node-browser"]
},
worker: {
globals: globals.worker
},
serviceworker: {
globals: globals.serviceworker
},
// Frameworks
commonjs: {
globals: globals.commonjs,
parserOptions: {
ecmaFeatures: {
globalReturn: true
}
}
},
amd: {
globals: globals.amd
},
mocha: {
globals: globals.mocha
},
jasmine: {
globals: globals.jasmine
},
jest: {
globals: globals.jest
},
phantomjs: {
globals: globals.phantomjs
},
jquery: {
globals: globals.jquery
},
qunit: {
globals: globals.qunit
},
prototypejs: {
globals: globals.prototypejs
},
shelljs: {
globals: globals.shelljs
},
meteor: {
globals: globals.meteor
},
mongo: {
globals: globals.mongo
},
protractor: {
globals: globals.protractor
},
applescript: {
globals: globals.applescript
},
nashorn: {
globals: globals.nashorn
},
atomtest: {
globals: globals.atomtest
},
embertest: {
globals: globals.embertest
},
webextensions: {
globals: globals.webextensions
},
greasemonkey: {
globals: globals.greasemonkey
}
}));
/**
* @fileoverview Stub eslint:all config
* @author Nicholas C. Zakas
*/
"use strict";
module.exports = {
settings: {
"eslint:all": true
}
};
/**
* @fileoverview Stub eslint:recommended config
* @author Nicholas C. Zakas
*/
"use strict";
module.exports = {
settings: {
"eslint:recommended": true
}
};
/**
* @fileoverview `CascadingConfigArrayFactory` class.
*
* `CascadingConfigArrayFactory` class has a responsibility:
*
* 1. Handles cascading of config files.
*
* It provides two methods:
*
* - `getConfigArrayForFile(filePath)`
* Get the corresponded configuration of a given file. This method doesn't
* throw even if the given file didn't exist.
* - `clearCache()`
* Clear the internal cache. You have to call this method when
* `additionalPluginPool` was updated if `baseConfig` or `cliConfig` depends
* on the additional plugins. (`CLIEngine#addPlugin()` method calls this.)
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const os = require("os");
const path = require("path");
const ConfigValidator = require("./shared/config-validator");
const { emitDeprecationWarning } = require("./shared/deprecation-warnings");
const { ConfigArrayFactory } = require("./config-array-factory");
const { ConfigArray, ConfigDependency, IgnorePattern } = require("./config-array");
const debug = require("debug")("eslintrc:cascading-config-array-factory");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("./shared/types").ConfigData} ConfigData */
/** @typedef {import("./shared/types").Parser} Parser */
/** @typedef {import("./shared/types").Plugin} Plugin */
/** @typedef {import("./shared/types").Rule} Rule */
/** @typedef {ReturnType<ConfigArrayFactory["create"]>} ConfigArray */
/**
* @typedef {Object} CascadingConfigArrayFactoryOptions
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
* @property {ConfigData} [baseConfig] The config by `baseConfig` option.
* @property {ConfigData} [cliConfig] The config by CLI options (`--env`, `--global`, `--ignore-pattern`, `--parser`, `--parser-options`, `--plugin`, and `--rule`). CLI options overwrite the setting in config files.
* @property {string} [cwd] The base directory to start lookup.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]} [rulePaths] The value of `--rulesdir` option.
* @property {string} [specificConfigPath] The value of `--config` option.
* @property {boolean} [useEslintrc] if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
*/
/**
* @typedef {Object} CascadingConfigArrayFactoryInternalSlots
* @property {ConfigArray} baseConfigArray The config array of `baseConfig` option.
* @property {ConfigData} baseConfigData The config data of `baseConfig` option. This is used to reset `baseConfigArray`.
* @property {ConfigArray} cliConfigArray The config array of CLI options.
* @property {ConfigData} cliConfigData The config data of CLI options. This is used to reset `cliConfigArray`.
* @property {ConfigArrayFactory} configArrayFactory The factory for config arrays.
* @property {Map<string, ConfigArray>} configCache The cache from directory paths to config arrays.
* @property {string} cwd The base directory to start lookup.
* @property {WeakMap<ConfigArray, ConfigArray>} finalizeCache The cache from config arrays to finalized config arrays.
* @property {string} [ignorePath] The path to the alternative file of `.eslintignore`.
* @property {string[]|null} rulePaths The value of `--rulesdir` option. This is used to reset `baseConfigArray`.
* @property {string|null} specificConfigPath The value of `--config` option. This is used to reset `cliConfigArray`.
* @property {boolean} useEslintrc if `false` then it doesn't load config files.
* @property {Function} loadRules The function to use to load rules.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
*/
/** @type {WeakMap<CascadingConfigArrayFactory, CascadingConfigArrayFactoryInternalSlots>} */
const internalSlotsMap = new WeakMap();
/**
* Create the config array from `baseConfig` and `rulePaths`.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createBaseConfigArray({
configArrayFactory,
baseConfigData,
rulePaths,
cwd,
loadRules
}) {
const baseConfigArray = configArrayFactory.create(
baseConfigData,
{ name: "BaseConfig" }
);
/*
* Create the config array element for the default ignore patterns.
* This element has `ignorePattern` property that ignores the default
* patterns in the current working directory.
*/
baseConfigArray.unshift(configArrayFactory.create(
{ ignorePatterns: IgnorePattern.DefaultPatterns },
{ name: "DefaultIgnorePattern" }
)[0]);
/*
* Load rules `--rulesdir` option as a pseudo plugin.
* Use a pseudo plugin to define rules of `--rulesdir`, so we can validate
* the rule's options with only information in the config array.
*/
if (rulePaths && rulePaths.length > 0) {
baseConfigArray.push({
type: "config",
name: "--rulesdir",
filePath: "",
plugins: {
"": new ConfigDependency({
definition: {
rules: rulePaths.reduce(
(map, rulesPath) => Object.assign(
map,
loadRules(rulesPath, cwd)
),
{}
)
},
filePath: "",
id: "",
importerName: "--rulesdir",
importerPath: ""
})
}
});
}
return baseConfigArray;
}
/**
* Create the config array from CLI options.
* @param {CascadingConfigArrayFactoryInternalSlots} slots The slots.
* @returns {ConfigArray} The config array of the base configs.
*/
function createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}) {
const cliConfigArray = configArrayFactory.create(
cliConfigData,
{ name: "CLIOptions" }
);
cliConfigArray.unshift(
...(ignorePath
? configArrayFactory.loadESLintIgnore(ignorePath)
: configArrayFactory.loadDefaultESLintIgnore())
);
if (specificConfigPath) {
cliConfigArray.unshift(
...configArrayFactory.loadFile(
specificConfigPath,
{ name: "--config", basePath: cwd }
)
);
}
return cliConfigArray;
}
/**
* The error type when there are files matched by a glob, but all of them have been ignored.
*/
class ConfigurationNotFoundError extends Error {
// eslint-disable-next-line jsdoc/require-description
/**
* @param {string} directoryPath The directory path.
*/
constructor(directoryPath) {
super(`No ESLint configuration found in ${directoryPath}.`);
this.messageTemplate = "no-config-found";
this.messageData = { directoryPath };
}
}
/**
* This class provides the functionality that enumerates every file which is
* matched by given glob patterns and that configuration.
*/
class CascadingConfigArrayFactory {
/**
* Initialize this enumerator.
* @param {CascadingConfigArrayFactoryOptions} options The options.
*/
constructor({
additionalPluginPool = new Map(),
baseConfig: baseConfigData = null,
cliConfig: cliConfigData = null,
cwd = process.cwd(),
ignorePath,
resolvePluginsRelativeTo,
rulePaths = [],
specificConfigPath = null,
useEslintrc = true,
builtInRules = new Map(),
loadRules,
resolver,
eslintRecommendedPath,
eslintAllPath
} = {}) {
const configArrayFactory = new ConfigArrayFactory({
additionalPluginPool,
cwd,
resolvePluginsRelativeTo,
builtInRules,
resolver,
eslintRecommendedPath,
eslintAllPath
});
internalSlotsMap.set(this, {
baseConfigArray: createBaseConfigArray({
baseConfigData,
configArrayFactory,
cwd,
rulePaths,
loadRules,
resolver
}),
baseConfigData,
cliConfigArray: createCLIConfigArray({
cliConfigData,
configArrayFactory,
cwd,
ignorePath,
specificConfigPath
}),
cliConfigData,
configArrayFactory,
configCache: new Map(),
cwd,
finalizeCache: new WeakMap(),
ignorePath,
rulePaths,
specificConfigPath,
useEslintrc,
builtInRules,
loadRules
});
}
/**
* The path to the current working directory.
* This is used by tests.
* @type {string}
*/
get cwd() {
const { cwd } = internalSlotsMap.get(this);
return cwd;
}
/**
* Get the config array of a given file.
* If `filePath` was not given, it returns the config which contains only
* `baseConfigData` and `cliConfigData`.
* @param {string} [filePath] The file path to a file.
* @param {Object} [options] The options.
* @param {boolean} [options.ignoreNotFoundError] If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The config array of the file.
*/
getConfigArrayForFile(filePath, { ignoreNotFoundError = false } = {}) {
const {
baseConfigArray,
cliConfigArray,
cwd
} = internalSlotsMap.get(this);
if (!filePath) {
return new ConfigArray(...baseConfigArray, ...cliConfigArray);
}
const directoryPath = path.dirname(path.resolve(cwd, filePath));
debug(`Load config files for ${directoryPath}.`);
return this._finalizeConfigArray(
this._loadConfigInAncestors(directoryPath),
directoryPath,
ignoreNotFoundError
);
}
/**
* Set the config data to override all configs.
* Require to call `clearCache()` method after this method is called.
* @param {ConfigData} configData The config data to override all configs.
* @returns {void}
*/
setOverrideConfig(configData) {
const slots = internalSlotsMap.get(this);
slots.cliConfigData = configData;
}
/**
* Clear config cache.
* @returns {void}
*/
clearCache() {
const slots = internalSlotsMap.get(this);
slots.baseConfigArray = createBaseConfigArray(slots);
slots.cliConfigArray = createCLIConfigArray(slots);
slots.configCache.clear();
}
/**
* Load and normalize config files from the ancestor directories.
* @param {string} directoryPath The path to a leaf directory.
* @param {boolean} configsExistInSubdirs `true` if configurations exist in subdirectories.
* @returns {ConfigArray} The loaded config.
* @private
*/
_loadConfigInAncestors(directoryPath, configsExistInSubdirs = false) {
const {
baseConfigArray,
configArrayFactory,
configCache,
cwd,
useEslintrc
} = internalSlotsMap.get(this);
if (!useEslintrc) {
return baseConfigArray;
}
let configArray = configCache.get(directoryPath);
// Hit cache.
if (configArray) {
debug(`Cache hit: ${directoryPath}.`);
return configArray;
}
debug(`No cache found: ${directoryPath}.`);
const homePath = os.homedir();
// Consider this is root.
if (directoryPath === homePath && cwd !== homePath) {
debug("Stop traversing because of considered root.");
if (configsExistInSubdirs) {
const filePath = ConfigArrayFactory.getPathToConfigFileInDirectory(directoryPath);
if (filePath) {
emitDeprecationWarning(
filePath,
"ESLINT_PERSONAL_CONFIG_SUPPRESS"
);
}
}
return this._cacheConfig(directoryPath, baseConfigArray);
}
// Load the config on this directory.
try {
configArray = configArrayFactory.loadInDirectory(directoryPath);
} catch (error) {
/* istanbul ignore next */
if (error.code === "EACCES") {
debug("Stop traversing because of 'EACCES' error.");
return this._cacheConfig(directoryPath, baseConfigArray);
}
throw error;
}
if (configArray.length > 0 && configArray.isRoot()) {
debug("Stop traversing because of 'root:true'.");
configArray.unshift(...baseConfigArray);
return this._cacheConfig(directoryPath, configArray);
}
// Load from the ancestors and merge it.
const parentPath = path.dirname(directoryPath);
const parentConfigArray = parentPath && parentPath !== directoryPath
? this._loadConfigInAncestors(
parentPath,
configsExistInSubdirs || configArray.length > 0
)
: baseConfigArray;
if (configArray.length > 0) {
configArray.unshift(...parentConfigArray);
} else {
configArray = parentConfigArray;
}
// Cache and return.
return this._cacheConfig(directoryPath, configArray);
}
/**
* Freeze and cache a given config.
* @param {string} directoryPath The path to a directory as a cache key.
* @param {ConfigArray} configArray The config array as a cache value.
* @returns {ConfigArray} The `configArray` (frozen).
*/
_cacheConfig(directoryPath, configArray) {
const { configCache } = internalSlotsMap.get(this);
Object.freeze(configArray);
configCache.set(directoryPath, configArray);
return configArray;
}
/**
* Finalize a given config array.
* Concatenate `--config` and other CLI options.
* @param {ConfigArray} configArray The parent config array.
* @param {string} directoryPath The path to the leaf directory to find config files.
* @param {boolean} ignoreNotFoundError If `true` then it doesn't throw `ConfigurationNotFoundError`.
* @returns {ConfigArray} The loaded config.
* @private
*/
_finalizeConfigArray(configArray, directoryPath, ignoreNotFoundError) {
const {
cliConfigArray,
configArrayFactory,
finalizeCache,
useEslintrc,
builtInRules
} = internalSlotsMap.get(this);
let finalConfigArray = finalizeCache.get(configArray);
if (!finalConfigArray) {
finalConfigArray = configArray;
// Load the personal config if there are no regular config files.
if (
useEslintrc &&
configArray.every(c => !c.filePath) &&
cliConfigArray.every(c => !c.filePath) // `--config` option can be a file.
) {
const homePath = os.homedir();
debug("Loading the config file of the home directory:", homePath);
const personalConfigArray = configArrayFactory.loadInDirectory(
homePath,
{ name: "PersonalConfig" }
);
if (
personalConfigArray.length > 0 &&
!directoryPath.startsWith(homePath)
) {
const lastElement =
personalConfigArray[personalConfigArray.length - 1];
emitDeprecationWarning(
lastElement.filePath,
"ESLINT_PERSONAL_CONFIG_LOAD"
);
}
finalConfigArray = finalConfigArray.concat(personalConfigArray);
}
// Apply CLI options.
if (cliConfigArray.length > 0) {
finalConfigArray = finalConfigArray.concat(cliConfigArray);
}
// Validate rule settings and environments.
const validator = new ConfigValidator({
builtInRules
});
validator.validateConfigArray(finalConfigArray);
// Cache it.
Object.freeze(finalConfigArray);
finalizeCache.set(configArray, finalConfigArray);
debug(
"Configuration was determined: %o on %s",
finalConfigArray,
directoryPath
);
}
// At least one element (the default ignore patterns) exists.
if (!ignoreNotFoundError && useEslintrc && finalConfigArray.length <= 1) {
throw new ConfigurationNotFoundError(directoryPath);
}
return finalConfigArray;
}
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = { CascadingConfigArrayFactory };
/**
* @fileoverview The factory of `ConfigArray` objects.
*
* This class provides methods to create `ConfigArray` instance.
*
* - `create(configData, options)`
* Create a `ConfigArray` instance from a config data. This is to handle CLI
* options except `--config`.
* - `loadFile(filePath, options)`
* Create a `ConfigArray` instance from a config file. This is to handle
* `--config` option. If the file was not found, throws the following error:
* - If the filename was `*.js`, a `MODULE_NOT_FOUND` error.
* - If the filename was `package.json`, an IO error or an
* `ESLINT_CONFIG_FIELD_NOT_FOUND` error.
* - Otherwise, an IO error such as `ENOENT`.
* - `loadInDirectory(directoryPath, options)`
* Create a `ConfigArray` instance from a config file which is on a given
* directory. This tries to load `.eslintrc.*` or `package.json`. If not
* found, returns an empty `ConfigArray`.
* - `loadESLintIgnore(filePath)`
* Create a `ConfigArray` instance from a config file that is `.eslintignore`
* format. This is to handle `--ignore-path` option.
* - `loadDefaultESLintIgnore()`
* Create a `ConfigArray` instance from `.eslintignore` or `package.json` in
* the current working directory.
*
* `ConfigArrayFactory` class has the responsibility that loads configuration
* files, including loading `extends`, `parser`, and `plugins`. The created
* `ConfigArray` instance has the loaded `extends`, `parser`, and `plugins`.
*
* But this class doesn't handle cascading. `CascadingConfigArrayFactory` class
* handles cascading and hierarchy.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const fs = require("fs");
const path = require("path");
const importFresh = require("import-fresh");
const stripComments = require("strip-json-comments");
const ConfigValidator = require("./shared/config-validator");
const naming = require("./shared/naming");
const ModuleResolver = require("./shared/relative-module-resolver");
const {
ConfigArray,
ConfigDependency,
IgnorePattern,
OverrideTester
} = require("./config-array");
const debug = require("debug")("eslintrc:config-array-factory");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const configFilenames = [
".eslintrc.js",
".eslintrc.cjs",
".eslintrc.yaml",
".eslintrc.yml",
".eslintrc.json",
".eslintrc",
"package.json"
];
// Define types for VSCode IntelliSense.
/** @typedef {import("./shared/types").ConfigData} ConfigData */
/** @typedef {import("./shared/types").OverrideConfigData} OverrideConfigData */
/** @typedef {import("./shared/types").Parser} Parser */
/** @typedef {import("./shared/types").Plugin} Plugin */
/** @typedef {import("./shared/types").Rule} Rule */
/** @typedef {import("./config-array/config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-array/config-dependency").DependentPlugin} DependentPlugin */
/** @typedef {ConfigArray[0]} ConfigArrayElement */
/**
* @typedef {Object} ConfigArrayFactoryOptions
* @property {Map<string,Plugin>} [additionalPluginPool] The map for additional plugins.
* @property {string} [cwd] The path to the current working directory.
* @property {string} [resolvePluginsRelativeTo] A path to the directory that plugins should be resolved from. Defaults to `cwd`.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
*/
/**
* @typedef {Object} ConfigArrayFactoryInternalSlots
* @property {Map<string,Plugin>} additionalPluginPool The map for additional plugins.
* @property {string} cwd The path to the current working directory.
* @property {string | undefined} resolvePluginsRelativeTo An absolute path the the directory that plugins should be resolved from.
* @property {Map<string,Rule>} builtInRules The rules that are built in to ESLint.
* @property {Object} [resolver=ModuleResolver] The module resolver object.
* @property {string} eslintAllPath The path to the definitions for eslint:all.
* @property {string} eslintRecommendedPath The path to the definitions for eslint:recommended.
*/
/**
* @typedef {Object} ConfigArrayFactoryLoadingContext
* @property {string} filePath The path to the current configuration.
* @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
* @property {string} name The name of the current configuration.
* @property {string} pluginBasePath The base path to resolve plugins.
* @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
*/
/**
* @typedef {Object} ConfigArrayFactoryLoadingContext
* @property {string} filePath The path to the current configuration.
* @property {string} matchBasePath The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
* @property {string} name The name of the current configuration.
* @property {"config" | "ignore" | "implicit-processor"} type The type of the current configuration. This is `"config"` in normal. This is `"ignore"` if it came from `.eslintignore`. This is `"implicit-processor"` if it came from legacy file-extension processors.
*/
/** @type {WeakMap<ConfigArrayFactory, ConfigArrayFactoryInternalSlots>} */
const internalSlotsMap = new WeakMap();
/**
* Check if a given string is a file path.
* @param {string} nameOrPath A module name or file path.
* @returns {boolean} `true` if the `nameOrPath` is a file path.
*/
function isFilePath(nameOrPath) {
return (
/^\.{1,2}[/\\]/u.test(nameOrPath) ||
path.isAbsolute(nameOrPath)
);
}
/**
* Convenience wrapper for synchronously reading file contents.
* @param {string} filePath The filename to read.
* @returns {string} The file contents, with the BOM removed.
* @private
*/
function readFile(filePath) {
return fs.readFileSync(filePath, "utf8").replace(/^\ufeff/u, "");
}
/**
* Loads a YAML configuration from a file.
* @param {string} filePath The filename to load.
* @returns {ConfigData} The configuration object from the file.
* @throws {Error} If the file cannot be read.
* @private
*/
function loadYAMLConfigFile(filePath) {
debug(`Loading YAML config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
try {
// empty YAML file can be null, so always use
return yaml.safeLoad(readFile(filePath)) || {};
} catch (e) {
debug(`Error reading YAML file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
/**
* Loads a JSON configuration from a file.
* @param {string} filePath The filename to load.
* @returns {ConfigData} The configuration object from the file.
* @throws {Error} If the file cannot be read.
* @private
*/
function loadJSONConfigFile(filePath) {
debug(`Loading JSON config file: ${filePath}`);
try {
return JSON.parse(stripComments(readFile(filePath)));
} catch (e) {
debug(`Error reading JSON file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
e.messageTemplate = "failed-to-read-json";
e.messageData = {
path: filePath,
message: e.message
};
throw e;
}
}
/**
* Loads a legacy (.eslintrc) configuration from a file.
* @param {string} filePath The filename to load.
* @returns {ConfigData} The configuration object from the file.
* @throws {Error} If the file cannot be read.
* @private
*/
function loadLegacyConfigFile(filePath) {
debug(`Loading legacy config file: ${filePath}`);
// lazy load YAML to improve performance when not used
const yaml = require("js-yaml");
try {
return yaml.safeLoad(stripComments(readFile(filePath))) || /* istanbul ignore next */ {};
} catch (e) {
debug("Error reading YAML file: %s\n%o", filePath, e);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
/**
* Loads a JavaScript configuration from a file.
* @param {string} filePath The filename to load.
* @returns {ConfigData} The configuration object from the file.
* @throws {Error} If the file cannot be read.
* @private
*/
function loadJSConfigFile(filePath) {
debug(`Loading JS config file: ${filePath}`);
try {
return importFresh(filePath);
} catch (e) {
debug(`Error reading JavaScript file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
/**
* Loads a configuration from a package.json file.
* @param {string} filePath The filename to load.
* @returns {ConfigData} The configuration object from the file.
* @throws {Error} If the file cannot be read.
* @private
*/
function loadPackageJSONConfigFile(filePath) {
debug(`Loading package.json config file: ${filePath}`);
try {
const packageData = loadJSONConfigFile(filePath);
if (!Object.hasOwnProperty.call(packageData, "eslintConfig")) {
throw Object.assign(
new Error("package.json file doesn't have 'eslintConfig' field."),
{ code: "ESLINT_CONFIG_FIELD_NOT_FOUND" }
);
}
return packageData.eslintConfig;
} catch (e) {
debug(`Error reading package.json file: ${filePath}`);
e.message = `Cannot read config file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
/**
* Loads a `.eslintignore` from a file.
* @param {string} filePath The filename to load.
* @returns {string[]} The ignore patterns from the file.
* @private
*/
function loadESLintIgnoreFile(filePath) {
debug(`Loading .eslintignore file: ${filePath}`);
try {
return readFile(filePath)
.split(/\r?\n/gu)
.filter(line => line.trim() !== "" && !line.startsWith("#"));
} catch (e) {
debug(`Error reading .eslintignore file: ${filePath}`);
e.message = `Cannot read .eslintignore file: ${filePath}\nError: ${e.message}`;
throw e;
}
}
/**
* Creates an error to notify about a missing config to extend from.
* @param {string} configName The name of the missing config.
* @param {string} importerName The name of the config that imported the missing config
* @param {string} messageTemplate The text template to source error strings from.
* @returns {Error} The error object to throw
* @private
*/
function configInvalidError(configName, importerName, messageTemplate) {
return Object.assign(
new Error(`Failed to load config "${configName}" to extend from.`),
{
messageTemplate,
messageData: { configName, importerName }
}
);
}
/**
* Loads a configuration file regardless of the source. Inspects the file path
* to determine the correctly way to load the config file.
* @param {string} filePath The path to the configuration.
* @returns {ConfigData|null} The configuration information.
* @private
*/
function loadConfigFile(filePath) {
switch (path.extname(filePath)) {
case ".js":
case ".cjs":
return loadJSConfigFile(filePath);
case ".json":
if (path.basename(filePath) === "package.json") {
return loadPackageJSONConfigFile(filePath);
}
return loadJSONConfigFile(filePath);
case ".yaml":
case ".yml":
return loadYAMLConfigFile(filePath);
default:
return loadLegacyConfigFile(filePath);
}
}
/**
* Write debug log.
* @param {string} request The requested module name.
* @param {string} relativeTo The file path to resolve the request relative to.
* @param {string} filePath The resolved file path.
* @returns {void}
*/
function writeDebugLogForLoading(request, relativeTo, filePath) {
/* istanbul ignore next */
if (debug.enabled) {
let nameAndVersion = null;
try {
const packageJsonPath = ModuleResolver.resolve(
`${request}/package.json`,
relativeTo
);
const { version = "unknown" } = require(packageJsonPath);
nameAndVersion = `${request}@${version}`;
} catch (error) {
debug("package.json was not found:", error.message);
nameAndVersion = request;
}
debug("Loaded: %s (%s)", nameAndVersion, filePath);
}
}
/**
* Create a new context with default values.
* @param {ConfigArrayFactoryInternalSlots} slots The internal slots.
* @param {"config" | "ignore" | "implicit-processor" | undefined} providedType The type of the current configuration. Default is `"config"`.
* @param {string | undefined} providedName The name of the current configuration. Default is the relative path from `cwd` to `filePath`.
* @param {string | undefined} providedFilePath The path to the current configuration. Default is empty string.
* @param {string | undefined} providedMatchBasePath The type of the current configuration. Default is the directory of `filePath` or `cwd`.
* @returns {ConfigArrayFactoryLoadingContext} The created context.
*/
function createContext(
{ cwd, resolvePluginsRelativeTo },
providedType,
providedName,
providedFilePath,
providedMatchBasePath
) {
const filePath = providedFilePath
? path.resolve(cwd, providedFilePath)
: "";
const matchBasePath =
(providedMatchBasePath && path.resolve(cwd, providedMatchBasePath)) ||
(filePath && path.dirname(filePath)) ||
cwd;
const name =
providedName ||
(filePath && path.relative(cwd, filePath)) ||
"";
const pluginBasePath =
resolvePluginsRelativeTo ||
(filePath && path.dirname(filePath)) ||
cwd;
const type = providedType || "config";
return { filePath, matchBasePath, name, pluginBasePath, type };
}
/**
* Normalize a given plugin.
* - Ensure the object to have four properties: configs, environments, processors, and rules.
* - Ensure the object to not have other properties.
* @param {Plugin} plugin The plugin to normalize.
* @returns {Plugin} The normalized plugin.
*/
function normalizePlugin(plugin) {
return {
configs: plugin.configs || {},
environments: plugin.environments || {},
processors: plugin.processors || {},
rules: plugin.rules || {}
};
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* The factory of `ConfigArray` objects.
*/
class ConfigArrayFactory {
/**
* Initialize this instance.
* @param {ConfigArrayFactoryOptions} [options] The map for additional plugins.
*/
constructor({
additionalPluginPool = new Map(),
cwd = process.cwd(),
resolvePluginsRelativeTo,
builtInRules,
resolver = ModuleResolver,
eslintAllPath,
eslintRecommendedPath
} = {}) {
internalSlotsMap.set(this, {
additionalPluginPool,
cwd,
resolvePluginsRelativeTo:
resolvePluginsRelativeTo &&
path.resolve(cwd, resolvePluginsRelativeTo),
builtInRules,
resolver,
eslintAllPath,
eslintRecommendedPath
});
}
/**
* Create `ConfigArray` instance from a config data.
* @param {ConfigData|null} configData The config data to create.
* @param {Object} [options] The options.
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
* @param {string} [options.filePath] The path to this config data.
* @param {string} [options.name] The config name.
* @returns {ConfigArray} Loaded config.
*/
create(configData, { basePath, filePath, name } = {}) {
if (!configData) {
return new ConfigArray();
}
const slots = internalSlotsMap.get(this);
const ctx = createContext(slots, "config", name, filePath, basePath);
const elements = this._normalizeConfigData(configData, ctx);
return new ConfigArray(...elements);
}
/**
* Load a config file.
* @param {string} filePath The path to a config file.
* @param {Object} [options] The options.
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
* @param {string} [options.name] The config name.
* @returns {ConfigArray} Loaded config.
*/
loadFile(filePath, { basePath, name } = {}) {
const slots = internalSlotsMap.get(this);
const ctx = createContext(slots, "config", name, filePath, basePath);
return new ConfigArray(...this._loadConfigData(ctx));
}
/**
* Load the config file on a given directory if exists.
* @param {string} directoryPath The path to a directory.
* @param {Object} [options] The options.
* @param {string} [options.basePath] The base path to resolve relative paths in `overrides[].files`, `overrides[].excludedFiles`, and `ignorePatterns`.
* @param {string} [options.name] The config name.
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
*/
loadInDirectory(directoryPath, { basePath, name } = {}) {
const slots = internalSlotsMap.get(this);
for (const filename of configFilenames) {
const ctx = createContext(
slots,
"config",
name,
path.join(directoryPath, filename),
basePath
);
if (fs.existsSync(ctx.filePath) && fs.statSync(ctx.filePath).isFile()) {
let configData;
try {
configData = loadConfigFile(ctx.filePath);
} catch (error) {
if (!error || error.code !== "ESLINT_CONFIG_FIELD_NOT_FOUND") {
throw error;
}
}
if (configData) {
debug(`Config file found: ${ctx.filePath}`);
return new ConfigArray(
...this._normalizeConfigData(configData, ctx)
);
}
}
}
debug(`Config file not found on ${directoryPath}`);
return new ConfigArray();
}
/**
* Check if a config file on a given directory exists or not.
* @param {string} directoryPath The path to a directory.
* @returns {string | null} The path to the found config file. If not found then null.
*/
static getPathToConfigFileInDirectory(directoryPath) {
for (const filename of configFilenames) {
const filePath = path.join(directoryPath, filename);
if (fs.existsSync(filePath)) {
if (filename === "package.json") {
try {
loadPackageJSONConfigFile(filePath);
return filePath;
} catch { /* ignore */ }
} else {
return filePath;
}
}
}
return null;
}
/**
* Load `.eslintignore` file.
* @param {string} filePath The path to a `.eslintignore` file to load.
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
*/
loadESLintIgnore(filePath) {
const slots = internalSlotsMap.get(this);
const ctx = createContext(
slots,
"ignore",
void 0,
filePath,
slots.cwd
);
const ignorePatterns = loadESLintIgnoreFile(ctx.filePath);
return new ConfigArray(
...this._normalizeESLintIgnoreData(ignorePatterns, ctx)
);
}
/**
* Load `.eslintignore` file in the current working directory.
* @returns {ConfigArray} Loaded config. An empty `ConfigArray` if any config doesn't exist.
*/
loadDefaultESLintIgnore() {
const slots = internalSlotsMap.get(this);
const eslintIgnorePath = path.resolve(slots.cwd, ".eslintignore");
const packageJsonPath = path.resolve(slots.cwd, "package.json");
if (fs.existsSync(eslintIgnorePath)) {
return this.loadESLintIgnore(eslintIgnorePath);
}
if (fs.existsSync(packageJsonPath)) {
const data = loadJSONConfigFile(packageJsonPath);
if (Object.hasOwnProperty.call(data, "eslintIgnore")) {
if (!Array.isArray(data.eslintIgnore)) {
throw new Error("Package.json eslintIgnore property requires an array of paths");
}
const ctx = createContext(
slots,
"ignore",
"eslintIgnore in package.json",
packageJsonPath,
slots.cwd
);
return new ConfigArray(
...this._normalizeESLintIgnoreData(data.eslintIgnore, ctx)
);
}
}
return new ConfigArray();
}
/**
* Load a given config file.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} Loaded config.
* @private
*/
_loadConfigData(ctx) {
return this._normalizeConfigData(loadConfigFile(ctx.filePath), ctx);
}
/**
* Normalize a given `.eslintignore` data to config array elements.
* @param {string[]} ignorePatterns The patterns to ignore files.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
*_normalizeESLintIgnoreData(ignorePatterns, ctx) {
const elements = this._normalizeObjectConfigData(
{ ignorePatterns },
ctx
);
// Set `ignorePattern.loose` flag for backward compatibility.
for (const element of elements) {
if (element.ignorePattern) {
element.ignorePattern.loose = true;
}
yield element;
}
}
/**
* Normalize a given config to an array.
* @param {ConfigData} configData The config data to normalize.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
_normalizeConfigData(configData, ctx) {
const validator = new ConfigValidator();
validator.validateConfigSchema(configData, ctx.name || ctx.filePath);
return this._normalizeObjectConfigData(configData, ctx);
}
/**
* Normalize a given config to an array.
* @param {ConfigData|OverrideConfigData} configData The config data to normalize.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
*_normalizeObjectConfigData(configData, ctx) {
const { files, excludedFiles, ...configBody } = configData;
const criteria = OverrideTester.create(
files,
excludedFiles,
ctx.matchBasePath
);
const elements = this._normalizeObjectConfigDataBody(configBody, ctx);
// Apply the criteria to every element.
for (const element of elements) {
/*
* Merge the criteria.
* This is for the `overrides` entries that came from the
* configurations of `overrides[].extends`.
*/
element.criteria = OverrideTester.and(criteria, element.criteria);
/*
* Remove `root` property to ignore `root` settings which came from
* `extends` in `overrides`.
*/
if (element.criteria) {
element.root = void 0;
}
yield element;
}
}
/**
* Normalize a given config to an array.
* @param {ConfigData} configData The config data to normalize.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
*_normalizeObjectConfigDataBody(
{
env,
extends: extend,
globals,
ignorePatterns,
noInlineConfig,
parser: parserName,
parserOptions,
plugins: pluginList,
processor,
reportUnusedDisableDirectives,
root,
rules,
settings,
overrides: overrideList = []
},
ctx
) {
const extendList = Array.isArray(extend) ? extend : [extend];
const ignorePattern = ignorePatterns && new IgnorePattern(
Array.isArray(ignorePatterns) ? ignorePatterns : [ignorePatterns],
ctx.matchBasePath
);
// Flatten `extends`.
for (const extendName of extendList.filter(Boolean)) {
yield* this._loadExtends(extendName, ctx);
}
// Load parser & plugins.
const parser = parserName && this._loadParser(parserName, ctx);
const plugins = pluginList && this._loadPlugins(pluginList, ctx);
// Yield pseudo config data for file extension processors.
if (plugins) {
yield* this._takeFileExtensionProcessors(plugins, ctx);
}
// Yield the config data except `extends` and `overrides`.
yield {
// Debug information.
type: ctx.type,
name: ctx.name,
filePath: ctx.filePath,
// Config data.
criteria: null,
env,
globals,
ignorePattern,
noInlineConfig,
parser,
parserOptions,
plugins,
processor,
reportUnusedDisableDirectives,
root,
rules,
settings
};
// Flatten `overries`.
for (let i = 0; i < overrideList.length; ++i) {
yield* this._normalizeObjectConfigData(
overrideList[i],
{ ...ctx, name: `${ctx.name}#overrides[${i}]` }
);
}
}
/**
* Load configs of an element in `extends`.
* @param {string} extendName The name of a base config.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
_loadExtends(extendName, ctx) {
debug("Loading {extends:%j} relative to %s", extendName, ctx.filePath);
try {
if (extendName.startsWith("eslint:")) {
return this._loadExtendedBuiltInConfig(extendName, ctx);
}
if (extendName.startsWith("plugin:")) {
return this._loadExtendedPluginConfig(extendName, ctx);
}
return this._loadExtendedShareableConfig(extendName, ctx);
} catch (error) {
error.message += `\nReferenced from: ${ctx.filePath || ctx.name}`;
throw error;
}
}
/**
* Load configs of an element in `extends`.
* @param {string} extendName The name of a base config.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
_loadExtendedBuiltInConfig(extendName, ctx) {
const { eslintAllPath, eslintRecommendedPath } = internalSlotsMap.get(this);
if (extendName === "eslint:recommended") {
return this._loadConfigData({
...ctx,
filePath: eslintRecommendedPath,
name: `${ctx.name} » ${extendName}`
});
}
if (extendName === "eslint:all") {
return this._loadConfigData({
...ctx,
filePath: eslintAllPath,
name: `${ctx.name} » ${extendName}`
});
}
throw configInvalidError(extendName, ctx.name, "extend-config-missing");
}
/**
* Load configs of an element in `extends`.
* @param {string} extendName The name of a base config.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
_loadExtendedPluginConfig(extendName, ctx) {
const slashIndex = extendName.lastIndexOf("/");
if (slashIndex === -1) {
throw configInvalidError(extendName, ctx.filePath, "plugin-invalid");
}
const pluginName = extendName.slice("plugin:".length, slashIndex);
const configName = extendName.slice(slashIndex + 1);
if (isFilePath(pluginName)) {
throw new Error("'extends' cannot use a file path for plugins.");
}
const plugin = this._loadPlugin(pluginName, ctx);
const configData =
plugin.definition &&
plugin.definition.configs[configName];
if (configData) {
return this._normalizeConfigData(configData, {
...ctx,
filePath: plugin.filePath || ctx.filePath,
name: `${ctx.name} » plugin:${plugin.id}/${configName}`
});
}
throw plugin.error || configInvalidError(extendName, ctx.filePath, "extend-config-missing");
}
/**
* Load configs of an element in `extends`.
* @param {string} extendName The name of a base config.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The normalized config.
* @private
*/
_loadExtendedShareableConfig(extendName, ctx) {
const { cwd, resolver } = internalSlotsMap.get(this);
const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
let request;
if (isFilePath(extendName)) {
request = extendName;
} else if (extendName.startsWith(".")) {
request = `./${extendName}`; // For backward compatibility. A ton of tests depended on this behavior.
} else {
request = naming.normalizePackageName(
extendName,
"eslint-config"
);
}
let filePath;
try {
filePath = resolver.resolve(request, relativeTo);
} catch (error) {
/* istanbul ignore else */
if (error && error.code === "MODULE_NOT_FOUND") {
throw configInvalidError(extendName, ctx.filePath, "extend-config-missing");
}
throw error;
}
writeDebugLogForLoading(request, relativeTo, filePath);
return this._loadConfigData({
...ctx,
filePath,
name: `${ctx.name} » ${request}`
});
}
/**
* Load given plugins.
* @param {string[]} names The plugin names to load.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {Record<string,DependentPlugin>} The loaded parser.
* @private
*/
_loadPlugins(names, ctx) {
return names.reduce((map, name) => {
if (isFilePath(name)) {
throw new Error("Plugins array cannot includes file paths.");
}
const plugin = this._loadPlugin(name, ctx);
map[plugin.id] = plugin;
return map;
}, {});
}
/**
* Load a given parser.
* @param {string} nameOrPath The package name or the path to a parser file.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {DependentParser} The loaded parser.
*/
_loadParser(nameOrPath, ctx) {
debug("Loading parser %j from %s", nameOrPath, ctx.filePath);
const { cwd } = internalSlotsMap.get(this);
const relativeTo = ctx.filePath || path.join(cwd, "__placeholder__.js");
try {
const filePath = ModuleResolver.resolve(nameOrPath, relativeTo);
writeDebugLogForLoading(nameOrPath, relativeTo, filePath);
return new ConfigDependency({
definition: require(filePath),
filePath,
id: nameOrPath,
importerName: ctx.name,
importerPath: ctx.filePath
});
} catch (error) {
// If the parser name is "espree", load the espree of ESLint.
if (nameOrPath === "espree") {
debug("Fallback espree.");
return new ConfigDependency({
definition: require("espree"),
filePath: require.resolve("espree"),
id: nameOrPath,
importerName: ctx.name,
importerPath: ctx.filePath
});
}
debug("Failed to load parser '%s' declared in '%s'.", nameOrPath, ctx.name);
error.message = `Failed to load parser '${nameOrPath}' declared in '${ctx.name}': ${error.message}`;
return new ConfigDependency({
error,
id: nameOrPath,
importerName: ctx.name,
importerPath: ctx.filePath
});
}
}
/**
* Load a given plugin.
* @param {string} name The plugin name to load.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {DependentPlugin} The loaded plugin.
* @private
*/
_loadPlugin(name, ctx) {
debug("Loading plugin %j from %s", name, ctx.filePath);
const { additionalPluginPool } = internalSlotsMap.get(this);
const request = naming.normalizePackageName(name, "eslint-plugin");
const id = naming.getShorthandName(request, "eslint-plugin");
const relativeTo = path.join(ctx.pluginBasePath, "__placeholder__.js");
if (name.match(/\s+/u)) {
const error = Object.assign(
new Error(`Whitespace found in plugin name '${name}'`),
{
messageTemplate: "whitespace-found",
messageData: { pluginName: request }
}
);
return new ConfigDependency({
error,
id,
importerName: ctx.name,
importerPath: ctx.filePath
});
}
// Check for additional pool.
const plugin =
additionalPluginPool.get(request) ||
additionalPluginPool.get(id);
if (plugin) {
return new ConfigDependency({
definition: normalizePlugin(plugin),
filePath: "", // It's unknown where the plugin came from.
id,
importerName: ctx.name,
importerPath: ctx.filePath
});
}
let filePath;
let error;
try {
filePath = ModuleResolver.resolve(request, relativeTo);
} catch (resolveError) {
error = resolveError;
/* istanbul ignore else */
if (error && error.code === "MODULE_NOT_FOUND") {
error.messageTemplate = "plugin-missing";
error.messageData = {
pluginName: request,
resolvePluginsRelativeTo: ctx.pluginBasePath,
importerName: ctx.name
};
}
}
if (filePath) {
try {
writeDebugLogForLoading(request, relativeTo, filePath);
const startTime = Date.now();
const pluginDefinition = require(filePath);
debug(`Plugin ${filePath} loaded in: ${Date.now() - startTime}ms`);
return new ConfigDependency({
definition: normalizePlugin(pluginDefinition),
filePath,
id,
importerName: ctx.name,
importerPath: ctx.filePath
});
} catch (loadError) {
error = loadError;
}
}
debug("Failed to load plugin '%s' declared in '%s'.", name, ctx.name);
error.message = `Failed to load plugin '${name}' declared in '${ctx.name}': ${error.message}`;
return new ConfigDependency({
error,
id,
importerName: ctx.name,
importerPath: ctx.filePath
});
}
/**
* Take file expression processors as config array elements.
* @param {Record<string,DependentPlugin>} plugins The plugin definitions.
* @param {ConfigArrayFactoryLoadingContext} ctx The loading context.
* @returns {IterableIterator<ConfigArrayElement>} The config array elements of file expression processors.
* @private
*/
*_takeFileExtensionProcessors(plugins, ctx) {
for (const pluginId of Object.keys(plugins)) {
const processors =
plugins[pluginId] &&
plugins[pluginId].definition &&
plugins[pluginId].definition.processors;
if (!processors) {
continue;
}
for (const processorId of Object.keys(processors)) {
if (processorId.startsWith(".")) {
yield* this._normalizeObjectConfigData(
{
files: [`*${processorId}`],
processor: `${pluginId}/${processorId}`
},
{
...ctx,
type: "implicit-processor",
name: `${ctx.name}#processors["${pluginId}/${processorId}"]`
}
);
}
}
}
}
}
module.exports = { ConfigArrayFactory, createContext };
/**
* @fileoverview `ConfigArray` class.
*
* `ConfigArray` class expresses the full of a configuration. It has the entry
* config file, base config files that were extended, loaded parsers, and loaded
* plugins.
*
* `ConfigArray` class provides three properties and two methods.
*
* - `pluginEnvironments`
* - `pluginProcessors`
* - `pluginRules`
* The `Map` objects that contain the members of all plugins that this
* config array contains. Those map objects don't have mutation methods.
* Those keys are the member ID such as `pluginId/memberName`.
* - `isRoot()`
* If `true` then this configuration has `root:true` property.
* - `extractConfig(filePath)`
* Extract the final configuration for a given file. This means merging
* every config array element which that `criteria` property matched. The
* `filePath` argument must be an absolute path.
*
* `ConfigArrayFactory` provides the loading logic of config files.
*
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const { ExtractedConfig } = require("./extracted-config");
const { IgnorePattern } = require("./ignore-pattern");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
// Define types for VSCode IntelliSense.
/** @typedef {import("../../shared/types").Environment} Environment */
/** @typedef {import("../../shared/types").GlobalConf} GlobalConf */
/** @typedef {import("../../shared/types").RuleConf} RuleConf */
/** @typedef {import("../../shared/types").Rule} Rule */
/** @typedef {import("../../shared/types").Plugin} Plugin */
/** @typedef {import("../../shared/types").Processor} Processor */
/** @typedef {import("./config-dependency").DependentParser} DependentParser */
/** @typedef {import("./config-dependency").DependentPlugin} DependentPlugin */
/** @typedef {import("./override-tester")["OverrideTester"]} OverrideTester */
/**
* @typedef {Object} ConfigArrayElement
* @property {string} name The name of this config element.
* @property {string} filePath The path to the source file of this config element.
* @property {InstanceType<OverrideTester>|null} criteria The tester for the `files` and `excludedFiles` of this config element.
* @property {Record<string, boolean>|undefined} env The environment settings.
* @property {Record<string, GlobalConf>|undefined} globals The global variable settings.
* @property {IgnorePattern|undefined} ignorePattern The ignore patterns.
* @property {boolean|undefined} noInlineConfig The flag that disables directive comments.
* @property {DependentParser|undefined} parser The parser loader.
* @property {Object|undefined} parserOptions The parser options.
* @property {Record<string, DependentPlugin>|undefined} plugins The plugin loaders.
* @property {string|undefined} processor The processor name to refer plugin's processor.
* @property {boolean|undefined} reportUnusedDisableDirectives The flag to report unused `eslint-disable` comments.
* @property {boolean|undefined} root The flag to express root.
* @property {Record<string, RuleConf>|undefined} rules The rule settings
* @property {Object|undefined} settings The shared settings.
* @property {"config" | "ignore" | "implicit-processor"} type The element type.
*/
/**
* @typedef {Object} ConfigArrayInternalSlots
* @property {Map<string, ExtractedConfig>} cache The cache to extract configs.
* @property {ReadonlyMap<string, Environment>|null} envMap The map from environment ID to environment definition.
* @property {ReadonlyMap<string, Processor>|null} processorMap The map from processor ID to environment definition.
* @property {ReadonlyMap<string, Rule>|null} ruleMap The map from rule ID to rule definition.
*/
/** @type {WeakMap<ConfigArray, ConfigArrayInternalSlots>} */
const internalSlotsMap = new class extends WeakMap {
get(key) {
let value = super.get(key);
if (!value) {
value = {
cache: new Map(),
envMap: null,
processorMap: null,
ruleMap: null
};
super.set(key, value);
}
return value;
}
}();
/**
* Get the indices which are matched to a given file.
* @param {ConfigArrayElement[]} elements The elements.
* @param {string} filePath The path to a target file.
* @returns {number[]} The indices.
*/
function getMatchedIndices(elements, filePath) {
const indices = [];
for (let i = elements.length - 1; i >= 0; --i) {
const element = elements[i];
if (!element.criteria || (filePath && element.criteria.test(filePath))) {
indices.push(i);
}
}
return indices;
}
/**
* Check if a value is a non-null object.
* @param {any} x The value to check.
* @returns {boolean} `true` if the value is a non-null object.
*/
function isNonNullObject(x) {
return typeof x === "object" && x !== null;
}
/**
* Merge two objects.
*
* Assign every property values of `y` to `x` if `x` doesn't have the property.
* If `x`'s property value is an object, it does recursive.
* @param {Object} target The destination to merge
* @param {Object|undefined} source The source to merge.
* @returns {void}
*/
function mergeWithoutOverwrite(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
if (isNonNullObject(target[key])) {
mergeWithoutOverwrite(target[key], source[key]);
} else if (target[key] === void 0) {
if (isNonNullObject(source[key])) {
target[key] = Array.isArray(source[key]) ? [] : {};
mergeWithoutOverwrite(target[key], source[key]);
} else if (source[key] !== void 0) {
target[key] = source[key];
}
}
}
}
/**
* The error for plugin conflicts.
*/
class PluginConflictError extends Error {
/**
* Initialize this error object.
* @param {string} pluginId The plugin ID.
* @param {{filePath:string, importerName:string}[]} plugins The resolved plugins.
*/
constructor(pluginId, plugins) {
super(`Plugin "${pluginId}" was conflicted between ${plugins.map(p => `"${p.importerName}"`).join(" and ")}.`);
this.messageTemplate = "plugin-conflict";
this.messageData = { pluginId, plugins };
}
}
/**
* Merge plugins.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, DependentPlugin>} target The destination to merge
* @param {Record<string, DependentPlugin>|undefined} source The source to merge.
* @returns {void}
*/
function mergePlugins(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetValue = target[key];
const sourceValue = source[key];
// Adopt the plugin which was found at first.
if (targetValue === void 0) {
if (sourceValue.error) {
throw sourceValue.error;
}
target[key] = sourceValue;
} else if (sourceValue.filePath !== targetValue.filePath) {
throw new PluginConflictError(key, [
{
filePath: targetValue.filePath,
importerName: targetValue.importerName
},
{
filePath: sourceValue.filePath,
importerName: sourceValue.importerName
}
]);
}
}
}
/**
* Merge rule configs.
* `target`'s definition is prior to `source`'s.
* @param {Record<string, Array>} target The destination to merge
* @param {Record<string, RuleConf>|undefined} source The source to merge.
* @returns {void}
*/
function mergeRuleConfigs(target, source) {
if (!isNonNullObject(source)) {
return;
}
for (const key of Object.keys(source)) {
if (key === "__proto__") {
continue;
}
const targetDef = target[key];
const sourceDef = source[key];
// Adopt the rule config which was found at first.
if (targetDef === void 0) {
if (Array.isArray(sourceDef)) {
target[key] = [...sourceDef];
} else {
target[key] = [sourceDef];
}
/*
* If the first found rule config is severity only and the current rule
* config has options, merge the severity and the options.
*/
} else if (
targetDef.length === 1 &&
Array.isArray(sourceDef) &&
sourceDef.length >= 2
) {
targetDef.push(...sourceDef.slice(1));
}
}
}
/**
* Create the extracted config.
* @param {ConfigArray} instance The config elements.
* @param {number[]} indices The indices to use.
* @returns {ExtractedConfig} The extracted config.
*/
function createConfig(instance, indices) {
const config = new ExtractedConfig();
const ignorePatterns = [];
// Merge elements.
for (const index of indices) {
const element = instance[index];
// Adopt the parser which was found at first.
if (!config.parser && element.parser) {
if (element.parser.error) {
throw element.parser.error;
}
config.parser = element.parser;
}
// Adopt the processor which was found at first.
if (!config.processor && element.processor) {
config.processor = element.processor;
}
// Adopt the noInlineConfig which was found at first.
if (config.noInlineConfig === void 0 && element.noInlineConfig !== void 0) {
config.noInlineConfig = element.noInlineConfig;
config.configNameOfNoInlineConfig = element.name;
}
// Adopt the reportUnusedDisableDirectives which was found at first.
if (config.reportUnusedDisableDirectives === void 0 && element.reportUnusedDisableDirectives !== void 0) {
config.reportUnusedDisableDirectives = element.reportUnusedDisableDirectives;
}
// Collect ignorePatterns
if (element.ignorePattern) {
ignorePatterns.push(element.ignorePattern);
}
// Merge others.
mergeWithoutOverwrite(config.env, element.env);
mergeWithoutOverwrite(config.globals, element.globals);
mergeWithoutOverwrite(config.parserOptions, element.parserOptions);
mergeWithoutOverwrite(config.settings, element.settings);
mergePlugins(config.plugins, element.plugins);
mergeRuleConfigs(config.rules, element.rules);
}
// Create the predicate function for ignore patterns.
if (ignorePatterns.length > 0) {
config.ignores = IgnorePattern.createIgnore(ignorePatterns.reverse());
}
return config;
}
/**
* Collect definitions.
* @template T, U
* @param {string} pluginId The plugin ID for prefix.
* @param {Record<string,T>} defs The definitions to collect.
* @param {Map<string, U>} map The map to output.
* @param {function(T): U} [normalize] The normalize function for each value.
* @returns {void}
*/
function collect(pluginId, defs, map, normalize) {
if (defs) {
const prefix = pluginId && `${pluginId}/`;
for (const [key, value] of Object.entries(defs)) {
map.set(
`${prefix}${key}`,
normalize ? normalize(value) : value
);
}
}
}
/**
* Normalize a rule definition.
* @param {Function|Rule} rule The rule definition to normalize.
* @returns {Rule} The normalized rule definition.
*/
function normalizePluginRule(rule) {
return typeof rule === "function" ? { create: rule } : rule;
}
/**
* Delete the mutation methods from a given map.
* @param {Map<any, any>} map The map object to delete.
* @returns {void}
*/
function deleteMutationMethods(map) {
Object.defineProperties(map, {
clear: { configurable: true, value: void 0 },
delete: { configurable: true, value: void 0 },
set: { configurable: true, value: void 0 }
});
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArrayElement[]} elements The config elements.
* @param {ConfigArrayInternalSlots} slots The internal slots.
* @returns {void}
*/
function initPluginMemberMaps(elements, slots) {
const processed = new Set();
slots.envMap = new Map();
slots.processorMap = new Map();
slots.ruleMap = new Map();
for (const element of elements) {
if (!element.plugins) {
continue;
}
for (const [pluginId, value] of Object.entries(element.plugins)) {
const plugin = value.definition;
if (!plugin || processed.has(pluginId)) {
continue;
}
processed.add(pluginId);
collect(pluginId, plugin.environments, slots.envMap);
collect(pluginId, plugin.processors, slots.processorMap);
collect(pluginId, plugin.rules, slots.ruleMap, normalizePluginRule);
}
}
deleteMutationMethods(slots.envMap);
deleteMutationMethods(slots.processorMap);
deleteMutationMethods(slots.ruleMap);
}
/**
* Create `envMap`, `processorMap`, `ruleMap` with the plugins in the config array.
* @param {ConfigArray} instance The config elements.
* @returns {ConfigArrayInternalSlots} The extracted config.
*/
function ensurePluginMemberMaps(instance) {
const slots = internalSlotsMap.get(instance);
if (!slots.ruleMap) {
initPluginMemberMaps(instance, slots);
}
return slots;
}
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
/**
* The Config Array.
*
* `ConfigArray` instance contains all settings, parsers, and plugins.
* You need to call `ConfigArray#extractConfig(filePath)` method in order to
* extract, merge and get only the config data which is related to an arbitrary
* file.
* @extends {Array<ConfigArrayElement>}
*/
class ConfigArray extends Array {
/**
* Get the plugin environments.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Environment>} The plugin environments.
*/
get pluginEnvironments() {
return ensurePluginMemberMaps(this).envMap;
}
/**
* Get the plugin processors.
* The returned map cannot be mutated.
* @type {ReadonlyMap<string, Processor>} The plugin processors.
*/
get pluginProcessors() {
return ensurePluginMemberMaps(this).processorMap;
}
/**
* Get the plugin rules.
* The returned map cannot be mutated.
* @returns {ReadonlyMap<string, Rule>} The plugin rules.
*/
get pluginRules() {
return ensurePluginMemberMaps(this).ruleMap;
}
/**
* Check if this config has `root` flag.
* @returns {boolean} `true` if this config array is root.
*/
isRoot() {
for (let i = this.length - 1; i >= 0; --i) {
const root = this[i].root;
if (typeof root === "boolean") {
return root;
}
}
return false;
}
/**
* Extract the config data which is related to a given file.
* @param {string} filePath The absolute path to the target file.
* @returns {ExtractedConfig} The extracted config data.
*/
extractConfig(filePath) {
const { cache } = internalSlotsMap.get(this);
const indices = getMatchedIndices(this, filePath);
const cacheKey = indices.join(",");
if (!cache.has(cacheKey)) {
cache.set(cacheKey, createConfig(this, indices));
}
return cache.get(cacheKey);
}
/**
* Check if a given path is an additional lint target.
* @param {string} filePath The absolute path to the target file.
* @returns {boolean} `true` if the file is an additional lint target.
*/
isAdditionalTargetPath(filePath) {
for (const { criteria, type } of this) {
if (
type === "config" &&
criteria &&
!criteria.endsWithWildcard &&
criteria.test(filePath)
) {
return true;
}
}
return false;
}
}
const exportObject = {
ConfigArray,
/**
* Get the used extracted configs.
* CLIEngine will use this method to collect used deprecated rules.
* @param {ConfigArray} instance The config array object to get.
* @returns {ExtractedConfig[]} The used extracted configs.
* @private
*/
getUsedExtractedConfigs(instance) {
const { cache } = internalSlotsMap.get(instance);
return Array.from(cache.values());
}
};
module.exports = exportObject;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment