@tanstack/eslint-plugin-query 5.91.4 → 5.94.4

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 (44) hide show
  1. package/package.json +5 -6
  2. package/src/rules/exhaustive-deps/exhaustive-deps.rule.ts +14 -14
  3. package/src/rules/exhaustive-deps/exhaustive-deps.utils.ts +159 -0
  4. package/src/utils/ast-utils.ts +13 -1
  5. package/build/legacy/chunk-MUQBIZ2R.js +0 -1027
  6. package/build/legacy/chunk-MUQBIZ2R.js.map +0 -1
  7. package/build/legacy/index.cjs +0 -1096
  8. package/build/legacy/index.cjs.map +0 -1
  9. package/build/legacy/index.d.cts +0 -52
  10. package/build/legacy/index.d.ts +0 -52
  11. package/build/legacy/index.js +0 -50
  12. package/build/legacy/index.js.map +0 -1
  13. package/build/legacy/rules.cjs +0 -1053
  14. package/build/legacy/rules.cjs.map +0 -1
  15. package/build/legacy/rules.d.cts +0 -6
  16. package/build/legacy/rules.d.ts +0 -6
  17. package/build/legacy/rules.js +0 -7
  18. package/build/legacy/rules.js.map +0 -1
  19. package/build/legacy/types.cjs +0 -19
  20. package/build/legacy/types.cjs.map +0 -1
  21. package/build/legacy/types.d.cts +0 -5
  22. package/build/legacy/types.d.ts +0 -5
  23. package/build/legacy/types.js +0 -1
  24. package/build/legacy/types.js.map +0 -1
  25. package/build/modern/chunk-2FPOGBVA.js +0 -1019
  26. package/build/modern/chunk-2FPOGBVA.js.map +0 -1
  27. package/build/modern/index.cjs +0 -1089
  28. package/build/modern/index.cjs.map +0 -1
  29. package/build/modern/index.d.cts +0 -52
  30. package/build/modern/index.d.ts +0 -52
  31. package/build/modern/index.js +0 -50
  32. package/build/modern/index.js.map +0 -1
  33. package/build/modern/rules.cjs +0 -1046
  34. package/build/modern/rules.cjs.map +0 -1
  35. package/build/modern/rules.d.cts +0 -6
  36. package/build/modern/rules.d.ts +0 -6
  37. package/build/modern/rules.js +0 -7
  38. package/build/modern/rules.js.map +0 -1
  39. package/build/modern/types.cjs +0 -20
  40. package/build/modern/types.cjs.map +0 -1
  41. package/build/modern/types.d.cts +0 -5
  42. package/build/modern/types.d.ts +0 -5
  43. package/build/modern/types.js +0 -1
  44. package/build/modern/types.js.map +0 -1
