@checkdigit/eslint-plugin 7.6.0-PR.75-1b09 → 7.6.0-PR.75-c06b

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.
@@ -0,0 +1,322 @@
1
+ // agent/supertest-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 { ScopeManager, Variable } from '@typescript-eslint/scope-manager';
12
+ import { AST_NODE_TYPES, ESLintUtils, TSESTree } from '@typescript-eslint/utils';
13
+ import type { SourceCode } from '@typescript-eslint/utils/ts-eslint';
14
+
15
+ import { getEnclosingFunction, getParent, isUsedInArrayOrAsArgument } from '../library/ts-tree';
16
+ import getDocumentationUrl from '../get-documentation-url';
17
+ import { getIndentation } from '../library/format';
18
+ // import { isInvalidResponseHeadersAccess } from './fetch';
19
+
20
+ export const ruleId = 'supertest-then';
21
+
22
+ interface FixtureCallInformation {
23
+ fixtureNode: TSESTree.CallExpression;
24
+ requestBody?: TSESTree.Expression;
25
+ requestHeaders?: { name: TSESTree.Expression; value: TSESTree.Expression }[];
26
+ assertions?: TSESTree.Expression[][];
27
+ }
28
+
29
+ // recursively analyze the fixture/supertest call chain to collect information of request/response
30
+ function analyzeFixtureCall(call: TSESTree.CallExpression, results: FixtureCallInformation, sourceCode: SourceCode) {
31
+ const parent = getParent(call);
32
+ if (!parent) {
33
+ return;
34
+ }
35
+
36
+ let nextCall;
37
+ if (parent.type !== AST_NODE_TYPES.MemberExpression) {
38
+ results.fixtureNode = call;
39
+ return;
40
+ }
41
+
42
+ if (parent.property.type === AST_NODE_TYPES.Identifier) {
43
+ if (parent.property.name === 'expect') {
44
+ // supertest assertions
45
+ const assertionCall = getParent(parent);
46
+ assert.ok(assertionCall && assertionCall.type === AST_NODE_TYPES.CallExpression);
47
+ results.assertions = [...(results.assertions ?? []), assertionCall.arguments as TSESTree.Expression[]];
48
+ nextCall = assertionCall;
49
+ }
50
+ } else {
51
+ throw new Error(`Unexpected TSESTree.Expression in fixture/supertest call ${sourceCode.getText(parent)}.`);
52
+ }
53
+ if (nextCall) {
54
+ analyzeFixtureCall(nextCall, results, sourceCode);
55
+ }
56
+ }
57
+
58
+ // eslint-disable-next-line sonarjs/cognitive-complexity
59
+ function createResponseAssertions(
60
+ fixtureCallInformation: FixtureCallInformation,
61
+ sourceCode: SourceCode,
62
+ responseVariableName: string,
63
+ ) {
64
+ let statusAssertion: string | undefined;
65
+ const nonStatusAssertions: string[] = [];
66
+ for (const expectArguments of fixtureCallInformation.assertions ?? []) {
67
+ if (expectArguments.length === 1) {
68
+ const [assertionArgument] = expectArguments;
69
+ assert.ok(assertionArgument);
70
+ if (
71
+ (assertionArgument.type === AST_NODE_TYPES.MemberExpression &&
72
+ assertionArgument.object.type === AST_NODE_TYPES.Identifier &&
73
+ assertionArgument.object.name === 'StatusCodes') ||
74
+ assertionArgument.type === AST_NODE_TYPES.Literal ||
75
+ sourceCode.getText(assertionArgument).includes('StatusCodes.')
76
+ ) {
77
+ // status code assertion
78
+ statusAssertion = `assert.equal(${responseVariableName}.status, ${sourceCode.getText(assertionArgument)})`;
79
+ } else if (assertionArgument.type === AST_NODE_TYPES.ArrowFunctionExpression) {
80
+ // callback assertion using arrow function
81
+ let functionBody = sourceCode.getText(assertionArgument.body);
82
+
83
+ const [originalResponseArgument] = assertionArgument.params;
84
+ assert.ok(originalResponseArgument?.type === AST_NODE_TYPES.Identifier);
85
+ const originalResponseArgumentName = originalResponseArgument.name;
86
+ if (originalResponseArgumentName !== responseVariableName) {
87
+ functionBody = functionBody.replace(
88
+ new RegExp(`\\b${originalResponseArgumentName}\\b`, 'ug'),
89
+ responseVariableName,
90
+ );
91
+ }
92
+ nonStatusAssertions.push(`assert.doesNotThrow(()=>${functionBody})`);
93
+ } else if (assertionArgument.type === AST_NODE_TYPES.Identifier) {
94
+ // callback assertion using function reference
95
+ nonStatusAssertions.push(
96
+ `assert.doesNotThrow(()=>${sourceCode.getText(assertionArgument)}(${responseVariableName}))`,
97
+ );
98
+ } else if (
99
+ assertionArgument.type === AST_NODE_TYPES.ObjectExpression ||
100
+ assertionArgument.type === AST_NODE_TYPES.CallExpression
101
+ ) {
102
+ // body deep equal assertion
103
+ nonStatusAssertions.push(
104
+ `assert.deepEqual(await ${responseVariableName}.json(), ${sourceCode.getText(assertionArgument)})`,
105
+ );
106
+ } else {
107
+ throw new Error(`Unexpected Supertest assertion argument: ".expect(${sourceCode.getText(assertionArgument)})`);
108
+ }
109
+ } else if (expectArguments.length === 2) {
110
+ // header assertion
111
+ const [headerName, headerValue] = expectArguments;
112
+ assert.ok(headerName && headerValue);
113
+ const headersReference = `${responseVariableName}.headers`;
114
+ if (headerValue.type === AST_NODE_TYPES.Literal && headerValue.value instanceof RegExp) {
115
+ nonStatusAssertions.push(
116
+ `assert.ok(${headersReference}.get(${sourceCode.getText(headerName)}).match(${sourceCode.getText(headerValue)}))`,
117
+ );
118
+ } else {
119
+ nonStatusAssertions.push(
120
+ `assert.equal(${headersReference}.get(${sourceCode.getText(headerName)}), ${sourceCode.getText(headerValue)})`,
121
+ );
122
+ }
123
+ }
124
+ }
125
+ return {
126
+ statusAssertion,
127
+ nonStatusAssertions,
128
+ };
129
+ }
130
+
131
+ // function getResponseHeadersAccesses(responseVariables: Variable[], scopeManager: ScopeManager, sourceCode: SourceCode) {
132
+ // const responseHeadersAccesses: TSESTree.MemberExpression[] = [];
133
+ // for (const responseVariable of responseVariables) {
134
+ // for (const responseReference of responseVariable.references) {
135
+ // const responseAccess = getParent(responseReference.identifier);
136
+ // if (!responseAccess || responseAccess.type !== AST_NODE_TYPES.MemberExpression) {
137
+ // continue;
138
+ // }
139
+
140
+ // const responseAccessParent = getParent(responseAccess);
141
+ // if (!responseAccessParent) {
142
+ // continue;
143
+ // }
144
+
145
+ // if (
146
+ // responseAccessParent.type === AST_NODE_TYPES.CallExpression &&
147
+ // responseAccessParent.arguments[0]?.type === AST_NODE_TYPES.ArrowFunctionExpression
148
+ // ) {
149
+ // // map-like operation against responses, e.g. responses.map((response) => response.headers.etag)
150
+ // responseHeadersAccesses.push(
151
+ // ...getResponseHeadersAccesses(
152
+ // scopeManager.getDeclaredVariables(responseAccessParent.arguments[0]),
153
+ // scopeManager,
154
+ // sourceCode,
155
+ // ),
156
+ // );
157
+ // continue;
158
+ // }
159
+
160
+ // if (
161
+ // responseAccess.computed &&
162
+ // responseAccess.property.type === AST_NODE_TYPES.Literal &&
163
+ // responseAccessParent.type === AST_NODE_TYPES.MemberExpression
164
+ // ) {
165
+ // // header access through indexed responses array, e.g. responses[0].headers, responses[1].get(...), etc.
166
+ // responseHeadersAccesses.push(responseAccessParent);
167
+ // } else {
168
+ // responseHeadersAccesses.push(responseAccess);
169
+ // }
170
+ // }
171
+ // }
172
+ // return responseHeadersAccesses;
173
+ // }
174
+
175
+ const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
176
+ const rule: ESLintUtils.RuleModule<
177
+ 'unknownError' | 'preferNativeFetch'
178
+ // | 'shouldUseHeaderGetter'
179
+ > = createRule({
180
+ name: ruleId,
181
+ meta: {
182
+ type: 'suggestion',
183
+ docs: {
184
+ description: 'Prefer native fetch API over customized fixture API.',
185
+ url: getDocumentationUrl(ruleId),
186
+ },
187
+ messages: {
188
+ preferNativeFetch: 'Prefer native fetch API over customized fixture API.',
189
+ // shouldUseHeaderGetter: 'Getter should be used to access response headers.',
190
+ unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
191
+ },
192
+ fixable: 'code',
193
+ schema: [],
194
+ },
195
+ defaultOptions: [],
196
+ create(context) {
197
+ const sourceCode = context.sourceCode;
198
+ const scopeManager = sourceCode.scopeManager;
199
+ assert.ok(scopeManager);
200
+
201
+ return {
202
+ 'CallExpression[callee.property.name="expect"]': (supertestCall: TSESTree.CallExpression) => {
203
+ try {
204
+ assert.ok(supertestCall.callee.type === AST_NODE_TYPES.MemberExpression);
205
+ if (
206
+ supertestCall.callee.object.type !== AST_NODE_TYPES.CallExpression ||
207
+ (supertestCall.callee.object.callee.type === AST_NODE_TYPES.MemberExpression &&
208
+ supertestCall.callee.object.callee.property.type === AST_NODE_TYPES.Identifier &&
209
+ supertestCall.callee.object.callee.property.name === 'expect')
210
+ ) {
211
+ // skip nested expect calls, only focus on the top level
212
+ return;
213
+ }
214
+
215
+ if (!(isUsedInArrayOrAsArgument(supertestCall) || getEnclosingFunction(supertestCall)?.async === false)) {
216
+ return;
217
+ }
218
+
219
+ const fixtureFunction = supertestCall.callee.object;
220
+ const indentation = getIndentation(supertestCall, sourceCode);
221
+
222
+ const [urlArgumentNode] = supertestCall.arguments; // e.g. `/sample-service/v1/ping`
223
+ assert.ok(urlArgumentNode !== undefined);
224
+
225
+ const fixtureCallInformation = {} as FixtureCallInformation;
226
+ analyzeFixtureCall(fixtureFunction, fixtureCallInformation, sourceCode);
227
+
228
+ const responseVariableNameToUse = 'res';
229
+ const { statusAssertion, nonStatusAssertions } = createResponseAssertions(
230
+ fixtureCallInformation,
231
+ sourceCode,
232
+ responseVariableNameToUse,
233
+ );
234
+
235
+ // add variable declaration if needed
236
+ const disableLintComment = '// eslint-disable-next-line @checkdigit/no-promise-instance-method';
237
+ const fetchCallText = sourceCode.getText(fixtureFunction);
238
+ const appendingAssignmentAndAssertionText = [
239
+ ...(statusAssertion !== undefined ? [statusAssertion] : []),
240
+ ...nonStatusAssertions,
241
+ ].join(`;\n${indentation}`);
242
+ const replacementText = fixtureCallInformation.assertions
243
+ ? [
244
+ disableLintComment,
245
+ `${fetchCallText}.then((${responseVariableNameToUse}) => {`,
246
+ appendingAssignmentAndAssertionText === '' ? '' : ` ${appendingAssignmentAndAssertionText};`,
247
+ ` return ${responseVariableNameToUse};`,
248
+ `})`,
249
+ ].join(`\n${indentation}`)
250
+ : fetchCallText;
251
+
252
+ context.report({
253
+ node: supertestCall,
254
+ messageId: 'preferNativeFetch',
255
+ fix(fixer) {
256
+ return fixer.replaceText(fixtureCallInformation.fixtureNode, replacementText);
257
+ },
258
+ });
259
+
260
+ // const responsesVariable = getEnclosingStatement(fixtureCallInformation.fixtureNode);
261
+ // if (!responsesVariable) {
262
+ // return;
263
+ // }
264
+
265
+ // const responseVariableReferences = scopeManager.getDeclaredVariables(responsesVariable);
266
+ // const responseHeadersAccesses = getResponseHeadersAccesses(
267
+ // responseVariableReferences,
268
+ // scopeManager,
269
+ // sourceCode,
270
+ // );
271
+ // for (const responseHeadersAccess of responseHeadersAccesses) {
272
+ // if (isInvalidResponseHeadersAccess(responseHeadersAccess)) {
273
+ // const headerAccess = getParent(responseHeadersAccess);
274
+ // if (headerAccess?.type === AST_NODE_TYPES.MemberExpression) {
275
+ // const headerNameNode = headerAccess.property;
276
+ // const headerName = headerAccess.computed
277
+ // ? sourceCode.getText(headerNameNode)
278
+ // : `'${sourceCode.getText(headerNameNode)}'`;
279
+ // const headerAccessReplacementText = `${sourceCode.getText(headerAccess.object)}.get(${headerName})`;
280
+
281
+ // context.report({
282
+ // node: headerAccess,
283
+ // messageId: 'shouldUseHeaderGetter',
284
+ // fix(fixer) {
285
+ // return fixer.replaceText(headerAccess, headerAccessReplacementText);
286
+ // },
287
+ // });
288
+ // } else if (
289
+ // headerAccess?.type === AST_NODE_TYPES.CallExpression &&
290
+ // responseHeadersAccess.property.type === AST_NODE_TYPES.Identifier &&
291
+ // responseHeadersAccess.property.name === 'get'
292
+ // ) {
293
+ // const headerAccessReplacementText = `${sourceCode.getText(responseHeadersAccess.object)}.headers.get(${sourceCode.getText(headerAccess.arguments[0])})`;
294
+
295
+ // context.report({
296
+ // node: headerAccess,
297
+ // messageId: 'shouldUseHeaderGetter',
298
+ // fix(fixer) {
299
+ // return fixer.replaceText(headerAccess, headerAccessReplacementText);
300
+ // },
301
+ // });
302
+ // }
303
+ // }
304
+ // }
305
+ } catch (error) {
306
+ // eslint-disable-next-line no-console
307
+ console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
308
+ context.report({
309
+ node: supertestCall,
310
+ messageId: 'unknownError',
311
+ data: {
312
+ fileName: context.filename,
313
+ error: error instanceof Error ? error.toString() : JSON.stringify(error),
314
+ },
315
+ });
316
+ }
317
+ },
318
+ };
319
+ },
320
+ });
321
+
322
+ export default rule;
package/src/index.ts CHANGED
@@ -23,6 +23,7 @@ import invalidJsonStringify, { ruleId as invalidJsonStringifyRuleId } from './in
23
23
  import noDuplicatedImports, { ruleId as noDuplicatedImportsRuleId } from './no-duplicated-imports';
