main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
declare const _exports: typeof Components & {
detect(rule: any): (context?: any) => {
[_: string]: Function;
};
};
export = _exports;
/**
* Components
*/
declare class Components {
/**
* Add a node to the components list, or update it if it's already in the list
*
* @param {ASTNode} node The AST node being added.
* @param {number} confidence Confidence in the component detection (0=banned, 1=maybe, 2=yes)
* @returns {Object} Added component object
*/
add(node: ASTNode, confidence: number): any;
/**
* Find a component in the list using its node
*
* @param {ASTNode} node The AST node being searched.
* @returns {Object} Component object, undefined if the component is not found or has confidence value of 0.
*/
get(node: ASTNode): any;
/**
* Update a component in the list
*
* @param {ASTNode} node The AST node being updated.
* @param {Object} props Additional properties to add to the component.
*/
set(node: ASTNode, props: any): void;
/**
* Return the components list
* Components for which we are not confident are not returned
*
* @returns {Object} Components list
*/
list(): any;
/**
* Return the length of the components list
* Components for which we are not confident are not counted
*
* @returns {number} Components list length
*/
length(): number;
/**
* Return the node naming the default React import
* It can be used to determine the local name of import, even if it's imported
* with an unusual name.
*
* @returns {ASTNode} React default import node
*/
getDefaultReactImports(): ASTNode;
/**
* Return the nodes of all React named imports
*
* @returns {Object} The list of React named imports
*/
getNamedReactImports(): any;
/**
* Add the default React import specifier to the scope
*
* @param {ASTNode} specifier The AST Node of the default React import
* @returns {void}
*/
addDefaultReactImport(specifier: ASTNode): void;
/**
* Add a named React import specifier to the scope
*
* @param {ASTNode} specifier The AST Node of a named React import
* @returns {void}
*/
addNamedReactImport(specifier: ASTNode): void;
}
//# sourceMappingURL=Components.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Components.d.ts","sourceRoot":"","sources":["Components.js"],"names":[],"mappings":";;;;;;AA2DA;;GAEG;AACH;IAME;;;;;;OAMG;IACH,UAJW,OAAO,cACP,MAAM,OAmBhB;IAED;;;;;OAKG;IACH,UAHW,OAAO,OAUjB;IAED;;;;;OAKG;IACH,UAHW,OAAO,oBAwBjB;IAED;;;;;OAKG;IACH,YAoCC;IAED;;;;;OAKG;IACH,UAFa,MAAM,CAKlB;IAED;;;;;;OAMG;IACH,0BAFa,OAAO,CAInB;IAED;;;;OAIG;IACH,4BAEC;IAED;;;;;OAKG;IACH,iCAHW,OAAO,GACL,IAAI,CAOhB;IAED;;;;;OAKG;IACH,+BAHW,OAAO,GACL,IAAI,CAOhB;CACF"}

959
node_modules/eslint-plugin-react/lib/util/Components.js generated vendored Normal file
View File

@@ -0,0 +1,959 @@
/**
* @fileoverview Utility class and functions for React components detection
* @author Yannick Croissant
*/
'use strict';
const arrayIncludes = require('array-includes');
const fromEntries = require('object.fromentries');
const values = require('object.values');
const iterFrom = require('es-iterator-helpers/Iterator.from');
const map = require('es-iterator-helpers/Iterator.prototype.map');
const variableUtil = require('./variable');
const pragmaUtil = require('./pragma');
const astUtil = require('./ast');
const componentUtil = require('./componentUtil');
const propTypesUtil = require('./propTypes');
const jsxUtil = require('./jsx');
const usedPropTypesUtil = require('./usedPropTypes');
const defaultPropsUtil = require('./defaultProps');
const isFirstLetterCapitalized = require('./isFirstLetterCapitalized');
const isDestructuredFromPragmaImport = require('./isDestructuredFromPragmaImport');
const eslintUtil = require('./eslint');
const getScope = eslintUtil.getScope;
const getText = eslintUtil.getText;
function getId(node) {
return node ? `${node.range[0]}:${node.range[1]}` : '';
}
function usedPropTypesAreEquivalent(propA, propB) {
if (propA.name === propB.name) {
if (!propA.allNames && !propB.allNames) {
return true;
}
if (Array.isArray(propA.allNames) && Array.isArray(propB.allNames) && propA.allNames.join('') === propB.allNames.join('')) {
return true;
}
return false;
}
return false;
}
function mergeUsedPropTypes(propsList, newPropsList) {
const propsToAdd = newPropsList.filter((newProp) => {
const newPropIsAlreadyInTheList = propsList.some((prop) => usedPropTypesAreEquivalent(prop, newProp));
return !newPropIsAlreadyInTheList;
});
return propsList.concat(propsToAdd);
}
const USE_HOOK_PREFIX_REGEX = /^use[A-Z]/;
const Lists = new WeakMap();
const ReactImports = new WeakMap();
/**
* Components
*/
class Components {
constructor() {
Lists.set(this, {});
ReactImports.set(this, {});
}
/**
* Add a node to the components list, or update it if it's already in the list
*
* @param {ASTNode} node The AST node being added.
* @param {number} confidence Confidence in the component detection (0=banned, 1=maybe, 2=yes)
* @returns {Object} Added component object
*/
add(node, confidence) {
const id = getId(node);
const list = Lists.get(this);
if (list[id]) {
if (confidence === 0 || list[id].confidence === 0) {
list[id].confidence = 0;
} else {
list[id].confidence = Math.max(list[id].confidence, confidence);
}
return list[id];
}
list[id] = {
node,
confidence,
};
return list[id];
}
/**
* Find a component in the list using its node
*
* @param {ASTNode} node The AST node being searched.
* @returns {Object} Component object, undefined if the component is not found or has confidence value of 0.
*/
get(node) {
const id = getId(node);
const item = Lists.get(this)[id];
if (item && item.confidence >= 1) {
return item;
}
return null;
}
/**
* Update a component in the list
*
* @param {ASTNode} node The AST node being updated.
* @param {Object} props Additional properties to add to the component.
*/
set(node, props) {
const list = Lists.get(this);
let component = list[getId(node)];
while (!component || component.confidence < 1) {
node = node.parent;
if (!node) {
return;
}
component = list[getId(node)];
}
Object.assign(
component,
props,
{
usedPropTypes: mergeUsedPropTypes(
component.usedPropTypes || [],
props.usedPropTypes || []
),
}
);
}
/**
* Return the components list
* Components for which we are not confident are not returned
*
* @returns {Object} Components list
*/
list() {
const thisList = Lists.get(this);
const list = {};
const usedPropTypes = {};
// Find props used in components for which we are not confident
Object.keys(thisList).filter((i) => thisList[i].confidence < 2).forEach((i) => {
let component = null;
let node = null;
node = thisList[i].node;
while (!component && node.parent) {
node = node.parent;
// Stop moving up if we reach a decorator
if (node.type === 'Decorator') {
break;
}
component = this.get(node);
}
if (component) {
const newUsedProps = (thisList[i].usedPropTypes || []).filter((propType) => !propType.node || propType.node.kind !== 'init');
const componentId = getId(component.node);
usedPropTypes[componentId] = mergeUsedPropTypes(usedPropTypes[componentId] || [], newUsedProps);
}
});
// Assign used props in not confident components to the parent component
Object.keys(thisList).filter((j) => thisList[j].confidence >= 2).forEach((j) => {
const id = getId(thisList[j].node);
list[j] = thisList[j];
if (usedPropTypes[id]) {
list[j].usedPropTypes = mergeUsedPropTypes(list[j].usedPropTypes || [], usedPropTypes[id]);
}
});
return list;
}
/**
* Return the length of the components list
* Components for which we are not confident are not counted
*
* @returns {number} Components list length
*/
length() {
const list = Lists.get(this);
return values(list).filter((component) => component.confidence >= 2).length;
}
/**
* Return the node naming the default React import
* It can be used to determine the local name of import, even if it's imported
* with an unusual name.
*
* @returns {ASTNode} React default import node
*/
getDefaultReactImports() {
return ReactImports.get(this).defaultReactImports;
}
/**
* Return the nodes of all React named imports
*
* @returns {Object} The list of React named imports
*/
getNamedReactImports() {
return ReactImports.get(this).namedReactImports;
}
/**
* Add the default React import specifier to the scope
*
* @param {ASTNode} specifier The AST Node of the default React import
* @returns {void}
*/
addDefaultReactImport(specifier) {
const info = ReactImports.get(this);
ReactImports.set(this, Object.assign({}, info, {
defaultReactImports: (info.defaultReactImports || []).concat(specifier),
}));
}
/**
* Add a named React import specifier to the scope
*
* @param {ASTNode} specifier The AST Node of a named React import
* @returns {void}
*/
addNamedReactImport(specifier) {
const info = ReactImports.get(this);
ReactImports.set(this, Object.assign({}, info, {
namedReactImports: (info.namedReactImports || []).concat(specifier),
}));
}
}
function getWrapperFunctions(context, pragma) {
const componentWrapperFunctions = context.settings.componentWrapperFunctions || [];
// eslint-disable-next-line arrow-body-style
return componentWrapperFunctions.map((wrapperFunction) => {
return typeof wrapperFunction === 'string'
? { property: wrapperFunction }
: Object.assign({}, wrapperFunction, {
object: wrapperFunction.object === '<pragma>' ? pragma : wrapperFunction.object,
});
}).concat([
{ property: 'forwardRef', object: pragma },
{ property: 'memo', object: pragma },
]);
}
// eslint-disable-next-line valid-jsdoc
/**
* Merge many eslint rules into one
* @param {{[_: string]: Function}[]} rules the returned values for eslint rule.create(context)
* @returns {{[_: string]: Function}} merged rule
*/
function mergeRules(rules) {
/** @type {Map<string, Function[]>} */
const handlersByKey = new Map();
rules.forEach((rule) => {
Object.keys(rule).forEach((key) => {
const fns = handlersByKey.get(key);
if (!fns) {
handlersByKey.set(key, [rule[key]]);
} else {
fns.push(rule[key]);
}
});
});
/** @type {{ [key: string]: Function }} */
return fromEntries(map(iterFrom(handlersByKey), (entry) => [
entry[0],
function mergedHandler(node) {
entry[1].forEach((fn) => {
fn(node);
});
},
]));
}
function componentRule(rule, context) {
const pragma = pragmaUtil.getFromContext(context);
const components = new Components();
const wrapperFunctions = getWrapperFunctions(context, pragma);
// Utilities for component detection
const utils = {
/**
* Check if variable is destructured from pragma import
*
* @param {ASTNode} node The AST node to check
* @param {string} variable The variable name to check
* @returns {boolean} True if createElement is destructured from the pragma
*/
isDestructuredFromPragmaImport(node, variable) {
return isDestructuredFromPragmaImport(context, node, variable);
},
/**
* @param {ASTNode} node
* @param {boolean=} strict
* @returns {boolean}
*/
isReturningJSX(node, strict) {
return jsxUtil.isReturningJSX(context, node, strict, true);
},
isReturningJSXOrNull(node, strict) {
return jsxUtil.isReturningJSX(context, node, strict);
},
isReturningOnlyNull(node) {
return jsxUtil.isReturningOnlyNull(node, context);
},
getPragmaComponentWrapper(node) {
let isPragmaComponentWrapper;
let currentNode = node;
let prevNode;
do {
currentNode = currentNode.parent;
isPragmaComponentWrapper = this.isPragmaComponentWrapper(currentNode);
if (isPragmaComponentWrapper) {
prevNode = currentNode;
}
} while (isPragmaComponentWrapper);
return prevNode;
},
getComponentNameFromJSXElement(node) {
if (node.type !== 'JSXElement') {
return null;
}
if (node.openingElement && node.openingElement.name && node.openingElement.name.name) {
return node.openingElement.name.name;
}
return null;
},
/**
* Getting the first JSX element's name.
* @param {object} node
* @returns {string | null}
*/
getNameOfWrappedComponent(node) {
if (node.length < 1) {
return null;
}
const body = node[0].body;
if (!body) {
return null;
}
if (body.type === 'JSXElement') {
return this.getComponentNameFromJSXElement(body);
}
if (body.type === 'BlockStatement') {
const jsxElement = body.body.find((item) => item.type === 'ReturnStatement');
return jsxElement
&& jsxElement.argument
&& this.getComponentNameFromJSXElement(jsxElement.argument);
}
return null;
},
/**
* Get the list of names of components created till now
* @returns {string | boolean}
*/
getDetectedComponents() {
const list = components.list();
return values(list).filter((val) => {
if (val.node.type === 'ClassDeclaration') {
return true;
}
if (
val.node.type === 'ArrowFunctionExpression'
&& val.node.parent
&& val.node.parent.type === 'VariableDeclarator'
&& val.node.parent.id
) {
return true;
}
return false;
}).map((val) => {
if (val.node.type === 'ArrowFunctionExpression') return val.node.parent.id.name;
return val.node.id && val.node.id.name;
});
},
/**
* It will check whether memo/forwardRef is wrapping existing component or
* creating a new one.
* @param {object} node
* @returns {boolean}
*/
nodeWrapsComponent(node) {
const childComponent = this.getNameOfWrappedComponent(node.arguments);
const componentList = this.getDetectedComponents();
return !!childComponent && arrayIncludes(componentList, childComponent);
},
isPragmaComponentWrapper(node) {
if (!astUtil.isCallExpression(node)) {
return false;
}
return wrapperFunctions.some((wrapperFunction) => {
if (node.callee.type === 'MemberExpression') {
return wrapperFunction.object
&& wrapperFunction.object === node.callee.object.name
&& wrapperFunction.property === node.callee.property.name
&& !this.nodeWrapsComponent(node);
}
return wrapperFunction.property === node.callee.name
&& (!wrapperFunction.object
// Functions coming from the current pragma need special handling
|| (wrapperFunction.object === pragma && this.isDestructuredFromPragmaImport(node, node.callee.name))
);
});
},
/**
* Find a return statement in the current node
*
* @param {ASTNode} node The AST node being checked
*/
findReturnStatement: astUtil.findReturnStatement,
/**
* Get the parent component node from the current scope
* @param {ASTNode} node
*
* @returns {ASTNode} component node, null if we are not in a component
*/
getParentComponent(node) {
return (
componentUtil.getParentES6Component(context, node)
|| componentUtil.getParentES5Component(context, node)
|| utils.getParentStatelessComponent(node)
);
},
/**
* @param {ASTNode} node
* @returns {boolean}
*/
isInAllowedPositionForComponent(node) {
switch (node.parent.type) {
case 'VariableDeclarator':
case 'AssignmentExpression':
case 'Property':
case 'ReturnStatement':
case 'ExportDefaultDeclaration':
case 'ArrowFunctionExpression': {
return true;
}
case 'SequenceExpression': {
return utils.isInAllowedPositionForComponent(node.parent)
&& node === node.parent.expressions[node.parent.expressions.length - 1];
}
default:
return false;
}
},
/**
* Get node if node is a stateless component, or node.parent in cases like
* `React.memo` or `React.forwardRef`. Otherwise returns `undefined`.
* @param {ASTNode} node
* @returns {ASTNode | undefined}
*/
getStatelessComponent(node) {
const parent = node.parent;
if (
node.type === 'FunctionDeclaration'
&& (!node.id || isFirstLetterCapitalized(node.id.name))
&& utils.isReturningJSXOrNull(node)
) {
return node;
}
if (node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression') {
const isPropertyAssignment = parent.type === 'AssignmentExpression'
&& parent.left.type === 'MemberExpression';
const isModuleExportsAssignment = isPropertyAssignment
&& parent.left.object.name === 'module'
&& parent.left.property.name === 'exports';
if (node.parent.type === 'ExportDefaultDeclaration') {
if (utils.isReturningJSX(node)) {
return node;
}
return undefined;
}
if (node.parent.type === 'VariableDeclarator' && utils.isReturningJSXOrNull(node)) {
if (isFirstLetterCapitalized(node.parent.id.name)) {
return node;
}
return undefined;
}
// case: const any = () => { return (props) => null }
// case: const any = () => (props) => null
if (
(node.parent.type === 'ReturnStatement' || (node.parent.type === 'ArrowFunctionExpression' && node.parent.expression))
&& !utils.isReturningJSX(node)
) {
return undefined;
}
// case: any = () => { return => null }
// case: any = () => null
if (node.parent.type === 'AssignmentExpression' && !isPropertyAssignment && utils.isReturningJSXOrNull(node)) {
if (isFirstLetterCapitalized(node.parent.left.name)) {
return node;
}
return undefined;
}
// case: any = () => () => null
if (node.parent.type === 'ArrowFunctionExpression' && node.parent.parent.type === 'AssignmentExpression' && !isPropertyAssignment && utils.isReturningJSXOrNull(node)) {
if (isFirstLetterCapitalized(node.parent.parent.left.name)) {
return node;
}
return undefined;
}
// case: { any: () => () => null }
if (node.parent.type === 'ArrowFunctionExpression' && node.parent.parent.type === 'Property' && !isPropertyAssignment && utils.isReturningJSXOrNull(node)) {
if (isFirstLetterCapitalized(node.parent.parent.key.name)) {
return node;
}
return undefined;
}
// case: any = function() {return function() {return null;};}
if (node.parent.type === 'ReturnStatement') {
if (isFirstLetterCapitalized(node.id && node.id.name)) {
return node;
}
const functionExpr = node.parent.parent.parent;
if (functionExpr.parent.type === 'AssignmentExpression' && !isPropertyAssignment && utils.isReturningJSXOrNull(node)) {
if (isFirstLetterCapitalized(functionExpr.parent.left.name)) {
return node;
}
return undefined;
}
}
// case: { any: function() {return function() {return null;};} }
if (node.parent.type === 'ReturnStatement') {
const functionExpr = node.parent.parent.parent;
if (functionExpr.parent.type === 'Property' && !isPropertyAssignment && utils.isReturningJSXOrNull(node)) {
if (isFirstLetterCapitalized(functionExpr.parent.key.name)) {
return node;
}
return undefined;
}
}
// for case abc = { [someobject.somekey]: props => { ... return not-jsx } }
if (
node.parent
&& node.parent.key
&& node.parent.key.type === 'MemberExpression'
&& !utils.isReturningJSX(node)
&& !utils.isReturningOnlyNull(node)
) {
return undefined;
}
if (
node.parent.type === 'Property' && (
(node.parent.method && !node.parent.computed) // case: { f() { return ... } }
|| (!node.id && !node.parent.computed) // case: { f: () => ... }
)
) {
if (
isFirstLetterCapitalized(node.parent.key.name)
&& utils.isReturningJSX(node)
) {
return node;
}
return undefined;
}
// Case like `React.memo(() => <></>)` or `React.forwardRef(...)`
const pragmaComponentWrapper = utils.getPragmaComponentWrapper(node);
if (pragmaComponentWrapper && utils.isReturningJSXOrNull(node)) {
return pragmaComponentWrapper;
}
if (!(utils.isInAllowedPositionForComponent(node) && utils.isReturningJSXOrNull(node))) {
return undefined;
}
if (utils.isParentComponentNotStatelessComponent(node)) {
return undefined;
}
if (node.id) {
return isFirstLetterCapitalized(node.id.name) ? node : undefined;
}
if (
isPropertyAssignment
&& !isModuleExportsAssignment
&& !isFirstLetterCapitalized(parent.left.property.name)
) {
return undefined;
}
if (parent.type === 'Property' && utils.isReturningOnlyNull(node)) {
return undefined;
}
return node;
}
return undefined;
},
/**
* Get the parent stateless component node from the current scope
*
* @param {ASTNode} node The AST node being checked
* @returns {ASTNode} component node, null if we are not in a component
*/
getParentStatelessComponent(node) {
let scope = getScope(context, node);
while (scope) {
const statelessComponent = utils.getStatelessComponent(scope.block);
if (statelessComponent) {
return statelessComponent;
}
scope = scope.upper;
}
return null;
},
/**
* Get the related component from a node
*
* @param {ASTNode} node The AST node being checked (must be a MemberExpression).
* @returns {ASTNode | null} component node, null if we cannot find the component
*/
getRelatedComponent(node) {
let i;
let j;
let k;
let l;
let componentNode;
// Get the component path
const componentPath = [];
let nodeTemp = node;
while (nodeTemp) {
if (nodeTemp.property && nodeTemp.property.type === 'Identifier') {
componentPath.push(nodeTemp.property.name);
}
if (nodeTemp.object && nodeTemp.object.type === 'Identifier') {
componentPath.push(nodeTemp.object.name);
}
nodeTemp = nodeTemp.object;
}
componentPath.reverse();
const componentName = componentPath.slice(0, componentPath.length - 1).join('.');
// Find the variable in the current scope
const variableName = componentPath.shift();
if (!variableName) {
return null;
}
const variableInScope = variableUtil.getVariableFromContext(context, node, variableName);
if (!variableInScope) {
return null;
}
// Try to find the component using variable references
variableInScope.references.some((ref) => {
let refId = ref.identifier;
if (refId.parent && refId.parent.type === 'MemberExpression') {
refId = refId.parent;
}
if (getText(context, refId) !== componentName) {
return false;
}
if (refId.type === 'MemberExpression') {
componentNode = refId.parent.right;
} else if (
refId.parent
&& refId.parent.type === 'VariableDeclarator'
&& refId.parent.init
&& refId.parent.init.type !== 'Identifier'
) {
componentNode = refId.parent.init;
}
return true;
});
if (componentNode) {
// Return the component
return components.add(componentNode, 1);
}
// Try to find the component using variable declarations
const defs = variableInScope.defs;
const defInScope = defs.find((def) => (
def.type === 'ClassName'
|| def.type === 'FunctionName'
|| def.type === 'Variable'
));
if (!defInScope || !defInScope.node) {
return null;
}
componentNode = defInScope.node.init || defInScope.node;
// Traverse the node properties to the component declaration
for (i = 0, j = componentPath.length; i < j; i++) {
if (!componentNode.properties) {
continue; // eslint-disable-line no-continue
}
for (k = 0, l = componentNode.properties.length; k < l; k++) {
if (componentNode.properties[k].key && componentNode.properties[k].key.name === componentPath[i]) {
componentNode = componentNode.properties[k];
break;
}
}
if (!componentNode || !componentNode.value) {
return null;
}
componentNode = componentNode.value;
}
// Return the component
return components.add(componentNode, 1);
},
isParentComponentNotStatelessComponent(node) {
return !!(
node.parent
&& node.parent.key
&& node.parent.key.type === 'Identifier'
// custom component functions must start with a capital letter (returns false otherwise)
&& node.parent.key.name.charAt(0) === node.parent.key.name.charAt(0).toLowerCase()
// react render function cannot have params
&& !!(node.params || []).length
);
},
/**
* Identify whether a node (CallExpression) is a call to a React hook
*
* @param {ASTNode} node The AST node being searched. (expects CallExpression)
* @param {('useCallback'|'useContext'|'useDebugValue'|'useEffect'|'useImperativeHandle'|'useLayoutEffect'|'useMemo'|'useReducer'|'useRef'|'useState')[]} [expectedHookNames] React hook names to which search is limited.
* @returns {boolean} True if the node is a call to a React hook
*/
isReactHookCall(node, expectedHookNames) {
if (!astUtil.isCallExpression(node)) {
return false;
}
const defaultReactImports = components.getDefaultReactImports();
const namedReactImports = components.getNamedReactImports();
const defaultReactImportName = defaultReactImports
&& defaultReactImports[0]
&& defaultReactImports[0].local.name;
const reactHookImportSpecifiers = namedReactImports
&& namedReactImports.filter((specifier) => USE_HOOK_PREFIX_REGEX.test(specifier.imported.name));
const reactHookImportNames = reactHookImportSpecifiers
&& fromEntries(reactHookImportSpecifiers.map((specifier) => [specifier.local.name, specifier.imported.name]));
const isPotentialReactHookCall = defaultReactImportName
&& node.callee.type === 'MemberExpression'
&& node.callee.object.type === 'Identifier'
&& node.callee.object.name === defaultReactImportName
&& node.callee.property.type === 'Identifier'
&& node.callee.property.name.match(USE_HOOK_PREFIX_REGEX);
const isPotentialHookCall = reactHookImportNames
&& node.callee.type === 'Identifier'
&& node.callee.name.match(USE_HOOK_PREFIX_REGEX);
const scope = (isPotentialReactHookCall || isPotentialHookCall) && getScope(context, node);
const reactResolvedDefs = isPotentialReactHookCall
&& scope.references
&& scope.references.find(
(reference) => reference.identifier.name === defaultReactImportName
).resolved.defs;
const isReactShadowed = isPotentialReactHookCall && reactResolvedDefs
&& reactResolvedDefs.some((reactDef) => reactDef.type !== 'ImportBinding');
const potentialHookReference = isPotentialHookCall
&& scope.references
&& scope.references.find(
(reference) => reactHookImportNames[reference.identifier.name]
);
const hookResolvedDefs = potentialHookReference && potentialHookReference.resolved.defs;
const localHookName = (
isPotentialReactHookCall
&& node.callee.property.name
) || (
isPotentialHookCall
&& potentialHookReference
&& node.callee.name
);
const isHookShadowed = isPotentialHookCall
&& hookResolvedDefs
&& hookResolvedDefs.some(
(hookDef) => hookDef.name.name === localHookName
&& hookDef.type !== 'ImportBinding'
);
const isHookCall = (isPotentialReactHookCall && !isReactShadowed)
|| (isPotentialHookCall && localHookName && !isHookShadowed);
if (!isHookCall) {
return false;
}
if (!expectedHookNames) {
return true;
}
return arrayIncludes(
expectedHookNames,
(reactHookImportNames && reactHookImportNames[localHookName]) || localHookName
);
},
};
// Component detection instructions
const detectionInstructions = {
CallExpression(node) {
if (!utils.isPragmaComponentWrapper(node)) {
return;
}
if (node.arguments.length > 0 && astUtil.isFunctionLikeExpression(node.arguments[0])) {
components.add(node, 2);
}
},
ClassExpression(node) {
if (!componentUtil.isES6Component(node, context)) {
return;
}
components.add(node, 2);
},
ClassDeclaration(node) {
if (!componentUtil.isES6Component(node, context)) {
return;
}
components.add(node, 2);
},
ObjectExpression(node) {
if (!componentUtil.isES5Component(node, context)) {
return;
}
components.add(node, 2);
},
FunctionExpression(node) {
if (node.async && node.generator) {
components.add(node, 0);
return;
}
const component = utils.getStatelessComponent(node);
if (!component) {
return;
}
components.add(component, 2);
},
FunctionDeclaration(node) {
if (node.async && node.generator) {
components.add(node, 0);
return;
}
const cNode = utils.getStatelessComponent(node);
if (!cNode) {
return;
}
components.add(cNode, 2);
},
ArrowFunctionExpression(node) {
const component = utils.getStatelessComponent(node);
if (!component) {
return;
}
components.add(component, 2);
},
ThisExpression(node) {
const component = utils.getParentStatelessComponent(node);
if (!component || !/Function/.test(component.type) || !node.parent.property) {
return;
}
// Ban functions accessing a property on a ThisExpression
components.add(node, 0);
},
};
// Detect React import specifiers
const reactImportInstructions = {
ImportDeclaration(node) {
const isReactImported = node.source.type === 'Literal' && node.source.value === 'react';
if (!isReactImported) {
return;
}
node.specifiers.forEach((specifier) => {
if (specifier.type === 'ImportDefaultSpecifier') {
components.addDefaultReactImport(specifier);
}
if (specifier.type === 'ImportSpecifier') {
components.addNamedReactImport(specifier);
}
});
},
};
const ruleInstructions = rule(context, components, utils);
const propTypesInstructions = propTypesUtil(context, components, utils);
const usedPropTypesInstructions = usedPropTypesUtil(context, components, utils);
const defaultPropsInstructions = defaultPropsUtil(context, components, utils);
const mergedRule = mergeRules([
detectionInstructions,
propTypesInstructions,
usedPropTypesInstructions,
defaultPropsInstructions,
reactImportInstructions,
ruleInstructions,
]);
return mergedRule;
}
module.exports = Object.assign(Components, {
detect(rule) {
return componentRule.bind(this, rule);
},
});

