UNPKG

api

Version:

Magical SDK generation from an OpenAPI definition 🪄

426 lines (425 loc) • 25.9 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { 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; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; var fs_1 = __importDefault(require("fs")); var path_1 = __importDefault(require("path")); var stream_1 = __importDefault(require("stream")); var caseless_1 = __importDefault(require("caseless")); var parser_1 = __importDefault(require("datauri/parser")); var sync_1 = __importDefault(require("datauri/sync")); var get_stream_1 = __importDefault(require("get-stream")); var merge_1 = __importDefault(require("lodash/merge")); var remove_undefined_objects_1 = __importDefault(require("remove-undefined-objects")); var getJSONSchemaDefaults_1 = __importDefault(require("./getJSONSchemaDefaults")); // These headers are normally only defined by the OpenAPI definition but we allow the user to // manually supply them in their `metadata` parameter if they wish. var specialHeaders = ['accept', 'authorization']; /** * Extract all available parameters from an operations Parameter Object into a digestable array * that we can use to apply to the request. * * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#parameterObject} * @see {@link https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterObject} */ function digestParameters(parameters) { return parameters.reduce(function (prev, param) { var _a; if ('$ref' in param || 'allOf' in param || 'anyOf' in param || 'oneOf' in param) { throw new Error("The OpenAPI document for this operation wasn't dereferenced before processing."); } else if (param.name in prev) { 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.")); } return Object.assign(prev, (_a = {}, _a[param.name] = param, _a)); }, {}); } // https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_isempty function isEmpty(obj) { return [Object, Array].includes((obj || {}).constructor) && !Object.entries(obj || {}).length; } function isObject(thing) { if (thing instanceof stream_1["default"].Readable) { return false; } return typeof thing === 'object' && thing !== null && !Array.isArray(thing); } function isPrimitive(obj) { return obj === null || typeof obj === 'number' || typeof obj === 'string'; } function merge(src, target) { if (Array.isArray(target)) { // @todo we need to add support for merging array defaults with array body/metadata arguments return target; } else if (!isObject(target)) { return target; } return (0, merge_1["default"])(src, target); } /** * Ingest a file path or readable stream into a common object that we can later use to process it * into a parameters object for making an API request. * */ function processFile(paramName, file) { var _this = this; if (typeof file === 'string') { // In order to support relative pathed files, we need to attempt to resolve them. var resolvedFile_1 = path_1["default"].resolve(file); return new Promise(function (resolve, reject) { fs_1["default"].stat(resolvedFile_1, function (err) { return __awaiter(_this, void 0, void 0, function () { var fileMetadata, payloadFilename; return __generator(this, function (_a) { switch (_a.label) { case 0: if (err) { if (err.code === 'ENOENT') { // It's less than ideal for us to handle files that don't exist like this but because // `file` is a string it might actually be the full text contents of the file and not // actually a path. // // We also can't really regex to see if `file` *looks*` like a path because one should be // able to pass in a relative `owlbert.png` (instead of `./owlbert.png`) and though that // doesn't *look* like a path, it is one that should still work. return [2 /*return*/, resolve(undefined)]; } return [2 /*return*/, reject(err)]; } return [4 /*yield*/, (0, sync_1["default"])(resolvedFile_1)]; case 1: fileMetadata = _a.sent(); payloadFilename = encodeURIComponent(path_1["default"].basename(resolvedFile_1)); return [2 /*return*/, resolve({ paramName: paramName, base64: fileMetadata.content.replace(';base64', ";name=".concat(payloadFilename, ";base64")), filename: payloadFilename, buffer: fileMetadata.buffer })]; } }); }); }); }); } else if (file instanceof stream_1["default"].Readable) { return get_stream_1["default"].buffer(file).then(function (buffer) { var filePath = file.path; var parser = new parser_1["default"](); var base64 = parser.format(filePath, buffer).content; var payloadFilename = encodeURIComponent(path_1["default"].basename(filePath)); return { paramName: paramName, base64: base64.replace(';base64', ";name=".concat(payloadFilename, ";base64")), filename: payloadFilename, buffer: buffer }; }); } return Promise.reject(new TypeError(paramName ? "The data supplied for the `".concat(paramName, "` request body parameter is not a file handler that we support.") : 'The data supplied for the request body payload is not a file handler that we support.')); } /** * With potentially supplied body and/or metadata we need to run through them against a given API * operation to see what's what and prepare any available parameters to be used in an API request * with `@readme/oas-to-har`. * */ function prepareParams(operation, body, metadata) { var _a, _b, _c, _d; return __awaiter(this, void 0, void 0, function () { var metadataIntersected, digestedParameters, jsonSchema, throwNoParamsError, bodyParams_1, jsonSchemaDefaults, params, headerParams_1, intersection, payloadJsonSchema, conversions_1; return __generator(this, function (_e) { switch (_e.label) { case 0: metadataIntersected = false; digestedParameters = digestParameters(operation.getParameters()); jsonSchema = operation.getParametersAsJSONSchema(); /** * It might be common for somebody to run `sdk.findPetsByStatus({ status: 'available' }, {})`, in * which case we want to filter out the second (metadata) parameter and treat the first parameter * as the metadata instead. If we don't do this, their supplied `status` metadata will be treated * as a body parameter, and because there's no `status` body parameter, and no supplied metadata * (because it's an empty object), the request won't send a payload. * * @see {@link https://github.com/readmeio/api/issues/449} */ // eslint-disable-next-line no-param-reassign metadata = (0, remove_undefined_objects_1["default"])(metadata); if (!jsonSchema && (body !== undefined || metadata !== undefined)) { throwNoParamsError = true; // If this operation doesn't have any parameters for us to transform to JSON Schema but they've // sent us either an `Accept` or `Authorization` header (or both) we should let them do that. // We should, however, only do this check for the `body` parameter as if they've sent this // request both `body` and `metadata` we can reject it outright as the operation won't have any // body data. if (body !== undefined) { if (typeof body === 'object' && body !== null && !Array.isArray(body)) { if (Object.keys(body).length <= 2) { bodyParams_1 = (0, caseless_1["default"])(body); if (specialHeaders.some(function (header) { return bodyParams_1.has(header); })) { throwNoParamsError = false; } } } } if (throwNoParamsError) { 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."); } } jsonSchemaDefaults = jsonSchema ? (0, getJSONSchemaDefaults_1["default"])(jsonSchema) : {}; params = jsonSchemaDefaults; // If a body argument was supplied we need to do a bit of work to see if it's actually a body // argument or metadata because the library lets you supply either a body, metadata, or body with // metadata. if (typeof body !== 'undefined') { if (Array.isArray(body) || isPrimitive(body)) { // If the body param is an array or a primitive then we know it's absolutely a body because // metadata can only ever be undefined or an object. params.body = merge(params.body, body); } else if (typeof metadata === 'undefined') { headerParams_1 = (0, caseless_1["default"])({}); Object.entries(digestedParameters).forEach(function (_a) { var paramName = _a[0], param = _a[1]; // Headers are sent case-insensitive so we need to make sure that we're properly // matching them when detecting what our incoming payload looks like. if (param["in"] === 'header') { headerParams_1.set(paramName, ''); } }); // `Accept` and `Authorization` headers can't be defined as normal parameters but we should // always allow the user to supply them if they wish. specialHeaders.forEach(function (header) { if (!headerParams_1.has(header)) { headerParams_1.set(header, ''); } }); intersection = Object.keys(body).filter(function (value) { if (Object.keys(digestedParameters).includes(value)) { return true; } else if (headerParams_1.has(value)) { return true; } return false; }).length; if (intersection && intersection / Object.keys(body).length > 0.25) { /* eslint-disable no-param-reassign */ // If more than 25% of the body intersects with the parameters that we've got on hand, // then we should treat it as a metadata object and organize into parameters. metadataIntersected = true; metadata = merge(params.body, body); body = undefined; /* eslint-enable no-param-reassign */ } else { // For all other cases, we should just treat the supplied body as a body. params.body = merge(params.body, body); } } else { // Body and metadata were both supplied. params.body = merge(params.body, body); } } if (!!operation.hasRequestBody()) return [3 /*break*/, 1]; // If this operation doesn't have any documented request body then we shouldn't be sending // anything. delete params.body; return [3 /*break*/, 3]; case 1: if (!('body' in params)) params.body = {}; payloadJsonSchema = jsonSchema.find(function (js) { return js.type === 'body'; }); if (!payloadJsonSchema) return [3 /*break*/, 3]; if (!params.files) params.files = {}; conversions_1 = []; // @todo add support for `type: array`, `oneOf` and `anyOf` if ((_a = payloadJsonSchema.schema) === null || _a === void 0 ? void 0 : _a.properties) { Object.entries((_b = payloadJsonSchema.schema) === null || _b === void 0 ? void 0 : _b.properties) .filter(function (_a) { var schema = _a[1]; return (schema === null || schema === void 0 ? void 0 : schema.format) === 'binary'; }) .filter(function (_a) { var prop = _a[0]; return Object.keys(params.body).includes(prop); }) .forEach(function (_a) { var prop = _a[0]; conversions_1.push(processFile(prop, params.body[prop])); }); } else if (((_c = payloadJsonSchema.schema) === null || _c === void 0 ? void 0 : _c.type) === 'string') { if (((_d = payloadJsonSchema.schema) === null || _d === void 0 ? void 0 : _d.format) === 'binary') { conversions_1.push(processFile(undefined, params.body)); } } return [4 /*yield*/, Promise.all(conversions_1) .then(function (fileMetadata) { return fileMetadata.filter(Boolean); }) .then(function (fm) { fm.forEach(function (fileMetadata) { if (!fileMetadata) { // If we don't have any metadata here it's because the file we have is likely // the full string content of the file so since we don't have any filenames to // work with we shouldn't do any additional handling to the `body` or `files` // parameters. return; } if (fileMetadata.paramName) { params.body[fileMetadata.paramName] = fileMetadata.base64; } else { params.body = fileMetadata.base64; } params.files[fileMetadata.filename] = fileMetadata.buffer; }); })]; case 2: _e.sent(); _e.label = 3; case 3: // Form data should be placed within `formData` instead of `body` for it to properly get picked // up by `fetch-har`. if (operation.isFormUrlEncoded()) { params.formData = merge(params.formData, params.body); delete params.body; } // Only spend time trying to organize metadata into parameters if we were able to digest // parameters out of the operation schema. If we couldn't digest anything, but metadata was // supplied then we wouldn't know how to send it in the request! if (typeof metadata !== 'undefined') { if (!('cookie' in params)) params.cookie = {}; if (!('header' in params)) params.header = {}; if (!('path' in params)) params.path = {}; if (!('query' in params)) params.query = {}; Object.entries(digestedParameters).forEach(function (_a) { var paramName = _a[0], param = _a[1]; var value; var metadataHeaderParam; if (typeof metadata === 'object' && !isEmpty(metadata)) { if (paramName in metadata) { value = metadata[paramName]; metadataHeaderParam = paramName; } else if (param["in"] === 'header') { // Headers are sent case-insensitive so we need to make sure that we're properly // matching them when detecting what our incoming payload looks like. metadataHeaderParam = Object.keys(metadata).find(function (k) { return k.toLowerCase() === paramName.toLowerCase(); }); value = metadata[metadataHeaderParam]; } } if (value === undefined) { return; } /* eslint-disable no-param-reassign */ switch (param["in"]) { case 'path': params.path[paramName] = value; delete metadata[paramName]; break; case 'query': params.query[paramName] = value; delete metadata[paramName]; break; case 'header': params.header[paramName.toLowerCase()] = value; delete metadata[metadataHeaderParam]; break; case 'cookie': params.cookie[paramName] = value; delete metadata[paramName]; break; default: // no-op } /* eslint-enable no-param-reassign */ // Because a user might have sent just a metadata object, we want to make sure that we filter // out anything that they sent that is a parameter from also being sent as part of a form // data payload for `x-www-form-urlencoded` requests. if (metadataIntersected && operation.isFormUrlEncoded()) { if (paramName in params.formData) { delete params.formData[paramName]; } } }); // If there's any leftover metadata that hasn't been moved into form data for this request we // need to move it or else it'll get tossed. if (!isEmpty(metadata)) { if (typeof metadata === 'object') { // If the user supplied an `accept` or `authorization` header themselves we should allow it // through. Normally these headers are automatically handled by `@readme/oas-to-har` but in // the event that maybe the user wants to return XML for an API that normally returns JSON // or specify a custom auth header (maybe we can't handle their auth case right) this is the // only way with this library that they can do that. specialHeaders.forEach(function (headerName) { var headerParam = Object.keys(metadata).find(function (m) { return m.toLowerCase() === headerName; }); if (headerParam) { params.header[headerName] = metadata[headerParam]; // eslint-disable-next-line no-param-reassign delete metadata[headerParam]; } }); } if (operation.isFormUrlEncoded()) { params.formData = merge(params.formData, metadata); } else { // Any other remaining unused metadata will be unused because we don't know where to place // it in the request. } } } ['body', 'cookie', 'files', 'formData', 'header', 'path', 'query'].forEach(function (type) { if (type in params && isEmpty(params[type])) { delete params[type]; } }); return [2 /*return*/, params]; } }); }); } exports["default"] = prepareParams;