@checkdigit/eslint-plugin 7.5.0 → 7.6.0-PR.75-5da1

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 (66) hide show
  1. package/dist-mjs/agent/add-assert-import.mjs +58 -0
  2. package/dist-mjs/agent/add-base-path-const.mjs +65 -0
  3. package/dist-mjs/agent/add-base-path-import.mjs +60 -0
  4. package/dist-mjs/agent/add-url-domain.mjs +61 -0
  5. package/dist-mjs/agent/agent-test-wiring.mjs +221 -0
  6. package/dist-mjs/agent/fetch-response-body-json.mjs +146 -0
  7. package/dist-mjs/agent/fetch-response-header-getter.mjs +117 -0
  8. package/dist-mjs/agent/fetch-response-status.mjs +66 -0
  9. package/dist-mjs/agent/fetch-then.mjs +269 -0
  10. package/dist-mjs/agent/fetch.mjs +38 -0
  11. package/dist-mjs/agent/file.mjs +43 -0
  12. package/dist-mjs/agent/fix-function-call-arguments.mjs +153 -0
  13. package/dist-mjs/agent/no-fixture.mjs +361 -0
  14. package/dist-mjs/agent/no-mapped-response.mjs +75 -0
  15. package/dist-mjs/agent/no-service-wrapper.mjs +185 -0
  16. package/dist-mjs/agent/no-status-code.mjs +59 -0
  17. package/dist-mjs/agent/no-unused-function-argument.mjs +79 -0
  18. package/dist-mjs/agent/no-unused-imports.mjs +81 -0
  19. package/dist-mjs/agent/no-unused-service-variable.mjs +74 -0
  20. package/dist-mjs/agent/response-reference.mjs +70 -0
  21. package/dist-mjs/agent/url.mjs +32 -0
  22. package/dist-mjs/index.mjs +146 -4
  23. package/dist-types/agent/add-assert-import.d.ts +4 -0
  24. package/dist-types/agent/add-base-path-const.d.ts +4 -0
  25. package/dist-types/agent/add-base-path-import.d.ts +4 -0
  26. package/dist-types/agent/add-url-domain.d.ts +4 -0
  27. package/dist-types/agent/agent-test-wiring.d.ts +4 -0
  28. package/dist-types/agent/fetch-response-body-json.d.ts +4 -0
  29. package/dist-types/agent/fetch-response-header-getter.d.ts +4 -0
  30. package/dist-types/agent/fetch-response-status.d.ts +4 -0
  31. package/dist-types/agent/fetch-then.d.ts +4 -0
  32. package/dist-types/agent/fetch.d.ts +5 -0
  33. package/dist-types/agent/file.d.ts +7 -0
  34. package/dist-types/agent/fix-function-call-arguments.d.ts +9 -0
  35. package/dist-types/agent/no-fixture.d.ts +4 -0
  36. package/dist-types/agent/no-mapped-response.d.ts +4 -0
  37. package/dist-types/agent/no-service-wrapper.d.ts +4 -0
  38. package/dist-types/agent/no-status-code.d.ts +4 -0
  39. package/dist-types/agent/no-unused-function-argument.d.ts +4 -0
  40. package/dist-types/agent/no-unused-imports.d.ts +4 -0
  41. package/dist-types/agent/no-unused-service-variable.d.ts +4 -0
  42. package/dist-types/agent/response-reference.d.ts +16 -0
  43. package/dist-types/agent/url.d.ts +4 -0
  44. package/package.json +1 -96
  45. package/src/agent/add-assert-import.ts +74 -0
  46. package/src/agent/add-base-path-const.ts +81 -0
  47. package/src/agent/add-base-path-import.ts +69 -0
  48. package/src/agent/add-url-domain.ts +76 -0
  49. package/src/agent/agent-test-wiring.ts +273 -0
  50. package/src/agent/fetch-response-body-json.ts +197 -0
  51. package/src/agent/fetch-response-header-getter.ts +148 -0
  52. package/src/agent/fetch-response-status.ts +87 -0
  53. package/src/agent/fetch-then.ts +357 -0
  54. package/src/agent/fetch.ts +57 -0
  55. package/src/agent/file.ts +42 -0
  56. package/src/agent/fix-function-call-arguments.ts +200 -0
  57. package/src/agent/no-fixture.ts +521 -0
  58. package/src/agent/no-mapped-response.ts +84 -0
  59. package/src/agent/no-service-wrapper.ts +241 -0
  60. package/src/agent/no-status-code.ts +72 -0
  61. package/src/agent/no-unused-function-argument.ts +98 -0
  62. package/src/agent/no-unused-imports.ts +103 -0
  63. package/src/agent/no-unused-service-variable.ts +93 -0
  64. package/src/agent/response-reference.ts +129 -0
  65. package/src/agent/url.ts +32 -0
  66. package/src/index.ts +142 -0