View File

@@ -0,0 +1,8 @@
/**
* Checks if we are declaring a `props` argument with a flow type annotation.
* @param {ASTNode} node The AST node being checked.
* @param {Object} context
* @returns {boolean} True if the node is a type annotated props declaration, false if not.
*/
export function isAnnotatedFunctionPropsDeclaration(node: ASTNode, context: any): boolean;
//# sourceMappingURL=annotations.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"annotations.d.ts","sourceRoot":"","sources":["annotations.js"],"names":[],"mappings":"AAUA;;;;;GAKG;AACH,0DAJW,OAAO,iBAEL,OAAO,CAenB"}

View File

@@ -0,0 +1,34 @@
/**
* @fileoverview Utility functions for type annotation detection.
* @author Yannick Croissant
* @author Vitor Balocco
*/
'use strict';
const getFirstTokens = require('./eslint').getFirstTokens;
/**
* Checks if we are declaring a `props` argument with a flow type annotation.
* @param {ASTNode} node The AST node being checked.
* @param {Object} context
* @returns {boolean} True if the node is a type annotated props declaration, false if not.
*/
function isAnnotatedFunctionPropsDeclaration(node, context) {
if (!node || !node.params || !node.params.length) {
return false;
}
const typeNode = node.params[0].type === 'AssignmentPattern' ? node.params[0].left : node.params[0];
const tokens = getFirstTokens(context, typeNode, 2);
const isAnnotated = typeNode.typeAnnotation;
const isDestructuredProps = typeNode.type === 'ObjectPattern';
const isProps = tokens[0].value === 'props' || (tokens[1] && tokens[1].value === 'props');
return (isAnnotated && (isDestructuredProps || isProps));
}
module.exports = {
isAnnotatedFunctionPropsDeclaration,
};

136
node_modules/eslint-plugin-react/lib/util/ast.d.ts generated vendored Normal file
View File

@@ -0,0 +1,136 @@
/**
* Find a return statement in the current node
*
* @param {ASTNode} node The AST node being checked
* @returns {ASTNode | false}
*/
export function findReturnStatement(node: ASTNode): ASTNode | false;
/**
* Get properties for a given AST node
* @param {ASTNode} node The AST node being checked.
* @returns {Array} Properties array.
*/
export function getComponentProperties(node: ASTNode): any[];
/**
* Gets the first node in a line from the initial node, excluding whitespace.
* @param {Object} context The node to check
* @param {ASTNode} node The node to check
* @return {ASTNode} the first node in the line
*/
export function getFirstNodeInLine(context: any, node: ASTNode): ASTNode;
/**
* Retrieve the name of a key node
* @param {Context} context The AST node with the key.
* @param {any} node The AST node with the key.
* @return {string | undefined} the name of the key
*/
export function getKeyValue(context: Context, node: any): string | undefined;
/**
* Get properties name
* @param {Object} node - Property.
* @returns {string} Property name.
*/
export function getPropertyName(node: any): string;
/**
* Get node with property's name
* @param {Object} node - Property.
* @returns {Object} Property name node.
*/
export function getPropertyNameNode(node: any): any;
/**
* Check if we are in a class constructor
* @param {Context} context
* @param {ASTNode} node The AST node being checked.
* @return {boolean}
*/
export function inConstructor(context: Context, node: ASTNode): boolean;
/**
* Checks if a node is being assigned a value: props.bar = 'bar'
* @param {ASTNode} node The AST node being checked.
* @returns {boolean}
*/
export function isAssignmentLHS(node: ASTNode): boolean;
/**
* Matcher used to check whether given node is a `CallExpression`
* @param {ASTNode} node The AST node
* @returns {boolean} True if node is a `CallExpression`, false if not
*/
export function isCallExpression(node: ASTNode): boolean;
/**
* Checks if the node is a class.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a class
*/
export function isClass(node: ASTNode): boolean;
/**
* Checks if the node is a function.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a function
*/
export function isFunction(node: ASTNode): boolean;
/**
* Checks if node is a function declaration or expression or arrow function.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a function-like
*/
export function isFunctionLike(node: ASTNode): boolean;
/**
* Checks if the node is a function or arrow function expression.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a function-like expression
*/
export function isFunctionLikeExpression(node: ASTNode): boolean;
/**
* Checks if the node is the first in its line, excluding whitespace.
* @param {Object} context The node to check
* @param {ASTNode} node The node to check
* @return {boolean} true if it's the first node in its line
*/
export function isNodeFirstInLine(context: any, node: ASTNode): boolean;
/**
* Checks if a node is surrounded by parenthesis.
*
* @param {object} context - Context from the rule
* @param {ASTNode} node - Node to be checked
* @returns {boolean}
*/
export function isParenthesized(context: object, node: ASTNode): boolean;
export function isTSAsExpression(node: any): boolean;
export function isTSFunctionType(node: any): boolean;
export function isTSInterfaceDeclaration(node: any): boolean;
export function isTSInterfaceHeritage(node: any): boolean;
export function isTSIntersectionType(node: any): boolean;
export function isTSParenthesizedType(node: any): boolean;
export function isTSTypeAliasDeclaration(node: any): boolean;
export function isTSTypeAnnotation(node: any): boolean;
export function isTSTypeDeclaration(node: any): boolean;
export function isTSTypeLiteral(node: any): boolean;
export function isTSTypeParameterInstantiation(node: any): boolean;
export function isTSTypeQuery(node: any): boolean;
export function isTSTypeReference(node: any): boolean;
/**
* Wrapper for estraverse.traverse
*
* @param {ASTNode} ASTnode The AST node being checked
* @param {Object} visitor Visitor Object for estraverse
*/
export function traverse(ASTnode: ASTNode, visitor: any): void;
/**
* Helper function for traversing "returns" (return statements or the
* returned expression in the case of an arrow function) of a function
*
* @param {ASTNode} ASTNode The AST node being checked
* @param {Context} context The context of `ASTNode`.
* @param {(returnValue: ASTNode, breakTraverse: () => void) => void} onReturn
* Function to execute for each returnStatement found
* @returns {undefined}
*/
export function traverseReturns(ASTNode: ASTNode, context: Context, onReturn: (returnValue: ASTNode, breakTraverse: () => void) => void): undefined;
/**
* Extracts the expression node that is wrapped inside a TS type assertion
*
* @param {ASTNode} node - potential TS node
* @returns {ASTNode} - unwrapped expression node
*/
export function unwrapTSAsExpression(node: ASTNode): ASTNode;
//# sourceMappingURL=ast.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["ast.js"],"names":[],"mappings":"AAkDA;;;;;GAKG;AACH,0CAHW,OAAO,GACL,OAAO,GAAG,KAAK,CAa3B;AA0GD;;;;GAIG;AACH,6CAHW,OAAO,SAajB;AAED;;;;;GAKG;AACH,uDAHW,OAAO,GACN,OAAO,CAgBlB;AA8ED;;;;;GAKG;AACH,qCAJW,OAAO,QACP,GAAG,GACF,MAAM,GAAG,SAAS,CAqB7B;AAtJD;;;;GAIG;AACH,4CAFa,MAAM,CAKlB;AA3BD;;;;GAIG;AACH,oDAYC;AAoGD;;;;;GAKG;AACH,uCAJW,OAAO,QACP,OAAO,GACN,OAAO,CAYlB;AAuDD;;;;GAIG;AACH,sCAHW,OAAO,GACL,OAAO,CAQnB;AAMD;;;;GAIG;AACH,uCAHW,OAAO,GACL,OAAO,CAInB;AAxGD;;;;GAIG;AACH,8BAHW,OAAO,GACN,OAAO,CAIlB;AAzBD;;;;GAIG;AACH,iCAHW,OAAO,GACN,OAAO,CAIlB;AAED;;;;GAIG;AACH,qCAHW,OAAO,GACN,OAAO,CAIlB;AAzBD;;;;GAIG;AACH,+CAHW,OAAO,GACN,OAAO,CAIlB;AApBD;;;;;GAKG;AACH,sDAHW,OAAO,GACN,OAAO,CAOlB;AA4FD;;;;;;GAMG;AACH,yCAJW,MAAM,QACN,OAAO,GACL,OAAO,CAUnB;AAeD,qDAEC;AAqFD,qDAIC;AAtCD,6DAOC;AAbD,0DAIC;AAVD,yDAIC;AAoCD,0DAIC;AAbD,6DAOC;AAlDD,uDAIC;AA6BD,wDAQC;AAnCD,oDAIC;AA4DD,mEAIC;AAVD,kDAIC;AA1ED,sDAIC;AAtWD;;;;;GAKG;AACH,kCAHW,OAAO,sBAgBjB;AAqCD;;;;;;;;;GASG;AACH,yCANW,OAAO,WACP,OAAO,0BACO,OAAO,iBAAiB,MAAM,IAAI,KAAK,IAAI,GAEvD,SAAS,CAgErB;AAwND;;;;;GAKG;AACH,2CAHW,OAAO,GACL,OAAO,CAInB"}

