@bigbinary/eslint-plugin-neeto 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +16 -13
  2. package/dist/index.js +2500 -834
  3. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,12 +1,13 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('path'), require('ramda')) :
3
- typeof define === 'function' && define.amd ? define(['path', 'ramda'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global["@bigbinary/eslint-plugin-neeto"] = factory(global.path, global.ramda));
5
- })(this, (function (path, ramda) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('path'), require('ramda'), require('fs')) :
3
+ typeof define === 'function' && define.amd ? define(['path', 'ramda', 'fs'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global["@bigbinary/eslint-plugin-neeto"] = factory(global.path$2, global.ramda, global.fs));
5
+ })(this, (function (path$2, ramda, fs) { 'use strict';
6
6
 
7
7
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
8
 
9
- var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
9
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path$2);
10
+ var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
10
11
 
11
12
  function _arrayWithHoles(arr) {
12
13
  if (Array.isArray(arr)) return arr;
@@ -78,175 +79,128 @@
78
79
  return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
79
80
  }, _typeof(obj);
80
81
  }
81
- var matches = ramda.curry(function (pattern, object) {
82
- var __parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : object;
83
-
84
- if (object === pattern) return true;
85
- if (typeof pattern === "function" && pattern(object, __parent)) return true;
86
- if (ramda.isNil(pattern) || ramda.isNil(object)) return false;
87
- if (_typeof(pattern) !== "object") return false;
88
- return Object.entries(pattern).every(function (_ref5) {
89
- var _ref6 = _slicedToArray(_ref5, 2),
90
- key = _ref6[0],
91
- value = _ref6[1];
92
-
93
- return matches(value, object[key], __parent);
94
- });
95
- });
96
-
97
- function _defineProperty(obj, key, value) {
98
- if (key in obj) {
99
- Object.defineProperty(obj, key, {
100
- value: value,
101
- enumerable: true,
102
- configurable: true,
103
- writable: true
104
- });
105
- } else {
106
- obj[key] = value;
107
- }
108
82
 
109
- return obj;
110
- }
83
+ /**
84
+ * @template {Function} T
85
+ * @param {T} func
86
+ * @returns {T}
87
+ */
111
88
 
112
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
89
+ var nullSafe = function nullSafe(func) {
90
+ return (// @ts-ignore
91
+ ramda.curryN(func.length, function () {
92
+ var _ref;
113
93
 
114
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
115
- ramda.curry(function (id, array) {
116
- return array.filter(function (item) {
117
- return item.id !== id;
118
- });
119
- });
120
- ramda.curry(function (id, array) {
121
- return array.find(function (item) {
122
- return item.id === id;
123
- });
124
- });
125
- ramda.curry(function (id, newItem, array) {
126
- return array.map(function (item) {
127
- return item.id === id ? newItem : item;
128
- });
129
- });
130
- ramda.curry(function (id, modifier, array) {
131
- return array.map(function (item) {
132
- return item.id === id ? modifier(item) : item;
133
- });
134
- });
135
- ramda.curry(function (pattern, array) {
136
- return array.find(matches(pattern));
137
- });
138
- ramda.curry(function (pattern, array) {
139
- return array.filter(ramda.complement(matches(pattern)));
140
- });
141
- ramda.curry(function (pattern, newItem, array) {
142
- return array.map(function (item) {
143
- return matches(pattern, item) ? newItem : item;
144
- });
145
- });
146
- ramda.curry(function (pattern, modifier, array) {
147
- return array.map(function (item) {
148
- return matches(pattern, item) ? modifier(item) : item;
149
- });
94
+ var dataArg = (_ref = func.length - 1, _ref < 0 || arguments.length <= _ref ? undefined : arguments[_ref]);
95
+ return ramda.isNil(dataArg) ? dataArg : func.apply(void 0, arguments);
96
+ })
97
+ );
98
+ };
99
+ var isNotEmpty$1 = /*#__PURE__*/ramda.complement(ramda.isEmpty);
100
+ var notEquals = /*#__PURE__*/ramda.curry(function (x, y) {
101
+ return x !== y;
150
102
  });
151
- ramda.curry(function (id, array) {
152
- return array.some(function (item) {
153
- return item.id === id;
103
+
104
+ var slugify = function slugify(string) {
105
+ return string.toString().toLowerCase().replace(/\s+/g, "-") // Replace spaces with -
106
+ .replace(/&/g, "-and-") // Replace & with 'and'
107
+ .replace(/[^\w-]+/g, "") // Remove all non-word characters
108
+ .replace(/--+/g, "-") // Replace multiple - with single -
109
+ .replace(/^-+/, "") // Trim - from start of text
110
+ .replace(/-+$/, "");
111
+ }; // Trim - from end of text
112
+
113
+ var humanize = function humanize(string) {
114
+ string = string.replace(/[_-]+/g, " ").replace(/\s{2,}/g, " ").replace(/([a-z\d])([A-Z])/g, "$1" + " " + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + " " + "$2").toLowerCase().trim();
115
+ string = string.charAt(0).toUpperCase() + string.slice(1);
116
+ return string;
117
+ };
118
+ var snakeToCamelCase = function snakeToCamelCase(string) {
119
+ return string.replace(/(_\w)/g, function (letter) {
120
+ return letter[1].toUpperCase();
154
121
  });
155
- });
156
- var existsBy$1 = ramda.curry(function (pattern, array) {
157
- return array.some(matches(pattern));
158
- });
159
- ramda.curry(function (pattern, array) {
160
- return ramda.findLast(matches(pattern), array);
161
- });
162
- ramda.curry(function (id, array) {
163
- return array.findIndex(function (item) {
164
- return item.id === id;
122
+ };
123
+ var camelToSnakeCase = function camelToSnakeCase(string) {
124
+ return string.replace(/[A-Z]/g, function (letter) {
125
+ return "_".concat(letter.toLowerCase());
165
126
  });
166
- });
167
- ramda.curry(function (pattern, array) {
168
- return array.findIndex(matches(pattern));
169
- });
170
- ramda.curry(function (pattern, array) {
171
- return ramda.findLastIndex(matches(pattern), array);
172
- });
173
- ramda.curry(function (pattern, array) {
174
- return array.filter(matches(pattern));
175
- });
176
- ramda.curry(function (pattern, array) {
177
- return ramda.count(matches(pattern), array);
178
- });
179
- ramda.curry(function (keyMap, objectArray) {
180
- return objectArray.map(function (object) {
181
- var shallowCopy = _objectSpread({}, object);
182
-
183
- for (var source in keyMap) {
184
- shallowCopy[keyMap[source]] = object[source];
185
- }
127
+ };
128
+ var capitalize$1 = function capitalize(string) {
129
+ return string.charAt(0).toUpperCase() + string.slice(1);
130
+ };
131
+ nullSafe(slugify);
132
+ nullSafe(humanize);
133
+ nullSafe(snakeToCamelCase);
134
+ nullSafe(camelToSnakeCase);
135
+ nullSafe(capitalize$1);
186
136
 
187
- return shallowCopy;
188
- });
189
- });
190
- ramda.curry(function (keyMap, objectArray) {
191
- return objectArray.map(function (object) {
192
- var shallowCopy = _objectSpread({}, object);
137
+ var matchesImpl = function matchesImpl(pattern, object) {
138
+ var __parent = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : object;
193
139
 
194
- for (var source in keyMap) {
195
- shallowCopy[keyMap[source]] = object[source];
196
- delete shallowCopy[source];
197
- }
140
+ if (object === pattern) return true;
141
+ if (typeof pattern === "function" && pattern(object, __parent)) return true;
142
+ if (ramda.isNil(pattern) || ramda.isNil(object)) return false;
143
+ if (_typeof(pattern) !== "object") return false;
144
+ return Object.entries(pattern).every(function (_ref) {
145
+ var _ref2 = _slicedToArray(_ref, 2),
146
+ key = _ref2[0],
147
+ value = _ref2[1];
198
148
 
199
- return shallowCopy;
149
+ return matchesImpl(value, object[key], __parent);
200
150
  });
151
+ };
152
+ var matches = /*#__PURE__*/ramda.curry(function (pattern, object) {
153
+ return matchesImpl(pattern, object);
201
154
  });
202
- ramda.curry(function (keyMap, objectArray) {
203
- var copyKeysSingleObject = function copyKeysSingleObject(object, keyMap) {
204
- var root = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : object;
205
- return _objectSpread(_objectSpread({}, object), ramda.fromPairs(ramda.toPairs(keyMap).map(function (_ref) {
206
- var _ref2 = _slicedToArray(_ref, 2),
207
- destination = _ref2[0],
208
- source = _ref2[1];
209
-
210
- if (typeof source === "function") {
211
- return [destination, source(object[destination], root)];
212
- } else if (Array.isArray(source)) {
213
- return [destination, ramda.path(source, root)];
214
- } else if (_typeof(source) === "object") {
215
- return [destination, copyKeysSingleObject(object[destination], source, root)];
216
- }
155
+ var filterNonNull = function filterNonNull(object) {
156
+ return Object.fromEntries(Object.entries(object).filter(function (_ref5) {
157
+ var _ref6 = _slicedToArray(_ref5, 2),
158
+ v = _ref6[1];
217
159
 
218
- return [destination, object[source]];
219
- })));
220
- };
160
+ return !ramda.isNil(v);
161
+ }).map(function (_ref7) {
162
+ var _ref8 = _slicedToArray(_ref7, 2),
163
+ k = _ref8[0],
164
+ v = _ref8[1];
221
165
 
222
- return objectArray.map(function (object) {
223
- return copyKeysSingleObject(object, keyMap);
224
- });
166
+ return [k, _typeof(v) === "object" && !Array.isArray(v) ? filterNonNull(v) : v];
167
+ }));
168
+ };
169
+ nullSafe(filterNonNull);
170
+ var existsBy$1 = /*#__PURE__*/ramda.curry(function (pattern, array) {
171
+ return array.some(matches(pattern));
225
172
  });
226
- ramda.complement(ramda.isNil);
227
- var isNotEmpty$1 = ramda.complement(ramda.isEmpty);
228
- var notEquals = ramda.curry(function (x, y) {
229
- return x !== y;
173
+ var filterBy$1 = /*#__PURE__*/ramda.curry(function (pattern, array) {
174
+ return array.filter(matches(pattern));
230
175
  });
231
- var isNot$1 = notEquals;
232
- ramda.complement(ramda.equals);
233
176
 
234
177
  const APIS_DIRECTORY = "app/javascript/src/apis";
235
178
  const ROUTES_FILE_PATH = "app/javascript/src/common/routes.js";
236
- const BLACKLISTED_PACKAGES = ["moment", "bootstrap", "blueprint", "react-spinners", "react-table", "remixicon", "mjml", "react-select", "antd"];
179
+ const BLACKLISTED_PACKAGES = ["moment", "bootstrap", "blueprint", "react-spinners", "react-table", "remixicon", "mjml", "react-select", "antd", "@bigbinary/neeto-utils"];
237
180
  const TYPES = {
238
181
  ARRAY_EXPRESSION: "ArrayExpression",
239
182
  ARROW_FUNCTION_EXPRESSION: "ArrowFunctionExpression",
240
183
  ASSIGNMENT_PATTERN: "AssignmentPattern",
241
184
  AWAIT_EXPRESSION: "AwaitExpression",
242
185
  BINARY_EXPRESSION: "BinaryExpression",
186
+ BLOCK_STATEMENT: "BlockStatement",
187
+ BREAK_STATEMENT: "BreakStatement",
243
188
  CALL_EXPRESSION: "CallExpression",
189
+ CHAIN_EXPRESSION: "ChainExpression",
190
+ CONDITIONAL_EXPRESSION: "ConditionalExpression",
244
191
  EXPORT_NAMED_DECLARATION: "ExportNamedDeclaration",
245
192
  EXPORT_DEFAULT_DECLARATION: "ExportDefaultDeclaration",
193
+ FUNCTION_DECLARATION: "FunctionDeclaration",
194
+ FUNCTION_EXPRESSION: "FunctionExpression",
246
195
  IDENTIFIER: "Identifier",
247
196
  IF_STATEMENT: "IfStatement",
248
197
  IMPORT_DECLARATION: "ImportDeclaration",
249
198
  IMPORT_DEFAULT_SPECIFIER: "ImportDefaultSpecifier",
199
+ IMPORT_SPECIFIER: "ImportSpecifier",
200
+ JSX_ATTRIBUTE: "JSXAttribute",
201
+ JSX_ELEMENT: "JSXElement",
202
+ JSX_EXPRESSION_CONTAINER: "JSXExpressionContainer",
203
+ JSX_IDENTIFIER: "JSXIdentifier",
250
204
  LITERAL: "Literal",
251
205
  LOGICAL_EXPRESSION: "LogicalExpression",
252
206
  MEMBER_EXPRESSION: "MemberExpression",
@@ -254,33 +208,93 @@
254
208
  OBJECT_PATTERN: "ObjectPattern",
255
209
  PROGRAM: "Program",
256
210
  PROPERTY: "Property",
211
+ RETURN_STATEMENT: "ReturnStatement",
257
212
  SPREAD_ELEMENT: "SpreadElement",
213
+ TEMPLATE_ELEMENT: "TemplateElement",
258
214
  TEMPLATE_LITERAL: "TemplateLiteral",
259
215
  UNARY_EXPRESSION: "UnaryExpression",
260
216
  VARIABLE_DECLARATION: "VariableDeclaration",
261
217
  VARIABLE_DECLARATOR: "VariableDeclarator",
262
- WHILE_STATEMENT: "WhileStatement",
263
- JSX_ATTRIBUTE: "JSXAttribute",
264
- JSX_ELEMENT: "JSXElement",
265
- JSX_EXPRESSION_CONTAINER: "JSXExpressionContainer",
266
- JSX_IDENTIFIER: "JSXIdentifier"
218
+ WHILE_STATEMENT: "WhileStatement"
267
219
  };
268
220
  const IMPORT_DECLARATION = {
269
- type: "ImportDeclaration",
221
+ type: TYPES.IMPORT_DECLARATION,
270
222
  source: {
271
- type: "Literal"
223
+ type: TYPES.LITERAL
272
224
  },
273
225
  specifiers: [{
274
- type: "ImportSpecifier"
226
+ type: TYPES.IMPORT_SPECIFIER
275
227
  }]
276
228
  };
277
229
 
230
+ /**
231
+ * Returns a list of nodes that matches the pattern
232
+ * somewhere deep inside the given object-tree by
233
+ * partial object matching.
234
+ *
235
+ * @param {Object} obj the object tree to check
236
+ * @param {Object} pattern the pattern to match partially
237
+ * @param {Array} res list of nodes that matches the pattern
238
+ */
239
+
240
+ const findMatchingNodesDeep = (obj, pattern, res = []) => {
241
+ if (typeof obj !== "object" || ramda.isNil(obj)) return res;
242
+ if (matches(pattern, obj)) return ramda.append(obj, res);
243
+ return Object.entries(obj).reduce((acc, [key, value]) => {
244
+ if (key === "parent") return acc;
245
+ return findMatchingNodesDeep(value, pattern, acc);
246
+ }, res);
247
+ };
248
+ /**
249
+ * Checks if any of the given pattern matches the object.
250
+ * @param {Object} obj The object tree to check.
251
+ * @param {Object[]} list The list of patterns to compare against.
252
+ * also @see matches
253
+ */
254
+
255
+ const matchesAny = ramda.curry((list, obj) => list.some(matches(ramda.__, obj)));
256
+ /**
257
+ * Checks if the given pattern exists somewhere deep inside
258
+ * the given object-tree by partial object matching.
259
+ *
260
+ * @param {Object} pattern the pattern to match partially
261
+ * @param {Object} obj the object tree to check
262
+ */
263
+
264
+ const patternExistsDeep = ramda.curry((pattern, obj) => {
265
+ if (typeof obj !== "object" || ramda.isNil(obj)) return false;
266
+ if (matches(pattern, obj)) return true;
267
+ return Object.entries(obj).some(([key, value]) => {
268
+ if (key === "parent") return false;
269
+ return patternExistsDeep(pattern, value);
270
+ });
271
+ });
272
+
273
+ const addFunctionImport = (context, fixer, functions, importPattern) => {
274
+ const root = context.getAncestors()[0];
275
+ const packageImport = root.body.find(matches(importPattern));
276
+
277
+ if (packageImport) {
278
+ const extraImports = functions.filter(func => !packageImport.specifiers.some(ramda.pathEq(["imported", "name"], func)));
279
+ if (ramda.isEmpty(extraImports)) return undefined;
280
+ return fixer.insertTextBefore(packageImport.specifiers[0], `${extraImports.join(", ")}, `);
281
+ }
282
+
283
+ const packageName = importPattern.source.value;
284
+ return fixer.insertTextBefore(root.body[0], `import { ${functions.join(", ")} } from "${packageName}";\n`);
285
+ };
286
+
287
+ const addNullSafeImport = (context, fixer) => {
288
+ const importPattern = ramda.assocPath(["source", "value"], "neetocommons/pure", IMPORT_DECLARATION);
289
+ return addFunctionImport(context, fixer, ["nullSafe"], importPattern);
290
+ };
278
291
  /**
279
292
  * @param {Object} context - ESLint context
280
293
  * @param {Object} node - AST node
281
294
  * @returns the source code corresponding to the supplied node.
282
295
  */
283
296
 
297
+
284
298
  const getCode$1 = (context, node) => context.getSourceCode().text.substr(node.range[0], node.range[1] - node.range[0]);
285
299
  /**
286
300
  * Checks if the specified package is imported or not
@@ -324,42 +338,57 @@
324
338
  */
325
339
 
326
340
  const isPackageImported = (context, node, packageName) => getPackagesAndAliases(context, [packageName]).includes(node.source.value);
327
- const nodeReplacerWithImports = importPattern => {
328
- const addFunctionImport = (context, fixer, functions) => {
329
- const root = context.getAncestors()[0];
330
- const packageImport = root.body.find(node => matches(importPattern, node));
331
-
332
- if (packageImport) {
333
- const extraImports = functions.filter(func => !packageImport.specifiers.some(ramda.pathEq(["imported", "name"], func)));
334
- if (ramda.isEmpty(extraImports)) return undefined;
335
- return fixer.insertTextBefore(packageImport.specifiers[0], `${extraImports.join(", ")}, `);
341
+ const nodeReplacerWithImports = importPattern => ({
342
+ replaceNode: ({
343
+ context,
344
+ node,
345
+ fix,
346
+ functions,
347
+ importNullSafe = false
348
+ }) => function* (fixer) {
349
+ const imports = addFunctionImport(context, fixer, Array.isArray(functions) ? functions : [functions], importPattern);
350
+ if (imports) yield imports;
351
+
352
+ if (importNullSafe) {
353
+ const nullSafeImport = addNullSafeImport(context, fixer);
354
+ if (nullSafeImport) yield nullSafeImport;
336
355
  }
337
356
 
338
- const packageName = importPattern.source.value;
339
- return fixer.insertTextBefore(root.body[0], `import { ${functions.join(", ")} } from "${packageName}";\n`);
340
- };
357
+ yield fixer.replaceText(node, fix);
358
+ }
359
+ });
360
+ const arrayFuncParam = root => root.arguments[0].params[0]; // find all file level imports from any node in the AST
341
361
 
342
- return {
343
- replaceNode: ({
344
- context,
345
- node,
346
- fix,
347
- functions
348
- }) => function* (fixer) {
349
- const imports = addFunctionImport(context, fixer, Array.isArray(functions) ? functions : [functions]);
350
- if (imports) yield imports;
351
- yield fixer.replaceText(node, fix);
352
- }
353
- };
362
+ /** @type {(any) => any[]} */
363
+
364
+ const getAllImports = node => {
365
+ let topNode = node;
366
+
367
+ while (!matches({
368
+ type: TYPES.PROGRAM
369
+ }, topNode)) {
370
+ topNode = topNode.parent;
371
+ }
372
+
373
+ return filterBy$1({
374
+ type: TYPES.IMPORT_DECLARATION
375
+ }, topNode.body);
354
376
  };
355
- const arrayFuncParam = root => root.arguments[0].params[0];
377
+ const isOptionalChainingPresent = node => patternExistsDeep({
378
+ type: TYPES.MEMBER_EXPRESSION,
379
+ optional: true
380
+ }, node);
381
+ const optionalChainingOptimizedName = (funcName, node) => isOptionalChainingPresent(node) ? `_${funcName}` : funcName;
356
382
 
357
383
  const ARGUMENT_LIMIT = 3;
358
384
  const API_ACTIONS_ARGUMENT_LIMIT = 2;
359
385
  const FIXABLE_PARAMETER_TYPES = [TYPES.IDENTIFIER, TYPES.ASSIGNMENT_PATTERN];
360
386
 
387
+ const addInJsconfig = aliasName => `Add path for "${aliasName}" in jsconfig.json. Refer https://bit.ly/webpack-jsconfig-rule for more details.`;
361
388
  const canBeReplacedWith = fix => `Can be replaced with: ${fix}`;
362
389
  const disallowUse = packageName => `Do not use the package ${packageName}`;
390
+ const exportedObjectShouldBe = caseStyle => `Exported object should be in ${caseStyle}`;
391
+ const filenameShouldBe = caseStyle => `Filename should be in ${caseStyle}`;
363
392
  const moveToConstantsJs = constantName => `Move the constant ${constantName} to a constants.js file.`;
364
393
  const renameFile = filename => `Rename this file to ${filename}`;
365
394
  const replaceWith = fix => `Replace this with: ${fix}`;
@@ -367,9 +396,9 @@
367
396
  key,
368
397
  fileName
369
398
  }) => `Unable to resolve localized string '${key}' in ${fileName}`;
370
- const useConstantCaseFor = constantName => `Use constant-case for naming the constant - ${constantName}.`;
371
399
  const API_CONNECTOR_SHOULD_USE_DEFAULT_EXPORT_MESSAGE = "API Connector should be exported using the default export method";
372
400
  const COMBINE_MULTIPLE_INDEPENDENT_AWAITS_MESSAGE = "Combine independent awaits to a single `Promise.all` call.";
401
+ const EXPORTED_OBJECT_AND_FILENAME_SHOULD_MATCH_MESSAGE = `Exported object and filename should match.`;
373
402
  const GLOBALPROPS_NO_ASSIGNMENT_MESSAGE = "globalProps should not be assigned to other variables";
374
403
  const NESTED_GLOBALPROPS_NO_ASSIGNMENT_MESSAGE = "Nested properties of globalProps should not be assigned to other variables";
375
404
  const NO_AXIOS_IMPORT_OUTSIDE_APIS_MESSAGE = "Do not use axios outside `app/javascript/src/apis`";
@@ -386,11 +415,17 @@
386
415
  const ROUTES_HAS_ALREADY_BEEN_DECLARED = "Identifier `routes` has already been declared";
387
416
  const ROUTES_CONSTANT_SHOULD_BE_DECLARED = "A constant object named `routes` should be declared inside routes.js";
388
417
  const ROUTES_SHOULD_USE_DEFAULT_EXPORT = "`routes` should be exported using the default export method.";
418
+ const USE_ARRAY_METHODS = "Use array methods (forEach, map, filter, reduce, etc) instead of 'for' loop. Refer 'Advanced Array Methods' section in https://bit.ly/learn-advanced-javascript";
389
419
  const USE_AXIOS_CONFIG_FOR_PASSING_QUERY_PARAMETERS_MESSAGE = "Use 'params attribute in axios configuration' to pass query parameters.";
390
420
  const USE_LINK_FOR_NAVIGATION = "Use Link or NavLink component from 'react-router-dom' for click-navigation instead of onClick handler";
391
421
  const USE_ANCHOR_FOR_NAVIGATION = "Use Anchor element (<a>) for click-navigation instead of onClick handler";
392
422
  const USE_BUTTON_TO_FOR_LINK_NAVIGATION = "Use `to` prop of Button (<Button to='path'>) for click-navigation instead of onClick handler";
393
423
  const USE_BUTTON_TO_FOR_ANCHOR_NAVIGATION = "Use `href` prop of Button (<Button href='path'>) for click-navigation instead of onClick handler";
424
+ const USE_NEETOUI_BORDER_COLOR = "Use neetoUI border color. Refer https://bit.ly/border-color-page for more details.";
425
+ const USE_NEETOUI_BORDER_RADIUS = "Use neetoUI border radius. Refer https://bit.ly/border-radius-page for more details.";
426
+ const USE_NEETOUI_BOX_SHADOW = "Use neetoUI border shadow. Refer https://bit.ly/box-shadows-page for more details.";
427
+ const USE_NEETOUI_TEXT_COLOR = "Use neetoUI text color. Refer https://bit.ly/text-color-page for more details.";
428
+ const DONT_USE_ZUSTAND_STORE_WITHOUT_SELECTOR = "Don't use zustand store hook without a selector function. It will impact the performance";
394
429
 
395
430
  const toCamelCase = text => {
396
431
  const capitalized = text.split(/[^0-9a-z]/i).map(part => `${part[0].toUpperCase()}${part.slice(1)}`).join("");
@@ -452,49 +487,6 @@
452
487
  })
453
488
  };
454
489
 
455
- /**
456
- * Returns a list of nodes that matches the pattern
457
- * somewhere deep inside the given object-tree by
458
- * partial object matching.
459
- *
460
- * @param {Object} obj the object tree to check
461
- * @param {Object} pattern the pattern to match partially
462
- * @param {Array} res list of nodes that matches the pattern
463
- */
464
-
465
- const findMatchingNodesDeep = (obj, pattern, res = []) => {
466
- if (typeof obj !== "object" || ramda.isNil(obj)) return res;
467
- if (matches(pattern, obj)) return ramda.append(obj, res);
468
- return Object.entries(obj).reduce((acc, [key, value]) => {
469
- if (key === "parent") return acc;
470
- return findMatchingNodesDeep(value, pattern, acc);
471
- }, res);
472
- };
473
- /**
474
- * Checks if any of the given pattern matches the object.
475
- * @param {Object} obj The object tree to check.
476
- * @param {Object[]} list The list of patterns to compare against.
477
- * also @see matches
478
- */
479
-
480
- const matchesAny = ramda.curry((list, obj) => list.some(matches(ramda.__, obj)));
481
- /**
482
- * Checks if the given pattern exists somewhere deep inside
483
- * the given object-tree by partial object matching.
484
- *
485
- * @param {Object} obj the object tree to check
486
- * @param {Object} pattern the pattern to match partially
487
- */
488
-
489
- const patternExistsDeep = ramda.curry((pattern, obj) => {
490
- if (typeof obj !== "object" || ramda.isNil(obj)) return false;
491
- if (matches(pattern, obj)) return true;
492
- return Object.entries(obj).some(([key, value]) => {
493
- if (key === "parent") return false;
494
- return patternExistsDeep(pattern, value);
495
- });
496
- });
497
-
498
490
  const AWAIT_DECLARATION_PATTERN = {
499
491
  type: TYPES.VARIABLE_DECLARATOR,
500
492
  init: {
@@ -958,20 +950,20 @@
958
950
 
959
951
 
960
952
  const HISTORY_PUSH_PATTERN = {
961
- type: "CallExpression",
953
+ type: TYPES.CALL_EXPRESSION,
962
954
  callee: {
963
- type: "MemberExpression",
955
+ type: TYPES.MEMBER_EXPRESSION,
964
956
  object: {
965
- type: "Identifier",
957
+ type: TYPES.IDENTIFIER,
966
958
  name: "history"
967
959
  },
968
960
  property: {
969
- type: "Identifier",
961
+ type: TYPES.IDENTIFIER,
970
962
  name: "push"
971
963
  }
972
964
  },
973
965
  arguments: args => args.length === 1 && matches([{
974
- type: isNot$1("ObjectExpression")
966
+ type: notEquals(TYPES.OBJECT_EXPRESSION)
975
967
  }], args)
976
968
  };
977
969
  const WINDOW_LOCATION_PATTERNS = [// window.location.href = "/path"
@@ -979,22 +971,22 @@
979
971
  type: "AssignmentExpression",
980
972
  operator: "=",
981
973
  left: {
982
- type: "MemberExpression",
974
+ type: TYPES.MEMBER_EXPRESSION,
983
975
  object: {
984
- type: "MemberExpression",
976
+ type: TYPES.MEMBER_EXPRESSION,
985
977
  object: {
986
- type: "Identifier",
978
+ type: TYPES.IDENTIFIER,
987
979
  name: "window"
988
980
  },
989
981
  property: {
990
- type: "Identifier",
982
+ type: TYPES.IDENTIFIER,
991
983
  name: "location"
992
984
  },
993
985
  computed: false,
994
986
  optional: false
995
987
  },
996
988
  property: {
997
- type: "Identifier",
989
+ type: TYPES.IDENTIFIER,
998
990
  name: "href"
999
991
  },
1000
992
  computed: false,
@@ -1002,24 +994,24 @@
1002
994
  }
1003
995
  }, // window.location.assign("/path")
1004
996
  {
1005
- type: "CallExpression",
997
+ type: TYPES.CALL_EXPRESSION,
1006
998
  callee: {
1007
- type: "MemberExpression",
999
+ type: TYPES.MEMBER_EXPRESSION,
1008
1000
  object: {
1009
- type: "MemberExpression",
1001
+ type: TYPES.MEMBER_EXPRESSION,
1010
1002
  object: {
1011
- type: "Identifier",
1003
+ type: TYPES.IDENTIFIER,
1012
1004
  name: "window"
1013
1005
  },
1014
1006
  property: {
1015
- type: "Identifier",
1007
+ type: TYPES.IDENTIFIER,
1016
1008
  name: "location"
1017
1009
  },
1018
1010
  computed: false,
1019
1011
  optional: false
1020
1012
  },
1021
1013
  property: {
1022
- type: "Identifier",
1014
+ type: TYPES.IDENTIFIER,
1023
1015
  name: "assign"
1024
1016
  },
1025
1017
  computed: false,
@@ -1029,15 +1021,15 @@
1029
1021
  }]; // onClick={() => <expression>}
1030
1022
 
1031
1023
  const ONCLICK_ATTRIBUTE_PATTERN = {
1032
- type: "JSXAttribute",
1024
+ type: TYPES.JSX_ATTRIBUTE,
1033
1025
  name: {
1034
- type: "JSXIdentifier",
1026
+ type: TYPES.JSX_IDENTIFIER,
1035
1027
  name: "onClick"
1036
1028
  },
1037
1029
  value: {
1038
- type: "JSXExpressionContainer",
1030
+ type: TYPES.JSX_EXPRESSION_CONTAINER,
1039
1031
  expression: {
1040
- type: "ArrowFunctionExpression",
1032
+ type: TYPES.ARROW_FUNCTION_EXPRESSION,
1041
1033
  params: ramda.isEmpty,
1042
1034
  generator: false,
1043
1035
  async: false
@@ -1047,7 +1039,7 @@
1047
1039
 
1048
1040
  const LINK_REPLACEABLE_PATTERN = {
1049
1041
  name: {
1050
- type: "JSXIdentifier",
1042
+ type: TYPES.JSX_IDENTIFIER,
1051
1043
  name: ramda.includes(ramda.__, ["Button", "button", "span", "div", "a"])
1052
1044
  },
1053
1045
  attributes: ramda.any(matches(ramda.assocPath(["value", "expression", "body"], matchesAny([HISTORY_PUSH_PATTERN, wrappedInBlockPattern(HISTORY_PUSH_PATTERN)]), ONCLICK_ATTRIBUTE_PATTERN)))
@@ -1055,7 +1047,7 @@
1055
1047
 
1056
1048
  const ANCHOR_REPLACEABLE_PATTERN = {
1057
1049
  name: {
1058
- type: "JSXIdentifier",
1050
+ type: TYPES.JSX_IDENTIFIER,
1059
1051
  name: ramda.includes(ramda.__, ["Button", "button", "span", "div"])
1060
1052
  },
1061
1053
  attributes: ramda.any(matches(ramda.assocPath(["value", "expression", "body"], matchesAny([WINDOW_LOCATION_PATTERNS, WINDOW_LOCATION_PATTERNS.map(wrappedInBlockPattern)].flat()), ONCLICK_ATTRIBUTE_PATTERN)))
@@ -1069,7 +1061,7 @@
1069
1061
  }) => fixer => {
1070
1062
  const onClickAttributeNode = node.attributes.find(matches(ONCLICK_ATTRIBUTE_PATTERN));
1071
1063
  const pathNode = findPathNode(onClickAttributeNode);
1072
- const navigateAttr = pathNode.type === "Literal" ? `${attribute}="${pathNode.value}"` : `${attribute}={${getCode$1(context, pathNode)}}`;
1064
+ const navigateAttr = pathNode.type === TYPES.LITERAL ? `${attribute}="${pathNode.value}"` : `${attribute}={${getCode$1(context, pathNode)}}`;
1073
1065
  return fixer.replaceText(onClickAttributeNode, navigateAttr);
1074
1066
  };
1075
1067
 
@@ -1129,7 +1121,15 @@
1129
1121
  };
1130
1122
 
1131
1123
  const CONSTANT_CASE_PATTERN = /^[A-Z0-9_]*$/;
1132
- const CONSTANTS_FILES = [/.*constants.js$/i, /app\/javascript\/src\/common\/urls.js$/];
1124
+ const CONSTANTS_FILES = [/.*constants.(js|jsx)$/i, /app\/javascript\/src\/common\/urls.js$/];
1125
+ const CONSTANT_DECALARATION_PATTERN = {
1126
+ kind: "const",
1127
+ declarations: [{
1128
+ id: {
1129
+ name: name => CONSTANT_CASE_PATTERN.test(name)
1130
+ }
1131
+ }]
1132
+ };
1133
1133
 
1134
1134
  const isConstantsFile = context => CONSTANTS_FILES.some(filePath => filePath.test(path__default["default"].resolve(context.getFilename())));
1135
1135
 
@@ -1137,16 +1137,13 @@
1137
1137
  meta: {
1138
1138
  type: "suggestion",
1139
1139
  docs: {
1140
- description: "Indicates that any constant outside a constant.js file should be moved to a constant.js file."
1140
+ description: "Indicates that any constant outside a constant.[js|jsx] file should be moved to a constant.[js|jsx] file."
1141
1141
  }
1142
1142
  },
1143
1143
  create: context => ({
1144
1144
  VariableDeclaration(node) {
1145
- if (node.kind !== "const") return;
1146
- if (isConstantsFile(context)) return;
1147
- const constantName = node.declarations[0].id.name;
1148
-
1149
- if (CONSTANT_CASE_PATTERN.test(constantName)) {
1145
+ if (!isConstantsFile(context) && matches(CONSTANT_DECALARATION_PATTERN, node)) {
1146
+ const constantName = node.declarations[0].id.name;
1150
1147
  context.report(node, moveToConstantsJs(constantName));
1151
1148
  }
1152
1149
  }
@@ -1196,135 +1193,1415 @@
1196
1193
  })
1197
1194
  };
1198
1195
 
1199
- const toConstantCase = text => text.replace(/([A-Z0-9][a-z])/g, "_$1").replace(/([a-z0-9])([A-Z0-9])/g, "$1_$2").toUpperCase().replace(/[^A-Z0-9_]/g, "").replace(/^_/g, "");
1196
+ const isWindows = typeof process === 'object' &&
1197
+ process &&
1198
+ process.platform === 'win32';
1199
+ var path$1 = isWindows ? { sep: '\\' } : { sep: '/' };
1200
1200
 
1201
- const checkCaseAndReport = ({
1202
- context,
1203
- name,
1204
- node
1205
- }) => {
1206
- if (CONSTANT_CASE_PATTERN.test(name)) return;
1207
- context.report({
1208
- node,
1209
- message: useConstantCaseFor(name),
1210
- suggest: [{
1211
- desc: `Replace ${getCode$1(context, node)} with ${toConstantCase(name)}`,
1212
- fix: fixer => fixer.replaceText(node, toConstantCase(name))
1213
- }]
1214
- });
1215
- };
1201
+ var balancedMatch = balanced$1;
1202
+ function balanced$1(a, b, str) {
1203
+ if (a instanceof RegExp) a = maybeMatch(a, str);
1204
+ if (b instanceof RegExp) b = maybeMatch(b, str);
1216
1205
 
1217
- const checkExportAndReport = ({
1218
- context,
1219
- exported,
1220
- local,
1221
- node,
1222
- statement
1223
- }) => {
1224
- if (CONSTANT_CASE_PATTERN.test(exported.name)) return;
1225
- context.report({
1226
- node,
1227
- message: useConstantCaseFor(exported.name),
1228
- suggest: [{
1229
- desc: `Replace ${getCode$1(context, node)} with ${toConstantCase(exported.name)}`,
1230
- fix: fixer => {
1231
- const newName = toConstantCase(exported.name);
1232
-
1233
- if (local.name === exported.name) {
1234
- return fixer.replaceText(statement, newName);
1235
- }
1206
+ var r = range(a, b, str);
1236
1207
 
1237
- if (local.name === newName) {
1238
- return fixer.replaceText(statement, local.name);
1239
- }
1208
+ return r && {
1209
+ start: r[0],
1210
+ end: r[1],
1211
+ pre: str.slice(0, r[0]),
1212
+ body: str.slice(r[0] + a.length, r[1]),
1213
+ post: str.slice(r[1] + b.length)
1214
+ };
1215
+ }
1240
1216
 
1241
- return fixer.replaceText(exported, newName);
1242
- }
1243
- }]
1244
- });
1245
- };
1217
+ function maybeMatch(reg, str) {
1218
+ var m = str.match(reg);
1219
+ return m ? m[0] : null;
1220
+ }
1246
1221
 
1247
- var useConstantCase = {
1248
- meta: {
1249
- type: "suggestion",
1250
- docs: {
1251
- description: "Enforces constants in constants.js file to be named using constant-case."
1252
- },
1253
- hasSuggestions: true
1254
- },
1255
- create: context => ({
1256
- ExportNamedDeclaration(node) {
1257
- var _node$declaration;
1258
-
1259
- if (!isConstantsFile(context)) return;
1260
-
1261
- if (((_node$declaration = node.declaration) === null || _node$declaration === void 0 ? void 0 : _node$declaration.kind) === "const") {
1262
- var _node$declaration2;
1263
-
1264
- (_node$declaration2 = node.declaration) === null || _node$declaration2 === void 0 ? void 0 : _node$declaration2.declarations.forEach(({
1265
- id
1266
- }) => {
1267
- if (id.type !== TYPES.OBJECT_PATTERN) {
1268
- checkCaseAndReport({
1269
- context,
1270
- name: id.name,
1271
- node: id
1272
- });
1273
- return;
1274
- }
1222
+ balanced$1.range = range;
1223
+ function range(a, b, str) {
1224
+ var begs, beg, left, right, result;
1225
+ var ai = str.indexOf(a);
1226
+ var bi = str.indexOf(b, ai + 1);
1227
+ var i = ai;
1275
1228
 
1276
- id.properties.forEach(statement => {
1277
- checkExportAndReport({
1278
- context,
1279
- exported: statement.value,
1280
- local: statement.key,
1281
- node,
1282
- statement
1283
- });
1284
- });
1285
- });
1229
+ if (ai >= 0 && bi > 0) {
1230
+ if(a===b) {
1231
+ return [ai, bi];
1232
+ }
1233
+ begs = [];
1234
+ left = str.length;
1235
+
1236
+ while (i >= 0 && !result) {
1237
+ if (i == ai) {
1238
+ begs.push(i);
1239
+ ai = str.indexOf(a, i + 1);
1240
+ } else if (begs.length == 1) {
1241
+ result = [ begs.pop(), bi ];
1286
1242
  } else {
1287
- node.specifiers.forEach(statement => {
1288
- const {
1289
- exported,
1290
- local
1291
- } = statement;
1292
- checkExportAndReport({
1293
- context,
1294
- exported,
1295
- local,
1296
- node,
1297
- statement
1298
- });
1299
- });
1243
+ beg = begs.pop();
1244
+ if (beg < left) {
1245
+ left = beg;
1246
+ right = bi;
1247
+ }
1248
+
1249
+ bi = str.indexOf(b, i + 1);
1300
1250
  }
1301
- }
1302
1251
 
1303
- })
1304
- };
1252
+ i = ai < bi && ai >= 0 ? ai : bi;
1253
+ }
1305
1254
 
1306
- const ASSIGNMENT_PATTERNS = [{
1307
- id: {
1308
- type: "ObjectPattern"
1255
+ if (begs.length) {
1256
+ result = [ left, right ];
1257
+ }
1258
+ }
1259
+
1260
+ return result;
1261
+ }
1262
+
1263
+ var balanced = balancedMatch;
1264
+
1265
+ var braceExpansion = expandTop;
1266
+
1267
+ var escSlash = '\0SLASH'+Math.random()+'\0';
1268
+ var escOpen = '\0OPEN'+Math.random()+'\0';
1269
+ var escClose = '\0CLOSE'+Math.random()+'\0';
1270
+ var escComma = '\0COMMA'+Math.random()+'\0';
1271
+ var escPeriod = '\0PERIOD'+Math.random()+'\0';
1272
+
1273
+ function numeric(str) {
1274
+ return parseInt(str, 10) == str
1275
+ ? parseInt(str, 10)
1276
+ : str.charCodeAt(0);
1277
+ }
1278
+
1279
+ function escapeBraces(str) {
1280
+ return str.split('\\\\').join(escSlash)
1281
+ .split('\\{').join(escOpen)
1282
+ .split('\\}').join(escClose)
1283
+ .split('\\,').join(escComma)
1284
+ .split('\\.').join(escPeriod);
1285
+ }
1286
+
1287
+ function unescapeBraces(str) {
1288
+ return str.split(escSlash).join('\\')
1289
+ .split(escOpen).join('{')
1290
+ .split(escClose).join('}')
1291
+ .split(escComma).join(',')
1292
+ .split(escPeriod).join('.');
1293
+ }
1294
+
1295
+
1296
+ // Basically just str.split(","), but handling cases
1297
+ // where we have nested braced sections, which should be
1298
+ // treated as individual members, like {a,{b,c},d}
1299
+ function parseCommaParts(str) {
1300
+ if (!str)
1301
+ return [''];
1302
+
1303
+ var parts = [];
1304
+ var m = balanced('{', '}', str);
1305
+
1306
+ if (!m)
1307
+ return str.split(',');
1308
+
1309
+ var pre = m.pre;
1310
+ var body = m.body;
1311
+ var post = m.post;
1312
+ var p = pre.split(',');
1313
+
1314
+ p[p.length-1] += '{' + body + '}';
1315
+ var postParts = parseCommaParts(post);
1316
+ if (post.length) {
1317
+ p[p.length-1] += postParts.shift();
1318
+ p.push.apply(p, postParts);
1319
+ }
1320
+
1321
+ parts.push.apply(parts, p);
1322
+
1323
+ return parts;
1324
+ }
1325
+
1326
+ function expandTop(str) {
1327
+ if (!str)
1328
+ return [];
1329
+
1330
+ // I don't know why Bash 4.3 does this, but it does.
1331
+ // Anything starting with {} will have the first two bytes preserved
1332
+ // but *only* at the top level, so {},a}b will not expand to anything,
1333
+ // but a{},b}c will be expanded to [a}c,abc].
1334
+ // One could argue that this is a bug in Bash, but since the goal of
1335
+ // this module is to match Bash's rules, we escape a leading {}
1336
+ if (str.substr(0, 2) === '{}') {
1337
+ str = '\\{\\}' + str.substr(2);
1338
+ }
1339
+
1340
+ return expand$1(escapeBraces(str), true).map(unescapeBraces);
1341
+ }
1342
+
1343
+ function embrace(str) {
1344
+ return '{' + str + '}';
1345
+ }
1346
+ function isPadded(el) {
1347
+ return /^-?0\d/.test(el);
1348
+ }
1349
+
1350
+ function lte(i, y) {
1351
+ return i <= y;
1352
+ }
1353
+ function gte(i, y) {
1354
+ return i >= y;
1355
+ }
1356
+
1357
+ function expand$1(str, isTop) {
1358
+ var expansions = [];
1359
+
1360
+ var m = balanced('{', '}', str);
1361
+ if (!m) return [str];
1362
+
1363
+ // no need to expand pre, since it is guaranteed to be free of brace-sets
1364
+ var pre = m.pre;
1365
+ var post = m.post.length
1366
+ ? expand$1(m.post, false)
1367
+ : [''];
1368
+
1369
+ if (/\$$/.test(m.pre)) {
1370
+ for (var k = 0; k < post.length; k++) {
1371
+ var expansion = pre+ '{' + m.body + '}' + post[k];
1372
+ expansions.push(expansion);
1373
+ }
1374
+ } else {
1375
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
1376
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
1377
+ var isSequence = isNumericSequence || isAlphaSequence;
1378
+ var isOptions = m.body.indexOf(',') >= 0;
1379
+ if (!isSequence && !isOptions) {
1380
+ // {a},b}
1381
+ if (m.post.match(/,.*\}/)) {
1382
+ str = m.pre + '{' + m.body + escClose + m.post;
1383
+ return expand$1(str);
1384
+ }
1385
+ return [str];
1386
+ }
1387
+
1388
+ var n;
1389
+ if (isSequence) {
1390
+ n = m.body.split(/\.\./);
1391
+ } else {
1392
+ n = parseCommaParts(m.body);
1393
+ if (n.length === 1) {
1394
+ // x{{a,b}}y ==> x{a}y x{b}y
1395
+ n = expand$1(n[0], false).map(embrace);
1396
+ if (n.length === 1) {
1397
+ return post.map(function(p) {
1398
+ return m.pre + n[0] + p;
1399
+ });
1400
+ }
1401
+ }
1402
+ }
1403
+
1404
+ // at this point, n is the parts, and we know it's not a comma set
1405
+ // with a single entry.
1406
+ var N;
1407
+
1408
+ if (isSequence) {
1409
+ var x = numeric(n[0]);
1410
+ var y = numeric(n[1]);
1411
+ var width = Math.max(n[0].length, n[1].length);
1412
+ var incr = n.length == 3
1413
+ ? Math.abs(numeric(n[2]))
1414
+ : 1;
1415
+ var test = lte;
1416
+ var reverse = y < x;
1417
+ if (reverse) {
1418
+ incr *= -1;
1419
+ test = gte;
1420
+ }
1421
+ var pad = n.some(isPadded);
1422
+
1423
+ N = [];
1424
+
1425
+ for (var i = x; test(i, y); i += incr) {
1426
+ var c;
1427
+ if (isAlphaSequence) {
1428
+ c = String.fromCharCode(i);
1429
+ if (c === '\\')
1430
+ c = '';
1431
+ } else {
1432
+ c = String(i);
1433
+ if (pad) {
1434
+ var need = width - c.length;
1435
+ if (need > 0) {
1436
+ var z = new Array(need + 1).join('0');
1437
+ if (i < 0)
1438
+ c = '-' + z + c.slice(1);
1439
+ else
1440
+ c = z + c;
1441
+ }
1442
+ }
1443
+ }
1444
+ N.push(c);
1445
+ }
1446
+ } else {
1447
+ N = [];
1448
+
1449
+ for (var j = 0; j < n.length; j++) {
1450
+ N.push.apply(N, expand$1(n[j], false));
1451
+ }
1452
+ }
1453
+
1454
+ for (var j = 0; j < N.length; j++) {
1455
+ for (var k = 0; k < post.length; k++) {
1456
+ var expansion = pre + N[j] + post[k];
1457
+ if (!isTop || isSequence || expansion)
1458
+ expansions.push(expansion);
1459
+ }
1460
+ }
1461
+ }
1462
+
1463
+ return expansions;
1464
+ }
1465
+
1466
+ const minimatch = minimatch_1 = (p, pattern, options = {}) => {
1467
+ assertValidPattern(pattern);
1468
+
1469
+ // shortcut: comments match nothing.
1470
+ if (!options.nocomment && pattern.charAt(0) === '#') {
1471
+ return false
1472
+ }
1473
+
1474
+ return new Minimatch(pattern, options).match(p)
1475
+ };
1476
+
1477
+ var minimatch_1 = minimatch;
1478
+
1479
+ const path = path$1;
1480
+ minimatch.sep = path.sep;
1481
+
1482
+ const GLOBSTAR = Symbol('globstar **');
1483
+ minimatch.GLOBSTAR = GLOBSTAR;
1484
+ const expand = braceExpansion;
1485
+
1486
+ const plTypes = {
1487
+ '!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
1488
+ '?': { open: '(?:', close: ')?' },
1489
+ '+': { open: '(?:', close: ')+' },
1490
+ '*': { open: '(?:', close: ')*' },
1491
+ '@': { open: '(?:', close: ')' }
1492
+ };
1493
+
1494
+ // any single thing other than /
1495
+ // don't need to escape / when using new RegExp()
1496
+ const qmark = '[^/]';
1497
+
1498
+ // * => any number of characters
1499
+ const star = qmark + '*?';
1500
+
1501
+ // ** when dots are allowed. Anything goes, except .. and .
1502
+ // not (^ or / followed by one or two dots followed by $ or /),
1503
+ // followed by anything, any number of times.
1504
+ const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?';
1505
+
1506
+ // not a ^ or / followed by a dot,
1507
+ // followed by anything, any number of times.
1508
+ const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?';
1509
+
1510
+ // "abc" -> { a:true, b:true, c:true }
1511
+ const charSet = s => s.split('').reduce((set, c) => {
1512
+ set[c] = true;
1513
+ return set
1514
+ }, {});
1515
+
1516
+ // characters that need to be escaped in RegExp.
1517
+ const reSpecials = charSet('().*{}+?[]^$\\!');
1518
+
1519
+ // characters that indicate we have to add the pattern start
1520
+ const addPatternStartSet = charSet('[.(');
1521
+
1522
+ // normalizes slashes.
1523
+ const slashSplit = /\/+/;
1524
+
1525
+ minimatch.filter = (pattern, options = {}) =>
1526
+ (p, i, list) => minimatch(p, pattern, options);
1527
+
1528
+ const ext = (a, b = {}) => {
1529
+ const t = {};
1530
+ Object.keys(a).forEach(k => t[k] = a[k]);
1531
+ Object.keys(b).forEach(k => t[k] = b[k]);
1532
+ return t
1533
+ };
1534
+
1535
+ minimatch.defaults = def => {
1536
+ if (!def || typeof def !== 'object' || !Object.keys(def).length) {
1537
+ return minimatch
1538
+ }
1539
+
1540
+ const orig = minimatch;
1541
+
1542
+ const m = (p, pattern, options) => orig(p, pattern, ext(def, options));
1543
+ m.Minimatch = class Minimatch extends orig.Minimatch {
1544
+ constructor (pattern, options) {
1545
+ super(pattern, ext(def, options));
1546
+ }
1547
+ };
1548
+ m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch;
1549
+ m.filter = (pattern, options) => orig.filter(pattern, ext(def, options));
1550
+ m.defaults = options => orig.defaults(ext(def, options));
1551
+ m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options));
1552
+ m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options));
1553
+ m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options));
1554
+
1555
+ return m
1556
+ };
1557
+
1558
+
1559
+
1560
+
1561
+
1562
+ // Brace expansion:
1563
+ // a{b,c}d -> abd acd
1564
+ // a{b,}c -> abc ac
1565
+ // a{0..3}d -> a0d a1d a2d a3d
1566
+ // a{b,c{d,e}f}g -> abg acdfg acefg
1567
+ // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
1568
+ //
1569
+ // Invalid sets are not expanded.
1570
+ // a{2..}b -> a{2..}b
1571
+ // a{b}c -> a{b}c
1572
+ minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options);
1573
+
1574
+ const braceExpand = (pattern, options = {}) => {
1575
+ assertValidPattern(pattern);
1576
+
1577
+ // Thanks to Yeting Li <https://github.com/yetingli> for
1578
+ // improving this regexp to avoid a ReDOS vulnerability.
1579
+ if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
1580
+ // shortcut. no need to expand.
1581
+ return [pattern]
1582
+ }
1583
+
1584
+ return expand(pattern)
1585
+ };
1586
+
1587
+ const MAX_PATTERN_LENGTH = 1024 * 64;
1588
+ const assertValidPattern = pattern => {
1589
+ if (typeof pattern !== 'string') {
1590
+ throw new TypeError('invalid pattern')
1591
+ }
1592
+
1593
+ if (pattern.length > MAX_PATTERN_LENGTH) {
1594
+ throw new TypeError('pattern is too long')
1595
+ }
1596
+ };
1597
+
1598
+ // parse a component of the expanded set.
1599
+ // At this point, no pattern may contain "/" in it
1600
+ // so we're going to return a 2d array, where each entry is the full
1601
+ // pattern, split on '/', and then turned into a regular expression.
1602
+ // A regexp is made at the end which joins each array with an
1603
+ // escaped /, and another full one which joins each regexp with |.
1604
+ //
1605
+ // Following the lead of Bash 4.1, note that "**" only has special meaning
1606
+ // when it is the *only* thing in a path portion. Otherwise, any series
1607
+ // of * is equivalent to a single *. Globstar behavior is enabled by
1608
+ // default, and can be disabled by setting options.noglobstar.
1609
+ const SUBPARSE = Symbol('subparse');
1610
+
1611
+ minimatch.makeRe = (pattern, options) =>
1612
+ new Minimatch(pattern, options || {}).makeRe();
1613
+
1614
+ minimatch.match = (list, pattern, options = {}) => {
1615
+ const mm = new Minimatch(pattern, options);
1616
+ list = list.filter(f => mm.match(f));
1617
+ if (mm.options.nonull && !list.length) {
1618
+ list.push(pattern);
1619
+ }
1620
+ return list
1621
+ };
1622
+
1623
+ // replace stuff like \* with *
1624
+ const globUnescape = s => s.replace(/\\(.)/g, '$1');
1625
+ const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
1626
+
1627
+ class Minimatch {
1628
+ constructor (pattern, options) {
1629
+ assertValidPattern(pattern);
1630
+
1631
+ if (!options) options = {};
1632
+
1633
+ this.options = options;
1634
+ this.set = [];
1635
+ this.pattern = pattern;
1636
+ this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
1637
+ options.allowWindowsEscape === false;
1638
+ if (this.windowsPathsNoEscape) {
1639
+ this.pattern = this.pattern.replace(/\\/g, '/');
1640
+ }
1641
+ this.regexp = null;
1642
+ this.negate = false;
1643
+ this.comment = false;
1644
+ this.empty = false;
1645
+ this.partial = !!options.partial;
1646
+
1647
+ // make the set of regexps etc.
1648
+ this.make();
1649
+ }
1650
+
1651
+ debug () {}
1652
+
1653
+ make () {
1654
+ const pattern = this.pattern;
1655
+ const options = this.options;
1656
+
1657
+ // empty patterns and comments match nothing.
1658
+ if (!options.nocomment && pattern.charAt(0) === '#') {
1659
+ this.comment = true;
1660
+ return
1661
+ }
1662
+ if (!pattern) {
1663
+ this.empty = true;
1664
+ return
1665
+ }
1666
+
1667
+ // step 1: figure out negation, etc.
1668
+ this.parseNegate();
1669
+
1670
+ // step 2: expand braces
1671
+ let set = this.globSet = this.braceExpand();
1672
+
1673
+ if (options.debug) this.debug = (...args) => console.error(...args);
1674
+
1675
+ this.debug(this.pattern, set);
1676
+
1677
+ // step 3: now we have a set, so turn each one into a series of path-portion
1678
+ // matching patterns.
1679
+ // These will be regexps, except in the case of "**", which is
1680
+ // set to the GLOBSTAR object for globstar behavior,
1681
+ // and will not contain any / characters
1682
+ set = this.globParts = set.map(s => s.split(slashSplit));
1683
+
1684
+ this.debug(this.pattern, set);
1685
+
1686
+ // glob --> regexps
1687
+ set = set.map((s, si, set) => s.map(this.parse, this));
1688
+
1689
+ this.debug(this.pattern, set);
1690
+
1691
+ // filter out everything that didn't compile properly.
1692
+ set = set.filter(s => s.indexOf(false) === -1);
1693
+
1694
+ this.debug(this.pattern, set);
1695
+
1696
+ this.set = set;
1697
+ }
1698
+
1699
+ parseNegate () {
1700
+ if (this.options.nonegate) return
1701
+
1702
+ const pattern = this.pattern;
1703
+ let negate = false;
1704
+ let negateOffset = 0;
1705
+
1706
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
1707
+ negate = !negate;
1708
+ negateOffset++;
1709
+ }
1710
+
1711
+ if (negateOffset) this.pattern = pattern.substr(negateOffset);
1712
+ this.negate = negate;
1713
+ }
1714
+
1715
+ // set partial to true to test if, for example,
1716
+ // "/a/b" matches the start of "/*/b/*/d"
1717
+ // Partial means, if you run out of file before you run
1718
+ // out of pattern, then that's fine, as long as all
1719
+ // the parts match.
1720
+ matchOne (file, pattern, partial) {
1721
+ var options = this.options;
1722
+
1723
+ this.debug('matchOne',
1724
+ { 'this': this, file: file, pattern: pattern });
1725
+
1726
+ this.debug('matchOne', file.length, pattern.length);
1727
+
1728
+ for (var fi = 0,
1729
+ pi = 0,
1730
+ fl = file.length,
1731
+ pl = pattern.length
1732
+ ; (fi < fl) && (pi < pl)
1733
+ ; fi++, pi++) {
1734
+ this.debug('matchOne loop');
1735
+ var p = pattern[pi];
1736
+ var f = file[fi];
1737
+
1738
+ this.debug(pattern, p, f);
1739
+
1740
+ // should be impossible.
1741
+ // some invalid regexp stuff in the set.
1742
+ /* istanbul ignore if */
1743
+ if (p === false) return false
1744
+
1745
+ if (p === GLOBSTAR) {
1746
+ this.debug('GLOBSTAR', [pattern, p, f]);
1747
+
1748
+ // "**"
1749
+ // a/**/b/**/c would match the following:
1750
+ // a/b/x/y/z/c
1751
+ // a/x/y/z/b/c
1752
+ // a/b/x/b/x/c
1753
+ // a/b/c
1754
+ // To do this, take the rest of the pattern after
1755
+ // the **, and see if it would match the file remainder.
1756
+ // If so, return success.
1757
+ // If not, the ** "swallows" a segment, and try again.
1758
+ // This is recursively awful.
1759
+ //
1760
+ // a/**/b/**/c matching a/b/x/y/z/c
1761
+ // - a matches a
1762
+ // - doublestar
1763
+ // - matchOne(b/x/y/z/c, b/**/c)
1764
+ // - b matches b
1765
+ // - doublestar
1766
+ // - matchOne(x/y/z/c, c) -> no
1767
+ // - matchOne(y/z/c, c) -> no
1768
+ // - matchOne(z/c, c) -> no
1769
+ // - matchOne(c, c) yes, hit
1770
+ var fr = fi;
1771
+ var pr = pi + 1;
1772
+ if (pr === pl) {
1773
+ this.debug('** at the end');
1774
+ // a ** at the end will just swallow the rest.
1775
+ // We have found a match.
1776
+ // however, it will not swallow /.x, unless
1777
+ // options.dot is set.
1778
+ // . and .. are *never* matched by **, for explosively
1779
+ // exponential reasons.
1780
+ for (; fi < fl; fi++) {
1781
+ if (file[fi] === '.' || file[fi] === '..' ||
1782
+ (!options.dot && file[fi].charAt(0) === '.')) return false
1783
+ }
1784
+ return true
1785
+ }
1786
+
1787
+ // ok, let's see if we can swallow whatever we can.
1788
+ while (fr < fl) {
1789
+ var swallowee = file[fr];
1790
+
1791
+ this.debug('\nglobstar while', file, fr, pattern, pr, swallowee);
1792
+
1793
+ // XXX remove this slice. Just pass the start index.
1794
+ if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
1795
+ this.debug('globstar found match!', fr, fl, swallowee);
1796
+ // found a match.
1797
+ return true
1798
+ } else {
1799
+ // can't swallow "." or ".." ever.
1800
+ // can only swallow ".foo" when explicitly asked.
1801
+ if (swallowee === '.' || swallowee === '..' ||
1802
+ (!options.dot && swallowee.charAt(0) === '.')) {
1803
+ this.debug('dot detected!', file, fr, pattern, pr);
1804
+ break
1805
+ }
1806
+
1807
+ // ** swallows a segment, and continue.
1808
+ this.debug('globstar swallow a segment, and continue');
1809
+ fr++;
1810
+ }
1811
+ }
1812
+
1813
+ // no match was found.
1814
+ // However, in partial mode, we can't say this is necessarily over.
1815
+ // If there's more *pattern* left, then
1816
+ /* istanbul ignore if */
1817
+ if (partial) {
1818
+ // ran out of file
1819
+ this.debug('\n>>> no match, partial?', file, fr, pattern, pr);
1820
+ if (fr === fl) return true
1821
+ }
1822
+ return false
1823
+ }
1824
+
1825
+ // something other than **
1826
+ // non-magic patterns just have to match exactly
1827
+ // patterns with magic have been turned into regexps.
1828
+ var hit;
1829
+ if (typeof p === 'string') {
1830
+ hit = f === p;
1831
+ this.debug('string match', p, f, hit);
1832
+ } else {
1833
+ hit = f.match(p);
1834
+ this.debug('pattern match', p, f, hit);
1835
+ }
1836
+
1837
+ if (!hit) return false
1838
+ }
1839
+
1840
+ // Note: ending in / means that we'll get a final ""
1841
+ // at the end of the pattern. This can only match a
1842
+ // corresponding "" at the end of the file.
1843
+ // If the file ends in /, then it can only match a
1844
+ // a pattern that ends in /, unless the pattern just
1845
+ // doesn't have any more for it. But, a/b/ should *not*
1846
+ // match "a/b/*", even though "" matches against the
1847
+ // [^/]*? pattern, except in partial mode, where it might
1848
+ // simply not be reached yet.
1849
+ // However, a/b/ should still satisfy a/*
1850
+
1851
+ // now either we fell off the end of the pattern, or we're done.
1852
+ if (fi === fl && pi === pl) {
1853
+ // ran out of pattern and filename at the same time.
1854
+ // an exact hit!
1855
+ return true
1856
+ } else if (fi === fl) {
1857
+ // ran out of file, but still had pattern left.
1858
+ // this is ok if we're doing the match as part of
1859
+ // a glob fs traversal.
1860
+ return partial
1861
+ } else /* istanbul ignore else */ if (pi === pl) {
1862
+ // ran out of pattern, still have file left.
1863
+ // this is only acceptable if we're on the very last
1864
+ // empty segment of a file with a trailing slash.
1865
+ // a/* should match a/b/
1866
+ return (fi === fl - 1) && (file[fi] === '')
1867
+ }
1868
+
1869
+ // should be unreachable.
1870
+ /* istanbul ignore next */
1871
+ throw new Error('wtf?')
1872
+ }
1873
+
1874
+ braceExpand () {
1875
+ return braceExpand(this.pattern, this.options)
1876
+ }
1877
+
1878
+ parse (pattern, isSub) {
1879
+ assertValidPattern(pattern);
1880
+
1881
+ const options = this.options;
1882
+
1883
+ // shortcuts
1884
+ if (pattern === '**') {
1885
+ if (!options.noglobstar)
1886
+ return GLOBSTAR
1887
+ else
1888
+ pattern = '*';
1889
+ }
1890
+ if (pattern === '') return ''
1891
+
1892
+ let re = '';
1893
+ let hasMagic = !!options.nocase;
1894
+ let escaping = false;
1895
+ // ? => one single character
1896
+ const patternListStack = [];
1897
+ const negativeLists = [];
1898
+ let stateChar;
1899
+ let inClass = false;
1900
+ let reClassStart = -1;
1901
+ let classStart = -1;
1902
+ let cs;
1903
+ let pl;
1904
+ let sp;
1905
+ // . and .. never match anything that doesn't start with .,
1906
+ // even when options.dot is set.
1907
+ const patternStart = pattern.charAt(0) === '.' ? '' // anything
1908
+ // not (start or / followed by . or .. followed by / or end)
1909
+ : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
1910
+ : '(?!\\.)';
1911
+
1912
+ const clearStateChar = () => {
1913
+ if (stateChar) {
1914
+ // we had some state-tracking character
1915
+ // that wasn't consumed by this pass.
1916
+ switch (stateChar) {
1917
+ case '*':
1918
+ re += star;
1919
+ hasMagic = true;
1920
+ break
1921
+ case '?':
1922
+ re += qmark;
1923
+ hasMagic = true;
1924
+ break
1925
+ default:
1926
+ re += '\\' + stateChar;
1927
+ break
1928
+ }
1929
+ this.debug('clearStateChar %j %j', stateChar, re);
1930
+ stateChar = false;
1931
+ }
1932
+ };
1933
+
1934
+ for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
1935
+ this.debug('%s\t%s %s %j', pattern, i, re, c);
1936
+
1937
+ // skip over any that are escaped.
1938
+ if (escaping) {
1939
+ /* istanbul ignore next - completely not allowed, even escaped. */
1940
+ if (c === '/') {
1941
+ return false
1942
+ }
1943
+
1944
+ if (reSpecials[c]) {
1945
+ re += '\\';
1946
+ }
1947
+ re += c;
1948
+ escaping = false;
1949
+ continue
1950
+ }
1951
+
1952
+ switch (c) {
1953
+ /* istanbul ignore next */
1954
+ case '/': {
1955
+ // Should already be path-split by now.
1956
+ return false
1957
+ }
1958
+
1959
+ case '\\':
1960
+ clearStateChar();
1961
+ escaping = true;
1962
+ continue
1963
+
1964
+ // the various stateChar values
1965
+ // for the "extglob" stuff.
1966
+ case '?':
1967
+ case '*':
1968
+ case '+':
1969
+ case '@':
1970
+ case '!':
1971
+ this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c);
1972
+
1973
+ // all of those are literals inside a class, except that
1974
+ // the glob [!a] means [^a] in regexp
1975
+ if (inClass) {
1976
+ this.debug(' in class');
1977
+ if (c === '!' && i === classStart + 1) c = '^';
1978
+ re += c;
1979
+ continue
1980
+ }
1981
+
1982
+ // if we already have a stateChar, then it means
1983
+ // that there was something like ** or +? in there.
1984
+ // Handle the stateChar, then proceed with this one.
1985
+ this.debug('call clearStateChar %j', stateChar);
1986
+ clearStateChar();
1987
+ stateChar = c;
1988
+ // if extglob is disabled, then +(asdf|foo) isn't a thing.
1989
+ // just clear the statechar *now*, rather than even diving into
1990
+ // the patternList stuff.
1991
+ if (options.noext) clearStateChar();
1992
+ continue
1993
+
1994
+ case '(':
1995
+ if (inClass) {
1996
+ re += '(';
1997
+ continue
1998
+ }
1999
+
2000
+ if (!stateChar) {
2001
+ re += '\\(';
2002
+ continue
2003
+ }
2004
+
2005
+ patternListStack.push({
2006
+ type: stateChar,
2007
+ start: i - 1,
2008
+ reStart: re.length,
2009
+ open: plTypes[stateChar].open,
2010
+ close: plTypes[stateChar].close
2011
+ });
2012
+ // negation is (?:(?!js)[^/]*)
2013
+ re += stateChar === '!' ? '(?:(?!(?:' : '(?:';
2014
+ this.debug('plType %j %j', stateChar, re);
2015
+ stateChar = false;
2016
+ continue
2017
+
2018
+ case ')':
2019
+ if (inClass || !patternListStack.length) {
2020
+ re += '\\)';
2021
+ continue
2022
+ }
2023
+
2024
+ clearStateChar();
2025
+ hasMagic = true;
2026
+ pl = patternListStack.pop();
2027
+ // negation is (?:(?!js)[^/]*)
2028
+ // The others are (?:<pattern>)<type>
2029
+ re += pl.close;
2030
+ if (pl.type === '!') {
2031
+ negativeLists.push(pl);
2032
+ }
2033
+ pl.reEnd = re.length;
2034
+ continue
2035
+
2036
+ case '|':
2037
+ if (inClass || !patternListStack.length) {
2038
+ re += '\\|';
2039
+ continue
2040
+ }
2041
+
2042
+ clearStateChar();
2043
+ re += '|';
2044
+ continue
2045
+
2046
+ // these are mostly the same in regexp and glob
2047
+ case '[':
2048
+ // swallow any state-tracking char before the [
2049
+ clearStateChar();
2050
+
2051
+ if (inClass) {
2052
+ re += '\\' + c;
2053
+ continue
2054
+ }
2055
+
2056
+ inClass = true;
2057
+ classStart = i;
2058
+ reClassStart = re.length;
2059
+ re += c;
2060
+ continue
2061
+
2062
+ case ']':
2063
+ // a right bracket shall lose its special
2064
+ // meaning and represent itself in
2065
+ // a bracket expression if it occurs
2066
+ // first in the list. -- POSIX.2 2.8.3.2
2067
+ if (i === classStart + 1 || !inClass) {
2068
+ re += '\\' + c;
2069
+ continue
2070
+ }
2071
+
2072
+ // handle the case where we left a class open.
2073
+ // "[z-a]" is valid, equivalent to "\[z-a\]"
2074
+ // split where the last [ was, make sure we don't have
2075
+ // an invalid re. if so, re-walk the contents of the
2076
+ // would-be class to re-translate any characters that
2077
+ // were passed through as-is
2078
+ // TODO: It would probably be faster to determine this
2079
+ // without a try/catch and a new RegExp, but it's tricky
2080
+ // to do safely. For now, this is safe and works.
2081
+ cs = pattern.substring(classStart + 1, i);
2082
+ try {
2083
+ RegExp('[' + cs + ']');
2084
+ } catch (er) {
2085
+ // not a valid class!
2086
+ sp = this.parse(cs, SUBPARSE);
2087
+ re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]';
2088
+ hasMagic = hasMagic || sp[1];
2089
+ inClass = false;
2090
+ continue
2091
+ }
2092
+
2093
+ // finish up the class.
2094
+ hasMagic = true;
2095
+ inClass = false;
2096
+ re += c;
2097
+ continue
2098
+
2099
+ default:
2100
+ // swallow any state char that wasn't consumed
2101
+ clearStateChar();
2102
+
2103
+ if (reSpecials[c] && !(c === '^' && inClass)) {
2104
+ re += '\\';
2105
+ }
2106
+
2107
+ re += c;
2108
+ break
2109
+
2110
+ } // switch
2111
+ } // for
2112
+
2113
+ // handle the case where we left a class open.
2114
+ // "[abc" is valid, equivalent to "\[abc"
2115
+ if (inClass) {
2116
+ // split where the last [ was, and escape it
2117
+ // this is a huge pita. We now have to re-walk
2118
+ // the contents of the would-be class to re-translate
2119
+ // any characters that were passed through as-is
2120
+ cs = pattern.substr(classStart + 1);
2121
+ sp = this.parse(cs, SUBPARSE);
2122
+ re = re.substr(0, reClassStart) + '\\[' + sp[0];
2123
+ hasMagic = hasMagic || sp[1];
2124
+ }
2125
+
2126
+ // handle the case where we had a +( thing at the *end*
2127
+ // of the pattern.
2128
+ // each pattern list stack adds 3 chars, and we need to go through
2129
+ // and escape any | chars that were passed through as-is for the regexp.
2130
+ // Go through and escape them, taking care not to double-escape any
2131
+ // | chars that were already escaped.
2132
+ for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
2133
+ let tail;
2134
+ tail = re.slice(pl.reStart + pl.open.length);
2135
+ this.debug('setting tail', re, pl);
2136
+ // maybe some even number of \, then maybe 1 \, followed by a |
2137
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
2138
+ /* istanbul ignore else - should already be done */
2139
+ if (!$2) {
2140
+ // the | isn't already escaped, so escape it.
2141
+ $2 = '\\';
2142
+ }
2143
+
2144
+ // need to escape all those slashes *again*, without escaping the
2145
+ // one that we need for escaping the | character. As it works out,
2146
+ // escaping an even number of slashes can be done by simply repeating
2147
+ // it exactly after itself. That's why this trick works.
2148
+ //
2149
+ // I am sorry that you have to see this.
2150
+ return $1 + $1 + $2 + '|'
2151
+ });
2152
+
2153
+ this.debug('tail=%j\n %s', tail, tail, pl, re);
2154
+ const t = pl.type === '*' ? star
2155
+ : pl.type === '?' ? qmark
2156
+ : '\\' + pl.type;
2157
+
2158
+ hasMagic = true;
2159
+ re = re.slice(0, pl.reStart) + t + '\\(' + tail;
2160
+ }
2161
+
2162
+ // handle trailing things that only matter at the very end.
2163
+ clearStateChar();
2164
+ if (escaping) {
2165
+ // trailing \\
2166
+ re += '\\\\';
2167
+ }
2168
+
2169
+ // only need to apply the nodot start if the re starts with
2170
+ // something that could conceivably capture a dot
2171
+ const addPatternStart = addPatternStartSet[re.charAt(0)];
2172
+
2173
+ // Hack to work around lack of negative lookbehind in JS
2174
+ // A pattern like: *.!(x).!(y|z) needs to ensure that a name
2175
+ // like 'a.xyz.yz' doesn't match. So, the first negative
2176
+ // lookahead, has to look ALL the way ahead, to the end of
2177
+ // the pattern.
2178
+ for (let n = negativeLists.length - 1; n > -1; n--) {
2179
+ const nl = negativeLists[n];
2180
+
2181
+ const nlBefore = re.slice(0, nl.reStart);
2182
+ const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
2183
+ let nlAfter = re.slice(nl.reEnd);
2184
+ const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
2185
+
2186
+ // Handle nested stuff like *(*.js|!(*.json)), where open parens
2187
+ // mean that we should *not* include the ) in the bit that is considered
2188
+ // "after" the negated section.
2189
+ const openParensBefore = nlBefore.split('(').length - 1;
2190
+ let cleanAfter = nlAfter;
2191
+ for (let i = 0; i < openParensBefore; i++) {
2192
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, '');
2193
+ }
2194
+ nlAfter = cleanAfter;
2195
+
2196
+ const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : '';
2197
+ re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
2198
+ }
2199
+
2200
+ // if the re is not "" at this point, then we need to make sure
2201
+ // it doesn't match against an empty path part.
2202
+ // Otherwise a/* will match a/, which it should not.
2203
+ if (re !== '' && hasMagic) {
2204
+ re = '(?=.)' + re;
2205
+ }
2206
+
2207
+ if (addPatternStart) {
2208
+ re = patternStart + re;
2209
+ }
2210
+
2211
+ // parsing just a piece of a larger pattern.
2212
+ if (isSub === SUBPARSE) {
2213
+ return [re, hasMagic]
2214
+ }
2215
+
2216
+ // skip the regexp for non-magical patterns
2217
+ // unescape anything in it, though, so that it'll be
2218
+ // an exact match against a file etc.
2219
+ if (!hasMagic) {
2220
+ return globUnescape(pattern)
2221
+ }
2222
+
2223
+ const flags = options.nocase ? 'i' : '';
2224
+ try {
2225
+ return Object.assign(new RegExp('^' + re + '$', flags), {
2226
+ _glob: pattern,
2227
+ _src: re,
2228
+ })
2229
+ } catch (er) /* istanbul ignore next - should be impossible */ {
2230
+ // If it was an invalid regular expression, then it can't match
2231
+ // anything. This trick looks for a character after the end of
2232
+ // the string, which is of course impossible, except in multi-line
2233
+ // mode, but it's not a /m regex.
2234
+ return new RegExp('$.')
2235
+ }
2236
+ }
2237
+
2238
+ makeRe () {
2239
+ if (this.regexp || this.regexp === false) return this.regexp
2240
+
2241
+ // at this point, this.set is a 2d array of partial
2242
+ // pattern strings, or "**".
2243
+ //
2244
+ // It's better to use .match(). This function shouldn't
2245
+ // be used, really, but it's pretty convenient sometimes,
2246
+ // when you just want to work with a regex.
2247
+ const set = this.set;
2248
+
2249
+ if (!set.length) {
2250
+ this.regexp = false;
2251
+ return this.regexp
2252
+ }
2253
+ const options = this.options;
2254
+
2255
+ const twoStar = options.noglobstar ? star
2256
+ : options.dot ? twoStarDot
2257
+ : twoStarNoDot;
2258
+ const flags = options.nocase ? 'i' : '';
2259
+
2260
+ // coalesce globstars and regexpify non-globstar patterns
2261
+ // if it's the only item, then we just do one twoStar
2262
+ // if it's the first, and there are more, prepend (\/|twoStar\/)? to next
2263
+ // if it's the last, append (\/twoStar|) to previous
2264
+ // if it's in the middle, append (\/|\/twoStar\/) to previous
2265
+ // then filter out GLOBSTAR symbols
2266
+ let re = set.map(pattern => {
2267
+ pattern = pattern.map(p =>
2268
+ typeof p === 'string' ? regExpEscape(p)
2269
+ : p === GLOBSTAR ? GLOBSTAR
2270
+ : p._src
2271
+ ).reduce((set, p) => {
2272
+ if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
2273
+ set.push(p);
2274
+ }
2275
+ return set
2276
+ }, []);
2277
+ pattern.forEach((p, i) => {
2278
+ if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {
2279
+ return
2280
+ }
2281
+ if (i === 0) {
2282
+ if (pattern.length > 1) {
2283
+ pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1];
2284
+ } else {
2285
+ pattern[i] = twoStar;
2286
+ }
2287
+ } else if (i === pattern.length - 1) {
2288
+ pattern[i-1] += '(?:\\\/|' + twoStar + ')?';
2289
+ } else {
2290
+ pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1];
2291
+ pattern[i+1] = GLOBSTAR;
2292
+ }
2293
+ });
2294
+ return pattern.filter(p => p !== GLOBSTAR).join('/')
2295
+ }).join('|');
2296
+
2297
+ // must match entire pattern
2298
+ // ending in a * or ** will make it less strict.
2299
+ re = '^(?:' + re + ')$';
2300
+
2301
+ // can match anything, as long as it's not this.
2302
+ if (this.negate) re = '^(?!' + re + ').*$';
2303
+
2304
+ try {
2305
+ this.regexp = new RegExp(re, flags);
2306
+ } catch (ex) /* istanbul ignore next - should be impossible */ {
2307
+ this.regexp = false;
2308
+ }
2309
+ return this.regexp
2310
+ }
2311
+
2312
+ match (f, partial = this.partial) {
2313
+ this.debug('match', f, this.pattern);
2314
+ // short-circuit in the case of busted things.
2315
+ // comments, etc.
2316
+ if (this.comment) return false
2317
+ if (this.empty) return f === ''
2318
+
2319
+ if (f === '/' && partial) return true
2320
+
2321
+ const options = this.options;
2322
+
2323
+ // windows: need to use /, not \
2324
+ if (path.sep !== '/') {
2325
+ f = f.split(path.sep).join('/');
2326
+ }
2327
+
2328
+ // treat the test path as a set of pathparts.
2329
+ f = f.split(slashSplit);
2330
+ this.debug(this.pattern, 'split', f);
2331
+
2332
+ // just ONE of the pattern sets in this.set needs to match
2333
+ // in order for it to be valid. If negating, then just one
2334
+ // match means that we have failed.
2335
+ // Either way, return on the first hit.
2336
+
2337
+ const set = this.set;
2338
+ this.debug(this.pattern, 'set', set);
2339
+
2340
+ // Find the basename of the path by looking for the last non-empty segment
2341
+ let filename;
2342
+ for (let i = f.length - 1; i >= 0; i--) {
2343
+ filename = f[i];
2344
+ if (filename) break
2345
+ }
2346
+
2347
+ for (let i = 0; i < set.length; i++) {
2348
+ const pattern = set[i];
2349
+ let file = f;
2350
+ if (options.matchBase && pattern.length === 1) {
2351
+ file = [filename];
2352
+ }
2353
+ const hit = this.matchOne(file, pattern, partial);
2354
+ if (hit) {
2355
+ if (options.flipNegate) return true
2356
+ return !this.negate
2357
+ }
2358
+ }
2359
+
2360
+ // didn't get any hits. this is success if it's a negative
2361
+ // pattern, failure otherwise.
2362
+ if (options.flipNegate) return false
2363
+ return this.negate
2364
+ }
2365
+
2366
+ static defaults (def) {
2367
+ return minimatch.defaults(def).Minimatch
2368
+ }
2369
+ }
2370
+
2371
+ minimatch.Minimatch = Minimatch;
2372
+
2373
+ var minimatch$1 = minimatch_1;
2374
+
2375
+ const CAMEL_CASE_REGEX = /^[a-z][A-Za-z0-9]*$/;
2376
+ const CONSTANT_CASE_REGEX = /^[A-Z_]+$/;
2377
+ const PASCAL_CASE_REGEX = /^[A-Z][A-Za-z0-9]*$/;
2378
+ const SNAKE_CASE_REGEX$1 = /^[a-z0-9_]+$/;
2379
+ const EXPORT_PATTERN = {
2380
+ type: ramda.includes(ramda.__, [TYPES.EXPORT_DEFAULT_DECLARATION, TYPES.EXPORT_NAMED_DECLARATION])
2381
+ };
2382
+
2383
+ const isInsideBaseDirectory = context => context.getFilename().startsWith(context.options[0].basePath);
2384
+
2385
+ const asArray = item => {
2386
+ if (!item) return [];
2387
+ return Array.isArray(item) ? item : new Array(item);
2388
+ };
2389
+
2390
+ const isCaseMatching = (text, caseStyle) => {
2391
+ var _regexes$caseStyle;
2392
+
2393
+ if (!text) return true;
2394
+ const regexes = {
2395
+ camelCase: CAMEL_CASE_REGEX,
2396
+ CONSTANT_CASE: CONSTANT_CASE_REGEX,
2397
+ PascalCase: PASCAL_CASE_REGEX,
2398
+ snake_case: SNAKE_CASE_REGEX$1
2399
+ };
2400
+ return ((_regexes$caseStyle = regexes[caseStyle]) === null || _regexes$caseStyle === void 0 ? void 0 : _regexes$caseStyle.test(text)) ?? true;
2401
+ };
2402
+
2403
+ const findMatchedConfig = (context, configs) => {
2404
+ const fullFilePath = context.getFilename();
2405
+ const matchedConfig = configs.find(config => {
2406
+ const isIncluded = asArray(config.includes).some(pathPattern => minimatch$1(fullFilePath, pathPattern));
2407
+ if (config.includes && !isIncluded) return false;
2408
+ const isExcluded = asArray(config.excludes).some(pathPattern => minimatch$1(fullFilePath, pathPattern));
2409
+ if (config.excludes && isExcluded) return false;
2410
+ return true;
2411
+ });
2412
+ return matchedConfig;
2413
+ };
2414
+
2415
+ const checkFilenameCase = (context, node, filenameCase) => {
2416
+ const [filename] = getFilenameAndExtension(context);
2417
+ if (filename === "index") return;
2418
+
2419
+ if (!isCaseMatching(filename, filenameCase)) {
2420
+ context.report({
2421
+ node,
2422
+ message: filenameShouldBe(filenameCase)
2423
+ });
2424
+ }
2425
+ };
2426
+
2427
+ const reportExportCaseMismatch = ({
2428
+ context,
2429
+ node,
2430
+ exportnameCase,
2431
+ objectName
2432
+ }) => {
2433
+ if (objectName && !isCaseMatching(objectName, exportnameCase)) {
2434
+ context.report({
2435
+ node,
2436
+ message: exportedObjectShouldBe(exportnameCase)
2437
+ });
2438
+ }
2439
+ };
2440
+
2441
+ const checkExportItemsCase = ({
2442
+ context,
2443
+ items,
2444
+ itemsType,
2445
+ exportnameCase
2446
+ }) => {
2447
+ items === null || items === void 0 ? void 0 : items.forEach(item => {
2448
+ const objectName = itemsType === "specifiers" ? item.exported.name : item.value.name;
2449
+ reportExportCaseMismatch({
2450
+ context,
2451
+ node: item,
2452
+ exportnameCase,
2453
+ objectName
2454
+ });
2455
+ });
2456
+ };
2457
+
2458
+ const checkNamedExportCase = (context, node, exportnameCase) => {
2459
+ var _node$declaration;
2460
+
2461
+ if (((_node$declaration = node.declaration) === null || _node$declaration === void 0 ? void 0 : _node$declaration.kind) === "const") {
2462
+ node.declaration.declarations.forEach(({
2463
+ id
2464
+ }) => {
2465
+ if (id.type === TYPES.IDENTIFIER) {
2466
+ reportExportCaseMismatch({
2467
+ context,
2468
+ node: id,
2469
+ exportnameCase,
2470
+ objectName: id.name
2471
+ });
2472
+ } else {
2473
+ checkExportItemsCase({
2474
+ context,
2475
+ items: id.properties,
2476
+ itemsType: "properties",
2477
+ exportnameCase
2478
+ });
2479
+ }
2480
+ });
2481
+ } else {
2482
+ checkExportItemsCase({
2483
+ context,
2484
+ items: node.specifiers,
2485
+ itemsType: "specifiers",
2486
+ exportnameCase
2487
+ });
2488
+ }
2489
+ };
2490
+
2491
+ const checkDefaultExportCase = (context, node, exportnameCase) => {
2492
+ var _declaration$id;
2493
+
2494
+ const declaration = node.declaration;
2495
+
2496
+ if (declaration.type === TYPES.OBJECT_EXPRESSION) {
2497
+ checkExportItemsCase({
2498
+ context,
2499
+ items: declaration.properties,
2500
+ itemsType: "properties",
2501
+ exportnameCase
2502
+ });
2503
+ return;
2504
+ }
2505
+
2506
+ const objectName = declaration.type === TYPES.IDENTIFIER ? declaration.name : (_declaration$id = declaration.id) === null || _declaration$id === void 0 ? void 0 : _declaration$id.name;
2507
+ reportExportCaseMismatch({
2508
+ context,
2509
+ node,
2510
+ exportnameCase,
2511
+ objectName
2512
+ });
2513
+ };
2514
+
2515
+ const checkExportnameCase = (context, exportNodes, exportnameCase) => {
2516
+ exportNodes.forEach(node => {
2517
+ const isNamedExport = node.type === TYPES.EXPORT_NAMED_DECLARATION;
2518
+
2519
+ if (isNamedExport) {
2520
+ checkNamedExportCase(context, node, exportnameCase);
2521
+ } else {
2522
+ checkDefaultExportCase(context, node, exportnameCase);
2523
+ }
2524
+ });
2525
+ };
2526
+
2527
+ const checkFilenameAndExportname = (context, exportNodes) => {
2528
+ var _defaultExportNode$de;
2529
+
2530
+ const [filename] = getFilenameAndExtension(context);
2531
+ const defaultExportNode = exportNodes.find(node => node.type === TYPES.EXPORT_DEFAULT_DECLARATION);
2532
+ if (!defaultExportNode) return;
2533
+ const exportedObjectName = (_defaultExportNode$de = defaultExportNode.declaration) === null || _defaultExportNode$de === void 0 ? void 0 : _defaultExportNode$de.name;
2534
+ if (!exportedObjectName) return;
2535
+ const pathKeys = context.getFilename().split(/\.|\//g).slice(0, -1);
2536
+ const pathString = filename === "index" ? pathKeys.slice(0, -1).join("") : pathKeys.join("");
2537
+ const isNameMatches = pathString.endsWith(exportedObjectName);
2538
+ if (isNameMatches) return;
2539
+ context.report({
2540
+ node: defaultExportNode,
2541
+ message: EXPORTED_OBJECT_AND_FILENAME_SHOULD_MATCH_MESSAGE
2542
+ });
2543
+ };
2544
+
2545
+ var fileNameAndExportNameStandards = {
2546
+ meta: {
2547
+ type: "suggestion",
2548
+ docs: {
2549
+ description: "Allows you to enforce a consistent naming pattern for the filenames and exports."
2550
+ }
2551
+ },
2552
+ create: context => ({
2553
+ Program(node) {
2554
+ if (!isInsideBaseDirectory(context)) return;
2555
+ const defaultConfig = context.options[0].default;
2556
+ const configs = context.options[0].configs;
2557
+ const {
2558
+ filenameCase,
2559
+ exportnameCase,
2560
+ matchFileNameAndExportName
2561
+ } = findMatchedConfig(context, configs) || defaultConfig;
2562
+
2563
+ if (filenameCase) {
2564
+ checkFilenameCase(context, node, filenameCase);
2565
+ }
2566
+
2567
+ if (exportnameCase || matchFileNameAndExportName) {
2568
+ const exportNodes = findMatchingNodesDeep(node, EXPORT_PATTERN);
2569
+
2570
+ if (exportnameCase) {
2571
+ checkExportnameCase(context, exportNodes, exportnameCase);
2572
+ }
2573
+
2574
+ if (matchFileNameAndExportName) {
2575
+ checkFilenameAndExportname(context, exportNodes);
2576
+ }
2577
+ }
2578
+ }
2579
+
2580
+ })
2581
+ };
2582
+
2583
+ const ASSIGNMENT_PATTERNS = [{
2584
+ id: {
2585
+ type: TYPES.OBJECT_PATTERN
1309
2586
  }
1310
2587
  }, {
1311
2588
  id: {
1312
- type: "Identifier"
2589
+ type: TYPES.IDENTIFIER
1313
2590
  }
1314
2591
  }];
1315
2592
  const IDENTIFIER_INITIALIZATION_PATTERN = {
1316
- type: "Identifier",
2593
+ type: TYPES.IDENTIFIER,
1317
2594
  name: "globalProps"
1318
2595
  };
1319
2596
  const MEMBER_EXPRESSION_INITIALIZATION_PATTERN = {
1320
- type: "MemberExpression",
2597
+ type: TYPES.MEMBER_EXPRESSION,
1321
2598
  object: {
1322
- type: "Identifier",
2599
+ type: TYPES.IDENTIFIER,
1323
2600
  name: "globalProps"
1324
2601
  }
1325
2602
  };
1326
2603
  const GLOBALPROPS_REASSIGNMENT_PATTERN = {
1327
- type: "Identifier",
2604
+ type: TYPES.IDENTIFIER,
1328
2605
  name: "globalProps"
1329
2606
  };
1330
2607
 
@@ -1370,7 +2647,59 @@
1370
2647
  })