24
24
  import noFixture, { ruleId as noFixtureRuleId } from './agent/no-fixture';
25
25
  import noSupertest, { ruleId as noSupertestRuleId } from './agent/no-supertest';
26
+ import supertestThen, { ruleId as supertestThenRuleId } from './agent/supertest-then';
26
27
  import noLegacyServiceTyping, { ruleId as noLegacyServiceTypingRuleId } from './no-legacy-service-typing';
27
28
  import noMappedResponse, { ruleId as noMappedResponseRuleId } from './agent/no-mapped-response';
28
29
  import noPromiseInstanceMethod, { ruleId as noPromiseInstanceMethodRuleId } from './no-promise-instance-method';
@@ -74,6 +75,7 @@ const rules: Record<string, TSESLint.LooseRuleDefinition> = {
74
75
  [noPromiseInstanceMethodRuleId]: noPromiseInstanceMethod,
75
76
  [noFixtureRuleId]: noFixture,
76
77
  [noSupertestRuleId]: noSupertest,
78
+ [supertestThenRuleId]: supertestThen,
77
79
  [fetchThenRuleId]: fetchThen,
78
80
  [noServiceWrapperRuleId]: noServiceWrapper,
79
81
  [noStatusCodeRuleId]: noStatusCode,
@@ -134,6 +136,7 @@ const configs: Record<string, TSESLint.FlatConfig.Config[]> = {
134
136
  [`@checkdigit/${addUrlDomainRuleId}`]: 'off',
135
137
  [`@checkdigit/${noFixtureRuleId}`]: 'off',
136
138
  [`@checkdigit/${noSupertestRuleId}`]: 'off',
139
+ [`@checkdigit/${supertestThenRuleId}`]: 'off',
137
140
  [`@checkdigit/${noServiceWrapperRuleId}`]: 'off',
138
141
  [`@checkdigit/${noStatusCodeRuleId}`]: 'off',
139
142
  [`@checkdigit/${fetchResponseBodyJsonRuleId}`]: 'off',
@@ -183,6 +186,7 @@ const configs: Record<string, TSESLint.FlatConfig.Config[]> = {
183
186
  [`@checkdigit/${addUrlDomainRuleId}`]: 'off',
184
187
  [`@checkdigit/${noFixtureRuleId}`]: 'off',
185
188
  [`@checkdigit/${noSupertestRuleId}`]: 'off',
189
+ [`@checkdigit/${supertestThenRuleId}`]: 'off',
186
190
  [`@checkdigit/${noServiceWrapperRuleId}`]: 'off',
187
191
  [`@checkdigit/${noStatusCodeRuleId}`]: 'off',
188
192
  [`@checkdigit/${fetchResponseBodyJsonRuleId}`]: 'off',
@@ -227,6 +231,7 @@ const configs: Record<string, TSESLint.FlatConfig.Config[]> = {
227
231
  [`@checkdigit/${addAssertImportRuleId}`]: 'error',
228
232
  [`@checkdigit/${noFixtureRuleId}`]: 'error',
229
233
  [`@checkdigit/${noSupertestRuleId}`]: 'error',
234
+ [`@checkdigit/${supertestThenRuleId}`]: 'error',
230
235
  },
231
236
  },
232
237
  {