483
node_modules/eslint-plugin-react/lib/util/ast.js generated vendored Normal file
View File

@@ -0,0 +1,483 @@
/**
* @fileoverview Utility functions for AST
*/
'use strict';
const estraverse = require('estraverse');
const eslintUtil = require('./eslint');
const getFirstTokens = eslintUtil.getFirstTokens;
const getScope = eslintUtil.getScope;
const getSourceCode = eslintUtil.getSourceCode;
// const pragmaUtil = require('./pragma');
/**
* Wrapper for estraverse.traverse
*
* @param {ASTNode} ASTnode The AST node being checked
* @param {Object} visitor Visitor Object for estraverse
*/
function traverse(ASTnode, visitor) {
const opts = Object.assign({}, {
fallback(node) {
return Object.keys(node).filter((key) => key === 'children' || key === 'argument');
},
}, visitor);
opts.keys = Object.assign({}, visitor.keys, {
JSXElement: ['children'],
JSXFragment: ['children'],
});
estraverse.traverse(ASTnode, opts);
}
function loopNodes(nodes) {
for (let i = nodes.length - 1; i >= 0; i--) {
if (nodes[i].type === 'ReturnStatement') {
return nodes[i];
}
if (nodes[i].type === 'SwitchStatement') {
const j = nodes[i].cases.length - 1;
if (j >= 0) {
return loopNodes(nodes[i].cases[j].consequent);
}
}
}
return false;
}
/**
* Find a return statement in the current node
*
* @param {ASTNode} node The AST node being checked
* @returns {ASTNode | false}
*/
function findReturnStatement(node) {
if (
(!node.value || !node.value.body || !node.value.body.body)
&& (!node.body || !node.body.body)
) {
return false;
}
const bodyNodes = node.value ? node.value.body.body : node.body.body;
return loopNodes(bodyNodes);
}
// eslint-disable-next-line valid-jsdoc -- valid-jsdoc cannot parse function types.
/**
* Helper function for traversing "returns" (return statements or the
* returned expression in the case of an arrow function) of a function
*
* @param {ASTNode} ASTNode The AST node being checked
* @param {Context} context The context of `ASTNode`.
* @param {(returnValue: ASTNode, breakTraverse: () => void) => void} onReturn
* Function to execute for each returnStatement found
* @returns {undefined}
*/
function traverseReturns(ASTNode, context, onReturn) {
const nodeType = ASTNode.type;
if (nodeType === 'ReturnStatement') {
onReturn(ASTNode.argument, () => {});
return;
}
if (nodeType === 'ArrowFunctionExpression' && ASTNode.expression) {
onReturn(ASTNode.body, () => {});
return;
}
/* TODO: properly warn on React.forwardRefs having typo properties
if (astUtil.isCallExpression(ASTNode)) {
const callee = ASTNode.callee;
const pragma = pragmaUtil.getFromContext(context);
if (
callee.type === 'MemberExpression'
&& callee.object.type === 'Identifier'
&& callee.object.name === pragma
&& callee.property.type === 'Identifier'
&& callee.property.name === 'forwardRef'
&& ASTNode.arguments.length > 0
) {
return enterFunc(ASTNode.arguments[0]);
}
return;
}
*/
if (
nodeType !== 'FunctionExpression'
&& nodeType !== 'FunctionDeclaration'
&& nodeType !== 'ArrowFunctionExpression'
&& nodeType !== 'MethodDefinition'
) {
return;
}
traverse(ASTNode.body, {
enter(node) {
const breakTraverse = () => {
this.break();
};
switch (node.type) {
case 'ReturnStatement':
this.skip();
onReturn(node.argument, breakTraverse);
return;
case 'BlockStatement':
case 'IfStatement':
case 'ForStatement':
case 'WhileStatement':
case 'SwitchStatement':
case 'SwitchCase':
return;
default:
this.skip();
}
},
});
}
/**
* Get node with property's name
* @param {Object} node - Property.
* @returns {Object} Property name node.
*/
function getPropertyNameNode(node) {
if (
node.key
|| node.type === 'MethodDefinition'
|| node.type === 'Property'
) {
return node.key;
}
if (node.type === 'MemberExpression') {
return node.property;
}
return null;
}
/**
* Get properties name
* @param {Object} node - Property.
* @returns {string} Property name.
*/
function getPropertyName(node) {
const nameNode = getPropertyNameNode(node);
return nameNode ? nameNode.name : '';
}
/**
* Get properties for a given AST node
* @param {ASTNode} node The AST node being checked.
* @returns {Array} Properties array.
*/
function getComponentProperties(node) {
switch (node.type) {
case 'ClassDeclaration':
case 'ClassExpression':
return node.body.body;
case 'ObjectExpression':
return node.properties;
default:
return [];
}
}
/**
* Gets the first node in a line from the initial node, excluding whitespace.
* @param {Object} context The node to check
* @param {ASTNode} node The node to check
* @return {ASTNode} the first node in the line
*/
function getFirstNodeInLine(context, node) {
const sourceCode = getSourceCode(context);
let token = node;
let lines;
do {
token = sourceCode.getTokenBefore(token);
lines = token.type === 'JSXText'
? token.value.split('\n')
: null;
} while (
token.type === 'JSXText'
&& /^\s*$/.test(lines[lines.length - 1])
);
return token;
}
/**
* Checks if the node is the first in its line, excluding whitespace.
* @param {Object} context The node to check
* @param {ASTNode} node The node to check
* @return {boolean} true if it's the first node in its line
*/
function isNodeFirstInLine(context, node) {
const token = getFirstNodeInLine(context, node);
const startLine = node.loc.start.line;
const endLine = token ? token.loc.end.line : -1;
return startLine !== endLine;
}
/**
* Checks if the node is a function or arrow function expression.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a function-like expression
*/
function isFunctionLikeExpression(node) {
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
/**
* Checks if the node is a function.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a function
*/
function isFunction(node) {
return node.type === 'FunctionExpression' || node.type === 'FunctionDeclaration';
}
/**
* Checks if node is a function declaration or expression or arrow function.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a function-like
*/
function isFunctionLike(node) {
return node.type === 'FunctionDeclaration' || isFunctionLikeExpression(node);
}
/**
* Checks if the node is a class.
* @param {ASTNode} node The node to check
* @return {boolean} true if it's a class
*/
function isClass(node) {
return node.type === 'ClassDeclaration' || node.type === 'ClassExpression';
}
/**
* Check if we are in a class constructor
* @param {Context} context
* @param {ASTNode} node The AST node being checked.
* @return {boolean}
*/
function inConstructor(context, node) {
let scope = getScope(context, node);
while (scope) {
// @ts-ignore
if (scope.block && scope.block.parent && scope.block.parent.kind === 'constructor') {
return true;
}
scope = scope.upper;
}
return false;
}
/**
* Removes quotes from around an identifier.
* @param {string} string the identifier to strip
* @returns {string}
*/
function stripQuotes(string) {
return string.replace(/^'|'$/g, '');
}
/**
* Retrieve the name of a key node
* @param {Context} context The AST node with the key.
* @param {any} node The AST node with the key.
* @return {string | undefined} the name of the key
*/
function getKeyValue(context, node) {
if (node.type === 'ObjectTypeProperty') {
const tokens = getFirstTokens(context, node, 2);
return (tokens[0].value === '+' || tokens[0].value === '-'
? tokens[1].value
: stripQuotes(tokens[0].value)
);
}
if (node.type === 'GenericTypeAnnotation') {
return node.id.name;
}
if (node.type === 'ObjectTypeAnnotation') {
return;
}
const key = node.key || node.argument;
if (!key) {
return;
}
return key.type === 'Identifier' ? key.name : key.value;
}
/**
* Checks if a node is surrounded by parenthesis.
*
* @param {object} context - Context from the rule
* @param {ASTNode} node - Node to be checked
* @returns {boolean}
*/
function isParenthesized(context, node) {
const sourceCode = getSourceCode(context);
const previousToken = sourceCode.getTokenBefore(node);
const nextToken = sourceCode.getTokenAfter(node);
return !!previousToken && !!nextToken
&& previousToken.value === '(' && previousToken.range[1] <= node.range[0]
&& nextToken.value === ')' && nextToken.range[0] >= node.range[1];
}
/**
* Checks if a node is being assigned a value: props.bar = 'bar'
* @param {ASTNode} node The AST node being checked.
* @returns {boolean}
*/
function isAssignmentLHS(node) {
return (
node.parent
&& node.parent.type === 'AssignmentExpression'
&& node.parent.left === node
);
}
function isTSAsExpression(node) {
return node && node.type === 'TSAsExpression';
}
/**
* Matcher used to check whether given node is a `CallExpression`
* @param {ASTNode} node The AST node
* @returns {boolean} True if node is a `CallExpression`, false if not
*/
function isCallExpression(node) {
return node && node.type === 'CallExpression';
}
/**
* Extracts the expression node that is wrapped inside a TS type assertion
*
* @param {ASTNode} node - potential TS node
* @returns {ASTNode} - unwrapped expression node
*/
function unwrapTSAsExpression(node) {
return isTSAsExpression(node) ? node.expression : node;
}
function isTSTypeReference(node) {
if (!node) return false;
return node.type === 'TSTypeReference';
}
function isTSTypeAnnotation(node) {
if (!node) { return false; }
return node.type === 'TSTypeAnnotation';
}
function isTSTypeLiteral(node) {
if (!node) { return false; }
return node.type === 'TSTypeLiteral';
}
function isTSIntersectionType(node) {
if (!node) { return false; }
return node.type === 'TSIntersectionType';
}
function isTSInterfaceHeritage(node) {
if (!node) { return false; }
return node.type === 'TSInterfaceHeritage';
}
function isTSInterfaceDeclaration(node) {
if (!node) { return false; }
return (node.type === 'ExportNamedDeclaration' && node.declaration
? node.declaration.type
: node.type
) === 'TSInterfaceDeclaration';
}
function isTSTypeDeclaration(node) {
if (!node) { return false; }
const nodeToCheck = node.type === 'ExportNamedDeclaration' && node.declaration
? node.declaration
: node;
return nodeToCheck.type === 'VariableDeclaration' && nodeToCheck.kind === 'type';
}
function isTSTypeAliasDeclaration(node) {
if (!node) { return false; }
if (node.type === 'ExportNamedDeclaration' && node.declaration) {
return node.declaration.type === 'TSTypeAliasDeclaration' && node.exportKind === 'type';
}
return node.type === 'TSTypeAliasDeclaration';
}
function isTSParenthesizedType(node) {
if (!node) { return false; }
return node.type === 'TSTypeAliasDeclaration';
}
function isTSFunctionType(node) {
if (!node) { return false; }
return node.type === 'TSFunctionType';
}
function isTSTypeQuery(node) {
if (!node) { return false; }
return node.type === 'TSTypeQuery';
}
function isTSTypeParameterInstantiation(node) {
if (!node) { return false; }
return node.type === 'TSTypeParameterInstantiation';
}
module.exports = {
findReturnStatement,
getComponentProperties,
getFirstNodeInLine,
getKeyValue,
getPropertyName,
getPropertyNameNode,
inConstructor,
isAssignmentLHS,
isCallExpression,
isClass,
isFunction,
isFunctionLike,
isFunctionLikeExpression,
isNodeFirstInLine,
isParenthesized,
isTSAsExpression,
isTSFunctionType,
isTSInterfaceDeclaration,
isTSInterfaceHeritage,
isTSIntersectionType,
isTSParenthesizedType,
isTSTypeAliasDeclaration,
isTSTypeAnnotation,
isTSTypeDeclaration,
isTSTypeLiteral,
isTSTypeParameterInstantiation,
isTSTypeQuery,
isTSTypeReference,
traverse,
traverseReturns,
unwrapTSAsExpression,
};

View File

@@ -0,0 +1,46 @@
/**
* @param {ASTNode} node
* @param {Context} context
* @returns {boolean}
*/
export function isES5Component(node: ASTNode, context: Context): boolean;
/**
* @param {ASTNode} node
* @param {Context} context
* @returns {boolean}
*/
export function isES6Component(node: ASTNode, context: Context): boolean;
/**
* Get the parent ES5 component node from the current scope
* @param {Context} context
* @param {ASTNode} node
* @returns {ASTNode|null}
*/
export function getParentES5Component(context: Context, node: ASTNode): ASTNode | null;
/**
* Get the parent ES6 component node from the current scope
* @param {Context} context
* @param {ASTNode} node
* @returns {ASTNode | null}
*/
export function getParentES6Component(context: Context, node: ASTNode): ASTNode | null;
/**
* Check if the node is explicitly declared as a descendant of a React Component
* @param {any} node
* @param {Context} context
* @returns {boolean}
*/
export function isExplicitComponent(node: any, context: Context): boolean;
/**
* Checks if a component extends React.PureComponent
* @param {ASTNode} node
* @param {Context} context
* @returns {boolean}
*/
export function isPureComponent(node: ASTNode, context: Context): boolean;
/**
* @param {ASTNode} node
* @returns {boolean}
*/
export function isStateMemberExpression(node: ASTNode): boolean;
//# sourceMappingURL=componentUtil.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"componentUtil.d.ts","sourceRoot":"","sources":["componentUtil.js"],"names":[],"mappings":"AAiCA;;;;GAIG;AACH,qCAJW,OAAO,WACP,OAAO,GACL,OAAO,CAmBnB;AAyCD;;;;GAIG;AACH,qCAJW,OAAO,WACP,OAAO,GACL,OAAO,CAmBnB;AAED;;;;;GAKG;AACH,+CAJW,OAAO,QACP,OAAO,GACL,OAAO,GAAC,IAAI,CAaxB;AAED;;;;;GAKG;AACH,+CAJW,OAAO,QACP,OAAO,GACL,OAAO,GAAG,IAAI,CAY1B;AAlGD;;;;;GAKG;AACH,0CAJW,GAAG,WACH,OAAO,GACL,OAAO,CAiCnB;AA+DD;;;;;GAKG;AACH,sCAJW,OAAO,WACP,OAAO,GACL,OAAO,CAQnB;AAED;;;GAGG;AACH,8CAHW,OAAO,GACL,OAAO,CAMnB"}

View File

@@ -0,0 +1,190 @@
'use strict';
const doctrine = require('doctrine');
const pragmaUtil = require('./pragma');
const eslintUtil = require('./eslint');
const getScope = eslintUtil.getScope;
const getSourceCode = eslintUtil.getSourceCode;
const getText = eslintUtil.getText;
// eslint-disable-next-line valid-jsdoc
/**
* @template {(_: object) => any} T
* @param {T} fn
* @returns {T}
*/
function memoize(fn) {
const cache = new WeakMap();
// @ts-ignore
return function memoizedFn(arg) {
const cachedValue = cache.get(arg);
if (cachedValue !== undefined) {
return cachedValue;
}
const v = fn(arg);
cache.set(arg, v);
return v;
};
}
const getPragma = memoize(pragmaUtil.getFromContext);
const getCreateClass = memoize(pragmaUtil.getCreateClassFromContext);
/**
* @param {ASTNode} node
* @param {Context} context
* @returns {boolean}
*/
function isES5Component(node, context) {
const pragma = getPragma(context);
const createClass = getCreateClass(context);
if (!node.parent || !node.parent.callee) {
return false;
}
const callee = node.parent.callee;
// React.createClass({})
if (callee.type === 'MemberExpression') {
return callee.object.name === pragma && callee.property.name === createClass;
}
// createClass({})
if (callee.type === 'Identifier') {
return callee.name === createClass;
}
return false;
}
/**
* Check if the node is explicitly declared as a descendant of a React Component
* @param {any} node
* @param {Context} context
* @returns {boolean}
*/
function isExplicitComponent(node, context) {
const sourceCode = getSourceCode(context);
let comment;
// Sometimes the passed node may not have been parsed yet by eslint, and this function call crashes.
// Can be removed when eslint sets "parent" property for all nodes on initial AST traversal: https://github.com/eslint/eslint-scope/issues/27
// eslint-disable-next-line no-warning-comments
// FIXME: Remove try/catch when https://github.com/eslint/eslint-scope/issues/27 is implemented.
try {
comment = sourceCode.getJSDocComment(node);
} catch (e) {
comment = null;
}
if (comment === null) {
return false;
}
let commentAst;
try {
commentAst = doctrine.parse(comment.value, {
unwrap: true,
tags: ['extends', 'augments'],
});
} catch (e) {
// handle a bug in the archived `doctrine`, see #2596
return false;
}
const relevantTags = commentAst.tags.filter((tag) => tag.name === 'React.Component' || tag.name === 'React.PureComponent');
return relevantTags.length > 0;
}
/**
* @param {ASTNode} node
* @param {Context} context
* @returns {boolean}
*/
function isES6Component(node, context) {
const pragma = getPragma(context);
if (isExplicitComponent(node, context)) {
return true;
}
if (!node.superClass) {
return false;
}
if (node.superClass.type === 'MemberExpression') {
return node.superClass.object.name === pragma
&& /^(Pure)?Component$/.test(node.superClass.property.name);
}
if (node.superClass.type === 'Identifier') {
return /^(Pure)?Component$/.test(node.superClass.name);
}
return false;
}
/**
* Get the parent ES5 component node from the current scope
* @param {Context} context
* @param {ASTNode} node
* @returns {ASTNode|null}
*/
function getParentES5Component(context, node) {
let scope = getScope(context, node);
while (scope) {
// @ts-ignore
node = scope.block && scope.block.parent && scope.block.parent.parent;
if (node && isES5Component(node, context)) {
return node;
}
scope = scope.upper;
}
return null;
}
/**
* Get the parent ES6 component node from the current scope
* @param {Context} context
* @param {ASTNode} node
* @returns {ASTNode | null}
*/
function getParentES6Component(context, node) {
let scope = getScope(context, node);
while (scope && scope.type !== 'class') {
scope = scope.upper;
}
node = scope && scope.block;
if (!node || !isES6Component(node, context)) {
return null;
}
return node;
}
/**
* Checks if a component extends React.PureComponent
* @param {ASTNode} node
* @param {Context} context
* @returns {boolean}
*/
function isPureComponent(node, context) {
const pragma = getPragma(context);
if (node.superClass) {
return new RegExp(`^(${pragma}\\.)?PureComponent$`).test(getText(context, node.superClass));
}
return false;
}
/**
* @param {ASTNode} node
* @returns {boolean}
*/
function isStateMemberExpression(node) {
return node.type === 'MemberExpression'
&& node.object.type === 'ThisExpression'
&& node.property.name === 'state';
}
module.exports = {
isES5Component,
isES6Component,
getParentES5Component,
getParentES6Component,
isExplicitComponent,
isPureComponent,
isStateMemberExpression,
};

View File

@@ -0,0 +1,8 @@
declare function _exports(context: any, components: any, utils: any): {
MemberExpression(node: any): void;
MethodDefinition(node: any): void;
'ClassProperty, PropertyDefinition'(node: any): void;
ObjectExpression(node: any): void;
};
export = _exports;
//# sourceMappingURL=defaultProps.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"defaultProps.d.ts","sourceRoot":"","sources":["defaultProps.js"],"names":[],"mappings":"AAgBiB;;;;;EA0PhB"}

View File

@@ -0,0 +1,267 @@
/**
* @fileoverview Common defaultProps detection functionality.
*/
'use strict';
const fromEntries = require('object.fromentries');
const astUtil = require('./ast');
const componentUtil = require('./componentUtil');
const propsUtil = require('./props');
const variableUtil = require('./variable');
const propWrapperUtil = require('./propWrapper');
const getText = require('./eslint').getText;
const QUOTES_REGEX = /^["']|["']$/g;
module.exports = function defaultPropsInstructions(context, components, utils) {
/**
* Try to resolve the node passed in to a variable in the current scope. If the node passed in is not
* an Identifier, then the node is simply returned.
* @param {ASTNode} node The node to resolve.
* @returns {ASTNode|null} Return null if the value could not be resolved, ASTNode otherwise.
*/
function resolveNodeValue(node) {
if (node.type === 'Identifier') {
return variableUtil.findVariableByName(context, node, node.name);
}
if (
astUtil.isCallExpression(node)
&& propWrapperUtil.isPropWrapperFunction(context, node.callee.name)
&& node.arguments && node.arguments[0]
) {
return resolveNodeValue(node.arguments[0]);
}
return node;
}
/**
* Extracts a DefaultProp from an ObjectExpression node.
* @param {ASTNode} objectExpression ObjectExpression node.
* @returns {Object|string} Object representation of a defaultProp, to be consumed by
* `addDefaultPropsToComponent`, or string "unresolved", if the defaultProps
* from this ObjectExpression can't be resolved.
*/
function getDefaultPropsFromObjectExpression(objectExpression) {
const hasSpread = objectExpression.properties.find((property) => property.type === 'ExperimentalSpreadProperty' || property.type === 'SpreadElement');
if (hasSpread) {
return 'unresolved';
}
return objectExpression.properties.map((defaultProp) => ({
name: getText(context, defaultProp.key).replace(QUOTES_REGEX, ''),
node: defaultProp,
}));
}
/**
* Marks a component's DefaultProps declaration as "unresolved". A component's DefaultProps is
* marked as "unresolved" if we cannot safely infer the values of its defaultProps declarations
* without risking false negatives.
* @param {Object} component The component to mark.
* @returns {void}
*/
function markDefaultPropsAsUnresolved(component) {
components.set(component.node, {
defaultProps: 'unresolved',
});
}
/**
* Adds defaultProps to the component passed in.
* @param {ASTNode} component The component to add the defaultProps to.
* @param {Object[]|'unresolved'} defaultProps defaultProps to add to the component or the string "unresolved"
* if this component has defaultProps that can't be resolved.
* @returns {void}
*/
function addDefaultPropsToComponent(component, defaultProps) {
// Early return if this component's defaultProps is already marked as "unresolved".
if (component.defaultProps === 'unresolved') {
return;
}
if (defaultProps === 'unresolved') {
markDefaultPropsAsUnresolved(component);
return;
}
const defaults = component.defaultProps || {};
const newDefaultProps = Object.assign(
{},
defaults,
fromEntries(defaultProps.map((prop) => [prop.name, prop]))
);
components.set(component.node, {
defaultProps: newDefaultProps,
});
}
return {
MemberExpression(node) {
const isDefaultProp = propsUtil.isDefaultPropsDeclaration(node);
if (!isDefaultProp) {
return;
}
// find component this defaultProps belongs to
const component = utils.getRelatedComponent(node);
if (!component) {
return;
}
// e.g.:
// MyComponent.propTypes = {
// foo: React.PropTypes.string.isRequired,
// bar: React.PropTypes.string
// };
//
// or:
//
// MyComponent.propTypes = myPropTypes;
if (node.parent.type === 'AssignmentExpression') {
const expression = resolveNodeValue(node.parent.right);
if (!expression || expression.type !== 'ObjectExpression') {
// If a value can't be found, we mark the defaultProps declaration as "unresolved", because
// we should ignore this component and not report any errors for it, to avoid false-positives
// with e.g. external defaultProps declarations.
if (isDefaultProp) {
markDefaultPropsAsUnresolved(component);
}
return;
}
addDefaultPropsToComponent(component, getDefaultPropsFromObjectExpression(expression));
return;
}
// e.g.:
// MyComponent.propTypes.baz = React.PropTypes.string;
if (node.parent.type === 'MemberExpression' && node.parent.parent
&& node.parent.parent.type === 'AssignmentExpression') {
addDefaultPropsToComponent(component, [{
name: node.parent.property.name,
node: node.parent.parent,
}]);
}
},
// e.g.:
// class Hello extends React.Component {
// static get defaultProps() {
// return {
// name: 'Dean'
// };
// }
// render() {
// return <div>Hello {this.props.name}</div>;
// }
// }
MethodDefinition(node) {
if (!node.static || node.kind !== 'get') {
return;
}
if (!propsUtil.isDefaultPropsDeclaration(node)) {
return;
}
// find component this propTypes/defaultProps belongs to
const component = components.get(componentUtil.getParentES6Component(context, node));
if (!component) {
return;
}
const returnStatement = utils.findReturnStatement(node);
if (!returnStatement) {
return;
}
const expression = resolveNodeValue(returnStatement.argument);
if (!expression || expression.type !== 'ObjectExpression') {
return;
}
addDefaultPropsToComponent(component, getDefaultPropsFromObjectExpression(expression));
},
// e.g.:
// class Greeting extends React.Component {
// render() {
// return (
// <h1>Hello, {this.props.foo} {this.props.bar}</h1>
// );
// }
// static defaultProps = {
// foo: 'bar',
// bar: 'baz'
// };
// }
'ClassProperty, PropertyDefinition'(node) {
if (!(node.static && node.value)) {
return;
}
const propName = astUtil.getPropertyName(node);
const isDefaultProp = propName === 'defaultProps' || propName === 'getDefaultProps';
if (!isDefaultProp) {
return;
}
// find component this propTypes/defaultProps belongs to
const component = components.get(componentUtil.getParentES6Component(context, node));
if (!component) {
return;
}
const expression = resolveNodeValue(node.value);
if (!expression || expression.type !== 'ObjectExpression') {
return;
}
addDefaultPropsToComponent(component, getDefaultPropsFromObjectExpression(expression));
},
// e.g.:
// React.createClass({
// render: function() {
// return <div>{this.props.foo}</div>;
// },
// getDefaultProps: function() {
// return {
// foo: 'default'
// };
// }
// });
ObjectExpression(node) {
// find component this propTypes/defaultProps belongs to
const component = componentUtil.isES5Component(node, context) && components.get(node);
if (!component) {
return;
}
// Search for the proptypes declaration
node.properties.forEach((property) => {
if (property.type === 'ExperimentalSpreadProperty' || property.type === 'SpreadElement') {
return;
}
const isDefaultProp = propsUtil.isDefaultPropsDeclaration(property);
if (isDefaultProp && property.value.type === 'FunctionExpression') {
const returnStatement = utils.findReturnStatement(property);
if (!returnStatement || returnStatement.argument.type !== 'ObjectExpression') {
return;
}
addDefaultPropsToComponent(component, getDefaultPropsFromObjectExpression(returnStatement.argument));
}
});
},
};
};

View File

@@ -0,0 +1,3 @@
export = docsUrl;
declare function docsUrl(ruleName: any): string;
//# sourceMappingURL=docsUrl.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"docsUrl.d.ts","sourceRoot":"","sources":["docsUrl.js"],"names":[],"mappings":";AAEA,gDAEC"}

7
node_modules/eslint-plugin-react/lib/util/docsUrl.js generated vendored Normal file
View File

@@ -0,0 +1,7 @@
'use strict';
function docsUrl(ruleName) {
return `https://github.com/jsx-eslint/eslint-plugin-react/tree/master/docs/rules/${ruleName}.md`;
}
module.exports = docsUrl;

7
node_modules/eslint-plugin-react/lib/util/error.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export = error;
/**
* Logs out a message if there is no format option set.
* @param {string} message - Message to log.
*/
declare function error(message: string): void;
//# sourceMappingURL=error.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"error.d.ts","sourceRoot":"","sources":["error.js"],"names":[],"mappings":";AAEA;;;GAGG;AACH,gCAFW,MAAM,QAOhB"}

14
node_modules/eslint-plugin-react/lib/util/error.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
'use strict';
/**
* Logs out a message if there is no format option set.
* @param {string} message - Message to log.
*/
function error(message) {
if (!/=-(f|-format)=/.test(process.argv.join('='))) {
// eslint-disable-next-line no-console
console.error(message);
}
}
module.exports = error;

View File

@@ -0,0 +1,7 @@
export function getAncestors(context: any, node: any): any;
export function getFirstTokens(context: any, node: any, count: any): any;
export function getScope(context: any, node: any): any;
export function getSourceCode(context: any): any;
export function getText(context: any, ...args: any[]): any;
export function markVariableAsUsed(name: any, node: any, context: any): any;
//# sourceMappingURL=eslint.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"eslint.d.ts","sourceRoot":"","sources":["eslint.js"],"names":[],"mappings":"AAMA,2DAGC;AAkBD,yEAGC;AAnBD,uDAOC;AAhBD,iDAEC;AA4BD,2DAIC;AAhBD,4EAKC"}

46
node_modules/eslint-plugin-react/lib/util/eslint.js generated vendored Normal file
View File

@@ -0,0 +1,46 @@
'use strict';
function getSourceCode(context) {
return context.getSourceCode ? context.getSourceCode() : context.sourceCode;
}
function getAncestors(context, node) {
const sourceCode = getSourceCode(context);
return sourceCode.getAncestors ? sourceCode.getAncestors(node) : context.getAncestors();
}
function getScope(context, node) {
const sourceCode = getSourceCode(context);
if (sourceCode.getScope) {
return sourceCode.getScope(node);
}
return context.getScope();
}
function markVariableAsUsed(name, node, context) {
const sourceCode = getSourceCode(context);
return sourceCode.markVariableAsUsed
? sourceCode.markVariableAsUsed(name, node)
: context.markVariableAsUsed(name);
}
function getFirstTokens(context, node, count) {
const sourceCode = getSourceCode(context);
return sourceCode.getFirstTokens ? sourceCode.getFirstTokens(node, count) : context.getFirstTokens(node, count);
}
function getText(context) {
const sourceCode = getSourceCode(context);
const args = Array.prototype.slice.call(arguments, 1);
return sourceCode.getText ? sourceCode.getText.apply(sourceCode, args) : context.getSource.apply(context, args);
}
module.exports = {
getAncestors,
getFirstTokens,
getScope,
getSourceCode,
getText,
markVariableAsUsed,
};

View File

@@ -0,0 +1,8 @@
export = getTokenBeforeClosingBracket;
/**
* Find the token before the closing bracket.
* @param {ASTNode} node - The JSX element node.
* @returns {Token} The token before the closing bracket.
*/
declare function getTokenBeforeClosingBracket(node: ASTNode): Token;
//# sourceMappingURL=getTokenBeforeClosingBracket.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getTokenBeforeClosingBracket.d.ts","sourceRoot":"","sources":["getTokenBeforeClosingBracket.js"],"names":[],"mappings":";AAEA;;;;GAIG;AACH,oDAHW,OAAO,GACL,KAAK,CAQjB"}

View File

@@ -0,0 +1,16 @@
'use strict';
/**
* Find the token before the closing bracket.
* @param {ASTNode} node - The JSX element node.
* @returns {Token} The token before the closing bracket.
*/
function getTokenBeforeClosingBracket(node) {
const attributes = node.attributes;
if (!attributes || attributes.length === 0) {
return node.name;
}
return attributes[attributes.length - 1];
}
module.exports = getTokenBeforeClosingBracket;

View File

@@ -0,0 +1,3 @@
declare function _exports(node: ASTNode): boolean;
export = _exports;
//# sourceMappingURL=isCreateContext.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"isCreateContext.d.ts","sourceRoot":"","sources":["isCreateContext.js"],"names":[],"mappings":"AASiB,gCAHN,OAAO,GACL,OAAO,CA8CnB"}

View File

@@ -0,0 +1,54 @@
'use strict';
const astUtil = require('./ast');
/**
* Checks if the node is a React.createContext call
* @param {ASTNode} node - The AST node being checked.
* @returns {boolean} - True if node is a React.createContext call, false if not.
*/
module.exports = function isCreateContext(node) {
if (
node.init
&& node.init.callee
) {
if (
astUtil.isCallExpression(node.init)
&& node.init.callee.name === 'createContext'
) {
return true;
}
if (
node.init.callee.type === 'MemberExpression'
&& node.init.callee.property
&& node.init.callee.property.name === 'createContext'
) {
return true;
}
}
if (
node.expression
&& node.expression.type === 'AssignmentExpression'
&& node.expression.operator === '='
&& astUtil.isCallExpression(node.expression.right)
&& node.expression.right.callee
) {
const right = node.expression.right;
if (right.callee.name === 'createContext') {
return true;
}
if (
right.callee.type === 'MemberExpression'
&& right.callee.property
&& right.callee.property.name === 'createContext'
) {
return true;
}
}
return false;
};

View File

@@ -0,0 +1,3 @@
declare function _exports(context: Context, node: ASTNode): boolean;
export = _exports;
//# sourceMappingURL=isCreateElement.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"isCreateElement.d.ts","sourceRoot":"","sources":["isCreateElement.js"],"names":[],"mappings":"AAWiB,mCAJN,OAAO,QACP,OAAO,GACL,OAAO,CAwBnB"}

View File

@@ -0,0 +1,34 @@
'use strict';
const pragmaUtil = require('./pragma');
const isDestructuredFromPragmaImport = require('./isDestructuredFromPragmaImport');
/**
* Checks if the node is a createElement call
* @param {Context} context - The AST node being checked.
* @param {ASTNode} node - The AST node being checked.
* @returns {boolean} - True if node is a createElement call object literal, False if not.
*/
module.exports = function isCreateElement(context, node) {
if (!node.callee) {
return false;
}
if (
node.callee.type === 'MemberExpression'
&& node.callee.property.name === 'createElement'
&& node.callee.object
&& node.callee.object.name === pragmaUtil.getFromContext(context)
) {
return true;
}
if (
node.callee.name === 'createElement'
&& isDestructuredFromPragmaImport(context, node, 'createElement')
) {
return true;
}
return false;
};

View File

@@ -0,0 +1,3 @@
declare function _exports(context: Context, node: ASTNode, variable: string, ...args: any[]): boolean;
export = _exports;
//# sourceMappingURL=isDestructuredFromPragmaImport.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"isDestructuredFromPragmaImport.d.ts","sourceRoot":"","sources":["isDestructuredFromPragmaImport.js"],"names":[],"mappings":"AAciB,mCALN,OAAO,QACP,OAAO,YACP,MAAM,mBACJ,OAAO,CAmEnB"}

View File

@@ -0,0 +1,80 @@
'use strict';
const astUtil = require('./ast');
const pragmaUtil = require('./pragma');
const variableUtil = require('./variable');
/**
* Check if variable is destructured from pragma import
*
* @param {Context} context eslint context
* @param {ASTNode} node The AST node to check
* @param {string} variable The variable name to check
* @returns {boolean} True if createElement is destructured from the pragma
*/
module.exports = function isDestructuredFromPragmaImport(context, node, variable) {
const pragma = pragmaUtil.getFromContext(context);
const variableInScope = variableUtil.getVariableFromContext(context, node, variable);
if (variableInScope) {
const latestDef = variableUtil.getLatestVariableDefinition(variableInScope);
if (latestDef) {
// check if latest definition is a variable declaration: 'variable = value'
if (latestDef.node.type === 'VariableDeclarator' && latestDef.node.init) {
// check for: 'variable = pragma.variable'
if (
latestDef.node.init.type === 'MemberExpression'
&& latestDef.node.init.object.type === 'Identifier'
&& latestDef.node.init.object.name === pragma
) {
return true;
}
// check for: '{variable} = pragma'
if (
latestDef.node.init.type === 'Identifier'
&& latestDef.node.init.name === pragma
) {
return true;
}
// "require('react')"
let requireExpression = null;
// get "require('react')" from: "{variable} = require('react')"
if (astUtil.isCallExpression(latestDef.node.init)) {
requireExpression = latestDef.node.init;
}
// get "require('react')" from: "variable = require('react').variable"
if (
!requireExpression
&& latestDef.node.init.type === 'MemberExpression'
&& astUtil.isCallExpression(latestDef.node.init.object)
) {
requireExpression = latestDef.node.init.object;
}
// check proper require.
if (
requireExpression
&& requireExpression.callee
&& requireExpression.callee.name === 'require'
&& requireExpression.arguments[0]
&& requireExpression.arguments[0].value === pragma.toLocaleLowerCase()
) {
return true;
}
return false;
}
// latest definition is an import declaration: import {<variable>} from 'react'
if (
latestDef.parent
&& latestDef.parent.type === 'ImportDeclaration'
&& latestDef.parent.source.value === pragma.toLocaleLowerCase()
) {
return true;
}
}
}
return false;
};

View File

@@ -0,0 +1,3 @@
declare function _exports(word: string): boolean;
export = _exports;
//# sourceMappingURL=isFirstLetterCapitalized.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"isFirstLetterCapitalized.d.ts","sourceRoot":"","sources":["isFirstLetterCapitalized.js"],"names":[],"mappings":"AAOiB,gCAHN,MAAM,GACJ,OAAO,CAQnB"}

View File

@@ -0,0 +1,14 @@
'use strict';
/**
* Check if the first letter of a string is capitalized.
* @param {string} word String to check
* @returns {boolean} True if first letter is capitalized.
*/
module.exports = function isFirstLetterCapitalized(word) {
if (!word) {
return false;
}
const firstLetter = word.replace(/^_+/, '').charAt(0);
return firstLetter.toUpperCase() === firstLetter;
};

51
node_modules/eslint-plugin-react/lib/util/jsx.d.ts generated vendored Normal file
View File

@@ -0,0 +1,51 @@
/**
* Checks if a node represents a DOM element according to React.
* @param {object} node - JSXOpeningElement to check.
* @returns {boolean} Whether or not the node corresponds to a DOM element.
*/
export function isDOMComponent(node: object): boolean;
/**
* Test whether a JSXElement is a fragment
* @param {JSXElement} node
* @param {string} reactPragma
* @param {string} fragmentPragma
* @returns {boolean}
*/
export function isFragment(node: JSXElement, reactPragma: string, fragmentPragma: string): boolean;
/**
* Checks if a node represents a JSX element or fragment.
* @param {object} node - node to check.
* @returns {boolean} Whether or not the node if a JSX element or fragment.
*/
export function isJSX(node: object): boolean;
/**
* Check if node is like `key={...}` as in `<Foo key={...} />`
* @param {ASTNode} node
* @returns {boolean}
*/
export function isJSXAttributeKey(node: ASTNode): boolean;
/**
* Check if value has only whitespaces
* @param {unknown} value
* @returns {boolean}
*/
export function isWhiteSpaces(value: unknown): boolean;
/**
* Check if the node is returning JSX or null
*
* @param {Context} context The context of `ASTNode`.
* @param {ASTNode} ASTnode The AST node being checked
* @param {boolean} [strict] If true, in a ternary condition the node must return JSX in both cases
* @param {boolean} [ignoreNull] If true, null return values will be ignored
* @returns {boolean} True if the node is returning JSX or null, false if not
*/
export function isReturningJSX(context: Context, ASTnode: ASTNode, strict?: boolean, ignoreNull?: boolean): boolean;
/**
* Check if the node is returning only null values
*
* @param {ASTNode} ASTnode The AST node being checked
* @param {Context} context The context of `ASTNode`.
* @returns {boolean} True if the node is returning only null values
*/
export function isReturningOnlyNull(ASTnode: ASTNode, context: Context): boolean;
//# sourceMappingURL=jsx.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"jsx.d.ts","sourceRoot":"","sources":["jsx.js"],"names":[],"mappings":"AAgBA;;;;GAIG;AACH,qCAHW,MAAM,GACJ,OAAO,CAKnB;AAED;;;;;;GAMG;AACH,iCALW,UAAU,eACV,MAAM,kBACN,MAAM,GACJ,OAAO,CAsBnB;AAED;;;;GAIG;AACH,4BAHW,MAAM,GACJ,OAAO,CAInB;AAED;;;;GAIG;AACH,wCAHW,OAAO,GACL,OAAO,CAOnB;AAED;;;;GAIG;AACH,qCAHW,OAAO,GACL,OAAO,CAInB;AAED;;;;;;;;GAQG;AACH,wCANW,OAAO,WACP,OAAO,WACP,OAAO,eACP,OAAO,GACL,OAAO,CAgDnB;AAED;;;;;;GAMG;AACH,6CAJW,OAAO,WACP,OAAO,GACL,OAAO,CAsCnB"}

196
node_modules/eslint-plugin-react/lib/util/jsx.js generated vendored Normal file
View File

@@ -0,0 +1,196 @@
/**
* @fileoverview Utility functions for JSX
*/
'use strict';
const elementType = require('jsx-ast-utils/elementType');
const astUtil = require('./ast');
const isCreateElement = require('./isCreateElement');
const variableUtil = require('./variable');
// See https://github.com/babel/babel/blob/ce420ba51c68591e057696ef43e028f41c6e04cd/packages/babel-types/src/validators/react/isCompatTag.js
// for why we only test for the first character
const COMPAT_TAG_REGEX = /^[a-z]/;
/**
* Checks if a node represents a DOM element according to React.
* @param {object} node - JSXOpeningElement to check.
* @returns {boolean} Whether or not the node corresponds to a DOM element.
*/
function isDOMComponent(node) {
const name = elementType(node);
return COMPAT_TAG_REGEX.test(name);
}
/**
* Test whether a JSXElement is a fragment
* @param {JSXElement} node
* @param {string} reactPragma
* @param {string} fragmentPragma
* @returns {boolean}
*/
function isFragment(node, reactPragma, fragmentPragma) {
const name = node.openingElement.name;
// <Fragment>
if (name.type === 'JSXIdentifier' && name.name === fragmentPragma) {
return true;
}
// <React.Fragment>
if (
name.type === 'JSXMemberExpression'
&& name.object.type === 'JSXIdentifier'
&& name.object.name === reactPragma
&& name.property.type === 'JSXIdentifier'
&& name.property.name === fragmentPragma
) {
return true;
}
return false;
}
/**
* Checks if a node represents a JSX element or fragment.
* @param {object} node - node to check.
* @returns {boolean} Whether or not the node if a JSX element or fragment.
*/
function isJSX(node) {
return node && ['JSXElement', 'JSXFragment'].indexOf(node.type) >= 0;
}
/**
* Check if node is like `key={...}` as in `<Foo key={...} />`
* @param {ASTNode} node
* @returns {boolean}
*/
function isJSXAttributeKey(node) {
return node.type === 'JSXAttribute'
&& node.name
&& node.name.type === 'JSXIdentifier'
&& node.name.name === 'key';
}
/**
* Check if value has only whitespaces
* @param {unknown} value
* @returns {boolean}
*/
function isWhiteSpaces(value) {
return typeof value === 'string' ? /^\s*$/.test(value) : false;
}
/**
* Check if the node is returning JSX or null
*
* @param {Context} context The context of `ASTNode`.
* @param {ASTNode} ASTnode The AST node being checked
* @param {boolean} [strict] If true, in a ternary condition the node must return JSX in both cases
* @param {boolean} [ignoreNull] If true, null return values will be ignored
* @returns {boolean} True if the node is returning JSX or null, false if not
*/
function isReturningJSX(context, ASTnode, strict, ignoreNull) {
const isJSXValue = (node) => {
if (!node) {
return false;
}
switch (node.type) {
case 'ConditionalExpression':
if (strict) {
return isJSXValue(node.consequent) && isJSXValue(node.alternate);
}
return isJSXValue(node.consequent) || isJSXValue(node.alternate);
case 'LogicalExpression':
if (strict) {
return isJSXValue(node.left) && isJSXValue(node.right);
}
return isJSXValue(node.left) || isJSXValue(node.right);
case 'SequenceExpression':
return isJSXValue(node.expressions[node.expressions.length - 1]);
case 'JSXElement':
case 'JSXFragment':
return true;
case 'CallExpression':
return isCreateElement(context, node);
case 'Literal':
if (!ignoreNull && node.value === null) {
return true;
}
return false;
case 'Identifier': {
const variable = variableUtil.findVariableByName(context, node, node.name);
return isJSX(variable);
}
default:
return false;
}
};
let found = false;
astUtil.traverseReturns(ASTnode, context, (node, breakTraverse) => {
if (isJSXValue(node)) {
found = true;
breakTraverse();
}
});
return found;
}
/**
* Check if the node is returning only null values
*
* @param {ASTNode} ASTnode The AST node being checked
* @param {Context} context The context of `ASTNode`.
* @returns {boolean} True if the node is returning only null values
*/
function isReturningOnlyNull(ASTnode, context) {
let found = false;
let foundSomethingElse = false;
astUtil.traverseReturns(ASTnode, context, (node) => {
// Traverse return statement
astUtil.traverse(node, {
enter(childNode) {
const setFound = () => {
found = true;
this.skip();
};
const setFoundSomethingElse = () => {
foundSomethingElse = true;
this.skip();
};
switch (childNode.type) {
case 'ReturnStatement':
break;
case 'ConditionalExpression':
if (childNode.consequent.value === null && childNode.alternate.value === null) {
setFound();
}
break;
case 'Literal':
if (childNode.value === null) {
setFound();
}
break;
default:
setFoundSomethingElse();
}
},
});
});
return found && !foundSomethingElse;
}
module.exports = {
isDOMComponent,
isFragment,
isJSX,
isJSXAttributeKey,
isWhiteSpaces,
isReturningJSX,
isReturningOnlyNull,
};

View File

@@ -0,0 +1,6 @@
declare const _exports: {
instance: string[];
static: string[];
};
export = _exports;
//# sourceMappingURL=lifecycleMethods.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"lifecycleMethods.d.ts","sourceRoot":"","sources":["lifecycleMethods.js"],"names":[],"mappings":""}

View File

@@ -0,0 +1,30 @@
/**
* @fileoverview lifecycle methods
* @author Tan Nguyen
*/
'use strict';
module.exports = {
instance: [
'getDefaultProps',
'getInitialState',
'getChildContext',
'componentWillMount',
'UNSAFE_componentWillMount',
'componentDidMount',
'componentWillReceiveProps',
'UNSAFE_componentWillReceiveProps',
'shouldComponentUpdate',
'componentWillUpdate',
'UNSAFE_componentWillUpdate',
'getSnapshotBeforeUpdate',
'componentDidUpdate',
'componentDidCatch',
'componentWillUnmount',
'render',
],
static: [
'getDerivedStateFromProps',
],
};

View File

@@ -0,0 +1,3 @@
export function getFormComponents(context: any): Map<any, any>;
export function getLinkComponents(context: any): Map<any, any>;
//# sourceMappingURL=linkComponents.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"linkComponents.d.ts","sourceRoot":"","sources":["linkComponents.js"],"names":[],"mappings":"AAmBA,+DAWC;AAED,+DAWC"}

View File

@@ -0,0 +1,49 @@
/**
* @fileoverview Utility functions for propWrapperFunctions setting
*/
'use strict';
const iterFrom = require('es-iterator-helpers/Iterator.from');
const map = require('es-iterator-helpers/Iterator.prototype.map');
/** TODO: type {(string | { name: string, linkAttribute: string })[]} */
/** @type {any} */
const DEFAULT_LINK_COMPONENTS = ['a'];
const DEFAULT_LINK_ATTRIBUTE = 'href';
/** TODO: type {(string | { name: string, formAttribute: string })[]} */
/** @type {any} */
const DEFAULT_FORM_COMPONENTS = ['form'];
const DEFAULT_FORM_ATTRIBUTE = 'action';
function getFormComponents(context) {
const settings = context.settings || {};
const formComponents = /** @type {typeof DEFAULT_FORM_COMPONENTS} */ (
DEFAULT_FORM_COMPONENTS.concat(settings.formComponents || [])
);
return new Map(map(iterFrom(formComponents), (value) => {
if (typeof value === 'string') {
return [value, [DEFAULT_FORM_ATTRIBUTE]];
}
return [value.name, [].concat(value.formAttribute)];
}));
}
function getLinkComponents(context) {
const settings = context.settings || {};
const linkComponents = /** @type {typeof DEFAULT_LINK_COMPONENTS} */ (
DEFAULT_LINK_COMPONENTS.concat(settings.linkComponents || [])
);
return new Map(map(iterFrom(linkComponents), (value) => {
if (typeof value === 'string') {
return [value, [DEFAULT_LINK_ATTRIBUTE]];
}
return [value.name, [].concat(value.linkAttribute)];
}));
}
module.exports = {
getFormComponents,
getLinkComponents,
};

7
node_modules/eslint-plugin-react/lib/util/log.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export = log;
/**
* Logs out a message if there is no format option set.
* @param {string} message - Message to log.
*/
declare function log(message: string): void;
//# sourceMappingURL=log.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"log.d.ts","sourceRoot":"","sources":["log.js"],"names":[],"mappings":";AAEA;;;GAGG;AACH,8BAFW,MAAM,QAOhB"}

14
node_modules/eslint-plugin-react/lib/util/log.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
'use strict';
/**
* Logs out a message if there is no format option set.
* @param {string} message - Message to log.
*/
function log(message) {
if (!/=-(f|-format)=/.test(process.argv.join('='))) {
// eslint-disable-next-line no-console
console.log(message);
}
}
module.exports = log;

View File

@@ -0,0 +1,3 @@
declare function _exports(methodName: string, shouldCheckUnsafeCb?: (context: import('eslint').Rule.RuleContext) => boolean): import('eslint').Rule.RuleModule;
export = _exports;
//# sourceMappingURL=makeNoMethodSetStateRule.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"makeNoMethodSetStateRule.d.ts","sourceRoot":"","sources":["makeNoMethodSetStateRule.js"],"names":[],"mappings":"AAoDiB,sCAJN,MAAM,kCACI,OAAO,QAAQ,EAAE,IAAI,CAAC,WAAW,KAAK,OAAO,GACrD,OAAO,QAAQ,EAAE,IAAI,CAAC,UAAU,CA+E5C"}

View File

@@ -0,0 +1,130 @@
/**
* @fileoverview Prevent usage of setState in lifecycle methods
* @author Yannick Croissant
*/
'use strict';
const findLast = require('array.prototype.findlast');
const docsUrl = require('./docsUrl');
const report = require('./report');
const getAncestors = require('./eslint').getAncestors;
const testReactVersion = require('./version').testReactVersion;
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
function mapTitle(methodName) {
const map = {
componentDidMount: 'did-mount',
componentDidUpdate: 'did-update',
componentWillUpdate: 'will-update',
};
const title = map[methodName];
if (!title) {
throw Error(`No docsUrl for '${methodName}'`);
}
return `no-${title}-set-state`;
}
const messages = {
noSetState: 'Do not use setState in {{name}}',
};
const methodNoopsAsOf = {
componentDidMount: '>= 16.3.0',
componentDidUpdate: '>= 16.3.0',
};
function shouldBeNoop(context, methodName) {
return methodName in methodNoopsAsOf
&& testReactVersion(context, methodNoopsAsOf[methodName])
&& !testReactVersion(context, '999.999.999'); // for when the version is not specified
}
// eslint-disable-next-line valid-jsdoc
/**
* @param {string} methodName
* @param {(context: import('eslint').Rule.RuleContext) => boolean} [shouldCheckUnsafeCb]
* @returns {import('eslint').Rule.RuleModule}
*/
module.exports = function makeNoMethodSetStateRule(methodName, shouldCheckUnsafeCb) {
return {
meta: {
docs: {
description: `Disallow usage of setState in ${methodName}`,
category: 'Best Practices',
recommended: false,
url: docsUrl(mapTitle(methodName)),
},
messages,
schema: [{
enum: ['disallow-in-func'],
}],
},
create(context) {
const mode = context.options[0] || 'allow-in-func';
function nameMatches(name) {
if (name === methodName) {
return true;
}
if (typeof shouldCheckUnsafeCb === 'function' && shouldCheckUnsafeCb(context)) {
return name === `UNSAFE_${methodName}`;
}
return false;
}
if (shouldBeNoop(context, methodName)) {
return {};
}
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
return {
CallExpression(node) {
const callee = node.callee;
if (
callee.type !== 'MemberExpression'
|| callee.object.type !== 'ThisExpression'
|| !('name' in callee.property)
|| callee.property.name !== 'setState'
) {
return;
}
const ancestors = getAncestors(context, node);
let depth = 0;
findLast(ancestors, (ancestor) => {
// ancestors.some((ancestor) => {
if (/Function(Expression|Declaration)$/.test(ancestor.type)) {
depth += 1;
}
if (
(ancestor.type !== 'Property' && ancestor.type !== 'MethodDefinition' && ancestor.type !== 'ClassProperty' && ancestor.type !== 'PropertyDefinition')
|| !nameMatches(ancestor.key.name)
|| (mode !== 'disallow-in-func' && depth > 1)
) {
return false;
}
report(context, messages.noSetState, 'noSetState', {
node: callee,
data: {
name: ancestor.key.name,
},
});
return true;
});
},
};
},
};
};

View File

@@ -0,0 +1,9 @@
declare function _exports(messageId: any, message: any): {
messageId: any;
message?: undefined;
} | {
message: any;
messageId?: undefined;
};
export = _exports;
//# sourceMappingURL=message.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"message.d.ts","sourceRoot":"","sources":["message.js"],"names":[],"mappings":"AAKiB;;;;;;EAEhB"}

8
node_modules/eslint-plugin-react/lib/util/message.js generated vendored Normal file
View File

@@ -0,0 +1,8 @@
'use strict';
const semver = require('semver');
const eslintPkg = require('eslint/package.json');
module.exports = function getMessageData(messageId, message) {
return messageId && semver.satisfies(eslintPkg.version, '>= 4.15') ? { messageId } : { message };
};

16
node_modules/eslint-plugin-react/lib/util/pragma.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
/**
* @param {Context} context
* @returns {string}
*/
export function getCreateClassFromContext(context: Context): string;
/**
* @param {Context} context
* @returns {string}
*/
export function getFragmentFromContext(context: Context): string;
/**
* @param {Context} context
* @returns {string}
*/
export function getFromContext(context: Context): string;
//# sourceMappingURL=pragma.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"pragma.d.ts","sourceRoot":"","sources":["pragma.js"],"names":[],"mappings":"AAaA;;;GAGG;AACH,mDAHW,OAAO,GACL,MAAM,CAYlB;AAED;;;GAGG;AACH,gDAHW,OAAO,GACL,MAAM,CAYlB;AAED;;;GAGG;AACH,wCAHW,OAAO,GACL,MAAM,CAqBlB"}

75
node_modules/eslint-plugin-react/lib/util/pragma.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
/**
* @fileoverview Utility functions for React pragma configuration
* @author Yannick Croissant
*/
'use strict';
const getSourceCode = require('./eslint').getSourceCode;
const JSX_ANNOTATION_REGEX = /@jsx\s+([^\s]+)/;
// Does not check for reserved keywords or unicode characters
const JS_IDENTIFIER_REGEX = /^[_$a-zA-Z][_$a-zA-Z0-9]*$/;
/**
* @param {Context} context
* @returns {string}
*/
function getCreateClassFromContext(context) {
let pragma = 'createReactClass';
// .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
if (context.settings.react && context.settings.react.createClass) {
pragma = context.settings.react.createClass;
}
if (!JS_IDENTIFIER_REGEX.test(pragma)) {
throw new Error(`createClass pragma ${pragma} is not a valid function name`);
}
return pragma;
}
/**
* @param {Context} context
* @returns {string}
*/
function getFragmentFromContext(context) {
let pragma = 'Fragment';
// .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
if (context.settings.react && context.settings.react.fragment) {
pragma = context.settings.react.fragment;
}
if (!JS_IDENTIFIER_REGEX.test(pragma)) {
throw new Error(`Fragment pragma ${pragma} is not a valid identifier`);
}
return pragma;
}
/**
* @param {Context} context
* @returns {string}
*/
function getFromContext(context) {
let pragma = 'React';
const sourceCode = getSourceCode(context);
const pragmaNode = sourceCode.getAllComments().find((node) => JSX_ANNOTATION_REGEX.test(node.value));
if (pragmaNode) {
const matches = JSX_ANNOTATION_REGEX.exec(pragmaNode.value);
pragma = matches[1].split('.')[0];
// .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
} else if (context.settings.react && context.settings.react.pragma) {
pragma = context.settings.react.pragma;
}
if (!JS_IDENTIFIER_REGEX.test(pragma)) {
console.warn(`React pragma ${pragma} is not a valid identifier`);
return 'React';
}
return pragma;
}
module.exports = {
getCreateClassFromContext,
getFragmentFromContext,
getFromContext,
};

View File

@@ -0,0 +1,20 @@
declare function _exports(context: any, components: any, utils: any): {
ClassExpression(node: any): void;
ClassDeclaration(node: any): void;
'ClassProperty, PropertyDefinition'(node: any): void;
ObjectExpression(node: any): void;
FunctionExpression(node: any): void;
ImportDeclaration(node: any): void;
FunctionDeclaration: (node: ASTNode, rootNode: ASTNode) => void;
ArrowFunctionExpression: (node: ASTNode, rootNode: ASTNode) => void;
MemberExpression(node: any): void;
MethodDefinition(node: any): void;
TypeAlias(node: any): void;
TypeParameterDeclaration(node: any): void;
Program(): void;
BlockStatement(): void;
'BlockStatement:exit'(): void;
'Program:exit'(): void;
};
export = _exports;
//# sourceMappingURL=propTypes.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"propTypes.d.ts","sourceRoot":"","sources":["propTypes.js"],"names":[],"mappings":"AAoGiB;;;;;;;gCAu6BJ,OAAO,YAEP,OAAO;oCAFP,OAAO,YAEP,OAAO;;;;;;;;;EAqQnB"}

1299
node_modules/eslint-plugin-react/lib/util/propTypes.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,40 @@
/**
* Fixes sort order of prop types.
*
* @param {Context} context the second element to compare.
* @param {Fixer} fixer the first element to compare.
* @param {Array} declarations The context of the two nodes.
* @param {boolean=} ignoreCase whether or not to ignore case when comparing the two elements.
* @param {boolean=} requiredFirst whether or not to sort required elements first.
* @param {boolean=} callbacksLast whether or not to sort callbacks after everything else.
* @param {boolean=} noSortAlphabetically whether or not to disable alphabetical sorting of the elements.
* @param {boolean=} sortShapeProp whether or not to sort propTypes defined in PropTypes.shape.
* @param {boolean=} checkTypes whether or not sorting of prop type definitions are checked.
* @returns {Object|*|{range, text}} the sort order of the two elements.
*/
export function fixPropTypesSort(context: Context, fixer: Fixer, declarations: any[], ignoreCase?: boolean | undefined, requiredFirst?: boolean | undefined, callbacksLast?: boolean | undefined, noSortAlphabetically?: boolean | undefined, sortShapeProp?: boolean | undefined, checkTypes?: boolean | undefined): any | any | {
range;
text;
};
/**
* Checks if the proptype is a callback by checking if it starts with 'on'.
*
* @param {string} propName the name of the proptype to check.
* @returns {boolean} true if the proptype is a callback.
*/
export function isCallbackPropName(propName: string): boolean;
/**
* Checks if the prop is required or not.
*
* @param {ASTNode} node the prop to check.
* @returns {boolean} true if the prop is required.
*/
export function isRequiredProp(node: ASTNode): boolean;
/**
* Checks if the prop is PropTypes.shape.
*
* @param {ASTNode} node the prop to check.
* @returns {boolean} true if the prop is PropTypes.shape.
*/
export function isShapeProp(node: ASTNode): boolean;
//# sourceMappingURL=propTypesSort.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"propTypesSort.d.ts","sourceRoot":"","sources":["propTypesSort.js"],"names":[],"mappings":"AA4HA;;;;;;;;;;;;;GAaG;AACH,0CAXW,OAAO,SACP,KAAK,oCAEL,OAAO,8BACP,OAAO,8BACP,OAAO,qCACP,OAAO,8BACP,OAAO,2BACP,OAAO,eACL,YAAS;IAAC,KAAK,CAAC;IAAC,IAAI,CAAA;CAAC,CAyFlC;AA7LD;;;;;GAKG;AACH,6CAHW,MAAM,GACJ,OAAO,CAInB;AAlBD;;;;;GAKG;AACH,qCAHW,OAAO,GACL,OAAO,CAInB;AAYD;;;;;GAKG;AACH,kCAHW,OAAO,GACL,OAAO,CASnB"}

View File

@@ -0,0 +1,233 @@
/**
* @fileoverview Common propTypes sorting functionality.
*/
'use strict';
const toSorted = require('array.prototype.tosorted');
const astUtil = require('./ast');
const eslintUtil = require('./eslint');
const getSourceCode = eslintUtil.getSourceCode;
const getText = eslintUtil.getText;
/**
* Returns the value name of a node.
*
* @param {ASTNode} node the node to check.
* @returns {string} The name of the node.
*/
function getValueName(node) {
return node.type === 'Property'
&& node.value.property
&& node.value.property.name;
}
/**
* Checks if the prop is required or not.
*
* @param {ASTNode} node the prop to check.
* @returns {boolean} true if the prop is required.
*/
function isRequiredProp(node) {
return getValueName(node) === 'isRequired';
}
/**
* Checks if the proptype is a callback by checking if it starts with 'on'.
*
* @param {string} propName the name of the proptype to check.
* @returns {boolean} true if the proptype is a callback.
*/
function isCallbackPropName(propName) {
return /^on[A-Z]/.test(propName);
}
/**
* Checks if the prop is PropTypes.shape.
*
* @param {ASTNode} node the prop to check.
* @returns {boolean} true if the prop is PropTypes.shape.
*/
function isShapeProp(node) {
return !!(
node
&& node.callee
&& node.callee.property
&& node.callee.property.name === 'shape'
);
}
/**
* Returns the properties of a PropTypes.shape.
*
* @param {ASTNode} node the prop to check.
* @returns {Array} the properties of the PropTypes.shape node.
*/
function getShapeProperties(node) {
return node.arguments
&& node.arguments[0]
&& node.arguments[0].properties;
}
/**
* Compares two elements.
*
* @param {ASTNode} a the first element to compare.
* @param {ASTNode} b the second element to compare.
* @param {Context} context The context of the two nodes.
* @param {boolean=} ignoreCase whether or not to ignore case when comparing the two elements.
* @param {boolean=} requiredFirst whether or not to sort required elements first.
* @param {boolean=} callbacksLast whether or not to sort callbacks after everything else.
* @param {boolean=} noSortAlphabetically whether or not to disable alphabetical sorting of the elements.
* @returns {number} the sort order of the two elements.
*/
function sorter(a, b, context, ignoreCase, requiredFirst, callbacksLast, noSortAlphabetically) {
const aKey = String(astUtil.getKeyValue(context, a));
const bKey = String(astUtil.getKeyValue(context, b));
if (requiredFirst) {
if (isRequiredProp(a) && !isRequiredProp(b)) {
return -1;
}
if (!isRequiredProp(a) && isRequiredProp(b)) {
return 1;
}
}
if (callbacksLast) {
if (isCallbackPropName(aKey) && !isCallbackPropName(bKey)) {
return 1;
}
if (!isCallbackPropName(aKey) && isCallbackPropName(bKey)) {
return -1;
}
}
if (!noSortAlphabetically) {
if (ignoreCase) {
return aKey.localeCompare(bKey);
}
if (aKey < bKey) {
return -1;
}
if (aKey > bKey) {
return 1;
}
}
return 0;
}
const commentnodeMap = new WeakMap(); // all nodes reference WeakMap for start and end range
/**
* Fixes sort order of prop types.
*
* @param {Context} context the second element to compare.
* @param {Fixer} fixer the first element to compare.
* @param {Array} declarations The context of the two nodes.
* @param {boolean=} ignoreCase whether or not to ignore case when comparing the two elements.
* @param {boolean=} requiredFirst whether or not to sort required elements first.
* @param {boolean=} callbacksLast whether or not to sort callbacks after everything else.
* @param {boolean=} noSortAlphabetically whether or not to disable alphabetical sorting of the elements.
* @param {boolean=} sortShapeProp whether or not to sort propTypes defined in PropTypes.shape.
* @param {boolean=} checkTypes whether or not sorting of prop type definitions are checked.
* @returns {Object|*|{range, text}} the sort order of the two elements.
*/
function fixPropTypesSort(
context,
fixer,
declarations,
ignoreCase,
requiredFirst,
callbacksLast,
noSortAlphabetically,
sortShapeProp,
checkTypes
) {
function sortInSource(allNodes, source) {
const originalSource = source;
const sourceCode = getSourceCode(context);
for (let i = 0; i < allNodes.length; i++) {
const node = allNodes[i];
let commentAfter = [];
let commentBefore = [];
let newStart = 0;
let newEnd = 0;
try {
commentBefore = sourceCode.getCommentsBefore(node);
commentAfter = sourceCode.getCommentsAfter(node);
} catch (e) { /**/ }
if (commentAfter.length === 0 || commentBefore.length === 0) {
newStart = node.range[0];
newEnd = node.range[1];
}
const firstCommentBefore = commentBefore[0];
if (commentBefore.length >= 1) {
newStart = firstCommentBefore.range[0];
}
const lastCommentAfter = commentAfter[commentAfter.length - 1];
if (commentAfter.length >= 1) {
newEnd = lastCommentAfter.range[1];
}
commentnodeMap.set(node, { start: newStart, end: newEnd, hasComment: true });
}
const nodeGroups = allNodes.reduce((acc, curr) => {
if (curr.type === 'ExperimentalSpreadProperty' || curr.type === 'SpreadElement') {
acc.push([]);
} else {
acc[acc.length - 1].push(curr);
}
return acc;
}, [[]]);
nodeGroups.forEach((nodes) => {
const sortedAttributes = toSorted(
nodes,
(a, b) => sorter(a, b, context, ignoreCase, requiredFirst, callbacksLast, noSortAlphabetically)
);
const sourceCodeText = getText(context);
let separator = '';
source = nodes.reduceRight((acc, attr, index) => {
const sortedAttr = sortedAttributes[index];
const commentNode = commentnodeMap.get(sortedAttr);
let sortedAttrText = sourceCodeText.slice(commentNode.start, commentNode.end);
const sortedAttrTextLastChar = sortedAttrText[sortedAttrText.length - 1];
if (!separator && [';', ','].some((allowedSep) => sortedAttrTextLastChar === allowedSep)) {
separator = sortedAttrTextLastChar;
}
if (sortShapeProp && isShapeProp(sortedAttr.value)) {
const shape = getShapeProperties(sortedAttr.value);
if (shape) {
const attrSource = sortInSource(
shape,
originalSource
);
sortedAttrText = attrSource.slice(sortedAttr.range[0], sortedAttr.range[1]);
}
}
const sortedAttrTextVal = checkTypes && !sortedAttrText.endsWith(separator) ? `${sortedAttrText}${separator}` : sortedAttrText;
return `${acc.slice(0, commentnodeMap.get(attr).start)}${sortedAttrTextVal}${acc.slice(commentnodeMap.get(attr).end)}`;
}, source);
});
return source;
}
const source = sortInSource(declarations, getText(context));
const rangeStart = commentnodeMap.get(declarations[0]).start;
const rangeEnd = commentnodeMap.get(declarations[declarations.length - 1]).end;
return fixer.replaceTextRange([rangeStart, rangeEnd], source.slice(rangeStart, rangeEnd));
}
module.exports = {
fixPropTypesSort,
isCallbackPropName,
isRequiredProp,
isShapeProp,
};

View File

@@ -0,0 +1,6 @@
export function formatPropWrapperFunctions(propWrapperFunctions: any): string;
export function getExactPropWrapperFunctions(context: any): Set<any>;
export function getPropWrapperFunctions(context: any): Set<any>;
export function isExactPropWrapperFunction(context: any, name: any): any;
export function isPropWrapperFunction(context: any, name: any): any;
//# sourceMappingURL=propWrapper.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"propWrapper.d.ts","sourceRoot":"","sources":["propWrapper.js"],"names":[],"mappings":"AA0CA,8EAUC;AArBD,qEAIC;AAhBD,gEAEC;AAgBD,yEAGC;AAjBD,oEAMC"}

View File

@@ -0,0 +1,61 @@
/**
* @fileoverview Utility functions for propWrapperFunctions setting
*/
'use strict';
const filter = require('es-iterator-helpers/Iterator.prototype.filter');
const some = require('es-iterator-helpers/Iterator.prototype.some');
function searchPropWrapperFunctions(name, propWrapperFunctions) {
const splitName = name.split('.');
return some(propWrapperFunctions.values(), (func) => {
if (splitName.length === 2 && func.object === splitName[0] && func.property === splitName[1]) {
return true;
}
return name === func || func.property === name;
});
}
function getPropWrapperFunctions(context) {
return new Set(context.settings.propWrapperFunctions || []);
}
function isPropWrapperFunction(context, name) {
if (typeof name !== 'string') {
return false;
}
const propWrapperFunctions = getPropWrapperFunctions(context);
return searchPropWrapperFunctions(name, propWrapperFunctions);
}
function getExactPropWrapperFunctions(context) {
const propWrapperFunctions = getPropWrapperFunctions(context);
const exactPropWrappers = filter(propWrapperFunctions.values(), (func) => func.exact === true);
return new Set(exactPropWrappers);
}
function isExactPropWrapperFunction(context, name) {
const exactPropWrappers = getExactPropWrapperFunctions(context);
return searchPropWrapperFunctions(name, exactPropWrappers);
}
function formatPropWrapperFunctions(propWrapperFunctions) {
return Array.from(propWrapperFunctions, (func) => {
if (func.object && func.property) {
return `'${func.object}.${func.property}'`;
}
if (func.property) {
return `'${func.property}'`;
}
return `'${func}'`;
}).join(', ');
}
module.exports = {
formatPropWrapperFunctions,
getExactPropWrapperFunctions,
getPropWrapperFunctions,
isExactPropWrapperFunction,
isPropWrapperFunction,
};

55
node_modules/eslint-plugin-react/lib/util/props.d.ts generated vendored Normal file
View File

@@ -0,0 +1,55 @@
/**
* Checks if the Identifier node passed in looks like a propTypes declaration.
* @param {ASTNode} node The node to check. Must be an Identifier node.
* @returns {boolean} `true` if the node is a propTypes declaration, `false` if not
*/
export function isPropTypesDeclaration(node: ASTNode): boolean;
/**
* Checks if the node passed in looks like a contextTypes declaration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a contextTypes declaration, `false` if not
*/
export function isContextTypesDeclaration(node: ASTNode): boolean;
/**
* Checks if the node passed in looks like a contextType declaration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a contextType declaration, `false` if not
*/
export function isContextTypeDeclaration(node: ASTNode): boolean;
/**
* Checks if the node passed in looks like a childContextTypes declaration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a childContextTypes declaration, `false` if not
*/
export function isChildContextTypesDeclaration(node: ASTNode): boolean;
/**
* Checks if the Identifier node passed in looks like a defaultProps declaration.
* @param {ASTNode} node The node to check. Must be an Identifier node.
* @returns {boolean} `true` if the node is a defaultProps declaration, `false` if not
*/
export function isDefaultPropsDeclaration(node: ASTNode): boolean;
/**
* Checks if we are declaring a display name
* @param {ASTNode} node The AST node being checked.
* @returns {boolean} True if we are declaring a display name, false if not.
*/
export function isDisplayNameDeclaration(node: ASTNode): boolean;
/**
* Checks if the PropTypes MemberExpression node passed in declares a required propType.
* @param {ASTNode} propTypeExpression node to check. Must be a `PropTypes` MemberExpression.
* @returns {boolean} `true` if this PropType is required, `false` if not.
*/
export function isRequiredPropType(propTypeExpression: ASTNode): boolean;
/**
* Returns the type arguments of a node or type parameters if type arguments are not available.
* @param {ASTNode} node The node to get the type arguments from.
* @returns {ASTNode} The type arguments or type parameters of the node.
*/
export function getTypeArguments(node: ASTNode): ASTNode;
/**
* Returns the super type arguments of a node or super type parameters if type arguments are not available.
* @param {ASTNode} node The node to get the super type arguments from.
* @returns {ASTNode} The super type arguments or parameters of the node.
*/
export function getSuperTypeArguments(node: ASTNode): ASTNode;
//# sourceMappingURL=props.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"props.d.ts","sourceRoot":"","sources":["props.js"],"names":[],"mappings":"AAQA;;;;GAIG;AACH,6CAHW,OAAO,GACL,OAAO,CAUnB;AAED;;;;GAIG;AACH,gDAHW,OAAO,GACL,OAAO,CAUnB;AAED;;;;GAIG;AACH,+CAHW,OAAO,GACL,OAAO,CAInB;AAED;;;;GAIG;AACH,qDAHW,OAAO,GACL,OAAO,CAInB;AAED;;;;GAIG;AACH,gDAHW,OAAO,GACL,OAAO,CAKnB;AAED;;;;GAIG;AACH,+CAHW,OAAO,GACL,OAAO,CAcnB;AAED;;;;GAIG;AACH,uDAHW,OAAO,GACL,OAAO,CAKnB;AAED;;;;GAIG;AACH,uCAHW,OAAO,GACL,OAAO,CAOnB;AAED;;;;GAIG;AACH,4CAHW,OAAO,GACL,OAAO,CAOnB"}

130
node_modules/eslint-plugin-react/lib/util/props.js generated vendored Normal file
View File

@@ -0,0 +1,130 @@
/**
* @fileoverview Utility functions for props
*/
'use strict';
const astUtil = require('./ast');
/**
* Checks if the Identifier node passed in looks like a propTypes declaration.
* @param {ASTNode} node The node to check. Must be an Identifier node.
* @returns {boolean} `true` if the node is a propTypes declaration, `false` if not
*/
function isPropTypesDeclaration(node) {
if (node && (node.type === 'ClassProperty' || node.type === 'PropertyDefinition')) {
// Flow support
if (node.typeAnnotation && node.key.name === 'props') {
return true;
}
}
return astUtil.getPropertyName(node) === 'propTypes';
}
/**
* Checks if the node passed in looks like a contextTypes declaration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a contextTypes declaration, `false` if not
*/
function isContextTypesDeclaration(node) {
if (node && (node.type === 'ClassProperty' || node.type === 'PropertyDefinition')) {
// Flow support
if (node.typeAnnotation && node.key.name === 'context') {
return true;
}
}
return astUtil.getPropertyName(node) === 'contextTypes';
}
/**
* Checks if the node passed in looks like a contextType declaration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a contextType declaration, `false` if not
*/
function isContextTypeDeclaration(node) {
return astUtil.getPropertyName(node) === 'contextType';
}
/**
* Checks if the node passed in looks like a childContextTypes declaration.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is a childContextTypes declaration, `false` if not
*/
function isChildContextTypesDeclaration(node) {
return astUtil.getPropertyName(node) === 'childContextTypes';
}
/**
* Checks if the Identifier node passed in looks like a defaultProps declaration.
* @param {ASTNode} node The node to check. Must be an Identifier node.
* @returns {boolean} `true` if the node is a defaultProps declaration, `false` if not
*/
function isDefaultPropsDeclaration(node) {
const propName = astUtil.getPropertyName(node);
return (propName === 'defaultProps' || propName === 'getDefaultProps');
}
/**
* Checks if we are declaring a display name
* @param {ASTNode} node The AST node being checked.
* @returns {boolean} True if we are declaring a display name, false if not.
*/
function isDisplayNameDeclaration(node) {
switch (node.type) {
case 'ClassProperty':
case 'PropertyDefinition':
return node.key && node.key.name === 'displayName';
case 'Identifier':
return node.name === 'displayName';
case 'Literal':
return node.value === 'displayName';
default:
return false;
}
}
/**
* Checks if the PropTypes MemberExpression node passed in declares a required propType.
* @param {ASTNode} propTypeExpression node to check. Must be a `PropTypes` MemberExpression.
* @returns {boolean} `true` if this PropType is required, `false` if not.
*/
function isRequiredPropType(propTypeExpression) {
return propTypeExpression.type === 'MemberExpression'
&& propTypeExpression.property.name === 'isRequired';
}
/**
* Returns the type arguments of a node or type parameters if type arguments are not available.
* @param {ASTNode} node The node to get the type arguments from.
* @returns {ASTNode} The type arguments or type parameters of the node.
*/
function getTypeArguments(node) {
if ('typeArguments' in node) {
return node.typeArguments;
}
return node.typeParameters;
}
/**
* Returns the super type arguments of a node or super type parameters if type arguments are not available.
* @param {ASTNode} node The node to get the super type arguments from.
* @returns {ASTNode} The super type arguments or parameters of the node.
*/
function getSuperTypeArguments(node) {
if ('superTypeArguments' in node) {
return node.superTypeArguments;
}
return node.superTypeParameters;
}
module.exports = {
isPropTypesDeclaration,
isContextTypesDeclaration,
isContextTypeDeclaration,
isChildContextTypesDeclaration,
isDefaultPropsDeclaration,
isDisplayNameDeclaration,
isRequiredPropType,
getTypeArguments,
getSuperTypeArguments,
};

View File

@@ -0,0 +1,3 @@
declare function _exports(context: any, message: any, messageId: any, data: any): void;
export = _exports;
//# sourceMappingURL=report.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"report.d.ts","sourceRoot":"","sources":["report.js"],"names":[],"mappings":"AAIiB,uFAOhB"}

12
node_modules/eslint-plugin-react/lib/util/report.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
'use strict';
const getMessageData = require('./message');
module.exports = function report(context, message, messageId, data) {
context.report(
Object.assign(
getMessageData(messageId, message),
data
)
);
};

View File

@@ -0,0 +1,15 @@
declare function _exports(context: any, components: any, utils: any): {
VariableDeclarator(node: any): void;
FunctionDeclaration: (node: ASTNode) => void;
ArrowFunctionExpression: (node: ASTNode) => void;
FunctionExpression: (node: ASTNode) => void;
'FunctionDeclaration:exit': () => void;
'ArrowFunctionExpression:exit': () => void;
'FunctionExpression:exit': () => void;
JSXSpreadAttribute(node: any): void;
'MemberExpression, OptionalMemberExpression'(node: any): void;
ObjectPattern(node: any): void;
'Program:exit'(): void;
};
export = _exports;
//# sourceMappingURL=usedPropTypes.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"usedPropTypes.d.ts","sourceRoot":"","sources":["usedPropTypes.js"],"names":[],"mappings":"AAiTiB;;gCA2JJ,OAAO;oCAAP,OAAO;+BAAP,OAAO;;;;;;;;EA2HnB"}

View File

@@ -0,0 +1,584 @@
/**
* @fileoverview Common used propTypes detection functionality.
*/
'use strict';
const values = require('object.values');
const astUtil = require('./ast');
const componentUtil = require('./componentUtil');
const testReactVersion = require('./version').testReactVersion;
const ast = require('./ast');
const eslintUtil = require('./eslint');
const getScope = eslintUtil.getScope;
const getSourceCode = eslintUtil.getSourceCode;
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
const LIFE_CYCLE_METHODS = ['componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'componentDidUpdate'];
const ASYNC_SAFE_LIFE_CYCLE_METHODS = ['getDerivedStateFromProps', 'getSnapshotBeforeUpdate', 'UNSAFE_componentWillReceiveProps', 'UNSAFE_componentWillUpdate'];
function createPropVariables() {
/** @type {Map<string, string[]>} Maps the variable to its definition. `props.a.b` is stored as `['a', 'b']` */
let propVariables = new Map();
let hasBeenWritten = false;
const stack = [{ propVariables, hasBeenWritten }];
return {
pushScope() {
// popVariables is not copied until first write.
stack.push({ propVariables, hasBeenWritten: false });
},
popScope() {
stack.pop();
propVariables = stack[stack.length - 1].propVariables;
hasBeenWritten = stack[stack.length - 1].hasBeenWritten;
},
/**
* Add a variable name to the current scope
* @param {string} name
* @param {string[]} allNames Example: `props.a.b` should be formatted as `['a', 'b']`
* @returns {Map<string, string[]>}
*/
set(name, allNames) {
if (!hasBeenWritten) {
// copy on write
propVariables = new Map(propVariables);
Object.assign(stack[stack.length - 1], { propVariables, hasBeenWritten: true });
stack[stack.length - 1].hasBeenWritten = true;
}
return propVariables.set(name, allNames);
},
/**
* Get the definition of a variable.
* @param {string} name
* @returns {string[]} Example: `props.a.b` is represented by `['a', 'b']`
*/
get(name) {
return propVariables.get(name);
},
};
}
/**
* Checks if the string is one of `props`, `nextProps`, or `prevProps`
* @param {string} name The AST node being checked.
* @returns {boolean} True if the prop name matches
*/
function isCommonVariableNameForProps(name) {
return name === 'props' || name === 'nextProps' || name === 'prevProps';
}
/**
* Checks if the component must be validated
* @param {Object} component The component to process
* @returns {boolean} True if the component must be validated, false if not.
*/
function mustBeValidated(component) {
return !!(component && !component.ignorePropsValidation);
}
/**
* Check if we are in a lifecycle method
* @param {object} context
* @param {ASTNode} node The AST node being checked.
* @param {boolean} checkAsyncSafeLifeCycles
* @return {boolean} true if we are in a class constructor, false if not
*/
function inLifeCycleMethod(context, node, checkAsyncSafeLifeCycles) {
let scope = getScope(context, node);
while (scope) {
if (scope.block && scope.block.parent && scope.block.parent.key) {
const name = scope.block.parent.key.name;
if (LIFE_CYCLE_METHODS.indexOf(name) >= 0) {
return true;
}
if (checkAsyncSafeLifeCycles && ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(name) >= 0) {
return true;
}
}
scope = scope.upper;
}
return false;
}
/**
* Returns true if the given node is a React Component lifecycle method
* @param {ASTNode} node The AST node being checked.
* @param {boolean} checkAsyncSafeLifeCycles
* @return {boolean} True if the node is a lifecycle method
*/
function isNodeALifeCycleMethod(node, checkAsyncSafeLifeCycles) {
if (node.key) {
if (node.kind === 'constructor') {
return true;
}
const nodeKeyName = node.key.name;
if (typeof nodeKeyName !== 'string') {
return false;
}
if (LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0) {
return true;
}
if (checkAsyncSafeLifeCycles && ASYNC_SAFE_LIFE_CYCLE_METHODS.indexOf(nodeKeyName) >= 0) {
return true;
}
}
return false;
}
/**
* Returns true if the given node is inside a React Component lifecycle
* method.
* @param {ASTNode} node The AST node being checked.
* @param {boolean} checkAsyncSafeLifeCycles
* @return {boolean} True if the node is inside a lifecycle method
*/
function isInLifeCycleMethod(node, checkAsyncSafeLifeCycles) {
if (
(node.type === 'MethodDefinition' || node.type === 'Property')
&& isNodeALifeCycleMethod(node, checkAsyncSafeLifeCycles)
) {
return true;
}
if (node.parent) {
return isInLifeCycleMethod(node.parent, checkAsyncSafeLifeCycles);
}
return false;
}
/**
* Check if a function node is a setState updater
* @param {ASTNode} node a function node
* @return {boolean}
*/
function isSetStateUpdater(node) {
const unwrappedParentCalleeNode = astUtil.isCallExpression(node.parent)
&& ast.unwrapTSAsExpression(node.parent.callee);
return unwrappedParentCalleeNode
&& unwrappedParentCalleeNode.property
&& unwrappedParentCalleeNode.property.name === 'setState'
// Make sure we are in the updater not the callback
&& node.parent.arguments[0] === node;
}
function isPropArgumentInSetStateUpdater(context, node, name) {
if (typeof name !== 'string') {
return;
}
let scope = getScope(context, node);
while (scope) {
const unwrappedParentCalleeNode = scope.block
&& astUtil.isCallExpression(scope.block.parent)
&& ast.unwrapTSAsExpression(scope.block.parent.callee);
if (
unwrappedParentCalleeNode
&& unwrappedParentCalleeNode.property
&& unwrappedParentCalleeNode.property.name === 'setState'
// Make sure we are in the updater not the callback
&& scope.block.parent.arguments[0].range[0] === scope.block.range[0]
&& scope.block.parent.arguments[0].params
&& scope.block.parent.arguments[0].params.length > 1
) {
return scope.block.parent.arguments[0].params[1].name === name;
}
scope = scope.upper;
}
return false;
}
/**
* @param {Context} context
* @param {ASTNode} node
* @returns {boolean}
*/
function isInClassComponent(context, node) {
return !!(componentUtil.getParentES6Component(context, node) || componentUtil.getParentES5Component(context, node));
}
/**
* Checks if the node is `this.props`
* @param {ASTNode|undefined} node
* @returns {boolean}
*/
function isThisDotProps(node) {
return !!node
&& node.type === 'MemberExpression'
&& ast.unwrapTSAsExpression(node.object).type === 'ThisExpression'
&& node.property.name === 'props';
}
/**
* Checks if the prop has spread operator.
* @param {object} context
* @param {ASTNode} node The AST node being marked.
* @returns {boolean} True if the prop has spread operator, false if not.
*/
function hasSpreadOperator(context, node) {
const tokens = getSourceCode(context).getTokens(node);
return tokens.length && tokens[0].value === '...';
}
/**
* Checks if the node is a propTypes usage of the form `this.props.*`, `props.*`, `prevProps.*`, or `nextProps.*`.
* @param {Context} context
* @param {ASTNode} node
* @param {Object} utils
* @param {boolean} checkAsyncSafeLifeCycles
* @returns {boolean}
*/
function isPropTypesUsageByMemberExpression(context, node, utils, checkAsyncSafeLifeCycles) {
const unwrappedObjectNode = ast.unwrapTSAsExpression(node.object);
if (isInClassComponent(context, node)) {
// this.props.*
if (isThisDotProps(unwrappedObjectNode)) {
return true;
}
// props.* or prevProps.* or nextProps.*
if (
isCommonVariableNameForProps(unwrappedObjectNode.name)
&& (inLifeCycleMethod(context, node, checkAsyncSafeLifeCycles) || astUtil.inConstructor(context, node))
) {
return true;
}
// this.setState((_, props) => props.*))
if (isPropArgumentInSetStateUpdater(context, node, unwrappedObjectNode.name)) {
return true;
}
return false;
}
// props.* in function component
return unwrappedObjectNode.name === 'props' && !ast.isAssignmentLHS(node);
}
/**
* Retrieve the name of a property node
* @param {Context} context
* @param {ASTNode} node The AST node with the property.
* @param {Object} utils
* @param {boolean} checkAsyncSafeLifeCycles
* @return {string|undefined} the name of the property or undefined if not found
*/
function getPropertyName(context, node, utils, checkAsyncSafeLifeCycles) {
const property = node.property;
if (property) {
switch (property.type) {
case 'Identifier':
if (node.computed) {
return '__COMPUTED_PROP__';
}
return property.name;
case 'MemberExpression':
return;
case 'Literal':
// Accept computed properties that are literal strings
if (typeof property.value === 'string') {
return property.value;
}
// Accept number as well but only accept props[123]
if (typeof property.value === 'number') {
if (isPropTypesUsageByMemberExpression(context, node, utils, checkAsyncSafeLifeCycles)) {
return property.raw;
}
}
// falls through
default:
if (node.computed) {
return '__COMPUTED_PROP__';
}
break;
}
}
}
module.exports = function usedPropTypesInstructions(context, components, utils) {
const checkAsyncSafeLifeCycles = testReactVersion(context, '>= 16.3.0');
const propVariables = createPropVariables();
const pushScope = propVariables.pushScope;
const popScope = propVariables.popScope;
/**
* Mark a prop type as used
* @param {ASTNode} node The AST node being marked.
* @param {string[]} [parentNames]
*/
function markPropTypesAsUsed(node, parentNames) {
parentNames = parentNames || [];
let type;
let name;
let allNames;
let properties;
switch (node.type) {
case 'OptionalMemberExpression':
case 'MemberExpression':
name = getPropertyName(context, node, utils, checkAsyncSafeLifeCycles);
if (name) {
allNames = parentNames.concat(name);
if (
// Match props.foo.bar, don't match bar[props.foo]
node.parent.type === 'MemberExpression'
&& node.parent.object === node
) {
markPropTypesAsUsed(node.parent, allNames);
}
// Handle the destructuring part of `const {foo} = props.a.b`
if (
node.parent.type === 'VariableDeclarator'
&& node.parent.id.type === 'ObjectPattern'
) {
node.parent.id.parent = node.parent; // patch for bug in eslint@4 in which ObjectPattern has no parent
markPropTypesAsUsed(node.parent.id, allNames);
}
// const a = props.a
if (
node.parent.type === 'VariableDeclarator'
&& node.parent.id.type === 'Identifier'
) {
propVariables.set(node.parent.id.name, allNames);
}
// Do not mark computed props as used.
type = name !== '__COMPUTED_PROP__' ? 'direct' : null;
}
break;
case 'ArrowFunctionExpression':
case 'FunctionDeclaration':
case 'FunctionExpression': {
if (node.params.length === 0) {
break;
}
type = 'destructuring';
const propParam = isSetStateUpdater(node) ? node.params[1] : node.params[0];
properties = propParam.type === 'AssignmentPattern'
? propParam.left.properties
: propParam.properties;
break;
}
case 'ObjectPattern':
type = 'destructuring';
properties = node.properties;
break;
case 'TSEmptyBodyFunctionExpression':
break;
default:
throw new Error(`${node.type} ASTNodes are not handled by markPropTypesAsUsed`);
}
const component = components.get(utils.getParentComponent(node));
const usedPropTypes = (component && component.usedPropTypes) || [];
let ignoreUnusedPropTypesValidation = (component && component.ignoreUnusedPropTypesValidation) || false;
switch (type) {
case 'direct': {
// Ignore Object methods
if (name in Object.prototype) {
break;
}
const reportedNode = node.property;
usedPropTypes.push({
name,
allNames,
node: reportedNode,
});
break;
}
case 'destructuring': {
for (let k = 0, l = (properties || []).length; k < l; k++) {
if (hasSpreadOperator(context, properties[k]) || properties[k].computed) {
ignoreUnusedPropTypesValidation = true;
break;
}
const propName = ast.getKeyValue(context, properties[k]);
if (!propName || properties[k].type !== 'Property') {
break;
}
usedPropTypes.push({
allNames: parentNames.concat([propName]),
name: propName,
node: properties[k],
});
if (properties[k].value.type === 'ObjectPattern') {
markPropTypesAsUsed(properties[k].value, parentNames.concat([propName]));
} else if (properties[k].value.type === 'Identifier') {
propVariables.set(properties[k].value.name, parentNames.concat(propName));
}
}
break;
}
default:
break;
}
components.set(component ? component.node : node, {
usedPropTypes,
ignoreUnusedPropTypesValidation,
});
}
/**
* @param {ASTNode} node We expect either an ArrowFunctionExpression,
* FunctionDeclaration, or FunctionExpression
*/
function markDestructuredFunctionArgumentsAsUsed(node) {
const param = node.params && isSetStateUpdater(node) ? node.params[1] : node.params[0];
const destructuring = param && (
param.type === 'ObjectPattern'
|| ((param.type === 'AssignmentPattern') && (param.left.type === 'ObjectPattern'))
);
if (destructuring && (components.get(node) || components.get(node.parent))) {
markPropTypesAsUsed(node);
}
}
function handleSetStateUpdater(node) {
if (!node.params || node.params.length < 2 || !isSetStateUpdater(node)) {
return;
}
markPropTypesAsUsed(node);
}
/**
* Handle both stateless functions and setState updater functions.
* @param {ASTNode} node We expect either an ArrowFunctionExpression,
* FunctionDeclaration, or FunctionExpression
*/
function handleFunctionLikeExpressions(node) {
pushScope();
handleSetStateUpdater(node);
markDestructuredFunctionArgumentsAsUsed(node);
}
function handleCustomValidators(component) {
const propTypes = component.declaredPropTypes;
if (!propTypes) {
return;
}
Object.keys(propTypes).forEach((key) => {
const node = propTypes[key].node;
if (node && node.value && astUtil.isFunctionLikeExpression(node.value)) {
markPropTypesAsUsed(node.value);
}
});
}
return {
VariableDeclarator(node) {
const unwrappedInitNode = ast.unwrapTSAsExpression(node.init);
// let props = this.props
if (isThisDotProps(unwrappedInitNode) && isInClassComponent(context, node) && node.id.type === 'Identifier') {
propVariables.set(node.id.name, []);
}
// Only handles destructuring
if (node.id.type !== 'ObjectPattern' || !unwrappedInitNode) {
return;
}
// let {props: {firstname}} = this
const propsProperty = node.id.properties.find((property) => (
property.key
&& (property.key.name === 'props' || property.key.value === 'props')
));
if (unwrappedInitNode.type === 'ThisExpression' && propsProperty && propsProperty.value.type === 'ObjectPattern') {
markPropTypesAsUsed(propsProperty.value);
return;
}
// let {props} = this
if (unwrappedInitNode.type === 'ThisExpression' && propsProperty && propsProperty.value.name === 'props') {
propVariables.set('props', []);
return;
}
// let {firstname} = props
if (
isCommonVariableNameForProps(unwrappedInitNode.name)
&& (utils.getParentStatelessComponent(node) || isInLifeCycleMethod(node, checkAsyncSafeLifeCycles))
) {
markPropTypesAsUsed(node.id);
return;
}
// let {firstname} = this.props
if (isThisDotProps(unwrappedInitNode) && isInClassComponent(context, node)) {
markPropTypesAsUsed(node.id);
return;
}
// let {firstname} = thing, where thing is defined by const thing = this.props.**.*
if (propVariables.get(unwrappedInitNode.name)) {
markPropTypesAsUsed(node.id, propVariables.get(unwrappedInitNode.name));
}
},
FunctionDeclaration: handleFunctionLikeExpressions,
ArrowFunctionExpression: handleFunctionLikeExpressions,
FunctionExpression: handleFunctionLikeExpressions,
'FunctionDeclaration:exit': popScope,
'ArrowFunctionExpression:exit': popScope,
'FunctionExpression:exit': popScope,
JSXSpreadAttribute(node) {
const component = components.get(utils.getParentComponent(node));
components.set(component ? component.node : node, {
ignoreUnusedPropTypesValidation: node.argument.type !== 'ObjectExpression',
});
},
'MemberExpression, OptionalMemberExpression'(node) {
if (isPropTypesUsageByMemberExpression(context, node, utils, checkAsyncSafeLifeCycles)) {
markPropTypesAsUsed(node);
return;
}
const propVariable = propVariables.get(ast.unwrapTSAsExpression(node.object).name);
if (propVariable) {
markPropTypesAsUsed(node, propVariable);
}
},
ObjectPattern(node) {
// If the object pattern is a destructured props object in a lifecycle
// method -- mark it for used props.
if (isNodeALifeCycleMethod(node.parent.parent, checkAsyncSafeLifeCycles) && node.properties.length > 0) {
markPropTypesAsUsed(node.parent);
}
},
'Program:exit'() {
values(components.list())
.filter((component) => mustBeValidated(component))
.forEach((component) => {
handleCustomValidators(component);
});
},
};
};

View File

@@ -0,0 +1,38 @@
/**
* Search a particular variable in a list
* @param {Array} variables The variables list.
* @param {string} name The name of the variable to search.
* @returns {boolean} True if the variable was found, false if not.
*/
export function findVariable(variables: any[], name: string): boolean;
/**
* Find a variable by name in the current scope.
* @param {Object} context The current rule context.
* @param {ASTNode} node The node to check. Must be an Identifier node.
* @param {string} name Name of the variable to look for.
* @returns {ASTNode|null} Return null if the variable could not be found, ASTNode otherwise.
*/
export function findVariableByName(context: any, node: ASTNode, name: string): ASTNode | null;
/**
* Find and return a particular variable in a list
* @param {Array} variables The variables list.
* @param {string} name The name of the variable to search.
* @returns {Object} Variable if the variable was found, null if not.
*/
export function getVariable(variables: any[], name: string): any;
/**
* Searches for a variable in the given scope.
*
* @param {Object} context The current rule context.
* @param {ASTNode} node The node to start looking from.
* @param {string} name The name of the variable to search.
* @returns {Object | undefined} Variable if the variable was found, undefined if not.
*/
export function getVariableFromContext(context: any, node: ASTNode, name: string): any | undefined;
/**
* Returns the latest definition of the variable.
* @param {Object} variable
* @returns {Object | undefined} The latest variable definition or undefined.
*/
export function getLatestVariableDefinition(variable: any): any | undefined;
//# sourceMappingURL=variable.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"variable.d.ts","sourceRoot":"","sources":["variable.js"],"names":[],"mappings":"AASA;;;;;GAKG;AACH,qDAHW,MAAM,GACJ,OAAO,CAInB;AA0CD;;;;;;GAMG;AACH,uDAJW,OAAO,QACN,MAAM,GACL,OAAO,GAAC,IAAI,CAkBxB;AA/DD;;;;;GAKG;AACH,oDAHW,MAAM,OAKhB;AAED;;;;;;;GAOG;AACH,2DAJW,OAAO,QACP,MAAM,GACJ,MAAS,SAAS,CAsB9B;AA2BD;;;;GAIG;AACH,4DAFa,MAAS,SAAS,CAI9B"}

100
node_modules/eslint-plugin-react/lib/util/variable.js generated vendored Normal file
View File

@@ -0,0 +1,100 @@
/**
* @fileoverview Utility functions for React components detection
* @author Yannick Croissant
*/
'use strict';
const getScope = require('./eslint').getScope;
/**
* Search a particular variable in a list
* @param {Array} variables The variables list.
* @param {string} name The name of the variable to search.
* @returns {boolean} True if the variable was found, false if not.
*/
function findVariable(variables, name) {
return variables.some((variable) => variable.name === name);
}
/**
* Find and return a particular variable in a list
* @param {Array} variables The variables list.
* @param {string} name The name of the variable to search.
* @returns {Object} Variable if the variable was found, null if not.
*/
function getVariable(variables, name) {
return variables.find((variable) => variable.name === name);
}
/**
* Searches for a variable in the given scope.
*
* @param {Object} context The current rule context.
* @param {ASTNode} node The node to start looking from.
* @param {string} name The name of the variable to search.
* @returns {Object | undefined} Variable if the variable was found, undefined if not.
*/
function getVariableFromContext(context, node, name) {
let scope = getScope(context, node);
while (scope) {
let variable = getVariable(scope.variables, name);
if (!variable && scope.childScopes.length) {
variable = getVariable(scope.childScopes[0].variables, name);
if (!variable && scope.childScopes[0].childScopes.length) {
variable = getVariable(scope.childScopes[0].childScopes[0].variables, name);
}
}
if (variable) {
return variable;
}
scope = scope.upper;
}
return undefined;
}
/**
* Find a variable by name in the current scope.
* @param {Object} context The current rule context.
* @param {ASTNode} node The node to check. Must be an Identifier node.
* @param {string} name Name of the variable to look for.
* @returns {ASTNode|null} Return null if the variable could not be found, ASTNode otherwise.
*/
function findVariableByName(context, node, name) {
const variable = getVariableFromContext(context, node, name);
if (!variable || !variable.defs[0] || !variable.defs[0].node) {
return null;
}
if (variable.defs[0].node.type === 'TypeAlias') {
return variable.defs[0].node.right;
}
if (variable.defs[0].type === 'ImportBinding') {
return variable.defs[0].node;
}
return variable.defs[0].node.init;
}
/**
* Returns the latest definition of the variable.
* @param {Object} variable
* @returns {Object | undefined} The latest variable definition or undefined.
*/
function getLatestVariableDefinition(variable) {
return variable.defs[variable.defs.length - 1];
}
module.exports = {
findVariable,
findVariableByName,
getVariable,
getVariableFromContext,
getLatestVariableDefinition,
};

View File

@@ -0,0 +1,6 @@
export function testReactVersion(context: any, semverRange: any): boolean;
export function testFlowVersion(context: any, semverRange: any): boolean;
export function resetWarningFlag(): void;
export function resetDetectedVersion(): void;
export function resetDefaultVersion(): void;
//# sourceMappingURL=version.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["version.js"],"names":[],"mappings":"AAsLA,0EAEC;AAED,yEAEC;AA1KD,yCAEC;AAID,6CAEC;AA6BD,4CAEC"}

197
node_modules/eslint-plugin-react/lib/util/version.js generated vendored Normal file
View File

@@ -0,0 +1,197 @@
/**
* @fileoverview Utility functions for React and Flow version configuration
* @author Yannick Croissant
*/
'use strict';
const fs = require('fs');
const path = require('path');
const resolve = require('resolve');
const semver = require('semver');
const error = require('./error');
const ULTIMATE_LATEST_SEMVER = '999.999.999';
let warnedForMissingVersion = false;
function resetWarningFlag() {
warnedForMissingVersion = false;
}
let cachedDetectedReactVersion;
function resetDetectedVersion() {
cachedDetectedReactVersion = undefined;
}
function resolveBasedir(contextOrFilename) {
if (contextOrFilename) {
const filename = typeof contextOrFilename === 'string' ? contextOrFilename : contextOrFilename.getFilename();
const dirname = path.dirname(filename);
try {
if (fs.statSync(filename).isFile()) {
// dirname must be dir here
return dirname;
}
} catch (err) {
// https://github.com/eslint/eslint/issues/11989
if (err.code === 'ENOTDIR') {
// virtual filename could be recursive
return resolveBasedir(dirname);
}
}
}
return process.cwd();
}
function convertConfVerToSemver(confVer) {
const fullSemverString = /^[0-9]+\.[0-9]+$/.test(confVer) ? `${confVer}.0` : confVer;
return semver.coerce(fullSemverString.split('.').map((part) => Number(part)).join('.'));
}
let defaultVersion = ULTIMATE_LATEST_SEMVER;
function resetDefaultVersion() {
defaultVersion = ULTIMATE_LATEST_SEMVER;
}
function readDefaultReactVersionFromContext(context) {
// .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
if (context.settings && context.settings.react && context.settings.react.defaultVersion) {
let settingsDefaultVersion = context.settings.react.defaultVersion;
if (typeof settingsDefaultVersion !== 'string') {
error('Warning: default React version specified in eslint-pluigin-react-settings must be a string; '
+ `got "${typeof settingsDefaultVersion}"`);
}
settingsDefaultVersion = String(settingsDefaultVersion);
const result = convertConfVerToSemver(settingsDefaultVersion);
if (result) {
defaultVersion = result.version;
} else {
error(`Warning: React version specified in eslint-plugin-react-settings must be a valid semver version, or "detect"; got “${settingsDefaultVersion}”. Falling back to latest version as default.`);
}
} else {
defaultVersion = ULTIMATE_LATEST_SEMVER;
}
}
// TODO, semver-major: remove context fallback
function detectReactVersion(context) {
if (cachedDetectedReactVersion) {
return cachedDetectedReactVersion;
}
const basedir = resolveBasedir(context);
try {
const reactPath = resolve.sync('react', { basedir });
const react = require(reactPath); // eslint-disable-line global-require, import/no-dynamic-require
cachedDetectedReactVersion = react.version;
return cachedDetectedReactVersion;
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
if (!warnedForMissingVersion) {
let sentence2 = 'Assuming latest React version for linting.';
if (defaultVersion !== ULTIMATE_LATEST_SEMVER) {
sentence2 = `Assuming default React version for linting: "${defaultVersion}".`;
}
error(`Warning: React version was set to "detect" in eslint-plugin-react settings, but the "react" package is not installed. ${sentence2}`);
warnedForMissingVersion = true;
}
cachedDetectedReactVersion = defaultVersion;
return cachedDetectedReactVersion;
}
throw e;
}
}
function getReactVersionFromContext(context) {
readDefaultReactVersionFromContext(context);
let confVer = defaultVersion;
// .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
if (context.settings && context.settings.react && context.settings.react.version) {
let settingsVersion = context.settings.react.version;
if (settingsVersion === 'detect') {
settingsVersion = detectReactVersion(context);
}
if (typeof settingsVersion !== 'string') {
error('Warning: React version specified in eslint-plugin-react-settings must be a string; '
+ `got “${typeof settingsVersion}`);
}
confVer = String(settingsVersion);
} else if (!warnedForMissingVersion) {
error('Warning: React version not specified in eslint-plugin-react settings. '
+ 'See https://github.com/jsx-eslint/eslint-plugin-react#configuration .');
warnedForMissingVersion = true;
}
const result = convertConfVerToSemver(confVer);
if (!result) {
error(`Warning: React version specified in eslint-plugin-react-settings must be a valid semver version, or "detect"; got “${confVer}`);
}
return result ? result.version : defaultVersion;
}
// TODO, semver-major: remove context fallback
function detectFlowVersion(context) {
const basedir = resolveBasedir(context);
try {
const flowPackageJsonPath = resolve.sync('flow-bin/package.json', { basedir });
const flowPackageJson = require(flowPackageJsonPath); // eslint-disable-line global-require, import/no-dynamic-require
return flowPackageJson.version;
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
error('Warning: Flow version was set to "detect" in eslint-plugin-react settings, '
+ 'but the "flow-bin" package is not installed. Assuming latest Flow version for linting.');
return ULTIMATE_LATEST_SEMVER;
}
throw e;
}
}
function getFlowVersionFromContext(context) {
let confVer = defaultVersion;
// .eslintrc shared settings (https://eslint.org/docs/user-guide/configuring#adding-shared-settings)
if (context.settings.react && context.settings.react.flowVersion) {
let flowVersion = context.settings.react.flowVersion;
if (flowVersion === 'detect') {
flowVersion = detectFlowVersion(context);
}
if (typeof flowVersion !== 'string') {
error('Warning: Flow version specified in eslint-plugin-react-settings must be a string; '
+ `got “${typeof flowVersion}`);
}
confVer = String(flowVersion);
} else {
throw 'Could not retrieve flowVersion from settings'; // eslint-disable-line no-throw-literal
}
const result = convertConfVerToSemver(confVer);
if (!result) {
error(`Warning: Flow version specified in eslint-plugin-react-settings must be a valid semver version, or "detect"; got “${confVer}`);
}
return result ? result.version : defaultVersion;
}
function test(semverRange, confVer) {
return semver.satisfies(confVer, semverRange);
}
function testReactVersion(context, semverRange) {
return test(semverRange, getReactVersionFromContext(context));
}
function testFlowVersion(context, semverRange) {
return test(semverRange, getFlowVersionFromContext(context));
}
module.exports = {
testReactVersion,
testFlowVersion,
resetWarningFlag,
resetDetectedVersion,
resetDefaultVersion,
};