api
Version:
Magical SDK generation from an OpenAPI definition 🪄
165 lines (164 loc) • 8.33 kB
JavaScript
;
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 openapi_parser_1 = __importDefault(require("@readme/openapi-parser"));
require("isomorphic-fetch");
var js_yaml_1 = __importDefault(require("js-yaml"));
var Fetcher = /** @class */ (function () {
function Fetcher(uri) {
if (typeof uri === 'string') {
if (Fetcher.isAPIRegistryUUID(uri)) {
// Resolve OpenAPI definition shorthand accessors from within the ReadMe API Registry.
this.uri = uri.replace(Fetcher.registryUUIDRegex, 'https://dash.readme.com/api/v1/api-registry/$4');
}
else if (Fetcher.isGitHubBlobURL(uri)) {
/**
* People may try to use a public repository URL to the source viewer on GitHub not knowing
* that this page actually serves HTML. In this case we want to rewrite these to the "raw"
* version of this page that'll allow us to access the API definition.
*
* @example https://github.com/readmeio/oas-examples/blob/main/3.1/json/petstore.json
*/
this.uri = uri.replace(/\/\/github.com/, '//raw.githubusercontent.com').replace(/\/blob\//, '/');
}
else {
this.uri = uri;
}
}
else {
this.uri = uri;
}
}
Fetcher.isAPIRegistryUUID = function (uri) {
return Fetcher.registryUUIDRegex.test(uri);
};
Fetcher.isGitHubBlobURL = function (uri) {
return /\/\/github.com\/[-_a-zA-Z0-9]+\/[-_a-zA-Z0-9]+\/blob\/(.*).(yaml|json|yml)/.test(uri);
};
Fetcher.getProjectPrefixFromRegistryUUID = function (uri) {
var matches = uri.match(Fetcher.registryUUIDRegex);
if (!matches) {
return undefined;
}
return matches.groups.project;
};
Fetcher.prototype.load = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (typeof this.uri !== 'string') {
throw new TypeError("Something disastrous occurred and a non-string URI was supplied to the Fetcher library. This shouldn't have happened!");
}
return [2 /*return*/, Promise.resolve(this.uri)
.then(function (uri) {
var url;
try {
url = new URL(uri);
}
catch (err) {
// If that try fails for whatever reason than the URI that we have isn't a real URL and
// we can safely attempt to look for it on the filesystem.
return Fetcher.getFile(uri);
}
return Fetcher.getURL(url.href);
})
.then(function (res) { return Fetcher.validate(res); })
.then(function (res) { return res; })];
});
});
};
Fetcher.getURL = function (url) {
// @todo maybe include our user-agent here to identify our request
return fetch(url).then(function (res) {
if (!res.ok) {
throw new Error("Unable to retrieve URL (".concat(url, "). Reason: ").concat(res.statusText));
}
if (res.headers.get('content-type') === 'application/yaml' || /\.(yaml|yml)/.test(url)) {
return res.text().then(function (text) {
return js_yaml_1["default"].load(text);
});
}
return res.json();
});
};
Fetcher.getFile = function (uri) {
// Support relative paths by resolving them against the cwd.
var file = path_1["default"].resolve(process.cwd(), uri);
if (!fs_1["default"].existsSync(file)) {
throw new Error("Sorry, we were unable to load an API definition from ".concat(file, ". Please either supply a URL or a path on your filesystem."));
}
return Promise.resolve(fs_1["default"].readFileSync(file, 'utf8')).then(function (res) {
if (/\.(yaml|yml)/.test(file)) {
return js_yaml_1["default"].load(res);
}
return JSON.parse(res);
});
};
Fetcher.validate = function (json) {
if (json.swagger) {
throw new Error('Sorry, this module only supports OpenAPI definitions.');
}
// The `validate` method handles dereferencing for us.
return openapi_parser_1["default"].validate(json, {
dereference: {
/**
* If circular `$refs` are ignored they'll remain in the API definition as `$ref: String`.
* This allows us to not only do easy circular reference detection but also stringify and
* save dereferenced API definitions back into the cache directory.
*/
circular: 'ignore'
}
})["catch"](function (err) {
if (/is not a valid openapi definition/i.test(err.message)) {
throw new Error("Sorry, that doesn't look like a valid OpenAPI definition.");
}
throw err;
});
};
/**
* @example @petstore/v1.0#n6kvf10vakpemvplx
* @example @petstore#n6kvf10vakpemvplx
*/
Fetcher.registryUUIDRegex = /^@(?<project>[a-zA-Z0-9-_]+)(\/?(?<version>.+))?#(?<uuid>[a-z0-9]+)$/;
return Fetcher;
}());
exports["default"] = Fetcher;