-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapi-response-status.test.ts
More file actions
338 lines (311 loc) · 9.42 KB
/
Copy pathapi-response-status.test.ts
File metadata and controls
338 lines (311 loc) · 9.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import { readdirSync, readFileSync } from 'node:fs';
import { join, relative } from 'node:path';
import { describe, expect, it } from 'vitest';
const PROJECT_ROOT = process.cwd();
const API_REFERENCE_DIR = join(PROJECT_ROOT, 'api-reference');
const FRONTMATTER_API_PATTERN = /^api:\s*"([A-Z]+) ([^"]+)"/mu;
const RESPONSE_TAB_PATTERN = /<Tab title="(\d{3})\b/gu;
const STATUS_CODE_PATTERN = /^\d{3}$/u;
const FULL_STATUS_AUDITED_OPERATIONS = new Set([
'DELETE /api-keys/{id}',
'DELETE /drafts/{id}',
'DELETE /monitors/{id}',
'DELETE /monitors/keywords/{id}',
'DELETE /styles/{id}',
'DELETE /webhooks/{id}',
'DELETE /x/accounts/{id}',
'DELETE /x/tweets/{id}',
'DELETE /x/tweets/{id}/like',
'DELETE /x/tweets/{id}/retweet',
'DELETE /x/users/{id}/follow',
'DELETE /x/communities/{id}',
'DELETE /x/communities/{id}/join',
'GET /account',
'GET /api-keys',
'GET /credits',
'GET /credits/topup/status',
'GET /drafts',
'GET /drafts/{id}',
'GET /draws',
'GET /draws/{id}',
'GET /draws/{id}/export',
'GET /events',
'GET /events/{id}',
'GET /extractions',
'GET /extractions/{id}',
'GET /extractions/{id}/export',
'GET /monitors',
'GET /monitors/{id}',
'GET /monitors/keywords',
'GET /monitors/keywords/{id}',
'GET /radar',
'GET /styles',
'GET /styles/{id}',
'GET /styles/{id}/performance',
'GET /styles/compare',
'GET /support/tickets',
'GET /support/tickets/{id}',
'GET /trends',
'GET /webhooks',
'GET /webhooks/{id}/deliveries',
'GET /x/followers/check',
'GET /x/articles/{tweetId}',
'GET /x/accounts',
'GET /x/accounts/{id}',
'GET /x/bookmarks',
'GET /x/bookmarks/folders',
'GET /x/communities/search',
'GET /x/communities/tweets',
'GET /x/communities/{id}/info',
'GET /x/communities/{id}/members',
'GET /x/communities/{id}/moderators',
'GET /x/communities/{id}/tweets',
'GET /x/dm/{userId}/history',
'GET /x/lists/{id}/followers',
'GET /x/lists/{id}/members',
'GET /x/lists/{id}/tweets',
'GET /x/notifications',
'GET /x/timeline',
'GET /x/trends',
'GET /x/tweets',
'GET /x/tweets/search',
'GET /x/tweets/{id}',
'GET /x/tweets/{id}/favoriters',
'GET /x/tweets/{id}/quotes',
'GET /x/tweets/{id}/replies',
'GET /x/tweets/{id}/retweeters',
'GET /x/tweets/{id}/thread',
'GET /x/users/batch',
'GET /x/users/search',
'GET /x/users/{id}',
'GET /x/users/{id}/followers',
'GET /x/users/{id}/followers-you-know',
'GET /x/users/{id}/following',
'GET /x/users/{id}/likes',
'GET /x/users/{id}/media',
'GET /x/users/{id}/mentions',
'GET /x/users/{id}/replies',
'GET /x/users/{id}/tweets',
'GET /x/users/{id}/verified-followers',
'PATCH /account',
'PATCH /monitors/{id}',
'PATCH /monitors/keywords/{id}',
'PATCH /support/tickets/{id}',
'PATCH /webhooks/{id}',
'POST /api-keys',
'POST /compose',
'POST /subscribe',
'POST /credits/quick-topup',
'POST /credits/topup',
'POST /drafts',
'POST /draws',
'POST /extractions',
'POST /extractions/estimate',
'POST /monitors',
'POST /monitors/keywords',
'POST /styles',
'POST /support/tickets',
'POST /support/tickets/{id}/messages',
'POST /webhooks',
'POST /webhooks/{id}/test',
'POST /x/account-connection-challenges/{id}/submit',
'POST /x/accounts',
'POST /x/accounts/{id}/reauth',
'POST /x/accounts/bulk-retry',
'POST /x/communities',
'POST /x/communities/{id}/join',
'POST /x/dm/{userId}',
'POST /x/media/download',
'POST /x/media',
'POST /x/tweets',
'POST /x/tweets/{id}/like',
'POST /x/tweets/{id}/retweet',
'POST /x/users/{id}/follow',
'POST /x/users/{id}/remove-follower',
'PUT /account/x-identity',
'PATCH /x/profile',
'PATCH /x/profile/avatar',
'PATCH /x/profile/banner',
'PUT /styles/{id}',
]);
interface ApiDoc {
readonly file: string;
readonly method: string;
readonly path: string;
readonly source: string;
}
interface OpenApiOperation {
readonly responses?: Record<string, unknown>;
}
interface OpenApiSpec {
readonly paths?: Record<string, Record<string, OpenApiOperation>>;
}
interface ResponseStatusFinding {
readonly file: string;
readonly issue: string;
readonly operation: string;
readonly status: string;
}
function parseYaml(source: string): OpenApiSpec {
const bun = globalThis as {
readonly Bun?: { readonly YAML?: { parse: (yaml: string) => unknown } };
};
const parse = bun.Bun?.YAML?.parse;
if (parse === undefined) {
throw new Error('Bun.YAML.parse is required for OpenAPI docs tests.');
}
return parse(source) as OpenApiSpec;
}
function listApiReferenceFiles(dir: string): readonly string[] {
const files: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...listApiReferenceFiles(fullPath));
continue;
}
if (entry.name.endsWith('.mdx')) {
files.push(relative(PROJECT_ROOT, fullPath));
}
}
return files.sort();
}
function readApiDocs(): readonly ApiDoc[] {
return listApiReferenceFiles(API_REFERENCE_DIR).flatMap((file) => {
const source = readFileSync(join(PROJECT_ROOT, file), 'utf8');
const match = FRONTMATTER_API_PATTERN.exec(source);
if (match?.[1] === undefined || match[2] === undefined) {
return [];
}
return [
{
file,
method: match[1].toLowerCase(),
path: match[2],
source,
},
];
});
}
function successfulResponseStatuses(
operation: OpenApiOperation,
): readonly string[] {
return Object.keys(operation.responses ?? {})
.filter(
(status): boolean =>
STATUS_CODE_PATTERN.test(status) && status.startsWith('2'),
)
.sort();
}
function documentedSuccessfulResponseTabs(source: string): readonly string[] {
return [...source.matchAll(RESPONSE_TAB_PATTERN)]
.map((match): string => match[1] ?? '')
.filter((status): boolean => status.startsWith('2'))
.sort();
}
function documentedResponseTabs(source: string): readonly string[] {
return [...source.matchAll(RESPONSE_TAB_PATTERN)]
.map((match): string => match[1] ?? '')
.sort();
}
function operationKey(apiDoc: ApiDoc): string {
return `${apiDoc.method.toUpperCase()} ${apiDoc.path}`;
}
function getOperation(
spec: OpenApiSpec,
apiDoc: ApiDoc,
): OpenApiOperation | undefined {
return spec.paths?.[apiDoc.path]?.[apiDoc.method];
}
function collectResponseStatusFindings(
spec: OpenApiSpec,
): readonly ResponseStatusFinding[] {
return collectStatusFindings({
docsStatusProvider: documentedSuccessfulResponseTabs,
issuePrefix: 'success ',
spec,
statusProvider: successfulResponseStatuses,
});
}
function responseStatuses(operation: OpenApiOperation): readonly string[] {
return Object.keys(operation.responses ?? {})
.filter((status): boolean => STATUS_CODE_PATTERN.test(status))
.sort();
}
function collectAuditedResponseStatusFindings(
spec: OpenApiSpec,
): readonly ResponseStatusFinding[] {
return collectStatusFindings({
docsStatusProvider: documentedResponseTabs,
issuePrefix: '',
operationFilter: (apiDoc): boolean =>
FULL_STATUS_AUDITED_OPERATIONS.has(operationKey(apiDoc)),
spec,
statusProvider: responseStatuses,
});
}
function collectStatusFindings({
docsStatusProvider,
issuePrefix,
operationFilter = (): boolean => true,
spec,
statusProvider,
}: {
readonly docsStatusProvider: (source: string) => readonly string[];
readonly issuePrefix: string;
readonly operationFilter?: (apiDoc: ApiDoc) => boolean;
readonly spec: OpenApiSpec;
readonly statusProvider: (operation: OpenApiOperation) => readonly string[];
}): readonly ResponseStatusFinding[] {
const findings: ResponseStatusFinding[] = [];
for (const apiDoc of readApiDocs()) {
if (!operationFilter(apiDoc)) {
continue;
}
const operation = getOperation(spec, apiDoc);
if (operation === undefined) {
findings.push({
file: apiDoc.file,
issue: 'API reference frontmatter does not match openapi.yaml.',
operation: operationKey(apiDoc),
status: apiDoc.path,
});
continue;
}
const openApiStatuses = statusProvider(operation);
const docsStatuses = docsStatusProvider(apiDoc.source);
for (const status of openApiStatuses.filter(
(statusCode): boolean => !docsStatuses.includes(statusCode),
)) {
findings.push({
file: apiDoc.file,
issue: `OpenAPI ${issuePrefix}response status is missing from endpoint docs.`,
operation: operationKey(apiDoc),
status,
});
}
for (const status of docsStatuses.filter(
(statusCode): boolean => !openApiStatuses.includes(statusCode),
)) {
findings.push({
file: apiDoc.file,
issue: `Endpoint docs include a ${issuePrefix}status not present in OpenAPI.`,
operation: operationKey(apiDoc),
status,
});
}
}
return findings;
}
describe('API success response status documentation', (): void => {
it('keeps endpoint success response tabs aligned with OpenAPI status codes', (): void => {
expect.assertions(1);
const spec = parseYaml(readFileSync(join(PROJECT_ROOT, 'openapi.yaml'), 'utf8'));
expect(collectResponseStatusFindings(spec)).toStrictEqual([]);
});
it('keeps fully audited endpoint response tabs aligned with OpenAPI status codes', (): void => {
expect.assertions(1);
const spec = parseYaml(readFileSync(join(PROJECT_ROOT, 'openapi.yaml'), 'utf8'));
expect(collectAuditedResponseStatusFindings(spec)).toStrictEqual([]);
});
});