@checkdigit/eslint-plugin 7.6.0-PR.75-4751 → 7.6.0-PR.97-af5e

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 (77) hide show
  1. package/dist-mjs/index.mjs +8 -156
  2. package/dist-mjs/no-status-code-assert.mjs +63 -0
  3. package/dist-mjs/require-resolve-full-response.mjs +5 -5
  4. package/dist-types/no-status-code-assert.d.ts +5 -0
  5. package/package.json +1 -1
  6. package/src/index.ts +4 -152
  7. package/src/no-status-code-assert.ts +85 -0
  8. package/src/require-resolve-full-response.ts +4 -4
  9. package/dist-mjs/agent/add-assert-import.mjs +0 -58
  10. package/dist-mjs/agent/add-base-path-const.mjs +0 -65
  11. package/dist-mjs/agent/add-base-path-import.mjs +0 -60
  12. package/dist-mjs/agent/add-url-domain.mjs +0 -61
  13. package/dist-mjs/agent/agent-test-wiring.mjs +0 -221
  14. package/dist-mjs/agent/fetch-response-body-json.mjs +0 -146
  15. package/dist-mjs/agent/fetch-response-header-getter.mjs +0 -117
  16. package/dist-mjs/agent/fetch-response-status.mjs +0 -76
  17. package/dist-mjs/agent/fetch-then.mjs +0 -205
  18. package/dist-mjs/agent/fetch.mjs +0 -48
  19. package/dist-mjs/agent/file.mjs +0 -43
  20. package/dist-mjs/agent/fix-function-call-arguments.mjs +0 -153
  21. package/dist-mjs/agent/no-fixture.mjs +0 -383
  22. package/dist-mjs/agent/no-mapped-response.mjs +0 -75
  23. package/dist-mjs/agent/no-service-wrapper.mjs +0 -185
  24. package/dist-mjs/agent/no-status-code.mjs +0 -59
  25. package/dist-mjs/agent/no-supertest.mjs +0 -332
  26. package/dist-mjs/agent/no-unused-function-argument.mjs +0 -79
  27. package/dist-mjs/agent/no-unused-imports.mjs +0 -81
  28. package/dist-mjs/agent/no-unused-service-variable.mjs +0 -74
  29. package/dist-mjs/agent/response-reference.mjs +0 -75
  30. package/dist-mjs/agent/supertest-then.mjs +0 -170
  31. package/dist-mjs/agent/url.mjs +0 -32
  32. package/dist-types/agent/add-assert-import.d.ts +0 -4
  33. package/dist-types/agent/add-base-path-const.d.ts +0 -4
  34. package/dist-types/agent/add-base-path-import.d.ts +0 -4
  35. package/dist-types/agent/add-url-domain.d.ts +0 -4
  36. package/dist-types/agent/agent-test-wiring.d.ts +0 -4
  37. package/dist-types/agent/fetch-response-body-json.d.ts +0 -4
  38. package/dist-types/agent/fetch-response-header-getter.d.ts +0 -4
  39. package/dist-types/agent/fetch-response-status.d.ts +0 -4
  40. package/dist-types/agent/fetch-then.d.ts +0 -4
  41. package/dist-types/agent/fetch.d.ts +0 -8
  42. package/dist-types/agent/file.d.ts +0 -7
  43. package/dist-types/agent/fix-function-call-arguments.d.ts +0 -9
  44. package/dist-types/agent/no-fixture.d.ts +0 -4
  45. package/dist-types/agent/no-mapped-response.d.ts +0 -4
  46. package/dist-types/agent/no-service-wrapper.d.ts +0 -4
  47. package/dist-types/agent/no-status-code.d.ts +0 -4
  48. package/dist-types/agent/no-supertest.d.ts +0 -4
  49. package/dist-types/agent/no-unused-function-argument.d.ts +0 -4
  50. package/dist-types/agent/no-unused-imports.d.ts +0 -4
  51. package/dist-types/agent/no-unused-service-variable.d.ts +0 -4
  52. package/dist-types/agent/response-reference.d.ts +0 -16
  53. package/dist-types/agent/supertest-then.d.ts +0 -4
  54. package/dist-types/agent/url.d.ts +0 -4
  55. package/src/agent/add-assert-import.ts +0 -74
  56. package/src/agent/add-base-path-const.ts +0 -81
  57. package/src/agent/add-base-path-import.ts +0 -69
  58. package/src/agent/add-url-domain.ts +0 -76
  59. package/src/agent/agent-test-wiring.ts +0 -273
  60. package/src/agent/fetch-response-body-json.ts +0 -194
  61. package/src/agent/fetch-response-header-getter.ts +0 -148
  62. package/src/agent/fetch-response-status.ts +0 -100
  63. package/src/agent/fetch-then.ts +0 -358
  64. package/src/agent/fetch.ts +0 -69
  65. package/src/agent/file.ts +0 -42
  66. package/src/agent/fix-function-call-arguments.ts +0 -200
  67. package/src/agent/no-fixture.ts +0 -581
  68. package/src/agent/no-mapped-response.ts +0 -84
  69. package/src/agent/no-service-wrapper.ts +0 -241
  70. package/src/agent/no-status-code.ts +0 -69
  71. package/src/agent/no-supertest.ts +0 -517
  72. package/src/agent/no-unused-function-argument.ts +0 -98
  73. package/src/agent/no-unused-imports.ts +0 -103
  74. package/src/agent/no-unused-service-variable.ts +0 -93
  75. package/src/agent/response-reference.ts +0 -153
  76. package/src/agent/supertest-then.ts +0 -230
  77. package/src/agent/url.ts +0 -32