@@ -0,0 +1,148 @@
1
+ // agent/fetch-response-header-getter-ts.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
+
13
+ export const ruleId = 'fetch-response-header-getter-ts';
14
+ const HEADER_BUILTIN_FUNCTIONS = Object.keys(Headers.prototype);
15
+
16
+ const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
17
+
18
+ const rule: ESLintUtils.RuleModule<'unknownError' | 'useGetter'> = createRule({
19
+ name: ruleId,
20
+ meta: {
21
+ type: 'suggestion',
22
+ docs: {
23
+ description: 'Use "get()" method to get header value from the headers object of the fetch response.',
24
+ },
25
+ messages: {
26
+ useGetter: 'Use "get()" method to get header value from the headers object of the fetch response.',
27
+ unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
28
+ },
29
+ fixable: 'code',
30
+ schema: [],
31
+ },
32
+ defaultOptions: [],
33
+ create(context) {
34
+ const parserServices = ESLintUtils.getParserServices(context);
35
+ const typeChecker = parserServices.program.getTypeChecker();
36
+ const sourceCode = context.sourceCode;
37
+
38
+ return {
39
+ MemberExpression: (responseHeadersAccess: TSESTree.MemberExpression) => {
40
+ try {
41
+ if (
42
+ responseHeadersAccess.property.type === AST_NODE_TYPES.Identifier &&
43
+ HEADER_BUILTIN_FUNCTIONS.includes(responseHeadersAccess.property.name)
44
+ ) {
45
+ // skip Headers's built-in function calls
46
+ return;
47
+ }
48
+
49
+ const responseHeadersTsNode = parserServices.esTreeNodeToTSNodeMap.get(responseHeadersAccess.object);
50
+ let responseHeadersType = typeChecker.getTypeAtLocation(responseHeadersTsNode);
51
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
52
+ responseHeadersType = responseHeadersType.isUnion() ? responseHeadersType.types[0]! : responseHeadersType;
53
+ const responseHeadersTypeName = // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
54
+ (responseHeadersType.symbol ?? responseHeadersType.aliasSymbol)?.escapedName;
55
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison
56
+ if (responseHeadersTypeName !== 'Headers' && responseHeadersTypeName !== 'HeaderGetter') {
57
+ return;
58
+ }
59
+
60
+ let replacementText: string;
61
+ if (!responseHeadersAccess.computed) {
62
+ // e.g. headers.etag
63
+ replacementText = `${sourceCode.getText(responseHeadersAccess.object)}.get('${sourceCode.getText(responseHeadersAccess.property)}')`;
64
+ } else if (
65
+ responseHeadersAccess.property.type === AST_NODE_TYPES.Identifier ||
66
+ responseHeadersAccess.property.type === AST_NODE_TYPES.Literal ||
67
+ responseHeadersAccess.property.type === AST_NODE_TYPES.TemplateLiteral
68
+ ) {
69
+ replacementText = `${sourceCode.getText(responseHeadersAccess.object)}.get(${sourceCode.getText(responseHeadersAccess.property)})`;
70
+ } else {
71
+ throw new Error(`Unexpected property type: ${responseHeadersAccess.property.type}`);
72
+ }
73
+
74
+ context.report({
75
+ messageId: 'useGetter',
76
+ node: responseHeadersAccess.property,
77
+ fix(fixer) {
78
+ return fixer.replaceText(responseHeadersAccess, replacementText);
79
+ },
80
+ });
81
+ } catch (error) {
82
+ // eslint-disable-next-line no-console
83
+ console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
84
+ context.report({
85
+ node: responseHeadersAccess,
86
+ messageId: 'unknownError',
87
+ data: {
88
+ fileName: context.filename,
89
+ error: error instanceof Error ? error.toString() : JSON.stringify(error),
90
+ },
91
+ });
92
+ }
93
+ },
94
+
95
+ // convert response.get() to response.headers.get()
96
+ 'CallExpression[callee.property.name="get"]': (responseHeadersAccess: TSESTree.CallExpression) => {
97
+ try {
98
+ if (responseHeadersAccess.callee.type !== AST_NODE_TYPES.MemberExpression) {
99
+ return;
100
+ }
101
+
102
+ // skip request-like calls
103
+ if (
104
+ responseHeadersAccess.callee.object.type !== AST_NODE_TYPES.Identifier ||
105
+ responseHeadersAccess.callee.object.name === 'request'
106
+ ) {
107
+ return;
108
+ }
109
+ const responseNode = responseHeadersAccess.callee.object;
110
+ const responseHeadersTsNode = parserServices.esTreeNodeToTSNodeMap.get(responseNode);
111
+ const responseType = typeChecker.getTypeAtLocation(responseHeadersTsNode);
112
+ const typeName = typeChecker.typeToString(responseType);
113
+ if (typeName === 'InboundContext' || typeName.endsWith('RequestType')) {
114
+ return;
115
+ }
116
+
117
+ // make sure the response type has "headers" property
118
+ const hasHeadersProperty = responseType.getProperties().some((symbol) => symbol.name === 'headers');
119
+ if (!hasHeadersProperty) {
120
+ return;
121
+ }
122
+
123
+ const replacementText = `${sourceCode.getText(responseNode)}.headers`;
124
+ context.report({
125
+ messageId: 'useGetter',
126
+ node: responseHeadersAccess,
127
+ fix(fixer) {
128
+ return fixer.replaceText(responseNode, replacementText);
129
+ },
130
+ });
131
+ } catch (error) {
132
+ // eslint-disable-next-line no-console
133
+ console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
134
+ context.report({
135
+ node: responseHeadersAccess,
136
+ messageId: 'unknownError',
137
+ data: {
138
+ fileName: context.filename,
139
+ error: error instanceof Error ? error.toString() : JSON.stringify(error),
140
+ },
141
+ });
142
+ }
143
+ },
144
+ };
145
+ },
146
+ });
147
+
148
+ export default rule;
@@ -0,0 +1,87 @@
1
+ // agent/fetch-response-status.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
+
13
+ export const ruleId = 'fetch-response-status';
14
+
15
+ const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
16
+
17
+ const rule: ESLintUtils.RuleModule<'unknownError' | 'renameStatusCodeProperty'> = createRule({
18
+ name: ruleId,
19
+ meta: {
20
+ type: 'problem',
21
+ docs: {
22
+ description: 'Replace "response.body" with "await response.json()".',
23
+ },
24
+ messages: {
25
+ renameStatusCodeProperty: 'Rename "statusCode" with "status".',
26
+ unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
27
+ },
28
+ fixable: 'code',
29
+ schema: [],
30
+ },
31
+ defaultOptions: [],
32
+ create(context) {
33
+ return {
34
+ VariableDeclaration: (variableDeclaration: TSESTree.VariableDeclaration) => {
35
+ const variableInit = variableDeclaration.declarations[0]?.init;
36
+ if (
37
+ !variableInit ||
38
+ variableInit.type !== AST_NODE_TYPES.AwaitExpression ||
39
+ variableInit.argument.type !== AST_NODE_TYPES.CallExpression ||
40
+ variableInit.argument.callee.type !== AST_NODE_TYPES.Identifier ||
41
+ variableInit.argument.callee.name !== 'fetch'
42
+ ) {
43
+ return;
44
+ }
45
+
46
+ const variableId = variableDeclaration.declarations[0]?.id;
47
+ if (variableId.type !== AST_NODE_TYPES.ObjectPattern) {
48
+ return;
49
+ }
50
+ const statusCodeProperty = variableId.properties.find<TSESTree.Property>(
51
+ (property): property is TSESTree.Property =>
52
+ property.type === AST_NODE_TYPES.Property &&
53
+ property.key.type === AST_NODE_TYPES.Identifier &&
54
+ property.key.name === 'statusCode',
55
+ );
56
+ if (!statusCodeProperty) {
57
+ return;
58
+ }
59
+
60
+ try {
61
+ context.report({
62
+ node: statusCodeProperty,
63
+ messageId: 'renameStatusCodeProperty',
64
+ fix(fixer) {
65
+ return statusCodeProperty.shorthand
66
+ ? fixer.replaceText(statusCodeProperty, 'status: statusCode')
67
+ : fixer.replaceText(statusCodeProperty.key, 'status');
68
+ },
69
+ });
70
+ } catch (error) {
71
+ // eslint-disable-next-line no-console
72
+ console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
73
+ context.report({
74
+ node: statusCodeProperty,
75
+ messageId: 'unknownError',
76
+ data: {
77
+ fileName: context.filename,
78
+ error: error instanceof Error ? error.toString() : JSON.stringify(error),
79
+ },
80
+ });
81
+ }
82
+ },
83
+ };
84
+ },
85
+ });
86
+
87
+ export default rule;
@@ -0,0 +1,357 @@
1
+ // agent/fetch-then.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 type { CallExpression, Expression, MemberExpression, SimpleCallExpression } from 'estree';
12
+ import { type Rule, type Scope, SourceCode } from 'eslint';
13
+
14
+ import { getEnclosingFunction, getEnclosingStatement, getParent, isUsedInArrayOrAsArgument } from '../library/tree';
15
+ import getDocumentationUrl from '../get-documentation-url';
16
+ import { getIndentation } from '../library/format';
17
+ import { isValidPropertyName } from '../library/variable';
18
+ import { hasAssertions, isInvalidResponseHeadersAccess } from './fetch';
19
+ import { replaceEndpointUrlPrefixWithBasePath } from './url';
20
+
21
+ export const ruleId = 'fetch-then';
22
+
23
+ interface FixtureCallInformation {
24
+ fixtureNode: SimpleCallExpression;
25
+ requestBody?: Expression;
26
+ requestHeaders?: { name: Expression; value: Expression }[];
27
+ assertions?: Expression[][];
28
+ }
29
+
30
+ // recursively analyze the fixture/supertest call chain to collect information of request/response
31
+ function analyzeFixtureCall(call: SimpleCallExpression, results: FixtureCallInformation, sourceCode: SourceCode) {
32
+ const parent = getParent(call);
33
+ if (!parent) {
34
+ return;
35
+ }
36
+
37
+ let nextCall;
38
+ if (parent.type !== 'MemberExpression') {
39
+ results.fixtureNode = call;
40
+ return;
41
+ }
42
+
43
+ if (parent.property.type === 'Identifier') {
44
+ if (parent.property.name === 'expect') {
45
+ // supertest assertions
46
+ const assertionCall = getParent(parent);
47
+ assert.ok(assertionCall && assertionCall.type === 'CallExpression');
48
+ results.assertions = [...(results.assertions ?? []), assertionCall.arguments as Expression[]];
49
+ nextCall = assertionCall;
50
+ } else if (parent.property.name === 'send') {
51
+ // request body
52
+ const sendRequestBodyCall = getParent(parent);
53
+ assert.ok(sendRequestBodyCall && sendRequestBodyCall.type === 'CallExpression');
54
+ results.requestBody = sendRequestBodyCall.arguments[0] as Expression;
55
+ nextCall = sendRequestBodyCall;
56
+ } else if (parent.property.name === 'set') {
57
+ // request headers
58
+ const setRequestHeaderCall = getParent(parent);
59
+ assert.ok(setRequestHeaderCall && setRequestHeaderCall.type === 'CallExpression');
60
+ const [name, value] = setRequestHeaderCall.arguments as [Expression, Expression];
61
+ results.requestHeaders = [...(results.requestHeaders ?? []), { name, value }];
62
+ nextCall = setRequestHeaderCall;
63
+ }
64
+ } else {
65
+ throw new Error(`Unexpected expression in fixture/supertest call ${sourceCode.getText(parent)}.`);
66
+ }
67
+ if (nextCall) {
68
+ analyzeFixtureCall(nextCall, results, sourceCode);
69
+ }
70
+ }
71
+
72
+ // eslint-disable-next-line sonarjs/cognitive-complexity
73
+ function createResponseAssertions(
74
+ fixtureCallInformation: FixtureCallInformation,
75
+ sourceCode: SourceCode,
76
+ responseVariableName: string,
77
+ ) {
78
+ let statusAssertion: string | undefined;
79
+ const nonStatusAssertions: string[] = [];
80
+ for (const expectArguments of fixtureCallInformation.assertions ?? []) {
81
+ if (expectArguments.length === 1) {
82
+ const [assertionArgument] = expectArguments;
83
+ assert.ok(assertionArgument);
84
+ if (
85
+ (assertionArgument.type === 'MemberExpression' &&
86
+ assertionArgument.object.type === 'Identifier' &&
87
+ assertionArgument.object.name === 'StatusCodes') ||
88
+ assertionArgument.type === 'Literal' ||
89
+ sourceCode.getText(assertionArgument).includes('StatusCodes.')
90
+ ) {
91
+ // status code assertion
92
+ statusAssertion = `assert.equal(${responseVariableName}.status, ${sourceCode.getText(assertionArgument)})`;
93
+ } else if (assertionArgument.type === 'ArrowFunctionExpression') {
94
+ // callback assertion using arrow function
95
+ let functionBody = sourceCode.getText(assertionArgument.body);
96
+
97
+ const [originalResponseArgument] = assertionArgument.params;
98
+ assert.ok(originalResponseArgument?.type === 'Identifier');
99
+ const originalResponseArgumentName = originalResponseArgument.name;
100
+ if (originalResponseArgumentName !== responseVariableName) {
101
+ functionBody = functionBody.replace(
102
+ new RegExp(`\\b${originalResponseArgumentName}\\b`, 'ug'),
103
+ responseVariableName,
104
+ );
105
+ }
106
+ nonStatusAssertions.push(`assert.doesNotThrow(()=>${functionBody})`);
107
+ } else if (assertionArgument.type === 'Identifier') {
108
+ // callback assertion using function reference
109
+ nonStatusAssertions.push(
110
+ `assert.doesNotThrow(()=>${sourceCode.getText(assertionArgument)}(${responseVariableName}))`,
111
+ );
112
+ } else if (assertionArgument.type === 'ObjectExpression' || assertionArgument.type === 'CallExpression') {
113
+ // body deep equal assertion
114
+ nonStatusAssertions.push(
115
+ `assert.deepEqual(await ${responseVariableName}.json(), ${sourceCode.getText(assertionArgument)})`,
116
+ );
117
+ } else {
118
+ throw new Error(`Unexpected Supertest assertion argument: ".expect(${sourceCode.getText(assertionArgument)})`);
119
+ }
120
+ } else if (expectArguments.length === 2) {
121
+ // header assertion
122
+ const [headerName, headerValue] = expectArguments;
123
+ assert.ok(headerName && headerValue);
124
+ const headersReference = `${responseVariableName}.headers`;
125
+ if (headerValue.type === 'Literal' && headerValue.value instanceof RegExp) {
126
+ nonStatusAssertions.push(
127
+ `assert.ok(${headersReference}.get(${sourceCode.getText(headerName)}).match(${sourceCode.getText(headerValue)}))`,
128
+ );
129
+ } else {
130
+ nonStatusAssertions.push(
131
+ `assert.equal(${headersReference}.get(${sourceCode.getText(headerName)}), ${sourceCode.getText(headerValue)})`,
132
+ );
133
+ }
134
+ }
135
+ }
136
+ return {
137
+ statusAssertion,
138
+ nonStatusAssertions,
139
+ };
140
+ }
141
+
142
+ function getResponseHeadersAccesses(
143
+ responseVariables: Scope.Variable[],
144
+ scopeManager: Scope.ScopeManager,
145
+ sourceCode: SourceCode,
146
+ ) {
147
+ const responseHeadersAccesses: MemberExpression[] = [];
148
+ for (const responseVariable of responseVariables) {
149
+ for (const responseReference of responseVariable.references) {
150
+ const responseAccess = getParent(responseReference.identifier);
151
+ if (!responseAccess || responseAccess.type !== 'MemberExpression') {
152
+ continue;
153
+ }
154
+
155
+ const responseAccessParent = getParent(responseAccess);
156
+ if (!responseAccessParent) {
157
+ continue;
158
+ }
159
+
160
+ if (
161
+ responseAccessParent.type === 'CallExpression' &&
162
+ responseAccessParent.arguments[0]?.type === 'ArrowFunctionExpression'
163
+ ) {
164
+ // map-like operation against responses, e.g. responses.map((response) => response.headers.etag)
165
+ responseHeadersAccesses.push(
166
+ ...getResponseHeadersAccesses(
167
+ scopeManager.getDeclaredVariables(responseAccessParent.arguments[0]),
168
+ scopeManager,
169
+ sourceCode,
170
+ ),
171
+ );
172
+ continue;
173
+ }
174
+
175
+ if (
176
+ responseAccess.computed &&
177
+ responseAccess.property.type === 'Literal' &&
178
+ responseAccessParent.type === 'MemberExpression'
179
+ ) {
180
+ // header access through indexed responses array, e.g. responses[0].headers, responses[1].get(...), etc.
181
+ responseHeadersAccesses.push(responseAccessParent);
182
+ } else {
183
+ responseHeadersAccesses.push(responseAccess);
184
+ }
185
+ }
186
+ }
187
+ return responseHeadersAccesses;
188
+ }
189
+
190
+ const rule: Rule.RuleModule = {
191
+ meta: {
192
+ type: 'suggestion',
193
+ docs: {
194
+ description: 'Prefer native fetch API over customized fixture API.',
195
+ url: getDocumentationUrl(ruleId),
196
+ },
197
+ messages: {
198
+ preferNativeFetch: 'Prefer native fetch API over customized fixture API.',
199
+ shouldUseHeaderGetter: 'Getter should be used to access response headers.',
200
+ unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
201
+ },
202
+ fixable: 'code',
203
+ schema: [],
204
+ },
205
+
206
+ create(context) {
207
+ const sourceCode = context.sourceCode;
208
+ const scopeManager = sourceCode.scopeManager;
209
+
210
+ return {
211
+ 'CallExpression[callee.object.object.name="fixture"][callee.object.property.name="api"]': (
212
+ fixtureCall: CallExpression,
213
+ // eslint-disable-next-line sonarjs/cognitive-complexity
214
+ ) => {
215
+ try {
216
+ if (!hasAssertions(fixtureCall)) {
217
+ // skip if there are no assertions, let "no-fixture" rule to handle the conversion
218
+ return;
219
+ }
220
+
221
+ if (!(isUsedInArrayOrAsArgument(fixtureCall) || getEnclosingFunction(fixtureCall)?.async === false)) {
222
+ return;
223
+ }
224
+
225
+ assert.ok(fixtureCall.type === 'CallExpression');
226
+ const fixtureFunction = fixtureCall.callee; // e.g. fixture.api.get
227
+ assert.ok(fixtureFunction.type === 'MemberExpression');
228
+ const indentation = getIndentation(fixtureCall, sourceCode);
229
+
230
+ const [urlArgumentNode] = fixtureCall.arguments; // e.g. `/sample-service/v1/ping`
231
+ assert.ok(urlArgumentNode !== undefined);
232
+
233
+ const fixtureCallInformation = {} as FixtureCallInformation;
234
+ analyzeFixtureCall(fixtureCall, fixtureCallInformation, sourceCode);
235
+
236
+ // convert url from `/sample-service/v1/ping` to `${BASE_PATH}/ping`
237
+ const originalUrlArgumentText = sourceCode.getText(urlArgumentNode);
238
+ const fetchUrlArgumentText = replaceEndpointUrlPrefixWithBasePath(originalUrlArgumentText);
239
+
240
+ // fetch request argument
241
+ const methodNode = fixtureFunction.property; // get/put/etc.
242
+ assert.ok(methodNode.type === 'Identifier');
243
+ const fetchRequestArgumentLines = [
244
+ '{',
245
+ ` method: '${methodNode.name.toUpperCase()}',`,
246
+ ...(fixtureCallInformation.requestBody
247
+ ? [` body: JSON.stringify(${sourceCode.getText(fixtureCallInformation.requestBody)}),`]
248
+ : []),
249
+ ...(fixtureCallInformation.requestHeaders
250
+ ? [
251
+ ` headers: {`,
252
+ ...fixtureCallInformation.requestHeaders.map(
253
+ ({ name, value }) =>
254
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, no-nested-ternary, sonarjs/no-nested-template-literals
255
+ ` ${name.type === 'Literal' ? (isValidPropertyName(name.value) ? name.value : `'${name.value}'`) : `[${sourceCode.getText(name)}]`}: ${sourceCode.getText(value)},`,
256
+ ),
257
+ ` },`,
258
+ ]
259
+ : []),
260
+ '}',
261
+ ].join(`\n${indentation}`);
262
+
263
+ const responseVariableNameToUse = 'res';
264
+ const { statusAssertion, nonStatusAssertions } = createResponseAssertions(
265
+ fixtureCallInformation,
266
+ sourceCode,
267
+ responseVariableNameToUse,
268
+ );
269
+
270
+ // add variable declaration if needed
271
+ const disableLintComment = '// eslint-disable-next-line @checkdigit/no-promise-instance-method';
272
+ const fetchCallText = `fetch(${fetchUrlArgumentText}, ${fetchRequestArgumentLines})`;
273
+ const appendingAssignmentAndAssertionText = [
274
+ ...(statusAssertion !== undefined ? [statusAssertion] : []),
275
+ ...nonStatusAssertions,
276
+ ].join(`;\n${indentation}`);
277
+ const replacementText = fixtureCallInformation.assertions
278
+ ? [
279
+ disableLintComment,
280
+ `${fetchCallText}.then((${responseVariableNameToUse}) => {`,
281
+ appendingAssignmentAndAssertionText === '' ? '' : ` ${appendingAssignmentAndAssertionText};`,
282
+ ` return ${responseVariableNameToUse};`,
283
+ `})`,
284
+ ].join(`\n${indentation}`)
285
+ : fetchCallText;
286
+
287
+ context.report({
288
+ node: fixtureCall,
289
+ messageId: 'preferNativeFetch',
290
+ fix(fixer) {
291
+ return fixer.replaceText(fixtureCallInformation.fixtureNode, replacementText);
292
+ },
293
+ });
294
+
295
+ const responsesVariable = getEnclosingStatement(fixtureCallInformation.fixtureNode);
296
+ if (!responsesVariable) {
297
+ return;
298
+ }
299
+
300
+ const responseVariableReferences = scopeManager.getDeclaredVariables(responsesVariable);
301
+ const responseHeadersAccesses = getResponseHeadersAccesses(
302
+ responseVariableReferences,
303
+ scopeManager,
304
+ sourceCode,
305
+ );
306
+ for (const responseHeadersAccess of responseHeadersAccesses) {
307
+ if (isInvalidResponseHeadersAccess(responseHeadersAccess)) {
308
+ const headerAccess = getParent(responseHeadersAccess);
309
+ if (headerAccess?.type === 'MemberExpression') {
310
+ const headerNameNode = headerAccess.property;
311
+ const headerName = headerAccess.computed
312
+ ? sourceCode.getText(headerNameNode)
313
+ : `'${sourceCode.getText(headerNameNode)}'`;
314
+ const headerAccessReplacementText = `${sourceCode.getText(headerAccess.object)}.get(${headerName})`;
315
+
316
+ context.report({
317
+ node: headerAccess,
318
+ messageId: 'shouldUseHeaderGetter',
319
+ fix(fixer) {
320
+ return fixer.replaceText(headerAccess, headerAccessReplacementText);
321
+ },
322
+ });
323
+ } else if (
324
+ headerAccess?.type === 'CallExpression' &&
325
+ responseHeadersAccess.property.type === 'Identifier' &&
326
+ responseHeadersAccess.property.name === 'get'
327
+ ) {
328
+ const headerAccessReplacementText = `${sourceCode.getText(responseHeadersAccess.object)}.headers.get(${sourceCode.getText(headerAccess.arguments[0])})`;
329
+
330
+ context.report({
331
+ node: headerAccess,
332
+ messageId: 'shouldUseHeaderGetter',
333
+ fix(fixer) {
334
+ return fixer.replaceText(headerAccess, headerAccessReplacementText);
335
+ },
336
+ });
337
+ }
338
+ }
339
+ }
340
+ } catch (error) {
341
+ // eslint-disable-next-line no-console
342
+ console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
343
+ context.report({
344
+ node: fixtureCall,
345
+ messageId: 'unknownError',
346
+ data: {
347
+ fileName: context.filename,
348
+ error: error instanceof Error ? error.toString() : JSON.stringify(error),
349
+ },
350
+ });
351
+ }
352
+ },
353
+ };
354
+ },
355
+ };
356
+
357
+ export default rule;
@@ -0,0 +1,57 @@
1
+ // agent/fetch.ts
2
+
3
+ import type { Node } from 'estree';
4
+
5
+ import { getParent, isBlockStatement } from '../library/tree';
6
+
7
+ export function getResponseBodyRetrievalText(responseVariableName: string) {
8
+ return `await ${responseVariableName}.json()`;
9
+ }
10
+
11
+ export function getResponseHeadersRetrievalText(responseVariableName: string) {
12
+ return `${responseVariableName}.headers`;
13
+ }
14
+
15
+ export function isInvalidResponseHeadersAccess(responseHeadersAccess: Node): boolean {
16
+ const responseHeaderAccessParent = getParent(responseHeadersAccess);
17
+ if (responseHeaderAccessParent?.type === 'VariableDeclarator') {
18
+ return false;
19
+ }
20
+
21
+ if (
22
+ responseHeaderAccessParent?.type === 'CallExpression' &&
23
+ responseHeaderAccessParent.callee.type === 'MemberExpression' &&
24
+ responseHeaderAccessParent.callee.property.type === 'Identifier' &&
25
+ responseHeaderAccessParent.callee.property.name === 'get'
26
+ ) {
27
+ return true;
28
+ }
29
+
30
+ return !(
31
+ responseHeaderAccessParent?.type === 'MemberExpression' &&
32
+ responseHeaderAccessParent.property.type === 'Identifier' &&
33
+ responseHeaderAccessParent.property.name === 'get'
34
+ );
35
+ }
36
+
37
+ export function hasAssertions(fixtureCall: Node): boolean {
38
+ if (isBlockStatement(fixtureCall)) {
39
+ return false;
40
+ }
41
+
42
+ const parent = getParent(fixtureCall);
43
+ if (!parent) {
44
+ return false;
45
+ }
46
+
47
+ if (
48
+ parent.type === 'MemberExpression' &&
49
+ parent.property.type === 'Identifier' &&
50
+ parent.property.name === 'expect' &&
51
+ getParent(parent)?.type === 'CallExpression'
52
+ ) {
53
+ return true;
54
+ }
55
+
56
+ return hasAssertions(parent);
57
+ }
@@ -0,0 +1,42 @@
1
+ // agent/file.ts
2
+
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ export function isApiIndexFile(filename: string): boolean {
7
+ return /.*\/src\/api\/v\d+\/index.ts/u.test(filename);
8
+ }
9
+
10
+ export function getProjectRootFolder(indexFilename: string): string {
11
+ return indexFilename.substring(0, indexFilename.lastIndexOf('/src/'));
12
+ }
13
+
14
+ export function getSwaggerPathByIndexFile(indexFilename: string): string {
15
+ return indexFilename.replace(/index\.ts$/u, 'swagger.yml');
16
+ }
17
+
18
+ export function loadSwagger(filename: string): string {
19
+ return fs.readFileSync(filename, 'utf8');
20
+ }
21
+
22
+ export function loadPackageJson(projectRoot: string): string {
23
+ return fs.readFileSync(`${projectRoot}/package.json`, 'utf8');
24
+ }
25
+
26
+ export function getApiFolder(folder: string): string | undefined {
27
+ if (/^\/?(?<absolutePath>(?:[^/]+\/)*)src\/api\/v\d+$/u.test(folder)) {
28
+ return folder;
29
+ }
30
+ const upperFolder = folder.substring(0, folder.lastIndexOf('/'));
31
+ return upperFolder.trim() === '' ? undefined : getApiFolder(upperFolder);
32
+ }
33
+
34
+ export function getApiIndexPathByFilename(filename: string): string | undefined {
35
+ const apiFolder = getApiFolder(filename);
36
+ if (apiFolder === undefined) {
37
+ return undefined;
38
+ }
39
+
40
+ const relativePath = path.relative(path.dirname(filename), `${apiFolder}/index`);
41
+ return relativePath.startsWith('../') ? relativePath : `./${relativePath}`;
42
+ }