api 6.1.1 → 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.
Files changed (69) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +0 -12
  3. package/dist/bin.js +3 -3
  4. package/dist/{cli/codegen → codegen}/index.js +4 -4
  5. package/dist/{cli/codegen → codegen}/language.js +4 -3
  6. package/dist/codegen/languages/typescript/util.d.ts +10 -0
  7. package/dist/{cli/codegen → codegen}/languages/typescript/util.js +5 -6
  8. package/dist/{cli/codegen → codegen}/languages/typescript.d.ts +12 -12
  9. package/dist/{cli/codegen → codegen}/languages/typescript.js +75 -75
  10. package/dist/{cli/commands → commands}/index.js +3 -3
  11. package/dist/{cli/commands → commands}/install.js +37 -34
  12. package/dist/fetcher.d.ts +8 -9
  13. package/dist/fetcher.js +15 -15
  14. package/dist/{cli/lib → lib}/prompt.js +3 -3
  15. package/dist/{cli/logger.js → logger.js} +3 -3
  16. package/dist/packageInfo.d.ts +1 -1
  17. package/dist/packageInfo.js +2 -2
  18. package/dist/{cli/storage.d.ts → storage.d.ts} +5 -4
  19. package/dist/{cli/storage.js → storage.js} +39 -36
  20. package/package.json +14 -32
  21. package/src/bin.ts +1 -1
  22. package/src/{cli/codegen → codegen}/language.ts +3 -2
  23. package/src/{cli/codegen → codegen}/languages/typescript/util.ts +1 -1
  24. package/src/{cli/codegen → codegen}/languages/typescript.ts +31 -32
  25. package/src/{cli/commands → commands}/install.ts +1 -1
  26. package/src/fetcher.ts +4 -5
  27. package/src/packageInfo.ts +1 -1
  28. package/src/{cli/storage.ts → storage.ts} +13 -9
  29. package/tsconfig.json +3 -13
  30. package/dist/cache.d.ts +0 -68
  31. package/dist/cache.js +0 -198
  32. package/dist/cli/codegen/languages/typescript/util.d.ts +0 -20
  33. package/dist/core/errors/fetchError.d.ts +0 -12
  34. package/dist/core/errors/fetchError.js +0 -36
  35. package/dist/core/getJSONSchemaDefaults.d.ts +0 -14
  36. package/dist/core/getJSONSchemaDefaults.js +0 -61
  37. package/dist/core/index.d.ts +0 -40
  38. package/dist/core/index.js +0 -168
  39. package/dist/core/parseResponse.d.ts +0 -6
  40. package/dist/core/parseResponse.js +0 -71
  41. package/dist/core/prepareAuth.d.ts +0 -5
  42. package/dist/core/prepareAuth.js +0 -84
  43. package/dist/core/prepareParams.d.ts +0 -21
  44. package/dist/core/prepareParams.js +0 -425
  45. package/dist/core/prepareServer.d.ts +0 -10
  46. package/dist/core/prepareServer.js +0 -47
  47. package/dist/index.d.ts +0 -6
  48. package/dist/index.js +0 -259
  49. package/src/.sink.d.ts +0 -1
  50. package/src/cache.ts +0 -193
  51. package/src/core/errors/fetchError.ts +0 -31
  52. package/src/core/getJSONSchemaDefaults.ts +0 -74
  53. package/src/core/index.ts +0 -148
  54. package/src/core/parseResponse.ts +0 -26
  55. package/src/core/prepareAuth.ts +0 -109
  56. package/src/core/prepareParams.ts +0 -415
  57. package/src/core/prepareServer.ts +0 -48
  58. package/src/index.ts +0 -203
  59. package/src/typings.d.ts +0 -2
  60. /package/dist/{cli/codegen → codegen}/index.d.ts +0 -0
  61. /package/dist/{cli/codegen → codegen}/language.d.ts +0 -0
  62. /package/dist/{cli/commands → commands}/index.d.ts +0 -0
  63. /package/dist/{cli/commands → commands}/install.d.ts +0 -0
  64. /package/dist/{cli/lib → lib}/prompt.d.ts +0 -0
  65. /package/dist/{cli/logger.d.ts → logger.d.ts} +0 -0
  66. /package/src/{cli/codegen → codegen}/index.ts +0 -0
  67. /package/src/{cli/commands → commands}/index.ts +0 -0
  68. /package/src/{cli/lib → lib}/prompt.ts +0 -0
  69. /package/src/{cli/logger.ts → logger.ts} +0 -0
