-
Notifications
You must be signed in to change notification settings - Fork 43
/
readmeAPIFetch.ts
413 lines (364 loc) · 13.8 KB
/
readmeAPIFetch.ts
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
import type { SpecFileType } from './prepareOas.js';
import type { Command } from '@oclif/core';
import path from 'node:path';
import mime from 'mime-types';
import { ProxyAgent } from 'undici';
import { APIv1Error, APIv2Error, type APIv2ErrorResponse } from './apiError.js';
import config from './config.js';
import { git } from './createGHA/index.js';
import { getPkgVersion } from './getPkg.js';
import isCI, { ciName, isGHA } from './isCI.js';
import { debug, warn } from './logger.js';
const SUCCESS_NO_CONTENT = 204;
/**
* This contains a few pieces of information about a file so
* we can properly construct a source URL for it.
*/
export interface FilePathDetails {
/** The URL or local file path */
filePath: string;
/** This is derived from the `oas-normalize` `type` property. */
fileType: SpecFileType;
}
function getProxy() {
// this is something of an industry standard env var, hence the checks for different casings
return process.env.HTTPS_PROXY || process.env.https_proxy;
}
/**
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning}
* @see {@link https://www.rfc-editor.org/rfc/rfc7234#section-5.5}
* @see {@link https://github.com/marcbachmann/warning-header-parser}
*/
interface WarningHeader {
agent: string;
code: string;
date?: string;
message: string;
}
function stripQuotes(s: string) {
if (!s) return '';
return s.replace(/(^"|[",]*$)/g, '');
}
/**
* Parses Warning header into an array of warning header objects
* @param header raw `Warning` header
* @see {@link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Warning}
* @see {@link https://www.rfc-editor.org/rfc/rfc7234#section-5.5}
* @see {@link https://github.com/marcbachmann/warning-header-parser}
*/
function parseWarningHeader(header: string): WarningHeader[] {
try {
const warnings = header.split(/([0-9]{3} [a-z0-9.@\-/]*) /g);
let previous: WarningHeader;
return warnings.reduce<WarningHeader[]>((all, w) => {
// eslint-disable-next-line no-param-reassign
w = w.trim();
const newError = w.match(/^([0-9]{3}) (.*)/);
if (newError) {
previous = { code: newError[1], agent: newError[2], message: '' };
} else if (w) {
const errorContent = w.split(/" "/);
if (errorContent) {
previous.message = stripQuotes(errorContent[0]);
previous.date = stripQuotes(errorContent[1]);
all.push(previous);
}
}
return all;
}, []);
} catch (e) {
debug(`error parsing warning header: ${e.message}`);
return [{ code: '199', agent: '-', message: header }];
}
}
/**
* Getter function for a string to be used in the user-agent header based on the current
* environment. Used for API v1 requests.
*
*/
export function getUserAgent() {
const gh = isGHA() ? '-github' : '';
return `rdme${gh}/${getPkgVersion()}`;
}
/**
* Creates a relative path for the file from the root of the repo,
* otherwise returns the path
*/
async function normalizeFilePath(opts: FilePathDetails) {
if (opts.fileType === 'path') {
const repoRoot = await git.revparse(['--show-toplevel']).catch(e => {
debug(`[fetch] error grabbing git root: ${e.message}`);
return '';
});
return path.relative(repoRoot, opts.filePath);
}
return opts.filePath;
}
/**
* Sanitizes and stringifies the `Headers` object for logging purposes
*/
function sanitizeHeaders(headers: Headers) {
const raw = Array.from(headers.entries()).reduce<Record<string, string>>((prev, current) => {
// eslint-disable-next-line no-param-reassign
prev[current[0]] = current[0].toLowerCase() === 'authorization' ? 'redacted' : current[1];
return prev;
}, {});
return JSON.stringify(raw);
}
/**
* Wrapper for the `fetch` API so we can add rdme-specific headers to all ReadMe API v1 requests.
*
* @param pathname the pathname to make the request to. Must have a leading slash.
* @param fileOpts optional object containing information about the file being sent.
* We use this to construct a full source URL for the file.
*/
export async function readmeAPIv1Fetch(
pathname: string,
options: RequestInit = { headers: new Headers() },
fileOpts: FilePathDetails = { filePath: '', fileType: false },
) {
let source = 'cli';
let headers = options.headers as Headers;
if (!(options.headers instanceof Headers)) {
headers = new Headers(options.headers);
}
headers.set('User-Agent', getUserAgent());
if (isGHA()) {
source = 'cli-gh';
if (process.env.GITHUB_REPOSITORY) headers.set('x-github-repository', process.env.GITHUB_REPOSITORY);
if (process.env.GITHUB_RUN_ATTEMPT) headers.set('x-github-run-attempt', process.env.GITHUB_RUN_ATTEMPT);
if (process.env.GITHUB_RUN_ID) headers.set('x-github-run-id', process.env.GITHUB_RUN_ID);
if (process.env.GITHUB_RUN_NUMBER) headers.set('x-github-run-number', process.env.GITHUB_RUN_NUMBER);
if (process.env.GITHUB_SHA) headers.set('x-github-sha', process.env.GITHUB_SHA);
const filePath = await normalizeFilePath(fileOpts);
if (filePath) {
/**
* Constructs a full URL to the file using GitHub Actions runner variables
* @see {@link https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables}
* @example https://github.com/readmeio/rdme/blob/cb4129d5c7b51ff3b50f933a9c7d0c3d0d33d62c/documentation/rdme.md
*/
try {
const sourceUrl = new URL(
`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${filePath}`,
).href;
headers.set('x-readme-source-url', sourceUrl);
} catch (e) {
debug(`error constructing github source url: ${e.message}`);
}
}
}
if (isCI()) {
headers.set('x-rdme-ci', ciName());
}
headers.set('x-readme-source', source);
if (fileOpts.filePath && fileOpts.fileType === 'url') {
headers.set('x-readme-source-url', fileOpts.filePath);
}
const fullUrl = `${config.host.v1}${pathname}`;
const proxy = getProxy();
debug(
`making ${(options.method || 'get').toUpperCase()} request to ${fullUrl} ${proxy ? `with proxy ${proxy} and ` : ''}with headers: ${sanitizeHeaders(headers)}`,
);
return fetch(fullUrl, {
...options,
headers,
// @ts-expect-error we need to clean up our undici usage here ASAP
dispatcher: proxy ? new ProxyAgent(proxy) : undefined,
})
.then(res => {
const warningHeader = res.headers.get('Warning');
if (warningHeader) {
debug(`received warning header: ${warningHeader}`);
const warnings = parseWarningHeader(warningHeader);
warnings.forEach(warning => {
warn(warning.message, 'ReadMe API Warning:');
});
}
return res;
})
.catch(e => {
debug(`error making fetch request: ${e}`);
throw e;
});
}
/**
* Wrapper for the `fetch` API so we can add rdme-specific headers to all ReadMe API v2 requests.
*
* @param pathname the pathname to make the request to. Must have a leading slash.
* @param fileOpts optional object containing information about the file being sent.
* We use this to construct a full source URL for the file.
*/
export async function readmeAPIv2Fetch<T extends Command>(
this: T,
pathname: string,
options: RequestInit = { headers: new Headers() },
fileOpts: FilePathDetails = { filePath: '', fileType: false },
) {
let source = 'cli';
let headers = options.headers as Headers;
if (!(options.headers instanceof Headers)) {
headers = new Headers(options.headers);
}
headers.set(
'User-Agent',
this.config.userAgent.replace(this.config.name, `${this.config.name}${isGHA() ? '-github' : ''}`),
);
if (!headers.get('accept')) {
headers.set('accept', 'application/json');
}
if (isGHA()) {
source = 'cli-gh';
if (process.env.GITHUB_REPOSITORY) headers.set('x-github-repository', process.env.GITHUB_REPOSITORY);
if (process.env.GITHUB_RUN_ATTEMPT) headers.set('x-github-run-attempt', process.env.GITHUB_RUN_ATTEMPT);
if (process.env.GITHUB_RUN_ID) headers.set('x-github-run-id', process.env.GITHUB_RUN_ID);
if (process.env.GITHUB_RUN_NUMBER) headers.set('x-github-run-number', process.env.GITHUB_RUN_NUMBER);
if (process.env.GITHUB_SHA) headers.set('x-github-sha', process.env.GITHUB_SHA);
const filePath = await normalizeFilePath(fileOpts);
if (filePath) {
/**
* Constructs a full URL to the file using GitHub Actions runner variables
* @see {@link https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables}
* @example https://github.com/readmeio/rdme/blob/cb4129d5c7b51ff3b50f933a9c7d0c3d0d33d62c/documentation/rdme.md
*/
try {
const sourceUrl = new URL(
`${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/blob/${process.env.GITHUB_SHA}/${filePath}`,
).href;
headers.set('x-readme-source-url', sourceUrl);
} catch (e) {
this.debug(`error constructing github source url: ${e.message}`);
}
}
}
if (isCI()) {
headers.set('x-rdme-ci', ciName());
}
headers.set('x-readme-source', source);
if (fileOpts.filePath && fileOpts.fileType === 'url') {
headers.set('x-readme-source-url', fileOpts.filePath);
}
const fullUrl = `${config.host.v2}${pathname}`;
const proxy = getProxy();
this.debug(
`making ${(options.method || 'get').toUpperCase()} request to ${fullUrl} ${proxy ? `with proxy ${proxy} and ` : ''}with headers: ${sanitizeHeaders(headers)}`,
);
return fetch(fullUrl, {
...options,
headers,
// @ts-expect-error we need to clean up our undici usage here ASAP
dispatcher: proxy ? new ProxyAgent(proxy) : undefined,
})
.then(res => {
const warningHeader = res.headers.get('Warning');
if (warningHeader) {
this.debug(`received warning header: ${warningHeader}`);
const warnings = parseWarningHeader(warningHeader);
warnings.forEach(warning => {
warn(warning.message, 'ReadMe API Warning:');
});
}
return res;
})
.catch(e => {
this.debug(`error making fetch request: ${e}`);
throw e;
});
}
/**
* Small handler for handling responses from ReadMe API v1.
*
* If we receive JSON errors, we throw an APIv1Error exception.
*
* If we receive non-JSON responses, we consider them errors and throw them.
*
* @param rejectOnJsonError if omitted (or set to true), the function will return
* an `APIv1Error` if the JSON body contains an `error` property. If set to false,
* the function will return a resolved promise containing the JSON object.
*
*/
export async function handleAPIv1Res(res: Response, rejectOnJsonError = true) {
const contentType = res.headers.get('content-type') || '';
const extension = mime.extension(contentType);
if (extension === 'json') {
// TODO: type this better
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = (await res.json()) as any;
debug(`received status code ${res.status} from ${res.url} with JSON response: ${JSON.stringify(body)}`);
if (body.error && rejectOnJsonError) {
return Promise.reject(new APIv1Error(body));
}
return body;
}
if (res.status === SUCCESS_NO_CONTENT) {
debug(`received status code ${res.status} from ${res.url} with no content`);
return {};
}
// If we receive a non-JSON response, it's likely an error.
// Let's debug the raw response body and throw it.
const body = await res.text();
debug(`received status code ${res.status} from ${res.url} with non-JSON response: ${body}`);
return Promise.reject(body);
}
/**
* Small handler for handling responses from ReadMe API v2.
*
* If we receive JSON errors, we throw an APIError exception.
*
* If we receive non-JSON responses, we consider them errors and throw them.
*/
export async function handleAPIv2Res<T extends Command>(this: T, res: Response) {
const contentType = res.headers.get('content-type') || '';
const extension = mime.extension(contentType) || contentType.includes('json') ? 'json' : false;
if (extension === 'json') {
// TODO: type this better
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const body = (await res.json()) as any;
this.debug(`received status code ${res.status} from ${res.url} with JSON response: ${JSON.stringify(body)}`);
if (!res.ok) {
throw new APIv2Error(body as APIv2ErrorResponse);
}
return body;
}
if (res.status === SUCCESS_NO_CONTENT) {
this.debug(`received status code ${res.status} from ${res.url} with no content`);
return {};
}
// If we receive a non-JSON response, it's likely an error.
// Let's debug the raw response body and throw it.
const body = await res.text();
this.debug(`received status code ${res.status} from ${res.url} with non-JSON response: ${body}`);
throw new Error(
'The ReadMe API responded with an unexpected error. Please try again and if this issue persists, get in touch with us at [email protected].',
);
}
/**
* If you supply `undefined` or `null` to the `Headers` API,
* it'll convert those to a string by default,
* so we instead filter those out here.
*/
function filterOutFalsyHeaders(inputHeaders: Headers) {
const headers = new Headers();
for (const header of inputHeaders.entries()) {
if (header[1] !== 'null' && header[1] !== 'undefined' && header[1].length > 0) {
headers.set(header[0], header[1]);
}
}
return headers;
}
/**
* Returns the basic auth header and any other defined headers for use in `fetch` calls against ReadMe API v1.
*
*/
export function cleanAPIv1Headers(
key: string,
/** used for `x-readme-header` */
version?: string,
headers: Headers = new Headers(),
) {
const encodedKey = Buffer.from(`${key}:`).toString('base64');
headers.set('Authorization', `Basic ${encodedKey}`);
if (version) {
headers.set('x-readme-version', version);
}
return filterOutFalsyHeaders(headers);
}