1371
2648
  };
1372
2649
 
1373
- const reportSuggestion = ({
2650
+ const storeImportPattern = name => ({
2651
+ specifiers: [{
2652
+ type: "ImportDefaultSpecifier",
2653
+ local: {
2654
+ type: TYPES.IDENTIFIER,
2655
+ name
2656
+ }
2657
+ }],
2658
+ source: {
2659
+ type: TYPES.LITERAL,
2660
+ value: ramda.startsWith("stores/")
2661
+ }
2662
+ }); // import useSampleStore from "stores/sampleStore";
2663
+ // .....
2664
+ // const { order } = useSampleStore();
2665
+
2666
+
2667
+ const ZUSTAND_HOOK_USAGE_PATTERN = {
2668
+ kind: "const",
2669
+ declarations: [{
2670
+ type: TYPES.VARIABLE_DECLARATOR,
2671
+ init: {
2672
+ type: TYPES.CALL_EXPRESSION,
2673
+ callee: {
2674
+ type: TYPES.IDENTIFIER,
2675
+ name: (name, root) => name.match(/use[a-zA-z0-9].+Store/) && existsBy$1(storeImportPattern(name), getAllImports(root))
2676
+ },
2677
+ arguments: ramda.isEmpty,
2678
+ optional: false
2679
+ }
2680
+ }]
2681
+ };
2682
+
2683
+ var minimizeZustandStoreAccessScope = {
2684
+ meta: {
2685
+ type: "problem",
2686
+ docs: {
2687
+ description: "Use function based accessor for obtaining values from zustand stores. Using state as a whole is not recommended."
2688
+ }
2689
+ },
2690
+ create: context => ({
2691
+ VariableDeclaration(node) {
2692
+ if (!matches(ZUSTAND_HOOK_USAGE_PATTERN, node)) return;
2693
+ context.report({
2694
+ node,
2695
+ message: DONT_USE_ZUSTAND_STORE_WITHOUT_SELECTOR
2696
+ });
2697
+ }
2698
+
2699
+ })
2700
+ };
2701
+
2702
+ const reportSuggestion$1 = ({
1374
2703
  context,
1375
2704
  node,
1376
2705
  fix,
@@ -1466,6 +2795,57 @@
1466
2795
  type: TYPES.IDENTIFIER,
1467
2796
  name: "length"
1468
2797
  }
2798
+ }; // string.charAt(0).toUpperCase()
2799
+
2800
+ const CAPITALIZE_LEFT_PATTERN = {
2801
+ type: TYPES.CALL_EXPRESSION,
2802
+ callee: {
2803
+ type: TYPES.MEMBER_EXPRESSION,
2804
+ object: {
2805
+ type: TYPES.CALL_EXPRESSION,
2806
+ callee: {
2807
+ type: TYPES.MEMBER_EXPRESSION,
2808
+ object: {
2809
+ type: TYPES.IDENTIFIER,
2810
+ name: (name, root) => {
2811
+ var _root$right$callee, _root$right$callee$ob, _root$right$expressio, _root$right$expressio2, _root$right$expressio3;
2812
+
2813
+ return name === ((_root$right$callee = root.right.callee) === null || _root$right$callee === void 0 ? void 0 : (_root$right$callee$ob = _root$right$callee.object) === null || _root$right$callee$ob === void 0 ? void 0 : _root$right$callee$ob.name) || ((_root$right$expressio = root.right.expression) === null || _root$right$expressio === void 0 ? void 0 : (_root$right$expressio2 = _root$right$expressio.callee) === null || _root$right$expressio2 === void 0 ? void 0 : (_root$right$expressio3 = _root$right$expressio2.object) === null || _root$right$expressio3 === void 0 ? void 0 : _root$right$expressio3.name);
2814
+ }
2815
+ },
2816
+ property: {
2817
+ type: TYPES.IDENTIFIER,
2818
+ name: "charAt"
2819
+ }
2820
+ },
2821
+ arguments: args => args.length === 1 && matches([{
2822
+ type: TYPES.LITERAL,
2823
+ value: 0
2824
+ }], args)
2825
+ },
2826
+ property: {
2827
+ type: TYPES.IDENTIFIER,
2828
+ name: "toUpperCase"
2829
+ }
2830
+ }
2831
+ }; // string.slice(1)
2832
+
2833
+ const CAPITALIZE_RIGHT_PATTERN = {
2834
+ type: TYPES.CALL_EXPRESSION,
2835
+ callee: {
2836
+ type: TYPES.MEMBER_EXPRESSION,
2837
+ object: {
2838
+ type: TYPES.IDENTIFIER
2839
+ },
2840
+ property: {
2841
+ type: TYPES.IDENTIFIER,
2842
+ name: "slice"
2843
+ }
2844
+ },
2845
+ arguments: args => args.length === 1 && matches([{
2846
+ type: TYPES.LITERAL,
2847
+ value: 1
2848
+ }], args)
1469
2849
  };
1470
2850
  const OBJ_KEY_LENGTH_PATTERN$1 = {
1471
2851
  type: TYPES.MEMBER_EXPRESSION,
@@ -1493,41 +2873,44 @@
1493
2873
  async: false,
1494
2874
  expression: false,
1495
2875
  body: {
1496
- type: "BlockStatement",
2876
+ type: TYPES.BLOCK_STATEMENT,
1497
2877
  body: body => ramda.isEmpty(body)
2878
+ },
2879
+ parent: {
2880
+ type: notEquals(TYPES.EXPORT_DEFAULT_DECLARATION)
1498
2881
  }
1499
2882
  };
1500
2883
  const LABEL_AND_VALUE_PATTERN = {
1501
2884
  properties: props => props.length === 2 && props.every(matches({
1502
- type: "Property",
2885
+ type: TYPES.PROPERTY,
1503
2886
  computed: false,
1504
2887
  key: {
1505
- type: "Identifier"
2888
+ type: TYPES.IDENTIFIER
1506
2889
  },
1507
2890
  value: {
1508
- type: ramda.includes(ramda.__, ["Literal", "Identifier", "MemberExpression"])
2891
+ type: ramda.includes(ramda.__, [TYPES.LITERAL, TYPES.IDENTIFIER, TYPES.MEMBER_EXPRESSION])
1509
2892
  }
1510
2893
  })) && ramda.equals(["label", "value"], props.map(ramda.path(["key", "name"])).sort())
1511
2894
  };
1512
2895
  const DYNAMIC_ARRAY_PATTERN = {
1513
2896
  callee: {
1514
- type: "MemberExpression",
2897
+ type: TYPES.MEMBER_EXPRESSION,
1515
2898
  object: {
1516
- type: "Identifier",
2899
+ type: TYPES.IDENTIFIER,
1517
2900
  name: "Array"
1518
2901
  },
1519
2902
  property: {
1520
- type: "Identifier",
2903
+ type: TYPES.IDENTIFIER,
1521
2904
  name: "from"
1522
2905
  }
1523
2906
  },
1524
2907
  arguments: args => args.length === 2 && matches({
1525
2908
  0: {
1526
- type: "ObjectExpression",
2909
+ type: TYPES.OBJECT_EXPRESSION,
1527
2910
  properties: props => props.length === 1 && props[0].key.name === "length"
1528
2911
  },
1529
2912
  1: {
1530
- type: "ArrowFunctionExpression"
2913
+ type: TYPES.ARROW_FUNCTION_EXPRESSION
1531
2914
  }
1532
2915
  }, args)
1533
2916
  };
@@ -1536,7 +2919,11 @@
1536
2919
  type: TYPES.LOGICAL_EXPRESSION,
1537
2920
  operator: "&&",
1538
2921
  left: NOT_NIL_BINARY_EXP_PATTERN,
1539
- right: NOT_NIL_BINARY_EXP_PATTERN
2922
+ right: (right, root) => {
2923
+ var _right$left, _root$left, _root$left$left;
2924
+
2925
+ return matches(NOT_NIL_BINARY_EXP_PATTERN, right) && ((_right$left = right.left) === null || _right$left === void 0 ? void 0 : _right$left.name) === ((_root$left = root.left) === null || _root$left === void 0 ? void 0 : (_root$left$left = _root$left.left) === null || _root$left$left === void 0 ? void 0 : _root$left$left.name);
2926
+ }
1540
2927
  }, // x => !isNil(x)
1541
2928
  {
1542
2929
  type: TYPES.ARROW_FUNCTION_EXPRESSION,
@@ -1551,7 +2938,14 @@
1551
2938
  type: TYPES.IDENTIFIER,
1552
2939
  name: "isNil"
1553
2940
  },
1554
- arguments: args => args.length === 1 && args[0].type === TYPES.IDENTIFIER
2941
+ arguments: (args, root) => args.length === 1 && matches([{
2942
+ type: TYPES.IDENTIFIER,
2943
+ name: name => {
2944
+ var _root$params$;
2945
+
2946
+ return name === ((_root$params$ = root.params[0]) === null || _root$params$ === void 0 ? void 0 : _root$params$.name);
2947
+ }
2948
+ }], args)
1555
2949
  }