package/src/core/index.ts DELETED
@@ -1,148 +0,0 @@
1
- import type Oas from 'oas';
2
- import type { Operation } from 'oas';
3
- import type { HttpMethods } from 'oas/dist/rmoas.types';
4
-
5
- import oasToHar from '@readme/oas-to-har';
6
- import fetchHar from 'fetch-har';
7
- import { FormDataEncoder } from 'form-data-encoder';
8
- import 'isomorphic-fetch';
9
- // `AbortController` was shipped in Node 15 so when Node 14 is EOL'd we can drop this dependency.
10
- import { AbortController } from 'node-abort-controller';
11
-
12
- import FetchError from './errors/fetchError';
13
- import getJSONSchemaDefaults from './getJSONSchemaDefaults';
14
- import parseResponse from './parseResponse';
15
- import prepareAuth from './prepareAuth';
16
- import prepareParams from './prepareParams';
17
- import prepareServer from './prepareServer';
18
-
19
- export interface ConfigOptions {
20
- /**
21
- * Override the default `fetch` request timeout of 30 seconds. This number should be represented
22
- * in milliseconds.
23
- */
24
- timeout?: number;
25
- }
26
-
27
- export interface FetchResponse<status, data> {
28
- data: data;
29
- headers: Headers;
30
- res: Response;
31
- status: status;
32
- }
33
-
34
- // https://stackoverflow.com/a/39495173
35
- type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N
36
- ? Acc[number]
37
- : Enumerate<N, [...Acc, Acc['length']]>;
38
-
39
- export type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
40
-
41
- export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
42
-
43
- export default class APICore {
44
- spec: Oas;
45
-
46
- private auth: (number | string)[] = [];
47
-
48
- private server:
49
- | false
50
- | {
51
- url?: string;
52
- variables?: Record<string, string | number>;
53
- } = false;
54
-
55
- private config: ConfigOptions = {};
56
-
57
- private userAgent: string;
58
-
59
- constructor(spec?: Oas, userAgent?: string) {
60
- this.spec = spec;
61
- this.userAgent = userAgent;
62
- }
63
-
64
- setSpec(spec: Oas) {
65
- this.spec = spec;
66
- }
67
-
68
- setConfig(config: ConfigOptions) {
69
- this.config = config;
70
- return this;
71
- }
72
-
73
- setUserAgent(userAgent: string) {
74
- this.userAgent = userAgent;
75
- return this;
76
- }
77
-
78
- setAuth(...values: string[] | number[]) {
79
- this.auth = values;
80
- return this;
81
- }
82
-
83
- setServer(url: string, variables: Record<string, string | number> = {}) {
84
- this.server = { url, variables };
85
- return this;
86
- }
87
-
88
- async fetch(path: string, method: HttpMethods, body?: unknown, metadata?: Record<string, unknown>) {
89
- const operation = this.spec.operation(path, method);
90
-
91
- return this.fetchOperation(operation, body, metadata);
92
- }
93
-
94
- async fetchOperation(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
95
- return prepareParams(operation, body, metadata).then(params => {
96
- const data = { ...params };
97
-
98
- // If `sdk.server()` has been issued data then we need to do some extra work to figure out
99
- // how to use that supplied server, and also handle any server variables that were sent
100
- // alongside it.
101
- if (this.server) {
102
- const preparedServer = prepareServer(this.spec, this.server.url, this.server.variables);
103
- if (preparedServer) {
104
- data.server = preparedServer;
105
- }
106
- }
107
-
108
- // @ts-expect-error `this.auth` typing is off. FIXME
109
- const har = oasToHar(this.spec, operation, data, prepareAuth(this.auth, operation));
110
-
111
- let timeoutSignal: any;
112
- const init: RequestInit = {};
113
- if (this.config.timeout) {
114
- const controller = new AbortController();
115
- timeoutSignal = setTimeout(() => controller.abort(), this.config.timeout);
116
- // @todo Typing on `AbortController` coming out of `node-abort-controler` isn't right so when
117
- // we eventually drop that dependency we can remove the `as any` here.
118
- init.signal = controller.signal as any;
119
- }
120
-
121
- return fetchHar(har as any, {
122
- files: data.files || {},
123
- init,
124
- multipartEncoder: FormDataEncoder,
125
- userAgent: this.userAgent,
126
- })
127
- .then(async (res: Response) => {
128
- const parsed = await parseResponse(res);
129
-
130
- if (res.status >= 400 && res.status <= 599) {
131
- throw new FetchError<typeof parsed.status, typeof parsed.data>(
132
- parsed.status,
133
- parsed.data,
134
- parsed.headers,
135
- parsed.res,
136
- );
137
- }
138
-
139
- return parsed;
140
- })
141
- .finally(() => {
142
- if (this.config.timeout) {
143
- clearTimeout(timeoutSignal);
144
- }
145
- });
146
- });
147
- }
148
- }
@@ -1,26 +0,0 @@
1
- import { utils } from 'oas';
2
-
3
- const { matchesMimeType } = utils;
4
-
5
- export default async function getResponseBody(response: Response) {
6
- const contentType = response.headers.get('Content-Type');
7
- const isJSON = contentType && (matchesMimeType.json(contentType) || matchesMimeType.wildcard(contentType));
8
-
9
- const responseBody = await response.text();
10
-
11
- let data = responseBody;
12
- if (isJSON) {
13
- try {
14
- data = JSON.parse(responseBody);
15
- } catch (e) {
16
- // If our JSON parsing failed then we can just return plaintext instead.
17
- }
18
- }
19
-
20
- return {
21
- data,
22
- status: response.status,
23
- headers: response.headers,
24
- res: response,
25
- };
26
- }
@@ -1,109 +0,0 @@
1
- /* eslint-disable no-underscore-dangle */
2
- import type { Operation } from 'oas';
3
-
4
- export default function prepareAuth(authKey: (number | string)[], operation: Operation) {
5
- if (authKey.length === 0) {
6
- return {};
7
- }
8
-
9
- const preparedAuth: Record<
10
- string,
11
- | string
12
- | number
13
- | {
14
- pass: string | number;
15
- user: string | number;
16
- }
17
- > = {};
18
-
19
- const security = operation.getSecurity();
20
- if (security.length === 0) {
21
- // If there's no auth configured on this operation, don't prepare anything (even if it was
22
- // supplied by the user).
23
- return {};
24
- }
25
-
26
- // Does this operation require multiple forms of auth?
27
- if (security.every(s => Object.keys(s).length > 1)) {
28
- throw new Error(
29
- "Sorry, this operation currently requires multiple forms of authentication which this library doesn't yet support.",
30
- );
31
- }
32
-
33
- // Since we can only handle single auth security configurations, let's pull those out. This code
34
- // is a bit opaque but `security` here may look like `[{ basic: [] }, { oauth2: [], basic: []}]`
35
- // and are filtering it down to only single-auth requirements of `[{ basic: [] }]`.
36
- const usableSecurity = security
37
- .map(s => {
38
- return Object.keys(s).length === 1 ? s : false;
39
- })
40
- .filter(Boolean);
41
-
42
- const usableSecuritySchemes = usableSecurity.map(s => Object.keys(s)).reduce((prev, next) => prev.concat(next), []);
43
- const preparedSecurity = operation.prepareSecurity();
44
-
45
- // If we have two auth tokens present let's look for Basic Auth in their configuration.
46
- if (authKey.length >= 2) {
47
- // If this operation doesn't support HTTP Basic auth but we have two tokens, that's a paddlin.
48
- if (!('Basic' in preparedSecurity)) {
49
- throw new Error('Multiple auth tokens were supplied for this endpoint but only a single token is needed.');
50
- }
51
-
52
- // If we have two auth keys for Basic Auth but Basic isn't a usable security scheme (maybe it's
53
- // part of an AND or auth configuration -- which we don't support) then we need to error out.
54
- const schemes = preparedSecurity.Basic.filter(s => usableSecuritySchemes.includes(s._key));
55
- if (!schemes.length) {
56
- throw new Error(
57
- 'Credentials for Basic Authentication were supplied but this operation requires another form of auth in that case, which this library does not yet support. This operation does, however, allow supplying a single auth token.',
58
- );
59
- }
60
-
61
- const scheme = schemes.shift();
62
- preparedAuth[scheme._key] = {
63
- user: authKey[0],
64
- pass: authKey.length === 2 ? authKey[1] : '',
65
- };
66
-
67
- return preparedAuth;
68
- }
69
-
70
- // If we know we don't need to use HTTP Basic auth because we have a username+password then we
71
- // can pick the first usable security scheme available and try to use that. This might not always
72
- // be the auth scheme that the user wants, but we don't have any other way for the user to tell
73
- // us what they want with the current `sdk.auth()` API.
74
- const usableScheme = usableSecuritySchemes[0];
75
- const schemes = Object.entries(preparedSecurity)
76
- .map(([, ps]) => ps.filter(s => usableScheme === s._key))
77
- .reduce((prev, next) => prev.concat(next), []);
78
-
79
- const scheme = schemes.shift();
80
- switch (scheme.type) {
81
- case 'http':
82
- if (scheme.scheme === 'basic') {
83
- preparedAuth[scheme._key] = {
84
- user: authKey[0],
85
- pass: authKey.length === 2 ? authKey[1] : '',
86
- };
87
- } else if (scheme.scheme === 'bearer') {
88
- preparedAuth[scheme._key] = authKey[0];
89
- }
90
- break;
91
-
92
- case 'oauth2':
93
- preparedAuth[scheme._key] = authKey[0];
94
- break;
95
-
96
- case 'apiKey':
97
- if (scheme.in === 'query' || scheme.in === 'header' || scheme.in === 'cookie') {
98
- preparedAuth[scheme._key] = authKey[0];
99
- }
100
- break;
101
-
102
- default:
103
- throw new Error(
104
- `Sorry, this API currently uses a security scheme, ${scheme.type}, which this library doesn't yet support.`,
105
- );
106
- }
107
-
108
- return preparedAuth;
109
- }
@@ -1,415 +0,0 @@
1
- import type { ReadStream } from 'fs';
2
- import type { Operation } from 'oas';
3
- import type { ParameterObject, SchemaObject } from 'oas/dist/rmoas.types';
4
-
5
- import fs from 'fs';
6
- import path from 'path';
7
- import stream from '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
- function isEmpty(obj: any) {
45
- return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length;
46
- }
47
-
48
- function isObject(thing: any) {
49
- if (thing instanceof stream.Readable) {
50
- return false;
51
- }
52
-
53
- return typeof thing === 'object' && thing !== null && !Array.isArray(thing);
54
- }
55
-
56
- function isPrimitive(obj: any) {
57
- return obj === null || typeof obj === 'number' || typeof obj === 'string';
58
- }
59
-
60
- function merge(src: any, target: any) {
61
- if (Array.isArray(target)) {
62
- // @todo we need to add support for merging array defaults with array body/metadata arguments
63
- return target;
64
- } else if (!isObject(target)) {
65
- return target;
66
- }
67
-
68
- return lodashMerge(src, target);
69
- }
70
-
71
- /**
72
- * Ingest a file path or readable stream into a common object that we can later use to process it
73
- * into a parameters object for making an API request.
74
- *
75
- */
76
- function processFile(
77
- paramName: string,
78
- file: string | ReadStream,
79
- ): Promise<{ base64: string; buffer: Buffer; filename: string; paramName: string }> {
80
- if (typeof file === 'string') {
81
- // In order to support relative pathed files, we need to attempt to resolve them.
82
- const resolvedFile = path.resolve(file);
83
-
84
- return new Promise((resolve, reject) => {
85
- fs.stat(resolvedFile, async err => {
86
- if (err) {
87
- if (err.code === 'ENOENT') {
88
- // It's less than ideal for us to handle files that don't exist like this but because
89
- // `file` is a string it might actually be the full text contents of the file and not
90
- // actually a path.
91
- //
92
- // We also can't really regex to see if `file` *looks*` like a path because one should be
93
- // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that
94
- // doesn't *look* like a path, it is one that should still work.
95
- return resolve(undefined);
96
- }
97
-
98
- return reject(err);
99
- }
100
-
101
- const fileMetadata = await datauri(resolvedFile);
102
- const payloadFilename = encodeURIComponent(path.basename(resolvedFile));
103
-
104
- return resolve({
105
- paramName,
106
- base64: fileMetadata.content.replace(';base64', `;name=${payloadFilename};base64`),
107
- filename: payloadFilename,
108
- buffer: fileMetadata.buffer,
109
- });
110
- });
111
- });
112
- } else if (file instanceof stream.Readable) {
113
- return getStream.buffer(file).then(buffer => {
114
- const filePath = file.path as string;
115
- const parser = new DatauriParser();
116
- const base64 = parser.format(filePath, buffer).content;
117
- const payloadFilename = encodeURIComponent(path.basename(filePath));
118
-
119
- return {
120
- paramName,
121
- base64: base64.replace(';base64', `;name=${payloadFilename};base64`),
122
- filename: payloadFilename,
123
- buffer,
124
- };
125
- });
126
- }
127
-
128
- return Promise.reject(
129
- new TypeError(
130
- paramName
131
- ? `The data supplied for the \`${paramName}\` request body parameter is not a file handler that we support.`
132
- : 'The data supplied for the request body payload is not a file handler that we support.',
133
- ),
134
- );
135
- }
136
-
137
- /**
138
- * With potentially supplied body and/or metadata we need to run through them against a given API
139
- * operation to see what's what and prepare any available parameters to be used in an API request
140
- * with `@readme/oas-to-har`.
141
- *
142
- */
143
- export default async function prepareParams(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
144
- let metadataIntersected = false;
145
- const digestedParameters = digestParameters(operation.getParameters());
146
- const jsonSchema = operation.getParametersAsJSONSchema();
147
-
148
- /**
149
- * It might be common for somebody to run `sdk.findPetsByStatus({ status: 'available' }, {})`, in
150
- * which case we want to filter out the second (metadata) parameter and treat the first parameter
151
- * as the metadata instead. If we don't do this, their supplied `status` metadata will be treated
152
- * as a body parameter, and because there's no `status` body parameter, and no supplied metadata
153
- * (because it's an empty object), the request won't send a payload.
154
- *
155
- * @see {@link https://github.com/readmeio/api/issues/449}
156
- */
157
- // eslint-disable-next-line no-param-reassign
158
- metadata = removeUndefinedObjects(metadata);
159
-
160
- if (!jsonSchema && (body !== undefined || metadata !== undefined)) {
161
- let throwNoParamsError = true;
162
-
163
- // If this operation doesn't have any parameters for us to transform to JSON Schema but they've
164
- // sent us either an `Accept` or `Authorization` header (or both) we should let them do that.
165
- // We should, however, only do this check for the `body` parameter as if they've sent this
166
- // request both `body` and `metadata` we can reject it outright as the operation won't have any
167
- // body data.
168
- if (body !== undefined) {
169
- if (typeof body === 'object' && body !== null && !Array.isArray(body)) {
170
- if (Object.keys(body).length <= 2) {
171
- const bodyParams = caseless(body);
172
-
173
- if (specialHeaders.some(header => bodyParams.has(header))) {
174
- throwNoParamsError = false;
175
- }
176
- }
177
- }
178
- }
179
-
180
- if (throwNoParamsError) {
181
- throw new Error(
182
- "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.",
183
- );
184
- }
185
- }
186
-
187
- const jsonSchemaDefaults = jsonSchema ? getJSONSchemaDefaults(jsonSchema) : {};
188
-
189
- const params: {
190
- body?: any;
191
- cookie?: Record<string, string | number | boolean>;
192
- files?: Record<string, Buffer>;
193
- formData?: any;
194
- header?: Record<string, string | number | boolean>;
195
- path?: Record<string, string | number | boolean>;
196
- query?: Record<string, string | number | boolean>;
197
- server?: {
198
- selected: number;
199
- variables: Record<string, string | number>;
200
- };
201
- } = jsonSchemaDefaults;
202
-
203
- // If a body argument was supplied we need to do a bit of work to see if it's actually a body
204
- // argument or metadata because the library lets you supply either a body, metadata, or body with
205
- // metadata.
206
- if (typeof body !== 'undefined') {
207
- if (Array.isArray(body) || isPrimitive(body)) {
208
- // If the body param is an array or a primitive then we know it's absolutely a body because
209
- // metadata can only ever be undefined or an object.
210
- params.body = merge(params.body, body);
211
- } else if (typeof metadata === 'undefined') {
212
- // No metadata was explicitly provided so we need to analyze the body to determine if it's a
213
- // body or should be actually be treated as metadata.
214
- const headerParams = caseless({});
215
- Object.entries(digestedParameters).forEach(([paramName, param]) => {
216
- // Headers are sent case-insensitive so we need to make sure that we're properly
217
- // matching them when detecting what our incoming payload looks like.
218
- if (param.in === 'header') {
219
- headerParams.set(paramName, '');
220
- }
221
- });
222
-
223
- // `Accept` and `Authorization` headers can't be defined as normal parameters but we should
224
- // always allow the user to supply them if they wish.
225
- specialHeaders.forEach(header => {
226
- if (!headerParams.has(header)) {
227
- headerParams.set(header, '');
228
- }
229
- });
230
-
231
- const intersection = Object.keys(body).filter(value => {
232
- if (Object.keys(digestedParameters).includes(value)) {
233
- return true;
234
- } else if (headerParams.has(value)) {
235
- return true;
236
- }
237
-
238
- return false;
239
- }).length;
240
-
241
- if (intersection && intersection / Object.keys(body).length > 0.25) {
242
- /* eslint-disable no-param-reassign */
243
- // If more than 25% of the body intersects with the parameters that we've got on hand,
244
- // then we should treat it as a metadata object and organize into parameters.
245
- metadataIntersected = true;
246
- metadata = merge(params.body, body) as Record<string, unknown>;
247
- body = undefined;
248
- /* eslint-enable no-param-reassign */
249
- } else {
250
- // For all other cases, we should just treat the supplied body as a body.
251
- params.body = merge(params.body, body);
252
- }
253
- } else {
254
- // Body and metadata were both supplied.
255
- params.body = merge(params.body, body);
256
- }
257
- }
258
-
259
- if (!operation.hasRequestBody()) {
260
- // If this operation doesn't have any documented request body then we shouldn't be sending
261
- // anything.
262
- delete params.body;
263
- } else {
264
- if (!('body' in params)) params.body = {};
265
-
266
- // We need to retrieve the request body for this operation to search for any `binary` format
267
- // data that the user wants to send so we know what we need to prepare for the final API
268
- // request.
269
- const payloadJsonSchema = jsonSchema.find(js => js.type === 'body');
270
- if (payloadJsonSchema) {
271
- if (!params.files) params.files = {};
272
-
273
- const conversions = [];
274
-
275
- // @todo add support for `type: array`, `oneOf` and `anyOf`
276
- if (payloadJsonSchema.schema?.properties) {
277
- Object.entries(payloadJsonSchema.schema?.properties)
278
- .filter(([, schema]: [string, SchemaObject]) => schema?.format === 'binary')
279
- .filter(([prop]) => Object.keys(params.body).includes(prop))
280
- .forEach(([prop]) => {
281
- conversions.push(processFile(prop, params.body[prop]));
282
- });
283
- } else if (payloadJsonSchema.schema?.type === 'string') {
284
- if (payloadJsonSchema.schema?.format === 'binary') {
285
- conversions.push(processFile(undefined, params.body));
286
- }
287
- }
288
-
289
- await Promise.all(conversions)
290
- .then(fileMetadata => fileMetadata.filter(Boolean))
291
- .then(fm => {
292
- fm.forEach(fileMetadata => {
293
- if (!fileMetadata) {
294
- // If we don't have any metadata here it's because the file we have is likely
295
- // the full string content of the file so since we don't have any filenames to
296
- // work with we shouldn't do any additional handling to the `body` or `files`
297
- // parameters.
298
- return;
299
- }
300
-
301
- if (fileMetadata.paramName) {
302
- params.body[fileMetadata.paramName] = fileMetadata.base64;
303
- } else {
304
- params.body = fileMetadata.base64;
305
- }
306
-
307
- params.files[fileMetadata.filename] = fileMetadata.buffer;
308
- });
309
- });
310
- }
311
- }
312
-
313
- // Form data should be placed within `formData` instead of `body` for it to properly get picked
314
- // up by `fetch-har`.
315
- if (operation.isFormUrlEncoded()) {
316
- params.formData = merge(params.formData, params.body);
317
- delete params.body;
318
- }
319
-
320
- // Only spend time trying to organize metadata into parameters if we were able to digest
321
- // parameters out of the operation schema. If we couldn't digest anything, but metadata was
322
- // supplied then we wouldn't know how to send it in the request!
323
- if (typeof metadata !== 'undefined') {
324
- if (!('cookie' in params)) params.cookie = {};
325
- if (!('header' in params)) params.header = {};
326
- if (!('path' in params)) params.path = {};
327
- if (!('query' in params)) params.query = {};
328
-
329
- Object.entries(digestedParameters).forEach(([paramName, param]) => {
330
- let value: any;
331
- let metadataHeaderParam;
332
- if (typeof metadata === 'object' && !isEmpty(metadata)) {
333
- if (paramName in metadata) {
334
- value = metadata[paramName];
335
- metadataHeaderParam = paramName;
336
- } else if (param.in === 'header') {
337
- // Headers are sent case-insensitive so we need to make sure that we're properly
338
- // matching them when detecting what our incoming payload looks like.
339
- metadataHeaderParam = Object.keys(metadata).find(k => k.toLowerCase() === paramName.toLowerCase());
340
- value = metadata[metadataHeaderParam];
341
- }
342
- }
343
-
344
- if (value === undefined) {
345
- return;
346
- }
347
-
348
- /* eslint-disable no-param-reassign */
349
- switch (param.in) {
350
- case 'path':
351
- params.path[paramName] = value;
352
- delete metadata[paramName];
353
- break;
354
- case 'query':
355
- params.query[paramName] = value;
356
- delete metadata[paramName];
357
- break;
358
- case 'header':
359
- params.header[paramName.toLowerCase()] = value;
360
- delete metadata[metadataHeaderParam];
361
- break;
362
- case 'cookie':
363
- params.cookie[paramName] = value;
364
- delete metadata[paramName];
365
- break;
366
- default: // no-op
367
- }
368
- /* eslint-enable no-param-reassign */
369
-
370
- // Because a user might have sent just a metadata object, we want to make sure that we filter
371
- // out anything that they sent that is a parameter from also being sent as part of a form
372
- // data payload for `x-www-form-urlencoded` requests.
373
- if (metadataIntersected && operation.isFormUrlEncoded()) {
374
- if (paramName in params.formData) {
375
- delete params.formData[paramName];
376
- }
377
- }
378
- });
379
-
380
- // If there's any leftover metadata that hasn't been moved into form data for this request we
381
- // need to move it or else it'll get tossed.
382
- if (!isEmpty(metadata)) {
383
- if (typeof metadata === 'object') {
384
- // If the user supplied an `accept` or `authorization` header themselves we should allow it
385
- // through. Normally these headers are automatically handled by `@readme/oas-to-har` but in
386
- // the event that maybe the user wants to return XML for an API that normally returns JSON
387
- // or specify a custom auth header (maybe we can't handle their auth case right) this is the
388
- // only way with this library that they can do that.
389
- specialHeaders.forEach(headerName => {
390
- const headerParam = Object.keys(metadata).find(m => m.toLowerCase() === headerName);
391
- if (headerParam) {
392
- params.header[headerName] = metadata[headerParam] as string;
393
- // eslint-disable-next-line no-param-reassign
394
- delete metadata[headerParam];
395
- }
396
- });
397
- }
398
-
399
- if (operation.isFormUrlEncoded()) {
400
- params.formData = merge(params.formData, metadata);
401
- } else {
402
- // Any other remaining unused metadata will be unused because we don't know where to place
403
- // it in the request.
404
- }
405
- }
406
- }
407
-
408
- ['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'].forEach((type: keyof typeof params) => {
409
- if (type in params && isEmpty(params[type])) {
410
- delete params[type];
411
- }
412
- });
413
-
414
- return params;
415
- }