@@ -1,69 +0,0 @@
1
- // agent/add-url-domain.ts
2
-
3
- /*
4
- * Copyright (c) 2021-2024 Check Digit, LLC
5
- *
6
- * This code is licensed under the MIT license (see LICENSE.txt for details).
7
- */
8
-
9
- import { strict as assert } from 'node:assert';
10
-
11
- import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils';
12
-
13
- import getDocumentationUrl from '../get-documentation-url';
14
- import { getApiIndexPathByFilename } from './file';
15
-
16
- export const ruleId = 'add-base-path-import';
17
-
18
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
19
-
20
- const rule: ESLintUtils.RuleModule<'addBasePathImport'> = createRule({
21
- name: ruleId,
22
- meta: {
23
- type: 'suggestion',
24
- docs: {
25
- description: 'Add import of BASE_PATH if it is used but not imported.',
26
- },
27
- messages: {
28
- addBasePathImport: 'Add import of BASE_PATH.',
29
- },
30
- fixable: 'code',
31
- schema: [],
32
- },
33
- defaultOptions: [],
34
- create(context) {
35
- const sourceCode = context.sourceCode;
36
-
37
- return {
38
- Program: (program) => {
39
- const isBasePathUsed = sourceCode.text.includes(`$\{BASE_PATH}`);
40
- if (isBasePathUsed) {
41
- const topScope = sourceCode.getScope(program).childScopes[0];
42
- assert(topScope);
43
- if (topScope.variables.some((variable) => variable.name === 'BASE_PATH')) {
44
- return;
45
- }
46
-
47
- const apiIndexPath = getApiIndexPathByFilename(context.filename);
48
- if (apiIndexPath !== undefined) {
49
- const lastImportStatement = program.body.findLast(
50
- (statement) => statement.type === AST_NODE_TYPES.ImportDeclaration,
51
- );
52
- assert(lastImportStatement);
53
-
54
- const basePathImportStatement = `\nimport { BASE_PATH } from '${apiIndexPath}';\n`;
55
- context.report({
56
- node: program,
57
- messageId: 'addBasePathImport',
58
- fix(fixer) {
59
- return fixer.insertTextAfter(lastImportStatement, basePathImportStatement);
60
- },
61
- });
62
- }
63
- }
64
- },
65
- };
66
- },
67
- });
68
-
69
- export default rule;
@@ -1,76 +0,0 @@
1
- // agent/add-url-domain.ts
2
-
3
- /*
4
- * Copyright (c) 2021-2024 Check Digit, LLC
5
- *
6
- * This code is licensed under the MIT license (see LICENSE.txt for details).
7
- */
8
-
9
- import { AST_NODE_TYPES, ESLintUtils, TSESTree } from '@typescript-eslint/utils';
10
-
11
- import getDocumentationUrl from '../get-documentation-url';
12
- import { addBasePathUrlDomain } from './url';
13
-
14
- export const ruleId = 'add-url-domain';
15
-
16
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
17
-
18
- const rule: ESLintUtils.RuleModule<'addDomain' | 'unknownError'> = createRule({
19
- name: ruleId,
20
- meta: {
21
- type: 'suggestion',
22
- docs: {
23
- description: 'Add HTTP domain to the BASE_PATH like url constant variable.',
24
- },
25
- messages: {
26
- addDomain: 'Add HTTP domain to the BASE_PATH like url constant variable.',
27
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
28
- },
29
- fixable: 'code',
30
- schema: [],
31
- },
32
- defaultOptions: [],
33
- create(context) {
34
- const sourceCode = context.sourceCode;
35
-
36
- return {
37
- 'VariableDeclarator[id.name=/^([A-Z]+_)*BASE_PATH$/]': (basePathDeclarator: TSESTree.VariableDeclarator) => {
38
- try {
39
- if (
40
- basePathDeclarator.init === null ||
41
- (basePathDeclarator.init.type !== AST_NODE_TYPES.Literal &&
42
- basePathDeclarator.init.type !== AST_NODE_TYPES.TemplateLiteral)
43
- ) {
44
- return;
45
- }
46
-
47
- const urlText = sourceCode.getText(basePathDeclarator.init);
48
- const replacement = addBasePathUrlDomain(urlText);
49
-
50
- if (replacement !== urlText) {
51
- context.report({
52
- messageId: 'addDomain',
53
- node: basePathDeclarator.init,
54
- fix(fixer) {
55
- return fixer.replaceText(basePathDeclarator.init as TSESTree.Node, replacement);
56
- },
57
- });
58
- }
59
- } catch (error) {
60
- // eslint-disable-next-line no-console
61
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
62
- context.report({
63
- node: basePathDeclarator,
64
- messageId: 'unknownError',
65
- data: {
66
- fileName: context.filename,
67
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
68
- },
69
- });
70
- }
71
- },
72
- };
73
- },
74
- });
75
-
76
- export default rule;
@@ -1,273 +0,0 @@
1
- // agent/agent-test-wiring.ts
2
-
3
- /*
4
- * Copyright (c) 2021-2024 Check Digit, LLC
5
- *
6
- * This code is licensed under the MIT license (see LICENSE.txt for details).
7
- */
8
-
9
- import { strict as assert } from 'node:assert';
10
-
11
- import { AST_TOKEN_TYPES, ESLintUtils, TSESTree } from '@typescript-eslint/utils';
12
- import type { RuleFix, RuleFixer } from '@typescript-eslint/utils/ts-eslint';
13
- import debug from 'debug';
14
-
15
- import getDocumentationUrl from '../get-documentation-url';
16
-
17
- export const ruleId = 'agent-test-wiring';
18
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
19
- const log = debug('eslint-plugin:agent:agent-test-wiring');
20
-
21
- const STATEMENT_FIXTURE_RESET = 'fixture.reset()';
22
- const STATEMENT_FIXTURE_RESET_AWAITED = `await ${STATEMENT_FIXTURE_RESET};`;
23
- const STATEMENT_AGENT_DECLARATION = 'let agent: Agent;';
24
- const STATEMENT_AGENT_CREATION = 'agent = await createAgent();';
25
- const STATEMENT_AGENT_REGISTER = 'agent.register(await fixturePlugin(fixture));';
26
- const STATEMENT_AGENT_ENABLE = 'agent.enable();';
27
- const STATEMENT_AGENT_DISPOSE = 'await agent[Symbol.asyncDispose]();';
28
-
29
- const rule: ESLintUtils.RuleModule<'updateTestWiring' | 'unknownError'> = createRule({
30
- name: ruleId,
31
- meta: {
32
- type: 'suggestion',
33
- docs: {
34
- description: 'Update test wiring.',
35
- },
36
- messages: {
37
- updateTestWiring: 'Updating test wiring.',
38
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
39
- },
40
- fixable: 'code',
41
- schema: [],
42
- },
43
- defaultOptions: [],
44
- // eslint-disable-next-line max-lines-per-function
45
- create(context) {
46
- log('Processing file:', context.filename);
47
- const sourceCode = context.sourceCode;
48
- const importDeclarations = new Map<string, TSESTree.ImportDeclaration>();
49
- let isFixtureUsed = false;
50
- let beforeAll: TSESTree.CallExpression | undefined;
51
- let beforeEach: TSESTree.CallExpression | undefined;
52
- let afterAll: TSESTree.CallExpression | undefined;
53
-
54
- return {
55
- ImportDeclaration(importDeclaration) {
56
- const moduleName = importDeclaration.source.value;
57
- importDeclarations.set(moduleName, importDeclaration);
58
- if (
59
- moduleName === '@checkdigit/fixture' &&
60
- importDeclaration.specifiers.some(
61
- (specifier) =>
62
- specifier.type === TSESTree.AST_NODE_TYPES.ImportSpecifier &&
63
- specifier.imported.type === TSESTree.AST_NODE_TYPES.Identifier &&
64
- specifier.imported.name === 'createFixture',
65
- )
66
- ) {
67
- isFixtureUsed = true;
68
- }
69
- },
70
- 'CallExpression[callee.name="beforeAll"]': (callExpression: TSESTree.CallExpression) => {
71
- beforeAll = callExpression;
72
- },
73
- 'CallExpression[callee.name="beforeEach"]': (callExpression: TSESTree.CallExpression) => {
74
- beforeEach = callExpression;
75
- },
76
- 'CallExpression[callee.name="afterAll"]': (callExpression: TSESTree.CallExpression) => {
77
- afterAll = callExpression;
78
- },
79
- // eslint-disable-next-line sonarjs/cognitive-complexity
80
- 'Program:exit'(program) {
81
- if (!isFixtureUsed || (beforeAll === undefined && beforeEach === undefined)) {
82
- // only update test wiring if fixture is used
83
- return;
84
- }
85
-
86
- try {
87
- let jestImportFixer: ((fixer: RuleFixer) => RuleFix) | undefined;
88
- let agentImportFixer: ((fixer: RuleFixer) => RuleFix) | undefined;
89
- let fixturePluginImportFixer: ((fixer: RuleFixer) => RuleFix) | undefined;
90
- let agentDeclarationFixer: ((fixer: RuleFixer) => RuleFix) | undefined;
91
- let beforeAllOrEachFixer: ((fixer: RuleFixer) => RuleFix) | undefined;
92
- let afterAllFixer: ((fixer: RuleFixer) => RuleFix) | undefined;
93
-
94
- const lastImportDeclaration = [...importDeclarations.values()].at(-1);
95
- assert.ok(lastImportDeclaration);
96
-
97
- // make sure that afterAll is imported from jest
98
- const jestImportDeclaration = importDeclarations.get('@jest/globals');
99
- assert.ok(jestImportDeclaration);
100
- const importsToAdd = ['afterAll', 'beforeAll'].filter(
101
- (jestHook) =>
102
- !jestImportDeclaration.specifiers.some(
103
- (specifier) =>
104
- specifier.type === TSESTree.AST_NODE_TYPES.ImportSpecifier &&
105
- specifier.imported.type === TSESTree.AST_NODE_TYPES.Identifier &&
106
- specifier.imported.name === jestHook,
107
- ),
108
- );
109
- if (importsToAdd.length > 0) {
110
- const firstImportSpecifier = jestImportDeclaration.specifiers[0];
111
- assert.ok(firstImportSpecifier);
112
- jestImportFixer = (fixer: RuleFixer) =>
113
- fixer.insertTextBefore(firstImportSpecifier, `${importsToAdd.join(', ')}, `);
114
- }
115
-
116
- // make sure that agent is imported
117
- const agentImportDeclaration = importDeclarations.get('@checkdigit/agent');
118
- if (!agentImportDeclaration) {
119
- agentImportFixer = (fixer: RuleFixer) =>
120
- fixer.insertTextAfter(
121
- lastImportDeclaration,
122
- `\nimport createAgent, { type Agent } from '@checkdigit/agent';`,
123
- );
124
- }
125
-
126
- // make sure that fixture plugin is imported
127
- const pathLets = context.filename.split('/');
128
- const currentFileIndex = pathLets.length - 1;
129
- const pluginFolderIndex = pathLets.lastIndexOf('src') + 1;
130
- // it should be safe to assume that the test code is always at least one level deeper than the plugin folder
131
- const fixturePluginImportPath = `${'../'.repeat(currentFileIndex - pluginFolderIndex)}plugin/fixture.test`;
132
- if (!importDeclarations.get(fixturePluginImportPath)) {
133
- fixturePluginImportFixer = (fixer: RuleFixer) =>
134
- fixer.insertTextAfter(lastImportDeclaration, `\nimport fixturePlugin from '${fixturePluginImportPath}';`);
135
- }
136
-
137
- // inject agent declaration and initialization
138
- if (beforeAll === undefined) {
139
- // create `beforeAll` block if it doesn't exist
140
- beforeAllOrEachFixer = (fixer: RuleFixer) =>
141
- fixer.insertTextBefore(
142
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
143
- beforeEach!,
144
- [
145
- STATEMENT_AGENT_DECLARATION,
146
- `beforeAll(async () => {`,
147
- [STATEMENT_AGENT_CREATION, STATEMENT_AGENT_REGISTER, STATEMENT_AGENT_ENABLE].join('\n'),
148
- `});\n`,
149
- ].join('\n'),
150
- );
151
- } else {
152
- const beforeAllArgument = beforeAll.arguments[0];
153
- assert.ok(beforeAllArgument !== undefined);
154
- if (!sourceCode.getText(beforeAllArgument).includes(STATEMENT_AGENT_CREATION)) {
155
- if (
156
- beforeAllArgument.type === TSESTree.AST_NODE_TYPES.ArrowFunctionExpression &&
157
- beforeAllArgument.body.type === TSESTree.AST_NODE_TYPES.BlockStatement
158
- ) {
159
- const fixtureResetStatement = beforeAllArgument.body.body.find(
160
- (statement) => sourceCode.getText(statement) === STATEMENT_FIXTURE_RESET_AWAITED,
161
- );
162
- assert.ok(fixtureResetStatement !== undefined);
163
- beforeAllOrEachFixer = (fixer: RuleFixer) =>
164
- fixer.replaceText(
165
- fixtureResetStatement,
166
- [
167
- STATEMENT_AGENT_CREATION,
168
- STATEMENT_AGENT_REGISTER,
169
- STATEMENT_AGENT_ENABLE,
170
- STATEMENT_FIXTURE_RESET_AWAITED,
171
- ].join('\n'),
172
- );
173
- } else {
174
- beforeAllOrEachFixer = (fixer: RuleFixer) =>
175
- fixer.replaceText(
176
- beforeAllArgument,
177
- [
178
- `async () => {`,
179
- STATEMENT_AGENT_CREATION,
180
- STATEMENT_AGENT_REGISTER,
181
- STATEMENT_AGENT_ENABLE,
182
- STATEMENT_FIXTURE_RESET_AWAITED,
183
- `}`,
184
- ].join('\n'),
185
- );
186
- }
187
- agentDeclarationFixer = (fixer: RuleFixer) =>
188
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
189
- fixer.insertTextBefore(beforeAll!, `${STATEMENT_AGENT_DECLARATION}\n`);
190
- }
191
- }
192
-
193
- // inject agent disposal to `afterAll` block
194
- if (afterAll !== undefined) {
195
- const afterAllArrowFunctionExpression = afterAll.arguments[0];
196
- assert.ok(
197
- afterAllArrowFunctionExpression !== undefined &&
198
- afterAllArrowFunctionExpression.type === TSESTree.AST_NODE_TYPES.ArrowFunctionExpression,
199
- );
200
- const arrowFunctionBody = afterAllArrowFunctionExpression.body;
201
- assert.ok(arrowFunctionBody.type === TSESTree.AST_NODE_TYPES.BlockStatement);
202
-
203
- const afterAllBodyText = sourceCode.getText(arrowFunctionBody);
204
- if (!afterAllBodyText.includes(STATEMENT_AGENT_DISPOSE)) {
205
- const lastStatement = arrowFunctionBody.body.at(-1);
206
- assert.ok(lastStatement);
207
- afterAllFixer = (fixer: RuleFixer) => fixer.insertTextAfter(lastStatement, STATEMENT_AGENT_DISPOSE);
208
- }
209
- } else {
210
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
211
- const nextToken = sourceCode.getTokenAfter(beforeAll ?? beforeEach!);
212
- afterAllFixer = (fixer: RuleFixer) =>
213
- fixer.insertTextAfter(
214
- nextToken !== null && nextToken.type === AST_TOKEN_TYPES.Punctuator
215
- ? nextToken
216
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
217
- beforeAll!,
218
- ['', `afterAll(async () => {`, STATEMENT_AGENT_DISPOSE, `});`].join('\n'),
219
- );
220
- }
221
-
222
- if (
223
- jestImportFixer !== undefined ||
224
- agentImportFixer !== undefined ||
225
- fixturePluginImportFixer !== undefined ||
226
- agentDeclarationFixer !== undefined ||
227
- beforeAllOrEachFixer !== undefined ||
228
- afterAllFixer !== undefined
229
- ) {
230
- context.report({
231
- messageId: 'updateTestWiring',
232
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
233
- node: beforeAll ?? beforeEach!,
234
- *fix(fixer) {
235
- if (jestImportFixer !== undefined) {
236
- yield jestImportFixer(fixer);
237
- }
238
- if (agentImportFixer !== undefined) {
239
- yield agentImportFixer(fixer);
240
- }
241
- if (fixturePluginImportFixer !== undefined) {
242
- yield fixturePluginImportFixer(fixer);
243
- }
244
- if (agentDeclarationFixer !== undefined) {
245
- yield agentDeclarationFixer(fixer);
246
- }
247
- if (beforeAllOrEachFixer !== undefined) {
248
- yield beforeAllOrEachFixer(fixer);
249
- }
250
- if (afterAllFixer !== undefined) {
251
- yield afterAllFixer(fixer);
252
- }
253
- },
254
- });
255
- }
256
- } catch (error) {
257
- // eslint-disable-next-line no-console
258
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
259
- context.report({
260
- node: program,
261
- messageId: 'unknownError',
262
- data: {
263
- fileName: context.filename,
264
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
265
- },
266
- });
267
- }
268
- },
269
- };
270
- },
271
- });
272
-
273
- export default rule;
@@ -1,194 +0,0 @@
1
- // agent/fetch-response-body-json.ts
2
-
3
- /*
4
- * Copyright (c) 2021-2024 Check Digit, LLC
5
- *
6
- * This code is licensed under the MIT license (see LICENSE.txt for details).
7
- */
8
-
9
- import { strict as assert } from 'node:assert';
10
-
11
- import { AST_NODE_TYPES, ESLintUtils, TSESTree } from '@typescript-eslint/utils';
12
-
13
- import getDocumentationUrl from '../get-documentation-url';
14
- import { getAncestor } from '../library/ts-tree';
15
- import { isFetchResponse } from './fetch';
16
-
17
- export const ruleId = 'fetch-response-body-json';
18
-
19
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
20
-
21
- interface Change {
22
- enclosingFunction: TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration;
23
- enclosingStatement: TSESTree.VariableDeclaration | TSESTree.ExpressionStatement | TSESTree.ReturnStatement;
24
- enclosingStatementIndex: number;
25
- responseBodyNode: TSESTree.MemberExpression;
26
- responseVariableName: string;
27
- responseBodyVariableName: string;
28
- isResponseBodyVariableDeclared: boolean;
29
- // replacementText: string;
30
- }
31
-
32
- const rule: ESLintUtils.RuleModule<'unknownError' | 'replaceBodyWithJson' | 'refactorNeeded'> = createRule({
33
- name: ruleId,
34
- meta: {
35
- type: 'suggestion',
36
- docs: {
37
- description: 'Replace "response.body" with "await response.json()".',
38
- },
39
- messages: {
40
- refactorNeeded:
41
- 'Please extract the fetch call and check its reponse status code before accessing its response body.',
42
- replaceBodyWithJson: 'Replace "response.body" with "await response.json()".',
43
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
44
- },
45
- fixable: 'code',
46
- schema: [],
47
- },
48
- defaultOptions: [],
49
- create(context) {
50
- const parserServices = ESLintUtils.getParserServices(context);
51
- const typeChecker = parserServices.program.getTypeChecker();
52
- const allChanges = new Map<TSESTree.Node, Map<string, Change[]>>();
53
-
54
- return {
55
- 'MemberExpression[property.name="body"]': (responseBodyNode: TSESTree.MemberExpression) => {
56
- try {
57
- const responseNode = parserServices.esTreeNodeToTSNodeMap.get(responseBodyNode.object);
58
- const responseType = typeChecker.getTypeAtLocation(responseNode);
59
-
60
- if (isFetchResponse(responseType)) {
61
- if (responseBodyNode.object.type !== AST_NODE_TYPES.Identifier) {
62
- context.report({
63
- node: responseBodyNode,
64
- messageId: 'refactorNeeded',
65
- });
66
- return;
67
- }
68
-
69
- const enclosingFunction = getAncestor(
70
- responseBodyNode,
71
- (node: TSESTree.Node) =>
72
- node.type === AST_NODE_TYPES.ArrowFunctionExpression ||
73
- node.type === AST_NODE_TYPES.FunctionExpression ||
74
- node.type === AST_NODE_TYPES.FunctionDeclaration,
75
- ) as TSESTree.FunctionExpression | TSESTree.ArrowFunctionExpression | TSESTree.FunctionDeclaration;
76
- const enclosingStatement = getAncestor(
77
- responseBodyNode,
78
- (node: TSESTree.Node) =>
79
- (node.type === AST_NODE_TYPES.VariableDeclaration ||
80
- node.type === AST_NODE_TYPES.ExpressionStatement ||
81
- node.type === AST_NODE_TYPES.ReturnStatement) &&
82
- node.parent.type === AST_NODE_TYPES.BlockStatement,
83
- ) as TSESTree.VariableDeclaration | TSESTree.ExpressionStatement | TSESTree.ReturnStatement;
84
- const enclosingStatementIndex = (enclosingFunction.body as TSESTree.BlockStatement).body.indexOf(
85
- enclosingStatement,
86
- );
87
- const responseVariableName = responseBodyNode.object.name;
88
- const isResponseBodyVariableDeclared =
89
- enclosingStatement.type === AST_NODE_TYPES.VariableDeclaration &&
90
- enclosingStatement.declarations.some(
91
- (declaration) =>
92
- declaration.init === responseBodyNode ||
93
- (declaration.init?.type === AST_NODE_TYPES.TSAsExpression &&
94
- declaration.init.expression === responseBodyNode),
95
- );
96
- const responseBodyVariableName = isResponseBodyVariableDeclared
97
- ? (enclosingStatement.declarations.find(
98
- (declaration) =>
99
- declaration.init === responseBodyNode ||
100
- (declaration.init?.type === AST_NODE_TYPES.TSAsExpression &&
101
- declaration.init.expression === responseBodyNode),
102
- )?.id as unknown as string)
103
- : `${responseBodyNode.object.name}Body`;
104
-
105
- const change: Change = {
106
- enclosingFunction,
107
- enclosingStatement,
108
- enclosingStatementIndex,
109
- responseVariableName,
110
- responseBodyNode,
111
- responseBodyVariableName,
112
- isResponseBodyVariableDeclared,
113
- };
114
-
115
- const changesByFunction = allChanges.get(enclosingFunction) ?? new Map<string, Change[]>();
116
- const changesByResponse = changesByFunction.get(responseVariableName) ?? [];
117
- changesByResponse.push(change);
118
- changesByFunction.set(responseVariableName, changesByResponse);
119
- allChanges.set(enclosingFunction, changesByFunction);
120
- }
121
- } catch (error) {
122
- // eslint-disable-next-line no-console
123
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
124
- context.report({
125
- node: responseBodyNode,
126
- messageId: 'unknownError',
127
- data: {
128
- fileName: context.filename,
129
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
130
- },
131
- });
132
- }
133
- },
134
-
135
- 'Program:exit': () => {
136
- if (allChanges.size === 0) {
137
- return;
138
- }
139
-
140
- const fixes: { node: TSESTree.Node | TSESTree.Token; text: string; insert: boolean }[] = [];
141
- for (const changesByFunction of allChanges.values()) {
142
- for (const changesByResponse of changesByFunction.values()) {
143
- const orderedChanges = changesByResponse.sort(
144
- (changeA, changeB) => changeA.enclosingStatementIndex - changeB.enclosingStatementIndex,
145
- );
146
- const firstChange = orderedChanges[0];
147
- assert(firstChange);
148
-
149
- const {
150
- responseBodyNode,
151
- responseVariableName,
152
- responseBodyVariableName,
153
- isResponseBodyVariableDeclared,
154
- enclosingStatement,
155
- } = firstChange;
156
-
157
- let remainingChanges;
158
- if (!isResponseBodyVariableDeclared) {
159
- fixes.push({
160
- node: context.sourceCode.getTokenBefore(enclosingStatement) as TSESTree.Token,
161
- text: `\nconst ${responseBodyVariableName} = await ${responseVariableName}.json();`,
162
- insert: true,
163
- });
164
- remainingChanges = orderedChanges;
165
- } else {
166
- fixes.push({
167
- node: responseBodyNode,
168
- text: `await ${responseVariableName}.json()`,
169
- insert: false,
170
- });
171
- remainingChanges = orderedChanges.slice(1);
172
- }
173
-
174
- for (const change of remainingChanges) {
175
- fixes.push({ node: change.responseBodyNode, text: responseBodyVariableName, insert: false });
176
- }
177
- }
178
- }
179
-
180
- for (const fix of fixes.reverse()) {
181
- context.report({
182
- node: fix.node,
183
- messageId: 'replaceBodyWithJson',
184
- fix(fixer) {
185
- return fix.insert ? fixer.insertTextAfter(fix.node, fix.text) : fixer.replaceText(fix.node, fix.text);
186
- },
187
- });
188
- }
189
- },
190
- };
191
- },
192
- });
193
-
194
- export default rule;