@readme/api-core 7.0.0-alpha.1

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,427 @@
1
+ import type { ReadStream } from 'node:fs';
2
+ import type { Operation } from 'oas';
3
+ import type { ParameterObject, SchemaObject } from 'oas/dist/rmoas.types';
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import stream from 'node:stream';
8
+
9
+ import caseless from 'caseless';
10
+ import DatauriParser from 'datauri/parser';
11
+ import datauri from 'datauri/sync';
12
+ import getStream from 'get-stream';
13
+ import lodashMerge from 'lodash.merge';
14
+ import removeUndefinedObjects from 'remove-undefined-objects';
15
+
16
+ import getJSONSchemaDefaults from './getJSONSchemaDefaults';
17
+
18
+ // These headers are normally only defined by the OpenAPI definition but we allow the user to
19
+ // manually supply them in their `metadata` parameter if they wish.
20
+ const specialHeaders = ['accept', 'authorization'];
21
+
22
+ /**
23
+ * Extract all available parameters from an operations Parameter Object into a digestable array
24
+ * that we can use to apply to the request.
25
+ *
26
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject}
27
+ * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject}
28
+ */
29
+ function digestParameters(parameters: ParameterObject[]): Record<string, ParameterObject> {
30
+ return parameters.reduce((prev, param) => {
31
+ if ('$ref' in param || 'allOf' in param || 'anyOf' in param || 'oneOf' in param) {
32
+ throw new Error("The OpenAPI document for this operation wasn't dereferenced before processing.");
33
+ } else if (param.name in prev) {
34
+ throw new Error(
35
+ `The operation you are using has the same parameter, ${param.name}, spread across multiple entry points. We unfortunately can't handle this right now.`,
36
+ );
37
+ }
38
+
39
+ return Object.assign(prev, { [param.name]: param });
40
+ }, {});
41
+ }
42
+
43
+ // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_isempty
44
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
+ function isEmpty(obj: any) {
46
+ return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
47
+ }
48
+
49
+ function isObject(thing: unknown) {
50
+ if (thing instanceof stream.Readable) {
51
+ return false;
52
+ }
53
+
54
+ return typeof thing === 'object' && thing !== null && !Array.isArray(thing);
55
+ }
56
+
57
+ function isPrimitive(obj: unknown) {
58
+ return obj === null || typeof obj === 'number' || typeof obj === 'string';
59
+ }
60
+
61
+ function merge(src: unknown, target: unknown) {
62
+ if (Array.isArray(target)) {
63
+ // @todo we need to add support for merging array defaults with array body/metadata arguments
64
+ return target;
65
+ } else if (!isObject(target)) {
66
+ return target;
67
+ }
68
+
69
+ return lodashMerge(src, target);
70
+ }
71
+
72
+ /**
73
+ * Ingest a file path or readable stream into a common object that we can later use to process it
74
+ * into a parameters object for making an API request.
75
+ *
76
+ */
77
+ function processFile(
78
+ paramName: string | undefined,
79
+ file: string | ReadStream,
80
+ ): Promise<{ base64?: string; buffer?: Buffer; filename: string; paramName?: string } | undefined> {
81
+ if (typeof file === 'string') {
82
+ // In order to support relative pathed files, we need to attempt to resolve them.
83
+ const resolvedFile = path.resolve(file);
84
+
85
+ return new Promise((resolve, reject) => {
86
+ fs.stat(resolvedFile, async err => {
87
+ if (err) {
88
+ if (err.code === 'ENOENT') {
89
+ // It's less than ideal for us to handle files that don't exist like this but because
90
+ // `file` is a string it might actually be the full text contents of the file and not
91
+ // actually a path.
92
+ //
93
+ // We also can't really regex to see if `file` *looks*` like a path because one should be
94
+ // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that
95
+ // doesn't *look* like a path, it is one that should still work.
96
+ return resolve(undefined);
97
+ }
98
+
99
+ return reject(err);
100
+ }
101
+
102
+ const fileMetadata = await datauri(resolvedFile);
103
+ const payloadFilename = encodeURIComponent(path.basename(resolvedFile));
104
+
105
+ return resolve({
106
+ paramName,
107
+ base64: fileMetadata?.content?.replace(';base64', `;name=${payloadFilename};base64`),
108
+ filename: payloadFilename,
109
+ buffer: fileMetadata.buffer,
110
+ });
111
+ });
112
+ });
113
+ } else if (file instanceof stream.Readable) {
114
+ return getStream.buffer(file).then(buffer => {
115
+ const filePath = file.path as string;
116
+ const parser = new DatauriParser();
117
+ const base64 = parser.format(filePath, buffer).content;
118
+ const payloadFilename = encodeURIComponent(path.basename(filePath));
119
+
120
+ return {
121
+ paramName,
122
+ base64: base64?.replace(';base64', `;name=${payloadFilename};base64`),
123
+ filename: payloadFilename,
124
+ buffer,
125
+ };
126
+ });
127
+ }
128
+
129
+ return Promise.reject(
130
+ new TypeError(
131
+ paramName
132
+ ? `The data supplied for the \`${paramName}\` request body parameter is not a file handler that we support.`
133
+ : 'The data supplied for the request body payload is not a file handler that we support.',
134
+ ),
135
+ );
136
+ }
137
+
138
+ /**
139
+ * With potentially supplied body and/or metadata we need to run through them against a given API
140
+ * operation to see what's what and prepare any available parameters to be used in an API request
141
+ * with `@readme/oas-to-har`.
142
+ *
143
+ */
144
+ export default async function prepareParams(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
145
+ let metadataIntersected = false;
146
+ const digestedParameters = digestParameters(operation.getParameters());
147
+ const jsonSchema = operation.getParametersAsJSONSchema();
148
+
149
+ /**
150
+ * It might be common for somebody to run `sdk.findPetsByStatus({ status: 'available' }, {})`, in
151
+ * which case we want to filter out the second (metadata) parameter and treat the first parameter
152
+ * as the metadata instead. If we don't do this, their supplied `status` metadata will be treated
153
+ * as a body parameter, and because there's no `status` body parameter, and no supplied metadata
154
+ * (because it's an empty object), the request won't send a payload.
155
+ *
156
+ * @see {@link https://github.com/readmeio/api/issues/449}
157
+ */
158
+ // eslint-disable-next-line no-param-reassign
159
+ metadata = removeUndefinedObjects(metadata);
160
+
161
+ if (!jsonSchema && (body !== undefined || metadata !== undefined)) {
162
+ let throwNoParamsError = true;
163
+
164
+ // If this operation doesn't have any parameters for us to transform to JSON Schema but they've
165
+ // sent us either an `Accept` or `Authorization` header (or both) we should let them do that.
166
+ // We should, however, only do this check for the `body` parameter as if they've sent this
167
+ // request both `body` and `metadata` we can reject it outright as the operation won't have any
168
+ // body data.
169
+ if (body !== undefined) {
170
+ if (typeof body === 'object' && body !== null && !Array.isArray(body)) {
171
+ if (Object.keys(body).length <= 2) {
172
+ const bodyParams = caseless(body);
173
+
174
+ if (specialHeaders.some(header => bodyParams.has(header))) {
175
+ throwNoParamsError = false;
176
+ }
177
+ }
178
+ }
179
+ }
180
+
181
+ if (throwNoParamsError) {
182
+ throw new Error(
183
+ "You supplied metadata and/or body data for this operation but it doesn't have any documented parameters or request payloads. If you think this is an error please contact support for the API you're using.",
184
+ );
185
+ }
186
+ }
187
+
188
+ const jsonSchemaDefaults = jsonSchema ? getJSONSchemaDefaults(jsonSchema) : {};
189
+
190
+ const params: {
191
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
192
+ body?: any;
193
+ cookie?: Record<string, string | number | boolean>;
194
+ files?: Record<string, Buffer>;
195
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
196
+ formData?: any;
197
+ header?: Record<string, string | number | boolean>;
198
+ path?: Record<string, string | number | boolean>;
199
+ query?: Record<string, string | number | boolean>;
200
+ server?: {
201
+ selected: number;
202
+ variables: Record<string, string | number>;
203
+ };
204
+ } = jsonSchemaDefaults;
205
+
206
+ // If a body argument was supplied we need to do a bit of work to see if it's actually a body
207
+ // argument or metadata because the library lets you supply either a body, metadata, or body with
208
+ // metadata.
209
+ if (typeof body !== 'undefined') {
210
+ if (Array.isArray(body) || isPrimitive(body)) {
211
+ // If the body param is an array or a primitive then we know it's absolutely a body because
212
+ // metadata can only ever be undefined or an object.
213
+ params.body = merge(params.body, body);
214
+ } else if (typeof metadata === 'undefined') {
215
+ // No metadata was explicitly provided so we need to analyze the body to determine if it's a
216
+ // body or should be actually be treated as metadata.
217
+ const headerParams = caseless({});
218
+ Object.entries(digestedParameters).forEach(([paramName, param]) => {
219
+ // Headers are sent case-insensitive so we need to make sure that we're properly
220
+ // matching them when detecting what our incoming payload looks like.
221
+ if (param.in === 'header') {
222
+ headerParams.set(paramName, '');
223
+ }
224
+ });
225
+
226
+ // `Accept` and `Authorization` headers can't be defined as normal parameters but we should
227
+ // always allow the user to supply them if they wish.
228
+ specialHeaders.forEach(header => {
229
+ if (!headerParams.has(header)) {
230
+ headerParams.set(header, '');
231
+ }
232
+ });
233
+
234
+ const intersection = Object.keys(body as NonNullable<unknown>).filter(value => {
235
+ if (Object.keys(digestedParameters).includes(value)) {
236
+ return true;
237
+ } else if (headerParams.has(value)) {
238
+ return true;
239
+ }
240
+
241
+ return false;
242
+ }).length;
243
+
244
+ // If more than 25% of the body intersects with the parameters that we've got on hand, then
245
+ // we should treat it as a metadata object and organize into parameters.
246
+ if (intersection && intersection / Object.keys(body as NonNullable<unknown>).length > 0.25) {
247
+ /* eslint-disable no-param-reassign */
248
+ metadataIntersected = true;
249
+ metadata = merge(params.body, body) as Record<string, unknown>;
250
+ body = undefined;
251
+ /* eslint-enable no-param-reassign */
252
+ } else {
253
+ // For all other cases, we should just treat the supplied body as a body.
254
+ params.body = merge(params.body, body);
255
+ }
256
+ } else {
257
+ // Body and metadata were both supplied.
258
+ params.body = merge(params.body, body);
259
+ }
260
+ }
261
+
262
+ if (!operation.hasRequestBody()) {
263
+ // If this operation doesn't have any documented request body then we shouldn't be sending
264
+ // anything.
265
+ delete params.body;
266
+ } else {
267
+ if (!('body' in params)) params.body = {};
268
+
269
+ // We need to retrieve the request body for this operation to search for any `binary` format
270
+ // data that the user wants to send so we know what we need to prepare for the final API
271
+ // request.
272
+ const payloadJsonSchema = jsonSchema.find(js => js.type === 'body');
273
+ if (payloadJsonSchema) {
274
+ if (!params.files) params.files = {};
275
+
276
+ const conversions = [];
277
+
278
+ // @todo add support for `type: array`, `oneOf` and `anyOf`
279
+ if (payloadJsonSchema.schema?.properties) {
280
+ Object.entries(payloadJsonSchema.schema?.properties)
281
+ .filter(([, schema]: [string, SchemaObject]) => schema?.format === 'binary')
282
+ .filter(([prop]) => Object.keys(params.body).includes(prop))
283
+ .forEach(([prop]) => {
284
+ conversions.push(processFile(prop, params.body[prop]));
285
+ });
286
+ } else if (payloadJsonSchema.schema?.type === 'string') {
287
+ if (payloadJsonSchema.schema?.format === 'binary') {
288
+ conversions.push(processFile(undefined, params.body));
289
+ }
290
+ }
291
+
292
+ await Promise.all(conversions)
293
+ .then(fileMetadata => fileMetadata.filter(Boolean))
294
+ .then(fm => {
295
+ fm.forEach(fileMetadata => {
296
+ if (!fileMetadata) {
297
+ // If we don't have any metadata here it's because the file we have is likely
298
+ // the full string content of the file so since we don't have any filenames to
299
+ // work with we shouldn't do any additional handling to the `body` or `files`
300
+ // parameters.
301
+ return;
302
+ }
303
+
304
+ if (fileMetadata.paramName) {
305
+ params.body[fileMetadata.paramName] = fileMetadata.base64;
306
+ } else {
307
+ params.body = fileMetadata.base64;
308
+ }
309
+
310
+ if (fileMetadata.buffer && params?.files) {
311
+ params.files[fileMetadata.filename] = fileMetadata.buffer;
312
+ }
313
+ });
314
+ });
315
+ }
316
+ }
317
+
318
+ // Form data should be placed within `formData` instead of `body` for it to properly get picked
319
+ // up by `fetch-har`.
320
+ if (operation.isFormUrlEncoded()) {
321
+ params.formData = merge(params.formData, params.body);
322
+ delete params.body;
323
+ }
324
+
325
+ // Only spend time trying to organize metadata into parameters if we were able to digest
326
+ // parameters out of the operation schema. If we couldn't digest anything, but metadata was
327
+ // supplied then we wouldn't know how to send it in the request!
328
+ if (typeof metadata !== 'undefined') {
329
+ if (!('cookie' in params)) params.cookie = {};
330
+ if (!('header' in params)) params.header = {};
331
+ if (!('path' in params)) params.path = {};
332
+ if (!('query' in params)) params.query = {};
333
+
334
+ Object.entries(digestedParameters).forEach(([paramName, param]) => {
335
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
336
+ let value: any;
337
+ let metadataHeaderParam;
338
+ if (typeof metadata === 'object' && !isEmpty(metadata)) {
339
+ if (paramName in metadata) {
340
+ value = metadata[paramName];
341
+ metadataHeaderParam = paramName;
342
+ } else if (param.in === 'header') {
343
+ // Headers are sent case-insensitive so we need to make sure that we're properly
344
+ // matching them when detecting what our incoming payload looks like.
345
+ metadataHeaderParam = Object.keys(metadata).find(k => k.toLowerCase() === paramName.toLowerCase()) || '';
346
+ value = metadata[metadataHeaderParam];
347
+ }
348
+ }
349
+
350
+ if (value === undefined) {
351
+ return;
352
+ }
353
+
354
+ /* eslint-disable no-param-reassign */
355
+ switch (param.in) {
356
+ case 'path':
357
+ (params.path as NonNullable<typeof params.path>)[paramName] = value;
358
+ if (metadata?.[paramName]) delete metadata[paramName];
359
+ break;
360
+ case 'query':
361
+ (params.query as NonNullable<typeof params.query>)[paramName] = value;
362
+ if (metadata?.[paramName]) delete metadata[paramName];
363
+ break;
364
+ case 'header':
365
+ (params.header as NonNullable<typeof params.header>)[paramName.toLowerCase()] = value;
366
+ if (metadataHeaderParam && metadata?.[metadataHeaderParam]) delete metadata[metadataHeaderParam];
367
+ break;
368
+ case 'cookie':
369
+ (params.cookie as NonNullable<typeof params.cookie>)[paramName] = value;
370
+ if (metadata?.[paramName]) delete metadata[paramName];
371
+ break;
372
+ default: // no-op
373
+ }
374
+ /* eslint-enable no-param-reassign */
375
+
376
+ // Because a user might have sent just a metadata object, we want to make sure that we filter
377
+ // out anything that they sent that is a parameter from also being sent as part of a form
378
+ // data payload for `x-www-form-urlencoded` requests.
379
+ if (metadataIntersected && operation.isFormUrlEncoded()) {
380
+ if (paramName in params.formData) {
381
+ delete params.formData[paramName];
382
+ }
383
+ }
384
+ });
385
+
386
+ // If there's any leftover metadata that hasn't been moved into form data for this request we
387
+ // need to move it or else it'll get tossed.
388
+ if (!isEmpty(metadata)) {
389
+ if (typeof metadata === 'object') {
390
+ // If the user supplied an `accept` or `authorization` header themselves we should allow it
391
+ // through. Normally these headers are automatically handled by `@readme/oas-to-har` but in
392
+ // the event that maybe the user wants to return XML for an API that normally returns JSON
393
+ // or specify a custom auth header (maybe we can't handle their auth case right) this is the
394
+ // only way with this library that they can do that.
395
+ specialHeaders.forEach(headerName => {
396
+ const headerParam = Object.keys(metadata || {}).find(m => m.toLowerCase() === headerName);
397
+ if (headerParam) {
398
+ // this if-statement below is a typeguard
399
+ if (typeof metadata === 'object') {
400
+ // this if-statement below is a typeguard
401
+ if (typeof params.header === 'object') {
402
+ params.header[headerName] = metadata[headerParam] as string;
403
+ }
404
+ // eslint-disable-next-line no-param-reassign
405
+ delete metadata[headerParam];
406
+ }
407
+ }
408
+ });
409
+ }
410
+
411
+ if (operation.isFormUrlEncoded()) {
412
+ params.formData = merge(params.formData, metadata);
413
+ } else {
414
+ // Any other remaining unused metadata will be unused because we don't know where to place
415
+ // it in the request.
416
+ }
417
+ }
418
+ }
419
+
420
+ (['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'] as const).forEach((type: keyof typeof params) => {
421
+ if (type in params && isEmpty(params[type])) {
422
+ delete params[type];
423
+ }
424
+ });
425
+
426
+ return params;
427
+ }
@@ -0,0 +1,48 @@
1
+ import type Oas from 'oas';
2
+
3
+ function stripTrailingSlash(url: string) {
4
+ if (url[url.length - 1] === '/') {
5
+ return url.slice(0, -1);
6
+ }
7
+
8
+ return url;
9
+ }
10
+
11
+ /**
12
+ * With an SDK server config and an instance of OAS we should extract and prepare the server and
13
+ * any server variables to be supplied to `@readme/oas-to-har`.
14
+ *
15
+ */
16
+ export default function prepareServer(spec: Oas, url: string, variables: Record<string, string | number> = {}) {
17
+ let serverIdx;
18
+ const sanitizedUrl = stripTrailingSlash(url);
19
+ (spec.api.servers || []).forEach((server, i) => {
20
+ if (server.url === sanitizedUrl) {
21
+ serverIdx = i;
22
+ }
23
+ });
24
+
25
+ // If we were able to find the passed in server in the OAS servers, we should use that! If we
26
+ // couldn't and server variables were passed in we should try our best to handle that, otherwise
27
+ // we should ignore the passed in server and use whever the default from the OAS is.
28
+ if (serverIdx) {
29
+ return {
30
+ selected: serverIdx,
31
+ variables,
32
+ };
33
+ } else if (Object.keys(variables).length) {
34
+ // @todo we should run `oas.replaceUrl(url)` and pass that unto `@readme/oas-to-har`
35
+ } else {
36
+ const server = spec.splitVariables(url);
37
+ if (server) {
38
+ return {
39
+ selected: server.selected,
40
+ variables: server.variables,
41
+ };
42
+ }
43
+
44
+ // @todo we should pass `url` directly into `@readme/oas-to-har` as the base URL
45
+ }
46
+
47
+ return false;
48
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "allowJs": true,
4
+ "baseUrl": "./src",
5
+ "declaration": true,
6
+ "esModuleInterop": true,
7
+ "lib": ["DOM", "DOM.Iterable", "ES2020"],
8
+ "noImplicitAny": true,
9
+ "outDir": "dist/",
10
+ "strict": true
11
+ },
12
+ "include": ["./src/**/*"]
13
+ }