@readme/api-core 7.0.0-alpha.2 → 7.0.0-alpha.4

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