1556
2950
  }
1557
2951
  }];
@@ -1574,6 +2968,17 @@
1574
2968
  type: matchesAny([TYPES.IF_STATEMENT, TYPES.WHILE_STATEMENT]),
1575
2969
  test: matchesAny([ARRAY_LENGTH_PATTERN$1, OBJ_KEY_LENGTH_PATTERN$1])
1576
2970
  },
2971
+ // !!array.length, !!Object.keys(obj).length
2972
+ UNARY_EXP: {
2973
+ type: TYPES.UNARY_EXPRESSION,
2974
+ operator: "!",
2975
+ prefix: true,
2976
+ argument: matchesAny([ARRAY_LENGTH_PATTERN$1, OBJ_KEY_LENGTH_PATTERN$1]),
2977
+ parent: {
2978
+ type: TYPES.UNARY_EXPRESSION,
2979
+ operator: "!"
2980
+ }
2981
+ },
1577
2982
  // x => !isEmpty(x)
1578
2983
  ARROW_FUNC: {
1579
2984
  type: TYPES.ARROW_FUNCTION_EXPRESSION,
@@ -1595,70 +3000,94 @@
1595
3000
  };
1596
3001
  const REPLACE_BY_PATTERN = {
1597
3002
  callee: {
1598
- type: "MemberExpression",
3003
+ type: TYPES.MEMBER_EXPRESSION,
1599
3004
  property: {
1600
- type: "Identifier",
3005
+ type: TYPES.IDENTIFIER,
1601
3006
  name: "map"
1602
3007
  }
1603
3008
  },
1604
3009
  arguments: [{
1605
- type: "ArrowFunctionExpression",
3010
+ type: TYPES.ARROW_FUNCTION_EXPRESSION,
1606
3011
  generator: false,
1607
3012
  async: false,
1608
3013
  expression: true,
1609
- params: params => params.length === 1 && params[0].type === "Identifier",
3014
+ params: params => params.length === 1 && params[0].type === TYPES.IDENTIFIER,
1610
3015
  body: {
1611
- type: "ConditionalExpression",
3016
+ type: TYPES.CONDITIONAL_EXPRESSION,
1612
3017
  test: (test, root) => areAllChecksWithParams(test, arrayFuncParam(root), {
1613
3018
  compare: "===",
1614
3019
  join: "&&"
1615
3020
  }),
3021
+ consequent: (consq, root) => ramda.not(ramda.any(patternExistsDeep({
3022
+ type: TYPES.IDENTIFIER,
3023
+ name: name => name === arrayFuncParam(root).name
3024
+ }), consq.type === TYPES.OBJECT_EXPRESSION ? consq.properties : [consq])),
1616
3025
  alternate: {
1617
- type: "Identifier",
3026
+ type: TYPES.IDENTIFIER,
1618
3027
  name: (name, root) => name === arrayFuncParam(root).name
1619
3028
  }
1620
3029
  }
1621
3030
  }]
1622
3031
  };