@@ -1,1027 +0,0 @@
1
- // src/rules/exhaustive-deps/exhaustive-deps.rule.ts
2
- import { AST_NODE_TYPES as AST_NODE_TYPES3, ESLintUtils } from "@typescript-eslint/utils";
3
-
4
- // src/utils/ast-utils.ts
5
- import { AST_NODE_TYPES } from "@typescript-eslint/utils";
6
-
7
- // src/utils/unique-by.ts
8
- function uniqueBy(arr, fn) {
9
- return arr.filter((x, i, a) => a.findIndex((y) => fn(x) === fn(y)) === i);
10
- }
11
-
12
- // src/utils/ast-utils.ts
13
- var ASTUtils = {
14
- isNodeOfOneOf(node, types) {
15
- return types.includes(node.type);
16
- },
17
- isIdentifier(node) {
18
- return node.type === AST_NODE_TYPES.Identifier;
19
- },
20
- isIdentifierWithName(node, name8) {
21
- return ASTUtils.isIdentifier(node) && node.name === name8;
22
- },
23
- isIdentifierWithOneOfNames(node, name8) {
24
- return ASTUtils.isIdentifier(node) && name8.includes(node.name);
25
- },
26
- isProperty(node) {
27
- return node.type === AST_NODE_TYPES.Property;
28
- },
29
- isObjectExpression(node) {
30
- return node.type === AST_NODE_TYPES.ObjectExpression;
31
- },
32
- isPropertyWithIdentifierKey(node, key) {
33
- return ASTUtils.isProperty(node) && ASTUtils.isIdentifierWithName(node.key, key);
34
- },
35
- findPropertyWithIdentifierKey(properties, key) {
36
- return properties.find(
37
- (x) => ASTUtils.isPropertyWithIdentifierKey(x, key)
38
- );
39
- },
40
- getNestedIdentifiers(node) {
41
- const identifiers = [];
42
- if (ASTUtils.isIdentifier(node)) {
43
- identifiers.push(node);
44
- }
45
- if ("arguments" in node) {
46
- node.arguments.forEach((x) => {
47
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
48
- });
49
- }
50
- if ("elements" in node) {
51
- node.elements.forEach((x) => {
52
- if (x !== null) {
53
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
54
- }
55
- });
56
- }
57
- if ("properties" in node) {
58
- node.properties.forEach((x) => {
59
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
60
- });
61
- }
62
- if ("expressions" in node) {
63
- node.expressions.forEach((x) => {
64
- identifiers.push(...ASTUtils.getNestedIdentifiers(x));
65
- });
66
- }
67
- if ("left" in node) {
68
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.left));
69
- }
70
- if ("right" in node) {
71
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.right));
72
- }
73
- if (node.type === AST_NODE_TYPES.Property) {
74
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.value));
75
- }
76
- if (node.type === AST_NODE_TYPES.SpreadElement) {
77
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument));
78
- }
79
- if (node.type === AST_NODE_TYPES.MemberExpression) {
80
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.object));
81
- }
82
- if (node.type === AST_NODE_TYPES.UnaryExpression) {
83
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument));
84
- }
85
- if (node.type === AST_NODE_TYPES.ChainExpression) {
86
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression));
87
- }
88
- if (node.type === AST_NODE_TYPES.TSNonNullExpression) {
89
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.expression));
90
- }
91
- if (node.type === AST_NODE_TYPES.ArrowFunctionExpression) {
92
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.body));
93
- }
94
- if (node.type === AST_NODE_TYPES.FunctionExpression) {
95
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.body));
96
- }
97
- if (node.type === AST_NODE_TYPES.BlockStatement) {
98
- identifiers.push(
99
- ...node.body.map((body) => ASTUtils.getNestedIdentifiers(body)).flat()
100
- );
101
- }
102
- if (node.type === AST_NODE_TYPES.ReturnStatement && node.argument) {
103
- identifiers.push(...ASTUtils.getNestedIdentifiers(node.argument));
104
- }
105
- return identifiers;
106
- },
107
- isAncestorIsCallee(identifier) {
108
- let previousNode = identifier;
109
- let currentNode = identifier.parent;
110
- while (currentNode !== void 0) {
111
- if (currentNode.type === AST_NODE_TYPES.CallExpression && currentNode.callee === previousNode) {
112
- return true;
113
- }
114
- if (currentNode.type !== AST_NODE_TYPES.MemberExpression) {
115
- return false;
116
- }
117
- previousNode = currentNode;
118
- currentNode = currentNode.parent;
119
- }
120
- return false;
121
- },
122
- traverseUpOnly(identifier, allowedNodeTypes) {
123
- const parent = identifier.parent;
124
- if (parent !== void 0 && allowedNodeTypes.includes(parent.type)) {
125
- return ASTUtils.traverseUpOnly(parent, allowedNodeTypes);
126
- }
127
- return identifier;
128
- },
129
- isDeclaredInNode(params) {
130
- const { functionNode, reference, scopeManager } = params;
131
- const scope = scopeManager.acquire(functionNode);
132
- if (scope === null) {
133
- return false;
134
- }
135
- return scope.set.has(reference.identifier.name);
136
- },
137
- getExternalRefs(params) {
138
- const { scopeManager, sourceCode, node } = params;
139
- const scope = scopeManager.acquire(node);
140
- if (scope === null) {
141
- return [];
142
- }
143
- const references = scope.references.filter((x) => x.isRead() && !scope.set.has(x.identifier.name)).map((x) => {
144
- const referenceNode = ASTUtils.traverseUpOnly(x.identifier, [
145
- AST_NODE_TYPES.MemberExpression,
146
- AST_NODE_TYPES.Identifier
147
- ]);
148
- return {
149
- variable: x,
150
- node: referenceNode,
151
- text: sourceCode.getText(referenceNode)
152
- };
153
- });
154
- const localRefIds = new Set(
155
- [...scope.set.values()].map((x) => sourceCode.getText(x.identifiers[0]))
156
- );
157
- const externalRefs = references.filter(
158
- (x) => x.variable.resolved === null || !localRefIds.has(x.text)
159
- );
160
- return uniqueBy(externalRefs, (x) => x.text).map((x) => x.variable);
161
- },
162
- mapKeyNodeToText(node, sourceCode) {
163
- return sourceCode.getText(
164
- ASTUtils.traverseUpOnly(node, [
165
- AST_NODE_TYPES.MemberExpression,
166
- AST_NODE_TYPES.TSNonNullExpression,
167
- AST_NODE_TYPES.Identifier
168
- ])
169
- );
170
- },
171
- mapKeyNodeToBaseText(node, sourceCode) {
172
- return ASTUtils.mapKeyNodeToText(node, sourceCode).replace(
173
- /(?:\?(\.)|!)/g,
174
- "$1"
175
- );
176
- },
177
- isValidReactComponentOrHookName(identifier) {
178
- return identifier !== null && identifier !== void 0 && /^(use|[A-Z])/.test(identifier.name);
179
- },
180
- getFunctionAncestor(sourceCode, node) {
181
- var _a;
182
- for (const ancestor of sourceCode.getAncestors(node)) {
183
- if (ASTUtils.isNodeOfOneOf(ancestor, [
184
- AST_NODE_TYPES.FunctionDeclaration,
185
- AST_NODE_TYPES.FunctionExpression,
186
- AST_NODE_TYPES.ArrowFunctionExpression
187
- ])) {
188
- return ancestor;
189
- }
190
- if (((_a = ancestor.parent) == null ? void 0 : _a.type) === AST_NODE_TYPES.VariableDeclarator && ancestor.parent.id.type === AST_NODE_TYPES.Identifier && ASTUtils.isNodeOfOneOf(ancestor, [
191
- AST_NODE_TYPES.FunctionDeclaration,
192
- AST_NODE_TYPES.FunctionExpression,
193
- AST_NODE_TYPES.ArrowFunctionExpression
194
- ])) {
195
- return ancestor;
196
- }
197
- }
198
- return void 0;
199
- },
200
- getReferencedExpressionByIdentifier(params) {
201
- var _a, _b, _c;
202
- const { node, context } = params;
203
- const sourceCode = context.sourceCode ?? context.getSourceCode();
204
- const scope = context.sourceCode.getScope(node) ? sourceCode.getScope(node) : context.getScope();
205
- const resolvedNode = (_c = (_b = (_a = scope.references.find((ref) => ref.identifier === node)) == null ? void 0 : _a.resolved) == null ? void 0 : _b.defs[0]) == null ? void 0 : _c.node;
206
- if ((resolvedNode == null ? void 0 : resolvedNode.type) !== AST_NODE_TYPES.VariableDeclarator) {
207
- return null;
208
- }
209
- return resolvedNode.init;
210
- },
211
- getClosestVariableDeclarator(node) {
212
- let currentNode = node;
213
- while (currentNode.type !== AST_NODE_TYPES.Program) {
214
- if (currentNode.type === AST_NODE_TYPES.VariableDeclarator) {
215
- return currentNode;
216
- }
217
- currentNode = currentNode.parent;
218
- }
219
- return void 0;
220
- },
221
- getNestedReturnStatements(node) {
222
- const returnStatements = [];
223
- if (node.type === AST_NODE_TYPES.ReturnStatement) {
224
- returnStatements.push(node);
225
- }
226
- if ("body" in node && node.body !== void 0 && node.body !== null) {
227
- Array.isArray(node.body) ? node.body.forEach((x) => {
228
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
229
- }) : returnStatements.push(
230
- ...ASTUtils.getNestedReturnStatements(node.body)
231
- );
232
- }
233
- if ("consequent" in node) {
234
- Array.isArray(node.consequent) ? node.consequent.forEach((x) => {
235
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
236
- }) : returnStatements.push(
237
- ...ASTUtils.getNestedReturnStatements(node.consequent)
238
- );
239
- }
240
- if ("alternate" in node && node.alternate !== null) {
241
- Array.isArray(node.alternate) ? node.alternate.forEach((x) => {
242
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
243
- }) : returnStatements.push(
244
- ...ASTUtils.getNestedReturnStatements(node.alternate)
245
- );
246
- }
247
- if ("cases" in node) {
248
- node.cases.forEach((x) => {
249
- returnStatements.push(...ASTUtils.getNestedReturnStatements(x));
250
- });
251
- }
252
- if ("block" in node) {
253
- returnStatements.push(...ASTUtils.getNestedReturnStatements(node.block));
254
- }
255
- if ("handler" in node && node.handler !== null) {
256
- returnStatements.push(...ASTUtils.getNestedReturnStatements(node.handler));
257
- }
258
- if ("finalizer" in node && node.finalizer !== null) {
259
- returnStatements.push(
260
- ...ASTUtils.getNestedReturnStatements(node.finalizer)
261
- );
262
- }
263
- if ("expression" in node && node.expression !== true && node.expression !== false) {
264
- returnStatements.push(
265
- ...ASTUtils.getNestedReturnStatements(node.expression)
266
- );
267
- }
268
- if ("test" in node && node.test !== null) {
269
- returnStatements.push(...ASTUtils.getNestedReturnStatements(node.test));
270
- }
271
- return returnStatements;
272
- }
273
- };
274
-
275
- // src/utils/get-docs-url.ts
276
- var getDocsUrl = (ruleName) => `https://tanstack.com/query/latest/docs/eslint/${ruleName}`;
277
-
278
- // src/utils/detect-react-query-imports.ts
279
- import { TSESTree } from "@typescript-eslint/utils";
280
- function detectTanstackQueryImports(create) {
281
- return (context, optionsWithDefault) => {
282
- const tanstackQueryImportSpecifiers = [];
283
- const helpers = {
284
- isSpecificTanstackQueryImport(node, source) {
285
- return !!tanstackQueryImportSpecifiers.find((specifier) => {
286
- if (specifier.type === TSESTree.AST_NODE_TYPES.ImportSpecifier && specifier.parent.type === TSESTree.AST_NODE_TYPES.ImportDeclaration && specifier.parent.source.value === source) {
287
- return node.name === specifier.local.name;
288
- }
289
- return false;
290
- });
291
- },
292
- isTanstackQueryImport(node) {
293
- return !!tanstackQueryImportSpecifiers.find((specifier) => {
294
- if (specifier.type === TSESTree.AST_NODE_TYPES.ImportSpecifier) {
295
- return node.name === specifier.local.name;
296
- }
297
- return false;
298
- });
299
- }
300
- };
301
- const detectionInstructions = {
302
- ImportDeclaration(node) {
303
- if (node.specifiers.length > 0 && // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
304
- (node.importKind === "value" || node.importKind === void 0) && node.source.value.startsWith("@tanstack/") && node.source.value.endsWith("-query")) {
305
- tanstackQueryImportSpecifiers.push(...node.specifiers);
306
- }
307
- }
308
- };
309
- const ruleInstructions = create(context, optionsWithDefault, helpers);
310
- const enhancedRuleInstructions = {};
311
- const allKeys = new Set(
312
- Object.keys(detectionInstructions).concat(Object.keys(ruleInstructions))
313
- );
314
- allKeys.forEach((instruction) => {
315
- enhancedRuleInstructions[instruction] = (node) => {
316
- var _a;
317
- if (instruction in detectionInstructions) {
318
- (_a = detectionInstructions[instruction]) == null ? void 0 : _a.call(detectionInstructions, node);
319
- }
320
- const ruleInstruction = ruleInstructions[instruction];
321
- if (ruleInstruction) {
322
- return ruleInstruction(node);
323
- }
324
- return void 0;
325
- };
326
- });
327
- return enhancedRuleInstructions;
328
- };
329
- }
330
-
331
- // src/rules/exhaustive-deps/exhaustive-deps.utils.ts
332
- import { AST_NODE_TYPES as AST_NODE_TYPES2 } from "@typescript-eslint/utils";
333
- var ExhaustiveDepsUtils = {
334
- isRelevantReference(params) {
335
- var _a;
336
- const { sourceCode, reference, scopeManager, node, filename } = params;
337
- const component = ASTUtils.getFunctionAncestor(sourceCode, node);
338
- if (component !== void 0) {
339
- if (!ASTUtils.isDeclaredInNode({
340
- scopeManager,
341
- reference,
342
- functionNode: component
343
- })) {
344
- return false;
345
- }
346
- } else {
347
- const isVueFile = filename.endsWith(".vue");
348
- if (!isVueFile) {
349
- return false;
350
- }
351
- const definition = (_a = reference.resolved) == null ? void 0 : _a.defs[0];
352
- const isGlobalVariable = definition === void 0;
353
- const isImport = (definition == null ? void 0 : definition.type) === "ImportBinding";
354
- if (isGlobalVariable || isImport) {
355
- return false;
356
- }
357
- }
358
- return reference.identifier.name !== "undefined" && reference.identifier.parent.type !== AST_NODE_TYPES2.NewExpression && !ExhaustiveDepsUtils.isInstanceOfKind(reference.identifier.parent);
359
- },
360
- isInstanceOfKind(node) {
361
- return node.type === AST_NODE_TYPES2.BinaryExpression && node.operator === "instanceof";
362
- }
363
- };
364
-
365
- // src/rules/exhaustive-deps/exhaustive-deps.rule.ts
366
- var QUERY_KEY = "queryKey";
367
- var QUERY_FN = "queryFn";
368
- var name = "exhaustive-deps";
369
- var createRule = ESLintUtils.RuleCreator(getDocsUrl);
370
- var rule = createRule({
371
- name,
372
- meta: {
373
- type: "problem",
374
- docs: {
375
- description: "Exhaustive deps rule for useQuery",
376
- recommended: "error"
377
- },
378
- messages: {
379
- missingDeps: `The following dependencies are missing in your queryKey: {{deps}}`,
380
- fixTo: "Fix to {{result}}"
381
- },
382
- hasSuggestions: true,
383
- fixable: "code",
384
- schema: []
385
- },
386
- defaultOptions: [],
387
- create: detectTanstackQueryImports((context) => {
388
- return {
389
- Property: (node) => {
390
- if (!ASTUtils.isObjectExpression(node.parent) || !ASTUtils.isIdentifierWithName(node.key, QUERY_KEY)) {
391
- return;
392
- }
393
- const scopeManager = context.sourceCode.scopeManager;
394
- const queryKey = ASTUtils.findPropertyWithIdentifierKey(
395
- node.parent.properties,
396
- QUERY_KEY
397
- );
398
- const queryFn = ASTUtils.findPropertyWithIdentifierKey(
399
- node.parent.properties,
400
- QUERY_FN
401
- );
402
- if (scopeManager === null || queryKey === void 0 || queryFn === void 0 || !ASTUtils.isNodeOfOneOf(queryFn.value, [
403
- AST_NODE_TYPES3.ArrowFunctionExpression,
404
- AST_NODE_TYPES3.FunctionExpression,
405
- AST_NODE_TYPES3.ConditionalExpression
406
- ])) {
407
- return;
408
- }
409
- const queryKeyNode = dereferenceVariablesAndTypeAssertions(
410
- queryKey.value,
411
- context
412
- );
413
- const externalRefs = ASTUtils.getExternalRefs({
414
- scopeManager,
415
- sourceCode: context.sourceCode,
416
- node: getQueryFnRelevantNode(queryFn)
417
- });
418
- const relevantRefs = externalRefs.filter(
419
- (reference) => ExhaustiveDepsUtils.isRelevantReference({
420
- sourceCode: context.sourceCode,
421
- reference,
422
- scopeManager,
423
- node: getQueryFnRelevantNode(queryFn),
424
- filename: context.filename
425
- })
426
- );
427
- const existingKeys = ASTUtils.getNestedIdentifiers(queryKeyNode).map(
428
- (identifier) => ASTUtils.mapKeyNodeToBaseText(identifier, context.sourceCode)
429
- );
430
- const missingRefs = relevantRefs.map((ref) => ({
431
- ref,
432
- text: ASTUtils.mapKeyNodeToBaseText(
433
- ref.identifier,
434
- context.sourceCode
435
- )
436
- })).filter(({ ref, text }) => {
437
- return !ref.isTypeReference && !ASTUtils.isAncestorIsCallee(ref.identifier) && !existingKeys.some((existingKey) => existingKey === text) && !existingKeys.includes(text.split(/[?.]/)[0] ?? "");
438
- }).map(({ ref, text }) => ({
439
- identifier: ref.identifier,
440
- text
441
- }));
442
- const uniqueMissingRefs = uniqueBy(missingRefs, (x) => x.text);
443
- if (uniqueMissingRefs.length > 0) {
444
- const missingAsText = uniqueMissingRefs.map(
445
- (ref) => ASTUtils.mapKeyNodeToText(ref.identifier, context.sourceCode)
446
- ).join(", ");
447
- const queryKeyValue = context.sourceCode.getText(queryKeyNode);
448
- const existingWithMissing = queryKeyValue === "[]" ? `[${missingAsText}]` : queryKeyValue.replace(/\]$/, `, ${missingAsText}]`);
449
- const suggestions = [];
450
- if (queryKeyNode.type === AST_NODE_TYPES3.ArrayExpression) {
451
- suggestions.push({
452
- messageId: "fixTo",
453
- data: { result: existingWithMissing },
454
- fix(fixer) {
455
- return fixer.replaceText(queryKeyNode, existingWithMissing);
456
- }
457
- });
458
- }
459
- context.report({
460
- node,
461
- messageId: "missingDeps",
462
- data: {
463
- deps: uniqueMissingRefs.map((ref) => ref.text).join(", ")
464
- },
465
- suggest: suggestions
466
- });
467
- }
468
- }
469
- };
470
- })
471
- });
472
- function getQueryFnRelevantNode(queryFn) {
473
- if (queryFn.value.type !== AST_NODE_TYPES3.ConditionalExpression) {
474
- return queryFn.value;
475
- }
476
- if (queryFn.value.consequent.type === AST_NODE_TYPES3.Identifier && queryFn.value.consequent.name === "skipToken") {
477
- return queryFn.value.alternate;
478
- }
479
- return queryFn.value.consequent;
480
- }
481
- function dereferenceVariablesAndTypeAssertions(queryKeyNode, context) {
482
- const visitedNodes = /* @__PURE__ */ new Set();
483
- for (let i = 0; i < 1 << 8; ++i) {
484
- if (visitedNodes.has(queryKeyNode)) {
485
- return queryKeyNode;
486
- }
487
- visitedNodes.add(queryKeyNode);
488
- switch (queryKeyNode.type) {
489
- case AST_NODE_TYPES3.TSAsExpression:
490
- queryKeyNode = queryKeyNode.expression;
491
- break;
492
- case AST_NODE_TYPES3.Identifier: {
493
- const expression = ASTUtils.getReferencedExpressionByIdentifier({
494
- context,
495
- node: queryKeyNode
496
- });
497
- if (expression == null) {
498
- return queryKeyNode;
499
- }
500
- queryKeyNode = expression;
501
- break;
502
- }
503
- default:
504
- return queryKeyNode;
505
- }
506
- }
507
- return queryKeyNode;
508
- }
509
-
510
- // src/rules/stable-query-client/stable-query-client.rule.ts
511
- import { AST_NODE_TYPES as AST_NODE_TYPES4, ESLintUtils as ESLintUtils2 } from "@typescript-eslint/utils";
512
- var name2 = "stable-query-client";
513
- var createRule2 = ESLintUtils2.RuleCreator(getDocsUrl);
514
- var rule2 = createRule2({
515
- name: name2,
516
- meta: {
517
- type: "problem",
518
- docs: {
519
- description: "Makes sure that QueryClient is stable",
520
- recommended: "error"
521
- },
522
- messages: {
523
- unstable: [
524
- "QueryClient is not stable. It should be either extracted from the component or wrapped in React.useState.",
525
- "See https://tkdodo.eu/blog/react-query-fa-qs#2-the-queryclient-is-not-stable"
526
- ].join("\n"),
527
- fixTo: "Fix to {{result}}"
528
- },
529
- hasSuggestions: true,
530
- fixable: "code",
531
- schema: []
532
- },
533
- defaultOptions: [],
534
- create: detectTanstackQueryImports((context, _, helpers) => {
535
- return {
536
- NewExpression: (node) => {
537
- if (node.callee.type !== AST_NODE_TYPES4.Identifier || node.callee.name !== "QueryClient" || node.parent.type !== AST_NODE_TYPES4.VariableDeclarator || !helpers.isSpecificTanstackQueryImport(
538
- node.callee,
539
- "@tanstack/react-query"
540
- )) {
541
- return;
542
- }
543
- const fnAncestor = ASTUtils.getFunctionAncestor(
544
- context.sourceCode,
545
- node
546
- );
547
- const isReactServerComponent = (fnAncestor == null ? void 0 : fnAncestor.async) === true;
548
- if (!ASTUtils.isValidReactComponentOrHookName(fnAncestor == null ? void 0 : fnAncestor.id) || isReactServerComponent) {
549
- return;
550
- }
551
- context.report({
552
- node: node.parent,
553
- messageId: "unstable",
554
- fix: (() => {
555
- const { parent } = node;
556
- if (parent.id.type !== AST_NODE_TYPES4.Identifier) {
557
- return;
558
- }
559
- const sourceCode = context.sourceCode ?? context.getSourceCode();
560
- const nodeText = sourceCode.getText(node);
561
- const variableName = parent.id.name;
562
- return (fixer) => {
563
- return fixer.replaceTextRange(
564
- [parent.range[0], parent.range[1]],
565
- `[${variableName}] = React.useState(() => ${nodeText})`
566
- );
567
- };
568
- })()
569
- });
570
- }
571
- };
572
- })
573
- });
574
-
575
- // src/rules/no-rest-destructuring/no-rest-destructuring.rule.ts
576
- import { AST_NODE_TYPES as AST_NODE_TYPES6, ESLintUtils as ESLintUtils3 } from "@typescript-eslint/utils";
577
-
578
- // src/rules/no-rest-destructuring/no-rest-destructuring.utils.ts
579
- import { AST_NODE_TYPES as AST_NODE_TYPES5 } from "@typescript-eslint/utils";
580
- var NoRestDestructuringUtils = {
581
- isObjectRestDestructuring(node) {
582
- if (node.type !== AST_NODE_TYPES5.ObjectPattern) {
583
- return false;
584
- }
585
- return node.properties.some((p) => p.type === AST_NODE_TYPES5.RestElement);
586
- }
587
- };
588
-
589
- // src/rules/no-rest-destructuring/no-rest-destructuring.rule.ts
590
- var name3 = "no-rest-destructuring";
591
- var queryHooks = [
592
- "useQuery",
593
- "useQueries",
594
- "useInfiniteQuery",
595
- "useSuspenseQuery",
596
- "useSuspenseQueries",
597
- "useSuspenseInfiniteQuery"
598
- ];
599
- var createRule3 = ESLintUtils3.RuleCreator(getDocsUrl);
600
- var rule3 = createRule3({
601
- name: name3,
602
- meta: {
603
- type: "problem",
604
- docs: {
605
- description: "Disallows rest destructuring in queries",
606
- recommended: "warn"
607
- },
608
- messages: {
609
- objectRestDestructure: `Object rest destructuring on a query will observe all changes to the query, leading to excessive re-renders.`
610
- },
611
- schema: []
612
- },
613
- defaultOptions: [],
614
- create: detectTanstackQueryImports((context, _, helpers) => {
615
- const queryResultVariables = /* @__PURE__ */ new Set();
616
- return {
617
- CallExpression: (node) => {
618
- if (!ASTUtils.isIdentifierWithOneOfNames(node.callee, queryHooks) || node.parent.type !== AST_NODE_TYPES6.VariableDeclarator || !helpers.isTanstackQueryImport(node.callee)) {
619
- return;
620
- }
621
- const returnValue = node.parent.id;
622
- if (node.callee.name !== "useQueries" && node.callee.name !== "useSuspenseQueries") {
623
- if (NoRestDestructuringUtils.isObjectRestDestructuring(returnValue)) {
624
- return context.report({
625
- node: node.parent,
626
- messageId: "objectRestDestructure"
627
- });
628
- }
629
- if (returnValue.type === AST_NODE_TYPES6.Identifier) {
630
- queryResultVariables.add(returnValue.name);
631
- }
632
- return;
633
- }
634
- if (returnValue.type !== AST_NODE_TYPES6.ArrayPattern) {
635
- if (returnValue.type === AST_NODE_TYPES6.Identifier) {
636
- queryResultVariables.add(returnValue.name);
637
- }
638
- return;
639
- }
640
- returnValue.elements.forEach((queryResult) => {
641
- if (queryResult === null) {
642
- return;
643
- }
644
- if (NoRestDestructuringUtils.isObjectRestDestructuring(queryResult)) {
645
- context.report({
646
- node: queryResult,
647
- messageId: "objectRestDestructure"
648
- });
649
- }
650
- });
651
- },
652
- VariableDeclarator: (node) => {
653
- var _a;
654
- if (((_a = node.init) == null ? void 0 : _a.type) === AST_NODE_TYPES6.Identifier && queryResultVariables.has(node.init.name) && NoRestDestructuringUtils.isObjectRestDestructuring(node.id)) {
655
- context.report({
656
- node,
657
- messageId: "objectRestDestructure"
658
- });
659
- }
660
- },
661
- SpreadElement: (node) => {
662
- if (node.argument.type === AST_NODE_TYPES6.Identifier && queryResultVariables.has(node.argument.name)) {
663
- context.report({
664
- node,
665
- messageId: "objectRestDestructure"
666
- });
667
- }
668
- }
669
- };
670
- })
671
- });
672
-
673
- // src/rules/no-unstable-deps/no-unstable-deps.rule.ts
674
- import { AST_NODE_TYPES as AST_NODE_TYPES7, ESLintUtils as ESLintUtils4 } from "@typescript-eslint/utils";
675
- var name4 = "no-unstable-deps";
676
- var reactHookNames = ["useEffect", "useCallback", "useMemo"];
677
- var useQueryHookNames = [
678
- "useQuery",
679
- "useSuspenseQuery",
680
- "useQueries",
681
- "useSuspenseQueries",
682
- "useInfiniteQuery",
683
- "useSuspenseInfiniteQuery"
684
- ];
685
- var allHookNames = ["useMutation", ...useQueryHookNames];
686
- var createRule4 = ESLintUtils4.RuleCreator(getDocsUrl);
687
- var rule4 = createRule4({
688
- name: name4,
689
- meta: {
690
- type: "problem",
691
- docs: {
692
- description: "Disallow putting the result of query hooks directly in a React hook dependency array",
693
- recommended: "error"
694
- },
695
- messages: {
696
- noUnstableDeps: `The result of {{queryHook}} is not referentially stable, so don't pass it directly into the dependencies array of {{reactHook}}. Instead, destructure the return value of {{queryHook}} and pass the destructured values into the dependency array of {{reactHook}}.`
697
- },
698
- schema: []
699
- },
700
- defaultOptions: [],
701
- create: detectTanstackQueryImports((context, _options, helpers) => {
702
- const trackedVariables = {};
703
- const hookAliasMap = {};
704
- function getReactHook(node) {
705
- if (node.callee.type === "Identifier") {
706
- const calleeName = node.callee.name;
707
- if (reactHookNames.includes(calleeName) || calleeName in hookAliasMap) {
708
- return calleeName;
709
- }
710
- } else if (node.callee.type === "MemberExpression" && node.callee.object.type === "Identifier" && node.callee.object.name === "React" && node.callee.property.type === "Identifier" && reactHookNames.includes(node.callee.property.name)) {
711
- return node.callee.property.name;
712
- }
713
- return void 0;
714
- }
715
- function collectVariableNames(pattern, queryHook) {
716
- if (pattern.type === AST_NODE_TYPES7.Identifier) {
717
- trackedVariables[pattern.name] = queryHook;
718
- }
719
- }
720
- function hasCombineProperty(callExpression) {
721
- if (callExpression.arguments.length === 0) return false;
722
- const firstArg = callExpression.arguments[0];
723
- if (!firstArg || firstArg.type !== AST_NODE_TYPES7.ObjectExpression)
724
- return false;
725
- return firstArg.properties.some(
726
- (prop) => prop.type === AST_NODE_TYPES7.Property && prop.key.type === AST_NODE_TYPES7.Identifier && prop.key.name === "combine"
727
- );
728
- }
729
- return {
730
- ImportDeclaration(node) {
731
- if (node.specifiers.length > 0 && node.importKind === "value" && node.source.value === "React") {
732
- node.specifiers.forEach((specifier) => {
733
- if (specifier.type === AST_NODE_TYPES7.ImportSpecifier && specifier.imported.type === AST_NODE_TYPES7.Identifier && reactHookNames.includes(specifier.imported.name)) {
734
- hookAliasMap[specifier.local.name] = specifier.imported.name;
735
- }
736
- });
737
- }
738
- },
739
- VariableDeclarator(node) {
740
- if (node.init !== null && node.init.type === AST_NODE_TYPES7.CallExpression && node.init.callee.type === AST_NODE_TYPES7.Identifier && allHookNames.includes(node.init.callee.name) && helpers.isTanstackQueryImport(node.init.callee)) {
741
- if (node.init.callee.name === "useQueries" && hasCombineProperty(node.init)) {
742
- return;
743
- }
744
- collectVariableNames(node.id, node.init.callee.name);
745
- }
746
- },
747
- CallExpression: (node) => {
748
- var _a;
749
- const reactHook = getReactHook(node);
750
- if (reactHook !== void 0 && node.arguments.length > 1 && ((_a = node.arguments[1]) == null ? void 0 : _a.type) === AST_NODE_TYPES7.ArrayExpression) {
751
- const depsArray = node.arguments[1].elements;
752
- depsArray.forEach((dep) => {
753
- if (dep !== null && dep.type === AST_NODE_TYPES7.Identifier && trackedVariables[dep.name] !== void 0) {
754
- const queryHook = trackedVariables[dep.name];
755
- context.report({
756
- node: dep,
757
- messageId: "noUnstableDeps",
758
- data: {
759
- queryHook,
760
- reactHook
761
- }
762
- });
763
- }
764
- });
765
- }
766
- }
767
- };
768
- })
769
- });
770
-
771
- // src/utils/create-property-order-rule.ts
772
- import { AST_NODE_TYPES as AST_NODE_TYPES8, ESLintUtils as ESLintUtils5 } from "@typescript-eslint/utils";
773
-
774
- // src/utils/sort-data-by-order.ts
775
- function sortDataByOrder(data, orderRules, key) {
776
- const getSubsetIndex = (item, subsets) => {
777
- var _a;
778
- for (let i = 0; i < subsets.length; i++) {
779
- if ((_a = subsets[i]) == null ? void 0 : _a.includes(item)) {
780
- return i;
781
- }
782
- }
783
- return null;
784
- };
785
- const orderSets = orderRules.reduce(
786
- (sets, [A, B]) => [...sets, A, B],
787
- []
788
- );
789
- const inOrderArray = data.filter(
790
- (item) => getSubsetIndex(item[key], orderSets) !== null
791
- );
792
- let wasResorted = false;
793
- const sortedArray = inOrderArray.sort((a, b) => {
794
- const aKey = a[key], bKey = b[key];
795
- const aSubsetIndex = getSubsetIndex(aKey, orderSets);
796
- const bSubsetIndex = getSubsetIndex(bKey, orderSets);
797
- if (aSubsetIndex !== null && bSubsetIndex !== null && aSubsetIndex !== bSubsetIndex) {
798
- return aSubsetIndex - bSubsetIndex;
799
- }
800
- return 0;
801
- });
802
- const inOrderIterator = sortedArray.values();
803
- const result = data.map((item) => {
804
- if (getSubsetIndex(item[key], orderSets) !== null) {
805
- const sortedItem = inOrderIterator.next().value;
806
- if (sortedItem[key] !== item[key]) {
807
- wasResorted = true;
808
- }
809
- return sortedItem;
810
- }
811
- return item;
812
- });
813
- if (!wasResorted) {
814
- return null;
815
- }
816
- return result;
817
- }
818
-
819
- // src/utils/create-property-order-rule.ts
820
- var createRule5 = ESLintUtils5.RuleCreator(getDocsUrl);
821
- function createPropertyOrderRule(options, targetFunctions, orderRules) {
822
- const targetFunctionSet = new Set(targetFunctions);
823
- function isTargetFunction(node) {
824
- return targetFunctionSet.has(node);
825
- }
826
- return createRule5({
827
- ...options,
828
- create: detectTanstackQueryImports((context) => {
829
- return {
830
- CallExpression(node) {
831
- if (node.callee.type !== AST_NODE_TYPES8.Identifier) {
832
- return;
833
- }
834
- const functions = node.callee.name;
835
- if (!isTargetFunction(functions)) {
836
- return;
837
- }
838
- const argument = node.arguments[0];
839
- if (argument === void 0 || argument.type !== "ObjectExpression") {
840
- return;
841
- }
842
- const allProperties = argument.properties;
843
- if (allProperties.length < 2) {
844
- return;
845
- }
846
- const properties = allProperties.flatMap((p, index) => {
847
- if (p.type === AST_NODE_TYPES8.Property && p.key.type === AST_NODE_TYPES8.Identifier) {
848
- return { name: p.key.name, property: p };
849
- } else return { name: `_property_${index}`, property: p };
850
- });
851
- const sortedProperties = sortDataByOrder(
852
- properties,
853
- orderRules,
854
- "name"
855
- );
856
- if (sortedProperties === null) {
857
- return;
858
- }
859
- context.report({
860
- node: argument,
861
- data: { function: node.callee.name },
862
- messageId: "invalidOrder",
863
- fix(fixer) {
864
- const sourceCode = context.sourceCode;
865
- const reorderedText = sortedProperties.reduce(
866
- (sourceText, specifier, index) => {
867
- let textBetweenProperties = "";
868
- if (index < allProperties.length - 1) {
869
- textBetweenProperties = sourceCode.getText().slice(
870
- allProperties[index].range[1],
871
- allProperties[index + 1].range[0]
872
- );
873
- }
874
- return sourceText + sourceCode.getText(specifier.property) + textBetweenProperties;
875
- },
876
- ""
877
- );
878
- return fixer.replaceTextRange(
879
- [allProperties[0].range[0], allProperties.at(-1).range[1]],
880
- reorderedText
881
- );
882
- }
883
- });
884
- }
885
- };
886
- })
887
- });
888
- }
889
-
890
- // src/rules/infinite-query-property-order/constants.ts
891
- var infiniteQueryFunctions = [
892
- "infiniteQueryOptions",
893
- "useInfiniteQuery",
894
- "useSuspenseInfiniteQuery"
895
- ];
896
- var sortRules = [
897
- [["queryFn"], ["getPreviousPageParam", "getNextPageParam"]]
898
- ];
899
-
900
- // src/rules/infinite-query-property-order/infinite-query-property-order.rule.ts
901
- var name5 = "infinite-query-property-order";
902
- var rule5 = createPropertyOrderRule(
903
- {
904
- name: name5,
905
- meta: {
906
- type: "problem",
907
- docs: {
908
- description: "Ensure correct order of inference sensitive properties for infinite queries",
909
- recommended: "error"
910
- },
911
- messages: {
912
- invalidOrder: "Invalid order of properties for `{{function}}`."
913
- },
914
- schema: [],
915
- hasSuggestions: true,
916
- fixable: "code"
917
- },
918
- defaultOptions: []
919
- },
920
- infiniteQueryFunctions,
921
- sortRules
922
- );
923
-
924
- // src/rules/no-void-query-fn/no-void-query-fn.rule.ts
925
- import { ESLintUtils as ESLintUtils6 } from "@typescript-eslint/utils";
926
- var TypeFlags = {
927
- Void: 16384,
928
- Undefined: 32768
929
- };
930
- var name6 = "no-void-query-fn";
931
- var createRule6 = ESLintUtils6.RuleCreator(getDocsUrl);
932
- var rule6 = createRule6({
933
- name: name6,
934
- meta: {
935
- type: "problem",
936
- docs: {
937
- description: "Ensures queryFn returns a non-undefined value",
938
- recommended: "error"
939
- },
940
- messages: {
941
- noVoidReturn: "queryFn must return a non-undefined value"
942
- },
943
- schema: []
944
- },
945
- defaultOptions: [],
946
- create: detectTanstackQueryImports((context) => {
947
- return {
948
- Property(node) {
949
- var _a;
950
- if (!ASTUtils.isObjectExpression(node.parent) || !ASTUtils.isIdentifierWithName(node.key, "queryFn")) {
951
- return;
952
- }
953
- const parserServices = context.sourceCode.parserServices;
954
- if (!parserServices || !parserServices.esTreeNodeToTSNodeMap || !parserServices.program) {
955
- return;
956
- }
957
- const checker = parserServices.program.getTypeChecker();
958
- const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node.value);
959
- const type = checker.getTypeAtLocation(tsNode);
960
- if (type.getCallSignatures().length > 0) {
961
- const returnType = (_a = type.getCallSignatures()[0]) == null ? void 0 : _a.getReturnType();
962
- if (!returnType) {
963
- return;
964
- }
965
- if (isIllegalReturn(checker, returnType)) {
966
- context.report({
967
- node: node.value,
968
- messageId: "noVoidReturn"
969
- });
970
- }
971
- }
972
- }
973
- };
974
- })
975
- });
976
- function isIllegalReturn(checker, type) {
977
- const awaited = checker.getAwaitedType(type);
978
- if (!awaited) return false;
979
- if (awaited.isUnion()) {
980
- return awaited.types.some((t) => isIllegalReturn(checker, t));
981
- }
982
- return awaited.flags & (TypeFlags.Void | TypeFlags.Undefined) ? true : false;
983
- }
984
-
985
- // src/rules/mutation-property-order/constants.ts
986
- var mutationFunctions = ["useMutation"];
987
- var sortRules2 = [[["onMutate"], ["onError", "onSettled"]]];
988
-
989
- // src/rules/mutation-property-order/mutation-property-order.rule.ts
990
- var name7 = "mutation-property-order";
991
- var rule7 = createPropertyOrderRule(
992
- {
993
- name: name7,
994
- meta: {
995
- type: "problem",
996
- docs: {
997
- description: "Ensure correct order of inference-sensitive properties in useMutation()",
998
- recommended: "error"
999
- },
1000
- messages: {
1001
- invalidOrder: "Invalid order of properties for `{{function}}`."
1002
- },
1003
- schema: [],
1004
- hasSuggestions: true,
1005
- fixable: "code"
1006
- },
1007
- defaultOptions: []
1008
- },
1009
- mutationFunctions,
1010
- sortRules2
1011
- );
1012
-
1013
- // src/rules.ts
1014
- var rules = {
1015
- [name]: rule,
1016
- [name2]: rule2,
1017
- [name3]: rule3,
1018
- [name4]: rule4,
1019
- [name5]: rule5,
1020
- [name6]: rule6,
1021
- [name7]: rule7
1022
- };
1023
-
1024
- export {
1025
- rules
1026
- };
1027
- //# sourceMappingURL=chunk-MUQBIZ2R.js.map