@checkdigit/eslint-plugin 6.6.0-PR.75-edd9 → 6.6.0-PR.77-5328

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 (45) hide show
  1. package/dist-cjs/index.cjs +755 -2130
  2. package/dist-cjs/metafile.json +82 -519
  3. package/dist-mjs/index.mjs +2 -64
  4. package/dist-mjs/require-resolve-full-response.mjs +5 -2
  5. package/dist-types/index.d.ts +1 -50
  6. package/dist-types/require-resolve-full-response.d.ts +3 -1
  7. package/package.json +1 -1
  8. package/src/index.ts +0 -62
  9. package/src/require-resolve-full-response.ts +2 -1
  10. package/dist-mjs/agent/add-url-domain.mjs +0 -61
  11. package/dist-mjs/agent/fetch-response-body-json.mjs +0 -63
  12. package/dist-mjs/agent/fetch-response-header-getter.mjs +0 -117
  13. package/dist-mjs/agent/fetch-then.mjs +0 -269
  14. package/dist-mjs/agent/fetch.mjs +0 -34
  15. package/dist-mjs/agent/no-fixture.mjs +0 -328
  16. package/dist-mjs/agent/no-full-response.mjs +0 -67
  17. package/dist-mjs/agent/no-mapped-response.mjs +0 -75
  18. package/dist-mjs/agent/no-service-wrapper.mjs +0 -184
  19. package/dist-mjs/agent/no-status-code.mjs +0 -59
  20. package/dist-mjs/agent/response-reference.mjs +0 -56
  21. package/dist-mjs/agent/url.mjs +0 -26
  22. package/dist-types/agent/add-url-domain.d.ts +0 -4
  23. package/dist-types/agent/fetch-response-body-json.d.ts +0 -4
  24. package/dist-types/agent/fetch-response-header-getter.d.ts +0 -4
  25. package/dist-types/agent/fetch-then.d.ts +0 -4
  26. package/dist-types/agent/fetch.d.ts +0 -4
  27. package/dist-types/agent/no-fixture.d.ts +0 -4
  28. package/dist-types/agent/no-full-response.d.ts +0 -4
  29. package/dist-types/agent/no-mapped-response.d.ts +0 -4
  30. package/dist-types/agent/no-service-wrapper.d.ts +0 -4
  31. package/dist-types/agent/no-status-code.d.ts +0 -4
  32. package/dist-types/agent/response-reference.d.ts +0 -16
  33. package/dist-types/agent/url.d.ts +0 -5
  34. package/src/agent/add-url-domain.ts +0 -75
  35. package/src/agent/fetch-response-body-json.ts +0 -76
  36. package/src/agent/fetch-response-header-getter.ts +0 -148
  37. package/src/agent/fetch-then.ts +0 -354
  38. package/src/agent/fetch.ts +0 -52
  39. package/src/agent/no-fixture.ts +0 -453
  40. package/src/agent/no-full-response.ts +0 -75
  41. package/src/agent/no-mapped-response.ts +0 -84
  42. package/src/agent/no-service-wrapper.ts +0 -238
  43. package/src/agent/no-status-code.ts +0 -71
  44. package/src/agent/response-reference.ts +0 -100
  45. package/src/agent/url.ts +0 -23