1623
3032
  const REPLACE_BY_NEGATED_PATTERN = ramda.assocPath(["arguments", 0, "body"], {
1624
- type: "ConditionalExpression",
3033
+ type: TYPES.CONDITIONAL_EXPRESSION,
1625
3034
  test: (test, root) => areAllChecksWithParams(test, arrayFuncParam(root), {
1626
3035
  compare: "!==",
1627
3036
  join: "||"
1628
3037
  }),
1629
3038
  consequent: {
1630
- type: "Identifier",
3039
+ type: TYPES.IDENTIFIER,
1631
3040
  name: (name, root) => name === arrayFuncParam(root).name
1632
- }
3041
+ },
3042
+ alternate: (alt, root) => ramda.not(ramda.any(patternExistsDeep({
3043
+ type: TYPES.IDENTIFIER,
3044
+ name: name => name === arrayFuncParam(root).name
3045
+ }), alt.type === TYPES.OBJECT_EXPRESSION ? alt.properties : [alt]))
1633
3046
  }, REPLACE_BY_PATTERN);
1634
3047
  const COPY_KEYS_PATTERN = {
1635
- properties: props => props.length > 1 && matches({
1636
- type: "SpreadElement",
1637
- argument: {
1638
- type: "Identifier"
3048
+ type: TYPES.CALL_EXPRESSION,
3049
+ callee: {
3050
+ type: TYPES.MEMBER_EXPRESSION,
3051
+ property: {
3052
+ type: TYPES.IDENTIFIER,
3053
+ name: "map"
1639
3054
  }
1640
- }, props[0]) && props.slice(1).every(matches({
1641
- type: "Property",
1642
- kind: "init",
1643
- method: false,
1644
- computed: false,
1645
- shorthand: false,
1646
- key: {
1647
- type: "Identifier"
1648
- },
1649
- value: {
1650
- type: "MemberExpression",
1651
- computed: false,
1652
- optional: false,
1653
- object: {
1654
- type: "Identifier",
1655
- name: props[0].argument.name
1656
- },
1657
- property: {
1658
- type: "Identifier"
1659
- }
3055
+ },
3056
+ arguments: [{
3057
+ type: TYPES.ARROW_FUNCTION_EXPRESSION,
3058
+ params: params => params.length === 1 && params[0].type === TYPES.IDENTIFIER,
3059
+ body: {
3060
+ type: TYPES.OBJECT_EXPRESSION,
3061
+ properties: (props, root) => props.length > 1 && matches({
3062
+ type: TYPES.SPREAD_ELEMENT,
3063
+ argument: {
3064
+ type: TYPES.IDENTIFIER,
3065
+ name: root.arguments[0].params[0].name
3066
+ }
3067
+ }, props[0]) && props.slice(1).every(matches({
3068
+ type: TYPES.PROPERTY,
3069
+ kind: "init",
3070
+ method: false,
3071
+ computed: false,
3072
+ shorthand: false,
3073
+ key: {
3074
+ type: TYPES.IDENTIFIER
3075
+ },
3076
+ value: {
3077
+ type: TYPES.MEMBER_EXPRESSION,
3078
+ computed: false,
3079
+ optional: false,
3080
+ object: {
3081
+ type: TYPES.IDENTIFIER,
3082
+ name: props[0].argument.name
3083
+ },
3084
+ property: {
3085
+ type: TYPES.IDENTIFIER
3086
+ }
3087
+ }
3088
+ }))
1660
3089
  }
1661
- }))
3090
+ }]
1662
3091
  };
1663
3092
  const NOT_EQUALS_PATTERNS = {
1664
3093
  // !Object.is(item1, item2)
@@ -1715,66 +3144,29 @@
1715
3144
  }
1716
3145
  }
1717
3146
  };
