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