@@ -1,238 +0,0 @@
1
- // fixture/no-service-wrapper.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
- import { DefinitionType, type Scope } from '@typescript-eslint/scope-manager';
11
- import { PLAIN_URL_REGEXP, TOKENIZED_URL_REGEXP, replaceEndpointUrlPrefixWithDomain } from './url';
12
- import { strict as assert } from 'node:assert';
13
- import getDocumentationUrl from '../get-documentation-url';
14
- import { getEnclosingScopeNode } from '../library/ts-tree';
15
- import { getIndentation } from '../library/format';
16
-
17
- export const ruleId = 'no-service-wrapper';
18
-
19
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
20
-
21
- const rule = createRule({
22
- name: ruleId,
23
- meta: {
24
- type: 'suggestion',
25
- docs: {
26
- description: 'Prefer native fetch over customized service wrapper.',
27
- },
28
- messages: {
29
- preferNativeFetch: 'Prefer native fetch over customized service wrapper.',
30
- invalidOptions:
31
- '"options" argument should be provided with "resolveWithFullResponse" property set as "true". Otherwise, it indicates that the response body will be obtained without status code assertion which could result in unexpected issue. Please manually convert the usage of customized service wrapper call to native fetch.',
32
- unknownError:
33
- 'Unknown error occurred in file "{{fileName}}": {{ error }}. Please manually convert the usage of customized service wrapper call to native fetch.',
34
- },
35
- fixable: 'code',
36
- schema: [],
37
- },
38
- defaultOptions: [],
39
- create(context) {
40
- const sourceCode = context.sourceCode;
41
- const scopeManager = sourceCode.scopeManager;
42
- const parserService = ESLintUtils.getParserServices(context);
43
- const typeChecker = parserService.program.getTypeChecker();
44
-
45
- function isUrlArgumentValid(urlArgument: TSESTree.Node | undefined, scope: Scope) {
46
- if (
47
- (urlArgument?.type === AST_NODE_TYPES.Literal && typeof urlArgument.value === 'string') ||
48
- urlArgument?.type === AST_NODE_TYPES.TemplateLiteral
49
- ) {
50
- const urlText = sourceCode.getText(urlArgument);
51
- return PLAIN_URL_REGEXP.test(urlText) || TOKENIZED_URL_REGEXP.test(urlText);
52
- }
53
-
54
- if (urlArgument?.type === AST_NODE_TYPES.Identifier) {
55
- const foundVariable = scope.variables.find((variable) => variable.name === urlArgument.name);
56
- if (foundVariable) {
57
- const variableDefinition = foundVariable.defs.find((def) => def.type === DefinitionType.Variable);
58
- assert.ok(variableDefinition, `Variable "${urlArgument.name}" not defined in scope`);
59
- const variableDefinitionNode = variableDefinition.node;
60
- assert.ok(variableDefinitionNode.type === AST_NODE_TYPES.VariableDeclarator);
61
- assert.ok(variableDefinitionNode.init, 'Variable definition node has no init property');
62
- return isUrlArgumentValid(variableDefinitionNode.init, scope);
63
- }
64
- }
65
-
66
- return false;
67
- }
68
-
69
- function getType(identifier: TSESTree.Identifier) {
70
- const variable = parserService.esTreeNodeToTSNodeMap.get(identifier);
71
- const variableType = typeChecker.getTypeAtLocation(variable);
72
- return typeChecker.typeToString(variableType);
73
- }
74
-
75
- function isServiceLikeName(name: string) {
76
- return /.*[Ss]ervice$/u.test(name);
77
- }
78
-
79
- function isCalleeServiceWrapper(serviceCall: TSESTree.CallExpression) {
80
- const callee = serviceCall.callee;
81
- if (callee.type !== AST_NODE_TYPES.MemberExpression) {
82
- return false;
83
- }
84
-
85
- const endpoint = callee.object;
86
- if (endpoint.type === AST_NODE_TYPES.Identifier) {
87
- return getType(endpoint) === 'Endpoint' || isServiceLikeName(endpoint.name);
88
- }
89
- if (endpoint.type !== AST_NODE_TYPES.CallExpression) {
90
- return false;
91
- }
92
-
93
- const [contextArgument] = endpoint.arguments;
94
- if (contextArgument?.type !== AST_NODE_TYPES.Identifier) {
95
- return false;
96
- }
97
- if (contextArgument.name !== 'EMPTY_CONTEXT' && getType(contextArgument) !== 'InboundContext') {
98
- return false;
99
- }
100
- const service = endpoint.callee;
101
- if (service.type === AST_NODE_TYPES.Identifier) {
102
- return getType(service) === 'ResolvedService';
103
- }
104
-
105
- if (service.type !== AST_NODE_TYPES.MemberExpression) {
106
- return false;
107
- }
108
- const services = service.object;
109
- if (services.type === AST_NODE_TYPES.Identifier) {
110
- return getType(services) === 'ResolvedServices';
111
- }
112
-
113
- if (services.type !== AST_NODE_TYPES.MemberExpression) {
114
- return false;
115
- }
116
- const configuration = services.object;
117
- if (configuration.type === AST_NODE_TYPES.Identifier) {
118
- return ['Configuration', 'Configuration<ResolvedServices>'].includes(getType(configuration));
119
- }
120
-
121
- // following applies only to test code (fixture)
122
- if (configuration.type !== AST_NODE_TYPES.MemberExpression) {
123
- return false;
124
- }
125
- const fixture = configuration.object;
126
- if (fixture.type === AST_NODE_TYPES.Identifier) {
127
- return fixture.name === 'fixture' || getType(fixture) === 'Fixture';
128
- }
129
-
130
- return false;
131
- }
132
-
133
- return {
134
- 'CallExpression[callee.property.name=/^(head|get|put|post|del|patch)$/]': (
135
- serviceCall: TSESTree.CallExpression,
136
- ) => {
137
- try {
138
- if (!isCalleeServiceWrapper(serviceCall)) {
139
- return;
140
- }
141
-
142
- const enclosingScopeNode = getEnclosingScopeNode(serviceCall);
143
- assert.ok(enclosingScopeNode, 'enclosingScopeNode is undefined');
144
- const scope = scopeManager?.acquire(enclosingScopeNode);
145
- assert.ok(scope, 'scope is undefined');
146
- const urlArgument = serviceCall.arguments[0];
147
- if (!isUrlArgumentValid(urlArgument, scope)) {
148
- return;
149
- }
150
-
151
- assert.ok(serviceCall.callee.type === AST_NODE_TYPES.MemberExpression);
152
- assert.ok(serviceCall.callee.property.type === AST_NODE_TYPES.Identifier);
153
-
154
- // method
155
- const method = serviceCall.callee.property.name;
156
-
157
- // body
158
- let requestBodyProperty = ['put', 'post', 'options'].includes(method) ? serviceCall.arguments[1] : undefined;
159
- if (
160
- requestBodyProperty !== undefined &&
161
- requestBodyProperty.type === AST_NODE_TYPES.Identifier &&
162
- requestBodyProperty.name === 'undefined'
163
- ) {
164
- requestBodyProperty = undefined;
165
- }
166
- // options
167
- const optionsArgument = ['get', 'head', 'del'].includes(method)
168
- ? serviceCall.arguments[1]
169
- : serviceCall.arguments[2];
170
- if (optionsArgument === undefined || optionsArgument.type !== AST_NODE_TYPES.ObjectExpression) {
171
- context.report({
172
- node: serviceCall,
173
- messageId: 'invalidOptions',
174
- });
175
- return;
176
- }
177
- const resolveWithFullResponseProperty = optionsArgument.properties.find(
178
- (property) =>
179
- property.type === AST_NODE_TYPES.Property &&
180
- property.key.type === AST_NODE_TYPES.Identifier &&
181
- property.key.name === 'resolveWithFullResponse',
182
- );
183
- if (
184
- resolveWithFullResponseProperty?.type !== AST_NODE_TYPES.Property ||
185
- resolveWithFullResponseProperty.value.type !== AST_NODE_TYPES.Literal ||
186
- resolveWithFullResponseProperty.value.value !== true
187
- ) {
188
- context.report({
189
- node: optionsArgument,
190
- messageId: 'invalidOptions',
191
- });
192
- return;
193
- }
194
-
195
- // headers
196
- const requestHeadersProperty = optionsArgument.properties.find(
197
- (property) =>
198
- property.type === AST_NODE_TYPES.Property &&
199
- property.key.type === AST_NODE_TYPES.Identifier &&
200
- property.key.name === 'headers',
201
- );
202
-
203
- context.report({
204
- messageId: 'preferNativeFetch',
205
- node: serviceCall,
206
- fix(fixer) {
207
- const url = sourceCode.getText(urlArgument);
208
- const replacedUrl = replaceEndpointUrlPrefixWithDomain(url);
209
- const indentation = getIndentation(serviceCall, sourceCode);
210
-
211
- const fetchText = [
212
- `fetch(${replacedUrl}, {`,
213
- ` method: '${method.toLowerCase() === 'del' ? 'DELETE' : method.toUpperCase()}',`,
214
- ...(requestHeadersProperty ? [` ${sourceCode.getText(requestHeadersProperty)},`] : []),
215
- ...(requestBodyProperty ? [` body: JSON.stringify(${sourceCode.getText(requestBodyProperty)}),`] : []),
216
- '})',
217
- ].join(`\n${indentation}`);
218
- return fixer.replaceText(serviceCall, fetchText);
219
- },
220
- });
221
- } catch (error) {
222
- // eslint-disable-next-line no-console
223
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
224
- context.report({
225
- node: serviceCall,
226
- messageId: 'unknownError',
227
- data: {
228
- fileName: context.filename,
229
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
230
- },
231
- });
232
- }
233
- },
234
- };
235
- },
236
- });
237
-
238
- export default rule;
@@ -1,71 +0,0 @@
1
- // fixture/no-status-code.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 { ESLintUtils, TSESTree } from '@typescript-eslint/utils';
10
- import getDocumentationUrl from '../get-documentation-url';
11
-
12
- export const ruleId = 'no-status-code';
13
-
14
- const createRule = ESLintUtils.RuleCreator((name) => getDocumentationUrl(name));
15
-
16
- const rule = createRule({
17
- name: ruleId,
18
- meta: {
19
- type: 'suggestion',
20
- docs: {
21
- description: 'Access the status code property of the fetch Response using "status" instead of "statusCode".',
22
- },
23
- messages: {
24
- replaceStatusCode: 'Replace "statusCode" with "status".',
25
- unknownError: 'Unknown error occurred in file "{{fileName}}": {{ error }}.',
26
- },
27
- fixable: 'code',
28
- schema: [],
29
- },
30
- defaultOptions: [],
31
- create(context) {
32
- const parserServices = ESLintUtils.getParserServices(context);
33
- const typeChecker = parserServices.program.getTypeChecker();
34
-
35
- return {
36
- 'MemberExpression[property.name="statusCode"]': (responseStatusCode: TSESTree.MemberExpression) => {
37
- try {
38
- const responseNode = parserServices.esTreeNodeToTSNodeMap.get(responseStatusCode.object);
39
- const responseType = typeChecker.getTypeAtLocation(responseNode);
40
-
41
- const shouldReplace =
42
- responseType.getProperties().some((symbol) => symbol.name === 'status') &&
43
- !responseType.getProperties().some((symbol) => symbol.name === 'statusCode');
44
-
45
- if (shouldReplace) {
46
- context.report({
47
- messageId: 'replaceStatusCode',
48
- node: responseStatusCode.property,
49
- fix(fixer) {
50
- return fixer.replaceText(responseStatusCode.property, 'status');
51
- },
52
- });
53
- }
54
- } catch (error) {
55
- // eslint-disable-next-line no-console
56
- console.error(`Failed to apply ${ruleId} rule for file "${context.filename}":`, error);
57
- context.report({
58
- node: responseStatusCode,
59
- messageId: 'unknownError',
60
- data: {
61
- fileName: context.filename,
62
- error: error instanceof Error ? error.toString() : JSON.stringify(error),
63
- },
64
- });
65
- }
66
- },
67
- };
68
- },
69
- });
70
-
71
- export default rule;
@@ -1,100 +0,0 @@
1
- // fixture/response-reference.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 type { MemberExpression, VariableDeclaration } from 'estree';
10
- import { type Scope } from 'eslint';
11
- import { strict as assert } from 'node:assert';
12
- import { getParent } from '../library/tree';
13
-
14
- /**
15
- * analyze response related variables and their references
16
- * the implementation is for fixture API, but it can be used for fetch API as well since the tree structure is similar
17
- * @param variableDeclaration - variable declaration node
18
- */
19
- export function analyzeResponseReferences(
20
- variableDeclaration: VariableDeclaration | undefined,
21
- scopeManager: Scope.ScopeManager,
22
- ) {
23
- const results: {
24
- variable?: Scope.Variable;
25
- bodyReferences: MemberExpression[];
26
- headersReferences: MemberExpression[];
27
- statusReferences: MemberExpression[];
28
- destructuringBodyVariable?: Scope.Variable;
29
- destructuringHeadersVariable?: Scope.Variable;
30
- destructuringHeadersReferences?: MemberExpression[] | undefined;
31
- } = {
32
- bodyReferences: [],
33
- headersReferences: [],
34
- statusReferences: [],
35
- };
36
- if (!variableDeclaration) {
37
- return results;
38
- }
39
-
40
- const responseVariables = scopeManager.getDeclaredVariables(variableDeclaration);
41
- for (const responseVariable of responseVariables) {
42
- const identifier = responseVariable.identifiers[0];
43
- assert.ok(identifier);
44
- const identifierParent = getParent(identifier);
45
- assert.ok(identifierParent);
46
- if (identifierParent.type === 'VariableDeclarator') {
47
- // e.g. const response = ...
48
- results.variable = responseVariable;
49
- const responseReferences = responseVariable.references.map((responseReference) =>
50
- getParent(responseReference.identifier),
51
- );
52
- // e.g. response.body
53
- results.bodyReferences = responseReferences.filter(
54
- (node): node is MemberExpression =>
55
- node?.type === 'MemberExpression' && node.property.type === 'Identifier' && node.property.name === 'body',
56
- );
57
- // e.g. response.headers / response.header / response.get()
58
- results.headersReferences = responseReferences.filter(
59
- (node): node is MemberExpression =>
60
- node?.type === 'MemberExpression' &&
61
- node.property.type === 'Identifier' &&
62
- (node.property.name === 'header' || node.property.name === 'headers' || node.property.name === 'get'),
63
- );
64
- // e.g. response.status / response.statusCode
65
- results.statusReferences = responseReferences.filter(
66
- (node): node is MemberExpression =>
67
- node?.type === 'MemberExpression' &&
68
- node.property.type === 'Identifier' &&
69
- (node.property.name === 'status' || node.property.name === 'statusCode'),
70
- );
71
- } else if (
72
- // body reference through destruction/renaming, e.g. "const { body } = ..."
73
- identifierParent.type === 'Property' &&
74
- identifierParent.key.type === 'Identifier' &&
75
- identifierParent.key.name === 'body'
76
- ) {
77
- results.destructuringBodyVariable = responseVariable;
78
- } else if (
79
- // header reference through destruction/renaming, e.g. "const { headers } = ..."
80
- identifierParent.type === 'Property' &&
81
- identifierParent.key.type === 'Identifier' &&
82
- identifierParent.key.name === 'headers'
83
- ) {
84
- results.destructuringHeadersVariable = responseVariable;
85
- results.destructuringHeadersReferences = responseVariable.references
86
- .map((reference) => reference.identifier)
87
- .map(getParent)
88
- .filter(
89
- (parent): parent is MemberExpression =>
90
- parent?.type === 'MemberExpression' &&
91
- parent.property.type === 'Identifier' &&
92
- parent.property.name !== 'get' &&
93
- getParent(parent)?.type !== 'CallExpression',
94
- );
95
- } else {
96
- throw new Error(`Unknown response variable reference: ${responseVariable.name}`);
97
- }
98
- }
99
- return results;
100
- }
package/src/agent/url.ts DELETED
@@ -1,23 +0,0 @@
1
- // fixture/url.ts
2
-
3
- export const PLAIN_URL_REGEXP = /^[`']\/\w+(?<serviceNamePart>-\w+)*\/v\d+\/(?<any>.|\r|\n)+[`']$/u;
4
- export const TOKENIZED_URL_REGEXP = /^`\$\{(?<serviceNamePart>[A-Z]+_)*BASE_PATH\}\/(?<any>.|\r|\n)+`$/u;
5
-
6
- export function replaceEndpointUrlPrefixWithBasePath(url: string) {
7
- // eslint-disable-next-line no-template-curly-in-string
8
- return url.replace(/^`\/\w+(?<parts>-\w+)*\/v\d+\//u, '`${BASE_PATH}/');
9
- }
10
-
11
- export function replaceEndpointUrlPrefixWithDomain(url: string) {
12
- return url.replace(
13
- /^(?<quotStart>[`'])\/(?<servicename>\w+(?<parts>-\w+)*)(?<path>\/v\d+\/(?<any>.|\r|\n)+(?<quotEnd>[`'])$)/u,
14
- '$1https://$2.checkdigit/$2$4',
15
- );
16
- }
17
-
18
- export function addBasePathUrlDomain(url: string) {
19
- return url.replace(
20
- /^(?<quotStart>[`'])\/(?<servicename>\w+(?<parts>-\w+)*)(?<path>\/v\d+(?<quotEnd>[`'])$)/u,
21
- '$1https://$2.checkdigit/$2$4',
22
- );
23
- }