1718
- const CAPITALIZE_PATTERN = {
1719
- // string.charAt(0).toUpperCase() + string.slice(1)
1720
- type: TYPES.BINARY_EXPRESSION,
3147
+ const CAPITALIZE_PATTERNS = [// string.charAt(0).toUpperCase() + string.slice(1)
3148
+ {
3149
+ operator: "+",
3150
+ left: CAPITALIZE_LEFT_PATTERN,
3151
+ right: CAPITALIZE_RIGHT_PATTERN
3152
+ }, // string?.charAt(0).toUpperCase() + string?.slice(1)
3153
+ {
1721
3154
  operator: "+",
1722
3155
  left: {
1723
- type: TYPES.CALL_EXPRESSION,
1724
- callee: {
1725
- type: TYPES.MEMBER_EXPRESSION,
1726
- object: {
1727
- type: TYPES.CALL_EXPRESSION,
1728
- callee: {
1729
- type: TYPES.MEMBER_EXPRESSION,
1730
- object: {
1731
- type: TYPES.IDENTIFIER,
1732
- name: (name, root) => {
1733
- var _root$right$callee, _root$right$callee$ob;
1734
-
1735
- return name === ((_root$right$callee = root.right.callee) === null || _root$right$callee === void 0 ? void 0 : (_root$right$callee$ob = _root$right$callee.object) === null || _root$right$callee$ob === void 0 ? void 0 : _root$right$callee$ob.name);
1736
- }
1737
- },
1738
- property: {
1739
- type: TYPES.IDENTIFIER,
1740
- name: "charAt"
1741
- }
1742
- },
1743
- arguments: args => args.length === 1 && matches([{
1744
- type: TYPES.LITERAL,
1745
- value: 0
1746
- }], args)
1747
- },
1748
- property: {
1749
- type: TYPES.IDENTIFIER,
1750
- name: "toUpperCase"
1751
- }
1752
- }
3156
+ type: TYPES.CHAIN_EXPRESSION,
3157
+ expression: CAPITALIZE_LEFT_PATTERN
1753
3158
  },
1754
3159
  right: {
1755
- type: TYPES.CALL_EXPRESSION,
1756
- callee: {
1757
- type: TYPES.MEMBER_EXPRESSION,
1758
- object: {
1759
- type: TYPES.IDENTIFIER
1760
- },
1761
- property: {
1762
- type: TYPES.IDENTIFIER,
1763
- name: "slice"
1764
- }
1765
- },
1766
- arguments: args => args.length === 1 && matches([{
1767
- type: TYPES.LITERAL,
1768
- value: 1
1769
- }], args)
3160
+ type: TYPES.CHAIN_EXPRESSION,
3161
+ expression: CAPITALIZE_RIGHT_PATTERN
1770
3162
  }
1771
- };
3163
+ }];
1772
3164
  const COUNT_BY_PATTERN = {
1773
- type: "MemberExpression",
3165
+ type: TYPES.MEMBER_EXPRESSION,
1774
3166
  computed: false,
1775
3167
  optional: false,
1776
3168
  property: {
1777
- type: "Identifier",
3169
+ type: TYPES.IDENTIFIER,
1778
3170
  name: "length"
1779
3171
  }
1780
3172
  };
@@ -1815,11 +3207,14 @@
1815
3207
  array = getCode$1(context, node.callee.object);
1816
3208
  } else if (matches(genericPatterns.RAMDA, node)) {
1817
3209
  array = getCode$1(context, node.arguments[1]);
1818
- } else return; // arr.filter(x => x.prop === something).length
3210
+ } else return;
1819
3211
 
3212
+ const byIdFunc = optionalChainingOptimizedName(functions.byId, node.callee);
3213
+ const byFunc = optionalChainingOptimizedName(functions.by, node.callee); // arr.filter(x => x.prop === something).length
1820
3214
 
