@checkdigit/eslint-plugin 7.3.0-PR.75-d748 → 7.3.0-PR.93-561f

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