1821
3215
  if (functions.by === "filterBy" && matches(COUNT_BY_PATTERN, node.parent)) {
1822
- const message = canBeShortenedWithCommons("countBy");
3216
+ const func = optionalChainingOptimizedName("countBy", node.callee);
3217
+ const message = canBeShortenedWithCommons(func);
1823
3218
  context.report({
1824
3219
  node: node.parent,
1825
3220
  message
@@ -1839,15 +3234,15 @@
1839
3234
 
1840
3235
  if (idUsagePattern) {
1841
3236
  const id = matches(idUsagePattern, predicate.body.left) ? getCode$1(context, predicate.body.right) : getCode$1(context, predicate.body.left);
1842
- const fix = `${functions.byId}(${id}, ${array})`;
1843
- reportSuggestion({
3237
+ const fix = `${byIdFunc}(${id}, ${array})`;
3238
+ reportSuggestion$1({
1844
3239
  context,
1845
3240
  node,
1846
3241
  fix,
1847
- func: functions.byId
3242
+ func: byIdFunc
1848
3243
  });
1849
3244
  } else {
1850
- const message = canBeShortenedWithCommons(functions.by);
3245
+ const message = canBeShortenedWithCommons(byFunc);
1851
3246
  context.report({
1852
3247
  node,
1853
3248
  message
@@ -1856,7 +3251,7 @@
1856
3251
  } else {
1857
3252
  context.report({
1858
3253
  node,
1859
- message: canBeShortenedWithCommons(functions.by)
3254
+ message: canBeShortenedWithCommons(byFunc)
1860
3255
  });
1861
3256
  }
1862
3257
  };
@@ -1989,45 +3384,50 @@
1989
3384
  var capitalize = {
1990
3385
  operateOn: TYPES.BINARY_EXPRESSION,
1991
3386
  check: (context, node) => {
1992
- if (!matches(CAPITALIZE_PATTERN, node)) return;
1993
- const fix = `capitalize(${getCode$1(context, node.right.callee.object)})`;
1994
- reportSuggestion({
3387
+ if (!matchesAny(CAPITALIZE_PATTERNS, node)) return;
3388
+ const stringNode = node.right.type === TYPES.CHAIN_EXPRESSION ? node.right.expression.callee.object : node.right.callee.object;
3389
+ const func = optionalChainingOptimizedName("capitalize", node.right);
3390
+ const fix = `${func}(${getCode$1(context, stringNode)})`;
3391
+ reportSuggestion$1({
1995
3392
  context,
1996
3393
  node,
1997
3394
  fix,
1998
- func: "capitalize"
3395
+ func
1999
3396
  });
2000
3397
  }
2001
3398
  };
2002
3399
 
2003
3400
  var copyKeys = {
2004
- operateOn: TYPES.OBJECT_EXPRESSION,
3401
+ operateOn: TYPES.CALL_EXPRESSION,
2005
3402
  check: (context, node) => {
2006
3403
  if (!matches(COPY_KEYS_PATTERN, node)) return;
2007
- const keyValuePairs = node.properties.slice(1).map(prop => [prop.value.property.name, prop.key.name]);
3404
+ const keyValuePairs = node.arguments[0].body.properties.slice(1).map(prop => [prop.value.property.name, prop.key.name]);
2008
3405
  const keyMap = JSON.stringify(ramda.fromPairs(keyValuePairs));
2009
- const sourceObject = getCode$1(context, node.properties[0].argument);
2010
- const fix = `copyKeys(${keyMap}, ${sourceObject})`;
2011
- reportSuggestion({
3406
+ const sourceObject = getCode$1(context, node.callee.object);
3407
+ const func = optionalChainingOptimizedName("copyKeys", node.callee);
3408
+ const fix = `${func}(${keyMap}, ${sourceObject})`;
3409
+ reportSuggestion$1({
2012
3410
  context,
2013
3411
  node,
2014
3412
  fix,
2015
- func: "copyKeys"
3413
+ func
2016
3414
  });
2017
3415
  }
2018
3416
  };
2019
3417
 
2020
3418
  var dynamicArray = {
2021
- operateOn: "CallExpression",
3419
+ operateOn: TYPES.CALL_EXPRESSION,
2022
3420
  check: (context, node) => {
2023
3421
  var _node$arguments$1$par;
2024
3422
 
2025
3423
  if (!matches(DYNAMIC_ARRAY_PATTERN, node)) return;
2026
3424
  const length = getCode$1(context, node.arguments[0].properties[0].value);
2027
- const elementGenIndexParam = (_node$arguments$1$par = node.arguments[1].params[1]) === null || _node$arguments$1$par === void 0 ? void 0 : _node$arguments$1$par.name;
2028
- const elementGenBody = getCode$1(context, node.arguments[1].body);
2029
- const fix = `dynamicArray(${length}, ${elementGenIndexParam || "()"} => ${elementGenBody})`;
2030
- reportSuggestion({
3425
+ const indexParam = (_node$arguments$1$par = node.arguments[1].params[1]) === null || _node$arguments$1$par === void 0 ? void 0 : _node$arguments$1$par.name;
3426
+ const generatorBody = getCode$1(context, node.arguments[1].body);
3427
+ const isArrOrObjExp = [TYPES.ARRAY_EXPRESSION, TYPES.OBJECT_EXPRESSION].includes(node.arguments[1].body.type);
3428
+ const generator = `${indexParam || "()"} => ${isArrOrObjExp ? `(${generatorBody})` : generatorBody}`;
3429
+ const fix = `dynamicArray(${length}, ${generator})`;
3430
+ reportSuggestion$1({
2031
3431
  context,
2032
3432
  node,
2033
3433
  fix,
@@ -2041,13 +3441,11 @@
2041
3441
  check: (context, node) => {
2042
3442
  let fix = null;
2043
3443
 
2044
- if (node.type === TYPES.UNARY_EXPRESSION) {
2045
- if (!matches(NOT_EQUALS_PATTERNS.UNARY_EXP, node)) return;
3444
+ if (matches(NOT_EQUALS_PATTERNS.UNARY_EXP, node)) {
2046
3445
  const first = getCode$1(context, node.argument.arguments[0]);
2047
3446
  const second = getCode$1(context, node.argument.arguments[1]);
2048
3447
  fix = `isNot(${first}, ${second})`;
2049
- } else {
2050
- if (!matches(NOT_EQUALS_PATTERNS.ARROW_FUNC, node)) return;
3448
+ } else if (matches(NOT_EQUALS_PATTERNS.ARROW_FUNC, node)) {
2051
3449
  const argumentName = node.params[0].name;
2052
3450
  let externalValueNode = null;
2053
3451
 
@@ -2057,11 +3455,18 @@
2057
3455
  externalValueNode = node.body.left;
2058
3456
  } else return;
2059
3457
 
3458
+ if (patternExistsDeep({
3459
+ type: TYPES.IDENTIFIER,
3460
+ name: argumentName
3461
+ }, externalValueNode)) {
3462
+ return;
3463
+ }
3464
+
2060
3465
  const externalValue = getCode$1(context, externalValueNode);
2061
3466
  fix = `isNot(${externalValue})`;
2062
- }
3467
+ } else return;
2063
3468
 
2064
- reportSuggestion({
3469
+ reportSuggestion$1({
2065
3470
  context,
2066
3471
  node,
2067
3472
  fix,
@@ -2071,24 +3476,28 @@
2071
3476
  };
2072
3477
 
2073
3478
  var isNotEmpty = {
2074
- operateOn: [TYPES.IF_STATEMENT, TYPES.WHILE_STATEMENT, TYPES.BINARY_EXPRESSION, TYPES.ARROW_FUNCTION_EXPRESSION],
3479
+ operateOn: [TYPES.IF_STATEMENT, TYPES.WHILE_STATEMENT, TYPES.BINARY_EXPRESSION, TYPES.ARROW_FUNCTION_EXPRESSION, TYPES.UNARY_EXPRESSION],
2075
3480
  check: (context, node) => {
2076
- const isBinaryExp = node.type === TYPES.BINARY_EXPRESSION;
2077
- const isArrowFunc = node.type === TYPES.ARROW_FUNCTION_EXPRESSION;
2078
- const isCondStat = node.type === TYPES.IF_STATEMENT || node.type === TYPES.WHILE_STATEMENT;
2079
- if (isBinaryExp && !matches(NOT_EMPTY_PATTERNS.BINARY_EXP, node)) return;
2080
- if (isArrowFunc && !matches(NOT_EMPTY_PATTERNS.ARROW_FUNC, node)) return;
2081
- if (isCondStat && !matches(NOT_EMPTY_PATTERNS.CONDT_STAT, node)) return;
2082
3481
  let fix = null;
2083
3482
  let message = "";
2084
3483
  let nodeToBeReplaced = node;
2085
3484
 
2086
- if (isArrowFunc) {
3485
+ if (matches(NOT_EMPTY_PATTERNS.ARROW_FUNC, node)) {
2087
3486
  fix = "isNotEmpty";
2088
- } else {
2089
- const expNode = isBinaryExp ? node.left : node.test;
3487
+ } else if (matchesAny([NOT_EMPTY_PATTERNS.BINARY_EXP, NOT_EMPTY_PATTERNS.CONDT_STAT, NOT_EMPTY_PATTERNS.UNARY_EXP], node)) {
3488
+ const expNode = {
3489
+ [TYPES.BINARY_EXPRESSION]: node.left,
3490
+ [TYPES.UNARY_EXPRESSION]: node.argument,
3491
+ [TYPES.IF_STATEMENT]: node.test,
3492
+ [TYPES.WHILE_STATEMENT]: node.test
3493
+ }[node.type];
2090
3494
  const isObjLenCheck = matches(OBJ_KEY_LENGTH_PATTERN$1, expNode);
2091
- nodeToBeReplaced = isBinaryExp ? node : node.test;
3495
+ nodeToBeReplaced = {
3496
+ [TYPES.BINARY_EXPRESSION]: node,
3497
+ [TYPES.UNARY_EXPRESSION]: node.parent,
3498
+ [TYPES.IF_STATEMENT]: node.test,
3499
+ [TYPES.WHILE_STATEMENT]: node.test
3500
+ }[node.type];
2092
3501
 
2093
3502
  if (isObjLenCheck) {
2094
3503
  const objName = getCode$1(context, expNode.object.arguments[0]);
@@ -2098,9 +3507,9 @@
2098
3507
  fix = `isNotEmpty(${arrName})`;
2099
3508
  message = `Can be replaced with: ${fix}, if '${arrName}' is an array or string.`;
2100
3509
  }
2101
- }
3510
+ } else return;
2102
3511
 
2103
- reportSuggestion({
3512
+ reportSuggestion$1({
2104
3513
  context,
2105
3514
  node: nodeToBeReplaced,
2106
3515
  fix,
@@ -2115,13 +3524,11 @@
2115
3524
  check: (context, node) => {
2116
3525
  let fix = null;
2117
3526
 
2118
- if (node.type === TYPES.BINARY_EXPRESSION) {
2119
- if (!matches(NOT_EQUALS_DEEP_PATTERNS.BINARY_EXP, node)) return;
3527
+ if (matches(NOT_EQUALS_DEEP_PATTERNS.BINARY_EXP, node)) {
2120
3528
  const first = getCode$1(context, node.left.arguments[0]);
2121
3529
  const second = getCode$1(context, node.right.arguments[0]);
2122
3530
  fix = `isNotEqualDeep(${first}, ${second})`;
2123
- } else {
2124
- if (!matches(NOT_EQUALS_DEEP_PATTERNS.ARROW_FUNC, node)) return;
3531
+ } else if (matches(NOT_EQUALS_DEEP_PATTERNS.ARROW_FUNC, node)) {
2125
3532
  const argumentName = node.params[0].name;
2126
3533
  let externalValueNode = null;
2127
3534
 
@@ -2133,9 +3540,9 @@
2133
3540
 
2134
3541
  const externalValue = getCode$1(context, externalValueNode);
2135
3542
  fix = `isNotEqualDeep(${externalValue})`;
2136
- }
3543
+ } else return;
2137
3544
 
2138
- reportSuggestion({
3545
+ reportSuggestion$1({
2139
3546
  context,
2140
3547
  node,
2141
3548
  fix,
@@ -2151,14 +3558,12 @@
2151
3558
  let fix = null;
2152
3559
 
2153
3560
  if (node.type === TYPES.ARROW_FUNCTION_EXPRESSION) {
2154
- if (node.params[0].name !== node.body.argument.arguments[0].name) return;
2155
3561
  fix = `isNotNil`;
2156
3562
  } else if (node.type === TYPES.LOGICAL_EXPRESSION) {
2157
- if (node.left.left.name !== node.right.left.name) return;
2158
- fix = `isNotNil(${node.left.left.name})`;
3563
+ fix = `isNotNil(${getCode$1(context, node.left.left)})`;
2159
3564
  }
2160
3565
 
2161
- reportSuggestion({
3566
+ reportSuggestion$1({
2162
3567
  context,
2163
3568
  node,
2164
3569
  fix,
@@ -2168,16 +3573,25 @@
2168
3573
  };
2169
3574
 
2170
3575
  var noop = {
2171
- operateOn: ["FunctionExpression", "ArrowFunctionExpression", "FunctionDeclaration"],
3576
+ operateOn: [TYPES.FUNCTION_EXPRESSION, TYPES.ARROW_FUNCTION_EXPRESSION, TYPES.FUNCTION_DECLARATION],
2172
3577
  check: (context, node) => {
2173
- if (matches(NOOP_PATTERN, node)) {
2174
- reportSuggestion({
2175
- context,
2176
- node,
2177
- fix: "noop",
2178
- func: "noop"
2179
- });
3578
+ if (!matches(NOOP_PATTERN, node)) return;
3579
+ let fix = "noop";
3580
+ let nodeToBeReplaced = node;
3581
+
3582
+ if (node.type === TYPES.FUNCTION_DECLARATION) {
3583
+ fix = `const ${node.id.name} = noop`;
3584
+ } else if (node.type === TYPES.FUNCTION_EXPRESSION && node.parent.type === TYPES.PROPERTY) {
3585
+ nodeToBeReplaced = node.parent;
3586
+ fix = `${node.parent.key.name}: noop`;
2180
3587
  }
3588
+
3589
+ reportSuggestion$1({
3590
+ context,
3591
+ node: nodeToBeReplaced,
3592
+ fix,
3593
+ func: "noop"
3594
+ });
2181
3595
  }
2182
3596
  };
2183
3597
 
@@ -2224,9 +3638,10 @@
2224
3638
  } else return;
2225
3639
 
2226
3640
  if (!matches(binaryExpressionPattern, comparison)) {
3641
+ const func = optionalChainingOptimizedName("replaceBy", node.callee);
2227
3642
  context.report({
2228
3643
  node,
2229
- message: canBeShortenedWithCommons("replaceBy")
3644
+ message: canBeShortenedWithCommons(func)
2230
3645
  });
2231
3646
  return;
2232
3647
  }
@@ -2244,25 +3659,26 @@
2244
3659
  const id = getCode$1(context, externalId);
2245
3660
  const replacement = getCode$1(context, replaceNode);
2246
3661
  const array = getCode$1(context, node.callee.object);
2247
- const fix = `replaceById(${id}, ${replacement}, ${array})`;
2248
- reportSuggestion({
3662
+ const func = optionalChainingOptimizedName("replaceById", node.callee);
3663
+ const fix = `${func}(${id}, ${replacement}, ${array})`;
3664
+ reportSuggestion$1({
2249
3665
  context,
2250
3666
  node,
2251
3667
  fix,
2252
- func: "replaceById"
3668
+ func
2253
3669
  });
2254
3670
  }
2255
3671
  };
2256
3672
 
2257
3673
  var toLabelAndValue = {
2258
- operateOn: "ObjectExpression",
3674
+ operateOn: TYPES.OBJECT_EXPRESSION,
2259
3675
  check: (context, node) => {
2260
3676
  if (!matches(LABEL_AND_VALUE_PATTERN, node)) return;
2261
3677
  const [label, value] = ramda.pluck("value", node.properties).map(node => getCode$1(context, node)); // order doesn't matter here
2262
3678
 
2263
3679
  if (label !== value) return;
2264
3680
  const fix = `toLabelAndValue(${label})`;
2265
- reportSuggestion({
3681
+ reportSuggestion$1({
2266
3682
  context,
2267
3683
  node,
2268
3684
  fix,
@@ -2322,10 +3738,11 @@
2322
3738
  create: context => ({
2323
3739
  ImportDeclaration(node) {
2324
3740
  const disallowSources = getPackagesAndAliases(context, BLACKLISTED_PACKAGES);
2325
- if (!disallowSources.includes(node.source.value)) return;
2326
- context.report({
3741
+ const impSrc = node.source.value;
3742
+ const pkgName = disallowSources.find(src => impSrc === src || impSrc.startsWith(`${src}/`));
3743
+ if (pkgName) context.report({
2327
3744
  node,
2328
- message: disallowUse(node.source.value)
3745
+ message: disallowUse(pkgName)
2329
3746
  });
2330
3747
  }
2331
3748
 
@@ -2393,22 +3810,22 @@
2393
3810
 
2394
3811
  const LOCALIZATION_CALL_PATTERNS = [{
2395
3812
  callee: {
2396
- type: "Identifier",
3813
+ type: TYPES.IDENTIFIER,
2397
3814
  name: "t"
2398
3815
  },
2399
3816
  arguments: [{
2400
- type: "Literal"
3817
+ type: TYPES.LITERAL
2401
3818
  }]
2402
3819
  }, {
2403
3820
  callee: {
2404
- type: "MemberExpression",
3821
+ type: TYPES.MEMBER_EXPRESSION,
2405
3822
  property: {
2406
- type: "Identifier",
3823
+ type: TYPES.IDENTIFIER,
2407
3824
  name: "t"
2408
3825
  }
2409
3826
  },
2410
3827
  arguments: [{
2411
- type: "Literal"
3828
+ type: TYPES.LITERAL
2412
3829
  }]
2413
3830
  }];
2414
3831
 
@@ -2546,20 +3963,20 @@
2546
3963
  specifiers: [{
2547
3964
  type: "ImportNamespaceSpecifier",
2548
3965
  local: {
2549
- type: "Identifier"
3966
+ type: TYPES.IDENTIFIER
2550
3967
  }
2551
3968
  }],
2552
3969
  source: {
2553
- type: "Literal",
3970
+ type: TYPES.LITERAL,
2554
3971
  value: "ramda"
2555
3972
  }
2556
3973
  };
2557
3974
 
2558
3975
  const ramdaUsage = identifierName => ({
2559
- type: "MemberExpression",
3976
+ type: TYPES.MEMBER_EXPRESSION,
2560
3977
  object: {
2561
3978
  name: identifierName,
2562
- type: "Identifier"
3979
+ type: TYPES.IDENTIFIER
2563
3980
  }
2564
3981
  });
2565
3982
 
@@ -2601,8 +4018,12 @@
2601
4018
  };
2602
4019
 
2603
4020
  const SPECIAL_CHARS_PATTERN = /^ +| +$|[\r\n\t\f\v&<>{}"'`\\]+/;
2604
-
2605
- const isReplaceableLiteral = node => node.expression.type === TYPES.LITERAL && typeof node.expression.value === "string" && !SPECIAL_CHARS_PATTERN.test(node.expression.value);
4021
+ const REPLACEABLE_LITERAL_PATTERN = {
4022
+ expression: {
4023
+ type: TYPES.LITERAL,
4024
+ value: value => typeof value === "string" && !SPECIAL_CHARS_PATTERN.test(value)
4025
+ }
4026
+ };
2606
4027
 
2607
4028
  var noRedundantJsxExpression = {
2608
4029
  meta: {
@@ -2614,7 +4035,7 @@
2614
4035
  },
2615
4036
  create: context => ({
2616
4037
  JSXExpressionContainer(node) {
2617
- if (!isReplaceableLiteral(node)) return;
4038
+ if (!matches(REPLACEABLE_LITERAL_PATTERN, node)) return;
2618
4039
  let fix = "";
2619
4040
 
2620
4041
  if (node.parent.type === TYPES.JSX_ELEMENT) {
@@ -2639,10 +4060,48 @@
2639
4060
  const ENDS_WITH_SPACES_PATTERN = / +$/;
2640
4061
  const STARTS_OR_ENDS_WITH_SPACES_PATTERN = /^ +| +$/;
2641
4062
  const STARTS_WITH_SPACES_PATTERN = /^ +/;
4063
+ const QUASI_WITH_SPECIAL_CHARACTERS_PATTERN = {
4064
+ value: {
4065
+ cooked: cooked => cooked.match(CHARACTERS_TO_IGNORE_PATTERN)
4066
+ }
4067
+ };
4068
+ const EXPRESSION_ONLY_PATTERN = {
4069
+ expressions: exps => exps.length === 1,
4070
+ quasis: quasis => quasis.length === 2 && matches([{
4071
+ value: {
4072
+ cooked: ""
4073
+ }
4074
+ }, {
4075
+ value: {
4076
+ cooked: ""
4077
+ }
4078
+ }], quasis)
4079
+ };
4080
+ const INSIDE_JSX_ELEMENT_PATTERN = {
4081
+ parent: {
4082
+ type: TYPES.JSX_EXPRESSION_CONTAINER,
4083
+ parent: {
4084
+ type: TYPES.JSX_ELEMENT
4085
+ }
4086
+ },
4087
+ quasis: quasis => {
4088
+ var _quasis$, _last;
4089
+
4090
+ return !((_quasis$ = quasis[0]) !== null && _quasis$ !== void 0 && _quasis$.value.cooked.match(STARTS_WITH_SPACES_PATTERN)) && !((_last = ramda.last(quasis)) !== null && _last !== void 0 && _last.value.cooked.match(ENDS_WITH_SPACES_PATTERN));
4091
+ }
4092
+ };
4093
+ const REPLACEABLE_QUASIS_ONLY_PATTERN = {
4094
+ expressions: exps => exps.length === 0,
4095
+ quasis: quasis => quasis.length === 1 && matches([{
4096
+ value: {
4097
+ cooked: cooked => !cooked.match(STARTS_OR_ENDS_WITH_SPACES_PATTERN)
4098
+ }
4099
+ }], quasis)
4100
+ };
2642
4101
 
2643
4102
  const doQusisHaveSpecialCharacters = ({
2644
4103
  quasis
2645
- }) => quasis.some(quasi => quasi.value.cooked.match(CHARACTERS_TO_IGNORE_PATTERN));
4104
+ }) => quasis.some(matches(QUASI_WITH_SPECIAL_CHARACTERS_PATTERN));
2646
4105
 
2647
4106
  const getTemplateContent = (context, {
2648
4107
  expressions,
@@ -2653,12 +4112,6 @@
2653
4112
  return `${acc}{${expressionCode}}${quasi}`;
2654
4113
  }, `${quasis[0].value.cooked}`);
2655
4114
 
2656
- const isExpressionOnly = node => node.expressions.length === 1 && node.quasis.length === 2 && node.quasis[0].value.cooked === "" && node.quasis[1].value.cooked === "";
2657
-
2658
- const isInsideJSXElement = node => node.parent.type === TYPES.JSX_EXPRESSION_CONTAINER && node.parent.parent.type === TYPES.JSX_ELEMENT && !node.quasis[0].value.cooked.match(STARTS_WITH_SPACES_PATTERN) && !ramda.last(node.quasis).value.cooked.match(ENDS_WITH_SPACES_PATTERN);
2659
-
2660
- const isReplaceableQuasiOnly = node => node.expressions.length === 0 && node.quasis.length === 1 && !node.quasis[0].value.cooked.match(STARTS_OR_ENDS_WITH_SPACES_PATTERN);
2661
-
2662
4115
  var noRedundantStringTemplates = {
2663
4116
  meta: {
2664
4117
  type: "problem",
@@ -2671,21 +4124,21 @@
2671
4124
  TemplateLiteral(node) {
2672
4125
  if (doQusisHaveSpecialCharacters(node)) return;
2673
4126
 
2674
- if (isExpressionOnly(node)) {
4127
+ if (matches(EXPRESSION_ONLY_PATTERN, node)) {
2675
4128
  const fix = getCode$1(context, node.expressions[0]);
2676
4129
  context.report({
2677
4130
  node,
2678
4131
  message: canBeReplacedWith(fix),
2679
4132
  fix: fixer => fixer.replaceText(node, fix)
2680
4133
  });
2681
- } else if (isInsideJSXElement(node)) {
4134
+ } else if (matches(INSIDE_JSX_ELEMENT_PATTERN, node)) {
2682
4135
  const fix = getTemplateContent(context, node);
2683
4136
  context.report({
2684
4137
  node,
2685
4138
  message: canBeReplacedWith(fix),
2686
4139
  fix: fixer => fixer.replaceText(node.parent, fix)
2687
4140
  });
2688
- } else if (isReplaceableQuasiOnly(node)) {
4141
+ } else if (matches(REPLACEABLE_QUASIS_ONLY_PATTERN, node)) {
2689
4142
  const fix = `"${node.quasis[0].value.cooked}"`;
2690
4143
  context.report({
2691
4144
  node,
@@ -2750,6 +4203,12 @@
2750
4203
  name: "length"
2751
4204
  }
2752
4205
  };
4206
+ const ARRAY_PATTERN = {
4207
+ body: {
4208
+ type: TYPES.ARRAY_EXPRESSION,
4209
+ elements: elmts => elmts.length === 2
4210
+ }
4211
+ };
2753
4212
  const OBJ_KEY_LENGTH_PATTERN = {
2754
4213
  type: TYPES.MEMBER_EXPRESSION,
2755
4214
  object: {
@@ -2774,97 +4233,113 @@
2774
4233
  const ARRAY_INSERTS_PATTERN = {
2775
4234
  APPEND: {
2776
4235
  // x => [...x, y]
2777
- params: [{
2778
- type: "Identifier"
2779
- }],
4236
+ params: params => params.length === 1 && params[0].type === TYPES.IDENTIFIER,
2780
4237
  body: {
2781
- type: "ArrayExpression",
4238
+ type: TYPES.ARRAY_EXPRESSION,
2782
4239
  elements: [{
2783
- type: "SpreadElement",
4240
+ type: TYPES.SPREAD_ELEMENT,
2784
4241
  argument: {
2785
- type: "Identifier"
4242
+ type: TYPES.IDENTIFIER,
4243
+ name: (name, root) => {
4244
+ var _root$params$;
4245
+
4246
+ return name === ((_root$params$ = root.params[0]) === null || _root$params$ === void 0 ? void 0 : _root$params$.name);
4247
+ }
2786
4248
  }
4249
+ }, {
4250
+ type: notEquals(TYPES.SPREAD_ELEMENT)
2787
4251
  }]
2788
4252
  }
2789
4253
  },
2790
4254
  PREPEND: {
2791
4255
  // x => [y, ...x]
2792
- params: [{
2793
- type: "Identifier"
2794
- }],
4256
+ params: params => params.length === 1 && params[0].type === TYPES.IDENTIFIER,
2795
4257
  body: {
2796
- type: "ArrayExpression",
2797
- elements: {
2798
- 1: {
2799
- type: "SpreadElement",
2800
- argument: {
2801
- type: "Identifier"
4258
+ type: TYPES.ARRAY_EXPRESSION,
4259
+ elements: [{
4260
+ type: notEquals(TYPES.SPREAD_ELEMENT)
4261
+ }, {
4262
+ type: TYPES.SPREAD_ELEMENT,
4263
+ argument: {
4264
+ type: TYPES.IDENTIFIER,
4265
+ name: (name, root) => {
4266
+ var _root$params$2;
4267
+
4268
+ return name === ((_root$params$2 = root.params[0]) === null || _root$params$2 === void 0 ? void 0 : _root$params$2.name);
2802
4269
  }
2803
4270
  }
2804
- }
4271
+ }]
2805
4272
  }
2806
4273
  },
2807
4274
  CONCAT: {
2808
4275
  // x => [...x, ...y]
2809
- params: [{
2810
- type: "Identifier"
2811
- }],
4276
+ params: params => params.length === 1 && params[0].type === TYPES.IDENTIFIER,
2812
4277
  body: {
2813
- type: "ArrayExpression",
4278
+ type: TYPES.ARRAY_EXPRESSION,
2814
4279
  elements: [{
2815
- type: "SpreadElement",
4280
+ type: TYPES.SPREAD_ELEMENT,
2816
4281
  argument: {
2817
- type: "Identifier"
4282
+ type: TYPES.IDENTIFIER,
4283
+ name: (name, root) => {
4284
+ var _root$params$3;
4285
+
4286
+ return name === ((_root$params$3 = root.params[0]) === null || _root$params$3 === void 0 ? void 0 : _root$params$3.name);
4287
+ }
2818
4288
  }
2819
4289
  }, {
2820
- type: "SpreadElement"
4290
+ type: TYPES.SPREAD_ELEMENT
2821
4291
  }]
2822
4292
  }
2823
4293
  }
2824
4294
  };
2825
4295
  const ASSOC_PATTERN = {
2826
4296
  // x => ({ ...x, y: 10 })
2827
- params: [{
2828
- type: "Identifier"
2829
- }],
4297
+ params: params => params.length === 1 && matches([{
4298
+ type: TYPES.IDENTIFIER
4299
+ }], params),
2830
4300
  body: {
2831
- type: "ObjectExpression",
2832
- properties: [{
2833
- type: "SpreadElement",
2834
- argument: {
2835
- type: "Identifier"
2836
- }
2837
- }, {
2838
- type: "Property"
2839
- }]
4301
+ type: TYPES.OBJECT_EXPRESSION,
4302
+ properties: (props, root) => {
4303
+ var _root$params$4;
4304
+
4305
+ return props.length === 2 && matches([{
4306
+ type: TYPES.SPREAD_ELEMENT,
4307
+ argument: {
4308
+ type: TYPES.IDENTIFIER,
4309
+ name: (_root$params$4 = root.params[0]) === null || _root$params$4 === void 0 ? void 0 : _root$params$4.name
4310
+ }
4311
+ }, {
4312
+ type: TYPES.PROPERTY
4313
+ }], props);
4314
+ }
2840
4315
  }
2841
4316
  };
2842
4317
  const JSON_EQUALS_PATTERN = {
2843
4318
  // JSON.stringify(x) === JSON.stringify(y)
2844
4319
  left: {
2845
- type: "CallExpression",
4320
+ type: TYPES.CALL_EXPRESSION,
2846
4321
  callee: {
2847
- type: "MemberExpression",
4322
+ type: TYPES.MEMBER_EXPRESSION,
2848
4323
  object: {
2849
- type: "Identifier",
4324
+ type: TYPES.IDENTIFIER,
2850
4325
  name: "JSON"
2851
4326
  },
2852
4327
  property: {
2853
- type: "Identifier",
4328
+ type: TYPES.IDENTIFIER,
2854
4329
  name: "stringify"
2855
4330
  }
2856
4331
  }
2857
4332
  },
2858
4333
  right: {
2859
- type: "CallExpression",
4334
+ type: TYPES.CALL_EXPRESSION,
2860
4335
  callee: {
2861
- type: "MemberExpression",
4336
+ type: TYPES.MEMBER_EXPRESSION,
2862
4337
  object: {
2863
- type: "Identifier",
4338
+ type: TYPES.IDENTIFIER,
2864
4339
  name: "JSON"
2865
4340
  },
2866
4341
  property: {
2867
- type: "Identifier",
4342
+ type: TYPES.IDENTIFIER,
2868
4343
  name: "stringify"
2869
4344
  }
2870
4345
  }
@@ -2877,108 +4352,138 @@
2877
4352
  async: false,
2878
4353
  expression: true,
2879
4354
  params: [{
2880
- type: "Identifier"
4355
+ type: TYPES.IDENTIFIER
2881
4356
  }],
2882
4357
  body: {
2883
- type: "Identifier"
4358
+ type: TYPES.IDENTIFIER,
4359
+ name: (name, root) => {
4360
+ var _root$params$5;
4361
+
4362
+ return name === ((_root$params$5 = root.params[0]) === null || _root$params$5 === void 0 ? void 0 : _root$params$5.name);
4363
+ }
2884
4364
  }
2885
4365
  };
2886
4366
  const MERGE_PATTERNS = [{
2887
4367
  // x => ({ ...x, y: 10, z: 11 })
2888
- params: [{
2889
- type: "Identifier"
2890
- }],
4368
+ params: params => params.length === 1 && matches([{
4369
+ type: TYPES.IDENTIFIER
4370
+ }], params),
2891
4371
  body: {
2892
- type: "ObjectExpression",
4372
+ type: TYPES.OBJECT_EXPRESSION,
2893
4373
  properties: [{
2894
- type: "SpreadElement",
4374
+ type: TYPES.SPREAD_ELEMENT,
2895
4375
  argument: {
2896
- type: "Identifier"
4376
+ type: TYPES.IDENTIFIER,
4377
+ name: (name, root) => {
4378
+ var _root$params$6;
4379
+
4380
+ return name === ((_root$params$6 = root.params[0]) === null || _root$params$6 === void 0 ? void 0 : _root$params$6.name);
4381
+ }
2897
4382
  }
2898
4383
  }, {
2899
- type: "Property"
4384
+ type: TYPES.PROPERTY
2900
4385
  }, {
2901
- type: "Property"
4386
+ type: TYPES.PROPERTY
2902
4387
  }]
2903
4388
  }
2904
4389
  }, {
2905
4390
  // x => ({ ...x, y: 10, ...z })
2906
- params: [{
2907
- type: "Identifier"
2908
- }],
4391
+ params: params => params.length === 1 && matches([{
4392
+ type: TYPES.IDENTIFIER
4393
+ }], params),
2909
4394
  body: {
2910
- type: "ObjectExpression",
4395
+ type: TYPES.OBJECT_EXPRESSION,
2911
4396
  properties: [{
2912
- type: "SpreadElement",
4397
+ type: TYPES.SPREAD_ELEMENT,
2913
4398
  argument: {
2914
- type: "Identifier"
4399
+ type: TYPES.IDENTIFIER,
4400
+ name: (name, root) => {
4401
+ var _root$params$7;
4402
+
4403
+ return name === ((_root$params$7 = root.params[0]) === null || _root$params$7 === void 0 ? void 0 : _root$params$7.name);
4404
+ }
2915
4405
  }
2916
4406
  }, {
2917
- type: "Property"
4407
+ type: TYPES.PROPERTY
2918
4408
  }, {
2919
- type: "SpreadElement"
4409
+ type: TYPES.SPREAD_ELEMENT
2920
4410
  }]
2921
4411
  }
2922
4412
  }, {
2923
4413
  // x => ({ ...x, ...y })
2924
- params: [{
2925
- type: "Identifier"
2926
- }],
4414
+ params: params => params.length === 1 && matches([{
4415
+ type: TYPES.IDENTIFIER
4416
+ }], params),
2927
4417
  body: {
2928
- type: "ObjectExpression",
4418
+ type: TYPES.OBJECT_EXPRESSION,
2929
4419
  properties: [{
2930
- type: "SpreadElement",
4420
+ type: TYPES.SPREAD_ELEMENT,
2931
4421
  argument: {
2932
- type: "Identifier"
4422
+ type: TYPES.IDENTIFIER,
4423
+ name: (name, root) => {
4424
+ var _root$params$8;
4425
+
4426
+ return name === ((_root$params$8 = root.params[0]) === null || _root$params$8 === void 0 ? void 0 : _root$params$8.name);
4427
+ }
2933
4428
  }
2934
4429
  }, {
2935
- type: "SpreadElement"
4430
+ type: TYPES.SPREAD_ELEMENT
2936
4431
  }]
2937
4432
  }
2938
4433
  }];
2939
4434
  const PLUCK_PATTERNS = {
2940
4435
  OBJECT_ARROW_FUNCTION: {
2941
4436
  callee: {
2942
- type: "MemberExpression",
4437
+ type: TYPES.MEMBER_EXPRESSION,
2943
4438
  property: {
2944
4439
  name: "map"
2945
4440
  }
2946
4441
  },
2947
4442
  arguments: [{
2948
- type: "ArrowFunctionExpression"
4443
+ type: TYPES.ARROW_FUNCTION_EXPRESSION
2949
4444
  }]
2950
4445
  },
2951
4446
  IDENTIFIER: {
2952
4447
  // abc.map(x => x.a);
2953
4448
  params: [{
2954
- type: "Identifier"
4449
+ type: TYPES.IDENTIFIER
2955
4450
  }],
2956
4451
  body: {
2957
- type: "MemberExpression",
4452
+ type: TYPES.MEMBER_EXPRESSION,
2958
4453
  object: {
2959
- type: "Identifier"
4454
+ type: TYPES.IDENTIFIER,
4455
+ name: (name, root) => {
4456
+ var _root$params$9;
4457
+
4458
+ return name === ((_root$params$9 = root.params[0]) === null || _root$params$9 === void 0 ? void 0 : _root$params$9.name);
4459
+ }
2960
4460
  },
2961
4461
  property: {
2962
- type: "Identifier"
4462
+ type: TYPES.IDENTIFIER
2963
4463
  }
2964
4464
  }
2965
4465
  },
2966
4466
  DESTRUCTURE: {
2967
4467
  // abc.map(({ a }) => a);
2968
4468
  params: [{
2969
- type: "ObjectPattern",
4469
+ type: TYPES.OBJECT_PATTERN,
2970
4470
  properties: [{
2971
- type: "Property",
4471
+ type: TYPES.PROPERTY,
2972
4472
  key: {
2973
- type: "Identifier"
4473
+ type: TYPES.IDENTIFIER
2974
4474
  },
2975
4475
  value: {
2976
- type: "Identifier"
4476
+ type: TYPES.IDENTIFIER,
4477
+ name: (name, root) => {
4478
+ var _root$body;
4479
+
4480
+ return name === ((_root$body = root.body) === null || _root$body === void 0 ? void 0 : _root$body.name);
4481
+ }
2977
4482
  }
2978
4483
  }]
2979
4484
  }],
2980
4485
  body: {
2981
- type: "Identifier"
4486
+ type: TYPES.IDENTIFIER
2982
4487
  }
2983
4488
  }
2984
4489
  };
@@ -2989,16 +4494,21 @@
2989
4494
  async: false,
2990
4495
  expression: true,
2991
4496
  params: [{
2992
- type: "ObjectPattern",
4497
+ type: TYPES.OBJECT_PATTERN,
2993
4498
  properties: [{
2994
- type: "Property",
4499
+ type: TYPES.PROPERTY,
2995
4500
  value: {
2996
- type: "Identifier"
4501
+ type: TYPES.IDENTIFIER,
4502
+ name: (name, root) => {
4503
+ var _root$body2;
4504
+
4505
+ return name === ((_root$body2 = root.body) === null || _root$body2 === void 0 ? void 0 : _root$body2.name);
4506
+ }
2997
4507
  }
2998
4508
  }]
2999
4509
  }],
3000
4510
  body: {
3001
- type: "Identifier"
4511
+ type: TYPES.IDENTIFIER
3002
4512
  }
3003
4513
  },
3004
4514
  IDENTITY: {
@@ -3007,62 +4517,64 @@
3007
4517
  async: false,
3008
4518
  expression: true,
3009
4519
  params: [{
3010
- type: "Identifier"
4520
+ type: TYPES.IDENTIFIER
3011
4521
  }],
3012
4522
  body: {
3013
- type: "MemberExpression",
4523
+ type: TYPES.MEMBER_EXPRESSION,
3014
4524
  object: {
3015
- type: "Identifier"
3016
- },
3017
- property: {
3018
- type: "Identifier"
4525
+ type: TYPES.IDENTIFIER,
4526
+ name: (name, root) => {
4527
+ var _root$params$10;
4528
+
4529
+ return name === ((_root$params$10 = root.params[0]) === null || _root$params$10 === void 0 ? void 0 : _root$params$10.name);
4530
+ }
3019
4531
  }
3020
4532
  }
3021
4533
  }
3022
4534
  };
3023
4535
  const SUM_PATTERN = {
3024
4536
  callee: {
3025
- type: "MemberExpression",
4537
+ type: TYPES.MEMBER_EXPRESSION,
3026
4538
  property: {
3027
- type: "Identifier",
4539
+ type: TYPES.IDENTIFIER,
3028
4540
  name: "reduce"
3029
4541
  }
3030
4542
  },
3031
4543
  arguments: [{
3032
- type: "ArrowFunctionExpression",
4544
+ type: TYPES.ARROW_FUNCTION_EXPRESSION,
3033
4545
  generator: false,
3034
4546
  async: false,
3035
4547
  expression: true,
3036
4548
  body: {
3037
- type: "BinaryExpression",
4549
+ type: TYPES.BINARY_EXPRESSION,
3038
4550
  operator: "+"
3039
4551
  },
3040
4552
  params: [{
3041
- type: "Identifier"
4553
+ type: TYPES.IDENTIFIER
3042
4554
  }]
3043
4555
  }, {
3044
- type: "Literal",
4556
+ type: TYPES.LITERAL,
3045
4557
  value: 0
3046
4558
  }]
3047
4559
  };
3048
4560
  const RAMDA_IMPORT_PATTERN = {
3049
- type: "ImportDeclaration",
4561
+ type: TYPES.IMPORT_DECLARATION,
3050
4562
  source: {
3051
- type: "Literal",
4563
+ type: TYPES.LITERAL,
3052
4564
  value: "ramda"
3053
4565
  },
3054
4566
  specifiers: [{
3055
- type: "ImportSpecifier"
4567
+ type: TYPES.IMPORT_SPECIFIER
3056
4568
  }]
3057
4569
  }; // when ({ name }) => name is used inside something.map(...), ignore it.
3058
4570
  // It will be picked up by pluck function
3059
4571
 
3060
4572
  const PROP_IGNORE_PATTERN = {
3061
- type: "CallExpression",
4573
+ type: TYPES.CALL_EXPRESSION,
3062
4574
  callee: {
3063
- type: "MemberExpression",
4575
+ type: TYPES.MEMBER_EXPRESSION,
3064
4576
  property: {
3065
- type: "Identifier",
4577
+ type: TYPES.IDENTIFIER,
3066
4578
  name: "map"
3067
4579
  }
3068
4580
  }
@@ -3071,7 +4583,11 @@
3071
4583
  {
3072
4584
  operator: "||",
3073
4585
  left: NIL_BINARY_EXP_PATTERN,
3074
- right: NIL_BINARY_EXP_PATTERN
4586
+ right: (right, root) => {
4587
+ var _right$left, _root$left, _root$left$left;
4588
+
4589
+ return matches(NIL_BINARY_EXP_PATTERN, right) && ((_right$left = right.left) === null || _right$left === void 0 ? void 0 : _right$left.name) === ((_root$left = root.left) === null || _root$left === void 0 ? void 0 : (_root$left$left = _root$left.left) === null || _root$left$left === void 0 ? void 0 : _root$left$left.name);
4590
+ }
3075
4591
  };
3076
4592
  const EMPTY_PATTERN = [// array.length === 0, Object.keys(obj).length === 0, if(array.length === 0), while(array.length === 0)
3077
4593
  {
@@ -3087,49 +4603,58 @@
3087
4603
  type: TYPES.UNARY_EXPRESSION,
3088
4604
  operator: "!",
3089
4605
  prefix: true,
3090
- argument: matchesAny([ARRAY_LENGTH_PATTERN, OBJ_KEY_LENGTH_PATTERN])
4606
+ argument: matchesAny([ARRAY_LENGTH_PATTERN, OBJ_KEY_LENGTH_PATTERN]),
4607
+ parent: {
4608
+ type: notEquals(TYPES.UNARY_EXPRESSION),
4609
+ operator: notEquals("!")
4610
+ }
3091
4611
  }];
4612
+
3092
4613
  const replacer = nodeReplacerWithImports(RAMDA_IMPORT_PATTERN);
4614
+ const reportSuggestion = ({
4615
+ context,
4616
+ node,
4617
+ fix,
4618
+ functions,
4619
+ message = "",
4620
+ importNullSafe = false
4621
+ }) => context.report({
4622
+ node,
4623
+ message: message || canBeReplacedWith(fix),
4624
+ suggest: [{
4625
+ desc: `Replace with ${Array.isArray(functions) ? functions[0] : functions} function`,
4626
+ fix: replacer.replaceNode({
4627
+ context,
4628
+ node,
4629
+ fix,
4630
+ functions,
4631
+ importNullSafe
4632
+ })
4633
+ }]
4634
+ });
3093
4635
 
3094
4636
  var arrayInsertsLintCheck = {
3095
- operateOn: "ArrowFunctionExpression",
4637
+ operateOn: TYPES.ARROW_FUNCTION_EXPRESSION,
3096
4638
  check: (context, node) => {
3097
- const {
3098
- params,
3099
- body
3100
- } = node;
3101
-
3102
- if (body.type !== TYPES.ARRAY_EXPRESSION || body.elements.length !== 2) {
3103
- return;
3104
- }
3105
-
3106
- const {
3107
- elements
3108
- } = body;
4639
+ if (!matches(ARRAY_PATTERN, node)) return;
4640
+ const elements = node.body.elements;
3109
4641
  let fix = null;
3110
4642
 
3111
- if (matches(ARRAY_INSERTS_PATTERN.APPEND, node) && elements[1].type !== TYPES.SPREAD_ELEMENT && params[0].name === elements[0].argument.name) {
4643
+ if (matches(ARRAY_INSERTS_PATTERN.APPEND, node)) {
3112
4644
  fix = `append(${getCode$1(context, elements[1])})`;
3113
- } else if (matches(ARRAY_INSERTS_PATTERN.PREPEND, node) && elements[0].type !== TYPES.SPREAD_ELEMENT && params[0].name === elements[1].argument.name) {
4645
+ } else if (matches(ARRAY_INSERTS_PATTERN.PREPEND, node)) {
3114
4646
  fix = `prepend(${getCode$1(context, elements[0])})`;
3115
- } else if (matches(ARRAY_INSERTS_PATTERN.CONCAT, node) && params[0].name === elements[0].argument.name) {
4647
+ } else if (matches(ARRAY_INSERTS_PATTERN.CONCAT, node)) {
3116
4648
  fix = `concat(${getCode$1(context, elements[1].argument)})`;
3117
4649
  }
3118
4650
 
3119
4651
  if (!fix) return;
3120
4652
  const funcName = fix.split("(")[0];
3121
- context.report({
4653
+ reportSuggestion({
4654
+ context,
3122
4655
  node,
3123
- message: canBeReplacedWith(fix),
3124
- suggest: [{
3125
- desc: `Replace with ${funcName} function`,
3126
- fix: replacer.replaceNode({
3127
- context,
3128
- node,
3129
- fix,
3130
- functions: funcName
3131
- })
3132
- }]
4656
+ fix,
4657
+ functions: funcName
3133
4658
  });
3134
4659
  }
3135
4660
  };
@@ -3141,73 +4666,49 @@
3141
4666
  };
3142
4667
 
3143
4668
  var assocLintCheck = {
3144
- operateOn: "ArrowFunctionExpression",
4669
+ operateOn: TYPES.ARROW_FUNCTION_EXPRESSION,
3145
4670
  check: (context, node) => {
3146
- if (node.params.length !== 1) return;
3147
4671
  if (!matches(ASSOC_PATTERN, node)) return;
3148
- if (node.body.properties.length !== 2) return;
3149
- if (node.body.properties[0].argument.name !== node.params[0].name) return;
3150
4672
  const property = node.body.properties[1];
3151
4673
  const selfReferencingPattern = {
3152
- type: "Identifier",
4674
+ type: TYPES.IDENTIFIER,
3153
4675
  name: node.params[0].name
3154
4676
  };
3155
4677
  if (patternExistsDeep(selfReferencingPattern, property.value)) return;
3156
4678
  const fix = convertToAssoc(context, node);
3157
- context.report({
4679
+ reportSuggestion({
4680
+ context,
3158
4681
  node,
3159
- message: canBeReplacedWith(fix),
3160
- suggest: [{
3161
- desc: "Replace with assoc function",
3162
- fix: replacer.replaceNode({
3163
- context,
3164
- node,
3165
- fix,
3166
- functions: "assoc"
3167
- })
3168
- }]
4682
+ fix,
4683
+ functions: "assoc"
3169
4684
  });
3170
4685
  }
3171
4686
  };
3172
4687
 
3173
4688
  var equalsLintCheck = {
3174
- operateOn: "BinaryExpression",
4689
+ operateOn: TYPES.BINARY_EXPRESSION,
3175
4690
  check: (context, node) => {
3176
4691
  if (matches(JSON_EQUALS_PATTERN, node)) {
3177
4692
  const fix = `equals(${getCode$1(context, node.left.arguments[0])}, ${getCode$1(context, node.right.arguments[0])})`;
3178
- context.report({
4693
+ reportSuggestion({
4694
+ context,
3179
4695
  node,
3180
- message: canBeReplacedWith(fix),
3181
- suggest: [{
3182
- desc: "Replace with equals function",
3183
- fix: replacer.replaceNode({
3184
- context,
3185
- node,
3186
- fix,
3187
- functions: "equals"
3188
- })
3189
- }]
4696
+ fix,
4697
+ functions: "equals"
3190
4698
  });
3191
4699
  }
3192
4700
  }
3193
4701
  };
3194
4702
 
3195
4703
  var identityLintCheck = {
3196
- operateOn: "ArrowFunctionExpression",
4704
+ operateOn: TYPES.ARROW_FUNCTION_EXPRESSION,
3197
4705
  check: (context, node) => {
3198
- if (matches(IDENTITY_PATTERN, node) && node.params[0].name === node.body.name) {
3199
- context.report({
4706
+ if (matches(IDENTITY_PATTERN, node)) {
4707
+ reportSuggestion({
4708
+ context,
3200
4709
  node,
3201
- message: canBeReplacedWith("identity"),
3202
- suggest: [{
3203
- desc: "Replace with identity function",
3204
- fix: replacer.replaceNode({
3205
- context,
3206
- node,
3207
- fix: "identity",
3208
- functions: "identity"
3209
- })
3210
- }]
4710
+ fix: "identity",
4711
+ functions: "identity"
3211
4712
  });
3212
4713
  }
3213
4714
  }
@@ -3218,7 +4719,7 @@
3218
4719
  check: (context, node) => {
3219
4720
  if (!matchesAny(EMPTY_PATTERN, node)) return;
3220
4721
  let fix = null;
3221
- let message = "";
4722
+ let message = "Can be replaced with isEmpty function";
3222
4723
  const isBinaryExp = node.type === TYPES.BINARY_EXPRESSION;
3223
4724
  const expNode = isBinaryExp ? node.left : node.argument;
3224
4725
  const isObjLenCheck = matches(OBJ_KEY_LENGTH_PATTERN, expNode);
@@ -3235,9 +4736,9 @@
3235
4736
  reportSuggestion({
3236
4737
  context,
3237
4738
  node,
4739
+ message,
3238
4740
  fix,
3239
- func: "isEmpty",
3240
- message
4741
+ functions: "isEmpty"
3241
4742
  });
3242
4743
  }
3243
4744
  };
@@ -3246,13 +4747,12 @@
3246
4747
  operateOn: TYPES.LOGICAL_EXPRESSION,
3247
4748
  check: (context, node) => {
3248
4749
  if (!matches(NIL_PATTERN, node)) return;
3249
- if (node.left.left.name !== node.right.left.name) return;
3250
4750
  const fix = `isNil(${node.left.left.name})`;
3251
4751
  reportSuggestion({
3252
4752
  context,
3253
4753
  node,
3254
4754
  fix,
3255
- func: "isNil"
4755
+ functions: "isNil"
3256
4756
  });
3257
4757
  }
3258
4758
  };
@@ -3268,96 +4768,78 @@
3268
4768
  };
3269
4769
 
3270
4770
  var mergeLintCheck = {
3271
- operateOn: "ArrowFunctionExpression",
4771
+ operateOn: TYPES.ARROW_FUNCTION_EXPRESSION,
3272
4772
  check: (context, node) => {
3273
- if (node.params.length !== 1) return;
3274
4773
  const matchIndex = findPatternIndex(node);
3275
4774
  if (matchIndex < 0) return;
3276
- if (node.body.properties[0].argument.name !== node.params[0].name) return;
3277
4775
  const selfReferencingPattern = {
3278
- type: "Identifier",
4776
+ type: TYPES.IDENTIFIER,
3279
4777
  name: node.params[0].name
3280
4778
  };
3281
4779
  const properties = node.body.properties.slice(1);
3282
4780
  if (patternExistsDeep(selfReferencingPattern, properties)) return;
3283
4781
  const fix = convertToMergeLeft(context, node);
3284
- context.report({
4782
+ reportSuggestion({
4783
+ context,
3285
4784
  node,
3286
- message: canBeReplacedWith(fix),
3287
- suggest: [{
3288
- desc: "Replace with mergeLeft function",
3289
- fix: replacer.replaceNode({
3290
- context,
3291
- node,
3292
- fix,
3293
- functions: "mergeLeft"
3294
- })
3295
- }]
4785
+ fix,
4786
+ functions: "mergeLeft"
3296
4787
  });
3297
4788
  }
3298
4789
  };
3299
4790
 
3300
- const reportViolation = (context, node, fix) => context.report({
3301
- node,
3302
- message: canBeReplacedWith(fix),
3303
- suggest: [{
3304
- desc: "Replace with pluck function",
3305
- fix: replacer.replaceNode({
3306
- context,
3307
- node,
3308
- fix,
3309
- functions: "pluck"
3310
- })
3311
- }]
3312
- });
3313
-
3314
4791
  var pluckLintCheck = {
3315
- operateOn: "CallExpression",
4792
+ operateOn: TYPES.CALL_EXPRESSION,
3316
4793
  check: (context, node) => {
3317
4794
  if (matches(PLUCK_PATTERNS.OBJECT_ARROW_FUNCTION, node)) {
3318
4795
  const code = getCode$1(context, node.callee.object);
4796
+ const isNullSafeRequired = isOptionalChainingPresent(node.callee);
4797
+ const callee = isNullSafeRequired ? "nullSafe(pluck)" : "pluck";
3319
4798
  const func = node.arguments[0];
4799
+ let fix = null;
3320
4800
 
3321
4801
  if (matches(PLUCK_PATTERNS.IDENTIFIER, func)) {
3322
- if (func.params[0].name !== func.body.object.name) return;
3323
- const fix = `pluck("${func.body.property.name}", ${code})`;
3324
- reportViolation(context, node, fix);
4802
+ fix = `${callee}("${func.body.property.name}", ${code})`;
3325
4803
  } else if (matches(PLUCK_PATTERNS.DESTRUCTURE, func)) {
3326
4804
  const propertyName = func.params[0].properties[0].value.name;
3327
- if (propertyName !== func.body.name) return;
3328
- const fix = `pluck("${propertyName}", ${code})`;
3329
- reportViolation(context, node, fix);
3330
- }
4805
+ fix = `${callee}("${propertyName}", ${code})`;
4806
+ } else return;
4807
+
4808
+ reportSuggestion({
4809
+ context,
4810
+ node,
4811
+ fix,
4812
+ functions: "pluck",
4813
+ importNullSafe: isNullSafeRequired
4814
+ });
3331
4815
  }
3332
4816
  }
3333
4817
  };
3334
4818
 
3335
4819
  var propLintCheck = {
3336
- operateOn: "ArrowFunctionExpression",
4820
+ operateOn: TYPES.ARROW_FUNCTION_EXPRESSION,
3337
4821
  check: (context, node) => {
3338
4822
  let fix = null;
3339
4823
  if (matches(PROP_IGNORE_PATTERN, node.parent)) return;
3340
4824
 
3341
- if (matches(PROP_PATTERNS.OBJECT, node) && node.params[0].properties[0].value.name === node.body.name) {
4825
+ if (matches(PROP_PATTERNS.OBJECT, node)) {
3342
4826
  fix = `prop("${node.body.name}")`;
3343
- } else if (matches(PROP_PATTERNS.IDENTITY, node) && node.params[0].name === node.body.object.name) {
3344
- fix = `prop("${node.body.property.name}")`;
3345
- } else {
3346
- return;
3347
- }
4827
+ } else if (matches(PROP_PATTERNS.IDENTITY, node)) {
4828
+ const isComputed = node.body.computed;
4829
+ const propertyType = node.body.property.type;
3348
4830
 
3349
- context.report({
4831
+ if (isComputed) {
4832
+ fix = propertyType === TYPES.IDENTIFIER ? `prop(${node.body.property.name})` : `prop("${node.body.property.value}")`;
4833
+ } else {
4834
+ fix = `prop("${node.body.property.name}")`;
4835
+ }
4836
+ } else return;
4837
+
4838
+ reportSuggestion({
4839
+ context,
3350
4840
  node,
3351
- message: canBeReplacedWith(fix),
3352
- suggest: [{
3353
- desc: "Replace with prop function",
3354
- fix: replacer.replaceNode({
3355
- context,
3356
- node,
3357
- fix,
3358
- functions: "prop"
3359
- })
3360
- }]
4841
+ fix,
4842
+ functions: "prop"
3361
4843
  });
3362
4844
  }
3363
4845
  };
@@ -3383,7 +4865,7 @@
3383
4865
  };
3384
4866
 
3385
4867
  var sumLintCheck = {
3386
- operateOn: "CallExpression",
4868
+ operateOn: TYPES.CALL_EXPRESSION,
3387
4869
  check: (context, node) => {
3388
4870
  if (!matches(SUM_PATTERN, node)) return;
3389
4871
  const reduceFunc = node.arguments[0];
@@ -3394,31 +4876,27 @@
3394
4876
  if (!accumulator || !delta) return;
3395
4877
  let fix = null;
3396
4878
  let functions = ["sum"];
4879
+ const code = getCode$1(context, node.callee.object);
4880
+ let isNullSafeRequired = false;
3397
4881
 
3398
4882
  if (reduceFunc.params[1].type === TYPES.IDENTIFIER && delta.type === TYPES.IDENTIFIER && delta.name === reduceFunc.params[1].name) {
3399
- fix = `sum(${getCode$1(context, node.callee.object)})`;
3400
- } else if (reduceFunc.params[1].type === TYPES.OBJECT_PATTERN && delta.type === TYPES.IDENTIFIER && delta.name === reduceFunc.params[1].properties[0].value.name) {
3401
- fix = `sum(pluck("${delta.name}", ${getCode$1(context, node.callee.object)}))`;
4883
+ isNullSafeRequired = isOptionalChainingPresent(node.callee);
4884
+ const func = isNullSafeRequired ? "nullSafe(sum)" : "sum";
4885
+ fix = `${func}(${code})`;
4886
+ } else if (reduceFunc.params[1].type === TYPES.OBJECT_PATTERN && delta.type === TYPES.IDENTIFIER && delta.name === reduceFunc.params[1].properties[0].value.name && !isOptionalChainingPresent(node.callee)) {
4887
+ fix = `sum(pluck("${delta.name}", ${code}))`;
3402
4888
  functions = ["sum", "pluck"];
3403
- } else if (reduceFunc.params[1].type === TYPES.IDENTIFIER && delta.type === TYPES.MEMBER_EXPRESSION && delta.property.type === TYPES.IDENTIFIER && delta.object.name === reduceFunc.params[1].name) {
3404
- fix = `sum(pluck("${delta.property.name}", ${getCode$1(context, node.callee.object)}))`;
4889
+ } else if (reduceFunc.params[1].type === TYPES.IDENTIFIER && delta.type === TYPES.MEMBER_EXPRESSION && delta.property.type === TYPES.IDENTIFIER && delta.object.name === reduceFunc.params[1].name && !isOptionalChainingPresent(node.callee)) {
4890
+ fix = `sum(pluck("${delta.property.name}", ${code}))`;
3405
4891
  functions = ["sum", "pluck"];
3406
- } else {
3407
- return;
3408
- }
4892
+ } else return;
3409
4893
 
3410
- context.report({
4894
+ reportSuggestion({
4895
+ context,
3411
4896
  node,
3412
- message: canBeReplacedWith(fix),
3413
- suggest: [{
3414
- desc: "Replace with sum function",
3415
- fix: replacer.replaceNode({
3416
- context,
3417
- node,
3418
- fix,
3419
- functions
3420
- })
3421
- }]
4897
+ fix,
4898
+ functions,
4899
+ importNullSafe: isNullSafeRequired
3422
4900
  });
3423
4901
  }
3424
4902
  };
@@ -3444,6 +4922,62 @@
3444
4922
  }
3445
4923
  };
3446
4924
 
4925
+ const BREAK_STATEMENT_PATTERN = {
4926
+ type: TYPES.BREAK_STATEMENT
4927
+ };
4928
+ const RETURN_STATEMENT_PATTERN = {
4929
+ type: TYPES.RETURN_STATEMENT
4930
+ };
4931
+ const ARRAY_LENGTH_TEST_PATTERN = {
4932
+ test: {
4933
+ right: {
4934
+ type: TYPES.MEMBER_EXPRESSION,
4935
+ property: {
4936
+ name: "length"
4937
+ }
4938
+ }
4939
+ }
4940
+ };
4941
+ const CHAR_AT_PATTERN = {
4942
+ type: TYPES.CALL_EXPRESSION,
4943
+ callee: {
4944
+ property: {
4945
+ name: ramda.includes(ramda.__, ["charAt", "charCodeAt"])
4946
+ }
4947
+ }
4948
+ };
4949
+
4950
+ const isForLoopReplacable = node => ramda.not(patternExistsDeep(BREAK_STATEMENT_PATTERN, node.body) || patternExistsDeep(RETURN_STATEMENT_PATTERN, node.body) || patternExistsDeep(CHAR_AT_PATTERN, node.body));
4951
+
4952
+ var useArrayMethods = {
4953
+ meta: {
4954
+ type: "suggestion",
4955
+ docs: {
4956
+ description: "Warns when for loop is used instead of array methods."
4957
+ }
4958
+ },
4959
+ create: context => ({
4960
+ ForStatement(node) {
4961
+ if (!matches(ARRAY_LENGTH_TEST_PATTERN, node)) return;
4962
+ if (!isForLoopReplacable(node)) return;
4963
+ context.report({
4964
+ node,
4965
+ message: USE_ARRAY_METHODS
4966
+ });
4967
+ },
4968
+
4969
+ ForOfStatement(node) {
4970
+ if (!isForLoopReplacable(node)) return;
4971
+ context.report({
4972
+ node,
4973
+ message: USE_ARRAY_METHODS
4974
+ });
4975
+ }
4976
+
4977
+ })
4978
+ };
4979
+
4980
+ const VALID_URL_TYPES = [TYPES.LITERAL, TYPES.TEMPLATE_LITERAL];
3447
4981
  const AXIOS_GET_PATTERN = {
3448
4982
  callee: {
3449
4983
  type: TYPES.MEMBER_EXPRESSION,
@@ -3455,15 +4989,20 @@
3455
4989
  name: "get",
3456
4990
  type: TYPES.IDENTIFIER
3457
4991
  }
3458
- }
4992
+ },
4993
+ arguments: [{
4994
+ type: ramda.includes(ramda.__, VALID_URL_TYPES)
4995
+ }]
3459
4996
  };
3460
4997
  const AXIOS_PATTERN = {
3461
4998
  callee: {
3462
4999
  name: "axios",
3463
5000
  type: TYPES.IDENTIFIER
3464
- }
5001
+ },
5002
+ arguments: [{
5003
+ type: ramda.includes(ramda.__, [TYPES.LITERAL, TYPES.TEMPLATE_LITERAL, TYPES.OBJECT_EXPRESSION])
5004
+ }]
3465
5005
  };
3466
- const VALID_URL_TYPES = [TYPES.LITERAL, TYPES.TEMPLATE_LITERAL];
3467
5006
 
3468
5007
  const getPropValue = (configNode, name) => {
3469
5008
  var _configNode$propertie;
@@ -3473,26 +5012,25 @@
3473
5012
  }) => key.name === name)) === null || _configNode$propertie === void 0 ? void 0 : _configNode$propertie.value;
3474
5013
  };
3475
5014
 
3476
- const containsQuestionMark = ({
3477
- quasis
3478
- }) => quasis.some(({
3479
- value
3480
- }) => value.cooked.includes("?"));
3481
-
3482
5015
  const checkAndReport = ({
3483
5016
  context,
3484
5017
  node,
3485
5018
  urlNode
3486
5019
  }) => {
3487
- const addsQueryThroughTemplate = urlNode.type === TYPES.TEMPLATE_LITERAL && containsQuestionMark(urlNode);
3488
- const urlStringContainsQuery = urlNode.type === TYPES.LITERAL && urlNode.value.includes("?");
5020
+ let isQuestionMarkPresent = false;
3489
5021
 
3490
- if (addsQueryThroughTemplate || urlStringContainsQuery) {
3491
- context.report({
3492
- node,
3493
- message: USE_AXIOS_CONFIG_FOR_PASSING_QUERY_PARAMETERS_MESSAGE
3494
- });
5022
+ if (urlNode.type === TYPES.LITERAL) {
5023
+ isQuestionMarkPresent = urlNode.value.includes("?");
5024
+ } else {
5025
+ isQuestionMarkPresent = urlNode.quasis.some(({
5026
+ value
5027
+ }) => value.cooked.includes("?"));
3495
5028
  }
5029
+
5030
+ if (isQuestionMarkPresent) context.report({
5031
+ node,
5032
+ message: USE_AXIOS_CONFIG_FOR_PASSING_QUERY_PARAMETERS_MESSAGE
5033
+ });
3496
5034
  };
3497
5035
 
3498
5036
  var useAxiosConfigForPassingQueryParameters = {
@@ -3505,7 +5043,6 @@
3505
5043
  create: context => ({
3506
5044
  CallExpression(node) {
3507
5045
  if (matches(AXIOS_GET_PATTERN, node)) {
3508
- if (!VALID_URL_TYPES.includes(node.arguments[0].type)) return;
3509
5046
  checkAndReport({
3510
5047
  context,
3511
5048
  node,
@@ -3517,21 +5054,16 @@
3517
5054
  let methodNode = null;
3518
5055
  let urlNode = null;
3519
5056
 
3520
- if (VALID_URL_TYPES.includes(node.arguments[0].type)) {
3521
- urlNode = node.arguments[0];
3522
- methodNode = getPropValue(node.arguments[1], "method");
3523
- } else if (node.arguments[0].type === TYPES.OBJECT_EXPRESSION) {
5057
+ if (node.arguments[0].type === TYPES.OBJECT_EXPRESSION) {
3524
5058
  urlNode = getPropValue(node.arguments[0], "url");
3525
5059
  methodNode = getPropValue(node.arguments[0], "method");
5060
+ if (!VALID_URL_TYPES.includes(urlNode.type)) return;
5061
+ } else {
5062
+ urlNode = node.arguments[0];
5063
+ methodNode = getPropValue(node.arguments[1], "method");
3526
5064
  }
3527
5065
 
3528
- if (!urlNode) return;
3529
-
3530
- if (((_methodNode = methodNode) === null || _methodNode === void 0 ? void 0 : _methodNode.value.toLowerCase()) !== "get") {
3531
- return;
3532
- }
3533
-
3534
- if (!VALID_URL_TYPES.includes(urlNode.type)) return;
5066
+ if (((_methodNode = methodNode) === null || _methodNode === void 0 ? void 0 : _methodNode.value.toLowerCase()) !== "get") return;
3535
5067
  checkAndReport({
3536
5068
  context,
3537
5069
  node,
@@ -3543,6 +5075,101 @@
3543
5075
  })
3544
5076
  };
3545
5077
 
5078
+ const COLORS = ["black", "white", "gray", "red", "yellow", "green", "blue", "indigo", "purple", "pink"];
5079
+ const SIZES = ["none", "sm", "md", "lg", "xl", "2xl", "3xl", "full"];
5080
+ const BORDER_COLOR_PATTERNS = COLORS.map(color => new RegExp(`^((hover|focus|focus-visible):)?border-${color}(-[0-9]{2,3})?$`));
5081
+ const BORDER_RADIUS_PATTERNS = SIZES.map(size => new RegExp(`^rounded(-${size})?$`));
5082
+ const BOX_SHADOW_PATTERNS = SIZES.map(size => new RegExp(`^shadow(-${size})?$`));
5083
+ const TEXT_COLOR_PATTERNS = COLORS.map(color => new RegExp(`^((hover|focus|focus-visible):)?text-${color}(-[0-9]{2,3})?$`));
5084
+ const TAILWIND_CLASS_PATTERNS = {
5085
+ borderColor: {
5086
+ patterns: BORDER_COLOR_PATTERNS,
5087
+ message: USE_NEETOUI_BORDER_COLOR
5088
+ },
5089
+ borderRadius: {
5090
+ patterns: BORDER_RADIUS_PATTERNS,
5091
+ message: USE_NEETOUI_BORDER_RADIUS
5092
+ },
5093
+ boxShadow: {
5094
+ patterns: BOX_SHADOW_PATTERNS,
5095
+ message: USE_NEETOUI_BOX_SHADOW
5096
+ },
5097
+ textColor: {
5098
+ patterns: TEXT_COLOR_PATTERNS,
5099
+ message: USE_NEETOUI_TEXT_COLOR
5100
+ }
5101
+ };
5102
+
5103
+ const getLocation = ({
5104
+ nodeValue,
5105
+ nodeLoc,
5106
+ cssClass
5107
+ }) => {
5108
+ const startCol = nodeLoc.start.column + nodeValue.indexOf(cssClass) + 1;
5109
+ const endCol = startCol + cssClass.length;
5110
+ const line = nodeLoc.start.line;
5111
+ return {
5112
+ start: {
5113
+ line,
5114
+ column: startCol
5115
+ },
5116
+ end: {
5117
+ line,
5118
+ column: endCol
5119
+ }
5120
+ };
5121
+ };
5122
+
5123
+ const getCssProperty = cssClass => {
5124
+ let property = "";
5125
+ if (cssClass.includes("text")) property = "textColor";else if (cssClass.includes("border")) property = "borderColor";else if (cssClass.includes("rounded")) property = "borderRadius";else if (cssClass.includes("shadow")) property = "boxShadow";
5126
+ return property;
5127
+ };
5128
+
5129
+ const checkAndReportTailwindClasses = (context, node) => {
5130
+ const nodeValue = node.type === TYPES.LITERAL ? node.value : node.value.cooked;
5131
+ if (typeof nodeValue !== "string") return;
5132
+ const cssClasses = nodeValue.split(" ");
5133
+ cssClasses.forEach(cssClass => {
5134
+ const cssProperty = getCssProperty(cssClass);
5135
+ if (!cssProperty) return;
5136
+ const {
5137
+ patterns,
5138
+ message
5139
+ } = TAILWIND_CLASS_PATTERNS[cssProperty];
5140
+ const isPatternMatched = patterns.some(pattern => pattern.test(cssClass));
5141
+ if (!isPatternMatched) return;
5142
+ context.report({
5143
+ node,
5144
+ loc: getLocation({
5145
+ nodeValue,
5146
+ nodeLoc: node.loc,
5147
+ cssClass
5148
+ }),
5149
+ message
5150
+ });
5151
+ });
5152
+ };
5153
+
5154
+ var useNeetouiClasses = {
5155
+ meta: {
5156
+ type: "suggestion",
5157
+ docs: {
5158
+ description: "Warns when tailwind classes are used instead of neetoUI classes"
5159
+ }
5160
+ },
5161
+ create: context => ({
5162
+ Literal(node) {
5163
+ checkAndReportTailwindClasses(context, node);
5164
+ },
5165
+
5166
+ TemplateElement(node) {
5167
+ checkAndReportTailwindClasses(context, node);
5168
+ }
5169
+
5170
+ })
5171
+ };
5172
+
3546
5173
  const SNAKE_CASE_REGEX = /^[a-z0-9_]+$/;
3547
5174
 
3548
5175
  const isSnakeCase = text => SNAKE_CASE_REGEX.test(text);
@@ -3592,21 +5219,56 @@
3592
5219
  const aliases = context.options[0];
3593
5220
  if (ramda.isEmpty(aliases) || ramda.isNil(aliases)) return;
3594
5221
  const importPath = node.source.value;
3595
- if (!importPath.startsWith("../")) return;
3596
- const filename = context.getFilename();
3597
- const importFullPath = path__default["default"].resolve(filename, "../", importPath);
3598
- const matches = Object.entries(aliases).filter(([, path]) => importFullPath.startsWith(path)).sort((first, second) => first.length - second.length);
5222
+ const importFullPath = importPath.startsWith("../") ? path__default["default"].resolve(context.getFilename(), "../", importPath) : importPath;
5223
+ const matches = Object.entries(aliases).filter(([, path]) => importFullPath.startsWith(path) && ["/", undefined].includes(importFullPath.split(path)[1][0])).sort((first, second) => first.length - second.length);
3599
5224
  if (matches.length === 0) return;
3600
5225
  const aliasMatch = matches[matches.length - 1];
3601
5226
  const importPathWithAlias = importFullPath.replace(aliasMatch[1], aliasMatch[0]);
5227
+ if (importPath.length < importPathWithAlias.length) return;
5228
+ context.report({
5229
+ node,
5230
+ message: canBeReplacedWith(importPathWithAlias),
5231
+ fix: fixer => fixer.replaceText(node.source, `"${importPathWithAlias}"`)
5232
+ });
5233
+ }
3602
5234
 
3603
- if (importPath.length > importPathWithAlias.length) {
3604
- context.report({
3605
- node,
3606
- message: canBeReplacedWith(importPathWithAlias),
3607
- fix: fixer => fixer.replaceText(node.source, `"${importPathWithAlias}"`)
3608
- });
3609
- }
5235
+ })
5236
+ };
5237
+
5238
+ const removeComments = json => JSON.parse(json.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m));
5239
+
5240
+ const parseJsconfigData = ramda.memoizeWith(ramda.identity, jsconfigFilePath => {
5241
+ if (!jsconfigFilePath) return null;
5242
+ const jsonData = fs__default["default"].readFileSync(jsconfigFilePath).toString();
5243
+ const parsedJsonData = removeComments(jsonData);
5244
+ return parsedJsonData;
5245
+ });
5246
+ var webpackAliasesAndJsconfigPathsShouldBeInSync = {
5247
+ meta: {
5248
+ type: "problem",
5249
+ docs: {
5250
+ description: "Ensures that webpack alias and jsconfig are in sync"
5251
+ }
5252
+ },
5253
+ create: context => ({
5254
+ Property(node) {
5255
+ var _context$options, _context$options$, _node$parent, _node$parent$parent, _node$parent$parent$k, _context$options2, _context$options2$, _jsconfigData$compile;
5256
+
5257
+ const filename = context.getFilename();
5258
+ const isInsideAliasFile = filename === ((_context$options = context.options) === null || _context$options === void 0 ? void 0 : (_context$options$ = _context$options[0]) === null || _context$options$ === void 0 ? void 0 : _context$options$.aliasFilePath);
5259
+ if (!isInsideAliasFile) return;
5260
+ const isInsideAliasProperty = ((_node$parent = node.parent) === null || _node$parent === void 0 ? void 0 : (_node$parent$parent = _node$parent.parent) === null || _node$parent$parent === void 0 ? void 0 : (_node$parent$parent$k = _node$parent$parent.key) === null || _node$parent$parent$k === void 0 ? void 0 : _node$parent$parent$k.name) === "alias";
5261
+ if (!isInsideAliasProperty) return;
5262
+ const jsconfigData = parseJsconfigData((_context$options2 = context.options) === null || _context$options2 === void 0 ? void 0 : (_context$options2$ = _context$options2[0]) === null || _context$options2$ === void 0 ? void 0 : _context$options2$.jsconfigFilePath);
5263
+ const jsconfigPaths = jsconfigData === null || jsconfigData === void 0 ? void 0 : (_jsconfigData$compile = jsconfigData.compilerOptions) === null || _jsconfigData$compile === void 0 ? void 0 : _jsconfigData$compile.paths;
5264
+ if (!jsconfigPaths) return;
5265
+ const aliasName = node.key.name;
5266
+ const matches = Object.keys(jsconfigPaths).some(ramda.includes(ramda.__, [aliasName, `${aliasName}/*`]));
5267
+ if (matches) return;
5268
+ context.report({
5269
+ node,
5270
+ message: addInJsconfig(aliasName)
5271
+ });
3610
5272
  }
3611
5273
 
3612
5274
  })
@@ -3614,10 +5276,12 @@
3614
5276
 
3615
5277
  var index = {
3616
5278
  rules: {
5279
+ "minimize-zustand-store-access-scope": minimizeZustandStoreAccessScope,
3617
5280
  "api-connector-name-should-match-filename": apiConnectorNameShouldMatchFilename,
3618
5281
  "api-connector-should-use-default-export": apiConnectorShouldUseDefaultExport,
3619
5282
  "combine-multiple-independent-awaits": combineMultipleIndependentAwaits,
3620
5283
  "consistent-button-link-anchor": consistentButtonLinkAnchor,
5284
+ "file-name-and-export-name-standards": fileNameAndExportNameStandards,
3621
5285
  "neetocommons-tips": neetocommonsTips,
3622
5286
  "no-blacklisted-imports": noBlacklistedImports,
3623
5287
  "no-axios-import-outside-apis": noAxiosImportOutsideApis,
@@ -3635,11 +5299,13 @@
3635
5299
  "ramda-tips": ramdaTips,
3636
5300
  "routes-should-be-declared-and-default-exported": routesShouldBeDeclaredAndDefaultExported,
3637
5301
  "routes-should-match-object-path": routesShouldMatchObjectPath,
5302
+ "use-array-methods": useArrayMethods,
3638
5303
  "use-axios-config-for-passing-query-parameters": useAxiosConfigForPassingQueryParameters,
3639
- "use-constant-case": useConstantCase,
3640
5304
  "use-common-routes": useCommonRoutes,
5305
+ "use-neetoui-classes": useNeetouiClasses,
3641
5306
  "use-snake-case-for-api-connector-filename": useSnakeCaseForApiConnectorFilename,
3642
- "use-webpack-alias": useWebpackAlias
5307
+ "use-webpack-alias": useWebpackAlias,
5308
+ "webpack-aliases-and-jsconfig-paths-should-be-in-sync": webpackAliasesAndJsconfigPathsShouldBeInSync
3643
5309
  }
3644
5310
  };
3645
5311